feat(claw): show the user's profile in the bottom-left account
android / debug (push) Successful in 2m26s
android / release (push) Successful in 2m19s
ci / checks (push) Successful in 3m48s
ci / test (push) Successful in 1m24s
ci / chart (push) Successful in 7s
ci / docker (push) Successful in 2m11s
ci / web (push) Successful in 15s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 2m17s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 16s
ci / publish-edge-chart (push) Successful in 4s

The web shell's account showed the agent's identity and the word
"connected", which left no way to see or set the human's own name and
picture.

The claw now stores a user profile beside the bootstrap files and
serves it over /v1/user and /v1/user/avatar. The agent sets it during
onboarding with user_profile_set; the bottom-left account in both
sidebars renders it and opens an editor for the name and picture. The
prompt context exposes user_name and user_profile, and bootstrap
documents resolve {{ user_name }}, so USER.md and the other markdown
files can address the user by name.

The connection state stays with the unreachable banner, so the sidebars
no longer report it.

Unit and HTTP tests cover the profile store, the tool, the variable
expansion, and the routes. fmt, clippy, cargo test, nuxt typecheck, and
nuxt build pass; both sidebars and the editor checked at 1280x800.
This commit is contained in:
vhaudiquet committed 2026-12-01 18:30:50 +01:00
1 parent debc21a89f
commit cb1948742f
17 files changed
+1226 -149

No files matched your search

+6
View File
@@ -14,4 +14,10 @@ An avatar only if the user hands you an image file; they can also
upload one in the web interface's settings, and saying so beats
hunting one down. Never invent facts the user did not give.
Set the user's own profile with the user_profile_set tool: their
display name, and an avatar only from a picture they hand you. It
drives the account in the interface's bottom-left corner, and
`{{ user_name }}` in USER.md and other documents renders that name.
They can also edit it themselves by clicking that account.
When both files exist, say setup is done and stop offering.
+18 -5
View File
@@ -181,6 +181,11 @@ GET /v1/watches POST /v1/watches DELETE /v1/watches/{for
GET /v1/bootstrap {"soul": bool, "user": bool}
GET /v1/bootstrap/files SOUL.md, USER.md, ENVIRONMENT.md + onboarding status
PUT /v1/bootstrap/{kind} {"content"} — save soul or user; environment is refused
GET /v1/user {"name", "avatar"} — the human's profile
PUT /v1/user {"name"} — set the name; an empty string clears it, absent keeps it
GET /v1/user/avatar the profile picture's bytes
PUT /v1/user/avatar raw image body, content type from the header (png, jpeg, gif, webp)
DELETE /v1/user/avatar drop the picture
POST /v1/ingest {"source","key","payload"} -> 202
GET /v1/notifications?device=&since= POST /v1/notifications/{id}/ack
GET /v1/consents the asks a turn is waiting on
@@ -209,8 +214,14 @@ three identity files under the state dir's `bootstrap/` (config:
written with you; **USER.md**, the always-visible summary of who you
are; **ENVIRONMENT.md**, host, shell, and tool inventory, generated
deterministically at every boot (detection is code, not conversation;
hand edits are overwritten). The base renders the dispatch's own tool
roster too — every tool's name, description, and call schema, straight
hand edits are overwritten). Beside them, `user.json` holds the
human's profile: the display name and avatar the web interface shows in
its bottom-left account, served over `/v1/user`. The prompt context
carries `user_name` (and `user_profile`, with `name` and `avatar`), and
a bootstrap document may spell `{{ user_name }}` anywhere to insert the
name; an unset name leaves the token in place. The base renders the
dispatch's own tool roster too — every tool's name, description, and
call schema, straight
from the resolver chain, so what the prompt lists is what the request
advertises. On first run the claw *offers* a short
setup in chat: who you are, what the machine is for, who it should be.
@@ -219,9 +230,11 @@ tool as you answer, and — through the `identity_set` tool — sets its
own presentation the same way: its name, a mark or tagline, an avatar
from an image you hand it. The same tool is yours to invoke any time
("call yourself something else"); it is the same store the settings
pages write, so what it sets is what every client renders. Decline
and it simply keeps offering, never
interrogating. Both files stay hand-editable forever; `/v1/bootstrap`
pages write, so what it sets is what every client renders. It records
your profile with `user_profile_set`: the name and picture in the
interface's bottom-left account. Click that account to set them
yourself. Decline and it simply keeps offering, never interrogating.
Both files stay hand-editable forever; `/v1/bootstrap`
lets a UI badge setup state, and the Bootstrap settings page edits
SOUL.md and USER.md in place. ENVIRONMENT.md stays read-only there:
the boot pass overwrites it.
+467 -26
View File
@@ -30,6 +30,7 @@ use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_core::ToolSpec;
use rhema_prompt::render_template;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
/// The built-in system prompt, kept as data next to the code and read
@@ -43,6 +44,19 @@ pub const MAX_CONTENT_BYTES: usize = 16 * 1024;
/// The save tool's name — allowlists reference it.
pub const BOOTSTRAP_SAVE: &str = "bootstrap_save";
/// The user-profile tool's name — allowlists reference it.
pub const USER_PROFILE_SET: &str = "user_profile_set";
/// The cap on a user profile name; the same 64 the agent identity uses.
pub const MAX_USER_NAME_CHARS: usize = 64;
/// The file the structured user profile lives in, under the store's
/// root, beside the markdown files it feeds.
const USER_PROFILE_FILE: &str = "user.json";
/// The avatar's bytes, beside the profile document.
const USER_AVATAR_FILE: &str = "user-avatar.bin";
/// One of the three bootstrap files. SOUL.md and USER.md are the
/// model-written pair; ENVIRONMENT.md is the boot-generated one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
@@ -101,6 +115,46 @@ pub enum BootstrapError {
/// refuses to run on a prompt it cannot fully render.
#[error("system prompt template: {0}")]
Template(String),
/// The user profile document could not be read or written.
#[error("user profile store failed: {0}")]
Profile(String),
/// A profile name exceeded [`MAX_USER_NAME_CHARS`].
#[error("{0}")]
InvalidName(String),
/// An avatar exceeded [`crate::identity::MAX_IMAGE_BYTES`].
#[error("avatar too large: {size} bytes, the limit is {limit}")]
AvatarTooLarge {
/// The rejected body's size, in bytes.
size: usize,
/// The cap.
limit: usize,
},
/// An avatar upload carried a content type the routes do not serve.
#[error("not an image: {0:?}")]
NotAnImage(String),
}
/// The human user's profile as the interfaces render it: the display
/// name in the bottom-left account and the avatar beside it. Stored
/// claw-side so every client reads the same profile over `GET /v1/user`
/// and the prompt templates can spell `{{ user_name }}`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct UserProfile {
/// The user's display name, `None` while unset.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// Whether an avatar image is set (served at `/v1/user/avatar`).
pub avatar: bool,
}
/// The profile as it sits in `user.json`: the name plus the avatar's
/// content type, the presence flag being derived on read.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct StoredUserProfile {
#[serde(default)]
name: Option<String>,
#[serde(default)]
avatar_type: Option<String>,
}
/// Which of the onboarding files exist — the badge the HTTP surface
@@ -175,6 +229,136 @@ impl Bootstrap {
pub fn needs_onboarding(&self) -> bool {
!self.status().is_ok_and(|status| status.soul && status.user)
}
/// The file's text with the profile variables resolved: a document
/// that spells `{{ user_name }}` renders the profile name, and an
/// unset name leaves the token in place, so the document becomes
/// concrete the moment the profile is set. The file on disk is
/// never rewritten.
pub fn load_expanded(&self, kind: BootstrapKind) -> Result<Option<String>, BootstrapError> {
let Some(text) = self.load(kind)? else {
return Ok(None);
};
let profile = self.user_profile()?;
Ok(Some(expand_user_variables(&text, profile.name.as_deref())))
}
/// The user's profile; an unwritten document reads as an unnamed
/// user with no avatar.
pub fn user_profile(&self) -> Result<UserProfile, BootstrapError> {
let stored = self.stored_user_profile()?;
Ok(UserProfile {
name: stored.name,
avatar: stored.avatar_type.is_some(),
})
}
/// Sets or clears the profile name. An empty or whitespace-only
/// name clears it; a name over [`MAX_USER_NAME_CHARS`] is refused.
pub fn set_user_name(&self, name: Option<&str>) -> Result<UserProfile, BootstrapError> {
let cleaned = name.map(str::trim).filter(|name| !name.is_empty());
if let Some(name) = cleaned
&& name.chars().count() > MAX_USER_NAME_CHARS
{
return Err(BootstrapError::InvalidName(format!(
"name is over {MAX_USER_NAME_CHARS} characters"
)));
}
let mut stored = self.stored_user_profile()?;
stored.name = cleaned.map(str::to_owned);
self.write_user_profile(&stored)?;
self.user_profile()
}
/// Stores the avatar: the bytes in the store's root, the content
/// type in the profile document. The same image rules as
/// [`crate::identity::IdentityStore::set_image`], the agent's own
/// avatar route.
pub fn set_user_avatar(
&self,
bytes: &[u8],
content_type: &str,
) -> Result<UserProfile, BootstrapError> {
let content_type = crate::identity::image_content_type(content_type)
.ok_or_else(|| BootstrapError::NotAnImage(content_type.to_owned()))?;
if bytes.len() > crate::identity::MAX_IMAGE_BYTES {
return Err(BootstrapError::AvatarTooLarge {
size: bytes.len(),
limit: crate::identity::MAX_IMAGE_BYTES,
});
}
std::fs::create_dir_all(&self.root)?;
std::fs::write(self.root.join(USER_AVATAR_FILE), bytes)?;
let mut stored = self.stored_user_profile()?;
stored.avatar_type = Some(content_type);
self.write_user_profile(&stored)?;
self.user_profile()
}
/// The avatar's bytes and content type, when one is set.
pub fn user_avatar(&self) -> Result<Option<(Vec<u8>, String)>, BootstrapError> {
let stored = self.stored_user_profile()?;
match stored.avatar_type {
Some(content_type) => Ok(Some((
std::fs::read(self.root.join(USER_AVATAR_FILE))?,
content_type,
))),
None => Ok(None),
}
}
/// Drops the avatar; a no-op when unset.
pub fn clear_user_avatar(&self) -> Result<UserProfile, BootstrapError> {
match std::fs::remove_file(self.root.join(USER_AVATAR_FILE)) {
Ok(()) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => return Err(err.into()),
}
let mut stored = self.stored_user_profile()?;
stored.avatar_type = None;
self.write_user_profile(&stored)?;
self.user_profile()
}
fn stored_user_profile(&self) -> Result<StoredUserProfile, BootstrapError> {
match std::fs::read(self.root.join(USER_PROFILE_FILE)) {
Ok(bytes) => serde_json::from_slice(&bytes)
.map_err(|err| BootstrapError::Profile(err.to_string())),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
Ok(StoredUserProfile::default())
}
Err(err) => Err(err.into()),
}
}
fn write_user_profile(&self, stored: &StoredUserProfile) -> Result<(), BootstrapError> {
std::fs::create_dir_all(&self.root)?;
let bytes = serde_json::to_vec_pretty(stored)
.map_err(|err| BootstrapError::Profile(err.to_string()))?;
std::fs::write(self.root.join(USER_PROFILE_FILE), bytes)?;
Ok(())
}
}
/// The spellings a bootstrap document may use for the profile name.
/// Only these exact tokens are substituted, so a document's own braces
/// stay untouched.
const USER_NAME_VARIABLES: &[&str] = &[
"{{ user_name }}",
"{{user_name}}",
"{{ user_profile.name }}",
"{{user_profile.name}}",
];
/// Substitutes the profile name tokens in `text`; an unset name leaves
/// the document alone.
fn expand_user_variables(text: &str, name: Option<&str>) -> String {
let Some(name) = name.map(str::trim).filter(|name| !name.is_empty()) else {
return text.to_owned();
};
USER_NAME_VARIABLES
.iter()
.fold(text.to_owned(), |text, token| text.replace(token, name))
}
/// The stub a missing SOUL.md or USER.md renders.
@@ -236,9 +420,10 @@ pub fn render_system(
mcp: Option<&str>,
surface: Surface,
) -> Result<String, BootstrapError> {
let soul = bootstrap.load(BootstrapKind::Soul)?;
let user = bootstrap.load(BootstrapKind::User)?;
let environment = bootstrap.load(BootstrapKind::Environment)?;
let soul = bootstrap.load_expanded(BootstrapKind::Soul)?;
let user = bootstrap.load_expanded(BootstrapKind::User)?;
let environment = bootstrap.load_expanded(BootstrapKind::Environment)?;
let profile = bootstrap.user_profile()?;
let onboarding = if surface == Surface::Chat && (soul.is_none() || user.is_none()) {
ONBOARDING_MD
} else {
@@ -248,6 +433,8 @@ pub fn render_system(
let context = json!({
"session": session,
"workspace": workspace.display().to_string(),
"user_name": profile.name.clone().unwrap_or_default(),
"user_profile": profile,
"soul": section("## SOUL", soul.as_deref(), PENDING),
"user": section("## USER", user.as_deref(), PENDING),
"environment": section("## ENVIRONMENT", environment.as_deref(), GENERATED_AT_BOOT),
@@ -297,26 +484,114 @@ impl ToolOp for BootstrapSave {
}
}
/// The compiled operation behind the manifest, by `run.builtin` id.
fn builtins(bootstrap: Arc<Bootstrap>) -> BTreeMap<String, Arc<dyn ToolOp>> {
BTreeMap::from([(
"bootstrap.save".to_owned(),
Arc::new(BootstrapSave { bootstrap }) as Arc<dyn ToolOp>,
)])
/// Sets the human user's profile through the [`Bootstrap`] store: the
/// name the account shows and a picture beside it. The agent's own
/// presentation is [`crate::identity`]'s `identity_set`, never this.
pub struct UserProfileSet {
bootstrap: Arc<Bootstrap>,
workspace: PathBuf,
}
/// The `TOOL.yaml` of the bootstrap tool, embedded so the daemon ships
/// it with no filesystem layout.
pub const MANIFESTS: &[(&str, &str)] = &[(
"bootstrap_save",
include_str!("../tools/bootstrap_save/TOOL.yaml"),
)];
#[async_trait]
impl ToolOp for UserProfileSet {
async fn invoke(&self, args: Value) -> Result<String, ToolError> {
if !args.is_object() {
return Err("bad arguments: expected an object".to_owned().into());
}
// An absent name keeps the stored one; an empty string clears.
// The avatar path is read and validated before anything writes,
// so a bad path fails the call without a half-changed profile.
let avatar = match args["avatar"].as_str() {
Some(path) => {
let file = crate::identity::workspace_image(&self.workspace, path)?;
let bytes =
std::fs::read(&file).map_err(|err| format!("cannot read {path:?}: {err}"))?;
Some((bytes, crate::attachments::content_type(path)))
}
None => None,
};
let clear_avatar = match args["clear"].as_array() {
Some(list) => {
let mut clear = false;
for name in list {
match name.as_str() {
Some("avatar") => clear = true,
Some(other) => {
return Err(format!("unknown profile field {other:?}").into());
}
None => return Err("clear must name avatar".to_owned().into()),
}
}
clear
}
None => false,
};
/// The bootstrap tool set over `store`: `bootstrap_save`, the shape the
/// interactive resolver chain composes — its spec from the embedded
/// manifest, the operation compiled here.
pub fn registry(bootstrap: Arc<Bootstrap>) -> ToolRegistry {
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(bootstrap));
if let Some(name) = args.get("name") {
let name = name
.as_str()
.ok_or("name must be a string; an empty string clears it")?;
self.bootstrap
.set_user_name(Some(name))
.map_err(|err| err.to_string())?;
}
if let Some((bytes, content_type)) = avatar {
self.bootstrap
.set_user_avatar(&bytes, content_type)
.map_err(|err| err.to_string())?;
}
if clear_avatar {
self.bootstrap
.clear_user_avatar()
.map_err(|err| err.to_string())?;
}
let profile = self
.bootstrap
.user_profile()
.map_err(|err| err.to_string())?;
Ok(json!({ "saved": true, "profile": profile }).to_string())
}
}
/// The compiled operation behind the manifest, by `run.builtin` id.
fn builtins(bootstrap: Arc<Bootstrap>, workspace: PathBuf) -> BTreeMap<String, Arc<dyn ToolOp>> {
BTreeMap::from([
(
"bootstrap.save".to_owned(),
Arc::new(BootstrapSave {
bootstrap: bootstrap.clone(),
}) as Arc<dyn ToolOp>,
),
(
"user_profile.set".to_owned(),
Arc::new(UserProfileSet {
bootstrap,
workspace,
}) as Arc<dyn ToolOp>,
),
])
}
/// The `TOOL.yaml`s, embedded so the daemon ships them with no
/// filesystem layout.
pub const MANIFESTS: &[(&str, &str)] = &[
(
"bootstrap_save",
include_str!("../tools/bootstrap_save/TOOL.yaml"),
),
(
"user_profile_set",
include_str!("../tools/user_profile_set/TOOL.yaml"),
),
];
/// The identity tool set over `store`: `bootstrap_save` (SOUL.md and
/// USER.md) and `user_profile_set` (the human's name and picture), the
/// shape the interactive resolver chain composes — specs from the
/// embedded manifests, operations compiled here.
pub fn registry(bootstrap: Arc<Bootstrap>, workspace: impl Into<PathBuf>) -> ToolRegistry {
let (tools, skipped) =
crate::toolkit::builtin_tools(MANIFESTS, &builtins(bootstrap, workspace.into()));
assert!(
skipped.is_empty(),
"the bootstrap tool manifest must load: {skipped:?}"
@@ -444,9 +719,12 @@ mod tests {
#[test]
fn a_fresh_house_renders_stubs_and_the_onboarding_section() {
let (_dir, bootstrap) = store();
let tools = registry(Arc::new(Bootstrap {
root: bootstrap.root().to_path_buf(),
}))
let tools = registry(
Arc::new(Bootstrap {
root: bootstrap.root().to_path_buf(),
}),
"/ws",
)
.resolver_for(&crate::toolkit::Allowlist::permissive())
.specs();
let prompt = render_system(
@@ -680,9 +958,12 @@ mod tests {
use rhema_core::{ToolCall, ToolContext};
let (_dir, bootstrap) = store();
let resolver = registry(Arc::new(Bootstrap {
root: bootstrap.root().to_path_buf(),
}))
let resolver = registry(
Arc::new(Bootstrap {
root: bootstrap.root().to_path_buf(),
}),
"/ws",
)
.resolver_for(&Allowlist::permissive());
let ctx = ToolContext::default();
let call = |id: &str, args: Value| {
@@ -768,4 +1049,164 @@ mod tests {
assert!(prompt.contains("Always apply."), "{prompt}");
assert!(prompt.contains("/cfg/skills/unslop/SKILL.md"), "{prompt}");
}
#[test]
fn the_user_profile_round_trips_and_clears() {
let (_dir, bootstrap) = store();
assert_eq!(
bootstrap.user_profile().expect("reads"),
UserProfile::default(),
"an unwritten profile is unnamed with no avatar"
);
let saved = bootstrap
.set_user_name(Some(" Ana "))
.expect("the name saves");
assert_eq!(saved.name.as_deref(), Some("Ana"), "trimmed");
assert!(!saved.avatar);
let overlong = "x".repeat(MAX_USER_NAME_CHARS + 1);
let err = bootstrap
.set_user_name(Some(&overlong))
.expect_err("over the cap");
assert!(err.to_string().contains("over 64"), "{err}");
let cleared = bootstrap
.set_user_name(Some(" "))
.expect("a blank name clears");
assert_eq!(cleared.name, None);
}
#[test]
fn the_user_avatar_round_trips_and_refuses_non_images() {
let (_dir, bootstrap) = store();
let saved = bootstrap
.set_user_avatar(&[1, 2, 3], "image/png; charset=binary")
.expect("the avatar saves");
assert!(saved.avatar);
let (bytes, content_type) = bootstrap
.user_avatar()
.expect("reads")
.expect("an avatar is set");
assert_eq!(bytes, vec![1, 2, 3]);
assert_eq!(content_type, "image/png", "parameters stripped");
assert!(
bootstrap
.set_user_avatar(b"<svg/>", "image/svg+xml")
.is_err(),
"svg carries scripts"
);
assert!(bootstrap.set_user_avatar(b"plain", "text/plain").is_err());
let cleared = bootstrap.clear_user_avatar().expect("the clear saves");
assert!(!cleared.avatar);
assert!(bootstrap.user_avatar().expect("reads").is_none());
// Clearing an unset avatar is a no-op.
bootstrap
.clear_user_avatar()
.expect("the second clear is a no-op");
}
#[test]
fn a_document_reads_the_profile_name() {
let (_dir, bootstrap) = store();
let body = "The user is {{ user_name }}; keep {{ other }}.";
bootstrap.save(BootstrapKind::User, body).expect("saves");
assert_eq!(
bootstrap
.load_expanded(BootstrapKind::User)
.expect("reads")
.as_deref(),
Some(body),
"an unset name leaves the token in place"
);
bootstrap
.set_user_name(Some("Ana"))
.expect("the name saves");
assert_eq!(
bootstrap
.load_expanded(BootstrapKind::User)
.expect("reads")
.as_deref(),
Some("The user is Ana; keep {{ other }}."),
"only the profile token is substituted"
);
}
#[test]
fn the_prompt_context_carries_the_profile() {
let (_dir, bootstrap) = store();
bootstrap
.set_user_name(Some("Ana"))
.expect("the name saves");
let prompt = render_system(
"{{ user_name }}|{{ user_profile.name }}|{{ user_profile.avatar }}",
"interactive:web",
Path::new("/ws"),
&bootstrap,
&[],
&[],
None,
None,
Surface::Chat,
)
.expect("renders");
assert_eq!(prompt.trim(), "Ana|Ana|False");
}
#[tokio::test]
async fn the_profile_tool_saves_a_name_and_a_workspace_avatar() {
use crate::toolkit::Allowlist;
use rhema_core::{ToolCall, ToolContext};
let dir = tempfile::tempdir().expect("tempdir");
let workspace = dir.path().join("interactive");
std::fs::create_dir_all(&workspace).expect("workspace");
std::fs::write(workspace.join("face.png"), b"png-bytes").expect("the image writes");
let bootstrap = Arc::new(Bootstrap::new(dir.path().join("bootstrap")).expect("opens"));
let resolver =
registry(bootstrap.clone(), workspace).resolver_for(&Allowlist::permissive());
let ctx = ToolContext::default();
let call = |id: &str, args: Value| {
resolver.resolve(
ToolCall {
id: id.into(),
name: USER_PROFILE_SET.into(),
args,
provider_data: Value::Null,
},
&ctx,
)
};
let saved = call("c1", json!({"name": "Ana", "avatar": "face.png"})).await;
assert!(!saved.is_error, "{}", saved.content);
let answer: Value = serde_json::from_str(&saved.content).expect("parses");
assert_eq!(answer["profile"]["name"], "Ana");
assert_eq!(answer["profile"]["avatar"], true);
assert_eq!(
bootstrap.user_profile().expect("reads").name.as_deref(),
Some("Ana")
);
// An absent name keeps the stored one; clear drops the picture.
let cleared = call("c2", json!({"clear": ["avatar"]})).await;
assert!(!cleared.is_error, "{}", cleared.content);
let answer: Value = serde_json::from_str(&cleared.content).expect("parses");
assert_eq!(answer["profile"]["name"], "Ana", "kept");
assert_eq!(answer["profile"]["avatar"], false);
let emptied = call("c3", json!({"name": ""})).await;
assert!(!emptied.is_error, "{}", emptied.content);
assert_eq!(bootstrap.user_profile().expect("reads").name, None);
for bad in [
json!({"avatar": "../outside.png"}),
json!({"avatar": "/etc/hostname"}),
json!({"clear": ["logo"]}),
json!({"name": "x".repeat(65)}),
] {
assert!(call("bad", bad.clone()).await.is_error, "refused: {bad}");
}
}
}
+5 -1
View File
@@ -535,7 +535,11 @@ impl ClawHandler {
.load(BootstrapKind::Environment)
.ok()
.flatten();
config.user_preferences = self.bootstrap.load(BootstrapKind::User).ok().flatten();
config.user_preferences = self
.bootstrap
.load_expanded(BootstrapKind::User)
.ok()
.flatten();
let _handle = catalog.wire(&mut config);
}
Ok(config)
+115 -1
View File
@@ -1,5 +1,6 @@
//! The HTTP surface: the resident agent's chat routes, its session
//! inventory, its watch CRUD, its setup badge (`/v1/bootstrap`), the
//! human's profile (`/v1/user`), the
//! external-event ingress (`/v1/ingest`), the notification queue the
//! devices poll, and the health probe that stays open when everything
//! else is tokened.
@@ -333,6 +334,12 @@ impl ClawState {
&self.identity
}
/// The identity-file store: SOUL.md, USER.md, ENVIRONMENT.md, and
/// the human's profile the `/v1/user` routes read and write.
pub fn bootstrap(&self) -> &Bootstrap {
&self.bootstrap
}
/// The accounts layer: the identity routes list, save, and forget
/// through it, redacted records only.
pub fn accounts(&self) -> &dyn rhema_identity::IdentityStore {
@@ -399,6 +406,13 @@ pub fn router(state: ClawState) -> Router {
.put(agent_image_put)
.delete(agent_image_delete),
)
.route("/user", get(user_profile_get).put(user_profile_put))
.route(
"/user/avatar",
get(user_avatar_get)
.put(user_avatar_put)
.delete(user_avatar_delete),
)
.route("/providers", get(providers_list))
.route("/providers/active", put(providers_active))
.route(
@@ -432,7 +446,8 @@ pub fn router(state: ClawState) -> Router {
"chat": "/v1/sessions",
"api": ["/v1/sessions", "/v1/providers", "/v1/watches", "/v1/calendars",
"/v1/accounts", "/v1/notifications", "/v1/phones",
"/v1/bootstrap", "/v1/ingest", "/v1/skills", "/v1/mcp"],
"/v1/bootstrap", "/v1/agent", "/v1/user", "/v1/ingest",
"/v1/skills", "/v1/mcp"],
}))
}),
)
@@ -2811,6 +2826,105 @@ async fn agent_image_delete(
))
}
/// `GET /v1/user`: the human's profile — the display name and whether
/// an avatar is set. The web interface renders it in its bottom-left
/// account; the prompt templates read the name as `{{ user_name }}`.
async fn user_profile_get(
State(state): State<ClawState>,
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
let profile = state.bootstrap().user_profile().map_err(internal_error)?;
Ok(Json(
serde_json::to_value(&profile).map_err(internal_error)?,
))
}
/// `PUT /v1/user`: set the display name. An absent name keeps the
/// stored one; an empty string clears it.
async fn user_profile_put(
State(state): State<ClawState>,
Json(body): Json<Value>,
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
let name = match body.get("name") {
Some(Value::String(name)) => Some(name.clone()),
Some(_) => {
return Err(bad_request(
"name must be a string; an empty string clears it",
));
}
None => {
state
.bootstrap()
.user_profile()
.map_err(internal_error)?
.name
}
};
let profile = state
.bootstrap()
.set_user_name(name.as_deref())
.map_err(|err| match err {
crate::bootstrap::BootstrapError::InvalidName(_) => bad_request(err),
_ => internal_error(err),
})?;
Ok(Json(
serde_json::to_value(&profile).map_err(internal_error)?,
))
}
/// `PUT /v1/user/avatar`: store the profile picture from the raw body,
/// content type from the header. Answers the updated profile.
async fn user_avatar_put(
State(state): State<ClawState>,
headers: axum::http::HeaderMap,
body: axum::body::Bytes,
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
let content_type = headers
.get(axum::http::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.unwrap_or_default();
let profile = state
.bootstrap()
.set_user_avatar(&body, content_type)
.map_err(|err| match err {
crate::bootstrap::BootstrapError::NotAnImage(_)
| crate::bootstrap::BootstrapError::AvatarTooLarge { .. } => bad_request(err),
_ => internal_error(err),
})?;
Ok(Json(
serde_json::to_value(&profile).map_err(internal_error)?,
))
}
/// `GET /v1/user/avatar`: the picture's bytes, content type with them.
/// 404 when unset — the profile document's `avatar` flag is how a
/// client knows before asking.
async fn user_avatar_get(
State(state): State<ClawState>,
) -> Result<Response, (StatusCode, Json<Value>)> {
match state.bootstrap().user_avatar().map_err(internal_error)? {
Some((bytes, content_type)) => {
Ok(([(axum::http::header::CONTENT_TYPE, content_type)], bytes).into_response())
}
None => Err((
StatusCode::NOT_FOUND,
Json(json!({"error": "no avatar set"})),
)),
}
}
/// `DELETE /v1/user/avatar`: drop the picture. Answers the profile.
async fn user_avatar_delete(
State(state): State<ClawState>,
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
let profile = state
.bootstrap()
.clear_user_avatar()
.map_err(internal_error)?;
Ok(Json(
serde_json::to_value(&profile).map_err(internal_error)?,
))
}
fn image_kind(name: &str) -> Result<crate::identity::ImageKind, (StatusCode, Json<Value>)> {
match name {
"avatar" => Ok(crate::identity::ImageKind::Avatar),
+18 -13
View File
@@ -39,6 +39,21 @@ pub enum IdentityError {
/// every size the UI renders, small enough that the route stays cheap.
pub const MAX_IMAGE_BYTES: usize = 2 * 1024 * 1024;
/// The content type an upload is served back as, parameters stripped,
/// or `None` for a body the routes refuse. SVG is refused deliberately:
/// it is the one image format that can carry scripts, and the identity
/// and user-profile routes serve these bytes to a browser. The profile
/// store in [`crate::bootstrap`] applies the same rule.
pub fn image_content_type(raw: &str) -> Option<String> {
let content_type = raw
.split(';')
.next()
.unwrap_or_default()
.trim()
.to_ascii_lowercase();
(content_type.starts_with("image/") && content_type != "image/svg+xml").then_some(content_type)
}
/// The agent's identity as the wire sees it: the optional text fields
/// (each `null` when unset) and whether the images exist — the images
/// themselves live behind their own routes.
@@ -176,18 +191,8 @@ impl IdentityStore {
bytes: &[u8],
content_type: &str,
) -> Result<AgentIdentity, IdentityError> {
let content_type = content_type
.split(';')
.next()
.unwrap_or_default()
.trim()
.to_ascii_lowercase();
if !content_type.starts_with("image/") || content_type == "image/svg+xml" {
// SVG is refused deliberately: it is the one image format
// that can carry scripts, and the route serves these bytes
// back to a browser.
return Err(IdentityError::NotAnImage(content_type));
}
let content_type = image_content_type(content_type)
.ok_or_else(|| IdentityError::NotAnImage(content_type.to_owned()))?;
if bytes.len() > MAX_IMAGE_BYTES {
return Err(IdentityError::TooLarge(bytes.len(), MAX_IMAGE_BYTES));
}
@@ -322,7 +327,7 @@ impl ToolOp for IdentitySet {
/// Resolves a workspace-relative image path — absolute paths and `..`
/// escapes are refused, the same discipline the attachment tool keeps.
fn workspace_image(workspace: &Path, path: &str) -> Result<PathBuf, String> {
pub(crate) fn workspace_image(workspace: &Path, path: &str) -> Result<PathBuf, String> {
let relative = Path::new(path);
if relative.is_absolute()
|| relative
+14 -7
View File
@@ -235,8 +235,9 @@ pub struct InteractiveHandler {
/// The durable cross-session store the memory tools act on; the
/// resolver is built per dispatch so its scope tracks the workspace.
memory: Arc<dyn MemoryStore>,
/// The identity files: the system prompt renders from them per
/// dispatch, and the `bootstrap_save` resolver writes them.
/// The identity files and the human's profile: the system prompt
/// renders from them per dispatch, and the `bootstrap_save` and
/// `user_profile_set` resolvers write them.
bootstrap: Arc<Bootstrap>,
/// The attachment store: inbound chat images copy into it, so the
/// transcript carries ids and a client fetches the bytes over the
@@ -298,7 +299,8 @@ impl InteractiveHandler {
/// runs at assembly. The core toolsets are the handler's own: the
/// shell (approval v1-permissive — the shell is the point of a
/// resident coding agent — installed once, since resolution is
/// synchronous within a turn), memory, and `bootstrap_save`.
/// synchronous within a turn), memory, `bootstrap_save`, and
/// `user_profile_set`.
#[expect(clippy::too_many_arguments, reason = "ten parts, each load-bearing")]
pub fn new(
backends: Arc<BackendRegistry>,
@@ -330,8 +332,8 @@ impl InteractiveHandler {
false => ShellTools::with_env(&workspace, &env),
});
tools.install_approval(Arc::new(AllowAll));
let bootstrap_resolver =
crate::bootstrap::registry(bootstrap.clone()).resolver_for(&Allowlist::permissive());
let bootstrap_resolver = crate::bootstrap::registry(bootstrap.clone(), workspace.clone())
.resolver_for(&Allowlist::permissive());
Self {
backends,
workspace,
@@ -460,7 +462,11 @@ impl InteractiveHandler {
.load(BootstrapKind::Environment)
.ok()
.flatten();
config.user_preferences = self.bootstrap.load(BootstrapKind::User).ok().flatten();
config.user_preferences = self
.bootstrap
.load_expanded(BootstrapKind::User)
.ok()
.flatten();
let _handle = catalog.wire(&mut config);
}
Ok(config)
@@ -509,7 +515,8 @@ impl InteractiveHandler {
}
/// The extension side of one dispatch's chain: memory,
/// `bootstrap_save`, then every extension's tools in the standard
/// `bootstrap_save`, `user_profile_set`, then every extension's
/// tools in the standard
/// set's order. The whole side is cut per dispatch: the key-scoped
/// toolsets (consents, attachments, phone) must bind their asks and
/// cards to the session that asked, and the handler serves every
+5 -1
View File
@@ -35,6 +35,10 @@
//! - [`identity`] — the agent's presentation identity: name, email,
//! mark, images, served over `/v1/agent` and settable by the agent
//! itself through the `identity_set` tool
//! - [`bootstrap`] — the identity files and the human's profile: the
//! display name and avatar served over `/v1/user`, set by
//! `user_profile_set`, and readable as `{{ user_name }}` in the
//! markdown documents
//! - [`git_identity`] — the boot-time git identity: `user.name` and
//! `user.email` into the daemon user's global git config, resolved
//! from config, then identity, then defaults, guarded against
@@ -123,7 +127,7 @@ pub mod watch_tools;
pub use backends::{Backend, BackendError, BackendRegistry};
pub use bootstrap::{
BOOTSTRAP_SAVE, Bootstrap, BootstrapError, BootstrapKind, BootstrapStatus, DEFAULT_SYSTEM_MD,
render_system,
USER_PROFILE_SET, UserProfile, render_system,
};
pub use config::{ClawConfig, ConfigError};
pub use daemon::{ClawError, Daemon, TickReport, forge_dispatch, run_once};
+127
View File
@@ -3154,6 +3154,133 @@ async fn the_agent_identity_is_editable_over_the_surface() {
assert_eq!(gone.status(), 404);
}
/// The human's profile surface: the name round-trips with partial-save
/// semantics, the avatar uploads and serves back with its content type,
/// and clearing it 404s the read.
#[tokio::test]
async fn the_user_profile_is_editable_over_the_surface() {
let dir = tempfile::tempdir().expect("tempdir");
let daemon = Daemon::build(
&config(&dir, None),
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon assembles");
let base = serve(&daemon).await;
let client = reqwest::Client::new();
let empty: Value = client
.get(format!("{base}/v1/user"))
.send()
.await
.expect("the profile reads")
.json()
.await
.expect("the profile parses");
assert_eq!(empty["name"], Value::Null);
assert_eq!(empty["avatar"], false);
let saved: Value = client
.put(format!("{base}/v1/user"))
.json(&json!({"name": "Ana"}))
.send()
.await
.expect("the save posts")
.json()
.await
.expect("the save parses");
assert_eq!(saved["name"], "Ana");
// An absent name keeps the stored one.
let kept: Value = client
.put(format!("{base}/v1/user"))
.json(&json!({}))
.send()
.await
.expect("the empty save posts")
.json()
.await
.expect("the empty save parses");
assert_eq!(kept["name"], "Ana");
// An empty string clears it.
let cleared: Value = client
.put(format!("{base}/v1/user"))
.json(&json!({"name": ""}))
.send()
.await
.expect("the clear posts")
.json()
.await
.expect("the clear parses");
assert_eq!(cleared["name"], Value::Null);
// An overlong name is a 400.
let refused = client
.put(format!("{base}/v1/user"))
.json(&json!({"name": "x".repeat(65)}))
.send()
.await
.expect("the refusal posts");
assert_eq!(refused.status(), 400);
// The avatar: upload, serve, clear.
let uploaded: Value = client
.put(format!("{base}/v1/user/avatar"))
.header("content-type", "image/png")
.body(vec![9, 8, 7])
.send()
.await
.expect("the upload posts")
.json()
.await
.expect("the upload parses");
assert_eq!(uploaded["avatar"], true);
let served = client
.get(format!("{base}/v1/user/avatar"))
.send()
.await
.expect("the image reads");
assert_eq!(served.status(), 200);
assert_eq!(
served
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok()),
Some("image/png")
);
assert_eq!(
served.bytes().await.expect("the bytes read").as_ref(),
&[9, 8, 7]
);
let not_image = client
.put(format!("{base}/v1/user/avatar"))
.header("content-type", "text/html")
.body("<b>no</b>")
.send()
.await
.expect("the refusal posts");
assert_eq!(not_image.status(), 400);
let cleared_image: Value = client
.delete(format!("{base}/v1/user/avatar"))
.send()
.await
.expect("the clear posts")
.json()
.await
.expect("the clear parses");
assert_eq!(cleared_image["avatar"], false);
let gone = client
.get(format!("{base}/v1/user/avatar"))
.send()
.await
.expect("the read answers");
assert_eq!(gone.status(), 404);
}
/// The registry a rebuilt daemon boots over the same db: discovery's
/// stored instances plus the scripted mock, so a persisted active pair
/// referencing a named instance restores against it.
@@ -0,0 +1,29 @@
# The model-facing spec of the user_profile_set tool; the operation is
# the compiled builtin named under `run`.
name: user_profile_set
description: >-
Set the human user's profile: the display name the interface shows in
its bottom-left account and an avatar picture beside it. This is not
your own presentation; use identity_set for that. Leave a field out to
keep what is set; an empty name clears it. The avatar takes a
workspace-relative path to an image file (png, jpeg, gif, or webp,
under 2 MiB — svg is refused).
parameters:
type: object
properties:
name:
type: string
description: >-
The user's display name. Up to 64 chars. An empty string clears
it.
avatar:
type: string
description: Workspace-relative path to the user's avatar image.
clear:
type: array
items:
type: string
enum: [avatar]
description: Profile fields to remove.
run:
builtin: user_profile.set