-
Notifications
You must be signed in to change notification settings - Fork 10.2k
Expand file tree
/
Copy paththread_status.rs
More file actions
752 lines (668 loc) · 22.6 KB
/
thread_status.rs
File metadata and controls
752 lines (668 loc) · 22.6 KB
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
#[cfg(test)]
use crate::outgoing_message::OutgoingEnvelope;
#[cfg(test)]
use crate::outgoing_message::OutgoingMessage;
use crate::outgoing_message::OutgoingMessageSender;
use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::Thread;
use codex_app_server_protocol::ThreadActiveFlag;
use codex_app_server_protocol::ThreadStatus;
use codex_app_server_protocol::ThreadStatusChangedNotification;
use std::collections::HashMap;
#[cfg(test)]
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::Mutex;
#[cfg(test)]
use tokio::sync::mpsc;
use tokio::sync::watch;
#[derive(Clone)]
pub(crate) struct ThreadWatchManager {
state: Arc<Mutex<ThreadWatchState>>,
outgoing: Option<Arc<OutgoingMessageSender>>,
running_turn_count_tx: watch::Sender<usize>,
}
pub(crate) struct ThreadWatchActiveGuard {
manager: ThreadWatchManager,
thread_id: String,
guard_type: ThreadWatchActiveGuardType,
handle: tokio::runtime::Handle,
}
impl ThreadWatchActiveGuard {
fn new(
manager: ThreadWatchManager,
thread_id: String,
guard_type: ThreadWatchActiveGuardType,
) -> Self {
Self {
manager,
thread_id,
guard_type,
handle: tokio::runtime::Handle::current(),
}
}
}
impl Drop for ThreadWatchActiveGuard {
fn drop(&mut self) {
let manager = self.manager.clone();
let thread_id = self.thread_id.clone();
let guard_type = self.guard_type;
self.handle.spawn(async move {
manager
.note_active_guard_released(thread_id, guard_type)
.await;
});
}
}
#[derive(Clone, Copy)]
enum ThreadWatchActiveGuardType {
Permission,
UserInput,
}
impl Default for ThreadWatchManager {
fn default() -> Self {
Self::new()
}
}
impl ThreadWatchManager {
pub(crate) fn new() -> Self {
let (running_turn_count_tx, _running_turn_count_rx) = watch::channel(0);
Self {
state: Arc::new(Mutex::new(ThreadWatchState::default())),
outgoing: None,
running_turn_count_tx,
}
}
pub(crate) fn new_with_outgoing(outgoing: Arc<OutgoingMessageSender>) -> Self {
let (running_turn_count_tx, _running_turn_count_rx) = watch::channel(0);
Self {
state: Arc::new(Mutex::new(ThreadWatchState::default())),
outgoing: Some(outgoing),
running_turn_count_tx,
}
}
pub(crate) async fn upsert_thread(&self, thread: Thread) {
self.mutate_and_publish(move |state| state.upsert_thread(thread.id))
.await;
}
pub(crate) async fn remove_thread(&self, thread_id: &str) {
let thread_id = thread_id.to_string();
self.mutate_and_publish(move |state| state.remove_thread(&thread_id))
.await;
}
pub(crate) async fn loaded_status_for_thread(&self, thread_id: &str) -> ThreadStatus {
self.state.lock().await.loaded_status_for_thread(thread_id)
}
pub(crate) async fn loaded_statuses_for_threads(
&self,
thread_ids: Vec<String>,
) -> HashMap<String, ThreadStatus> {
let state = self.state.lock().await;
thread_ids
.into_iter()
.map(|thread_id| {
let status = state.loaded_status_for_thread(&thread_id);
(thread_id, status)
})
.collect()
}
#[cfg(test)]
pub(crate) async fn running_turn_count(&self) -> usize {
self.state
.lock()
.await
.runtime_by_thread_id
.values()
.filter(|runtime| runtime.running)
.count()
}
pub(crate) fn subscribe_running_turn_count(&self) -> watch::Receiver<usize> {
self.running_turn_count_tx.subscribe()
}
pub(crate) async fn note_turn_started(&self, thread_id: &str) {
self.update_runtime_for_thread(thread_id, |runtime| {
runtime.is_loaded = true;
runtime.running = true;
runtime.has_system_error = false;
})
.await;
}
pub(crate) async fn note_turn_completed(&self, thread_id: &str, _failed: bool) {
self.clear_active_state(thread_id).await;
}
pub(crate) async fn note_turn_interrupted(&self, thread_id: &str) {
self.clear_active_state(thread_id).await;
}
pub(crate) async fn note_thread_shutdown(&self, thread_id: &str) {
self.update_runtime_for_thread(thread_id, |runtime| {
runtime.running = false;
runtime.pending_permission_requests = 0;
runtime.pending_user_input_requests = 0;
runtime.is_loaded = false;
})
.await;
}
pub(crate) async fn note_system_error(&self, thread_id: &str) {
self.update_runtime_for_thread(thread_id, |runtime| {
runtime.running = false;
runtime.pending_permission_requests = 0;
runtime.pending_user_input_requests = 0;
runtime.has_system_error = true;
})
.await;
}
async fn clear_active_state(&self, thread_id: &str) {
self.update_runtime_for_thread(thread_id, move |runtime| {
runtime.running = false;
runtime.pending_permission_requests = 0;
runtime.pending_user_input_requests = 0;
})
.await;
}
pub(crate) async fn note_permission_requested(
&self,
thread_id: &str,
) -> ThreadWatchActiveGuard {
self.note_pending_request(thread_id, ThreadWatchActiveGuardType::Permission)
.await
}
pub(crate) async fn note_user_input_requested(
&self,
thread_id: &str,
) -> ThreadWatchActiveGuard {
self.note_pending_request(thread_id, ThreadWatchActiveGuardType::UserInput)
.await
}
async fn note_pending_request(
&self,
thread_id: &str,
guard_type: ThreadWatchActiveGuardType,
) -> ThreadWatchActiveGuard {
self.update_runtime_for_thread(thread_id, move |runtime| {
runtime.is_loaded = true;
let counter = Self::pending_counter(runtime, guard_type);
*counter = counter.saturating_add(1);
})
.await;
ThreadWatchActiveGuard::new(self.clone(), thread_id.to_string(), guard_type)
}
async fn mutate_and_publish<F>(&self, mutate: F)
where
F: FnOnce(&mut ThreadWatchState) -> Option<ThreadStatusChangedNotification>,
{
let (notification, running_turn_count) = {
let mut state = self.state.lock().await;
let notification = mutate(&mut state);
let running_turn_count = state
.runtime_by_thread_id
.values()
.filter(|runtime| runtime.running)
.count();
(notification, running_turn_count)
};
let _ = self.running_turn_count_tx.send(running_turn_count);
if let Some(notification) = notification
&& let Some(outgoing) = &self.outgoing
{
outgoing
.send_server_notification(ServerNotification::ThreadStatusChanged(notification))
.await;
}
}
async fn note_active_guard_released(
&self,
thread_id: String,
guard_type: ThreadWatchActiveGuardType,
) {
self.update_runtime_for_thread(&thread_id, move |runtime| {
let counter = Self::pending_counter(runtime, guard_type);
*counter = counter.saturating_sub(1);
})
.await;
}
async fn update_runtime_for_thread<F>(&self, thread_id: &str, update: F)
where
F: FnOnce(&mut RuntimeFacts),
{
let thread_id = thread_id.to_string();
self.mutate_and_publish(move |state| state.update_runtime(&thread_id, update))
.await;
}
fn pending_counter(
runtime: &mut RuntimeFacts,
guard_type: ThreadWatchActiveGuardType,
) -> &mut u32 {
match guard_type {
ThreadWatchActiveGuardType::Permission => &mut runtime.pending_permission_requests,
ThreadWatchActiveGuardType::UserInput => &mut runtime.pending_user_input_requests,
}
}
}
pub(crate) fn resolve_thread_status(
status: ThreadStatus,
has_in_progress_turn: bool,
) -> ThreadStatus {
// Running-turn events can arrive before the watch runtime state is observed by
// the listener loop. In that window we prefer to reflect a real active turn as
// `Active` instead of `Idle`/`NotLoaded`.
if has_in_progress_turn && matches!(status, ThreadStatus::Idle | ThreadStatus::NotLoaded) {
return ThreadStatus::Active {
active_flags: Vec::new(),
};
}
status
}
#[derive(Default)]
struct ThreadWatchState {
runtime_by_thread_id: HashMap<String, RuntimeFacts>,
}
impl ThreadWatchState {
fn upsert_thread(&mut self, thread_id: String) -> Option<ThreadStatusChangedNotification> {
let previous_status = self.status_for(&thread_id);
let runtime = self
.runtime_by_thread_id
.entry(thread_id.clone())
.or_default();
runtime.is_loaded = true;
self.status_changed_notification(thread_id, previous_status)
}
fn remove_thread(&mut self, thread_id: &str) -> Option<ThreadStatusChangedNotification> {
let previous_status = self.status_for(thread_id);
self.runtime_by_thread_id.remove(thread_id);
if previous_status.is_some() && previous_status != Some(ThreadStatus::NotLoaded) {
Some(ThreadStatusChangedNotification {
thread_id: thread_id.to_string(),
status: ThreadStatus::NotLoaded,
})
} else {
None
}
}
fn update_runtime<F>(
&mut self,
thread_id: &str,
mutate: F,
) -> Option<ThreadStatusChangedNotification>
where
F: FnOnce(&mut RuntimeFacts),
{
let previous_status = self.status_for(thread_id);
let runtime = self
.runtime_by_thread_id
.entry(thread_id.to_string())
.or_default();
runtime.is_loaded = true;
mutate(runtime);
self.status_changed_notification(thread_id.to_string(), previous_status)
}
fn status_for(&self, thread_id: &str) -> Option<ThreadStatus> {
self.runtime_by_thread_id
.get(thread_id)
.map(loaded_thread_status)
}
fn loaded_status_for_thread(&self, thread_id: &str) -> ThreadStatus {
self.status_for(thread_id)
.unwrap_or(ThreadStatus::NotLoaded)
}
fn status_changed_notification(
&self,
thread_id: String,
previous_status: Option<ThreadStatus>,
) -> Option<ThreadStatusChangedNotification> {
let status = self.status_for(&thread_id)?;
if previous_status.as_ref() == Some(&status) {
return None;
}
Some(ThreadStatusChangedNotification { thread_id, status })
}
}
#[derive(Clone, Default)]
struct RuntimeFacts {
is_loaded: bool,
running: bool,
pending_permission_requests: u32,
pending_user_input_requests: u32,
has_system_error: bool,
}
fn loaded_thread_status(runtime: &RuntimeFacts) -> ThreadStatus {
if !runtime.is_loaded {
return ThreadStatus::NotLoaded;
}
let mut active_flags = Vec::new();
if runtime.pending_permission_requests > 0 {
active_flags.push(ThreadActiveFlag::WaitingOnApproval);
}
if runtime.pending_user_input_requests > 0 {
active_flags.push(ThreadActiveFlag::WaitingOnUserInput);
}
if runtime.running || !active_flags.is_empty() {
return ThreadStatus::Active { active_flags };
}
if runtime.has_system_error {
return ThreadStatus::SystemError;
}
ThreadStatus::Idle
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use tokio::time::Duration;
use tokio::time::timeout;
const INTERACTIVE_THREAD_ID: &str = "00000000-0000-0000-0000-000000000001";
const NON_INTERACTIVE_THREAD_ID: &str = "00000000-0000-0000-0000-000000000002";
#[tokio::test]
async fn loaded_status_defaults_to_not_loaded_for_untracked_threads() {
let manager = ThreadWatchManager::new();
assert_eq!(
manager
.loaded_status_for_thread("00000000-0000-0000-0000-000000000003")
.await,
ThreadStatus::NotLoaded,
);
}
#[tokio::test]
async fn tracks_non_interactive_thread_status() {
let manager = ThreadWatchManager::new();
manager
.upsert_thread(test_thread(
NON_INTERACTIVE_THREAD_ID,
codex_app_server_protocol::SessionSource::AppServer,
))
.await;
manager.note_turn_started(NON_INTERACTIVE_THREAD_ID).await;
assert_eq!(
manager
.loaded_status_for_thread(NON_INTERACTIVE_THREAD_ID)
.await,
ThreadStatus::Active {
active_flags: vec![],
},
);
}
#[tokio::test]
async fn status_updates_track_single_thread() {
let manager = ThreadWatchManager::new();
manager
.upsert_thread(test_thread(
INTERACTIVE_THREAD_ID,
codex_app_server_protocol::SessionSource::Cli,
))
.await;
manager.note_turn_started(INTERACTIVE_THREAD_ID).await;
assert_eq!(
manager
.loaded_status_for_thread(INTERACTIVE_THREAD_ID)
.await,
ThreadStatus::Active {
active_flags: vec![],
},
);
let permission_guard = manager
.note_permission_requested(INTERACTIVE_THREAD_ID)
.await;
assert_eq!(
manager
.loaded_status_for_thread(INTERACTIVE_THREAD_ID)
.await,
ThreadStatus::Active {
active_flags: vec![ThreadActiveFlag::WaitingOnApproval],
},
);
let user_input_guard = manager
.note_user_input_requested(INTERACTIVE_THREAD_ID)
.await;
assert_eq!(
manager
.loaded_status_for_thread(INTERACTIVE_THREAD_ID)
.await,
ThreadStatus::Active {
active_flags: vec![
ThreadActiveFlag::WaitingOnApproval,
ThreadActiveFlag::WaitingOnUserInput,
],
},
);
drop(permission_guard);
wait_for_status(
&manager,
INTERACTIVE_THREAD_ID,
ThreadStatus::Active {
active_flags: vec![ThreadActiveFlag::WaitingOnUserInput],
},
)
.await;
drop(user_input_guard);
wait_for_status(
&manager,
INTERACTIVE_THREAD_ID,
ThreadStatus::Active {
active_flags: vec![],
},
)
.await;
manager
.note_turn_completed(INTERACTIVE_THREAD_ID, false)
.await;
assert_eq!(
manager
.loaded_status_for_thread(INTERACTIVE_THREAD_ID)
.await,
ThreadStatus::Idle,
);
}
#[test]
fn resolves_in_progress_turn_to_active_status() {
let status = resolve_thread_status(ThreadStatus::Idle, true);
assert_eq!(
status,
ThreadStatus::Active {
active_flags: Vec::new(),
}
);
let status = resolve_thread_status(ThreadStatus::NotLoaded, true);
assert_eq!(
status,
ThreadStatus::Active {
active_flags: Vec::new(),
}
);
}
#[test]
fn keeps_status_when_no_in_progress_turn() {
assert_eq!(
resolve_thread_status(ThreadStatus::Idle, false),
ThreadStatus::Idle
);
assert_eq!(
resolve_thread_status(ThreadStatus::SystemError, false),
ThreadStatus::SystemError
);
}
#[tokio::test]
async fn system_error_sets_idle_flag_until_next_turn() {
let manager = ThreadWatchManager::new();
manager
.upsert_thread(test_thread(
INTERACTIVE_THREAD_ID,
codex_app_server_protocol::SessionSource::Cli,
))
.await;
manager.note_turn_started(INTERACTIVE_THREAD_ID).await;
manager.note_system_error(INTERACTIVE_THREAD_ID).await;
assert_eq!(
manager
.loaded_status_for_thread(INTERACTIVE_THREAD_ID)
.await,
ThreadStatus::SystemError,
);
manager.note_turn_started(INTERACTIVE_THREAD_ID).await;
assert_eq!(
manager
.loaded_status_for_thread(INTERACTIVE_THREAD_ID)
.await,
ThreadStatus::Active {
active_flags: vec![],
},
);
}
#[tokio::test]
async fn shutdown_marks_thread_not_loaded() {
let manager = ThreadWatchManager::new();
manager
.upsert_thread(test_thread(
INTERACTIVE_THREAD_ID,
codex_app_server_protocol::SessionSource::Cli,
))
.await;
manager.note_turn_started(INTERACTIVE_THREAD_ID).await;
manager.note_thread_shutdown(INTERACTIVE_THREAD_ID).await;
assert_eq!(
manager
.loaded_status_for_thread(INTERACTIVE_THREAD_ID)
.await,
ThreadStatus::NotLoaded,
);
}
#[tokio::test]
async fn loaded_statuses_default_to_not_loaded_for_untracked_threads() {
let manager = ThreadWatchManager::new();
manager
.upsert_thread(test_thread(
INTERACTIVE_THREAD_ID,
codex_app_server_protocol::SessionSource::Cli,
))
.await;
manager.note_turn_started(INTERACTIVE_THREAD_ID).await;
let statuses = manager
.loaded_statuses_for_threads(vec![
INTERACTIVE_THREAD_ID.to_string(),
NON_INTERACTIVE_THREAD_ID.to_string(),
])
.await;
assert_eq!(
statuses.get(INTERACTIVE_THREAD_ID),
Some(&ThreadStatus::Active {
active_flags: vec![],
}),
);
assert_eq!(
statuses.get(NON_INTERACTIVE_THREAD_ID),
Some(&ThreadStatus::NotLoaded),
);
}
#[tokio::test]
async fn has_running_turns_tracks_runtime_running_flag_only() {
let manager = ThreadWatchManager::new();
manager
.upsert_thread(test_thread(
INTERACTIVE_THREAD_ID,
codex_app_server_protocol::SessionSource::Cli,
))
.await;
assert_eq!(manager.running_turn_count().await, 0);
let _permission_guard = manager
.note_permission_requested(INTERACTIVE_THREAD_ID)
.await;
assert_eq!(manager.running_turn_count().await, 0);
manager.note_turn_started(INTERACTIVE_THREAD_ID).await;
assert_eq!(manager.running_turn_count().await, 1);
manager
.note_turn_completed(INTERACTIVE_THREAD_ID, false)
.await;
assert_eq!(manager.running_turn_count().await, 0);
}
#[tokio::test]
async fn status_change_emits_notification() {
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(8);
let manager = ThreadWatchManager::new_with_outgoing(Arc::new(OutgoingMessageSender::new(
outgoing_tx,
)));
manager
.upsert_thread(test_thread(
INTERACTIVE_THREAD_ID,
codex_app_server_protocol::SessionSource::Cli,
))
.await;
assert_eq!(
recv_status_changed_notification(&mut outgoing_rx).await,
ThreadStatusChangedNotification {
thread_id: INTERACTIVE_THREAD_ID.to_string(),
status: ThreadStatus::Idle,
},
);
manager.note_turn_started(INTERACTIVE_THREAD_ID).await;
assert_eq!(
recv_status_changed_notification(&mut outgoing_rx).await,
ThreadStatusChangedNotification {
thread_id: INTERACTIVE_THREAD_ID.to_string(),
status: ThreadStatus::Active {
active_flags: vec![],
},
},
);
manager.remove_thread(INTERACTIVE_THREAD_ID).await;
assert_eq!(
recv_status_changed_notification(&mut outgoing_rx).await,
ThreadStatusChangedNotification {
thread_id: INTERACTIVE_THREAD_ID.to_string(),
status: ThreadStatus::NotLoaded,
},
);
}
async fn wait_for_status(
manager: &ThreadWatchManager,
thread_id: &str,
expected_status: ThreadStatus,
) {
timeout(Duration::from_secs(1), async {
loop {
let status = manager.loaded_status_for_thread(thread_id).await;
if status == expected_status {
break;
}
tokio::task::yield_now().await;
}
})
.await
.expect("timed out waiting for status");
}
async fn recv_status_changed_notification(
outgoing_rx: &mut mpsc::Receiver<OutgoingEnvelope>,
) -> ThreadStatusChangedNotification {
let envelope = timeout(Duration::from_secs(1), outgoing_rx.recv())
.await
.expect("timed out waiting for outgoing notification")
.expect("outgoing channel closed unexpectedly");
let OutgoingEnvelope::Broadcast { message } = envelope else {
panic!("expected broadcast notification");
};
let OutgoingMessage::AppServerNotification(ServerNotification::ThreadStatusChanged(
notification,
)) = message
else {
panic!("expected thread/status/changed notification");
};
notification
}
fn test_thread(thread_id: &str, source: codex_app_server_protocol::SessionSource) -> Thread {
Thread {
id: thread_id.to_string(),
preview: String::new(),
ephemeral: false,
model_provider: "mock-provider".to_string(),
created_at: 0,
updated_at: 0,
status: ThreadStatus::NotLoaded,
path: None,
cwd: PathBuf::from("/tmp"),
cli_version: "test".to_string(),
agent_nickname: None,
agent_role: None,
source,
git_info: None,
name: None,
turns: Vec::new(),
}
}
}