Skip to content

Commit 496f3bd

Browse files
feat(acp): report control command outcomes as system rows
Switches the acknowledgement from a kind:9 message to a kind:40099 system message. A cancelled turn or a rotated session is a lifecycle event, not the agent speaking, so it belongs in the grey system row beside "X joined the channel" rather than in the conversation. The row still lands in the thread the command was typed in: client thread placement is derived from NIP-10 `e` tags and is kind-agnostic, so the system message carries the same tags a kind:9 notice did. Payload is `{type, actor, target}` — `actor` the owner who issued the command, `target` the agent it acted on — matching every other system message, so both renderers resolve them to profile names and prefetch their profiles. Six types, one per outcome, including the two no-ops. Adds `buzz_sdk::build_system_message` so the NIP-10 tag construction is shared with `build_message` instead of duplicated in the harness, and cases in both renderers: an unknown `type` is dropped silently by each, so a client older than this contract shows no row at all. That is the one regression against the kind:9 shape, which rendered everywhere. Reverts the `post_failure_notice` rename from the first commit: the kind:9 helper is failure-only again now that control outcomes have their own path. Refs #3711 Co-Authored-By: Claude Opus 5 <[email protected]> Signed-off-by: Bérenger Ouadi <[email protected]>
1 parent 3c05927 commit 496f3bd

7 files changed

Lines changed: 254 additions & 37 deletions

File tree

‎crates/buzz-acp/README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,9 @@ Use `!cancel` to stop only the current turn; it is a no-op when the channel is i
159159

160160
Owner control commands must be kind:9 stream messages from the owner, must mention this agent with a `p` tag, and are consumed by the harness instead of being forwarded to the agent.
161161

162-
Because the command never reaches the agent, the harness posts the outcome back into the channel as a kind:9 notice — including when the command was a no-op (`!cancel` with no turn in flight, `!rotate` with no cached session), so a command that changed nothing is distinguishable from one that was never received.
162+
Because the command never reaches the agent, the harness publishes the outcome back into the channel as a kind:40099 system message — the grey row clients render beside "X joined the channel", since a cancelled turn or a rotated session is a lifecycle event rather than the agent speaking. It lands in the thread the command was typed in, and it is published for the no-op outcomes too (`!cancel` with no turn in flight, `!rotate` with no cached session), so a command that changed nothing stays distinguishable from one that was never received.
163+
164+
The payload is `{"type": …, "actor": <owner>, "target": <agent>}`. Clients switch on `type` and silently drop an unknown one, so a client older than this contract shows no row at all.
163165

164166
> **Note:** The default mode is `owner-only`. Agents without a registered `agent_owner_pubkey` will not respond to any events until the owner is resolved. Set `--respond-to anyone` to disable the gate entirely.
165167

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

Lines changed: 93 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2047,11 +2047,15 @@ async fn tokio_main() -> Result<()> {
20472047
// Awaited, not spawned: the harness is
20482048
// about to exit, and a spawned task
20492049
// would race the shutdown.
2050-
pool::post_notice(
2050+
pool::post_system_notice(
20512051
&ctx.rest_client,
20522052
buzz_event.channel_id,
20532053
&queue::parse_thread_tags(&buzz_event.event),
2054-
"Shutting down.",
2054+
&control_notice_payload(
2055+
NOTICE_SHUTDOWN,
2056+
owner,
2057+
&pubkey_hex,
2058+
),
20552059
)
20562060
.await;
20572061
let _ = shutdown_tx.send(());
@@ -2095,10 +2099,12 @@ async fn tokio_main() -> Result<()> {
20952099
&buzz_event.event,
20962100
buzz_event.channel_id,
20972101
if fired {
2098-
"Cancelled the current turn."
2102+
NOTICE_TURN_CANCELLED
20992103
} else {
2100-
"Nothing to cancel — no turn in flight."
2104+
NOTICE_TURN_CANCEL_NOOP
21012105
},
2106+
owner,
2107+
&pubkey_hex,
21022108
);
21032109
continue; // consume event — do NOT push to queue
21042110
}
@@ -2137,21 +2143,23 @@ async fn tokio_main() -> Result<()> {
21372143
channel_id = %buzz_event.channel_id,
21382144
"!rotate received — cancelling in-flight turn and rotating session"
21392145
);
2140-
"Cancelled the current turn — the next one starts from a fresh session."
2146+
NOTICE_SESSION_ROTATED_IN_FLIGHT
21412147
} else {
21422148
let invalidated = pool.invalidate_channel_sessions(buzz_event.channel_id);
21432149
tracing::info!(
21442150
channel_id = %buzz_event.channel_id,
21452151
invalidated,
21462152
"!rotate received — invalidated idle channel session(s)"
21472153
);
2148-
rotate_idle_notice(invalidated)
2154+
rotate_idle_notice_type(invalidated)
21492155
};
21502156
spawn_control_notice(
21512157
&ctx.rest_client,
21522158
&buzz_event.event,
21532159
buzz_event.channel_id,
21542160
notice,
2161+
owner,
2162+
&pubkey_hex,
21552163
);
21562164
continue; // consume event — do NOT push to queue
21572165
}
@@ -3074,13 +3082,44 @@ fn spawn_failure_notice(
30743082
let rest = rest.clone();
30753083
let channel_id = batch.channel_id;
30763084
tokio::spawn(async move {
3077-
pool::post_notice(&rest, channel_id, &thread_tags, &content).await;
3085+
pool::post_failure_notice(&rest, channel_id, &thread_tags, &content).await;
30783086
});
30793087
}
30803088
}
30813089

3082-
/// Spawn a task that posts the outcome of a consumed owner control command
3083-
/// back into the channel it came from.
3090+
/// `type` values of the kind:40099 system message reporting the outcome of a
3091+
/// consumed owner control command.
3092+
///
3093+
/// The renderers switch on these strings and drop an unknown one silently
3094+
/// (`describeSystemEvent` in `SystemMessageRow.tsx`, `SystemEvent.fromContent`
3095+
/// in `timeline_message.dart`), so adding a variant here means adding a case in
3096+
/// both.
3097+
const NOTICE_SHUTDOWN: &str = "agent_shutdown";
3098+
const NOTICE_TURN_CANCELLED: &str = "agent_turn_cancelled";
3099+
const NOTICE_TURN_CANCEL_NOOP: &str = "agent_turn_cancel_noop";
3100+
const NOTICE_SESSION_ROTATED_IN_FLIGHT: &str = "agent_session_rotated_in_flight";
3101+
const NOTICE_SESSION_ROTATED: &str = "agent_session_rotated";
3102+
const NOTICE_SESSION_ROTATE_NOOP: &str = "agent_session_rotate_noop";
3103+
3104+
/// Build the system-message payload for a consumed owner control command.
3105+
///
3106+
/// `actor` is the owner who issued the command, `target` the agent it acted on
3107+
/// — the same two fields every other system message uses, so the clients
3108+
/// resolve both to profile names and prefetch their profiles.
3109+
fn control_notice_payload(
3110+
notice_type: &str,
3111+
owner_hex: &str,
3112+
agent_hex: &str,
3113+
) -> serde_json::Value {
3114+
serde_json::json!({
3115+
"type": notice_type,
3116+
"actor": owner_hex,
3117+
"target": agent_hex,
3118+
})
3119+
}
3120+
3121+
/// Spawn a task that publishes the outcome of a consumed owner control command
3122+
/// into the channel it came from.
30843123
///
30853124
/// Control commands are consumed by the harness and never reach the agent, so
30863125
/// this notice is the only signal the owner gets. Without it a successful
@@ -3090,25 +3129,28 @@ fn spawn_control_notice(
30903129
rest_client: &relay::RestClient,
30913130
event: &nostr::Event,
30923131
channel_id: Uuid,
3093-
content: &'static str,
3132+
notice_type: &'static str,
3133+
owner_hex: &str,
3134+
agent_hex: &str,
30943135
) {
30953136
let thread_tags = queue::parse_thread_tags(event);
3137+
let payload = control_notice_payload(notice_type, owner_hex, agent_hex);
30963138
let rest = rest_client.clone();
30973139
tokio::spawn(async move {
3098-
pool::post_notice(&rest, channel_id, &thread_tags, content).await;
3140+
pool::post_system_notice(&rest, channel_id, &thread_tags, &payload).await;
30993141
});
31003142
}
31013143

3102-
/// Notice for a `!rotate` that found no turn in flight.
3144+
/// Notice type for a `!rotate` that found no turn in flight.
31033145
///
31043146
/// `invalidated` is how many cached sessions were dropped. Zero means there was
31053147
/// nothing to rotate — the next turn was already going to start fresh. Saying
31063148
/// so explicitly is the point: a silent no-op reads as a broken command.
3107-
fn rotate_idle_notice(invalidated: usize) -> &'static str {
3149+
fn rotate_idle_notice_type(invalidated: usize) -> &'static str {
31083150
if invalidated > 0 {
3109-
"Session rotated — the next turn starts fresh."
3151+
NOTICE_SESSION_ROTATED
31103152
} else {
3111-
"No session to rotate — the next turn already starts fresh."
3153+
NOTICE_SESSION_ROTATE_NOOP
31123154
}
31133155
}
31143156

@@ -4406,17 +4448,43 @@ mod owner_control_command_tests {
44064448

44074449
#[test]
44084450
fn rotate_idle_notice_distinguishes_a_rotation_from_a_no_op() {
4409-
// The no-op is the case worth wording carefully: nothing was cached, so
4410-
// the command changed nothing, and the notice has to say that rather
4411-
// than claim a rotation that did not happen.
4412-
assert_eq!(
4413-
rotate_idle_notice(0),
4414-
"No session to rotate — the next turn already starts fresh."
4415-
);
4451+
// The no-op is the case worth distinguishing: nothing was cached, so
4452+
// the command changed nothing, and the row has to say that rather than
4453+
// claim a rotation that did not happen.
4454+
assert_eq!(rotate_idle_notice_type(0), NOTICE_SESSION_ROTATE_NOOP);
44164455

4417-
let rotated = rotate_idle_notice(1);
4418-
assert_eq!(rotated, "Session rotated — the next turn starts fresh.");
4419-
assert_eq!(rotate_idle_notice(3), rotated);
4456+
let rotated = rotate_idle_notice_type(1);
4457+
assert_eq!(rotated, NOTICE_SESSION_ROTATED);
4458+
assert_eq!(rotate_idle_notice_type(3), rotated);
4459+
}
4460+
4461+
#[test]
4462+
fn control_notice_payload_names_the_owner_and_the_agent() {
4463+
// `actor` and `target` are the fields every other system message uses,
4464+
// and both renderers resolve them to profile names — swapping them
4465+
// would credit the wrong party for the command in the channel history.
4466+
let owner = "ab".repeat(32);
4467+
let agent = "cd".repeat(32);
4468+
let payload = control_notice_payload(NOTICE_TURN_CANCELLED, &owner, &agent);
4469+
4470+
assert_eq!(payload["type"], NOTICE_TURN_CANCELLED);
4471+
assert_eq!(payload["actor"], owner);
4472+
assert_eq!(payload["target"], agent);
4473+
}
4474+
4475+
#[test]
4476+
fn control_notice_types_are_distinct() {
4477+
// A duplicate would make two different outcomes render the same row.
4478+
let all = [
4479+
NOTICE_SHUTDOWN,
4480+
NOTICE_TURN_CANCELLED,
4481+
NOTICE_TURN_CANCEL_NOOP,
4482+
NOTICE_SESSION_ROTATED_IN_FLIGHT,
4483+
NOTICE_SESSION_ROTATED,
4484+
NOTICE_SESSION_ROTATE_NOOP,
4485+
];
4486+
let unique: std::collections::HashSet<&str> = all.iter().copied().collect();
4487+
assert_eq!(unique.len(), all.len());
44204488
}
44214489

44224490
#[test]

‎crates/buzz-acp/src/pool.rs‎

Lines changed: 49 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3635,11 +3635,51 @@ pub(crate) fn thread_ref_from_tags(thread_tags: &ThreadTags) -> Option<buzz_sdk:
36353635
})
36363636
}
36373637

3638-
/// Best-effort: post a visible notice (kind:9) to a channel — a dead-letter
3639-
/// warning, or the outcome of a consumed owner control command. Replies into
3640-
/// the thread of `thread_tags` when the triggering event was threaded. Errors
3641-
/// are logged and swallowed — the notice must never take down the main loop.
3642-
pub(crate) async fn post_notice(
3638+
/// Best-effort: publish a kind:40099 system message into `channel_id`, signed
3639+
/// with the agent's own key.
3640+
///
3641+
/// Carries the outcome of an owner control command the harness consumed. A
3642+
/// cancelled turn or a rotated session is a lifecycle event, not the agent
3643+
/// speaking, so it renders as a system row beside "X joined the channel"
3644+
/// instead of as a message in the conversation. It still lands in the thread
3645+
/// the command was typed in — thread placement is derived from NIP-10 `e` tags
3646+
/// and is kind-agnostic on the client.
3647+
///
3648+
/// Errors are logged and swallowed: the notice must never take down the main
3649+
/// loop, and must never block the command it reports on.
3650+
pub(crate) async fn post_system_notice(
3651+
rest: &crate::relay::RestClient,
3652+
channel_id: Uuid,
3653+
thread_tags: &ThreadTags,
3654+
payload: &serde_json::Value,
3655+
) {
3656+
let thread_ref = thread_ref_from_tags(thread_tags);
3657+
let builder = match buzz_sdk::build_system_message(channel_id, payload, thread_ref.as_ref()) {
3658+
Ok(b) => b,
3659+
Err(e) => {
3660+
tracing::warn!(channel = %channel_id, "system notice: build failed: {e}");
3661+
return;
3662+
}
3663+
};
3664+
let event = match builder.sign_with_keys(&rest.keys) {
3665+
Ok(e) => e,
3666+
Err(e) => {
3667+
tracing::warn!(channel = %channel_id, "system notice: sign failed: {e}");
3668+
return;
3669+
}
3670+
};
3671+
match tokio::time::timeout(Duration::from_secs(5), rest.submit_event(&event)).await {
3672+
Ok(Ok(_)) => {}
3673+
Ok(Err(e)) => tracing::warn!(channel = %channel_id, "system notice failed: {e}"),
3674+
Err(_) => tracing::warn!(channel = %channel_id, "system notice timed out"),
3675+
}
3676+
}
3677+
3678+
/// Best-effort: post a visible failure notice (kind:9) to a channel after a
3679+
/// batch is dead-lettered. Replies into the thread of `thread_tags` when the
3680+
/// triggering event was threaded. Errors are logged and swallowed — the
3681+
/// notice must never take down the main loop.
3682+
pub(crate) async fn post_failure_notice(
36433683
rest: &crate::relay::RestClient,
36443684
channel_id: Uuid,
36453685
thread_tags: &ThreadTags,
@@ -3650,21 +3690,21 @@ pub(crate) async fn post_notice(
36503690
match buzz_sdk::build_message(channel_id, content, thread_ref.as_ref(), &[], false, &[]) {
36513691
Ok(b) => b,
36523692
Err(e) => {
3653-
tracing::warn!(channel = %channel_id, "notice: build failed: {e}");
3693+
tracing::warn!(channel = %channel_id, "failure notice: build failed: {e}");
36543694
return;
36553695
}
36563696
};
36573697
let event = match builder.sign_with_keys(&rest.keys) {
36583698
Ok(e) => e,
36593699
Err(e) => {
3660-
tracing::warn!(channel = %channel_id, "notice: sign failed: {e}");
3700+
tracing::warn!(channel = %channel_id, "failure notice: sign failed: {e}");
36613701
return;
36623702
}
36633703
};
36643704
match tokio::time::timeout(Duration::from_secs(5), rest.submit_event(&event)).await {
36653705
Ok(Ok(_)) => {}
3666-
Ok(Err(e)) => tracing::warn!(channel = %channel_id, "notice failed: {e}"),
3667-
Err(_) => tracing::warn!(channel = %channel_id, "notice timed out"),
3706+
Ok(Err(e)) => tracing::warn!(channel = %channel_id, "failure notice failed: {e}"),
3707+
Err(_) => tracing::warn!(channel = %channel_id, "failure notice timed out"),
36683708
}
36693709
}
36703710

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -433,7 +433,9 @@ pub const KIND_STREAM_REMINDER: u32 = 40007;
433433
pub const KIND_STREAM_MESSAGE_DIFF: u32 = 40008;
434434
/// Canvas (shared document) for a channel.
435435
pub const KIND_CANVAS: u32 = 40100;
436-
/// System message for channel state changes (join, leave, rename, etc.).
436+
/// System message for channel state changes (join, leave, rename, etc.),
437+
/// and for the outcome of an owner control command consumed by the ACP
438+
/// harness. Relay-signed for channel state; agent-signed for the latter.
437439
pub const KIND_SYSTEM_MESSAGE: u32 = 40099;
438440

439441
// Relay-only sidecar kinds (never client-submitted)

‎crates/buzz-sdk/src/builders.rs‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
//! Typed event builder functions (38 builders).
1+
//! Typed event builder functions (39 builders).
22
//!
33
//! All functions return `Result<nostr::EventBuilder, SdkError>`.
44
//! The caller signs: `builder.sign_with_keys(&keys)?`.
@@ -237,6 +237,35 @@ pub fn build_message(
237237
Ok(EventBuilder::new(Kind::Custom(9), content).tags(tags))
238238
}
239239

240+
/// Build a system message (kind 40099) for a channel.
241+
///
242+
/// System messages carry a JSON payload whose `type` field clients switch on to
243+
/// render a system row — a channel lifecycle event such as a membership change,
244+
/// or the outcome of an owner control command consumed by the harness — instead
245+
/// of a message in the conversation. Unknown `type` values are dropped by the
246+
/// clients, so a new one needs matching cases in the renderers.
247+
///
248+
/// `thread_ref` places the row in the thread that triggered it; `None` posts it
249+
/// at channel level. Thread placement is derived from NIP-10 `e` tags and is
250+
/// kind-agnostic on the client, so this threads exactly like [`build_message`].
251+
pub fn build_system_message(
252+
channel_id: Uuid,
253+
payload: &serde_json::Value,
254+
thread_ref: Option<&ThreadRef>,
255+
) -> Result<EventBuilder, SdkError> {
256+
let content = payload.to_string();
257+
check_content(&content, 64 * 1024)?;
258+
let mut tags = vec![tag(&["h", &channel_id.to_string()])?];
259+
if let Some(tr) = thread_ref {
260+
thread_tags(tr, &mut tags)?;
261+
}
262+
Ok(EventBuilder::new(
263+
Kind::Custom(buzz_core::kind::KIND_SYSTEM_MESSAGE as u16),
264+
content,
265+
)
266+
.tags(tags))
267+
}
268+
240269
/// Build an encrypted agent observer frame (kind 24200).
241270
///
242271
/// `recipient_pubkey` is the cleartext `p` tag used by the relay for owner-only

‎desktop/src/features/messages/ui/SystemMessageRow.tsx‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -574,6 +574,53 @@ function describeSystemEvent(
574574
),
575575
};
576576
}
577+
// Owner control commands consumed by the ACP harness (`!shutdown`,
578+
// `!cancel`, `!rotate`). The command never reaches the agent, so this row
579+
// is the only signal it took effect — including when it changed nothing,
580+
// which is why the no-op outcomes get their own wording instead of being
581+
// dropped. Published by the harness, not the relay; see `buzz-acp`.
582+
case "agent_shutdown":
583+
if (!payload.actor || !payload.target) return null;
584+
return {
585+
title: actorName,
586+
action: <>shut down {targetName}</>,
587+
};
588+
case "agent_turn_cancelled":
589+
if (!payload.actor || !payload.target) return null;
590+
return {
591+
title: actorName,
592+
action: <>cancelled {targetName}&rsquo;s current turn</>,
593+
};
594+
case "agent_turn_cancel_noop":
595+
if (!payload.actor || !payload.target) return null;
596+
return {
597+
title: actorName,
598+
action: (
599+
<>tried to cancel {targetName}&rsquo;s turn — nothing was running</>
600+
),
601+
};
602+
case "agent_session_rotated_in_flight":
603+
if (!payload.actor || !payload.target) return null;
604+
return {
605+
title: actorName,
606+
action: (
607+
<>cancelled {targetName}&rsquo;s turn and rotated its session</>
608+
),
609+
};
610+
case "agent_session_rotated":
611+
if (!payload.actor || !payload.target) return null;
612+
return {
613+
title: actorName,
614+
action: <>rotated {targetName}&rsquo;s session</>,
615+
};
616+
case "agent_session_rotate_noop":
617+
if (!payload.actor || !payload.target) return null;
618+
return {
619+
title: actorName,
620+
action: (
621+
<>rotated {targetName}&rsquo;s session — it was already fresh</>
622+
),
623+
};
577624
case "member_left":
578625
return {
579626
title: actorName,

0 commit comments

Comments
 (0)