Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(web): make the server-rendered browser subpath-aware via <base href>
Djalma Júniora123f9040d70
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 0f960dd7..99088905 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -948,17 +948,38 @@ fn mount_web_router(};}- let web_router = ai_memory_web::router(reader, wiki);- info!(mount, "read-only wiki browser mounted");+ // The built-in server-rendered browser emits RELATIVE asset/link URLs+ // (`static/…`, `w/…`, `search`, `.`). Inject a `<base href>` into every+ // HTML response so they resolve under `{base_path}{web_slug}/` — the same+ // anchoring the custom SPA gets via its injected index. Default (`/web/`)+ // is byte-equivalent to the previous absolute `/web/…` links.+ let web_router = ai_memory_web::router(reader, wiki).layer(+ axum::middleware::from_fn_with_state(+ Arc::new(base_href.to_string()),+ inject_web_base_href,+ ),+ );+ info!(mount, base_href, "read-only wiki browser mounted");if slug.is_empty() {router.merge(web_router)} else {- let redirect_to = slug.clone();+ // Strip-trailing-slash redirect. The target must carry the full+ // external prefix (`{base_path}{slug}`), because the surrounding+ // `nest(&base_path, …)` does NOT rewrite Location headers. Derive it+ // from base_href (which already folds in base_path + slug).+ let canonical = {+ let trimmed = base_href.trim_end_matches('/');+ if trimmed.is_empty() {+ "/".to_string()+ } else {+ trimmed.to_string()+ }+ };router.route(&format!("{slug}/"),axum::routing::get(move || {- let to = redirect_to.clone();+ let to = canonical.clone();async move { axum::response::Redirect::permanent(&to) }}),)@@ -966,6 +987,43 @@ fn mount_web_router(}}+/// Response middleware: inject `<base href>` into `text/html` responses from+/// the built-in server-rendered web browser, so its relative URLs resolve+/// under the configured `{base_path}{web_slug}` prefix. Non-HTML responses+/// (static assets, redirects) pass through untouched.+async fn inject_web_base_href(+ State(base_href): State<Arc<String>>,+ req: Request<Body>,+ next: Next,+) -> Response {+ let resp = next.run(req).await;+ let is_html = resp+ .headers()+ .get(header::CONTENT_TYPE)+ .and_then(|v| v.to_str().ok())+ .is_some_and(|ct| ct.starts_with("text/html"));+ if !is_html {+ return resp;+ }+ let (mut parts, body) = resp.into_parts();+ let bytes = match axum::body::to_bytes(body, usize::MAX).await {+ Ok(b) => b,+ Err(_) => {+ return (StatusCode::INTERNAL_SERVER_ERROR, "response body read error\n")+ .into_response();+ }+ };+ match std::str::from_utf8(&bytes) {+ Ok(html) => {+ let injected = inject_base_href(html, &base_href);+ // Stale length from the pre-injection body; let hyper recompute.+ parts.headers.remove(header::CONTENT_LENGTH);+ Response::from_parts(parts, Body::from(injected))+ }+ Err(_) => Response::from_parts(parts, Body::from(bytes)),+ }+}+fn apply_http_layers(router: axum::Router,auth_state: Arc<AuthState>,diff --git a/crates/ai-memory-web/src/templates.rs b/crates/ai-memory-web/src/templates.rsindex a39af327..f0718bfc 100644--- a/crates/ai-memory-web/src/templates.rs+++ b/crates/ai-memory-web/src/templates.rs@@ -6,14 +6,16 @@ use askama::Template;// URL helpers// ----------------------------------------------------------------------------/// Build a `/web` project URL with path segments percent-encoded.+/// Build a project URL with path segments percent-encoded.+///+/// The URL is **relative** (`w/{ws}/{proj}`, no leading slash) so it+/// resolves against the page's injected `<base href>` — which the server+/// sets to `{base_path}{web_slug}/`. That keeps every link correct whether+/// the browser is served at the host root (`/web/…`) or under a reverse-proxy+/// subpath (`/wiki/web/…`), without the templates knowing the prefix.#[must_use]pub(crate) fn project_href(workspace: &str, project: &str) -> String {- format!(- "/web/w/{}/{}",- encode_segment(workspace),- encode_segment(project)- )+ format!("w/{}/{}", encode_segment(workspace), encode_segment(project))}/// Build a `/web` page URL with workspace/project/path percent-encoded.@@ -102,7 +104,7 @@ pub(crate) struct ProjectCard {pub page_count: u64,/// Humanised timestamp (e.g. "3 hours ago"), or empty string.pub last_updated_relative: String,- /// Link target (`/web/w/{ws}/{proj}`).+ /// Link target (`w/{ws}/{proj}`, relative to `<base href>`).pub href: String,}@@ -249,13 +251,15 @@ mod tests {#[test]fn href_helpers_percent_encode_segments() {+ // Relative (no leading slash) so they resolve against the injected+ // `<base href>` — see `project_href` docs.assert_eq!(project_href("default space", "proj#one"),- "/web/w/default%20space/proj%23one"+ "w/default%20space/proj%23one");assert_eq!(page_href("default", "scratch", "notes/a b%25.md"),- "/web/w/default/scratch/p/notes/a%20b%2525.md"+ "w/default/scratch/p/notes/a%20b%2525.md");}}diff --git a/crates/ai-memory-web/templates/base.html b/crates/ai-memory-web/templates/base.htmlindex 231b29bf..db5c31d0 100644--- a/crates/ai-memory-web/templates/base.html+++ b/crates/ai-memory-web/templates/base.html@@ -4,20 +4,20 @@<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{% block title %}ai-memory{% endblock %}</title>- <link rel="stylesheet" href="/web/static/tailwind.css">+ <link rel="stylesheet" href="static/tailwind.css"></head><body class="min-h-full bg-white text-slate-900 dark:bg-slate-950 dark:text-slate-100"><header class="border-b border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-950 sticky top-0 z-10"><div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex items-center gap-4 h-14">- <a href="/web/" class="flex items-center gap-2 shrink-0">+ <a href="." class="flex items-center gap-2 shrink-0"><picture>- <source media="(prefers-color-scheme: dark)" srcset="/web/static/logo-dark.png">- <img src="/web/static/logo.png" alt="ai-memory logo" class="h-7 w-auto">+ <source media="(prefers-color-scheme: dark)" srcset="static/logo-dark.png">+ <img src="static/logo.png" alt="ai-memory logo" class="h-7 w-auto"></picture><span class="font-semibold text-slate-800 dark:text-slate-100 text-sm hidden sm:inline">ai-memory</span></a><div class="flex-1"></div>- <form action="/web/search" method="get" class="flex items-center">+ <form action="search" method="get" class="flex items-center"><inputname="q"type="search"diff --git a/crates/ai-memory-web/templates/not_found.html b/crates/ai-memory-web/templates/not_found.htmlindex 9829769e..8197930a 100644--- a/crates/ai-memory-web/templates/not_found.html+++ b/crates/ai-memory-web/templates/not_found.html@@ -7,7 +7,7 @@<p class="text-6xl font-bold text-slate-200 dark:text-slate-800">404</p><h1 class="mt-4 text-2xl font-semibold text-slate-700 dark:text-slate-300">Page not found</h1><p class="mt-2 text-sm text-slate-500 dark:text-slate-400">The page you're looking for doesn't exist or has been superseded.</p>- <a href="/web/" class="mt-6 inline-block rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700">+ <a href="." class="mt-6 inline-block rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700">Back to home</a></div>diff --git a/crates/ai-memory-web/templates/page.html b/crates/ai-memory-web/templates/page.htmlindex 9d4691d9..a727c164 100644--- a/crates/ai-memory-web/templates/page.html+++ b/crates/ai-memory-web/templates/page.html@@ -4,7 +4,7 @@{% block content %}<nav class="mb-6 flex items-center gap-1 text-sm text-slate-500 dark:text-slate-400">- <a href="/web/" class="hover:text-blue-600 dark:hover:text-blue-400">home</a>+ <a href="." class="hover:text-blue-600 dark:hover:text-blue-400">home</a><span>/</span><a href="{{ project_href }}" class="hover:text-blue-600 dark:hover:text-blue-400">{{ workspace }}/{{ project }}</a><span>/</span>diff --git a/crates/ai-memory-web/templates/project.html b/crates/ai-memory-web/templates/project.htmlindex 6a670c8f..86a44179 100644--- a/crates/ai-memory-web/templates/project.html+++ b/crates/ai-memory-web/templates/project.html@@ -4,7 +4,7 @@{% block content %}<nav class="mb-6 flex items-center gap-1 text-sm text-slate-500 dark:text-slate-400">- <a href="/web/" class="hover:text-blue-600 dark:hover:text-blue-400">home</a>+ <a href="." class="hover:text-blue-600 dark:hover:text-blue-400">home</a><span>/</span><span class="text-slate-400 dark:text-slate-500">{{ workspace }}</span><span>/</span>diff --git a/crates/ai-memory-web/templates/search.html b/crates/ai-memory-web/templates/search.htmlindex 31afddfa..b2576faf 100644--- a/crates/ai-memory-web/templates/search.html+++ b/crates/ai-memory-web/templates/search.html@@ -13,7 +13,7 @@</h1></div>-<form action="/web/search" method="get" class="mb-8 flex gap-2">+<form action="search" method="get" class="mb-8 flex gap-2"><inputname="q"type="search"diff --git a/crates/ai-memory-web/tests/routes.rs b/crates/ai-memory-web/tests/routes.rsindex 77f40604..78d227b5 100644--- a/crates/ai-memory-web/tests/routes.rs+++ b/crates/ai-memory-web/tests/routes.rs@@ -369,9 +369,11 @@ async fn web_links_percent_encode_route_segments() {.await.unwrap();let text = std::str::from_utf8(&body).unwrap();+ // Links are now relative (no leading `/web/`) so they resolve against the+ // `<base href>` the server injects per the configured prefix.assert!(- text.contains("/web/w/default/scratch%20%231/p/notes/a%20b%2525.md"),- "expected encoded href in project response: {text}"+ text.contains("\"w/default/scratch%20%231/p/notes/a%20b%2525.md\""),+ "expected encoded relative href in project response: {text}");}