1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
//! Answers the followed session's input requests from the TUI (#1667),
//! with the approval prompt, the plan-approval questionnaire, and the
//! questionnaire ([`super::daemon_asks`]).
//!
//! The TUI shows one request at a time, oldest first; the rest wait. Each
//! prompt replies over a channel, read once the person's input is handled
//! ([`App::answer_daemon_input`]), and the reply goes to the daemon as
//! `rho/session/answer`. A request another client answered, the turn
//! withdrew, or the daemon answered at its timeout closes its prompt with a
//! notice ([`App::close_daemon_input`]).
//!
//! Keys reach the prompt while the TUI follows the session's turn
//! (`daemon_turn`): a session waits for input only while a turn runs, and
//! the job's `waiting_for_input` state keeps the TUI following it, whoever
//! started the turn.
//!
//! A question with a timeout counts down to the daemon's own answer. Once
//! the person touches its form, which pauses the countdown, the TUI holds
//! the request (`rho/session/hold`) so the daemon waits for them, as the
//! protocol asks of a client.
use std::{
collections::{HashSet, VecDeque},
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use futures_util::FutureExt;
use rho_protocol::{InputAnswer, InputAsker, InputRequest, InputRequestId, InputTimeout};
use rho_sdk::{ApprovalDecision, HostInputRequest};
use tokio::sync::oneshot;
use super::{
daemon_asks::{approval_answer, plan_answer, questions_answer, DaemonPrompt},
App, ComposerMode, DefaultTerminal, Entry, QuestionAnswerRequest, QuestionnaireCancelReason,
QuestionnaireReply, QuestionnaireResponseChannel,
};
use crate::permission::PermissionMode;
/// The daemon input request the TUI shows, and those waiting behind it.
#[derive(Default)]
pub(super) struct DaemonAnswers {
shown: Option<Shown>,
waiting: VecDeque<InputRequest>,
/// Requests whose questions the person cancelled: their closing goes
/// unsaid.
cancelled: HashSet<InputRequestId>,
/// The person's cancel of questions cancelled the running turn, whose
/// end then says the questionnaire was cancelled.
questions_cancelled_turn: bool,
}
/// The request whose prompt is open.
struct Shown {
id: InputRequestId,
asker: InputAsker,
reply: Reply,
/// Whether the request still times out, so the person's first touch of
/// its form holds it.
times_out: bool,
}
/// Where the open prompt replies.
enum Reply {
Approval(oneshot::Receiver<ApprovalDecision>),
PlanApproval {
reply: oneshot::Receiver<QuestionnaireReply>,
modes: Vec<PermissionMode>,
},
Questions(oneshot::Receiver<QuestionnaireReply>),
}
/// What the person did at the open prompt.
enum Reaction {
Answer(InputAnswer),
/// Cancelled a plan approval, which cancels the turn.
CancelTurn,
/// Cancelled questions: dismisses them, then, when they are the turn's
/// own, cancels the turn if one runs. The dismiss comes
/// first: the cancel alone would leave a subagent's question waiting.
DismissQuestions(InputAsker),
/// The prompt closed without a reply: another client may answer.
Nothing,
}
impl App {
/// Puts `request` to the person once no older request's prompt is open.
/// Requests wait in id order, which is the order the daemon opened them
/// in, so one shown again after a failed answer keeps its place.
pub(super) async fn ask_daemon_input(&mut self, request: InputRequest) {
let waiting = &mut self.daemon_answers.waiting;
let place = waiting.partition_point(|open| open.id < request.id);
waiting.insert(place, request);
self.show_next_daemon_input().await;
}
/// Closes request `id`'s prompt, or drops it from those waiting, and
/// says how it closed; then shows the next.
pub(super) async fn close_daemon_input(&mut self, id: InputRequestId, notice: String) {
if self
.daemon_answers
.shown
.as_ref()
.is_some_and(|shown| shown.id == id)
{
self.withdraw_daemon_prompt();
if self.daemon_turn_runs() {
self.set_status("running");
}
} else {
self.daemon_answers
.waiting
.retain(|request| request.id != id);
}
if !self.daemon_answers.cancelled.remove(&id) {
self.insert_entry(&Entry::Notice(notice));
}
self.show_next_daemon_input().await;
}
/// Request `id` no longer times out: its countdown stops.
pub(super) fn daemon_input_held(&mut self, id: InputRequestId) {
if let Some(request) = self
.daemon_answers
.waiting
.iter_mut()
.find(|request| request.id == id)
{
request.timeout = None;
}
let Some(shown) = self
.daemon_answers
.shown
.as_mut()
.filter(|shown| shown.id == id)
else {
return;
};
shown.times_out = false;
if let ComposerMode::Questionnaire(questionnaire) = self.input_ui.composer_mut() {
questionnaire.pause_timeout();
}
}
/// Closes every daemon request's prompt unanswered, as once the TUI
/// stops following the session's turn: those still open are left to
/// other clients.
pub(super) fn drop_daemon_inputs(&mut self) {
self.withdraw_daemon_prompt();
self.daemon_answers.waiting.clear();
self.daemon_answers.cancelled.clear();
self.daemon_answers.questions_cancelled_turn = false;
}
/// Whether the person's cancel of questions cancelled the turn that
/// ended; read once, as the turn's end shows.
pub(super) fn take_questions_cancelled_turn(&mut self) -> bool {
std::mem::take(&mut self.daemon_answers.questions_cancelled_turn)
}
/// Sends the open prompt's reply to the daemon once the person gave it,
/// or holds its request once they started on it, then shows the next
/// waiting request; run after each terminal event the running turn
/// handles. While `cancelling`, as when that event cancels the turn,
/// nothing new shows: the turn's end closes what it still asks.
pub(super) async fn answer_daemon_input(
&mut self,
terminal: &mut DefaultTerminal,
cancelling: bool,
) -> anyhow::Result<()> {
match self.take_daemon_reaction() {
None => self.hold_touched_daemon_input(terminal).await?,
Some((id, Reaction::Answer(answer))) => {
self.info.session.daemon.answer(id, answer).await;
self.show_taken_daemon_views(terminal).await?;
}
// The cancel withdraws the request.
Some((id, Reaction::CancelTurn)) => {
self.daemon_answers.cancelled.insert(id);
self.cancel_daemon_turn().await;
return Ok(());
}
Some((id, Reaction::DismissQuestions(asker))) => {
self.daemon_answers.cancelled.insert(id);
self.info
.session
.daemon
.answer(id, InputAnswer::Dismiss)
.await;
// An asker a newer daemon names is taken for the turn, as
// before the daemon said whose a request is.
let turns_question = !matches!(asker, InputAsker::Subagent);
if turns_question && self.daemon_turn_runs() {
self.daemon_answers.questions_cancelled_turn = true;
self.cancel_daemon_turn().await;
return Ok(());
}
self.show_taken_daemon_views(terminal).await?;
}
Some((_, Reaction::Nothing)) => {}
}
// Run on every event, so requests a failed cancel left waiting
// show at the next key.
if !cancelling {
self.show_next_daemon_input().await;
}
Ok(())
}
/// [`Self::answer_daemon_input`] while no turn runs, when the open
/// prompt is a subagent's question. Returns whether the prompt shown
/// changed.
pub(super) async fn answer_idle_daemon_input(
&mut self,
terminal: &mut DefaultTerminal,
) -> anyhow::Result<bool> {
let shown = |app: &Self| app.daemon_answers.shown.as_ref().map(|shown| shown.id);
let before = shown(self);
self.answer_daemon_input(terminal, /*cancelling*/ false)
.await?;
Ok(shown(self) != before)
}
/// Holds the open request once the person touched its form, which
/// pauses its countdown.
async fn hold_touched_daemon_input(
&mut self,
terminal: &mut DefaultTerminal,
) -> anyhow::Result<()> {
let touched = !self.questionnaire_timeout_running();
let Some(id) = self
.daemon_answers
.shown
.as_ref()
.filter(|shown| shown.times_out && touched)
.map(|shown| shown.id)
else {
return Ok(());
};
// A failed hold leaves the daemon's deadline running, so the next
// touch tries again.
if self.info.session.daemon.hold(id).await {
if let Some(shown) = self.daemon_answers.shown.as_mut() {
shown.times_out = false;
}
}
self.show_taken_daemon_views(terminal).await
}
/// What the person did at the open prompt, once they did something;
/// the prompt is then no longer shown.
fn take_daemon_reaction(&mut self) -> Option<(InputRequestId, Reaction)> {
let shown = self.daemon_answers.shown.as_mut()?;
let reaction = match &mut shown.reply {
Reply::Approval(reply) => match reply.now_or_never()? {
Ok(decision) => Reaction::Answer(approval_answer(decision)),
Err(_) => Reaction::Nothing,
},
Reply::PlanApproval { reply, modes } => {
questionnaire_reaction(reply.now_or_never()?, |response| {
plan_answer(response, modes)
})
}
Reply::Questions(reply) => {
match questionnaire_reaction(reply.now_or_never()?, questions_answer) {
Reaction::CancelTurn => Reaction::DismissQuestions(shown.asker),
reaction @ (Reaction::Answer(_)
| Reaction::DismissQuestions(_)
| Reaction::Nothing) => reaction,
}
}
};
let id = shown.id;
self.daemon_answers.shown = None;
Some((id, reaction))
}
/// Opens the oldest waiting request's prompt while none is open. One
/// the TUI cannot show says so, and is left to other clients. With no
/// turn running, a subagent's question waits for a plain, empty
/// composer, and shows once the loop finds
/// one: it must not replace a draft or an open picker.
async fn show_next_daemon_input(&mut self) {
let composer_free = matches!(self.input_ui.composer(), ComposerMode::Input)
&& !self.input_ui.has_pending_draft();
if !self.daemon_turn_runs() && !composer_free {
return;
}
while self.daemon_answers.shown.is_none() {
let Some(request) = self.daemon_answers.waiting.pop_front() else {
return;
};
let shown = match DaemonPrompt::of(&request) {
Ok(prompt) => self.open_daemon_prompt(&request, prompt).await,
Err(error) => Err(error),
};
match shown {
Ok(reply) => {
self.daemon_answers.shown = Some(Shown {
id: request.id,
asker: request.asker,
reply,
times_out: request.timeout.is_some(),
});
}
Err(error) => self.insert_entry(&Entry::Error(format!(
"could not show the request: {error}"
))),
}
}
}
async fn open_daemon_prompt(
&mut self,
request: &InputRequest,
prompt: DaemonPrompt,
) -> Result<Reply, String> {
match prompt {
DaemonPrompt::Approval(prompt) => {
let (sender, reply) = oneshot::channel();
self.open_replying_approval(prompt, sender).await;
Ok(Reply::Approval(reply))
}
DaemonPrompt::PlanApproval { form, modes } => {
let reply = self
.open_daemon_questionnaire(form, /*timeout*/ None)
.await?;
Ok(Reply::PlanApproval { reply, modes })
}
DaemonPrompt::Questions(form) => self
.open_daemon_questionnaire(form, request.timeout.as_ref())
.await
.map(Reply::Questions),
}
}
/// Opens the questionnaire for `form`, counting down to `timeout`'s
/// deadline, when the daemon answers it itself.
async fn open_daemon_questionnaire(
&mut self,
form: HostInputRequest,
timeout: Option<&InputTimeout>,
) -> Result<oneshot::Receiver<QuestionnaireReply>, String> {
let (sender, reply) = oneshot::channel();
self.open_questionnaire(QuestionAnswerRequest {
request: form,
response: QuestionnaireResponseChannel::new(sender),
notice: None,
})
.await
.map_err(|error| error.to_string())?;
if let (Some(timeout), ComposerMode::Questionnaire(questionnaire)) =
(timeout, self.input_ui.composer_mut())
{
let remaining = Duration::from_millis(timeout.deadline_ms.saturating_sub(now_ms()));
questionnaire.count_down_to_fallback(remaining, Instant::now());
}
Ok(reply)
}
/// Closes the open prompt, if any, unanswered.
fn withdraw_daemon_prompt(&mut self) {
let Some(shown) = self.daemon_answers.shown.take() else {
return;
};
match shown.reply {
Reply::Approval(_) => self.withdraw_approval(),
Reply::PlanApproval { .. } | Reply::Questions(_) => self.withdraw_questionnaire(),
}
}
}
/// What a questionnaire's `reply` comes to, its answers read by `answer`.
fn questionnaire_reaction(
reply: Result<QuestionnaireReply, oneshot::error::RecvError>,
answer: impl FnOnce(&rho_sdk::HostInputResponse) -> InputAnswer,
) -> Reaction {
match reply {
Ok(QuestionnaireReply::Answer(response)) => Reaction::Answer(answer(&response)),
Ok(QuestionnaireReply::Cancelled(QuestionnaireCancelReason::UserCancelled)) => {
Reaction::CancelTurn
}
Ok(QuestionnaireReply::Cancelled(QuestionnaireCancelReason::UiUnavailable)) | Err(_) => {
Reaction::Nothing
}
}
}
/// Unix time now, in milliseconds, as input request deadlines count it.
fn now_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |since| {
u64::try_from(since.as_millis()).unwrap_or(u64::MAX)
})
}