Skip to content

Commit 1d9f2c8

Browse files
baxenclaude
andauthored
feat(relay): accept an owner's presence for its agents (kind 20003) (block#8261)
## Summary App-hosted agents (buzz-app agents2) run inside the desktop app without a socket per agent, so they can't send their own kind 20001 presence and always read as offline — including to their owner on another device. This adds **kind 20003, an owner's presence for its agents**: - Owner-signed; `content` is the status (`online` / `away` / `offline`); each `p` tag names an agent (1–256 distinct). - WebSocket only (rejected on HTTP ingest, like 20001). - The relay keeps only the agents the signer owns (`users.agent_owner_pubkey`) — cached `true` from `observer_owner_cache`, the rest resolved with one `list_agents_for_owner` query. Only positive links are cached, so a just-linked agent isn't hidden for the cache TTL and the observer path isn't poisoned. - Sets (180s TTL) or clears each agent's presence in one Redis round trip, the same keys kind 20001 writes, so the presence snapshot reports them with no client change. - Not fanned out: live presence is matched by author, and the author here is the owner. A new kind rather than `p` tags on 20001, so a relay without this ignores the batch instead of storing it as the owner's own presence. ## Testing - `agent_presence_request_names_distinct_agents_with_a_known_status` (unit). - `presence_storage_postgres_tests::agent_presence_stores_only_owned_agents` (Postgres + Redis): only the owner's agent goes online, another owner's agent doesn't, a pre-cached `false` doesn't hide a linked agent, and `offline` clears it. All 5 presence Postgres tests pass via `scripts/postgres-test-run.sh -p buzz-relay --lib -E 'test(/presence/)'`. - `buzz-pubsub` ignored Redis test `test_presence_many_sets_with_ttl_and_clears` passes. - clippy clean. Plain `cargo test` failures locally were environmental only (buzz-media "role buzz does not exist", mesh_demo 504). - Not yet exercised end to end against a local relay + app. App side: block/buzz-app#862. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Bradley Axen <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 799cfd7 commit 1d9f2c8

8 files changed

Lines changed: 405 additions & 2 deletions

File tree

‎ARCHITECTURE.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,7 @@ The `kind` integer is the only dispatch switch. The relay routes, stores, and fa
189189
| 45003 | KIND_FORUM_COMMENT | Forum thread reply |
190190
| 46001–46012 | KIND_WORKFLOW_* | Workflow execution events |
191191
| 20001 | KIND_PRESENCE_UPDATE | Ephemeral presence heartbeat |
192+
| 20003 | KIND_AGENT_PRESENCE | Ephemeral presence heartbeat an owner sends for its agents |
192193

193194
`buzz-core` defines each event kind as a `pub const u32` and exports the full registry as `ALL_KINDS: &[u32]` (127 kinds at the time of writing); `crates/buzz-core/src/kind.rs` is the source of truth for the current list. Kinds are `u32` (NIP-01 specifies unsigned integer; `u32` covers the full range). Buzz uses both standard Nostr kinds (e.g., kind 7 for reactions) and custom ranges (40000+).
194195

@@ -305,6 +306,8 @@ Ephemeral events bypass DB storage, audit, and search. Two sub-paths:
305306
```
306307
Presence events skip membership checks and use local-only fan-out. Multi-node presence fan-out would require Redis pub/sub (documented as future work).
307308

309+
**Agent presence (kind 20003):** an owner's one heartbeat for all its agents, so an app that runs agents without a socket per agent can still show them online. Content is the status (`online`, `away` or `offline`) and each `p` tag names an agent, at most 256. WebSocket only. The relay keeps the agents the signer owns (`users.agent_owner_pubkey`, through the owner cache), skips the rest, and sets or clears their presence exactly as their own kind 20001 would, so the presence snapshot reports them unchanged. It is not fanned out, since live presence is matched by author; viewers see it on their next snapshot read.
310+
308311
**Other ephemeral events (e.g., typing indicators):**
309312
```
310313
1. VERIFY — spawn_blocking(verify_event)

‎NOSTR.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ PGPASSWORD=buzz_dev psql -h localhost -U buzz -d buzz -c \
6262
| **Group members (kind:39002)** | ✅ | Relay-signed; `d` tag + `p` tags for all members |
6363
| **Membership notifications** | ✅ | kind:44100 (added) / kind:44101 (removed); relay-signed, community-global scope (`channel_id=None` inside the connected community) |
6464
| **Presence (kind:20001)** | ✅ | Ephemeral; arbitrary status string (truncated to 128 chars); writes to Redis (`set_presence`/`clear_presence` on `"offline"`), then fan-out to local subscribers. In multi-community mode presence is scoped to the connected community. |
65+
| **Agent presence (kind:20003)** | ✅ | Ephemeral; an owner's presence for the agents it owns, named by `p` tags (at most 256); `online`/`away` set and `offline` clears each agent's presence as its own kind:20001 would. Not fanned out. |
6566
| **Typing indicators (kind:20002)** | ✅ | Ephemeral, not stored; published via Redis pub/sub (multi-node capable unlike presence fan-out) |
6667
| **NIP-42 authentication** | ✅ | Proactive challenge; optional pubkey allowlist |
6768
| **NIP-11 relay info** | ✅ | `GET /` with `Accept: application/nostr+json` |

‎crates/buzz-core/src/kind.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -467,6 +467,9 @@ pub const KIND_PRESENCE_UPDATE: u32 = 20001;
467467
pub const KIND_PAIRING: u32 = 24134;
468468
/// Ephemeral: typing indicator for a channel.
469469
pub const KIND_TYPING_INDICATOR: u32 = 20002;
470+
/// Ephemeral: an owner's presence for its agents. Content is the status, each
471+
/// `p` tag names one agent the signer owns. Never the signer's own presence.
472+
pub const KIND_AGENT_PRESENCE: u32 = 20003;
470473
/// Ephemeral: owner-scoped encrypted agent observer telemetry and control frame.
471474
pub const KIND_AGENT_OBSERVER_FRAME: u32 = 24200;
472475
/// Ephemeral: huddle emoji reaction burst. Channel-scoped to the ephemeral
@@ -703,6 +706,7 @@ pub const ALL_KINDS: &[u32] = &[
703706
KIND_THREAD_WINDOW_BOUNDS,
704707
KIND_PRESENCE_UPDATE,
705708
KIND_TYPING_INDICATOR,
709+
KIND_AGENT_PRESENCE,
706710
KIND_HUDDLE_REACTION,
707711
KIND_BLOSSOM_AUTH,
708712
KIND_PAIRING,

‎crates/buzz-db/src/store/user.rs‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,24 @@ pub async fn list_agents_for_owner(
404404
.await?)
405405
}
406406

407+
/// Of `candidates`, the agents whose `agent_owner_pubkey` is `owner_pubkey` in
408+
/// one community.
409+
pub async fn owned_agents_among(
410+
pool: &PgPool,
411+
community_id: CommunityId,
412+
owner_pubkey: &[u8],
413+
candidates: &[Vec<u8>],
414+
) -> Result<Vec<Vec<u8>>> {
415+
Ok(sqlx::query_scalar::<_, Vec<u8>>(
416+
"SELECT pubkey FROM users WHERE community_id = $1 AND agent_owner_pubkey = $2 AND pubkey = ANY($3)",
417+
)
418+
.bind(community_id.as_uuid())
419+
.bind(owner_pubkey)
420+
.bind(candidates)
421+
.fetch_all(pool)
422+
.await?)
423+
}
424+
407425
/// Check whether `actor_pubkey` is the `agent_owner_pubkey` of `target_pubkey`.
408426
/// Queries `agent_owner_pubkey` directly rather than going through
409427
/// `get_agent_channel_policy`, which would fetch unrelated fields.
@@ -593,6 +611,17 @@ impl Db {
593611
crate::user::list_agents_for_owner(&self.pool, community_id, owner_pubkey).await
594612
}
595613

614+
/// Of `candidates`, the agents owned by `owner_pubkey` in one community.
615+
#[datastore_span(name = "owned_agents_among", system = "postgresql")]
616+
pub async fn owned_agents_among(
617+
&self,
618+
community_id: CommunityId,
619+
owner_pubkey: &[u8],
620+
candidates: &[Vec<u8>],
621+
) -> Result<Vec<Vec<u8>>> {
622+
crate::user::owned_agents_among(&self.pool, community_id, owner_pubkey, candidates).await
623+
}
624+
596625
/// Check whether `actor_pubkey` is the agent owner of `target_pubkey`.
597626
#[datastore_span(name = "is_agent_owner", system = "postgresql")]
598627
pub async fn is_agent_owner(

‎crates/buzz-pubsub/src/lib.rs‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,25 @@ impl PubSubManager {
398398
presence::clear_presence(&self.pool, ctx, pubkey).await
399399
}
400400

401+
/// Set one status with the 180s TTL for each of `pubkeys`, in one round trip.
402+
pub async fn set_presence_many(
403+
&self,
404+
ctx: &TenantContext,
405+
pubkeys: &[PublicKey],
406+
status: &str,
407+
) -> Result<(), PubSubError> {
408+
presence::set_presence_many(&self.pool, ctx, pubkeys, status).await
409+
}
410+
411+
/// Remove presence for each of `pubkeys`.
412+
pub async fn clear_presence_many(
413+
&self,
414+
ctx: &TenantContext,
415+
pubkeys: &[PublicKey],
416+
) -> Result<(), PubSubError> {
417+
presence::clear_presence_many(&self.pool, ctx, pubkeys).await
418+
}
419+
401420
/// Returns the current presence status for `pubkey`, or `None` if not set.
402421
pub async fn get_presence(
403422
&self,

‎crates/buzz-pubsub/src/presence.rs‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,53 @@ pub async fn clear_presence(
5858
Ok(())
5959
}
6060

61+
/// Sets one status for every pubkey in `pubkeys`, each with the
62+
/// [`PRESENCE_TTL_SECS`] TTL, in one atomic round trip.
63+
pub async fn set_presence_many(
64+
pool: &Pool,
65+
ctx: &TenantContext,
66+
pubkeys: &[PublicKey],
67+
status: &str,
68+
) -> Result<(), PubSubError> {
69+
if pubkeys.is_empty() {
70+
return Ok(());
71+
}
72+
let mut conn = pool.get().await?;
73+
let mut pipe = redis::pipe();
74+
pipe.atomic();
75+
for pubkey in pubkeys {
76+
pipe.cmd("SET")
77+
.arg(presence_key(ctx, pubkey))
78+
.arg(status)
79+
.arg("EX")
80+
.arg(PRESENCE_TTL_SECS)
81+
.ignore();
82+
}
83+
pipe.query_async::<()>(&mut conn).await?;
84+
Ok(())
85+
}
86+
87+
/// Removes the presence entries for every pubkey in `pubkeys`.
88+
pub async fn clear_presence_many(
89+
pool: &Pool,
90+
ctx: &TenantContext,
91+
pubkeys: &[PublicKey],
92+
) -> Result<(), PubSubError> {
93+
if pubkeys.is_empty() {
94+
return Ok(());
95+
}
96+
let mut conn = pool.get().await?;
97+
let keys: Vec<String> = pubkeys
98+
.iter()
99+
.map(|pubkey| presence_key(ctx, pubkey))
100+
.collect();
101+
redis::cmd("DEL")
102+
.arg(&keys)
103+
.query_async::<()>(&mut conn)
104+
.await?;
105+
Ok(())
106+
}
107+
61108
/// Returns the current presence status for `pubkey`, or `None` if not set or expired.
62109
pub async fn get_presence(
63110
pool: &Pool,
@@ -209,6 +256,50 @@ mod tests {
209256
clear_presence(&pool, &ctx, &pk2).await.unwrap();
210257
}
211258

259+
#[tokio::test]
260+
#[ignore = "requires Redis"]
261+
async fn test_presence_many_sets_with_ttl_and_clears() {
262+
let pool = make_test_pool();
263+
let pk1 = make_pubkey();
264+
let pk2 = make_pubkey();
265+
let untouched = make_pubkey();
266+
let ctx = ctx(0xaaaa, "a.example");
267+
set_presence(&pool, &ctx, &untouched, "away").await.unwrap();
268+
269+
set_presence_many(&pool, &ctx, &[pk1, pk2], "online")
270+
.await
271+
.unwrap();
272+
let result = get_presence_bulk(&pool, &ctx, &[pk1, pk2, untouched])
273+
.await
274+
.unwrap();
275+
assert_eq!(
276+
result.get(&pk1.to_hex()).map(String::as_str),
277+
Some("online")
278+
);
279+
assert_eq!(
280+
result.get(&pk2.to_hex()).map(String::as_str),
281+
Some("online")
282+
);
283+
assert_eq!(
284+
result.get(&untouched.to_hex()).map(String::as_str),
285+
Some("away")
286+
);
287+
let mut conn = pool.get().await.unwrap();
288+
let ttl: i64 = redis::cmd("TTL")
289+
.arg(presence_key(&ctx, &pk2))
290+
.query_async(&mut conn)
291+
.await
292+
.unwrap();
293+
assert!(ttl > 0 && ttl <= PRESENCE_TTL_SECS as i64, "got TTL {ttl}");
294+
295+
clear_presence_many(&pool, &ctx, &[pk1, pk2]).await.unwrap();
296+
let result = get_presence_bulk(&pool, &ctx, &[pk1, pk2, untouched])
297+
.await
298+
.unwrap();
299+
assert_eq!(result.len(), 1, "only the untouched key remains");
300+
clear_presence(&pool, &ctx, &untouched).await.unwrap();
301+
}
302+
212303
#[tokio::test]
213304
#[ignore = "requires Redis"]
214305
async fn test_presence_ttl() {

0 commit comments

Comments
 (0)