Skip to content

Commit 2093ef5

Browse files
gilgtmg.s.opusclaude
authored
feat(acp): stop one thread with cancel_thread_turn (#10002)
## Summary Adds a new observer control type, `cancel_thread_turn`, that stops the agent's turn in one thread of a channel. `buzz-acp` stops the session that serves that thread through the same scope-exact path an owner's `!cancel` in the thread uses (`signal_in_flight_task_for_scope`). A channel running several thread sessions therefore no longer answers `ambiguous_target` to a stop aimed at one of them. `cancel_turn` stays channel-only, and its behavior is unchanged. Details: - Payload: `{ "type": "cancel_thread_turn", "channelId", "threadRootId", "requestId" }`. `threadRootId` is required. It is parsed as an event id and lowercased, the form scope keys use. A missing or malformed `threadRootId` drops the frame without an answer, as a missing `channelId` already does. - It is a separate type rather than a field on `cancel_turn` because an older harness reads only `channelId` from `cancel_turn`. Sent to such a harness, a threaded `cancel_turn` could stop another thread's turn in that channel. An older harness ignores the unknown `cancel_thread_turn` type instead, and the sender times out. `cancel_turn` ignores any `threadRootId`. - Target: the thread's `Thread` scope. A threaded stop reaches the channel's `Conversation` scope only when the channel is known to run as one conversation: under the channel session policy, or in a channel whose cached metadata says it is a DM. Under the thread policy, a `Conversation` scope can also come from a metadata miss, because the DM check fails closed, and that turn may belong to another thread. - Answer: a `control_result` with `{ type: "cancel_thread_turn", status, requestId }`. `status` is `sent` (the task received the signal; the turn may not have ended yet) or `no_active_turn` (no turn ran there, or it was already stopping). Both signal helpers now report `sent` only when the task actually received the signal, not when its receiver was already dropped. `docs/nips/NIP-AO.md` now documents the control contract the code implements: - `cancel_turn` and `cancel_thread_turn`, with their fields and statuses. - The `control_result` telemetry frame, and the `batch` frame that can carry it. - The two other control types already handled, `switch_model` and `publish_project_owner_announcements`, with their fields and results. The relay subscription text is untouched. This is one part of making Stop work for an agent that runs on another of the owner's devices. Senders use `cancel_thread_turn` for threaded conversations. ### Related issue None found. ### Testing - `cargo test -p buzz-acp`: all pass (1090 lib tests). - Tests in `owner_control_command_tests`: - `cancel_thread_turn_stops_only_that_thread`. Setup: two thread sessions in one channel. Results: - A stop with thread A's root, in uppercase, signals only A and answers `sent`. - A thread with no turn answers `no_active_turn`. - A again, after its signal is spent, answers `no_active_turn`. - A malformed, null or missing root gets no answer and signals nothing. - A `cancel_turn` carrying thread B's root stays channel-wide: it answers `ambiguous_target` and leaves B untouched. - `cancel_thread_turn_reaches_a_conversation_only_when_the_channel_is_one`: - A conversation-scoped channel's one turn is stopped. - A thread-policy channel where one thread fell back to a `Conversation` scope: stops for the other thread never reach that turn. - A task whose receiver was already dropped answers `no_active_turn`. - `cargo clippy -p buzz-acp --all-targets -- -D warnings` and `cargo fmt --check` are clean. - The end-to-end macOS validation on this PR (issuecomment-7232802009) ran before the move to `cancel_thread_turn`, so it covers the earlier `cancel_turn` + `threadRootId` frame. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Gil Birman <gil@squareup.com> Co-authored-by: g.s.opus <182de044fe08d24f64d005f425861956d29456fffb812544e93ed39df003b4d1@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 1866c0c commit 2093ef5

3 files changed

Lines changed: 493 additions & 25 deletions

File tree

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

Lines changed: 284 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1879,6 +1879,7 @@ fn handle_relay_observer_control_event(
18791879
observer: Option<&observer::ObserverHandle>,
18801880
owner_pubkey_hex: &str,
18811881
event_publisher: RelayEventPublisher,
1882+
conversation_scoped: &dyn Fn(Uuid) -> bool,
18821883
) {
18831884
// Defense-in-depth: verify signature even though the relay already checked.
18841885
if let Err(e) = buzz_core::verify_event(&event) {
@@ -1921,6 +1922,9 @@ fn handle_relay_observer_control_event(
19211922
Some("cancel_turn") => {
19221923
handle_cancel_turn_control(&payload, pool, observer);
19231924
}
1925+
Some("cancel_thread_turn") => {
1926+
handle_cancel_thread_turn_control(&payload, pool, observer, conversation_scoped);
1927+
}
19241928
Some("switch_model") => {
19251929
handle_switch_model_control(&payload, pool, observer);
19261930
}
@@ -2080,18 +2084,18 @@ fn emit_project_owner_control_result(
20802084
);
20812085
}
20822086

2083-
/// Handle a `cancel_turn` control frame: signal the in-flight task to cancel.
2087+
/// Handle a `cancel_turn` control frame: signal the channel's in-flight task to
2088+
/// cancel, refusing a channel with several scopes.
2089+
///
2090+
/// Channel-only: a `threadRootId` on the frame is ignored. Thread-targeted stops
2091+
/// use `cancel_thread_turn`, so a harness that predates it drops them instead
2092+
/// of stopping another thread's turn.
20842093
fn handle_cancel_turn_control(
20852094
payload: &serde_json::Value,
20862095
pool: &mut AgentPool,
20872096
observer: Option<&observer::ObserverHandle>,
20882097
) {
2089-
let Some(channel_id) = payload
2090-
.get("channelId")
2091-
.and_then(|value| value.as_str())
2092-
.and_then(|value| value.parse::<Uuid>().ok())
2093-
else {
2094-
tracing::warn!("observer cancel_turn control frame missing valid channelId");
2098+
let Some(channel_id) = control_channel_id(payload, "cancel_turn") else {
20952099
return;
20962100
};
20972101

@@ -2102,6 +2106,79 @@ fn handle_cancel_turn_control(
21022106
} else {
21032107
"no_active_turn"
21042108
};
2109+
emit_cancel_control_result(observer, channel_id, "cancel_turn", status, payload);
2110+
}
2111+
2112+
/// Handle a `cancel_thread_turn` control frame: signal the in-flight task for
2113+
/// one thread to cancel, scope-exact, as an owner's `!cancel` in the thread
2114+
/// does, so it can never be ambiguous. A frame without a valid `threadRootId`
2115+
/// is dropped unanswered.
2116+
///
2117+
/// `conversation_scoped` tells whether events in a channel are known to share
2118+
/// the channel's one `Conversation` scope: the channel session policy, or a
2119+
/// channel whose metadata says it is a DM. Only then may a threaded stop reach
2120+
/// a `Conversation` turn. Under the thread policy a `Conversation` scope can
2121+
/// also come from a metadata miss (the DM check fails closed), and that turn
2122+
/// may belong to another thread.
2123+
fn handle_cancel_thread_turn_control(
2124+
payload: &serde_json::Value,
2125+
pool: &mut AgentPool,
2126+
observer: Option<&observer::ObserverHandle>,
2127+
conversation_scoped: &dyn Fn(Uuid) -> bool,
2128+
) {
2129+
let Some(channel_id) = control_channel_id(payload, "cancel_thread_turn") else {
2130+
return;
2131+
};
2132+
// Lowercase hex, the form scope keys use.
2133+
let Some(root_event_id) = payload
2134+
.get("threadRootId")
2135+
.and_then(|value| value.as_str())
2136+
.and_then(|id| nostr::EventId::from_hex(id).ok())
2137+
.map(|root| root.to_hex())
2138+
else {
2139+
tracing::warn!("observer cancel_thread_turn control frame missing valid threadRootId");
2140+
return;
2141+
};
2142+
2143+
// The scope `SessionScope::derive` gives an event in this thread.
2144+
let target = if conversation_scoped(channel_id) {
2145+
scope::SessionScope::Conversation { channel_id }
2146+
} else {
2147+
scope::SessionScope::Thread {
2148+
channel_id,
2149+
root_event_id,
2150+
}
2151+
};
2152+
let status = if signal_in_flight_task_for_scope(pool, &target, ControlSignal::Cancel) {
2153+
"sent"
2154+
} else {
2155+
"no_active_turn"
2156+
};
2157+
emit_cancel_control_result(observer, channel_id, "cancel_thread_turn", status, payload);
2158+
}
2159+
2160+
/// The `channelId` of a control frame, or `None` (logged) when it is missing
2161+
/// or not a UUID.
2162+
fn control_channel_id(payload: &serde_json::Value, command_type: &str) -> Option<Uuid> {
2163+
let channel_id = payload
2164+
.get("channelId")
2165+
.and_then(|value| value.as_str())
2166+
.and_then(|value| value.parse::<Uuid>().ok());
2167+
if channel_id.is_none() {
2168+
tracing::warn!("observer {command_type} control frame missing valid channelId");
2169+
}
2170+
channel_id
2171+
}
2172+
2173+
/// Answer a cancel control frame with a `control_result` echoing its
2174+
/// `requestId`.
2175+
fn emit_cancel_control_result(
2176+
observer: Option<&observer::ObserverHandle>,
2177+
channel_id: Uuid,
2178+
command_type: &str,
2179+
status: &str,
2180+
payload: &serde_json::Value,
2181+
) {
21052182
if let Some(observer) = observer {
21062183
observer.emit(
21072184
"control_result",
@@ -2113,7 +2190,7 @@ fn handle_cancel_turn_control(
21132190
started_at: None,
21142191
},
21152192
serde_json::json!({
2116-
"type": "cancel_turn",
2193+
"type": command_type,
21172194
"status": status,
21182195
"requestId": payload.get("requestId"),
21192196
}),
@@ -3462,6 +3539,11 @@ async fn run_harness(
34623539
observer.as_ref(),
34633540
owner_hex,
34643541
relay.event_publisher(),
3542+
&|channel_id| {
3543+
config.session_policy == scope::SessionPolicy::Channel
3544+
|| ctx.channel_info.cached_channel_type(channel_id).as_deref()
3545+
== Some("dm")
3546+
},
34653547
);
34663548
} else {
34673549
tracing::warn!("observer control frame received but no owner resolved — dropping");
@@ -4497,15 +4579,17 @@ fn mode_gate_signal(
44974579
/// Send a control signal to the in-flight task for `channel_id`.
44984580
///
44994581
/// Channel-targeted: refuses channels with multiple session scopes. Used only
4500-
/// by desktop observer frames (`cancel_turn` / `switch_model`), which carry a
4501-
/// bare `channelId` and no thread context. Every thread-aware
4502-
/// path — mid-turn steering/interruption and the owner `!cancel` / `!rotate`
4503-
/// commands, whose triggering event carries NIP-10 thread tags — uses
4582+
/// by observer control frames that carry a bare `channelId` and no thread
4583+
/// context (`cancel_turn` and `switch_model`). Every thread-aware path —
4584+
/// mid-turn steering/interruption, the owner `!cancel` / `!rotate` commands,
4585+
/// whose triggering event carries NIP-10 thread tags, and the
4586+
/// `cancel_thread_turn` frame — uses
45044587
/// [`signal_in_flight_task_for_scope`], which targets one exact
45054588
/// [`scope::SessionScope`] so a signal for thread A can never hit thread B
45064589
/// running in the same channel.
45074590
///
4508-
/// Returns `true` if a signal was sent, `false` if no in-flight task was found.
4591+
/// Returns `true` if the task received a signal, `false` if no in-flight task
4592+
/// was found or it had already stopped listening.
45094593
fn signal_in_flight_task(
45104594
pool: &mut AgentPool,
45114595
channel_id: uuid::Uuid,
@@ -4522,8 +4606,8 @@ fn signal_in_flight_task(
45224606
if let Some(meta) = entry {
45234607
if let Some(tx) = meta.control_tx.take() {
45244608
tracing::info!(channel = %channel_id, ?mode, "control signal sent to in-flight task");
4525-
let _ = tx.send(mode);
4526-
return true;
4609+
// A finishing task may already have dropped its receiver.
4610+
return tx.send(mode).is_ok();
45274611
}
45284612
}
45294613
false
@@ -4536,7 +4620,8 @@ fn signal_in_flight_task(
45364620
/// “whichever task the channel happens to have first” — otherwise two threads
45374621
/// running concurrently in one channel could steer each other.
45384622
///
4539-
/// Returns `true` if a signal was sent, `false` if no in-flight task matched.
4623+
/// Returns `true` if the task received a signal, `false` if no in-flight task
4624+
/// matched or it had already stopped listening.
45404625
fn signal_in_flight_task_for_scope(
45414626
pool: &mut AgentPool,
45424627
scope: &scope::SessionScope,
@@ -4555,8 +4640,8 @@ fn signal_in_flight_task_for_scope(
45554640
?mode,
45564641
"control signal sent to in-flight task (scope-exact)"
45574642
);
4558-
let _ = tx.send(mode);
4559-
return true;
4643+
// A finishing task may already have dropped its receiver.
4644+
return tx.send(mode).is_ok();
45604645
}
45614646
}
45624647
false
@@ -6829,6 +6914,187 @@ mod owner_control_command_tests {
68296914
}
68306915
}
68316916

6917+
#[tokio::test]
6918+
async fn cancel_thread_turn_stops_only_that_thread() {
6919+
let mut pool = AgentPool::from_slots(vec![]);
6920+
let ch = Uuid::new_v4();
6921+
let (root_a, root_b) = ("a".repeat(64), "b".repeat(64));
6922+
let (tx_a, mut rx_a) = tokio::sync::oneshot::channel();
6923+
let (tx_b, mut rx_b) = tokio::sync::oneshot::channel();
6924+
insert_task_meta(&mut pool, 0, thread_scope(ch, &root_a), tx_a);
6925+
insert_task_meta(&mut pool, 1, thread_scope(ch, &root_b), tx_b);
6926+
let observer = observer::ObserverHandle::in_process();
6927+
let cancel = |root: serde_json::Value, request_id: &str| {
6928+
serde_json::json!({
6929+
"type": "cancel_thread_turn", "channelId": ch.to_string(),
6930+
"threadRootId": root, "requestId": request_id,
6931+
})
6932+
};
6933+
6934+
// Thread A, spelled in uppercase as NIP-10 allows: only A is cancelled.
6935+
handle_cancel_thread_turn_control(
6936+
&cancel(root_a.to_uppercase().into(), "stop-a"),
6937+
&mut pool,
6938+
Some(&observer),
6939+
&|_| false,
6940+
);
6941+
assert_eq!(rx_a.try_recv(), Ok(ControlSignal::Cancel));
6942+
assert_eq!(
6943+
rx_b.try_recv(),
6944+
Err(tokio::sync::oneshot::error::TryRecvError::Empty)
6945+
);
6946+
6947+
// A thread with no turn, and A again once its signal is spent.
6948+
handle_cancel_thread_turn_control(
6949+
&cancel("c".repeat(64).into(), "stop-c"),
6950+
&mut pool,
6951+
Some(&observer),
6952+
&|_| false,
6953+
);
6954+
handle_cancel_thread_turn_control(
6955+
&cancel(root_a.into(), "stop-a2"),
6956+
&mut pool,
6957+
Some(&observer),
6958+
&|_| false,
6959+
);
6960+
// A malformed or missing root is dropped without an answer or a signal.
6961+
for root in ["zz".into(), serde_json::Value::Null] {
6962+
handle_cancel_thread_turn_control(
6963+
&cancel(root, "bad"),
6964+
&mut pool,
6965+
Some(&observer),
6966+
&|_| false,
6967+
);
6968+
}
6969+
handle_cancel_thread_turn_control(
6970+
&serde_json::json!({ "channelId": ch.to_string(), "requestId": "bad" }),
6971+
&mut pool,
6972+
Some(&observer),
6973+
&|_| false,
6974+
);
6975+
assert_eq!(
6976+
rx_b.try_recv(),
6977+
Err(tokio::sync::oneshot::error::TryRecvError::Empty)
6978+
);
6979+
6980+
let results: Vec<_> = observer
6981+
.snapshot()
6982+
.into_iter()
6983+
.map(|result| {
6984+
assert_eq!(result.kind, "control_result");
6985+
assert_eq!(result.channel_id, Some(ch.to_string()));
6986+
assert_eq!(result.payload["type"], "cancel_thread_turn");
6987+
(
6988+
result.payload["requestId"].as_str().unwrap().to_string(),
6989+
result.payload["status"].as_str().unwrap().to_string(),
6990+
)
6991+
})
6992+
.collect();
6993+
let expected = [
6994+
("stop-a", "sent"),
6995+
("stop-c", "no_active_turn"),
6996+
("stop-a2", "no_active_turn"),
6997+
]
6998+
.map(|(id, status)| (id.to_string(), status.to_string()));
6999+
assert_eq!(results, expected);
7000+
7001+
// `cancel_turn` stays channel-wide and ignores a thread root, so the
7002+
// two threads make it ambiguous and B is still not signalled.
7003+
handle_cancel_turn_control(
7004+
&serde_json::json!({
7005+
"type": "cancel_turn", "channelId": ch.to_string(),
7006+
"threadRootId": root_b, "requestId": "stop-all",
7007+
}),
7008+
&mut pool,
7009+
Some(&observer),
7010+
);
7011+
assert_eq!(
7012+
observer.snapshot().last().unwrap().payload["status"],
7013+
"ambiguous_target"
7014+
);
7015+
assert_eq!(
7016+
rx_b.try_recv(),
7017+
Err(tokio::sync::oneshot::error::TryRecvError::Empty)
7018+
);
7019+
}
7020+
7021+
#[tokio::test]
7022+
async fn cancel_thread_turn_reaches_a_conversation_only_when_the_channel_is_one() {
7023+
let observer = observer::ObserverHandle::in_process();
7024+
let stop = |ch: Uuid, root: &str| {
7025+
serde_json::json!({
7026+
"type": "cancel_thread_turn", "channelId": ch.to_string(),
7027+
"threadRootId": root, "requestId": "stop",
7028+
})
7029+
};
7030+
let last_status = || {
7031+
observer.snapshot().last().unwrap().payload["status"]
7032+
.as_str()
7033+
.unwrap()
7034+
.to_string()
7035+
};
7036+
7037+
// Channel policy or a known DM: every thread runs in the channel's one
7038+
// conversation, which `!cancel` from any thread would stop too.
7039+
let mut pool = AgentPool::from_slots(vec![]);
7040+
let ch = Uuid::new_v4();
7041+
let (tx, mut rx) = tokio::sync::oneshot::channel();
7042+
insert_task_meta(
7043+
&mut pool,
7044+
0,
7045+
scope::SessionScope::Conversation { channel_id: ch },
7046+
tx,
7047+
);
7048+
handle_cancel_thread_turn_control(
7049+
&stop(ch, &"d".repeat(64)),
7050+
&mut pool,
7051+
Some(&observer),
7052+
&|c| c == ch,
7053+
);
7054+
assert_eq!(rx.try_recv(), Ok(ControlSignal::Cancel));
7055+
assert_eq!(last_status(), "sent");
7056+
7057+
// Thread policy after a metadata miss: thread A was admitted as the
7058+
// channel's conversation, and thread B runs in its own scope. Stops
7059+
// for B never fall through to A, even once B's signal is spent.
7060+
let mut pool = AgentPool::from_slots(vec![]);
7061+
let ch = Uuid::new_v4();
7062+
let root_b = "b".repeat(64);
7063+
let (tx_a, mut rx_a) = tokio::sync::oneshot::channel();
7064+
let (tx_b, mut rx_b) = tokio::sync::oneshot::channel();
7065+
insert_task_meta(
7066+
&mut pool,
7067+
0,
7068+
scope::SessionScope::Conversation { channel_id: ch },
7069+
tx_a,
7070+
);
7071+
insert_task_meta(&mut pool, 1, thread_scope(ch, &root_b), tx_b);
7072+
handle_cancel_thread_turn_control(&stop(ch, &root_b), &mut pool, Some(&observer), &|_| {
7073+
false
7074+
});
7075+
assert_eq!(rx_b.try_recv(), Ok(ControlSignal::Cancel));
7076+
assert_eq!(last_status(), "sent");
7077+
handle_cancel_thread_turn_control(&stop(ch, &root_b), &mut pool, Some(&observer), &|_| {
7078+
false
7079+
});
7080+
assert_eq!(last_status(), "no_active_turn");
7081+
assert_eq!(
7082+
rx_a.try_recv(),
7083+
Err(tokio::sync::oneshot::error::TryRecvError::Empty)
7084+
);
7085+
7086+
// A task that already dropped its receiver while finishing got no
7087+
// signal, so the stop is not reported as sent.
7088+
let root_c = "c".repeat(64);
7089+
let (tx_c, rx_c) = tokio::sync::oneshot::channel();
7090+
insert_task_meta(&mut pool, 2, thread_scope(ch, &root_c), tx_c);
7091+
drop(rx_c);
7092+
handle_cancel_thread_turn_control(&stop(ch, &root_c), &mut pool, Some(&observer), &|_| {
7093+
false
7094+
});
7095+
assert_eq!(last_status(), "no_active_turn");
7096+
}
7097+
68327098
// Fix #2: mid-turn steer/interrupt must target the exact thread scope, not
68337099
// “the first task in the channel” — two threads in one channel must not
68347100
// interrupt each other.

0 commit comments

Comments
 (0)