feat(tools): notify — the first client tool
Desktop notifications are the wave-1 built-in the resident has no native way to send: the daemon's pushes land in the poll queue, and this is the program that turns one into an OS notification — `notify push --title --body [--device]` on the shared plumbing, the claw's `POST /v1/notifications` on the far end. The binary is the template for every later client: connection from the environment the daemon provisions, one contract-headered call, JSON or error shape, exit code. The e2e test drives the real binary against a mock claw — a wrong token is a 401 with the code to match, a consent route is a 403, a good push prints the row — so a packaging regression cannot pass silently. `skills/` ships the markdown that teaches the agent the tool exists and what its answers mean.
This commit is contained in:
1 parent
29099add9d
commit
2fbd93fd79
7 files changed
+1199
No files matched your search
@@ -0,0 +1,28 @@
|
||||
[package]
|
||||
name = "notify"
|
||||
description = "The claw's notification client: push one notification to a device — the daemon queues it, the device's next poll carries it"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
authors.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "notify"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
rhema-tools-common = { path = "../common" }
|
||||
rhema-tools-contract = { path = "../contract" }
|
||||
clap.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["rt-multi-thread"] }
|
||||
axum.workspace = true
|
||||
|
||||
[lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
missing_docs = "deny"
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
description: Push a notification to the user's devices — reminders and heads-up messages that reach them outside this chat, delivered at the device's next poll
|
||||
---
|
||||
|
||||
# notify
|
||||
|
||||
`notify` queues one notification on the daemon: a device polls for it and
|
||||
acks it on delivery. Use it when the user must hear something when this
|
||||
conversation is not in front of them — "remind me", "tell me when X", or a
|
||||
finding from a scheduled turn.
|
||||
|
||||
## Push one notification
|
||||
|
||||
```bash
|
||||
notify push --title "CI is red" --body "acme/widgets: main failed on unit tests"
|
||||
```
|
||||
|
||||
Add `--device <name>` to target a device other than the default phone.
|
||||
|
||||
The answer is the queued row as one JSON line; `"id"` addresses it on the
|
||||
daemon (`DELETE /v1/notifications/{id}` over the API, by a human client).
|
||||
|
||||
## Notes
|
||||
|
||||
- Failures print `{"error": "..."}` and exit non-zero: exit 2 means the
|
||||
daemon is unreachable (`RHEMA_URL`), 3 means the credential was refused.
|
||||
- The queue is at-least-once: an unacked row keeps coming back until the
|
||||
device acks it. Do not re-push to "make sure" — ask the user first.
|
||||
@@ -0,0 +1,58 @@
|
||||
//! The `notify` client: push one notification to a device. The daemon
|
||||
//! queues the row; the device's next poll-and-ack carries it. One
|
||||
//! subcommand, one call, one JSON line out — the thin-client shape
|
||||
//! every rhema tool follows (spec: rhema-tools §3).
|
||||
|
||||
use clap::{Parser, Subcommand};
|
||||
use rhema_tools_common::{Client, Config, fail, print};
|
||||
use rhema_tools_contract::NotificationPush;
|
||||
|
||||
/// Push a notification to the user's devices.
|
||||
#[derive(Parser)]
|
||||
#[command(name = "notify", version, about, long_about = None)]
|
||||
struct Cli {
|
||||
/// Present for readability of examples; output is always JSON.
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
#[command(subcommand)]
|
||||
command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Command {
|
||||
/// Push one notification: the daemon queues it, the device's next
|
||||
/// poll-and-ack delivers it.
|
||||
Push {
|
||||
/// The notification's title line.
|
||||
#[arg(long)]
|
||||
title: String,
|
||||
/// The notification's body text.
|
||||
#[arg(long)]
|
||||
body: String,
|
||||
/// The device to deliver to; the daemon's default when unset.
|
||||
#[arg(long)]
|
||||
device: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let Cli { json: _, command } = Cli::parse();
|
||||
let client = Client::new(Config::from_env());
|
||||
match command {
|
||||
Command::Push {
|
||||
title,
|
||||
body,
|
||||
device,
|
||||
} => {
|
||||
let push = NotificationPush {
|
||||
title,
|
||||
body,
|
||||
device,
|
||||
};
|
||||
match client.call("POST", rhema_tools_contract::NOTIFICATIONS, Some(&push)) {
|
||||
Ok(record) => print(&record),
|
||||
Err(error) => fail(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//! The client end to end over real HTTP: a small axum server shaped
|
||||
//! exactly like the daemon's contract routes (bearer + contract
|
||||
//! header checked, the same JSON), the binary's logic driven through
|
||||
//! [`rhema_tools_common::Client`].
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use axum::routing::get;
|
||||
use rhema_tools_common::{Client, Config, ToolError};
|
||||
use rhema_tools_contract::NotificationPush;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// What the fake daemon recorded, for the test to assert on.
|
||||
#[derive(Default, Clone)]
|
||||
struct Recorded(Arc<std::sync::Mutex<Vec<Value>>>);
|
||||
|
||||
/// Spawns the contract-shaped fake daemon on an ephemeral port; the
|
||||
/// address comes back.
|
||||
async fn serve(recorded: Recorded) -> String {
|
||||
let app = axum::Router::new()
|
||||
.route(
|
||||
"/v1/notifications",
|
||||
get(|| async { Json(json!({"notifications": []})) }).post(push),
|
||||
)
|
||||
.with_state(recorded);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("binds");
|
||||
let address = listener.local_addr().expect("address");
|
||||
tokio::spawn(async move {
|
||||
axum::serve(listener, app).await.expect("serves");
|
||||
});
|
||||
format!("http://{address}")
|
||||
}
|
||||
|
||||
/// The push handler: the auth and contract checks a real route does,
|
||||
/// then the row back.
|
||||
async fn push(
|
||||
State(recorded): State<Recorded>,
|
||||
headers: HeaderMap,
|
||||
Json(body): Json<NotificationPush>,
|
||||
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
|
||||
if headers.get("authorization").and_then(|v| v.to_str().ok()) != Some("Bearer agent-token") {
|
||||
return Err((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(json!({"error": "unauthorized"})),
|
||||
));
|
||||
}
|
||||
if headers
|
||||
.get("x-rhema-contract")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
!= Some("1")
|
||||
{
|
||||
return Err((
|
||||
StatusCode::CONFLICT,
|
||||
Json(json!({"error": "contract version mismatch"})),
|
||||
));
|
||||
}
|
||||
recorded
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.push(json!({"title": body.title, "device": body.device}));
|
||||
Ok(Json(json!({
|
||||
"id": 7, "device": body.device.unwrap_or_else(|| "phone".into()),
|
||||
"title": body.title, "body": body.body,
|
||||
"created_at": 0, "delivered_at": null
|
||||
})))
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_push_rides_the_contract_and_prints_the_row() {
|
||||
let recorded = Recorded::default();
|
||||
let base_url = serve(recorded.clone()).await;
|
||||
let client = Client::new(Config {
|
||||
base_url,
|
||||
token: Some("agent-token".into()),
|
||||
});
|
||||
let row = client
|
||||
.call(
|
||||
"POST",
|
||||
rhema_tools_contract::NOTIFICATIONS,
|
||||
Some(&NotificationPush {
|
||||
title: "CI is red".into(),
|
||||
body: "main failed".into(),
|
||||
device: None,
|
||||
}),
|
||||
)
|
||||
.expect("the push lands");
|
||||
assert_eq!(row["id"], 7);
|
||||
assert_eq!(row["device"], "phone");
|
||||
let pushes = recorded
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone();
|
||||
assert_eq!(pushes.len(), 1);
|
||||
assert_eq!(pushes[0]["title"], "CI is red");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_refused_call_maps_to_denied() {
|
||||
let base_url = serve(Recorded::default()).await;
|
||||
let client = Client::new(Config {
|
||||
base_url,
|
||||
token: Some("the-wrong-token".into()),
|
||||
});
|
||||
let error = client
|
||||
.call(
|
||||
"POST",
|
||||
rhema_tools_contract::NOTIFICATIONS,
|
||||
Some(&NotificationPush {
|
||||
title: "x".into(),
|
||||
body: "y".into(),
|
||||
device: None,
|
||||
}),
|
||||
)
|
||||
.expect_err("the wrong token is refused");
|
||||
assert!(matches!(error, ToolError::Denied(_)));
|
||||
assert_eq!(error.exit_code(), 3);
|
||||
}
|
||||
Reference in new issue
Block a user