Notify running turn watchers only on count changes (#38170)

## What changed

- Publish the running-turn count while holding the thread state lock so updates
  remain ordered with their corresponding state mutations.
- Use `watch::Sender::send_if_modified` to avoid waking subscribers when a
  thread status update leaves the count unchanged.

## Testing

- Add a test that verifies turn start and shutdown notify the count watcher,
  while a permission request during the turn does not.

GitOrigin-RevId: 50fe6bcfb2cac7392715263cfdde0f382fe21502
This commit is contained in:
Tamir Duberstein
2026-08-12 11:07:46 +00:00
committed by copyberry
parent 69ae78291d
commit 16fbfe5574
+30 -3
View File
@@ -224,7 +224,7 @@ impl ThreadWatchManager {
where
F: FnOnce(&mut ThreadWatchState) -> Option<ThreadStatusChangedNotification>,
{
let (notification, running_turn_count) = {
let notification = {
let mut state = self.state.lock().await;
let notification = mutate(&mut state);
let running_turn_count = state
@@ -232,9 +232,16 @@ impl ThreadWatchManager {
.values()
.filter(|runtime| runtime.running)
.count();
(notification, running_turn_count)
self.running_turn_count_tx.send_if_modified(|current| {
if *current == running_turn_count {
false
} else {
*current = running_turn_count;
true
}
});
notification
};
let _ = self.running_turn_count_tx.send(running_turn_count);
if let Some(notification) = notification
&& let Some(outgoing) = &self.outgoing
@@ -695,6 +702,26 @@ mod tests {
assert_eq!(manager.running_turn_count().await, 0);
}
#[tokio::test]
async fn running_turn_watch_notifies_only_when_count_changes() {
let manager = ThreadWatchManager::new();
let mut count = manager.subscribe_running_turn_count();
manager.upsert_thread(INTERACTIVE_THREAD_ID).await;
manager.note_turn_started(INTERACTIVE_THREAD_ID).await;
assert!(count.has_changed().expect("watch remains open"));
assert_eq!(*count.borrow_and_update(), 1);
let _permission_guard = manager
.note_permission_requested(INTERACTIVE_THREAD_ID)
.await;
assert!(!count.has_changed().expect("watch remains open"));
manager.note_thread_shutdown(INTERACTIVE_THREAD_ID).await;
assert!(count.has_changed().expect("watch remains open"));
assert_eq!(*count.borrow_and_update(), 0);
}
#[tokio::test]
async fn status_change_emits_notification() {
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(8);