Profilo utente (birthdate/sex/notes), kid agent, i18n, shared folders, UX
This commit is contained in:
@@ -401,6 +401,9 @@ async fn create_registry_tables(pool: &SqlitePool) -> Result<()> {
|
||||
password_hash BLOB,
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
locale TEXT,
|
||||
birthdate TEXT,
|
||||
sex TEXT,
|
||||
notes TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
CHECK (
|
||||
@@ -413,6 +416,12 @@ async fn create_registry_tables(pool: &SqlitePool) -> Result<()> {
|
||||
.await?;
|
||||
// Per-user UI locale override is additive — reaches an existing DB in place.
|
||||
ensure_column(pool, "users", "locale", "TEXT").await?;
|
||||
// Admin-managed directory profile fields (§0.1-neutral): `birthdate` is an
|
||||
// ISO YYYY-MM-DD date, `sex` free text, `notes` admin-authored. Rendered
|
||||
// into agent prompts by the `__USER_PROFILE__` substitution. Additive.
|
||||
ensure_column(pool, "users", "birthdate", "TEXT").await?;
|
||||
ensure_column(pool, "users", "sex", "TEXT").await?;
|
||||
ensure_column(pool, "users", "notes", "TEXT").await?;
|
||||
|
||||
// Shared on-disk folders (blueprint §6/§0.1): a named directory
|
||||
// `{WD}/shared/{folder_name}` bind-mounted into the container of each member.
|
||||
|
||||
@@ -36,12 +36,25 @@ pub struct FolderMember {
|
||||
pub can_write: bool,
|
||||
}
|
||||
|
||||
/// A shared folder as the agent sees it: path component, the caller's
|
||||
/// capability on it, who else it is shared with, and the admin-authored
|
||||
/// description. Rendered into the system prompt by the `<!-- SHARED_FOLDERS -->`
|
||||
/// directive.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct SharedFolderAccess {
|
||||
pub folder_name: String,
|
||||
pub can_write: bool,
|
||||
/// Names of the folder's *other* members (the caller excluded), joined by
|
||||
/// `", "` — empty when the caller is the sole member.
|
||||
pub shared_with: String,
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
// ── Reads ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Every shared folder a user belongs to, with their per-folder capability.
|
||||
/// Drives both the user's container mounts and the fs-tool `shared/{X}` routing.
|
||||
pub async fn list_for_user(pool: &SqlitePool, user_id: &str) -> Result<Vec<SharedMembership>> {
|
||||
let rows = sqlx::query_as::<_, (i64, String, i64)>(
|
||||
pub async fn list_for_user(pool: &SqlitePool, user_id: &str) -> Result<Vec<SharedMembership>> { let rows = sqlx::query_as::<_, (i64, String, i64)>(
|
||||
"SELECT f.id, f.folder_name, m.can_write
|
||||
FROM shared_folder_members m
|
||||
JOIN shared_folders f ON f.id = m.folder_id
|
||||
@@ -61,6 +74,42 @@ pub async fn list_for_user(pool: &SqlitePool, user_id: &str) -> Result<Vec<Share
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The folders a user belongs to, with capability, the other members' names,
|
||||
/// and description — the row set rendered by the `<!-- SHARED_FOLDERS -->`
|
||||
/// prompt directive. Same join as [`list_for_user`], plus the agent-facing
|
||||
/// columns. `shared_with` names the *other* members (display name when set,
|
||||
/// username otherwise) so the prompt can state exactly who sees what.
|
||||
pub async fn agent_view(pool: &SqlitePool, user_id: &str) -> Result<Vec<SharedFolderAccess>> {
|
||||
let rows = sqlx::query_as::<_, (String, i64, String, String)>(
|
||||
"SELECT f.folder_name, m.can_write,
|
||||
COALESCE((SELECT GROUP_CONCAT(name, ', ') FROM (
|
||||
SELECT COALESCE(NULLIF(u2.display_name, ''), u2.username) AS name
|
||||
FROM shared_folder_members m2
|
||||
JOIN users u2 ON u2.id = m2.user_id
|
||||
WHERE m2.folder_id = f.id AND m2.user_id != ?
|
||||
ORDER BY name
|
||||
)), '') AS shared_with,
|
||||
f.description
|
||||
FROM shared_folder_members m
|
||||
JOIN shared_folders f ON f.id = m.folder_id
|
||||
WHERE m.user_id = ?
|
||||
ORDER BY f.folder_name",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(user_id)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|(folder_name, can_write, shared_with, description)| SharedFolderAccess {
|
||||
folder_name,
|
||||
can_write: can_write != 0,
|
||||
shared_with,
|
||||
description,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub async fn list_all(pool: &SqlitePool) -> Result<Vec<SharedFolder>> {
|
||||
let rows = sqlx::query_as::<_, (i64, String, String, String)>(
|
||||
"SELECT id, folder_name, description, created_at FROM shared_folders ORDER BY folder_name",
|
||||
@@ -197,3 +246,75 @@ pub fn is_valid_folder_name(name: &str) -> bool {
|
||||
&& !name.contains('\\')
|
||||
&& !name.contains('\0')
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A registry-schema database in a throwaway temp dir (mirrors the
|
||||
/// `owner_pool` helper in `memory_docs::tests`).
|
||||
async fn registry_pool(tag: &str) -> (SqlitePool, PathBuf) {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
let n = SEQ.fetch_add(1, Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir()
|
||||
.join(format!("skald-sharedfolders-{}-{tag}-{n}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let pool = crate::db::init_system_pool(&dir.join("system.db").to_string_lossy())
|
||||
.await
|
||||
.unwrap();
|
||||
(pool, dir)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn agent_view_returns_capability_members_and_description() {
|
||||
let (pool, dir) = registry_pool("agent-view").await;
|
||||
|
||||
// `shared_folder_members.user_id` is a real FK and `tuned` turns FK
|
||||
// enforcement on, so members must exist (`admin` role is seeded).
|
||||
for (id, name, display) in
|
||||
[("u1", "alice", None), ("u2", "bob", Some("Bob")), ("u3", "carol", None)]
|
||||
{
|
||||
sqlx::query("INSERT INTO users (id, username, display_name, role_id, encrypted) VALUES (?, ?, ?, 'admin', 0)")
|
||||
.bind(id)
|
||||
.bind(name)
|
||||
.bind(display)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let recipes = create(&pool, "recipes", "Recipes and meal plans").await.unwrap();
|
||||
let photos = create(&pool, "photos", "").await.unwrap();
|
||||
add_member(&pool, recipes, "u1", true).await.unwrap();
|
||||
add_member(&pool, recipes, "u2", true).await.unwrap();
|
||||
add_member(&pool, recipes, "u3", false).await.unwrap();
|
||||
add_member(&pool, photos, "u1", false).await.unwrap();
|
||||
|
||||
let rows = agent_view(&pool, "u1").await.unwrap();
|
||||
assert_eq!(rows.len(), 2);
|
||||
// Ordered by folder_name: photos first. Other members named by display
|
||||
// name when set, username otherwise, in name order; caller excluded.
|
||||
assert_eq!(rows[0].folder_name, "photos");
|
||||
assert!(!rows[0].can_write);
|
||||
assert_eq!(rows[0].shared_with, "");
|
||||
assert_eq!(rows[0].description, "");
|
||||
assert_eq!(rows[1].folder_name, "recipes");
|
||||
assert!(rows[1].can_write);
|
||||
assert_eq!(rows[1].shared_with, "Bob, carol");
|
||||
assert_eq!(rows[1].description, "Recipes and meal plans");
|
||||
|
||||
// Bob's view of the same folder names the other side.
|
||||
let bob = agent_view(&pool, "u2").await.unwrap();
|
||||
assert_eq!(bob.len(), 1);
|
||||
assert_eq!(bob[0].shared_with, "alice, carol");
|
||||
|
||||
// A non-member sees nothing.
|
||||
assert!(agent_view(&pool, "nobody").await.unwrap().is_empty());
|
||||
|
||||
drop(pool);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,6 +67,12 @@ pub struct User {
|
||||
pub active: bool,
|
||||
/// UI locale override (NULL = follow the instance default).
|
||||
pub locale: Option<String>,
|
||||
/// Directory profile: ISO `YYYY-MM-DD` date of birth (NULL = unknown).
|
||||
pub birthdate: Option<String>,
|
||||
/// Directory profile: free-text sex (NULL = not specified).
|
||||
pub sex: Option<String>,
|
||||
/// Directory profile: admin-authored notes (NULL = none).
|
||||
pub notes: Option<String>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
@@ -81,6 +87,9 @@ pub struct UserSummary {
|
||||
pub encrypted: bool,
|
||||
pub active: bool,
|
||||
pub locale: Option<String>,
|
||||
pub birthdate: Option<String>,
|
||||
pub sex: Option<String>,
|
||||
pub notes: Option<String>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
@@ -99,6 +108,9 @@ impl User {
|
||||
encrypted: self.is_encrypted(),
|
||||
active: self.active,
|
||||
locale: self.locale.clone(),
|
||||
birthdate: self.birthdate.clone(),
|
||||
sex: self.sex.clone(),
|
||||
notes: self.notes.clone(),
|
||||
created_at: self.created_at.clone(),
|
||||
updated_at: self.updated_at.clone(),
|
||||
}
|
||||
@@ -145,6 +157,9 @@ struct Row {
|
||||
password_hash: Option<Vec<u8>>,
|
||||
active: bool,
|
||||
locale: Option<String>,
|
||||
birthdate: Option<String>,
|
||||
sex: Option<String>,
|
||||
notes: Option<String>,
|
||||
created_at: String,
|
||||
updated_at: String,
|
||||
}
|
||||
@@ -155,7 +170,8 @@ macro_rules! select {
|
||||
($tail:literal) => {
|
||||
concat!(
|
||||
"SELECT id, username, display_name, role_id, encrypted, kdf_params, kdf_salt, ",
|
||||
"database_password, password_hash, active, locale, created_at, updated_at FROM users ",
|
||||
"database_password, password_hash, active, locale, birthdate, sex, notes, ",
|
||||
"created_at, updated_at FROM users ",
|
||||
$tail
|
||||
)
|
||||
};
|
||||
@@ -191,6 +207,9 @@ impl TryFrom<Row> for User {
|
||||
credentials,
|
||||
active: r.active,
|
||||
locale: r.locale,
|
||||
birthdate: r.birthdate,
|
||||
sex: r.sex,
|
||||
notes: r.notes,
|
||||
created_at: r.created_at,
|
||||
updated_at: r.updated_at,
|
||||
})
|
||||
@@ -359,6 +378,34 @@ pub async fn update_profile(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Replaces the admin-managed directory profile fields in one statement:
|
||||
/// `birthdate` (ISO `YYYY-MM-DD`), free-text `sex`, admin-authored `notes`.
|
||||
/// Validation is the caller's job — this layer stays dumb.
|
||||
pub async fn set_directory_fields(
|
||||
pool: &SqlitePool,
|
||||
id: &str,
|
||||
birthdate: Option<&str>,
|
||||
sex: Option<&str>,
|
||||
notes: Option<&str>,
|
||||
) -> Result<()> {
|
||||
let n = sqlx::query(
|
||||
"UPDATE users
|
||||
SET birthdate = ?2, sex = ?3, notes = ?4, updated_at = datetime('now')
|
||||
WHERE id = ?1",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(birthdate)
|
||||
.bind(sex)
|
||||
.bind(notes)
|
||||
.execute(pool)
|
||||
.await?
|
||||
.rows_affected();
|
||||
if n == 0 {
|
||||
bail!("no such user: {id}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn rename(pool: &SqlitePool, id: &str, username: &str, display_name: Option<&str>) -> Result<()> {
|
||||
let n = sqlx::query(
|
||||
"UPDATE users SET username = ?2, display_name = ?3, updated_at = datetime('now')
|
||||
@@ -569,6 +616,41 @@ mod tests {
|
||||
cleanup(&path);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn set_directory_fields_round_trips() {
|
||||
let path = temp_db_path("users-profile");
|
||||
let pool = crate::db::init_system_pool(&path).await.unwrap();
|
||||
|
||||
insert(&pool, "u-1", "ada", None, "admin", &encrypted()).await.unwrap();
|
||||
let u = get(&pool, "u-1").await.unwrap().unwrap();
|
||||
assert!(u.birthdate.is_none() && u.sex.is_none() && u.notes.is_none());
|
||||
|
||||
set_directory_fields(&pool, "u-1", Some("2019-02-10"), Some("female"), Some("loves dinosaurs"))
|
||||
.await.unwrap();
|
||||
let u = get(&pool, "u-1").await.unwrap().unwrap();
|
||||
assert_eq!(u.birthdate.as_deref(), Some("2019-02-10"));
|
||||
assert_eq!(u.sex.as_deref(), Some("female"));
|
||||
assert_eq!(u.notes.as_deref(), Some("loves dinosaurs"));
|
||||
|
||||
// Clearing the fields writes NULLs back.
|
||||
set_directory_fields(&pool, "u-1", None, None, None).await.unwrap();
|
||||
let u = get(&pool, "u-1").await.unwrap().unwrap();
|
||||
assert!(u.birthdate.is_none() && u.sex.is_none() && u.notes.is_none());
|
||||
|
||||
// The summary projection carries the fields too.
|
||||
set_directory_fields(&pool, "u-1", Some("2019-02-10"), Some("female"), Some("notes"))
|
||||
.await.unwrap();
|
||||
let s = get(&pool, "u-1").await.unwrap().unwrap().summary();
|
||||
assert_eq!(s.birthdate.as_deref(), Some("2019-02-10"));
|
||||
assert_eq!(s.sex.as_deref(), Some("female"));
|
||||
assert_eq!(s.notes.as_deref(), Some("notes"));
|
||||
|
||||
assert!(set_directory_fields(&pool, "ghost", None, None, None).await.is_err(), "unknown id must fail");
|
||||
|
||||
pool.close().await;
|
||||
cleanup(&path);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn debug_never_prints_key_material() {
|
||||
let u = User {
|
||||
@@ -579,6 +661,9 @@ mod tests {
|
||||
credentials: encrypted(),
|
||||
active: true,
|
||||
locale: None,
|
||||
birthdate: None,
|
||||
sex: None,
|
||||
notes: None,
|
||||
created_at: "now".into(),
|
||||
updated_at: "now".into(),
|
||||
};
|
||||
|
||||
@@ -18,6 +18,42 @@ pub fn is_supported(locale: &str) -> bool {
|
||||
SUPPORTED_LOCALES.contains(&locale)
|
||||
}
|
||||
|
||||
/// The instance default locale (registry `config.ui_locale`), `"en"` when
|
||||
/// unset. A read — no system bus involved — so it works from any context that
|
||||
/// has a pool (sessions, shells), not just where a `GlobalConfigManager`
|
||||
/// lives. An unreadable config table degrades to `"en"` rather than failing
|
||||
/// the caller.
|
||||
pub async fn default_locale(pool: &sqlx::SqlitePool) -> String {
|
||||
crate::db::config::get(pool, DEFAULT_LOCALE_KEY)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.unwrap_or_else(|| "en".into())
|
||||
}
|
||||
|
||||
/// The effective locale for a user: their `users.locale` override when set,
|
||||
/// the instance default otherwise (which itself falls back to `"en"`).
|
||||
/// **The** resolution chain — call this instead of re-implementing it.
|
||||
pub async fn resolve_locale(pool: &sqlx::SqlitePool, user_locale: Option<&str>) -> String {
|
||||
match user_locale.map(str::trim).filter(|s| !s.is_empty()) {
|
||||
Some(l) => l.to_string(),
|
||||
None => default_locale(pool).await,
|
||||
}
|
||||
}
|
||||
|
||||
/// Human language name for prompt rendering (`"it"` → `"Italian"`). Unknown
|
||||
/// codes pass through unchanged — the model copes, and this list need not
|
||||
/// track every locale ever stored.
|
||||
pub fn language_name(locale: &str) -> String {
|
||||
match locale {
|
||||
"en" => "English".into(),
|
||||
"it" => "Italian".into(),
|
||||
"fr" => "French".into(),
|
||||
other => other.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the instance default locale straight to the registry `config` table.
|
||||
/// Used by first-run provisioning shells (e.g. `skald-setup`), where no
|
||||
/// `GlobalConfigManager` — hence no system bus — exists. A running server
|
||||
@@ -53,3 +89,53 @@ pub fn config_set() -> ConfigSet {
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_db_path(tag: &str) -> String {
|
||||
let mut p = std::env::temp_dir();
|
||||
let nanos = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
||||
p.push(format!("skald-test-i18n-{tag}-{}-{nanos}", std::process::id()));
|
||||
p.push("database");
|
||||
p.push("system.db");
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn cleanup(path: &str) {
|
||||
if let Some(dir) = std::path::Path::new(path).parent().and_then(|p| p.parent()) {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_name_maps_known_codes_and_passes_through_unknown() {
|
||||
assert_eq!(language_name("en"), "English");
|
||||
assert_eq!(language_name("it"), "Italian");
|
||||
assert_eq!(language_name("fr"), "French");
|
||||
assert_eq!(language_name("de"), "de");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resolve_locale_follows_user_then_instance_then_builtin() {
|
||||
let path = temp_db_path("resolve");
|
||||
let pool = crate::db::init_system_pool(&path).await.unwrap();
|
||||
|
||||
// No override, no instance default → built-in English.
|
||||
assert_eq!(resolve_locale(&pool, None).await, "en");
|
||||
assert_eq!(default_locale(&pool).await, "en");
|
||||
|
||||
// Instance default kicks in when the user has no override.
|
||||
set_default_locale(&pool, "it").await.unwrap();
|
||||
assert_eq!(resolve_locale(&pool, None).await, "it");
|
||||
assert_eq!(resolve_locale(&pool, Some(" ")).await, "it", "blank override counts as none");
|
||||
|
||||
// The user override always wins.
|
||||
assert_eq!(resolve_locale(&pool, Some("fr")).await, "fr");
|
||||
|
||||
pool.close().await;
|
||||
cleanup(&path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +37,10 @@ pub struct MessageBuilder {
|
||||
/// The shared (`system.db`) pool, for injecting `shared-memory/` notes. The
|
||||
/// owner `pool` above backs `user-memory/`.
|
||||
pub shared_pool: Arc<SqlitePool>,
|
||||
/// The authenticated user who owns this session — drives per-user prompt
|
||||
/// sections like the `__SHARED_FOLDERS__` table (registry read on
|
||||
/// `shared_pool`).
|
||||
pub user_id: String,
|
||||
pub session_id: i64,
|
||||
pub mcp: Arc<dyn McpProvider>,
|
||||
pub datetime_config: DatetimeConfig,
|
||||
@@ -139,6 +143,20 @@ impl MessageBuilder {
|
||||
);
|
||||
}
|
||||
|
||||
if static_content.contains("__SHARED_FOLDERS__") {
|
||||
static_content = static_content.replace(
|
||||
"__SHARED_FOLDERS__",
|
||||
&self.render_shared_folders().await?,
|
||||
);
|
||||
}
|
||||
|
||||
if static_content.contains("__USER_PROFILE__") {
|
||||
static_content = static_content.replace(
|
||||
"__USER_PROFILE__",
|
||||
&self.render_user_profile().await?,
|
||||
);
|
||||
}
|
||||
|
||||
for (key, value) in system_substitutions {
|
||||
let sentinel = format!("__{key}__");
|
||||
if static_content.contains(sentinel.as_str()) {
|
||||
@@ -476,6 +494,33 @@ impl MessageBuilder {
|
||||
(abs, display)
|
||||
}
|
||||
|
||||
/// Builds the shared-folders table that replaces the `__SHARED_FOLDERS__`
|
||||
/// sentinel: the folders the session's user belongs to, with their access
|
||||
/// level and the admin-authored description (registry tables on
|
||||
/// `shared_pool`).
|
||||
async fn render_shared_folders(&self) -> anyhow::Result<String> {
|
||||
let rows = crate::db::shared_folders::agent_view(&self.shared_pool, &self.user_id).await?;
|
||||
Ok(render_shared_folders_table(&rows))
|
||||
}
|
||||
|
||||
/// Builds the user-profile block that replaces the `__USER_PROFILE__`
|
||||
/// sentinel: the session owner's admin-managed directory fields (registry
|
||||
/// `users` row on `shared_pool`), with the age computed at build time and
|
||||
/// the preferred language resolved through the standard chain
|
||||
/// (`users.locale` → instance default → English).
|
||||
async fn render_user_profile(&self) -> anyhow::Result<String> {
|
||||
let user = crate::db::users::get(&self.shared_pool, &self.user_id).await?;
|
||||
let locale = crate::i18n::resolve_locale(
|
||||
&self.shared_pool,
|
||||
user.as_ref().and_then(|u| u.locale.as_deref()),
|
||||
).await;
|
||||
Ok(render_user_profile_block(
|
||||
user.as_ref(),
|
||||
&locale,
|
||||
chrono::Utc::now().date_naive(),
|
||||
))
|
||||
}
|
||||
|
||||
fn render_mcp_list(&self, active_mcp_grants: &HashSet<String>) -> String {
|
||||
let all_servers: std::collections::BTreeSet<String> = self.mcp.tools()
|
||||
.into_iter()
|
||||
@@ -521,6 +566,71 @@ impl MessageBuilder {
|
||||
|
||||
// ── Free helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
/// Renders the shared-folders section body as a Markdown table — one row per
|
||||
/// folder the user belongs to, naming the folder's other members so the model
|
||||
/// knows exactly who sees what is written there. An empty membership yields an
|
||||
/// explicit "not a member" line so the model does not go probing `shared/` paths.
|
||||
fn render_shared_folders_table(rows: &[crate::db::shared_folders::SharedFolderAccess]) -> String {
|
||||
/// A free-text cell: single line, pipes escaped (they would split the table).
|
||||
fn cell(s: &str) -> String {
|
||||
s.trim().replace('|', "\\|").replace('\n', " ")
|
||||
}
|
||||
if rows.is_empty() {
|
||||
return "_You are not a member of any shared folder._\n".to_string();
|
||||
}
|
||||
let mut out = String::from("| Path | Access | Shared with | Description |\n|------|--------|-------------|-------------|\n");
|
||||
for r in rows {
|
||||
let access = if r.can_write { "read-write" } else { "read-only" };
|
||||
let shared_with = if r.shared_with.is_empty() { "—".to_string() } else { cell(&r.shared_with) };
|
||||
let desc = if r.description.trim().is_empty() { "—".to_string() } else { cell(&r.description) };
|
||||
out.push_str(&format!("| `shared/{}` | {access} | {shared_with} | {desc} |\n", r.folder_name));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Renders the profile block for `__USER_PROFILE__`. Every line is always
|
||||
/// present — an explicit `unknown` / `not specified` is a signal the agent can
|
||||
/// act on (e.g. gently ask) — except `Notes`, omitted entirely when empty.
|
||||
/// `today` is passed in so the age computation stays pure and testable.
|
||||
fn render_user_profile_block(
|
||||
user: Option<&crate::db::users::User>,
|
||||
locale: &str,
|
||||
today: chrono::NaiveDate,
|
||||
) -> String {
|
||||
let name = user
|
||||
.and_then(|u| non_empty(&u.display_name))
|
||||
.or_else(|| user.map(|u| u.username.as_str()))
|
||||
.unwrap_or("unknown");
|
||||
|
||||
let birth = match user.and_then(|u| non_empty(&u.birthdate)) {
|
||||
Some(raw) => match chrono::NaiveDate::parse_from_str(raw, "%Y-%m-%d") {
|
||||
Ok(dob) => match today.years_since(dob) {
|
||||
Some(age) => format!("{raw} (age {age})"),
|
||||
None => format!("{raw} (age unknown)"),
|
||||
},
|
||||
// Stored value bypassed validation — show it raw rather than drop it.
|
||||
Err(_) => raw.to_string(),
|
||||
},
|
||||
None => "unknown".to_string(),
|
||||
};
|
||||
|
||||
let sex = user.and_then(|u| non_empty(&u.sex)).unwrap_or("not specified");
|
||||
|
||||
let mut out = format!(
|
||||
"Name: {name}\nDate of birth: {birth}\nSex: {sex}\nPreferred language: {}\n",
|
||||
crate::i18n::language_name(locale),
|
||||
);
|
||||
if let Some(notes) = user.and_then(|u| non_empty(&u.notes)) {
|
||||
out.push_str(&format!("Notes: {notes}\n"));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An optional string field as a trimmed `&str`, `None` when empty/blank.
|
||||
fn non_empty(s: &Option<String>) -> Option<&str> {
|
||||
s.as_deref().map(str::trim).filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
/// Appends one user/agent chunk — text plus any inline media parts — to the
|
||||
/// message stream, coalescing with a preceding `user` message. Plain-text
|
||||
/// chunks merge exactly as before (one string); when either side carries
|
||||
@@ -670,10 +780,118 @@ fn summarize_tool_result(tool_name: &str, arguments: Option<&str>, result: &str)
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shared_folders_table_renders_access_and_description() {
|
||||
use crate::db::shared_folders::SharedFolderAccess;
|
||||
let rows = vec![
|
||||
SharedFolderAccess { folder_name: "photos".into(), can_write: false, shared_with: "Bob, Carol".into(), description: "Shared photo archive".into() },
|
||||
SharedFolderAccess { folder_name: "recipes".into(), can_write: true, shared_with: "".into(), description: "a | b\nc".into() },
|
||||
];
|
||||
let out = render_shared_folders_table(&rows);
|
||||
assert!(out.starts_with("| Path | Access | Shared with | Description |\n|------|--------|-------------|-------------|\n"));
|
||||
assert!(out.contains("| `shared/photos` | read-only | Bob, Carol | Shared photo archive |\n"));
|
||||
// Empty shared_with → "—"; free-text cells stay on one line with escaped pipes.
|
||||
assert!(out.contains("| `shared/recipes` | read-write | — | a \\| b c |\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_folders_table_empty_membership_is_explicit() {
|
||||
assert_eq!(
|
||||
render_shared_folders_table(&[]),
|
||||
"_You are not a member of any shared folder._\n"
|
||||
);
|
||||
}
|
||||
|
||||
fn img() -> Value {
|
||||
json!({ "type": "image_url", "image_url": { "url": "data:image/png;base64,QUJD" } })
|
||||
}
|
||||
|
||||
fn test_user() -> crate::db::users::User {
|
||||
crate::db::users::User {
|
||||
id: "u-1".into(),
|
||||
username: "luca".into(),
|
||||
display_name: None,
|
||||
role_id: "members".into(),
|
||||
credentials: crate::db::users::Credentials::Cleartext(None),
|
||||
active: true,
|
||||
locale: None,
|
||||
birthdate: None,
|
||||
sex: None,
|
||||
notes: None,
|
||||
created_at: "now".into(),
|
||||
updated_at: "now".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_profile_renders_all_fields_with_runtime_age() {
|
||||
let mut u = test_user();
|
||||
u.display_name = Some("Luca Rossi".into());
|
||||
u.birthdate = Some("2019-02-10".into());
|
||||
u.sex = Some("male".into());
|
||||
u.notes = Some("loves dinosaurs".into());
|
||||
let today = chrono::NaiveDate::from_ymd_opt(2026, 7, 18).unwrap();
|
||||
|
||||
let out = render_user_profile_block(Some(&u), "it", today);
|
||||
assert_eq!(
|
||||
out,
|
||||
"Name: Luca Rossi\n\
|
||||
Date of birth: 2019-02-10 (age 7)\n\
|
||||
Sex: male\n\
|
||||
Preferred language: Italian\n\
|
||||
Notes: loves dinosaurs\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_profile_age_counts_uncelebrated_birthdays() {
|
||||
let mut u = test_user();
|
||||
u.birthdate = Some("2019-12-25".into());
|
||||
let today = chrono::NaiveDate::from_ymd_opt(2026, 7, 18).unwrap();
|
||||
let out = render_user_profile_block(Some(&u), "en", today);
|
||||
assert!(out.contains("Date of birth: 2019-12-25 (age 6)\n"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_profile_empty_fields_are_explicit_and_notes_omitted() {
|
||||
let u = test_user();
|
||||
let today = chrono::NaiveDate::from_ymd_opt(2026, 7, 18).unwrap();
|
||||
let out = render_user_profile_block(Some(&u), "en", today);
|
||||
assert_eq!(
|
||||
out,
|
||||
"Name: luca\n\
|
||||
Date of birth: unknown\n\
|
||||
Sex: not specified\n\
|
||||
Preferred language: English\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_profile_tolerates_garbage_and_future_dates() {
|
||||
let mut u = test_user();
|
||||
u.birthdate = Some("not-a-date".into());
|
||||
let today = chrono::NaiveDate::from_ymd_opt(2026, 7, 18).unwrap();
|
||||
let out = render_user_profile_block(Some(&u), "en", today);
|
||||
assert!(out.contains("Date of birth: not-a-date\n"), "{out}");
|
||||
|
||||
u.birthdate = Some("2099-01-01".into());
|
||||
let out = render_user_profile_block(Some(&u), "en", today);
|
||||
assert!(out.contains("Date of birth: 2099-01-01 (age unknown)\n"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_profile_missing_user_still_renders_language() {
|
||||
let today = chrono::NaiveDate::from_ymd_opt(2026, 7, 18).unwrap();
|
||||
let out = render_user_profile_block(None, "fr", today);
|
||||
assert_eq!(
|
||||
out,
|
||||
"Name: unknown\n\
|
||||
Date of birth: unknown\n\
|
||||
Sex: not specified\n\
|
||||
Preferred language: French\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_text_chunks_merge_as_string() {
|
||||
let mut out = vec![];
|
||||
|
||||
@@ -30,6 +30,7 @@ impl ChatSessionHandler {
|
||||
let builder = MessageBuilder {
|
||||
pool: Arc::clone(&self.db),
|
||||
shared_pool: Arc::clone(&self.shared_pool),
|
||||
user_id: self.user_id.clone(),
|
||||
session_id: self.scratchpad_sid(),
|
||||
mcp: Arc::clone(&self.mcp),
|
||||
datetime_config: self.datetime_config.clone(),
|
||||
|
||||
Reference in New Issue
Block a user