1use std::collections::{HashMap, HashSet};
18use std::sync::{Arc, LazyLock};
19
20use crate::backend::agent_state::AgentState;
21use crate::backend::obj::MetaMapType;
22use crate::backend::work_facts::live_phrase;
23use crate::backend::storage::agents::AgentDefinition;
24use crate::backend::storage::filestore::FileStore;
25use crate::backend::storage::store::Store;
26use crate::backend::storage::work_queue::work_state;
27use crate::backend::wconfig::ConfigState;
28use super::urgent_asks::{self, Ask};
29use super::worker_notes as notes;
30
31pub const SETTING_QUIET_MINUTES: &str = "agents:quietminutes";
33pub const SETTING_QUIET_RUNNING_MINUTES: &str = "agents:quietrunningminutes";
35pub const SETTING_QUIET_ESCALATE_MINUTES: &str = "agents:quietescalateminutes";
37
38const DEFAULT_QUIET_MINUTES: i64 = 15;
39const DEFAULT_QUIET_RUNNING_MINUTES: i64 = 30;
40const DEFAULT_ESCALATE_MINUTES: i64 = 5;
41const NUDGE_SPACING_MS: u64 = 60 * 60_000;
43const BACKGROUND_FACTOR: u64 = 4;
46const SWEEP_EVERY: std::time::Duration = std::time::Duration::from_secs(30);
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub struct Limits {
52 pub quiet_ms: u64,
53 pub running_ms: u64,
54 pub escalate_ms: u64,
55}
56
57pub fn limits_from(extra: &HashMap<String, serde_json::Value>) -> Option<Limits> {
59 let minutes = |key: &str, default: i64| extra.get(key).and_then(|v| v.as_i64()).filter(|m| *m >= 0).unwrap_or(default);
60 let quiet = minutes(SETTING_QUIET_MINUTES, DEFAULT_QUIET_MINUTES);
61 if quiet == 0 {
62 return None;
63 }
64 let ms = |m: i64| (m as u64).saturating_mul(60_000);
65 Some(Limits {
66 quiet_ms: ms(quiet),
67 running_ms: ms(minutes(SETTING_QUIET_RUNNING_MINUTES, DEFAULT_QUIET_RUNNING_MINUTES)),
68 escalate_ms: ms(minutes(SETTING_QUIET_ESCALATE_MINUTES, DEFAULT_ESCALATE_MINUTES)),
69 })
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub struct Reading {
75 pub activity_ms: u64,
78 pub turn_active: bool,
80 pub background: bool,
82}
83
84fn idle_limit(background: bool, lim: &Limits) -> u64 {
86 if background {
87 lim.quiet_ms.saturating_mul(BACKGROUND_FACTOR)
88 } else {
89 lim.quiet_ms
90 }
91}
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub enum Action {
96 Nudge,
98 Tell { running: bool, idle_ms: u64 },
101}
102
103#[derive(Debug, Default)]
104struct Episode {
105 activity_at: u64,
108 nudged_at: Option<u64>,
109 nudge_skipped: bool,
111 told_at: Option<u64>,
112}
113
114#[derive(Debug, Default)]
116pub struct Watch {
117 episodes: HashMap<String, Episode>,
118 last_nudge: HashMap<String, u64>,
119}
120
121impl Watch {
122 pub fn step(&mut self, key: &str, reading: Reading, lim: &Limits, now_ms: u64) -> Option<Action> {
125 let ep = self.episodes.entry(key.to_string()).or_insert_with(|| Episode { activity_at: now_ms.max(reading.activity_ms), ..Episode::default() });
126 if reading.activity_ms > ep.activity_at {
127 *ep = Episode { activity_at: reading.activity_ms, ..Episode::default() };
129 }
130 let idle = now_ms.saturating_sub(ep.activity_at);
131 let may_tell = |ep: &Episode| ep.told_at.is_none();
133 if reading.turn_active {
134 if idle >= lim.running_ms.saturating_add(lim.escalate_ms) && may_tell(ep) {
135 return Some(Action::Tell { running: true, idle_ms: idle });
136 }
137 return None;
138 }
139 if idle < idle_limit(reading.background, lim) {
140 return None;
141 }
142 if reading.background {
143 ep.nudge_skipped = true;
145 }
146 if ep.nudged_at.is_none() && !ep.nudge_skipped {
147 let nudged_lately = self.last_nudge.get(key).is_some_and(|at| now_ms.saturating_sub(*at) < NUDGE_SPACING_MS);
148 if nudged_lately {
149 ep.nudge_skipped = true;
150 } else {
151 ep.nudged_at = Some(now_ms);
152 self.last_nudge.insert(key.to_string(), now_ms);
153 return Some(Action::Nudge);
154 }
155 }
156 let due = ep.nudge_skipped || ep.nudged_at.is_some_and(|at| now_ms.saturating_sub(at) >= lim.escalate_ms);
157 if due && may_tell(ep) {
158 return Some(Action::Tell { running: false, idle_ms: idle });
159 }
160 None
161 }
162
163 pub fn quiet_since(&self, key: &str, turn_active: bool, background: bool, lim: &Limits, now_ms: u64) -> Option<u64> {
167 let at = self.episodes.get(key)?.activity_at;
168 let limit = if turn_active { lim.running_ms } else { idle_limit(background, lim) };
169 (now_ms.saturating_sub(at) >= limit).then_some(at)
170 }
171
172 pub fn mark_told(&mut self, key: &str, now_ms: u64) {
176 if let Some(ep) = self.episodes.get_mut(key) {
177 ep.told_at = Some(now_ms);
178 }
179 }
180
181 pub fn retain(&mut self, keep: &HashSet<String>) {
184 self.episodes.retain(|k, _| keep.contains(k));
185 if self.last_nudge.len() > 512 {
186 let cutoff = agentmux_common::time::now_ms_u64().saturating_sub(NUDGE_SPACING_MS);
187 self.last_nudge.retain(|_, at| *at >= cutoff);
188 }
189 }
190}
191
192#[derive(Debug, Clone, PartialEq, Eq)]
194pub struct QuietView {
195 pub since_ms: u64,
197 pub tasks: Vec<i64>,
199 pub watchers: Vec<String>,
201}
202
203static QUIET: std::sync::LazyLock<parking_lot::Mutex<HashMap<String, QuietView>>> = std::sync::LazyLock::new(Default::default);
205
206pub fn quiet_view(def_id: &str) -> Option<QuietView> {
208 QUIET.lock().get(def_id).cloned()
209}
210
211pub const MAX_MUTE_MINUTES: u64 = 240;
213const MUTE_REASON_CHARS: usize = 120;
215
216#[derive(Debug, Clone, PartialEq, Eq)]
218pub struct Mute {
219 pub until_ms: u64,
220 pub reason: String,
222 pub by: String,
224}
225
226static MUTES: LazyLock<parking_lot::Mutex<HashMap<String, Mute>>> = LazyLock::new(Default::default);
229
230pub fn mute(def_id: &str, minutes: u64, reason: &str, by: &str, now_ms: u64) -> Result<Mute, String> {
232 if minutes == 0 || minutes > MAX_MUTE_MINUTES {
233 return Err(format!("minutes must be 1 to {MAX_MUTE_MINUTES} (0 lifts a mute); got {minutes}"));
234 }
235 let reason: String = reason.split_whitespace().collect::<Vec<_>>().join(" ").chars().filter(|c| !c.is_control()).take(MUTE_REASON_CHARS).collect();
236 let muted = Mute { until_ms: now_ms.saturating_add(minutes.saturating_mul(60_000)), reason, by: by.to_string() };
237 MUTES.lock().insert(def_id.to_string(), muted.clone());
238 Ok(muted)
239}
240
241pub fn unmute(def_id: &str, now_ms: u64) -> bool {
243 MUTES.lock().remove(def_id).is_some_and(|m| m.until_ms > now_ms)
244}
245
246pub fn mute_of(def_id: &str, now_ms: u64) -> Option<Mute> {
248 MUTES.lock().get(def_id).filter(|m| m.until_ms > now_ms).cloned()
249}
250
251const ENDED_MUTE_KEPT_MS: u64 = 24 * 60 * 60_000;
254
255fn mute_for_clock(def_id: &str, now_ms: u64) -> Option<Mute> {
258 let mut mutes = MUTES.lock();
259 mutes.retain(|_, m| now_ms.saturating_sub(m.until_ms) < ENDED_MUTE_KEPT_MS);
260 mutes.get(def_id).cloned()
261}
262
263pub fn leads(mstore: &Store, caller: &str, target: &str) -> bool {
266 let seat_lead = crate::backend::agent_seat::effective_seat_by_id(mstore, target).and_then(|seat| seat.lead);
267 seat_lead.as_deref() == Some(caller) || crate::backend::agent_seat::worker_of(mstore, target).as_deref() == Some(caller)
268}
269
270fn held_moved_ms(tasks: &[OwedTask]) -> u64 {
273 tasks.iter().filter(|t| !t.asked).map(|t| t.updated_ms).max().unwrap_or(0)
274}
275
276pub fn holding_for_quota(status: &MetaMapType, quota_tight: bool) -> bool {
280 quota_tight && live_phrase::declared_of(status).is_some_and(|line| line.state.as_deref() == Some("waiting") && line.src == live_phrase::SRC_AGENT)
281}
282
283pub fn paused_activity(status: &MetaMapType, mute: Option<&Mute>, now_ms: u64) -> u64 {
287 let mut at = live_phrase::declared_of(status).map_or(0, |line| line.at_ms);
288 if let Some(until) = live_phrase::waiting_until(status) {
289 at = at.max(until.min(now_ms));
290 }
291 if let Some(m) = mute {
292 at = at.max(m.until_ms.min(now_ms));
293 }
294 at
295}
296
297pub fn callable(state: Option<AgentState>) -> bool {
300 matches!(state, Some(AgentState::Working | AgentState::Idle))
301}
302
303#[derive(Debug, Clone, PartialEq, Eq)]
305pub struct OwedTask {
306 pub num: i64,
307 pub filer_uid: String,
309 pub updated_ms: u64,
311 pub asked: bool,
313}
314
315pub fn claimed_by_holder(items: &[crate::backend::storage::work_board::BoardTask]) -> HashMap<String, Vec<OwedTask>> {
319 let mut out: HashMap<String, Vec<OwedTask>> = HashMap::new();
320 for t in items.iter().filter(|t| t.item.state == work_state::CLAIMED) {
321 let key = if t.item.claimed_by_uid.is_empty() { format!("name:{}", t.item.claimed_by.to_lowercase()) } else { t.item.claimed_by_uid.clone() };
322 let moved = t.item.updated_at.max(t.card.updated_at).max(0) as u64;
323 out.entry(key).or_default().push(OwedTask { num: t.card.num, filer_uid: t.item.created_by_uid.clone(), updated_ms: moved, asked: false });
324 }
325 out.values_mut().for_each(|v| v.sort_by_key(|t| t.num));
326 out
327}
328
329pub fn owed_by(claimed: &HashMap<String, Vec<OwedTask>>, def: &AgentDefinition) -> Vec<OwedTask> {
331 let mut tasks: Vec<OwedTask> = claimed.get(&def.id).cloned().unwrap_or_default();
332 for name in [def.slug.to_lowercase(), def.name.to_lowercase()] {
333 if let Some(more) = claimed.get(&format!("name:{name}")) {
334 tasks.extend(more.iter().filter(|t| !tasks.iter().any(|have| have.num == t.num)).cloned().collect::<Vec<_>>());
335 }
336 }
337 tasks.sort_by_key(|t| t.num);
338 tasks
339}
340
341pub fn read_claimed(work: &Store, now_ms: i64) -> Vec<crate::backend::storage::work_board::BoardTask> {
345 work.work_claimed_list(now_ms).unwrap_or_default()
346}
347
348fn first_pane_by_def(mstore: &Store) -> HashMap<String, String> {
350 use crate::backend::obj::{self, Block, Tab};
351 let mut out = HashMap::new();
352 for tab in mstore.get_all::<Tab>().unwrap_or_default() {
353 for id in &tab.blockids {
354 let Some(block) = mstore.get::<Block>(id).ok().flatten() else { continue };
355 let def_id = obj::meta_get_string(&block.meta, "agentId", "");
356 if !def_id.is_empty() {
357 out.entry(def_id).or_insert_with(|| id.clone());
358 }
359 }
360 }
361 out
362}
363
364pub fn watcher_panes(mstore: &Store, def_id: &str, filers: &[String]) -> Vec<String> {
367 let own = notes::live_panes_of(mstore, def_id);
368 let mut panes: Vec<String> = Vec::new();
369 let mut add = |pane: Option<String>| {
370 if let Some(p) = pane.filter(|p| !own.contains(p) && !panes.contains(p)) {
371 panes.push(p);
372 }
373 };
374 add(crate::backend::agent_seat::worker_of(mstore, def_id).and_then(|leader| notes::live_panes_of(mstore, &leader).into_iter().next()));
375 add(notes::leader_pane_of(mstore, def_id));
376 for filer in filers.iter().filter(|f| !f.is_empty() && f.as_str() != def_id) {
377 add(notes::live_panes_of(mstore, filer).into_iter().next());
378 }
379 panes
380}
381
382pub fn ask_answered(ask: &Ask, replied_ms: Option<u64>, held: &[OwedTask], still_waiting: bool) -> bool {
386 replied_ms.is_some_and(|at| at >= ask.at_ms) || held.iter().any(|t| ask.tasks.contains(&t.num) && t.updated_ms > ask.at_ms) || !still_waiting
387}
388
389fn open_asks_by_def(mstore: &Store, work: &Store, defs: &[AgentDefinition], claimed: &HashMap<String, Vec<OwedTask>>, now_ms: u64) -> HashMap<String, Vec<OwedTask>> {
392 use crate::backend::obj::{self, Block};
393 let mut open: HashMap<String, Vec<OwedTask>> = HashMap::new();
394 let mut done: Vec<Ask> = Vec::new();
395 for ask in urgent_asks::open_asks(now_ms) {
396 let def_id = mstore.get::<Block>(&ask.block_id).ok().flatten().map(|b| obj::meta_get_string(&b.meta, "agentId", "")).unwrap_or_default();
397 let Some(def) = defs.iter().find(|d| d.id == def_id) else {
398 done.push(ask);
399 continue;
400 };
401 let Some(sender) = defs.iter().find(|d| d.slug.eq_ignore_ascii_case(&ask.sender) || d.name.eq_ignore_ascii_case(&ask.sender) || d.id == ask.sender) else { continue };
402 let held = owed_by(claimed, def);
403 let replied = notes::last_report(&def.slug, ¬es::live_panes_of(mstore, &sender.id));
404 let waiting = work.work_numbers_waiting_on(&ask.tasks, &def.id, &def.slug).unwrap_or(true);
405 if ask_answered(&ask, replied, &held, waiting) {
406 done.push(ask);
407 continue;
408 }
409 let entry = open.entry(def.id.clone()).or_default();
410 for num in &ask.tasks {
411 if !entry.iter().any(|t| t.num == *num && t.filer_uid == sender.id) {
412 entry.push(OwedTask { num: *num, filer_uid: sender.id.clone(), updated_ms: ask.at_ms, asked: true });
413 }
414 }
415 }
416 if !done.is_empty() {
417 urgent_asks::settle(|a| done.contains(a));
418 }
419 open
420}
421
422fn owes_report(mstore: &Store, defs: &[AgentDefinition], def: &AgentDefinition, worker_pane: &str) -> bool {
425 let Some(leader_id) = crate::backend::agent_seat::worker_of(mstore, &def.id) else { return false };
426 let Some(leader) = defs.iter().find(|d| d.id == leader_id) else { return false };
427 let given = notes::last_report(&leader.slug, &[worker_pane.to_string()]);
428 let reported = notes::last_report(&def.slug, ¬es::live_panes_of(mstore, &leader_id));
429 match (given, reported) {
430 (None, _) => false,
431 (Some(_), None) => true,
432 (Some(g), Some(r)) => r < g,
433 }
434}
435
436fn nudge_text(tasks: &[OwedTask], quiet_minutes: u64) -> String {
438 let (held, asked) = split_asked(tasks);
439 let mut owes: Vec<String> = Vec::new();
440 if !held.is_empty() {
441 owes.push(format!("You hold {}", task_list(&held)));
442 }
443 if !asked.is_empty() {
444 let lead = if held.is_empty() { "You have" } else { "have" };
445 owes.push(format!("{lead} an unanswered urgent message about {}", task_list(&asked)));
446 }
447 let owes = if owes.is_empty() { "You have not reported to your leader".to_string() } else { owes.join(", ") };
448 format!("{owes} and nothing has run for {quiet_minutes} minutes. Carry on, or say what you are waiting on.")
449}
450
451fn split_asked(tasks: &[OwedTask]) -> (Vec<OwedTask>, Vec<OwedTask>) {
453 tasks.iter().cloned().partition(|t| !t.asked)
454}
455
456fn task_list(tasks: &[OwedTask]) -> String {
457 let mut nums: Vec<i64> = tasks.iter().map(|t| t.num).collect();
458 nums.sort_unstable();
459 nums.dedup();
460 nums.iter().map(|n| format!("#{n}")).collect::<Vec<_>>().join(", ")
461}
462
463pub fn quiet_body(name: &str, is_worker: bool, tasks: &[OwedTask], idle_minutes: u64, running: bool, last_words: &str, background: &str) -> String {
465 let who = if is_worker { "worker" } else { "agent" };
466 let (held, asked) = split_asked(tasks);
467 let on = match (held.is_empty(), asked.is_empty()) {
468 (true, true) => " without reporting to you".to_string(),
469 (false, true) => format!(" on {}", task_list(&held)),
470 (true, false) => format!(" without answering your urgent message about {}", task_list(&asked)),
471 (false, false) => format!(" on {}, and has not answered your urgent message about {}", task_list(&held), task_list(&asked)),
472 };
473 let state = if running {
474 "Its turn is still running but has written nothing.".to_string()
475 } else if !background.is_empty() {
476 format!("Its turn ended, and a background command is still running: {background}")
477 } else if last_words.is_empty() {
478 "It is idle.".to_string()
479 } else {
480 format!("It is idle after a turn that ended: \"{last_words}\"")
481 };
482 format!("Your {who} {name} has been quiet for {idle_minutes} min{on}. {state}")
483}
484
485pub fn install(mstore: Arc<Store>, work: Arc<Store>, filestore: Arc<FileStore>, config: Arc<ConfigState>) {
487 tokio::spawn(async move {
488 let watch = Arc::new(parking_lot::Mutex::new(Watch::default()));
489 let mut tick = tokio::time::interval(SWEEP_EVERY);
490 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
491 loop {
492 tick.tick().await;
493 let (mstore, work, filestore, config, watch) = (mstore.clone(), work.clone(), filestore.clone(), config.clone(), watch.clone());
494 let _ = tokio::task::spawn_blocking(move || {
496 sweep(&mut watch.lock(), &mstore, &work, &filestore, &config, agentmux_common::time::now_ms_u64());
497 })
498 .await;
499 }
500 });
501}
502
503fn with_asked(mut held: Vec<OwedTask>, asked: Vec<OwedTask>) -> Vec<OwedTask> {
507 for more in asked {
508 if !held.iter().any(|t| t.asked && t.num == more.num && t.filer_uid == more.filer_uid) {
509 held.push(more);
510 }
511 }
512 held.sort_by_key(|t| (t.num, t.asked));
513 held
514}
515
516pub fn sweep(watch: &mut Watch, mstore: &Store, work: &Store, filestore: &FileStore, config: &ConfigState, now_ms: u64) {
518 let Some(lim) = limits_from(&config.get_settings().extra) else {
519 watch.retain(&HashSet::new());
520 QUIET.lock().clear();
521 return;
522 };
523 let defs = mstore.agent_def_list().unwrap_or_default();
524 let panes = first_pane_by_def(mstore);
525 notes::absorb(&crate::backend::reactive::get_global_handler().get_audit_log(usize::MAX));
526 let claimed = claimed_by_holder(&read_claimed(work, now_ms as i64));
527 let mut asked = open_asks_by_def(mstore, work, &defs, &claimed, now_ms);
528 let quota_tight = crate::backend::quota_mode::is_tight(&config.get_settings().extra);
529 let mut keep = HashSet::new();
530 let mut quiet_now = HashMap::new();
531 for def in &defs {
532 let Some(block_id) = panes.get(&def.id) else { continue };
533 let tasks = with_asked(owed_by(&claimed, def), asked.remove(&def.id).unwrap_or_default());
534 if tasks.is_empty() && !owes_report(mstore, &defs, def, block_id) {
535 continue;
536 }
537 let state = crate::backend::agent_state::current_state(mstore, block_id);
538 let Some(reading) = read(mstore, block_id, def, &tasks, state, now_ms, quota_tight) else { continue };
539 keep.insert(def.id.clone());
540 let action = watch.step(&def.id, reading, &lim, now_ms);
541 if let Some(since_ms) = watch.quiet_since(&def.id, reading.turn_active, reading.background, &lim, now_ms) {
542 let filers: Vec<String> = tasks.iter().map(|t| t.filer_uid.clone()).collect();
543 let watchers = watcher_panes(mstore, &def.id, &filers).iter().filter_map(|p| agent_name_of_pane(mstore, &defs, p)).collect();
544 let mut nums: Vec<i64> = tasks.iter().map(|t| t.num).collect();
545 nums.dedup();
546 quiet_now.insert(def.id.clone(), QuietView { since_ms, tasks: nums, watchers });
547 }
548 match action {
549 None => {}
550 Some(Action::Nudge) => nudge(&def.id, block_id, &tasks, lim.quiet_ms / 60_000),
551 Some(Action::Tell { running, idle_ms }) => {
552 if tell(mstore, filestore, config, def, block_id, &tasks, running, idle_ms / 60_000, now_ms) {
553 watch.mark_told(&def.id, now_ms);
554 }
555 }
556 }
557 }
558 watch.retain(&keep);
559 *QUIET.lock() = quiet_now;
560}
561
562fn agent_name_of_pane(mstore: &Store, defs: &[AgentDefinition], block_id: &str) -> Option<String> {
564 use crate::backend::obj::{self, Block};
565 let block = mstore.get::<Block>(block_id).ok().flatten()?;
566 let def_id = obj::meta_get_string(&block.meta, "agentId", "");
567 defs.iter().find(|d| d.id == def_id).map(|d| d.name.clone())
568}
569
570fn read(mstore: &Store, block_id: &str, def: &AgentDefinition, tasks: &[OwedTask], state: Option<AgentState>, now_ms: u64, quota_tight: bool) -> Option<Reading> {
573 if !callable(state) {
574 return None;
575 }
576 let ctrl = crate::backend::blockcontroller::get_controller(block_id)?;
577 let tracker = ctrl.turn_tracker()?;
578 let output = ctrl.last_output_ms().and_then(|v| u64::try_from(v).ok()).unwrap_or(0);
579 let sent = notes::last_message_by(&def.slug).unwrap_or(0);
580 let moved = held_moved_ms(tasks);
581 let status = mstore.get::<crate::backend::obj::Block>(block_id).ok().flatten().map(|b| b.meta).unwrap_or_default();
582 let paused = if holding_for_quota(&status, quota_tight) { now_ms } else { paused_activity(&status, mute_for_clock(&def.id, now_ms).as_ref(), now_ms) };
583 let turn_active = tracker.pass_started_ms().is_some();
584 let background = !turn_active && !super::background_set::for_block(block_id, now_ms).is_empty();
585 Some(Reading { activity_ms: output.max(sent).max(moved).max(paused), turn_active, background })
586}
587
588fn nudge(def_id: &str, block_id: &str, tasks: &[OwedTask], quiet_minutes: u64) {
589 let Some(target) = notes::note_target(block_id) else { return };
590 let text = format!("[AgentMux] {}", crate::backend::reactive::sanitize::quote_in_system_note(&nudge_text(tasks, quiet_minutes)));
591 match crate::backend::reactive::get_global_handler().deliver_system_note(&target, &text) {
592 Ok(()) => tracing::info!(def_id, "quiet agent nudged"),
593 Err(e) => tracing::warn!(def_id, error = %e, "quiet agent not nudged"),
594 }
595}
596
597#[allow(clippy::too_many_arguments)]
598fn background_label(block_id: &str, now_ms: u64) -> String {
601 let items = super::background_set::for_block(block_id, now_ms);
602 let Some(first) = items.first() else { return String::new() };
603 let one_line: String = first.label.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(90).collect();
604 match items.len() {
605 1 => one_line,
606 n => format!("{one_line} (and {} more)", n - 1),
607 }
608}
609
610fn tell(mstore: &Store, filestore: &FileStore, config: &ConfigState, def: &AgentDefinition, block_id: &str, tasks: &[OwedTask], running: bool, idle_minutes: u64, now_ms: u64) -> bool {
611 let filers: Vec<String> = tasks.iter().map(|t| t.filer_uid.clone()).collect();
612 let watchers = watcher_panes(mstore, &def.id, &filers);
613 let remote_lead = crate::backend::agent_seat::effective_seat_by_id(mstore, &def.id).and_then(|seat| seat.lead).filter(|lead| crate::backend::agent_seat::is_remote_lead(lead));
614 if watchers.is_empty() && remote_lead.is_none() {
615 return false;
616 }
617 let words = if running { String::new() } else { notes::last_words_of(mstore, filestore, block_id) };
618 let local = || {
619 let is_worker = crate::backend::agent_seat::worker_of(mstore, &def.id).is_some();
620 let background = if running { String::new() } else { background_label(block_id, now_ms) };
621 let body = quiet_body(&def.name, is_worker, tasks, idle_minutes, running, &words, &background);
622 let Some(body) = notes::admit(&def.id, body, now_ms) else { return false };
623 let line = super::note_outbox::Line {
626 agent: def.id.clone(),
627 text: crate::backend::reactive::sanitize::quote_in_system_note(&body),
628 held_key: Some(format!("quiet:{}", def.id)),
629 };
630 super::note_outbox::queue(mstore, config, &watchers, &line, now_ms);
631 true
632 };
633 let remote = || {
635 if let Some(lead) = &remote_lead {
636 let nums: Vec<i64> = tasks.iter().map(|t| t.num).collect();
637 super::quiet_remote::queue(lead, super::quiet_remote::Note::new(&def.name, running, idle_minutes, &nums, &words));
638 }
639 };
640 told_both(!watchers.is_empty(), local, remote)
641}
642
643fn told_both(has_local: bool, local: impl FnOnce() -> bool, remote: impl FnOnce()) -> bool {
647 if has_local && !local() {
648 return false;
649 }
650 remote();
651 true
652}
653
654#[cfg(test)]
655#[path = "quiet_watch_tests.rs"]
656mod tests;