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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
//! One loaded session's event stream (#1657): every wire event gets the
//! stream's next `seq`, goes to every attached client, and stays in a
//! buffer a client reattaching with its cursor resumes from.
//!
//! A client that attaches without a usable cursor gets a reset: the
//! session's saved transcript, as wire events, then the turn in progress
//! from the buffer. The feed keeps that transcript itself, extended with
//! each turn's saved rows as the turn saves, so an attach never waits for
//! the turn that holds the session's runtime. It keeps the rows, which
//! share their content with the session's history, and renders their
//! events for each reset ([`SavedTranscript`]). The transcript and the point
//! where the turn in progress begins move together under the feed's lock,
//! the same lock an attach reads both under, so a turn that saves while a
//! client attaches is neither sent twice nor skipped. A turn that could not
//! save stays in the buffer, so resets replay it live until a later turn
//! saves it.
//!
//! The feed also keeps the session's options, as the last
//! [`wire::SessionEvent::OptionsChanged`] left them, and its background
//! work, as the last [`wire::SessionEvent::Background`] did, so an attach,
//! and `rho/session/background/list`, report them without waiting for the
//! runtime either. It keeps the agent the session runs as, as the last
//! [`wire::SessionEvent::Agent`] said it, which every reset replays first:
//! no saved row holds it. It keeps what the sessions this one starts open
//! with, as the last [`wire::SessionEvent::StartedSessionDefaults`] said
//! it, which every reset replays next, and which `rho/session/new` reads
//! while this session's turn holds its runtime. It keeps what runs the
//! session and what that can do, as the last
//! [`wire::SessionEvent::Engine`] said it, which every reset replays next.
//! It keeps the session's pull requests, as the last
//! [`wire::SessionEvent::PullRequests`] sent them, so it sends them again
//! only when they change (see `pull_requests`).
//!
//! A loaded session's feed reports whether the session is settled (see
//! `settle`) as [`wire::SessionEvent::Activity`]: `active` goes out just
//! before a state event that starts a turn, and an attach's replay ends
//! with the current level: the event that last said it, when the replay
//! ends with that, else the level again, even in a replay that holds
//! nothing else. A feed
//! that was never told its activity, as a subagent run's, reports none.
//!
//! A reset's transcript events carry seq 0, except the last, which carries
//! the seq the turn in progress began after. A client's cursor is the
//! highest seq it has seen, so one that detaches partway through a
//! transcript holds no cursor past 0 and resets again.
//!
//! Each event goes out with when it happened
//! ([`wire::SessionEventEnvelope::at`]): a live event when the feed takes
//! it, which the buffer keeps for a tail, and a saved one when its row was
//! saved. The state a reset replays ahead of the transcript, and the
//! activity an attach's replay ends with, carry none.
use std::{
collections::{BTreeMap, VecDeque},
path::Path,
sync::{Mutex, MutexGuard, PoisonError},
time::{Duration, Instant},
};
use rho_protocol::{
self as wire, Cursor, DetachReason, EntryId, Published, Publisher, Seq, StreamEvent, StreamId,
Subscription,
};
use crate::{
app::{
pull_requests::unix_ms,
session_events::{defer, Deferrables, FeedEvent, SavedTranscript, SavedTurn},
},
tools::ui::SurfaceViewer,
};
use self::replay::{Replayed, ReplayedFrom};
use super::capabilities::SessionEngine;
/// How many events one client may fall behind before the daemon drops its
/// subscription; it then reattaches with its cursor.
//
// Measured: a real turn streamed 21 text deltas per second on average and
// 24 in its busiest second, about 104 bytes each, so this covers a client
// that stops reading for about 170 s of the busiest streaming measured.
const SUBSCRIBER_BACKLOG: usize = 4096;
/// How many bytes of encoded events the buffer keeps for reattaching
/// clients.
//
// Measured over 1,697 real turns in 229 saved sessions: a turn's saved
// content was at most 1.57 MB (p99 1.05 MB). Live events add JSON framing
// per delta, so this keeps the largest turn seen about ten times over.
// Evicting events of the turn in progress is a tripwire: it is logged, and a
// reset replay says the turn's start is unavailable until the turn saves.
const REPLAY_BUFFER_BYTES: usize = 16 * 1024 * 1024;
/// Tells a client reset into a turn whose start the buffer no longer holds.
const TURN_START_EVICTED: &str =
"the start of this turn is no longer buffered; it appears once the turn is saved";
/// A loaded session's event stream.
pub(super) struct Feed {
state: Mutex<FeedState>,
}
struct FeedState {
stream: StreamId,
/// The seq of the last event sent; `Seq(0)` before the first.
last: Seq,
buffer: VecDeque<Buffered>,
buffered_bytes: usize,
/// The seq the turn in progress began after. Events after it are the
/// turn's; the transcript holds everything up to it.
turn_start: Seq,
/// Whether the buffer evicted events of the turn in progress.
turn_start_evicted: bool,
/// The session's saved transcript, up to `turn_start`.
transcript: SavedTranscript,
/// The transcript's last entry, from when it last grew until the next
/// event carries it: a client that followed the turn live has shown
/// everything saved through it once it has the events before that one.
entry_stamp: Option<EntryId>,
/// The job state the last state event sent, so an attach reports the
/// state its replay ends in.
job: wire::JobState,
/// The turn `job` is of, as that event named it.
turn: Option<wire::TurnId>,
/// When the feed first saw `turn` under way, while it is.
turn_since: Option<Instant>,
/// The input requests opened and not yet resolved, so an attach reports
/// them even once the buffer no longer holds the events that opened
/// them.
inputs: BTreeMap<wire::InputRequestId, wire::InputRequest>,
/// The session's title: the saved one, then the last title change sent,
/// so an attach reports it though no transcript holds it.
title: Option<String>,
/// The session's first message as it names the session, once the
/// feed has seen it: in the transcript the session saved, or in a turn.
/// Kept though the buffer evicts it.
first_message: Option<String>,
/// The session's options, as the last options event sent them.
options: wire::SessionOptions,
/// The id of the agent the session runs as: the one it opened as,
/// then the last agent event sent.
agent: String,
/// What the sessions this one starts open with: what it opened with
/// (see [`Feed::seed_started_session_defaults`]), then the last
/// [`wire::SessionEvent::StartedSessionDefaults`] sent.
started_session_defaults: wire::StartedSessionDefaults,
/// What runs the session, whose [`wire::SessionEvent::Engine`] every
/// reset replays. `None` for a feed never told, as a subagent run's.
engine: Option<SessionEngine>,
/// The session's background work, as the last background event sent
/// it.
background: Vec<wire::BackgroundWork>,
/// The session's pull requests, as the last pull requests event sent
/// them; empty until the first.
pull_requests: wire::SessionPullRequests,
/// The session's context use and spend, as the last usage event sent
/// them.
usage: Option<wire::JobUsage>,
/// `usage` as of `turn_start`, which a reset replays with the
/// transcript: no saved row holds usage, and the turn in progress
/// replays its own.
saved_usage: Option<wire::JobUsage>,
/// Whether the session is settled, as the last activity event sent it;
/// `None` until the first.
activity: Option<wire::SessionActivity>,
/// The session's browser, as the last browser event sent it; `None`
/// until the session's browser tools first ran.
browser: Option<wire::SessionBrowser>,
subscribers: Vec<Subscriber>,
/// Set by [`Feed::close`]: a client attaching later is detached at once.
closed: Option<DetachReason>,
}
/// One attached client.
struct Subscriber {
publisher: Publisher,
/// The tool output its events leave out, if it asked and the session
/// defers any.
deferral: Option<wire::ToolOutputDeferral>,
/// Held while the client is attached, when it draws the session's
/// surfaces: the session's `ui` tool waits for the user only while one
/// such client follows it.
_viewer: Option<SurfaceViewer>,
}
impl Subscriber {
fn is_gone(&self) -> bool {
self.publisher.is_gone()
}
}
struct Buffered {
event: rho_protocol::StreamEvent,
bytes: usize,
/// What a deferral may leave out of it, with the refs a read finds the
/// items by: worked out when it was pushed if a client that defers
/// followed the session, else by the first read by ref that searches
/// it. Each item costs about 0.8 ms per MB to hash, so a session no
/// client defers for pays nothing.
deferrables: Option<Deferrables>,
}
/// Where a client attaching resumes from: its seq cursor, and the last
/// saved entry its stream sent, for when the cursor no longer resumes; how
/// much of the saved conversation it takes when it does not; and the tool
/// output its events leave out.
#[derive(Clone, Copy, Debug, Default)]
pub(super) struct ResumeFrom<'a> {
pub(super) after: Option<&'a Cursor>,
pub(super) entry: Option<&'a EntryId>,
pub(super) window: Option<wire::ReplayWindow>,
pub(super) deferral: Option<wire::ToolOutputDeferral>,
}
impl<'a> ResumeFrom<'a> {
/// From the seq cursor `after` alone, the conversation whole.
pub(super) fn cursor(after: Option<&'a Cursor>) -> Self {
Self {
after,
..Self::default()
}
}
}
/// What an attach sends, before the session's live events.
pub(super) struct Attached {
pub(super) stream: StreamId,
/// Where the replay starts.
from: ReplayedFrom,
/// How many events the replay holds.
pub(super) replay_events: u64,
/// The job state as of the attach, which the replay ends in.
pub(super) job: wire::JobState,
/// The turn `job` is of.
pub(super) turn: Option<wire::TurnId>,
/// How long `turn` had been under way as of the attach; `None` when no
/// turn is.
pub(super) turn_elapsed: Option<Duration>,
/// The input requests open as of the attach, oldest first.
pub(super) inputs: Vec<wire::InputRequest>,
/// The session's title as of the attach, if it has one.
pub(super) title: Option<String>,
/// The session's options as of the attach.
pub(super) options: wire::SessionOptions,
/// The session's background work as of the attach.
pub(super) background: Vec<wire::BackgroundWork>,
pub(super) subscription: Subscription,
}
/// The answer to an attach or observe of the session in `workspace`, and
/// the subscription its events then arrive on.
pub(super) fn attach_response(
workspace: &Path,
attached: Attached,
) -> (wire::SessionAttachAnswer, Subscription) {
let Attached {
stream,
from,
replay_events,
job,
turn,
turn_elapsed,
inputs,
title,
options,
background,
subscription,
} = attached;
let response = wire::SessionAttachResponse {
stream,
workspace: workspace.to_path_buf(),
replay: from.replay(),
replay_events,
state: job,
turn,
// Far below `u64::MAX` milliseconds.
turn_elapsed_ms: turn_elapsed
.map(|elapsed| u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)),
inputs,
title,
options,
background,
};
let mut answer = wire::SessionAttachAnswer::new(response);
from.answer(&mut answer);
(answer, subscription)
}
impl Feed {
/// A stream with nothing saved yet, its job in `job`: idle for a new
/// session, its last turn's end for a reopened one (#1661), whose saved
/// conversation [`Self::end_turn`] then adds. `turn` is the turn `job`
/// is of, and `title` the one the session has saved, if any; the
/// session opened with `options`, running as agent `agent`.
pub(super) fn new(
job: wire::JobState,
turn: Option<wire::TurnId>,
title: Option<String>,
options: wire::SessionOptions,
agent: String,
) -> Self {
Self {
state: Mutex::new(FeedState {
stream: StreamId::new(uuid::Uuid::new_v4().to_string()),
last: Seq(0),
buffer: VecDeque::new(),
buffered_bytes: 0,
turn_start: Seq(0),
turn_start_evicted: false,
transcript: SavedTranscript::default(),
entry_stamp: None,
job,
turn,
// A stream that opens on a turn under way, as a subagent
// run's does, times the turn from here.
turn_since: job.in_progress().then(Instant::now),
inputs: BTreeMap::new(),
title,
first_message: None,
options,
agent,
started_session_defaults: wire::StartedSessionDefaults::default(),
engine: None,
background: Vec::new(),
pull_requests: wire::SessionPullRequests::default(),
usage: None,
saved_usage: None,
activity: None,
browser: None,
subscribers: Vec::new(),
closed: None,
}),
}
}
/// Sends `events` to every attached client, in order, timed now, and
/// buffers them.
pub(super) fn publish<E: Into<FeedEvent>>(&self, events: impl IntoIterator<Item = E>) {
self.publish_change(|| ((), events));
}
/// Runs `change` holding the feed's lock and [`Self::publish`]es the
/// events it returns with its result: a client attaching meanwhile
/// waits, then sees those events. So a client that read the change
/// elsewhere first, as the job list tells a job's state, never attaches
/// to a feed that has yet to tell it. `change` must not touch this feed,
/// whose lock is not reentrant, and takes its own locks after the
/// feed's: the job registry's, which takes no other, holds it through
/// the record's write.
pub(super) fn publish_change<T, E, I>(&self, change: impl FnOnce() -> (T, I)) -> T
where
E: Into<FeedEvent>,
I: IntoIterator<Item = E>,
{
let mut state = self.state();
let (result, events) = change();
for event in events {
state.push(event);
}
result
}
/// Tells attached clients what runs the session is now `engine`, in a
/// fresh engine event, unless they know it: what the session can do
/// changes with what its ACP adapter said, as when it takes no images.
pub(super) fn update_engine(&self, engine: SessionEngine) {
let mut state = self.state();
if state.engine != Some(engine) {
state.engine = Some(engine);
state.push(super::capabilities::engine_event(engine));
}
}
/// Tells attached clients the session's options are now `options`,
/// unless they already are.
pub(super) fn update_options(&self, options: wire::SessionOptions) {
let mut state = self.state();
if state.options != options {
state.push(wire::SessionEvent::OptionsChanged {
options: Box::new(options),
});
}
}
/// Tells attached clients the session runs as agent `id` now, unless
/// they already know: an `/agent:` rebind changes it.
pub(super) fn update_agent(&self, id: &str) {
let mut state = self.state();
if state.agent != id {
state.push(wire::SessionEvent::Agent { id: id.to_owned() });
}
}
/// Tells attached clients the sessions this one starts open with
/// `defaults` now, unless they already do.
pub(super) fn update_started_session_defaults(&self, defaults: wire::StartedSessionDefaults) {
let mut state = self.state();
if state.started_session_defaults != defaults {
state.push(wire::SessionEvent::StartedSessionDefaults(defaults));
}
}
/// What the sessions this one starts open with.
pub(super) fn started_session_defaults(&self) -> wire::StartedSessionDefaults {
self.state().started_session_defaults.clone()
}
/// Tells attached clients the session's background work is now what
/// `read` reads, unless it already is. `read` runs under the feed's
/// lock, so of two reports the later read is the later publish.
pub(super) fn update_background(&self, read: impl FnOnce() -> Vec<wire::BackgroundWork>) {
let mut state = self.state();
let work = read();
if state.background != work {
state.push(wire::SessionEvent::Background { work });
}
}
/// Tells attached clients the session's pull requests are now what
/// `read` reads, unless they already are, and returns them. `read` runs
/// under the feed's lock, as [`Self::update_background`]'s does, so of
/// two reports the later read is the later publish, and a request that
/// answers with what this returns answers with what the feed last sent.
pub(super) fn update_pull_requests(
&self,
read: impl FnOnce() -> wire::SessionPullRequests,
) -> wire::SessionPullRequests {
let mut state = self.state();
let pull_requests = read();
if state.pull_requests != pull_requests {
state.push(wire::SessionEvent::PullRequests {
pull_requests: Box::new(pull_requests.clone()),
});
}
pull_requests
}
/// Tells attached clients whether the session is settled, unless they
/// already know: active while a turn is under way or `wake_due` says
/// the daemon or the session's host will start one, settled otherwise.
/// `wake_due` runs under the feed's lock, as [`Self::update_background`]'s
/// read does, and only between turns.
pub(super) fn update_activity(&self, wake_due: impl FnOnce() -> bool) {
let mut state = self.state();
let activity = if state.job.in_progress() || wake_due() {
wire::SessionActivity::Active
} else {
wire::SessionActivity::Settled
};
if state.activity != Some(activity) {
state.push(wire::SessionEvent::Activity { state: activity });
}
}
/// Tells attached clients the session's browser is now `browser`,
/// unless they already know.
pub(super) fn update_browser(&self, browser: wire::SessionBrowser) {
let mut state = self.state();
if state.browser.as_ref() != Some(&browser) {
state.push(wire::SessionEvent::Browser {
browser: Box::new(browser),
});
}
}
/// The session's background work, as the last background event sent
/// it.
pub(super) fn background(&self) -> Vec<wire::BackgroundWork> {
self.state().background.clone()
}
/// The session's options now.
pub(super) fn options(&self) -> wire::SessionOptions {
self.state().options.clone()
}
/// The live events the buffer holds, oldest first.
#[cfg(test)]
pub(super) fn buffered_for_tests(&self) -> Vec<wire::SessionEvent> {
let state = self.state();
state
.buffer
.iter()
.map(|buffered| buffered.event.event.clone())
.collect()
}
/// What a client attaching with no cursor replays, oldest first.
#[cfg(test)]
pub(super) fn reset_replay_for_tests(&self) -> Vec<wire::SessionEvent> {
self.replay_for_tests(None)
.into_iter()
.map(|event| event.event)
.collect()
}
/// What a client attaching with `after` replays, oldest first, as its
/// subscription carries it.
#[cfg(test)]
pub(super) fn replay_for_tests(
&self,
after: Option<&Cursor>,
) -> Vec<rho_protocol::StreamEvent> {
let replayed = self.state().replay_from(ResumeFrom::cursor(after));
replayed.events.events.collect()
}
/// Records that the turns since the last save saved as `saved`: it
/// joins the transcript, and resets stop replaying those turns' live
/// events.
pub(super) fn end_turn(&self, saved: SavedTurn) {
let mut state = self.state();
state.save(saved);
state.turn_start = state.last;
state.turn_start_evicted = false;
state.saved_usage = state.usage;
}
/// Replaces the conversation the feed holds with `transcript`, the
/// session's saved rows after its conversation moved to another point
/// of its tree, if it has any. The feed becomes a new stream, so no
/// cursor of the old one resumes, and every attached client is detached
/// as lagged, which it answers by attaching again and replaying
/// `transcript`. Then runs `change` and publishes the events it returns,
/// all under the feed's lock, as [`Self::publish_change`] does: a
/// client never attaches to the new stream before them. Call between
/// turns: the buffer holds no turn in progress then.
pub(super) fn restart<E, I>(&self, transcript: Option<SavedTurn>, change: impl FnOnce() -> I)
where
E: Into<FeedEvent>,
I: IntoIterator<Item = E>,
{
let mut state = self.state();
state.stream = StreamId::new(uuid::Uuid::new_v4().to_string());
state.transcript = SavedTranscript::default();
state.entry_stamp = None;
// The moved conversation's, which a rewind of its first message
// may change.
state.first_message = None;
if let Some(turn) = transcript {
state.save(turn);
}
state.buffer.clear();
state.buffered_bytes = 0;
state.last = Seq(0);
state.turn_start = Seq(0);
state.turn_start_evicted = false;
// The moved conversation's usage arrives as a live event.
state.saved_usage = None;
for subscriber in std::mem::take(&mut state.subscribers) {
subscriber.publisher.close(DetachReason::Lagged);
}
for event in change() {
state.push(event);
}
}
/// Subscribes a client resuming from `from`. A cursor this stream
/// still buffers resumes with the events after it; else a saved entry
/// the transcript holds resumes with the transcript after it and the
/// turn in progress; anything else resets to the transcript and the
/// turn in progress. Once the feed is closed, the client gets that
/// replay, then is detached.
pub(super) fn attach(&self, from: ResumeFrom<'_>) -> Attached {
self.attach_viewer(from, /*viewer*/ None)
}
/// [`Self::attach`], for a client that may draw the session's
/// surfaces: `viewer` is its place among those that do, given up once
/// the client is gone.
pub(super) fn attach_viewer(
&self,
from: ResumeFrom<'_>,
viewer: Option<SurfaceViewer>,
) -> Attached {
let mut state = self.state();
let from = ResumeFrom {
deferral: state.deferral(from.deferral),
..from
};
let Replayed {
from: replayed_from,
events,
} = state.replay_from(from);
// A replay's events are counted in memory, so far below `u64::MAX`.
let replay_events = u64::try_from(events.len).unwrap_or(u64::MAX);
let deferral = from.deferral;
let replay = events.events.map(move |event| deferred(event, deferral));
let (publisher, subscription) = rho_protocol::subscription_of(SUBSCRIBER_BACKLOG, replay);
// Clients that left an idle session would otherwise stay until the
// next event.
state.subscribers.retain(|subscriber| !subscriber.is_gone());
match state.closed {
Some(reason) => publisher.close(reason),
None => state.subscribers.push(Subscriber {
publisher,
deferral,
_viewer: viewer,
}),
}
Attached {
stream: state.stream.clone(),
from: replayed_from,
replay_events,
job: state.job,
turn: state.turn.clone(),
turn_elapsed: state.turn_since.map(|since| since.elapsed()),
inputs: state.inputs.values().cloned().collect(),
title: state.title.clone(),
options: state.options.clone(),
background: state.background.clone(),
subscription,
}
}
/// Starts the session's usage at `usage`, a usage event of the context
/// its saved conversation fills, which no saved row holds. Sent to no
/// live client, but a reset replays it until a saved turn's usage, with
/// the session's cost, replaces it.
pub(super) fn seed_usage(&self, usage: &wire::SessionEvent) {
let mut state = self.state();
state.usage = usage_of(usage);
state.saved_usage = state.usage;
}
/// Starts the session with `defaults`, what the sessions it starts
/// open with as it opened with them. Sent to no live client; a reset
/// replays it.
pub(super) fn seed_started_session_defaults(&self, defaults: wire::StartedSessionDefaults) {
self.state().started_session_defaults = defaults;
}
/// Starts the feed knowing what runs the session, `engine`, whose
/// runtime never changes while it is loaded
/// ([`Self::update_engine`]).
pub(super) fn seed_engine(&self, engine: SessionEngine) {
self.state().engine = Some(engine);
}
/// The session's title, if it has one.
pub(super) fn title(&self) -> Option<String> {
self.state().title.clone()
}
/// What names the session: its title, else its first message's first
/// line, as plain text (see [`message_name`]); `None` before its first
/// message.
pub(super) fn name(&self) -> Option<String> {
let state = self.state();
state.title.clone().or_else(|| state.first_message.clone())
}
/// Gives the person back each open question the session's starter was
/// told of: its `told_starter` clears. No event says so; `rho/job/list`
/// and a client that attaches later read it.
pub(super) fn return_told_questions(&self) {
for request in self.state().inputs.values_mut() {
request.told_starter = false;
}
}
/// What `rho/job/list` reports of the session's job from its stream.
pub(super) fn live(&self) -> wire::JobLive {
let state = self.state();
wire::JobLive {
title: state.title.clone(),
model: state.options.model.current.clone(),
// Far below `u64::MAX` milliseconds.
turn_elapsed_ms: state
.turn_since
.map(|since| u64::try_from(since.elapsed().as_millis()).unwrap_or(u64::MAX)),
usage: state.usage,
inputs: state.inputs.values().cloned().collect(),
}
}
/// Whether a client still follows the session's events.
pub(super) fn followed(&self) -> bool {
let mut state = self.state();
state.subscribers.retain(|subscriber| !subscriber.is_gone());
!state.subscribers.is_empty()
}
/// Ends every client's subscription with `reason`, and detaches each
/// client that attaches later with it. Closing again keeps the first
/// reason.
pub(super) fn close(&self, reason: DetachReason) {
let mut state = self.state();
let reason = *state.closed.get_or_insert(reason);
for subscriber in std::mem::take(&mut state.subscribers) {
subscriber.publisher.close(reason);
}
}
fn state(&self) -> MutexGuard<'_, FeedState> {
// Each change completes before the lock is released except a push
// that panicked mid-fan-out, which at worst leaves a subscriber
// that the next push drops.
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
}
/// The first message of `events`, a session's, as [`message_name`] names
/// it.
fn first_message(mut events: impl Iterator<Item = FeedEvent>) -> Option<String> {
events.find_map(|event| match &event.event {
wire::SessionEvent::UserMessage { content, .. } => message_name(content),
_ => None,
})
}
/// What a user message of `content` names an untitled session as: its
/// first line, as plain text, as the job list shows an untitled child
/// ([`crate::title::placeholder`]); `None` when it has no text, as an
/// image alone.
pub(super) fn message_name(content: &[wire::ContentBlock]) -> Option<String> {
crate::title::placeholder(&message_text(content))
}
/// The text of a user message of `content`: its text blocks, a line apart.
pub(super) fn message_text(content: &[wire::ContentBlock]) -> String {
content
.iter()
.filter_map(|block| match block {
wire::ContentBlock::Text { text } => Some(text.as_str()),
_ => None,
})
.collect::<Vec<_>>()
.join("\n")
}
/// `event` as a client gets it whose events leave `deferral`'s tool output
/// out.
fn deferred(mut event: StreamEvent, deferral: Option<wire::ToolOutputDeferral>) -> StreamEvent {
if let Some(thinned) = deferral.and_then(|deferral| defer(&event.event, deferral)) {
event.event = thinned;
}
event
}
impl FeedState {
/// Whether the session leaves out tool output a client asks it to: a
/// session an agent runtime runs defers none, as no read could find
/// its items once it unloads.
fn defers(&self) -> bool {
self.engine
.is_none_or(|engine| engine.runtime == crate::agent::AgentRuntime::Rho)
}
/// The tool output a client that asks `asked` gets left out.
fn deferral(
&self,
asked: Option<wire::ToolOutputDeferral>,
) -> Option<wire::ToolOutputDeferral> {
asked.filter(|_| self.defers())
}
/// Adds `turn` to the transcript, and names the session by its first
/// message if no earlier turn could.
fn save(&mut self, turn: SavedTurn) {
self.transcript.push(turn);
self.entry_stamp = self.transcript.final_entry();
if self.first_message.is_none() {
self.first_message = first_message(self.transcript.last_turn_events());
}
}
/// Sends `event` to every attached client, timed now, and buffers it.
fn push(&mut self, event: impl Into<FeedEvent>) {
let mut pushed = event.into();
let Some(bytes) = pushed.encoded_len() else {
return;
};
pushed.at = Some(unix_ms());
// A turn starting makes a settled session active, and clients hear
// that first, so it carries the last save's entry.
if self.activity == Some(wire::SessionActivity::Settled)
&& matches!(&pushed.event, wire::SessionEvent::State { state, .. } if state.in_progress())
{
self.push(wire::SessionEvent::Activity {
state: wire::SessionActivity::Active,
});
}
if let Some(entry) = self.entry_stamp.take() {
pushed.after_entry = Some(entry);
}
let event = &pushed.event;
match event {
wire::SessionEvent::State { state, turn } => {
// A turn waiting for input is still the same turn under way.
let continues = self.job.in_progress() && self.turn == *turn;
self.turn_since = match (state.in_progress(), continues) {
(false, _) => None,
(true, true) => self.turn_since.or_else(|| Some(Instant::now())),
(true, false) => Some(Instant::now()),
};
self.job = *state;
self.turn.clone_from(turn);
}
wire::SessionEvent::InputRequested { request } => {
self.inputs.insert(request.id, (**request).clone());
}
wire::SessionEvent::InputResolved { id, .. } => {
self.inputs.remove(id);
}
wire::SessionEvent::InputHeld { id } => {
if let Some(request) = self.inputs.get_mut(id) {
request.timeout = None;
}
}
wire::SessionEvent::InputTimeoutStarted { id, deadline_ms } => {
if let Some(timeout) = self.inputs.get_mut(id).and_then(|r| r.timeout.as_mut()) {
timeout.start(*deadline_ms);
}
}
wire::SessionEvent::TitleChanged { title } => self.title = Some(title.clone()),
wire::SessionEvent::UserMessage { content, .. } if self.first_message.is_none() => {
self.first_message = message_name(content);
}
wire::SessionEvent::Usage { .. } => self.usage = usage_of(event),
wire::SessionEvent::OptionsChanged { options } => self.options = (**options).clone(),
wire::SessionEvent::Agent { id } => self.agent.clone_from(id),
wire::SessionEvent::StartedSessionDefaults(defaults) => {
self.started_session_defaults.clone_from(defaults);
}
wire::SessionEvent::Background { work } => self.background.clone_from(work),
wire::SessionEvent::PullRequests { pull_requests } => {
self.pull_requests = (**pull_requests).clone();
}
wire::SessionEvent::Activity { state } => self.activity = Some(*state),
wire::SessionEvent::Browser { browser } => self.browser = Some((**browser).clone()),
_ => {}
}
let seq = Seq(self.last.0 + 1);
self.last = seq;
let event = pushed.into_stream(seq);
// Worked out now only if a client thins it, and kept; else the
// first read by ref works it out, and keeps it.
let mut deferrables: Option<Deferrables> = None;
// Thinned once for each deferral a client asked.
let mut thinned: Vec<(wire::ToolOutputDeferral, StreamEvent)> = Vec::new();
self.subscribers.retain(|subscriber| {
let sent = match subscriber.deferral {
Some(deferral) => match thinned.iter().find(|(asked, _)| *asked == deferral) {
Some((_, sent)) => sent.clone(),
None => {
let mut sent = event.clone();
let thin = deferrables
.get_or_insert_with(|| Deferrables::of(&event.event))
.thin(&event.event, deferral);
if let Some(thin) = thin {
sent.event = thin;
}
thinned.push((deferral, sent.clone()));
sent
}
},
None => event.clone(),
};
match subscriber.publisher.try_publish_event(sent) {
Ok(()) => true,
Err(Published::Lagged | Published::Gone) => false,
}
});
self.buffer.push_back(Buffered {
event,
bytes,
deferrables,
});
self.buffered_bytes += bytes;
while self.buffered_bytes > REPLAY_BUFFER_BYTES {
let Some(evicted) = self.buffer.pop_front() else {
break;
};
self.buffered_bytes -= evicted.bytes;
if evicted.event.seq > self.turn_start && !self.turn_start_evicted {
self.turn_start_evicted = true;
tracing::warn!(
limit = REPLAY_BUFFER_BYTES,
"a turn outgrew REPLAY_BUFFER_BYTES; clients that reset into it miss its start until it saves"
);
}
}
}
}
/// What `event` says of the session's context use and spend, if it is a
/// usage event.
fn usage_of(event: &wire::SessionEvent) -> Option<wire::JobUsage> {
match event {
wire::SessionEvent::Usage {
used_tokens,
window_tokens,
cost_usd_micros,
} => Some(wire::JobUsage {
used_tokens: *used_tokens,
window_tokens: *window_tokens,
cost_usd_micros: *cost_usd_micros,
}),
_ => None,
}
}
/// The usage event that reports `usage`; [`usage_of`] reverses it.
fn usage_event(usage: wire::JobUsage) -> wire::SessionEvent {
wire::SessionEvent::Usage {
used_tokens: usage.used_tokens,
window_tokens: usage.window_tokens,
cost_usd_micros: usage.cost_usd_micros,
}
}
#[path = "feed_history.rs"]
mod history;
#[path = "feed_replay.rs"]
mod replay;
#[path = "feed_tool_output.rs"]
mod tool_output;
#[cfg(test)]
#[path = "feed_tests.rs"]
mod tests;