收口 Rust Web 入口与 AI 写入链
- 将 3000 主入口继续收口到 mnote-web,补齐 /favicon.ico、/api/auth、session alias、AI run 等 Rust Web 路由边界。 - 更新登录页与 Convex Auth 代理,支持测试账号快速登录写入真实 Convex Auth cookie。 - 推进页面设置、Wolai 对齐、Phase 7 AI kernel/CLI-first 设计文档与相关 smoke 脚本。 - 更新 leptos-tiptap 生成资产、mnote-cli/bridge-runtime、前端依赖和 dev/prod 启动脚本。
This commit is contained in:
@@ -3,26 +3,21 @@ use crate::context::RequestContext;
|
||||
use crate::error::WebError;
|
||||
use crate::routes::query_support::resolve_effective_workspace_id;
|
||||
use crate::routes::snapshot_support::{load_projection_snapshot, ProjectionSnapshotSpec};
|
||||
use axum::body::{Body, Bytes};
|
||||
use axum::extract::Query;
|
||||
use axum::extract::{Extension, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::http::{header, HeaderMap, HeaderName, HeaderValue, Request, StatusCode};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::Json;
|
||||
use core_protocol::KernelProjectionKind;
|
||||
use futures_util::{StreamExt, TryStreamExt};
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CompatBoundaryResponse {
|
||||
pub ok: bool,
|
||||
pub boundary: &'static str,
|
||||
pub compatibility: &'static str,
|
||||
pub request_id: String,
|
||||
pub trace_id: String,
|
||||
pub target: String,
|
||||
pub notes: Vec<&'static str>,
|
||||
}
|
||||
use std::env;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -33,19 +28,548 @@ pub struct CompatSidebarQuery {
|
||||
pub async fn next_ai_agent_run(
|
||||
State(state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
) -> Json<CompatBoundaryResponse> {
|
||||
Json(CompatBoundaryResponse {
|
||||
ok: true,
|
||||
boundary: "next_route_compat",
|
||||
compatibility: "placeholder",
|
||||
request_id: context.trace.request_id,
|
||||
trace_id: context.trace.trace_id,
|
||||
target: format!("{}/bridge", state.config().hermes_base_path),
|
||||
notes: vec![
|
||||
"/api/ai-agent/run 是 legacy compat endpoint,canonical route 是 /api/hermes/bridge。",
|
||||
"结构化写入必须通过 Hermes/Rust bridge 再落到 page/tree/edge command。",
|
||||
],
|
||||
request: Request<Body>,
|
||||
) -> Result<Response, WebError> {
|
||||
let (parts, body) = request.into_parts();
|
||||
let body = axum::body::to_bytes(body, 10 * 1024 * 1024)
|
||||
.await
|
||||
.map_err(|error| WebError::internal(format!("读取 AI 请求体失败: {error}")))?;
|
||||
let payload: Value = serde_json::from_slice(&body).map_err(|error| {
|
||||
WebError::bad_request_code(
|
||||
"ai_agent_bad_request",
|
||||
format!("AI 请求体不是合法 JSON: {error}"),
|
||||
)
|
||||
.with_context(&context)
|
||||
.with_header("x-mnote-web-owner", "mnote-web")
|
||||
})?;
|
||||
|
||||
if state.config().enable_legacy_next_compat {
|
||||
if let Some(base_url) = state.config().legacy_next_base_url.as_deref() {
|
||||
if let Ok(response) =
|
||||
proxy_ai_agent_run_to_next(base_url, &context, &parts.headers, body.clone()).await
|
||||
{
|
||||
return Ok(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Ok(response) = run_local_mnote_cli_ai_host(&state, &context, &payload).await {
|
||||
return Ok(response);
|
||||
}
|
||||
|
||||
let Some(backend_url) = resolve_ai_orchestrator_backend_url() else {
|
||||
return Err(WebError::bad_gateway_code(
|
||||
"ai_orchestrator_unavailable",
|
||||
"未配置 BACKEND_URL,无法连接 document AI orchestrator。",
|
||||
)
|
||||
.with_context(&context)
|
||||
.with_header("x-mnote-web-owner", "mnote-web"));
|
||||
};
|
||||
|
||||
let upstream_url = reqwest::Url::parse(&format!(
|
||||
"{}/api/v1/ai-agent/document/run",
|
||||
backend_url.trim_end_matches('/')
|
||||
))
|
||||
.map_err(|error| WebError::internal(format!("AI orchestrator URL 非法: {error}")))?;
|
||||
let forward_payload = build_document_ai_orchestrator_payload(&state, &context, &payload);
|
||||
let client = reqwest::Client::builder()
|
||||
.connect_timeout(Duration::from_secs(5))
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.build()
|
||||
.map_err(|error| {
|
||||
WebError::internal(format!("AI orchestrator HTTP 客户端创建失败: {error}"))
|
||||
})?;
|
||||
|
||||
let mut upstream_request = client.post(upstream_url).json(&forward_payload);
|
||||
upstream_request = apply_ai_forward_headers(upstream_request, &parts.headers, &context);
|
||||
if let Some(api_key) = read_env_or_dotenv("MNOTE_AI_ORCHESTRATOR_API_KEY") {
|
||||
upstream_request = upstream_request.header("x-mnote-ai-key", api_key);
|
||||
}
|
||||
|
||||
let upstream_response = upstream_request.send().await.map_err(|error| {
|
||||
WebError::bad_gateway_code(
|
||||
"ai_orchestrator_proxy_error",
|
||||
format!("document AI orchestrator 请求失败: {error}"),
|
||||
)
|
||||
.with_context(&context)
|
||||
.with_header("x-mnote-web-owner", "mnote-web")
|
||||
.with_header("x-upstream-service", "document-ai-orchestrator")
|
||||
})?;
|
||||
|
||||
if !upstream_response.status().is_success() {
|
||||
let status = upstream_response.status();
|
||||
let body = upstream_response
|
||||
.text()
|
||||
.await
|
||||
.unwrap_or_else(|error| format!("读取 upstream 错误响应失败: {error}"));
|
||||
return Err(WebError::bad_gateway_code(
|
||||
"ai_orchestrator_upstream_error",
|
||||
format!(
|
||||
"document AI orchestrator 返回 HTTP {}: {}",
|
||||
status.as_u16(),
|
||||
body
|
||||
),
|
||||
)
|
||||
.with_context(&context)
|
||||
.with_header("x-mnote-web-owner", "mnote-web")
|
||||
.with_header("x-upstream-service", "document-ai-orchestrator"));
|
||||
}
|
||||
|
||||
build_ai_sse_proxy_response(upstream_response, &context)
|
||||
}
|
||||
|
||||
async fn proxy_ai_agent_run_to_next(
|
||||
base_url: &str,
|
||||
context: &RequestContext,
|
||||
headers: &HeaderMap,
|
||||
body_bytes: Bytes,
|
||||
) -> Result<Response, WebError> {
|
||||
let upstream_url = reqwest::Url::parse(&format!(
|
||||
"{}/api/ai-agent/run",
|
||||
base_url.trim_end_matches('/')
|
||||
))
|
||||
.map_err(|error| WebError::internal(format!("Next AI route URL 非法: {error}")))?;
|
||||
let client = reqwest::Client::builder()
|
||||
.connect_timeout(Duration::from_secs(5))
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.build()
|
||||
.map_err(|error| WebError::internal(format!("Next AI HTTP 客户端创建失败: {error}")))?;
|
||||
|
||||
let mut upstream_request = client.post(upstream_url).body(body_bytes.clone());
|
||||
for (name, value) in headers.iter() {
|
||||
if is_hop_by_hop_header(name.as_str())
|
||||
|| name == header::HOST
|
||||
|| name == header::CONTENT_LENGTH
|
||||
|| name == header::COOKIE
|
||||
|| name == header::AUTHORIZATION
|
||||
{
|
||||
continue;
|
||||
}
|
||||
upstream_request = upstream_request.header(name.as_str(), value.as_bytes());
|
||||
}
|
||||
if let Some(cookie) = context.auth.cookie_header.as_deref() {
|
||||
upstream_request = upstream_request.header(header::COOKIE, cookie);
|
||||
}
|
||||
if let Some(authorization) = context.auth.authorization.as_deref() {
|
||||
upstream_request = upstream_request.header(header::AUTHORIZATION, authorization);
|
||||
}
|
||||
upstream_request = upstream_request.header("x-request-id", context.trace.request_id.as_str());
|
||||
upstream_request = upstream_request.header("x-trace-id", context.trace.trace_id.as_str());
|
||||
upstream_request = upstream_request.header("x-mnote-source-channel", "rust_web_route");
|
||||
upstream_request = upstream_request.header("x-mnote-source-client", "mnote-web");
|
||||
upstream_request = upstream_request.header("x-mnote-actor-id", context.auth.actor_id.as_str());
|
||||
upstream_request =
|
||||
upstream_request.header("x-mnote-actor-type", context.auth.actor_type.as_str());
|
||||
if let Some(workspace_id) = context.workspace.workspace_id.as_deref() {
|
||||
upstream_request = upstream_request.header("x-mnote-workspace-id", workspace_id);
|
||||
}
|
||||
if let Some(session_id) = context.auth.session_id.as_deref() {
|
||||
upstream_request = upstream_request.header("x-mnote-session-id", session_id);
|
||||
}
|
||||
|
||||
let upstream_response = upstream_request.send().await.map_err(|error| {
|
||||
WebError::bad_gateway_code(
|
||||
"next_ai_proxy_error",
|
||||
format!("Next /api/ai-agent/run 请求失败: {error}"),
|
||||
)
|
||||
.with_context(context)
|
||||
.with_header("x-mnote-web-owner", "mnote-web")
|
||||
.with_header("x-upstream-service", "next-ai-route")
|
||||
})?;
|
||||
|
||||
if !upstream_response.status().is_success() {
|
||||
let status = upstream_response.status();
|
||||
let body = upstream_response
|
||||
.text()
|
||||
.await
|
||||
.unwrap_or_else(|error| format!("读取 Next AI 错误响应失败: {error}"));
|
||||
return Err(WebError::bad_gateway_code(
|
||||
"next_ai_upstream_error",
|
||||
format!(
|
||||
"Next /api/ai-agent/run 返回 HTTP {}: {}",
|
||||
status.as_u16(),
|
||||
body
|
||||
),
|
||||
)
|
||||
.with_context(context)
|
||||
.with_header("x-mnote-web-owner", "mnote-web")
|
||||
.with_header("x-upstream-service", "next-ai-route"));
|
||||
}
|
||||
|
||||
build_ai_sse_proxy_response(upstream_response, context)
|
||||
}
|
||||
|
||||
fn resolve_repo_root() -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../..")
|
||||
}
|
||||
|
||||
fn build_mnote_cli_args(context: &RequestContext, payload: &Value) -> Vec<String> {
|
||||
let ai = payload
|
||||
.get("options")
|
||||
.and_then(|value| value.get("ai"))
|
||||
.cloned()
|
||||
.unwrap_or(Value::Null);
|
||||
let runtime_context = payload.get("context").cloned().unwrap_or(Value::Null);
|
||||
let document_id = runtime_context
|
||||
.get("documentId")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("current");
|
||||
let workspace_id = runtime_context
|
||||
.get("workspaceId")
|
||||
.and_then(Value::as_str)
|
||||
.or(context.workspace.workspace_id.as_deref());
|
||||
let session_id = ai
|
||||
.get("sessionId")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| format!("ai-{}", context.trace.request_id));
|
||||
let args_json = json!({
|
||||
"pageId": document_id,
|
||||
"documentId": document_id,
|
||||
"workspaceId": workspace_id,
|
||||
"provider": ai.get("provider").cloned().unwrap_or(Value::Null),
|
||||
"modelKey": ai.get("modelKey").cloned().unwrap_or(Value::Null),
|
||||
"profileId": ai.get("profileId").cloned().unwrap_or(Value::Null),
|
||||
"selectedUids": runtime_context.get("selectedUids").cloned().unwrap_or(Value::Null),
|
||||
"pageOptions": runtime_context.get("pageOptions").cloned().unwrap_or(Value::Null),
|
||||
})
|
||||
.to_string();
|
||||
|
||||
vec![
|
||||
"run".into(),
|
||||
"--quiet".into(),
|
||||
"--manifest-path".into(),
|
||||
resolve_repo_root()
|
||||
.join("rust")
|
||||
.join("Cargo.toml")
|
||||
.to_string_lossy()
|
||||
.to_string(),
|
||||
"-p".into(),
|
||||
"mnote-cli".into(),
|
||||
"--".into(),
|
||||
"--json".into(),
|
||||
"--validate-only".into(),
|
||||
"--dry-run".into(),
|
||||
"--actor-id".into(),
|
||||
context.auth.actor_id.clone(),
|
||||
"--actor-type".into(),
|
||||
context.auth.actor_type.clone(),
|
||||
"--session-id".into(),
|
||||
session_id,
|
||||
"--reason".into(),
|
||||
"ai-agent-run:mnote-web-rust-host".into(),
|
||||
"tool".into(),
|
||||
"run".into(),
|
||||
"--tool-name".into(),
|
||||
"doc_get".into(),
|
||||
"--kind".into(),
|
||||
"query".into(),
|
||||
"--mode".into(),
|
||||
"explain-plan".into(),
|
||||
"--args-json".into(),
|
||||
args_json,
|
||||
]
|
||||
}
|
||||
|
||||
async fn run_local_mnote_cli_ai_host(
|
||||
state: &AppState,
|
||||
context: &RequestContext,
|
||||
payload: &Value,
|
||||
) -> Result<Response, WebError> {
|
||||
let stream = payload
|
||||
.get("stream")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(true);
|
||||
let args = build_mnote_cli_args(context, payload);
|
||||
let repo_root = resolve_repo_root();
|
||||
let actor_id =
|
||||
if context.auth.actor_id.trim().is_empty() || context.auth.actor_id == "anonymous" {
|
||||
state.config().dev_user_id.clone()
|
||||
} else {
|
||||
context.auth.actor_id.clone()
|
||||
};
|
||||
let actor_type =
|
||||
if context.auth.actor_type.trim().is_empty() || context.auth.actor_type == "anonymous" {
|
||||
"user".to_string()
|
||||
} else {
|
||||
context.auth.actor_type.clone()
|
||||
};
|
||||
let dev_email = state.config().dev_user_email.clone();
|
||||
let dev_name = state.config().dev_user_name.clone();
|
||||
|
||||
let output = tokio::task::spawn_blocking(move || {
|
||||
Command::new("cargo")
|
||||
.args(args)
|
||||
.current_dir(repo_root)
|
||||
.env("CARGO_TERM_COLOR", "never")
|
||||
.env(
|
||||
"RUSTUP_TOOLCHAIN",
|
||||
env::var("RUSTUP_TOOLCHAIN")
|
||||
.ok()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.unwrap_or_else(|| "1.89.0".into()),
|
||||
)
|
||||
.env("DEV_USER_ID", actor_id)
|
||||
.env("DEV_USER_EMAIL", dev_email)
|
||||
.env("DEV_USER_NAME", dev_name)
|
||||
.env("MNOTE_CLI_ALLOW_CREATE_PAGE", "1")
|
||||
.env("MNOTE_CLI_ALLOW_EDIT", "1")
|
||||
.env("MNOTE_ACTOR_TYPE", actor_type)
|
||||
.output()
|
||||
})
|
||||
.await
|
||||
.map_err(|error| {
|
||||
WebError::bad_gateway_code(
|
||||
"mnote_cli_host_join_error",
|
||||
format!("mnote-cli host join 失败: {error}"),
|
||||
)
|
||||
.with_context(context)
|
||||
.with_header("x-mnote-web-owner", "mnote-web")
|
||||
})?
|
||||
.map_err(|error| {
|
||||
WebError::bad_gateway_code(
|
||||
"mnote_cli_host_spawn_error",
|
||||
format!("mnote-cli host 启动失败: {error}"),
|
||||
)
|
||||
.with_context(context)
|
||||
.with_header("x-mnote-web-owner", "mnote-web")
|
||||
})?;
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
if !stream {
|
||||
if !output.status.success() {
|
||||
return Err(WebError::bad_gateway_code(
|
||||
"mnote_cli_host_failed",
|
||||
if stderr.is_empty() {
|
||||
"mnote-cli 执行失败".into()
|
||||
} else {
|
||||
stderr
|
||||
},
|
||||
)
|
||||
.with_context(context)
|
||||
.with_header("x-mnote-web-owner", "mnote-web"));
|
||||
}
|
||||
let mut response = Json(json!({
|
||||
"ok": true,
|
||||
"bridgeOwner": "mnote-cli",
|
||||
"text": if stdout.is_empty() { "mnote-cli 无输出" } else { &stdout },
|
||||
}))
|
||||
.into_response();
|
||||
stamp_owner_header(response.headers_mut());
|
||||
response.headers_mut().insert(
|
||||
HeaderName::from_static("x-mnote-ai-execution-owner"),
|
||||
HeaderValue::from_static("mnote-cli"),
|
||||
);
|
||||
return Ok(response);
|
||||
}
|
||||
|
||||
let body = if output.status.success() {
|
||||
format!(
|
||||
"event: ready\ndata: {}\n\nevent: assistant_message\ndata: {}\n\nevent: completion\ndata: {}\n\n",
|
||||
json!({"ok": true, "bridgeOwner": "mnote-cli"}).to_string(),
|
||||
json!({"text": if stdout.is_empty() { "mnote-cli 无输出" } else { &stdout }}).to_string(),
|
||||
json!({"ok": true, "text": if stdout.is_empty() { "mnote-cli 无输出" } else { &stdout }, "steps": 1}).to_string(),
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"event: ready\ndata: {}\n\nevent: error\ndata: {}\n\n",
|
||||
json!({"ok": true, "bridgeOwner": "mnote-cli"}).to_string(),
|
||||
json!({"ok": false, "message": if stderr.is_empty() { "mnote-cli 执行失败" } else { &stderr }}).to_string(),
|
||||
)
|
||||
};
|
||||
let mut response = Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(header::CONTENT_TYPE, "text/event-stream; charset=utf-8")
|
||||
.header(header::CACHE_CONTROL, "no-cache, no-transform")
|
||||
.header(header::CONNECTION, "keep-alive")
|
||||
.header("x-accel-buffering", "no")
|
||||
.header("x-mnote-ai-execution-owner", "mnote-cli")
|
||||
.body(Body::from(body))
|
||||
.map_err(|error| WebError::internal(format!("mnote-cli SSE 响应构造失败: {error}")))?;
|
||||
stamp_owner_header(response.headers_mut());
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
fn build_document_ai_orchestrator_payload(
|
||||
state: &AppState,
|
||||
context: &RequestContext,
|
||||
payload: &Value,
|
||||
) -> Value {
|
||||
let ai_options = payload.get("options").and_then(|value| value.get("ai"));
|
||||
let user_id = if context.auth.actor_id.trim().is_empty() || context.auth.actor_id == "anonymous"
|
||||
{
|
||||
state.config().dev_user_id.clone()
|
||||
} else {
|
||||
context.auth.actor_id.clone()
|
||||
};
|
||||
|
||||
json!({
|
||||
"userId": user_id,
|
||||
"sessionId": ai_options
|
||||
.and_then(|value| value.get("sessionId"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty()),
|
||||
"model": ai_options
|
||||
.and_then(|value| value.get("model"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty()),
|
||||
"modelKey": ai_options
|
||||
.and_then(|value| value.get("modelKey"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty()),
|
||||
"profileId": ai_options
|
||||
.and_then(|value| value.get("profileId"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty()),
|
||||
"maxSteps": payload.get("maxSteps").filter(|value| !value.is_null()).cloned().unwrap_or_else(|| json!(10)),
|
||||
"messages": payload.get("messages").cloned().unwrap_or_else(|| json!([])),
|
||||
"context": build_document_ai_context(payload.get("context")),
|
||||
})
|
||||
}
|
||||
|
||||
fn build_document_ai_context(context: Option<&Value>) -> Value {
|
||||
let get = |key: &str| {
|
||||
context
|
||||
.and_then(|value| value.get(key))
|
||||
.cloned()
|
||||
.unwrap_or(Value::Null)
|
||||
};
|
||||
|
||||
json!({
|
||||
"source": get("source"),
|
||||
"action": get("action"),
|
||||
"documentId": get("documentId"),
|
||||
"workspaceId": get("workspaceId"),
|
||||
"selectedBlockId": get("selectedBlockId"),
|
||||
"selectedBlockIndex": get("selectedBlockIndex"),
|
||||
"selectedUids": get("selectedUids"),
|
||||
"selectedText": get("selectedText"),
|
||||
"selection": get("selection"),
|
||||
"tiptapDocument": get("tiptapDocument"),
|
||||
"documentBlocks": get("documentBlocks"),
|
||||
"node": get("node"),
|
||||
"subtree": get("subtree"),
|
||||
"outline": get("outline"),
|
||||
"evidence": get("evidence"),
|
||||
"pageOptions": get("pageOptions"),
|
||||
})
|
||||
}
|
||||
|
||||
fn apply_ai_forward_headers(
|
||||
mut request: reqwest::RequestBuilder,
|
||||
headers: &HeaderMap,
|
||||
context: &RequestContext,
|
||||
) -> reqwest::RequestBuilder {
|
||||
for (name, value) in headers.iter() {
|
||||
if is_hop_by_hop_header(name.as_str())
|
||||
|| name == header::HOST
|
||||
|| name == header::CONTENT_LENGTH
|
||||
|| name == header::CONTENT_TYPE
|
||||
{
|
||||
continue;
|
||||
}
|
||||
request = request.header(name.as_str(), value.as_bytes());
|
||||
}
|
||||
|
||||
request = request.header(header::CONTENT_TYPE.as_str(), "application/json");
|
||||
request = request.header("x-request-id", context.trace.request_id.as_str());
|
||||
request = request.header("x-trace-id", context.trace.trace_id.as_str());
|
||||
request = request.header("x-mnote-source-channel", "rust_web_route");
|
||||
request = request.header("x-mnote-source-client", "mnote-web");
|
||||
request = request.header("x-mnote-actor-id", context.auth.actor_id.as_str());
|
||||
request.header("x-mnote-actor-type", context.auth.actor_type.as_str())
|
||||
}
|
||||
|
||||
fn build_ai_sse_proxy_response(
|
||||
upstream_response: reqwest::Response,
|
||||
context: &RequestContext,
|
||||
) -> Result<Response, WebError> {
|
||||
let status =
|
||||
StatusCode::from_u16(upstream_response.status().as_u16()).unwrap_or(StatusCode::OK);
|
||||
let ready = Bytes::from(format!(
|
||||
"event: ready\ndata: {}\n\n",
|
||||
json!({"ok": true, "requestId": context.trace.request_id}).to_string()
|
||||
));
|
||||
let upstream_stream = upstream_response
|
||||
.bytes_stream()
|
||||
.map_err(std::io::Error::other);
|
||||
let body_stream = futures_util::stream::once(async move { Ok::<Bytes, std::io::Error>(ready) })
|
||||
.chain(upstream_stream);
|
||||
|
||||
let mut response = Response::builder()
|
||||
.status(status)
|
||||
.header(header::CONTENT_TYPE, "text/event-stream; charset=utf-8")
|
||||
.header(header::CACHE_CONTROL, "no-cache, no-transform")
|
||||
.header(header::CONNECTION, "keep-alive")
|
||||
.header("x-accel-buffering", "no")
|
||||
.body(Body::from_stream(body_stream))
|
||||
.map_err(|error| WebError::internal(format!("AI SSE 响应构造失败: {error}")))?;
|
||||
stamp_owner_header(response.headers_mut());
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
fn stamp_owner_header(headers: &mut HeaderMap) {
|
||||
if let Ok(name) = HeaderName::from_lowercase(b"x-mnote-web-owner") {
|
||||
headers.insert(name, HeaderValue::from_static("mnote-web"));
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_ai_orchestrator_backend_url() -> Option<String> {
|
||||
read_env_or_dotenv("BACKEND_INTERNAL_URL")
|
||||
.or_else(|| read_env_or_dotenv("BACKEND_URL"))
|
||||
.map(|value| value.trim().trim_end_matches('/').to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
fn read_env_or_dotenv(key: &str) -> Option<String> {
|
||||
if let Ok(value) = env::var(key) {
|
||||
let trimmed = value.trim().trim_matches('"').to_string();
|
||||
if !trimmed.is_empty() {
|
||||
return Some(trimmed);
|
||||
}
|
||||
}
|
||||
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../..")
|
||||
.join(".env.all");
|
||||
let content = fs::read_to_string(root).ok()?;
|
||||
for line in content.lines() {
|
||||
let line = line.trim_end_matches('\r');
|
||||
if line.starts_with('#') || line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some((k, v)) = line.split_once('=') else {
|
||||
continue;
|
||||
};
|
||||
if k.trim() != key {
|
||||
continue;
|
||||
}
|
||||
let trimmed = v.trim().trim_matches('"').to_string();
|
||||
if !trimmed.is_empty() {
|
||||
return Some(trimmed);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn is_hop_by_hop_header(name: &str) -> bool {
|
||||
matches!(
|
||||
name.to_ascii_lowercase().as_str(),
|
||||
"connection"
|
||||
| "keep-alive"
|
||||
| "proxy-authenticate"
|
||||
| "proxy-authorization"
|
||||
| "te"
|
||||
| "trailers"
|
||||
| "transfer-encoding"
|
||||
| "upgrade"
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn next_sidebar(
|
||||
@@ -97,6 +621,8 @@ mod tests {
|
||||
use crate::app::{build_app, AppConfig, AppState};
|
||||
use axum::body::Body;
|
||||
use axum::http::{Request, StatusCode};
|
||||
use axum::response::IntoResponse;
|
||||
use tokio::net::TcpListener;
|
||||
use tower::util::ServiceExt;
|
||||
|
||||
fn app() -> axum::Router {
|
||||
@@ -135,4 +661,120 @@ mod tests {
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn direct_ai_agent_run_is_owned_by_rust_web_when_next_compat_disabled() {
|
||||
let response = 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: false,
|
||||
enable_debug_shell_routes: false,
|
||||
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: None,
|
||||
mutation_fixtures_json: None,
|
||||
dev_user_id: "dev-user".into(),
|
||||
dev_user_name: "开发用户".into(),
|
||||
dev_user_email: "dev@mnote.local".into(),
|
||||
}))
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/ai-agent/run")
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(r#"{"stream":true,"scope":"document","messages":[{"role":"user","content":"ping"}],"context":{"documentId":"doc-1"},"options":{"ai":{"provider":"online"}}}"#))
|
||||
.expect("request"),
|
||||
)
|
||||
.await
|
||||
.expect("response");
|
||||
|
||||
assert_ne!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
assert_eq!(
|
||||
response
|
||||
.headers()
|
||||
.get("x-mnote-web-owner")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("mnote-web")
|
||||
);
|
||||
let body = axum::body::to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("body");
|
||||
let text = String::from_utf8(body.to_vec()).expect("utf8");
|
||||
assert!(!text.contains("legacy_next_compat_disabled"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ai_agent_run_proxies_to_next_ai_route_when_legacy_next_compat_enabled() {
|
||||
let next_app = axum::Router::new().route(
|
||||
"/api/ai-agent/run",
|
||||
axum::routing::post(|| async move {
|
||||
(
|
||||
[(
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
"text/event-stream; charset=utf-8",
|
||||
)],
|
||||
"event: assistant_message\ndata: {\"text\":\"hello from next ai\"}\n\n",
|
||||
)
|
||||
.into_response()
|
||||
}),
|
||||
);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind next");
|
||||
let addr = listener.local_addr().expect("local addr");
|
||||
let server = tokio::spawn(async move {
|
||||
axum::serve(listener, next_app).await.expect("serve next");
|
||||
});
|
||||
|
||||
let response = 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(format!("http://{}", addr)),
|
||||
enable_legacy_next_compat: true,
|
||||
enable_debug_shell_routes: false,
|
||||
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: None,
|
||||
mutation_fixtures_json: None,
|
||||
dev_user_id: "dev-user".into(),
|
||||
dev_user_name: "开发用户".into(),
|
||||
dev_user_email: "dev@mnote.local".into(),
|
||||
}))
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/ai-agent/run")
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(r#"{"stream":true,"scope":"document","messages":[{"role":"user","content":"ping"}],"context":{"documentId":"doc-1"},"options":{"ai":{"provider":"hermes"}}}"#))
|
||||
.expect("request"),
|
||||
)
|
||||
.await
|
||||
.expect("response");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
response
|
||||
.headers()
|
||||
.get("x-mnote-web-owner")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("mnote-web")
|
||||
);
|
||||
let body = axum::body::to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("body");
|
||||
let text = String::from_utf8(body.to_vec()).expect("utf8");
|
||||
assert!(text.contains("assistant_message"));
|
||||
assert!(text.contains("hello from next ai"));
|
||||
|
||||
server.abort();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,6 +65,12 @@ pub struct DocumentOptionsRequest {
|
||||
pub command_name: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DocumentPurgeRequest {
|
||||
pub document_id: String,
|
||||
}
|
||||
|
||||
const NEXT_DOCUMENTS_BASE_URL_ENV: &str = "MNOTE_NEXT_BASE_URL";
|
||||
const HEADER_MNOTE_WEB_OWNER: &str = "x-mnote-web-owner";
|
||||
const HEADER_DOCUMENTS_TRANSPORT: &str = "x-mnote-documents-transport";
|
||||
@@ -552,6 +558,50 @@ pub async fn save(
|
||||
Ok(ok_response(&context, result))
|
||||
}
|
||||
|
||||
pub async fn purge(
|
||||
State(state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
Json(body): Json<DocumentPurgeRequest>,
|
||||
) -> Result<(StatusCode, HeaderMap, Json<Value>), WebError> {
|
||||
let document_id = body.document_id.trim();
|
||||
if document_id.is_empty() {
|
||||
return Err(
|
||||
WebError::bad_request_code("document_id_required", "缺少有效 documentId")
|
||||
.with_context(&context),
|
||||
);
|
||||
}
|
||||
let command = RuntimeCommandEnvelopeWire {
|
||||
name: "documents.purge".into(),
|
||||
command_id: format!("document_purge_{}", context.trace.request_id),
|
||||
idempotency_key: context.source.idempotency_key.clone(),
|
||||
actor: RuntimeActorWire {
|
||||
actor_type: context.auth.actor_type.clone(),
|
||||
actor_id: context.auth.actor_id.clone(),
|
||||
session_id: context.auth.session_id.clone(),
|
||||
},
|
||||
source: RuntimeSourceWire {
|
||||
channel: context.source.channel.clone(),
|
||||
client: context.source.client.clone(),
|
||||
},
|
||||
target: Some(RuntimeTargetWire {
|
||||
workspace_id: None,
|
||||
page_id: Some(document_id.to_string()),
|
||||
block_id: None,
|
||||
}),
|
||||
payload: json!({
|
||||
"documentId": document_id,
|
||||
}),
|
||||
preflight_data: None,
|
||||
reason: Some("mnote-web documents purge compat".into()),
|
||||
refs: vec!["mnote-web-documents-compat".into()],
|
||||
dry_run: false,
|
||||
validate_only: false,
|
||||
};
|
||||
let result =
|
||||
execute_runtime_command_via_convex(state.config(), &context, None, command).await?;
|
||||
Ok(ok_response(&context, result))
|
||||
}
|
||||
|
||||
pub async fn title(
|
||||
State(state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
|
||||
@@ -19,6 +19,10 @@ use std::time::Duration;
|
||||
const HEADER_MNOTE_WEB_OWNER: &str = "x-mnote-web-owner";
|
||||
const HEADER_MNOTE_LEGACY_UPSTREAM: &str = "x-mnote-legacy-upstream";
|
||||
const COOKIE_RECENT_PAGE_ID: &str = "mnote_recent_page_id";
|
||||
const COOKIE_CONVEX_AUTH_JWT: &str = "__convexAuthJWT";
|
||||
const COOKIE_CONVEX_AUTH_REFRESH_TOKEN: &str = "__convexAuthRefreshToken";
|
||||
const COOKIE_MNOTE_WEB_CONVEX_TOKEN: &str = "mnote_web_convex_token";
|
||||
const COOKIE_MNOTE_WEB_DEV_SESSION: &str = "mnote_web_dev_session";
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -55,7 +59,16 @@ pub async fn gateway_health(State(state): State<AppState>) -> Response {
|
||||
response
|
||||
}
|
||||
|
||||
pub async fn auth_entry(
|
||||
pub async fn favicon() -> Response {
|
||||
let mut response = Response::builder()
|
||||
.status(StatusCode::NO_CONTENT)
|
||||
.body(Body::empty())
|
||||
.unwrap_or_else(|_| StatusCode::NO_CONTENT.into_response());
|
||||
stamp_gateway_headers(response.headers_mut(), false);
|
||||
response
|
||||
}
|
||||
|
||||
pub async fn auth_api(
|
||||
State(state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
request: Request<Body>,
|
||||
@@ -64,6 +77,49 @@ pub async fn auth_entry(
|
||||
return legacy_next_proxy(State(state), Extension(context), request).await;
|
||||
}
|
||||
|
||||
let body = axum::body::to_bytes(request.into_body(), 256 * 1024)
|
||||
.await
|
||||
.map_err(|error| WebError::bad_request(format!("读取登录请求失败: {error}")))?;
|
||||
let payload: serde_json::Value = serde_json::from_slice(&body).map_err(|error| {
|
||||
WebError::bad_request_code(
|
||||
"auth_bad_request",
|
||||
format!("登录请求不是合法 JSON: {error}"),
|
||||
)
|
||||
.with_context(&context)
|
||||
.with_header(HEADER_MNOTE_WEB_OWNER, "mnote-web")
|
||||
})?;
|
||||
let action = payload
|
||||
.get("action")
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_default();
|
||||
if action != "auth:signIn" && action != "auth:signOut" {
|
||||
return Err(WebError::bad_request_code(
|
||||
"auth_action_unsupported",
|
||||
"Rust gateway 当前仅支持 Convex Auth 登录与登出动作。",
|
||||
)
|
||||
.with_context(&context)
|
||||
.with_header(HEADER_MNOTE_WEB_OWNER, "mnote-web"));
|
||||
}
|
||||
|
||||
let convex_response = run_convex_auth_action(&state, &context, &payload).await?;
|
||||
Ok(build_auth_proxy_response(&convex_response, &context))
|
||||
}
|
||||
|
||||
pub async fn auth_entry(
|
||||
State(_state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
_request: Request<Body>,
|
||||
) -> Result<Response, WebError> {
|
||||
if has_real_auth_context(&context) {
|
||||
let mut response = Response::builder()
|
||||
.status(StatusCode::SEE_OTHER)
|
||||
.header(header::LOCATION, "/")
|
||||
.body(Body::empty())
|
||||
.map_err(|error| WebError::internal(format!("认证跳转响应构造失败: {error}")))?;
|
||||
stamp_gateway_headers(response.headers_mut(), false);
|
||||
return Ok(response);
|
||||
}
|
||||
|
||||
let content = crate::ssr::render_view(crate::ssr::pages::auth::AuthPage());
|
||||
let mut response = Html(format!(
|
||||
r#"<!doctype html>
|
||||
@@ -90,6 +146,16 @@ pub async fn root_entry(
|
||||
Extension(context): Extension<RequestContext>,
|
||||
Query(query): Query<RootEntryQuery>,
|
||||
) -> Result<Response, WebError> {
|
||||
if !has_real_auth_context(&context) {
|
||||
let mut response = Response::builder()
|
||||
.status(StatusCode::SEE_OTHER)
|
||||
.header(header::LOCATION, "/auth")
|
||||
.body(Body::empty())
|
||||
.map_err(|error| WebError::internal(format!("认证入口跳转响应构造失败: {error}")))?;
|
||||
stamp_gateway_headers(response.headers_mut(), false);
|
||||
return Ok(response);
|
||||
}
|
||||
|
||||
let workspace_id =
|
||||
resolve_root_workspace_id(&state, &context, query.workspace_id.as_deref()).await?;
|
||||
let requested_page_id = normalize_optional_id(query.page_id.as_deref());
|
||||
@@ -365,6 +431,195 @@ fn normalize_optional_id(value: Option<&str>) -> Option<&str> {
|
||||
value.map(str::trim).filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
fn has_real_auth_context(context: &RequestContext) -> bool {
|
||||
let actor_id = context.auth.actor_id.trim();
|
||||
if !actor_id.is_empty() && actor_id != "anonymous" {
|
||||
return true;
|
||||
}
|
||||
|
||||
extract_cookie_value(context, COOKIE_CONVEX_AUTH_JWT).is_some()
|
||||
|| extract_cookie_value(context, COOKIE_MNOTE_WEB_CONVEX_TOKEN).is_some()
|
||||
}
|
||||
|
||||
async fn run_convex_auth_action(
|
||||
state: &AppState,
|
||||
context: &RequestContext,
|
||||
payload: &serde_json::Value,
|
||||
) -> Result<serde_json::Value, WebError> {
|
||||
let convex_url = state
|
||||
.config()
|
||||
.convex_url
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.ok_or_else(|| {
|
||||
WebError::service_unavailable_code(
|
||||
"convex_config_missing",
|
||||
"缺少 CONVEX_SELF_HOSTED_URL / NEXT_PUBLIC_CONVEX_URL,无法执行 Convex Auth。",
|
||||
)
|
||||
.with_context(context)
|
||||
.with_header("x-error-phase", "convex_auth_url")
|
||||
.with_header("x-upstream-service", "convex")
|
||||
})?;
|
||||
let action = payload
|
||||
.get("action")
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_default();
|
||||
let mut args = payload.get("args").cloned().unwrap_or_else(|| json!({}));
|
||||
if action == "auth:signIn"
|
||||
&& args
|
||||
.get("refreshToken")
|
||||
.map(|value| !value.is_null())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
if let Some(refresh_token) = extract_cookie_value(context, COOKIE_CONVEX_AUTH_REFRESH_TOKEN)
|
||||
{
|
||||
args["refreshToken"] = serde_json::Value::String(refresh_token);
|
||||
}
|
||||
}
|
||||
|
||||
let request_body = json!({
|
||||
"path": action,
|
||||
"format": "convex_encoded_json",
|
||||
"args": [args],
|
||||
});
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(Duration::from_secs(20))
|
||||
.build()
|
||||
.map_err(|error| {
|
||||
WebError::internal(format!("Convex Auth HTTP 客户端创建失败: {error}"))
|
||||
.with_context(context)
|
||||
.with_header("x-error-phase", "convex_auth_client")
|
||||
.with_header("x-upstream-service", "convex")
|
||||
})?;
|
||||
let mut request = client
|
||||
.post(format!("{}/api/action", convex_url.trim_end_matches('/')))
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Convex-Client", "mnote-web")
|
||||
.json(&request_body);
|
||||
if let Some(token) = extract_cookie_value(context, COOKIE_CONVEX_AUTH_JWT) {
|
||||
request = request.header(header::AUTHORIZATION, format!("Bearer {token}"));
|
||||
}
|
||||
|
||||
let response = request.send().await.map_err(|error| {
|
||||
WebError::bad_gateway_code(
|
||||
"convex_auth_proxy_error",
|
||||
format!("Convex Auth 请求失败: {error}"),
|
||||
)
|
||||
.with_context(context)
|
||||
.with_header("x-error-phase", "convex_auth_action")
|
||||
.with_header("x-upstream-service", "convex")
|
||||
})?;
|
||||
let status = response.status();
|
||||
let value: serde_json::Value = response.json().await.map_err(|error| {
|
||||
WebError::bad_gateway_code(
|
||||
"convex_auth_response_invalid",
|
||||
format!("Convex Auth 响应不是合法 JSON: {error}"),
|
||||
)
|
||||
.with_context(context)
|
||||
.with_header("x-error-phase", "convex_auth_decode")
|
||||
.with_header("x-upstream-service", "convex")
|
||||
})?;
|
||||
if !status.is_success() && status.as_u16() != 560 {
|
||||
return Err(WebError::bad_gateway_code(
|
||||
"convex_auth_upstream_error",
|
||||
format!("Convex Auth 返回 HTTP {}: {}", status.as_u16(), value),
|
||||
)
|
||||
.with_context(context)
|
||||
.with_header("x-error-phase", "convex_auth_status")
|
||||
.with_header("x-upstream-service", "convex"));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn build_auth_proxy_response(
|
||||
convex_response: &serde_json::Value,
|
||||
context: &RequestContext,
|
||||
) -> Response {
|
||||
if convex_response
|
||||
.get("status")
|
||||
.and_then(|value| value.as_str())
|
||||
!= Some("success")
|
||||
{
|
||||
let message = convex_response
|
||||
.get("errorMessage")
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or("Convex Auth 登录失败。");
|
||||
let mut response = axum::Json(json!({ "error": message })).into_response();
|
||||
*response.status_mut() = StatusCode::BAD_REQUEST;
|
||||
clear_auth_cookies(response.headers_mut());
|
||||
stamp_gateway_headers(response.headers_mut(), false);
|
||||
context.apply_response_headers(response.headers_mut());
|
||||
return response;
|
||||
}
|
||||
|
||||
let value = convex_response
|
||||
.get("value")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!({}));
|
||||
let tokens = value.get("tokens");
|
||||
let mut response_body = value.clone();
|
||||
if let Some(tokens) = tokens {
|
||||
if tokens.is_null() {
|
||||
response_body["tokens"] = serde_json::Value::Null;
|
||||
} else if let Some(token) = tokens.get("token").and_then(|value| value.as_str()) {
|
||||
response_body["tokens"] = json!({
|
||||
"token": token,
|
||||
"refreshToken": "dummy",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let mut response = axum::Json(response_body).into_response();
|
||||
if let Some(tokens) = tokens {
|
||||
if tokens.is_null() {
|
||||
clear_auth_cookies(response.headers_mut());
|
||||
} else {
|
||||
set_auth_cookie_from_value(
|
||||
response.headers_mut(),
|
||||
COOKIE_CONVEX_AUTH_JWT,
|
||||
tokens.get("token"),
|
||||
);
|
||||
set_auth_cookie_from_value(
|
||||
response.headers_mut(),
|
||||
COOKIE_CONVEX_AUTH_REFRESH_TOKEN,
|
||||
tokens.get("refreshToken"),
|
||||
);
|
||||
expire_cookie(response.headers_mut(), COOKIE_MNOTE_WEB_DEV_SESSION);
|
||||
}
|
||||
}
|
||||
stamp_gateway_headers(response.headers_mut(), false);
|
||||
context.apply_response_headers(response.headers_mut());
|
||||
response
|
||||
}
|
||||
|
||||
fn set_auth_cookie_from_value(
|
||||
headers: &mut axum::http::HeaderMap,
|
||||
name: &'static str,
|
||||
value: Option<&serde_json::Value>,
|
||||
) {
|
||||
let Some(value) = value.and_then(|value| value.as_str()) else {
|
||||
return;
|
||||
};
|
||||
let cookie = format!("{name}={value}; Path=/; HttpOnly; SameSite=Lax");
|
||||
if let Ok(value) = HeaderValue::from_str(&cookie) {
|
||||
headers.append(header::SET_COOKIE, value);
|
||||
}
|
||||
}
|
||||
|
||||
fn clear_auth_cookies(headers: &mut axum::http::HeaderMap) {
|
||||
expire_cookie(headers, COOKIE_CONVEX_AUTH_JWT);
|
||||
expire_cookie(headers, COOKIE_CONVEX_AUTH_REFRESH_TOKEN);
|
||||
expire_cookie(headers, COOKIE_MNOTE_WEB_DEV_SESSION);
|
||||
}
|
||||
|
||||
fn expire_cookie(headers: &mut axum::http::HeaderMap, name: &'static str) {
|
||||
let cookie = format!("{name}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0");
|
||||
if let Ok(value) = HeaderValue::from_str(&cookie) {
|
||||
headers.append(header::SET_COOKIE, value);
|
||||
}
|
||||
}
|
||||
|
||||
fn choose_root_entry_active_page_id(
|
||||
requested_page_id: Option<&str>,
|
||||
recent_page_id: Option<&str>,
|
||||
@@ -466,6 +721,14 @@ mod tests {
|
||||
fn app_with_config(
|
||||
legacy_next_base_url: String,
|
||||
enable_legacy_next_compat: bool,
|
||||
) -> axum::Router {
|
||||
app_with_config_and_convex_url(legacy_next_base_url, enable_legacy_next_compat, None)
|
||||
}
|
||||
|
||||
fn app_with_config_and_convex_url(
|
||||
legacy_next_base_url: String,
|
||||
enable_legacy_next_compat: bool,
|
||||
convex_url: Option<String>,
|
||||
) -> axum::Router {
|
||||
build_app(AppState::new(AppConfig {
|
||||
service_name: "mnote-web".into(),
|
||||
@@ -477,7 +740,7 @@ mod tests {
|
||||
enable_debug_shell_routes: false,
|
||||
hermes_base_path: "/api/hermes".into(),
|
||||
compat_next_base_path: "/api/compat/next".into(),
|
||||
convex_url: None,
|
||||
convex_url,
|
||||
convex_admin_key: None,
|
||||
allow_dev_fixtures: true,
|
||||
query_fixtures_json: None,
|
||||
@@ -488,6 +751,33 @@ mod tests {
|
||||
}))
|
||||
}
|
||||
|
||||
async fn spawn_convex_auth_upstream() -> String {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("convex auth listener");
|
||||
let addr = listener.local_addr().expect("convex auth addr");
|
||||
let app = axum::Router::new().route(
|
||||
"/api/action",
|
||||
post(|| async {
|
||||
axum::Json(serde_json::json!({
|
||||
"status": "success",
|
||||
"value": {
|
||||
"tokens": {
|
||||
"token": "jwt-demo",
|
||||
"refreshToken": "refresh-demo"
|
||||
}
|
||||
}
|
||||
}))
|
||||
}),
|
||||
);
|
||||
tokio::spawn(async move {
|
||||
axum::serve(listener, app)
|
||||
.await
|
||||
.expect("convex auth server");
|
||||
});
|
||||
format!("http://{addr}")
|
||||
}
|
||||
|
||||
async fn spawn_legacy_auth_upstream() -> String {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
@@ -598,6 +888,8 @@ mod tests {
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/")
|
||||
.header("x-mnote-actor-id", "user_real")
|
||||
.header("x-mnote-actor-type", "user")
|
||||
.body(Body::empty())
|
||||
.expect("request"),
|
||||
)
|
||||
@@ -674,6 +966,8 @@ mod tests {
|
||||
.uri("/")
|
||||
.header("cookie", "mnote_recent_page_id=page_child")
|
||||
.header("x-mnote-workspace-id", "ws_demo")
|
||||
.header("x-mnote-actor-id", "user_real")
|
||||
.header("x-mnote-actor-type", "user")
|
||||
.body(Body::empty())
|
||||
.expect("request"),
|
||||
)
|
||||
@@ -691,6 +985,57 @@ mod tests {
|
||||
assert!(html.contains(r#"data-root-active-page-id="page_child""#));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn root_entry_redirects_anonymous_viewer_to_auth() {
|
||||
let response = app_with_config("http://127.0.0.1:3100".into(), false)
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/")
|
||||
.body(Body::empty())
|
||||
.expect("request"),
|
||||
)
|
||||
.await
|
||||
.expect("response");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::SEE_OTHER);
|
||||
assert_eq!(
|
||||
response
|
||||
.headers()
|
||||
.get(header::LOCATION)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("/auth")
|
||||
);
|
||||
assert_eq!(
|
||||
response
|
||||
.headers()
|
||||
.get("x-mnote-web-owner")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("mnote-web")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn root_entry_allows_forwarded_actor_to_enter_workspace() {
|
||||
let response = app_with_config("http://127.0.0.1:3100".into(), false)
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/")
|
||||
.header("x-mnote-actor-id", "user_real")
|
||||
.header("x-mnote-actor-type", "user")
|
||||
.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 html = String::from_utf8(body.to_vec()).expect("utf8");
|
||||
assert!(html.contains(r#"data-mnote-shell="workspace""#));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn auth_entry_returns_gateway_fallback_shell_when_compat_disabled() {
|
||||
let response = app_with_config("http://127.0.0.1:3100".into(), false)
|
||||
@@ -720,7 +1065,77 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn auth_entry_uses_legacy_next_login_ui_when_compat_enabled() {
|
||||
async fn favicon_is_handled_by_gateway_when_compat_disabled() {
|
||||
let response = app_with_config("http://127.0.0.1:3100".into(), false)
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/favicon.ico")
|
||||
.body(Body::empty())
|
||||
.expect("request"),
|
||||
)
|
||||
.await
|
||||
.expect("response");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::NO_CONTENT);
|
||||
assert_eq!(
|
||||
response
|
||||
.headers()
|
||||
.get("x-mnote-web-owner")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("mnote-web")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn auth_api_sets_convex_auth_cookies_when_compat_disabled() {
|
||||
let convex_url = spawn_convex_auth_upstream().await;
|
||||
let response = app_with_config_and_convex_url(
|
||||
"http://127.0.0.1:3100".into(),
|
||||
false,
|
||||
Some(convex_url),
|
||||
)
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/auth")
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(
|
||||
r#"{"action":"auth:signIn","args":{"provider":"password","params":{"email":"mnote.e2e@example.com","password":"MnoteE2E123!","flow":"signIn"}}}"#,
|
||||
))
|
||||
.expect("request"),
|
||||
)
|
||||
.await
|
||||
.expect("response");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
response
|
||||
.headers()
|
||||
.get("x-mnote-web-owner")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("mnote-web")
|
||||
);
|
||||
let cookies = response.headers().get_all(header::SET_COOKIE);
|
||||
let values = cookies
|
||||
.iter()
|
||||
.map(|value| value.to_str().unwrap_or_default())
|
||||
.collect::<Vec<_>>();
|
||||
assert!(values
|
||||
.iter()
|
||||
.any(|value| value.contains("__convexAuthJWT=jwt-demo")));
|
||||
assert!(values
|
||||
.iter()
|
||||
.any(|value| value.contains("__convexAuthRefreshToken=refresh-demo")));
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("body");
|
||||
let payload: serde_json::Value = serde_json::from_slice(&body).expect("json");
|
||||
assert_eq!(payload["tokens"]["token"], "jwt-demo");
|
||||
assert_eq!(payload["tokens"]["refreshToken"], "dummy");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn auth_entry_uses_mnote_web_login_ui_when_compat_enabled() {
|
||||
let legacy_base_url = spawn_legacy_auth_upstream().await;
|
||||
let response = app_with_legacy_next_base_url(legacy_base_url)
|
||||
.oneshot(
|
||||
@@ -738,44 +1153,39 @@ mod tests {
|
||||
.headers()
|
||||
.get("x-mnote-legacy-upstream")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("next-app-router")
|
||||
None
|
||||
);
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("body");
|
||||
let html = String::from_utf8(body.to_vec()).expect("utf8");
|
||||
assert!(html.contains(r#"data-mnote-shell="auth""#));
|
||||
assert!(html.contains("邮箱登录"));
|
||||
assert!(html.contains("测试账号快速登录"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn auth_entry_proxies_post_to_legacy_next_when_compat_enabled() {
|
||||
let legacy_base_url = spawn_legacy_auth_upstream().await;
|
||||
let response = app_with_legacy_next_base_url(legacy_base_url)
|
||||
async fn auth_entry_redirects_authenticated_viewer_to_root() {
|
||||
let response = app_with_config("http://127.0.0.1:3100".into(), false)
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/auth")
|
||||
.header("origin", "http://127.0.0.1:3000")
|
||||
.header("referer", "http://127.0.0.1:3000/auth")
|
||||
.header("x-mnote-actor-id", "user_real")
|
||||
.header("x-mnote-actor-type", "user")
|
||||
.body(Body::empty())
|
||||
.expect("request"),
|
||||
)
|
||||
.await
|
||||
.expect("response");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.status(), StatusCode::SEE_OTHER);
|
||||
assert_eq!(
|
||||
response
|
||||
.headers()
|
||||
.get("x-mnote-legacy-upstream")
|
||||
.get(header::LOCATION)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("next-app-router")
|
||||
Some("/")
|
||||
);
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("body");
|
||||
let text = String::from_utf8(body.to_vec()).expect("utf8");
|
||||
assert_eq!(text, "auth-post-ok");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -30,6 +30,7 @@ pub fn build_router(state: AppState) -> Router {
|
||||
let mut router = Router::new()
|
||||
.route("/health", get(health::health))
|
||||
.route("/", get(gateway::root_entry))
|
||||
.route("/favicon.ico", get(gateway::favicon))
|
||||
.route("/auth", get(gateway::auth_entry).post(gateway::auth_entry))
|
||||
.route("/search", get(search::shell))
|
||||
.route(
|
||||
@@ -59,10 +60,16 @@ pub fn build_router(state: AppState) -> Router {
|
||||
.route("/api/search/documents", post(search::documents))
|
||||
.route("/api/gateway/health", get(gateway::gateway_health))
|
||||
.route("/api/runtime/config", get(session::runtime_config))
|
||||
.route("/api/auth", post(gateway::auth_api))
|
||||
.route("/api/auth/session", get(session::session))
|
||||
.route("/api/auth/whoami", get(session::session))
|
||||
.route("/api/auth/mnote-web-token", get(session::session))
|
||||
.route("/api/auth/session/refresh", post(session::refresh_session))
|
||||
.route("/api/ai-agent/run", post(compat::next_ai_agent_run))
|
||||
.route("/api/documents/meta", get(documents::meta))
|
||||
.route("/api/documents/content", get(documents::content))
|
||||
.route("/api/documents/page", get(web_shell::documents_page_compat))
|
||||
.route("/api/documents/purge", post(documents::purge))
|
||||
.route("/api/documents/title", post(documents::title))
|
||||
.route("/api/documents/options", post(documents::options))
|
||||
.route("/api/documents/save", post(documents::save))
|
||||
|
||||
@@ -28,6 +28,7 @@ pub struct SessionResponse {
|
||||
pub email: String,
|
||||
pub name: String,
|
||||
pub actor_type: String,
|
||||
pub auth_mode: &'static str,
|
||||
pub request_id: String,
|
||||
pub trace_id: String,
|
||||
}
|
||||
@@ -47,36 +48,57 @@ pub async fn session(
|
||||
State(state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
) -> Response {
|
||||
owner_json(Json(SessionResponse {
|
||||
ok: true,
|
||||
owner: "mnote-web",
|
||||
user_id: state.config().dev_user_id.clone(),
|
||||
email: state.config().dev_user_email.clone(),
|
||||
name: state.config().dev_user_name.clone(),
|
||||
actor_type: context.auth.actor_type,
|
||||
request_id: context.trace.request_id,
|
||||
trace_id: context.trace.trace_id,
|
||||
}))
|
||||
owner_json(Json(build_session_response(&state, context)))
|
||||
}
|
||||
|
||||
pub async fn refresh_session(
|
||||
State(state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
) -> Response {
|
||||
let mut response = owner_json(Json(SessionResponse {
|
||||
ok: true,
|
||||
owner: "mnote-web",
|
||||
user_id: state.config().dev_user_id.clone(),
|
||||
email: state.config().dev_user_email.clone(),
|
||||
name: state.config().dev_user_name.clone(),
|
||||
actor_type: context.auth.actor_type,
|
||||
request_id: context.trace.request_id,
|
||||
trace_id: context.trace.trace_id,
|
||||
}));
|
||||
let mut response = owner_json(Json(build_session_response(&state, context)));
|
||||
*response.status_mut() = StatusCode::OK;
|
||||
response
|
||||
}
|
||||
|
||||
fn build_session_response(state: &AppState, context: RequestContext) -> SessionResponse {
|
||||
let actor_id = context.auth.actor_id.trim();
|
||||
let has_forwarded_actor = !actor_id.is_empty() && actor_id != "anonymous";
|
||||
let user_id = if has_forwarded_actor {
|
||||
actor_id.to_string()
|
||||
} else {
|
||||
state.config().dev_user_id.clone()
|
||||
};
|
||||
let actor_type = if has_forwarded_actor {
|
||||
context.auth.actor_type
|
||||
} else {
|
||||
"devFallback".to_string()
|
||||
};
|
||||
|
||||
SessionResponse {
|
||||
ok: true,
|
||||
owner: "mnote-web",
|
||||
user_id,
|
||||
email: if has_forwarded_actor {
|
||||
String::new()
|
||||
} else {
|
||||
state.config().dev_user_email.clone()
|
||||
},
|
||||
name: if has_forwarded_actor {
|
||||
actor_id.to_string()
|
||||
} else {
|
||||
state.config().dev_user_name.clone()
|
||||
},
|
||||
actor_type,
|
||||
auth_mode: if has_forwarded_actor {
|
||||
"forwardedActor"
|
||||
} else {
|
||||
"devFallback"
|
||||
},
|
||||
request_id: context.trace.request_id,
|
||||
trace_id: context.trace.trace_id,
|
||||
}
|
||||
}
|
||||
|
||||
fn owner_json<T>(payload: Json<T>) -> Response
|
||||
where
|
||||
T: Serialize,
|
||||
@@ -172,4 +194,100 @@ mod tests {
|
||||
assert_eq!(payload["userId"], "dev-user");
|
||||
assert!(payload.get("convexAdminKey").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_prefers_forwarded_actor_identity_over_dev_fallback() {
|
||||
let response = app()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/auth/session")
|
||||
.header("x-mnote-actor-id", "user_real")
|
||||
.header("x-mnote-actor-type", "user")
|
||||
.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: serde_json::Value = serde_json::from_slice(&body).expect("json");
|
||||
assert_eq!(payload["owner"], "mnote-web");
|
||||
assert_eq!(payload["userId"], "user_real");
|
||||
assert_eq!(payload["actorType"], "user");
|
||||
assert_eq!(payload["authMode"], "forwardedActor");
|
||||
assert!(payload.get("convexAdminKey").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_whoami_alias_prefers_forwarded_actor_identity() {
|
||||
let response = app()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/auth/whoami")
|
||||
.header("x-mnote-actor-id", "user_real")
|
||||
.header("x-mnote-actor-type", "user")
|
||||
.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: serde_json::Value = serde_json::from_slice(&body).expect("json");
|
||||
assert_eq!(payload["owner"], "mnote-web");
|
||||
assert_eq!(payload["userId"], "user_real");
|
||||
assert_eq!(payload["actorType"], "user");
|
||||
assert_eq!(payload["authMode"], "forwardedActor");
|
||||
assert_ne!(payload["code"], "legacy_next_compat_disabled");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_whoami_alias_returns_dev_identity() {
|
||||
let response = app()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/auth/whoami")
|
||||
.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: serde_json::Value = serde_json::from_slice(&body).expect("json");
|
||||
assert_eq!(payload["owner"], "mnote-web");
|
||||
assert_eq!(payload["userId"], "dev-user");
|
||||
assert_ne!(payload["code"], "legacy_next_compat_disabled");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_mnote_web_token_alias_returns_dev_identity() {
|
||||
let response = app()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/auth/mnote-web-token")
|
||||
.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: serde_json::Value = serde_json::from_slice(&body).expect("json");
|
||||
assert_eq!(payload["owner"], "mnote-web");
|
||||
assert_eq!(payload["userId"], "dev-user");
|
||||
assert_ne!(payload["code"], "legacy_next_compat_disabled");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -295,11 +295,7 @@ pub(crate) fn collect_filetree_render_rows(
|
||||
let selected_ids = active_document_id
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(|document_id| {
|
||||
[format!("doc:{document_id}"), format!("index:{document_id}")]
|
||||
.into_iter()
|
||||
.collect::<BTreeSet<_>>()
|
||||
})
|
||||
.map(|document_id| BTreeSet::from([format!("index:{document_id}")]))
|
||||
.unwrap_or_default();
|
||||
|
||||
projection
|
||||
@@ -497,10 +493,7 @@ fn build_tree_shell_renderer_input(
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(|document_id| {
|
||||
FileTreeSelectionState::from_selected(&[
|
||||
format!("doc:{document_id}"),
|
||||
format!("index:{document_id}"),
|
||||
])
|
||||
FileTreeSelectionState::from_selected(&[format!("index:{document_id}")])
|
||||
})
|
||||
.unwrap_or_default();
|
||||
TreeShellRendererInput::filetree(FileTreeRendererInput {
|
||||
@@ -1512,10 +1505,10 @@ fn build_tree_shell_html(
|
||||
let selectedFileTreeRowIds = new Set(
|
||||
rendererSelectedFileTreeRowIds.length > 0
|
||||
? rendererSelectedFileTreeRowIds
|
||||
: currentActiveDocumentId ? [`doc:${currentActiveDocumentId}`, `index:${currentActiveDocumentId}`] : []
|
||||
: currentActiveDocumentId ? [`index:${currentActiveDocumentId}`] : []
|
||||
);
|
||||
let fileTreeAnchorRowId = rendererAnchorRowId || (currentActiveDocumentId ? `doc:${currentActiveDocumentId}` : null);
|
||||
let fileTreeFocusedRowId = rendererFocusedRowId || (currentActiveDocumentId ? `doc:${currentActiveDocumentId}` : null);
|
||||
let fileTreeAnchorRowId = rendererAnchorRowId || (currentActiveDocumentId ? `index:${currentActiveDocumentId}` : null);
|
||||
let fileTreeFocusedRowId = rendererFocusedRowId || (currentActiveDocumentId ? `index:${currentActiveDocumentId}` : null);
|
||||
let visibleFileTreeRowIds = [];
|
||||
let draggingPageNodeId = "";
|
||||
let activePageDropNodeId = null;
|
||||
@@ -4964,7 +4957,12 @@ mod tests {
|
||||
assert!(filetree_html.contains("\"rendererInput\""));
|
||||
assert!(filetree_html.contains("\"mode\":\"fileTree\""));
|
||||
assert!(filetree_html.contains("\"filetreeSelection\""));
|
||||
assert!(filetree_html.contains("\"selectedRowIds\""));
|
||||
assert!(filetree_html.contains("\"selectedRowIds\":[\"index:page_root\"]"));
|
||||
assert!(!filetree_html.contains("\"selectedRowIds\":[\"doc:page_root\""));
|
||||
assert!(filetree_html.contains("\"focusedRowId\":\"index:page_root\""));
|
||||
assert!(filetree_html.contains("data-row-id=\"doc:page_root\""));
|
||||
assert!(filetree_html.contains("data-row-id=\"index:page_root\""));
|
||||
assert!(filetree_html.contains("data-row-id=\"index:page_root\" data-row-kind=\"index\""));
|
||||
assert!(filetree_html.contains("\"commandDispatcher\""));
|
||||
assert!(filetree_html.contains("\"runtimeArtifact\""));
|
||||
assert!(filetree_html.contains("\"contractName\":\"rust_tree_shell_runtime_artifact_v1\""));
|
||||
|
||||
@@ -41,6 +41,13 @@ pub struct DocumentShellQuery {
|
||||
pub workspace_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DocumentPageCompatQuery {
|
||||
pub document_id: String,
|
||||
pub workspace_id: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn document_page_shell(
|
||||
State(state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
@@ -82,6 +89,8 @@ pub async fn document_page_shell(
|
||||
let workspace_name = workspace_projection.workspace_name.clone();
|
||||
let page_subtree_json =
|
||||
serde_json::to_string(&aggregate.tree.page_subtree).unwrap_or_else(|_| "null".to_string());
|
||||
let page_options_json = serde_json::to_string(&aggregate.layout.page_options)
|
||||
.unwrap_or_else(|_| "null".to_string());
|
||||
let snapshot_json = serde_json::to_string(&aggregate).unwrap_or_else(|_| "null".to_string());
|
||||
let bootstrap_json = build_editor_bootstrap_json(&aggregate, &context);
|
||||
let body_content = crate::ssr::render_view(leptos::view! {
|
||||
@@ -93,6 +102,7 @@ pub async fn document_page_shell(
|
||||
workspace_name={workspace_name}
|
||||
workspace_sidebar_html={workspace_sidebar_html}
|
||||
page_subtree_json={page_subtree_json}
|
||||
page_options_json={page_options_json}
|
||||
/>
|
||||
});
|
||||
let html = format!(
|
||||
@@ -198,9 +208,9 @@ pub(crate) fn render_document_title_controller_script() -> &'static str {
|
||||
}
|
||||
if (!documentId) return;
|
||||
const escapedId = cssEscape(documentId);
|
||||
setText(`.tree-row[data-node-id="${escapedId}"] > .tree-link > .tree-link-title`, title);
|
||||
setText(`.tree-row[data-document-id="${escapedId}"] > .tree-link > .tree-link-title`, title);
|
||||
setText(`.tree-row[data-doc-id="${escapedId}"] > .tree-link > .tree-link-title`, title);
|
||||
const escapedDocRowId = cssEscape(`doc:${documentId}`);
|
||||
setText(`.tree-row[data-shell-mode="page"][data-node-id="${escapedId}"] > .tree-link > .tree-link-title`, title);
|
||||
setText(`.tree-row[data-shell-mode="filetree"][data-row-id="${escapedDocRowId}"] > .tree-link > .tree-link-title`, title);
|
||||
setText(`.wolai-page-row[data-node-id="${escapedId}"] > .wolai-row-title`, title);
|
||||
setText(`a[href="/documents/${escapedId}"] > .wolai-row-title`, title);
|
||||
setText(`a[href^="/documents/${escapedId}?"] > .wolai-row-title`, title);
|
||||
@@ -307,8 +317,13 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
|
||||
return '';
|
||||
};
|
||||
|
||||
const legacyBlockToTiptap = (block) => {
|
||||
const legacyBlockToTiptap = (block, index = 0) => {
|
||||
const type = typeof block?.type === 'string' ? block.type : 'paragraph';
|
||||
const blockId = typeof block?.id === 'string' && block.id.trim()
|
||||
? block.id.trim()
|
||||
: typeof block?.blockId === 'string' && block.blockId.trim()
|
||||
? block.blockId.trim()
|
||||
: `block-${index + 1}`;
|
||||
const text = flattenText(block?.content);
|
||||
const content = text ? [{ type: 'text', text }] : [];
|
||||
const textAlign = typeof block?.props?.textAlign === 'string'
|
||||
@@ -318,15 +333,16 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
|
||||
: undefined;
|
||||
const withTextAlign = (attrs = {}) => textAlign ? { ...attrs, textAlign } : attrs;
|
||||
const nestedChildren = Array.isArray(block?.children)
|
||||
? block.children.map(legacyBlockToTiptap).filter(Boolean)
|
||||
? block.children.map((child, childIndex) => legacyBlockToTiptap(child, childIndex)).filter(Boolean)
|
||||
: [];
|
||||
const withListChildren = (itemType, listType, attrs = {}) => ({
|
||||
type: listType,
|
||||
attrs: { blockId, ...attrs },
|
||||
content: [{
|
||||
type: itemType,
|
||||
attrs,
|
||||
attrs: { blockId },
|
||||
content: [
|
||||
{ type: 'paragraph', content },
|
||||
{ type: 'paragraph', attrs: { blockId }, content },
|
||||
...nestedChildren,
|
||||
],
|
||||
}],
|
||||
@@ -334,7 +350,7 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
|
||||
if (type === 'heading') {
|
||||
const level = Number(block?.props?.level || block?.level || 1) || 1;
|
||||
const collapsed = typeof block?.props?.collapsed === 'boolean' ? { collapsed: block.props.collapsed } : {};
|
||||
return { type: 'heading', attrs: withTextAlign({ level: Math.max(1, Math.min(6, level)), ...collapsed }), content };
|
||||
return { type: 'heading', attrs: withTextAlign({ blockId, level: Math.max(1, Math.min(6, level)), ...collapsed }), content };
|
||||
}
|
||||
if (type === 'bulletListItem' || type === 'bullet_list_item') {
|
||||
return withListChildren('listItem', 'bulletList');
|
||||
@@ -346,13 +362,13 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
|
||||
return withListChildren('taskItem', 'taskList', { checked: Boolean(block?.props?.checked) });
|
||||
}
|
||||
if (type === 'quote' || type === 'blockquote') {
|
||||
return { type: 'blockquote', attrs: withTextAlign(), content: [{ type: 'paragraph', attrs: withTextAlign(), content }] };
|
||||
return { type: 'blockquote', attrs: withTextAlign({ blockId }), content: [{ type: 'paragraph', attrs: withTextAlign({ blockId }), content }] };
|
||||
}
|
||||
if (type === 'codeBlock' || type === 'code_block') {
|
||||
return { type: 'codeBlock', attrs: withTextAlign({ language: block?.props?.language || null }), content };
|
||||
return { type: 'codeBlock', attrs: withTextAlign({ blockId, language: block?.props?.language || null }), content };
|
||||
}
|
||||
if (type === 'divider' || type === 'horizontalRule' || type === 'horizontal_rule') {
|
||||
return { type: 'horizontalRule' };
|
||||
return { type: 'horizontalRule', attrs: { blockId } };
|
||||
}
|
||||
if (type === 'table') {
|
||||
const tableSnapshot = block?.props?.tiptapTable;
|
||||
@@ -395,9 +411,9 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
|
||||
alt: block?.props?.alt || block?.alt || null,
|
||||
title: block?.props?.title || block?.title || null,
|
||||
};
|
||||
return attrs.src ? { type: 'image', attrs } : null;
|
||||
return attrs.src ? { type: 'image', attrs: { blockId, ...attrs } } : null;
|
||||
}
|
||||
return { type: 'paragraph', attrs: withTextAlign(), content };
|
||||
return { type: 'paragraph', attrs: withTextAlign({ blockId }), content };
|
||||
};
|
||||
|
||||
const textToTiptapDocument = (text) => ({
|
||||
@@ -436,6 +452,102 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
|
||||
return textToTiptapDocument(fallbackText);
|
||||
};
|
||||
|
||||
const inlineTextNodes = (node) => {
|
||||
if (!node || typeof node !== 'object') return [];
|
||||
if (Array.isArray(node.content)) {
|
||||
return node.content.flatMap((child) => {
|
||||
if (child?.type === 'text') {
|
||||
const text = typeof child.text === 'string' ? child.text : '';
|
||||
return text ? [{ type: 'text', text }] : [];
|
||||
}
|
||||
if (child?.type === 'hardBreak') {
|
||||
return [{ type: 'text', text: '\n' }];
|
||||
}
|
||||
return inlineTextNodes(child);
|
||||
});
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
||||
const firstChild = (node) => Array.isArray(node?.content) ? node.content[0] : null;
|
||||
const blockIdOf = (node, index) => {
|
||||
const raw = typeof node?.attrs?.blockId === 'string' ? node.attrs.blockId.trim() : '';
|
||||
return raw || `block-${index + 1}`;
|
||||
};
|
||||
|
||||
const tiptapNodeToEditorBlock = (node, index) => {
|
||||
const blockId = blockIdOf(node, index);
|
||||
if (node?.type === 'paragraph') {
|
||||
return { blockId, blockType: 'paragraph', props: {}, contentNodes: inlineTextNodes(node), childBlockIds: [] };
|
||||
}
|
||||
if (node?.type === 'heading') {
|
||||
const level = Math.max(1, Math.min(6, Number(node?.attrs?.level || 1) || 1));
|
||||
return { blockId, blockType: 'heading', props: { headingLevel: level }, contentNodes: inlineTextNodes(node), childBlockIds: [] };
|
||||
}
|
||||
if (node?.type === 'bulletList') {
|
||||
return { blockId, blockType: 'bullet_list_item', props: {}, contentNodes: inlineTextNodes(firstChild(firstChild(node))), childBlockIds: [] };
|
||||
}
|
||||
if (node?.type === 'orderedList') {
|
||||
return { blockId, blockType: 'numbered_list_item', props: {}, contentNodes: inlineTextNodes(firstChild(firstChild(node))), childBlockIds: [] };
|
||||
}
|
||||
if (node?.type === 'taskList') {
|
||||
const taskItem = firstChild(node);
|
||||
return { blockId, blockType: 'todo', props: { checked: Boolean(taskItem?.attrs?.checked) }, contentNodes: inlineTextNodes(firstChild(taskItem)), childBlockIds: [] };
|
||||
}
|
||||
if (node?.type === 'blockquote') {
|
||||
return { blockId, blockType: 'quote', props: {}, contentNodes: inlineTextNodes(firstChild(node)), childBlockIds: [] };
|
||||
}
|
||||
if (node?.type === 'codeBlock') {
|
||||
return { blockId, blockType: 'code_block', props: { language: typeof node?.attrs?.language === 'string' ? node.attrs.language : null }, contentNodes: inlineTextNodes(node), childBlockIds: [] };
|
||||
}
|
||||
if (node?.type === 'horizontalRule') {
|
||||
return { blockId, blockType: 'divider', props: {}, contentNodes: [], childBlockIds: [] };
|
||||
}
|
||||
if (node?.type === 'image') {
|
||||
return { blockId, blockType: 'image', props: { src: node?.attrs?.src || '', alt: node?.attrs?.alt || null, title: node?.attrs?.title || null, tiptapImage: node }, contentNodes: [], childBlockIds: [] };
|
||||
}
|
||||
if (node?.type === 'tocNode') {
|
||||
return { blockId, blockType: 'toc', props: { tiptapTocNode: node }, contentNodes: [], childBlockIds: [] };
|
||||
}
|
||||
if (node?.type === 'table') {
|
||||
return { blockId, blockType: 'table', props: { tiptapTable: node }, contentNodes: inlineTextNodes(node), childBlockIds: [] };
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const editorDocumentFromTiptapDocument = (tiptapDocument) => {
|
||||
const content = Array.isArray(tiptapDocument?.content) ? tiptapDocument.content : [];
|
||||
const blocks = content.map(tiptapNodeToEditorBlock).filter(Boolean);
|
||||
return {
|
||||
documentId: bootstrap.documentId,
|
||||
rootBlockIds: blocks.map((block) => block.blockId),
|
||||
blocks,
|
||||
};
|
||||
};
|
||||
|
||||
const legacyBlocksFromEditorDocument = (editorDocument) => (
|
||||
Array.isArray(editorDocument?.blocks) ? editorDocument.blocks : []
|
||||
).map((block) => ({
|
||||
id: block.blockId,
|
||||
type: block.blockType,
|
||||
props: block.blockType === 'heading'
|
||||
? { level: block.props?.headingLevel || 1 }
|
||||
: block.blockType === 'todo'
|
||||
? { checked: Boolean(block.props?.checked) }
|
||||
: block.blockType === 'code_block'
|
||||
? { language: block.props?.language || null }
|
||||
: block.blockType === 'image'
|
||||
? { ...(block.props || {}) }
|
||||
: block.blockType === 'toc'
|
||||
? { ...(block.props || {}) }
|
||||
: block.blockType === 'table'
|
||||
? { ...(block.props || {}) }
|
||||
: undefined,
|
||||
content: Array.isArray(block.contentNodes)
|
||||
? block.contentNodes.map((node) => typeof node?.text === 'string' ? node.text : '').join('')
|
||||
: '',
|
||||
}));
|
||||
|
||||
const pageBody = aggregate.body || {};
|
||||
const permissions = aggregate.head?.permissions || {};
|
||||
const conflictDetectionKey = typeof pageBody.conflictDetectionKey === 'string'
|
||||
@@ -502,6 +614,8 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
|
||||
setStatus('saved');
|
||||
return;
|
||||
}
|
||||
const editorDocument = editorDocumentFromTiptapDocument(tiptapDocument);
|
||||
const content = legacyBlocksFromEditorDocument(editorDocument);
|
||||
setStatus('saving');
|
||||
const response = await fetch(bootstrap.saveEndpoint || '/api/documents/save', {
|
||||
method: 'POST',
|
||||
@@ -511,9 +625,10 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
|
||||
workspaceId: bootstrap.workspaceId,
|
||||
revision: editorMeta.revision,
|
||||
conflictDetectionKey: editorMeta.conflictDetectionKey,
|
||||
content: [],
|
||||
editorDocument,
|
||||
content,
|
||||
tiptapDocument,
|
||||
blockCount: null,
|
||||
blockCount: editorDocument.blocks.length,
|
||||
}),
|
||||
});
|
||||
const result = await response.json().catch(() => null);
|
||||
@@ -526,6 +641,15 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
|
||||
if (typeof saved.conflict_detection_key === 'string') editorMeta.conflictDetectionKey = saved.conflict_detection_key;
|
||||
if (typeof saved.conflictDetectionKey === 'string') editorMeta.conflictDetectionKey = saved.conflictDetectionKey;
|
||||
lastSavedSerialized = serialized;
|
||||
if (typeof window.__mnoteRecordPageHistorySnapshot === 'function') {
|
||||
window.__mnoteRecordPageHistorySnapshot('save', {
|
||||
wordCount: content.filter((block) => typeof block?.content === 'string' && block.content.trim()).length,
|
||||
characterCount: currentEditorText().replace(/\s/g, '').length,
|
||||
blockCount: editorDocument.blocks.length,
|
||||
todoTotal: editorDocument.blocks.filter((block) => block.blockType === 'todo').length,
|
||||
todoDone: editorDocument.blocks.filter((block) => block.blockType === 'todo' && block.props?.checked).length,
|
||||
});
|
||||
}
|
||||
setStatus('saved');
|
||||
};
|
||||
|
||||
@@ -566,6 +690,9 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
|
||||
const mountId = runtime.mount(root, mountOptions);
|
||||
root.setAttribute('data-runtime-mount-id', String(mountId));
|
||||
root.setAttribute('data-editor-host-kind', 'leptos_tiptap_island');
|
||||
if (typeof window.__mnoteApplyPageOptionsToShell === 'function') {
|
||||
window.__mnoteApplyPageOptionsToShell();
|
||||
}
|
||||
setStatus('ready');
|
||||
};
|
||||
|
||||
@@ -668,6 +795,47 @@ pub async fn leptos_tiptap_asset(Path(asset_path): Path<String>) -> Result<Respo
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
pub async fn documents_page_compat(
|
||||
State(state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
Query(query): Query<DocumentPageCompatQuery>,
|
||||
) -> Result<Response, WebError> {
|
||||
let document_id = query.document_id.trim().to_string();
|
||||
if document_id.is_empty() {
|
||||
return Err(
|
||||
WebError::bad_request_code("document_id_required", "缺少有效 documentId")
|
||||
.with_context(&context),
|
||||
);
|
||||
}
|
||||
let aggregate = build_page_aggregate_snapshot(
|
||||
&state,
|
||||
&context,
|
||||
&document_id,
|
||||
query.workspace_id.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
let projection_owner = aggregate.source_label();
|
||||
let mut response = (
|
||||
StatusCode::OK,
|
||||
Json(json!({
|
||||
"ok": true,
|
||||
"owner": "mnote-web",
|
||||
"schema": "mnote.documents_page_compat.v1",
|
||||
"page": aggregate,
|
||||
"requestId": context.trace.request_id,
|
||||
"traceId": context.trace.trace_id,
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
stamp_shell_headers(response.headers_mut(), "documents-page-compat");
|
||||
if let Ok(name) = HeaderName::from_lowercase(b"x-mnote-page-aggregate-owner") {
|
||||
if let Ok(value) = HeaderValue::from_str(projection_owner) {
|
||||
response.headers_mut().insert(name, value);
|
||||
}
|
||||
}
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
pub async fn page_aggregate(
|
||||
State(state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
@@ -1059,9 +1227,13 @@ mod tests {
|
||||
assert!(html.contains("data-page-title-input=\"true\""));
|
||||
assert!(html.contains("data-title-endpoint=\"/api/documents/title\""));
|
||||
assert!(html.contains("mnote.document_title_controller.v1"));
|
||||
assert!(html
|
||||
.contains(".tree-row[data-node-id=\"${escapedId}\"] > .tree-link > .tree-link-title"));
|
||||
assert!(html.contains(
|
||||
r#".tree-row[data-shell-mode="page"][data-node-id="' + escaped + '"] > .tree-link > .tree-link-title"#
|
||||
));
|
||||
assert!(!html.contains("[data-node-id=\"${escapedId}\"] .tree-link-title"));
|
||||
assert!(html.contains("data-testid=\"wolai-page-settings-trigger\""));
|
||||
assert!(html.contains("data-mnote-action=\"open-page-settings\""));
|
||||
assert!(html.contains("data-mnote-action=\"open-page-ai\""));
|
||||
assert!(html.contains("\"titleEndpoint\":\"/api/documents/title\""));
|
||||
assert!(html.contains("__MNOTE_TREE_LIVE_BOOTSTRAP__"));
|
||||
assert!(html.contains("mnote.tree_live_bootstrap.v1"));
|
||||
|
||||
Reference in New Issue
Block a user