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(),
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user