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
//! How a turn shows itself to the session's clients and its job.
use std::{future::Future, sync::Arc, time::SystemTime};
use rho_protocol as wire;
use rho_sdk::RunEvent;
use tokio::sync::{mpsc, watch};
use super::{
super::{
super::jobs::TurnEnd,
cost,
inputs::{Asker, Inputs},
options::available_auths,
prompt_keys::PromptMessage,
LoadedSession,
},
failed, spawn_title, PromptStart, UNEXPECTED_STOP,
};
use crate::{
app::{
session_events::FeedEvent,
session_runtime::{
PlanReport, SessionEvent, SessionRuntime, TurnControl, TurnIo, TurnView,
},
},
config::Config,
};
/// Shows a session's turn to its clients and its job: the session's input
/// requests follow the turn's, and the request that sent the prompt learns
/// how the turn began.
///
/// Records the turn's end exactly once: through [`Self::end`], or, when the
/// view drops without it, as the turn task panicking, failed with
/// [`UNEXPECTED_STOP`].
pub(in crate::app::daemon_host::sessions) struct DaemonView {
pub(in crate::app::daemon_host::sessions) session: Arc<LoadedSession>,
/// The turn's id, which its end is told under.
turn: wire::TurnId,
/// Told `Began` once the turn began (see [`PromptStart::Began`]), or
/// how the turn ended if it ends first.
start: watch::Sender<PromptStart>,
/// The prompt's user message, once the turn showed it.
message: PromptMessage,
/// Whether the turn's end is recorded.
ended: bool,
}
impl DaemonView {
pub(super) fn new(
session: Arc<LoadedSession>,
turn: wire::TurnId,
start: watch::Sender<PromptStart>,
message: PromptMessage,
) -> Self {
Self {
session,
turn,
start,
message,
ended: false,
}
}
/// Notes the prompt's user message among `shown`, the events the turn
/// shows as it inserts it, which the prompt's request answers with once
/// the turn began. A steer is no prompt's.
pub(in crate::app::daemon_host::sessions) fn inserted<'a>(
&self,
shown: impl IntoIterator<Item = &'a wire::SessionEvent>,
) {
let prompt = shown.into_iter().find_map(|event| match event {
wire::SessionEvent::UserMessage {
message,
steer: None,
..
} => Some(message),
_ => None,
});
if let Some(message) = prompt {
self.message.set(message.clone());
}
}
/// Tells whoever waits for the turn to begin that it began as `start`,
/// unless they were told already.
fn tell_start(&self, start: PromptStart) {
self.start.send_if_modified(|told| {
let first = *told == PromptStart::Pending;
if first {
*told = start;
}
first
});
}
/// Records that the turn ended as `end`, telling clients `outcome`
/// when there are clients to tell (`None` while the daemon stops).
pub(super) fn end(mut self, outcome: Option<wire::TurnOutcome>, end: TurnEnd) {
self.finish(outcome, end);
}
/// Tells clients the turn ended with `outcome`, if any, records it as
/// `end`, and tells a request still waiting for the turn to begin.
fn finish(&mut self, outcome: Option<wire::TurnOutcome>, end: TurnEnd) {
// How the turn began, if it had not reported beginning yet. A
// turn that completed began, and is recorded so (see `began`).
let start = match end {
TurnEnd::Completed => Some(PromptStart::Began),
TurnEnd::Interrupted => None,
TurnEnd::Cancelled | TurnEnd::TimedOut { .. } | TurnEnd::Failed(_) => {
outcome.clone().map(PromptStart::Ended)
}
};
// A turn that ended waits for nothing, and inserts nothing more.
self.session.change_inputs(Inputs::withdraw_turn);
self.message.settle();
{
// See `prompt`: the next turn's `running` cannot come before this.
let _turn = self.session.turn();
// A turn that ends before it began answers its prompt with that
// end, so the session whose call sent it hears it there alone.
if matches!(start, Some(PromptStart::Ended(_)))
&& *self.start.borrow() == PromptStart::Pending
{
self.session.peer_wake.forget();
}
self.session.end_turn(self.turn.clone(), outcome, end);
}
self.ended = true;
// Here, so a turn whose task panicked frees the watcher too.
if let Some(wake) = &self.session.idle_wake {
wake.turn_ended();
}
if let Some(keep) = &self.session.cache_warm {
keep.turn_ended();
}
match start {
Some(PromptStart::Began) => self.began(),
Some(start @ PromptStart::Ended(_)) => self.tell_start(start),
Some(PromptStart::Pending) | None => {}
}
}
/// Tells the request that sent the prompt, if it still waits, that the
/// turn began (see [`PromptStart::Began`]), and records it on the job,
/// so a later daemon still knows the prompt as one that ran.
///
/// Nothing a turn does before this needs a client: `rho acp` reads none
/// of the session's events while its prompt waits for this answer.
pub(in crate::app::daemon_host::sessions) fn began(&mut self) {
// Recorded before the request is answered, so a daemon killed right
// after its answer still left the turn recorded as begun. The
// registry records it once, and only on this turn.
self.message.settle();
let message = self.message.get();
self.session
.jobs
.turn_began(&self.session.job, &self.turn, message);
self.tell_start(PromptStart::Began);
}
/// Tells the request that sent the prompt that the turn began, though
/// it only waits for capacity: it has run nothing, so the job does not
/// record it begun until it does ([`Self::began`]).
pub(in crate::app::daemon_host::sessions) fn accepted(&mut self) {
self.tell_start(PromptStart::Began);
}
/// Takes the model turn's events until it drops its sender, opening
/// and withdrawing input requests whose answers go to `control`. Holds
/// `control` until then: a turn whose control channel closes fails, and
/// requests nobody answered yet must stay open.
pub(super) async fn show(
&mut self,
mut events: mpsc::UnboundedReceiver<SessionEvent>,
control: mpsc::UnboundedSender<TurnControl>,
mut cost: cost::TurnCost,
) {
loop {
// A streamed card held back for more arguments goes out when
// the stream pauses instead.
let event = if self.session.live().holds_previews() {
match tokio::time::timeout(PREVIEW_PAUSE, events.recv()).await {
Ok(event) => event,
Err(_) => {
let held = self.session.live().held_previews();
self.session.feed.publish(held);
continue;
}
}
} else {
events.recv().await
};
let event = match event {
Some(SessionEvent::TitleRequested(title)) => {
spawn_title(&self.session, *title);
continue;
}
Some(event) => event,
None => break,
};
let wire = {
let mut live = self.session.live();
let mut wire = live.map(&event);
if matches!(event, SessionEvent::Run(RunEvent::UsageUpdated { .. })) {
wire.extend(live.streamed_usage().map(FeedEvent::from));
}
wire
};
let wire = cost.priced(&event, wire, &self.session.id).await;
let inserted = matches!(event, SessionEvent::MessageInserted(_));
if inserted {
self.inserted(wire.iter().map(|shown| &shown.event));
}
self.session.feed.publish(wire);
if let Some(keep) = &self.session.cache_warm {
match &event {
SessionEvent::RunStarted { .. } => keep.run_started(),
SessionEvent::Run(RunEvent::ModelCallCompleted { metrics, .. }) => {
keep.model_call_completed(metrics);
}
SessionEvent::Run(RunEvent::CompactionCompleted { .. }) => {
keep.prefix_rewritten();
}
_ => {}
}
}
if inserted {
self.began();
}
self.session.change_inputs(|inputs| {
inputs.note(Asker::Turn, &control, &event, SystemTime::now())
});
}
}
}
/// How long a model's stream may pause before the card of what it wrote
/// last is sent though its arguments grew little: long enough that a card
/// per pause stays at four a second for a stream that only trickles, short
/// enough to read as the stream itself.
const PREVIEW_PAUSE: std::time::Duration = std::time::Duration::from_millis(250);
impl Drop for DaemonView {
fn drop(&mut self) {
if !self.ended {
let (outcome, end) = failed(wire::TurnError {
kind: wire::TurnErrorKind::Other,
message: UNEXPECTED_STOP.to_owned(),
});
self.finish(Some(outcome), end);
}
}
}
impl TurnView for DaemonView {
fn open_turn<'v>(
&'v mut self,
runtime: &SessionRuntime,
) -> (TurnIo, impl Future<Output = ()> + Send + use<'v>) {
let (events, event_receiver) = mpsc::unbounded_channel();
let (control_sender, control) = mpsc::unbounded_channel();
(
TurnIo { events, control },
self.show(
event_receiver,
control_sender,
cost::TurnCost::on(&runtime.current_model()),
),
)
}
/// A plan the session kept its mode for reaches clients as a notice
/// saying why. An approval that switched the permission mode changes
/// the session's options, which clients see before the implementation
/// turn.
fn report_plan(
&mut self,
runtime: &SessionRuntime,
_process_config: &Config,
report: PlanReport,
) -> impl Future<Output = ()> + Send {
let session = Arc::clone(&self.session);
let notice = match report {
PlanReport::Kept { notice } => Some(wire::SessionEvent::Notice { text: notice }),
PlanReport::Switched => {
// Before the implementation turn starts, so a change queued
// during it still applies afterwards.
session.turn().plan_switches += 1;
None
}
};
async move {
session.feed.publish(notice);
session.refresh_options(runtime, &available_auths(runtime.credentials()).await);
}
}
}