Skip to main content

trusty_code/session/
registry_prompters.rs

1//! Per-session prompter accounting and the `session.attach` forwarder that
2//! holds one such claim (#8100). A child module of `registry`, split out for
3//! the same 500-SLOC-cap reason as `events`.
4//!
5//! Why: an `ask` permission rule may only suspend a run when SOMEONE can see
6//! the prompt for THAT session and answer it. The first cut of #8100 asked
7//! `crate::events::bus().receiver_count()`, which is daemon-global: one
8//! console watching one PM session marked every headless `task.run` sub-agent
9//! as watched, restoring the 300 s stall the fix exists to remove.
10//! What: [`PrompterGuard`], an RAII claim on one session's prompter count,
11//! and the `claim_prompter`/`prompter_count` pair that mints and reads it. A
12//! guard released by ANY means — detach, a dead connection, a dropped SSE
13//! body, a panicking task — decrements, so a client that dies mid-ask stops
14//! counting without anyone calling a teardown.
15//! Test: `registry_tests::prompter_attached_while_a_session_attachment_lives`,
16//! `registry_tests::prompter_claim_is_released_when_its_guard_drops`,
17//! `registry_tests::prompter_attached_for_an_unknown_session_is_false`,
18//! `registry_tests::prompter_count_survives_a_poisoned_registry_lock`.
19
20use std::sync::atomic::{AtomicUsize, Ordering};
21
22use super::*;
23
24/// One live prompter's claim on one session, released when dropped (#8100).
25///
26/// Why: every prompter path ends in a different way — `session.detach` fires
27/// a cancel channel, an HTTP SSE body is dropped when the socket closes, a
28/// `session.events` stream ends when its receiver goes. A guard whose `Drop`
29/// does the decrementing needs none of them to agree on a teardown call, and
30/// covers the case the timeout was hiding: a client that dies mid-ask.
31/// What: holds the session's counter directly rather than a handle to the
32/// registry, so releasing it never re-enters the registry lock and a session
33/// removed from the map while a client is still attached cannot strand a
34/// count on an entry that no longer exists.
35/// Test: `registry_tests::prompter_claim_is_released_when_its_guard_drops`.
36pub struct PrompterGuard(Arc<AtomicUsize>);
37
38impl Drop for PrompterGuard {
39    fn drop(&mut self) {
40        self.0.fetch_sub(1, Ordering::SeqCst);
41    }
42}
43
44impl SessionRegistry {
45    /// Claim `id` as watched by a prompter until the returned guard drops.
46    ///
47    /// Why (#8100): the counted thing is a client that can both SEE this
48    /// session's `permission_requested` event and answer it with
49    /// `session.permission.respond` — `session.attach`, the `session.events`
50    /// stream, and the per-session HTTP SSE route. The workstream-aggregate
51    /// route (`workstreams::sse`) is deliberately NOT a claimant: it is bound
52    /// to a workstream, re-checks membership per event, and a session can
53    /// leave the group mid-ask, so no session's prompt is its to display.
54    /// What: `None` when `id` names no live session — nothing was claimed, so
55    /// there is nothing to release, and [`prompter_count`] keeps reading `0`.
56    /// Test: `registry_tests::prompter_attached_while_a_session_attachment_lives`,
57    /// `registry_tests::prompter_claim_is_released_when_its_guard_drops`.
58    ///
59    /// [`prompter_count`]: SessionRegistry::prompter_count
60    pub fn claim_prompter(&self, id: &str) -> Option<PrompterGuard> {
61        let counter = Arc::clone(&self.lock().get(id)?.prompters);
62        counter.fetch_add(1, Ordering::SeqCst);
63        Some(PrompterGuard(counter))
64    }
65
66    /// How many prompters currently watch `id`; `0` for an unknown session.
67    ///
68    /// Why (#8100): an unknown session is the fail-safe arm — a permission
69    /// prompt for a session the registry cannot find is a prompt nobody can be
70    /// shown, so it must read as unwatched and deny rather than wait.
71    /// What: `SessionRegistry::lock` recovers a poisoned mutex through
72    /// `into_inner`, so the count stays readable after an unrelated panic and
73    /// the missing entry is the only unreadable arm.
74    /// Test: `registry_tests::prompter_attached_for_an_unknown_session_is_false`,
75    /// `registry_tests::prompter_count_survives_a_poisoned_registry_lock`.
76    pub fn prompter_count(&self, id: &str) -> usize {
77        self.lock()
78            .get(id)
79            .map_or(0, |entry| entry.prompters.load(Ordering::SeqCst))
80    }
81}
82
83/// Spawn the background task that forwards one session's live event
84/// envelopes to a connection until cancelled or the connection is gone.
85///
86/// Why: split out of `attach` for readability; also gives `registry_tests`
87/// a single well-named spawn site to reason about. Subscribing to the bus
88/// SYNCHRONOUSLY here — before `tokio::spawn` schedules the forwarder body
89/// — matters: if the subscription happened inside the spawned `async`
90/// block instead, a caller that calls `send()` immediately after `attach()`
91/// returns could publish its event before the spawned task ever gets polled
92/// and subscribes, and `broadcast::Receiver`s only see events published
93/// after `subscribe()` was called — the event would be silently missed.
94/// What: subscribes to `crate::events::subscribe()` immediately, then
95/// spawns a task that forwards envelopes whose `session_id` matches
96/// `session_id` as a JSON-RPC notification via `notify` (`params` is the
97/// envelope itself — `seq`/`at`/`kind`/`event` all present), skips
98/// envelopes for other sessions and lag gaps, and exits on `cancel_rx`
99/// firing (either a real detach or the sender being dropped) or
100/// `notify.send` failing (connection gone). #8100: `prompter` rides the
101/// spawned task, so this connection stops counting as a prompter the moment
102/// the loop ends, however it ends.
103/// Test: `registry_tests::attach_forwards_live_events_until_detach`,
104/// `registry_tests::prompter_attached_while_a_session_attachment_lives`.
105pub(super) fn spawn_forwarder(
106    session_id: String,
107    notify: NotifySender,
108    cancel_rx: oneshot::Receiver<()>,
109    prompter: Option<PrompterGuard>,
110) {
111    use tokio::sync::broadcast::error::RecvError;
112
113    // Subscribe before spawning (see the Why above) so no event published
114    // by the caller right after `attach()` returns can be missed.
115    let mut events = crate::events::subscribe();
116
117    tokio::spawn(async move {
118        // #8100: released when this task ends — detach, dead connection, or
119        // a closed bus all decrement without a teardown call.
120        let _prompter = prompter;
121        tokio::pin!(cancel_rx);
122        loop {
123            tokio::select! {
124                biased;
125                _ = &mut cancel_rx => break,
126                received = events.recv() => match received {
127                    Ok(envelope) if envelope.session_id == session_id => {
128                        let notification = json!({
129                            "jsonrpc": "2.0",
130                            "method": "session.event",
131                            "params": envelope,
132                        });
133                        if notify.send(notification).is_err() {
134                            break;
135                        }
136                    }
137                    Ok(_) => continue,
138                    Err(RecvError::Lagged(_)) => continue,
139                    Err(RecvError::Closed) => break,
140                },
141            }
142        }
143    });
144}