argonauts-app 0.1.0

Argonauts Code's app controller and run host: the conversation, routing, choosing Captain or crew, and the run host each run has.
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
//! Keeping the computer awake. A long run stops when the laptop sleeps, so
//! while anything is working Argonauts Code holds sleep off by itself, and `/awake` holds it off
//! until you quit or for a time you give. On macOS the hold is the built-in `caffeinate`,
//! told to watch this process, so it ends when Argonauts Code does however that happens.
//!
//! `/awake` keeps the screen on too, since you asked in order to watch. The hold for work
//! under way leaves the screen to your own settings unless `awake.screen_while_working` adds
//! it. A closed lid still sleeps unless the laptop is on power.

use std::time::{Duration, Instant};

use argonauts_core::NoteLevel;
use argonauts_core::app::{AppEvent, AwakeHold};
use argonauts_core::settings::Span;
use argonauts_core::settings::awake::AwakeSettings;
use time::OffsetDateTime;

use crate::controller::{Ctx, Effect};

/// One hold on the computer's sleep, which ends when it's dropped.
pub(crate) trait Hold: Send + Sync {}

/// What a hold keeps awake.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Keeps {
    /// The computer; the screen dims and locks as your settings say.
    Computer,
    ComputerAndScreen,
}

impl Keeps {
    fn while_working(settings: &AwakeSettings) -> Self {
        if settings.screen_while_working {
            Keeps::ComputerAndScreen
        } else {
            Keeps::Computer
        }
    }
}

/// Starts a hold, for this many seconds or until it's dropped. `None` when the computer has
/// no way to hold sleep off that Argonauts Code knows.
pub(crate) type StartHold = Box<dyn Fn(Keeps, Option<u64>) -> Option<Box<dyn Hold>> + Send + Sync>;

/// What `/awake` says it did: what's held, how to undo it, and what it can't do.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Said {
    pub text: String,
    pub undo: Option<String>,
    pub caveat: Option<String>,
}

impl Said {
    fn held(text: String) -> Self {
        Self {
            text,
            undo: Some("/awake off lets them sleep again.".to_owned()),
            caveat: Some(LID.to_owned()),
        }
    }

    fn cant() -> Self {
        Self {
            text: CANT.to_owned(),
            undo: None,
            caveat: None,
        }
    }
}

/// No hold keeps a laptop awake through a closed lid on battery, so the message says so.
const LID: &str = "On battery, closing the lid still puts the Mac to sleep.";

/// What `/awake` asked for.
enum Asked {
    /// Nothing: awake while anything works, when the settings say so.
    Nothing,
    UntilQuit,
    /// For a time, which the hold ends by itself. The wall time is for the bottom line.
    Until {
        ends: Instant,
        at: OffsetDateTime,
    },
    /// `/awake off`: not even while working, until you ask again.
    Off,
}

pub(crate) struct KeepAwake {
    start: StartHold,
    /// `awake.while_working`, as last told.
    while_working: bool,
    /// What the hold for work under way keeps awake, from `awake.screen_while_working`.
    work_keeps: Keeps,
    working: bool,
    asked: Asked,
    /// The hold for work under way, with what it keeps awake.
    for_work: Option<(Keeps, Box<dyn Hold>)>,
    /// The hold `/awake` asked for.
    for_you: Option<Box<dyn Hold>>,
}

impl KeepAwake {
    /// Never holds anything, as in tests.
    pub(crate) fn never() -> Self {
        Self::with(Box::new(|_, _| None))
    }

    /// Holds sleep off the way this computer does it.
    pub(crate) fn system() -> Self {
        Self::with(Box::new(system_hold))
    }

    pub(crate) fn with(start: StartHold) -> Self {
        Self {
            start,
            while_working: true,
            work_keeps: Keeps::Computer,
            working: false,
            asked: Asked::Nothing,
            for_work: None,
            for_you: None,
        }
    }

    /// Whether anything is working now, and what `[awake]` says now.
    pub(crate) fn working(&mut self, working: bool, settings: &AwakeSettings) {
        self.working = working;
        self.while_working = settings.while_working;
        self.work_keeps = Keeps::while_working(settings);
        self.settle();
    }

    /// `/awake`: the computer and its screen, until you quit. Says what it did.
    pub(crate) fn until_quit(&mut self) -> Said {
        self.for_you = (self.start)(Keeps::ComputerAndScreen, None);
        if self.for_you.is_none() {
            return Said::cant();
        }
        self.asked = Asked::UntilQuit;
        self.settle();
        Said::held("Keeping the computer and its screen awake until you quit.".to_owned())
    }

    /// `/awake <time>`: for `span` from `now`, as you wrote it in `time`.
    pub(crate) fn for_a_time(&mut self, span: Duration, time: &str, now: OffsetDateTime) -> Said {
        self.for_you = (self.start)(Keeps::ComputerAndScreen, Some(span.as_secs().max(1)));
        if self.for_you.is_none() {
            return Said::cant();
        }
        self.asked = Asked::Until {
            ends: Instant::now() + span,
            at: now + span,
        };
        self.settle();
        Said::held(format!(
            "Keeping the computer and its screen awake for {time}."
        ))
    }

    /// `/awake off`: the computer may sleep, also while agents work.
    pub(crate) fn off(&mut self) -> Said {
        self.asked = Asked::Off;
        self.for_you = None;
        self.settle();
        Said {
            text: "The computer and its screen may sleep again, also while agents work.".to_owned(),
            undo: Some("/awake keeps them awake.".to_owned()),
            caveat: None,
        }
    }

    /// The hold you asked for, for the bottom line. `None` when you asked for none, or its
    /// time is up.
    pub(crate) fn held(&self) -> Option<AwakeHold> {
        match &self.asked {
            Asked::UntilQuit => Some(AwakeHold::UntilQuit),
            Asked::Until { ends, at } if Instant::now() < *ends => {
                Some(AwakeHold::Until { at: *at })
            }
            Asked::Until { .. } | Asked::Nothing | Asked::Off => None,
        }
    }

    /// Starts or ends the hold for work under way, as things stand.
    fn settle(&mut self) {
        // A time that's up leaves things as they were before you asked.
        if matches!(&self.asked, Asked::Until { ends, .. } if Instant::now() >= *ends) {
            self.asked = Asked::Nothing;
            self.for_you = None;
        }
        let wanted = self.working && self.while_working && !matches!(self.asked, Asked::Off);
        let held = self.for_work.as_ref().map(|(keeps, _)| *keeps);
        match (wanted, held) {
            (false, _) => self.for_work = None,
            // A changed setting swaps the hold for one that keeps what it now says.
            (true, held) if held != Some(self.work_keeps) => {
                self.for_work = None;
                self.for_work =
                    (self.start)(self.work_keeps, None).map(|hold| (self.work_keeps, hold));
            }
            (true, _) => {}
        }
    }
}

const CANT: &str = "Argonauts Code can keep only a Mac awake so far, so nothing changed.";

/// `/awake`, `/awake <time>` and `/awake off`. The bottom line shows a hold you asked for.
pub(crate) fn command(ctx: &mut Ctx, time: Option<String>) -> anyhow::Result<Vec<Effect>> {
    let said = match time.as_deref() {
        None => ctx.awake.until_quit(),
        Some("off") => ctx.awake.off(),
        Some(time) => match Span::new(time).parse() {
            Ok(Some(span)) if !span.is_zero() => {
                ctx.awake.for_a_time(span, time, OffsetDateTime::now_utc())
            }
            _ => anyhow::bail!("/awake takes a time such as 2h or 45m, or off"),
        },
    };
    match said {
        Said {
            text,
            undo: None,
            caveat: None,
        } => ctx.notice(NoteLevel::Info, text),
        Said { text, undo, caveat } => ctx.send(AppEvent::Switched { text, undo, caveat }),
    }
    Ok(vec![Effect::Status])
}

/// A hold for as long as this process hosts a run, for the run host, keeping what `[awake]`
/// says work under way keeps. `None` when the computer has no way Argonauts Code knows.
pub(crate) fn while_hosting(settings: &AwakeSettings) -> Option<Box<dyn Hold>> {
    system_hold(Keeps::while_working(settings), None)
}

#[cfg(target_os = "macos")]
fn system_hold(keeps: Keeps, secs: Option<u64>) -> Option<Box<dyn Hold>> {
    mac::Caffeinate::start(keeps, secs).map(|hold| Box::new(hold) as Box<dyn Hold>)
}

#[cfg(not(target_os = "macos"))]
fn system_hold(_keeps: Keeps, _secs: Option<u64>) -> Option<Box<dyn Hold>> {
    None
}

#[cfg(target_os = "macos")]
mod mac {
    use std::process::{Child, Command, Stdio};

    use super::Keeps;

    /// By its full path, so a wrapper of the same name on `PATH` is never what runs.
    const CAFFEINATE: &str = "/usr/bin/caffeinate";

    /// A running `caffeinate`, stopped when dropped.
    pub(super) struct Caffeinate(Child);

    impl Caffeinate {
        /// `-i` holds idle sleep off, `-s` system sleep while on power, and `-d` keeps the
        /// display on. `-w` ties it to this process, so it ends with Argonauts Code even
        /// after a crash. `-t` ends it by itself.
        pub(super) fn start(keeps: Keeps, secs: Option<u64>) -> Option<Self> {
            let mut command = Command::new(CAFFEINATE);
            command
                .arg(flags(keeps))
                .args(["-w", &std::process::id().to_string()]);
            if let Some(secs) = secs {
                command.args(["-t", &secs.to_string()]);
            }
            let child = command
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .spawn();
            match child {
                Ok(child) => Some(Self(child)),
                Err(err) => {
                    tracing::warn!("{CAFFEINATE} didn't start, so the computer may sleep: {err}");
                    None
                }
            }
        }
    }

    pub(super) fn flags(keeps: Keeps) -> &'static str {
        match keeps {
            Keeps::Computer => "-is",
            Keeps::ComputerAndScreen => "-dis",
        }
    }

    impl super::Hold for Caffeinate {}

    #[cfg(test)]
    impl Caffeinate {
        pub(super) fn pid(&self) -> u32 {
            self.0.id()
        }
    }

    impl Drop for Caffeinate {
        fn drop(&mut self) {
            let _ = self.0.kill();
            let _ = self.0.wait();
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::{Arc, Mutex};

    use super::*;

    /// Counts itself while it lives.
    struct Counted(Arc<AtomicUsize>);

    impl Hold for Counted {}

    impl Drop for Counted {
        fn drop(&mut self) {
            self.0.fetch_sub(1, Ordering::SeqCst);
        }
    }

    /// What each hold was started to keep awake, and for how long.
    type Started = Arc<Mutex<Vec<(Keeps, Option<u64>)>>>;

    /// A keeper whose live holds are counted.
    fn counted() -> (KeepAwake, Arc<AtomicUsize>, Started) {
        let held = Arc::new(AtomicUsize::new(0));
        let started = Started::default();
        let (count, log) = (held.clone(), started.clone());
        let start: StartHold = Box::new(move |keeps, secs| {
            log.lock().unwrap().push((keeps, secs));
            count.fetch_add(1, Ordering::SeqCst);
            Some(Box::new(Counted(count.clone())) as Box<dyn Hold>)
        });
        (KeepAwake::with(start), held, started)
    }

    fn settings(while_working: bool, screen_while_working: bool) -> AwakeSettings {
        AwakeSettings {
            while_working,
            screen_while_working,
        }
    }

    #[test]
    fn it_holds_sleep_off_only_while_something_works() {
        let (mut awake, held, started) = counted();
        let on = settings(true, false);
        assert_eq!(held.load(Ordering::SeqCst), 0);
        awake.working(true, &on);
        awake.working(true, &on);
        assert_eq!(held.load(Ordering::SeqCst), 1, "one hold, however often");
        assert_eq!(awake.held(), None, "the bottom line names only your own");
        awake.working(false, &on);
        assert_eq!(held.load(Ordering::SeqCst), 0);

        // `awake.while_working = false`, and then true again while it works.
        awake.working(true, &settings(false, false));
        assert_eq!(held.load(Ordering::SeqCst), 0);
        awake.working(true, &on);
        assert_eq!(held.load(Ordering::SeqCst), 1);
        // Work under way leaves the screen to your own settings.
        assert_eq!(
            *started.lock().unwrap(),
            [(Keeps::Computer, None), (Keeps::Computer, None)]
        );
    }

    #[test]
    fn work_under_way_keeps_the_screen_on_only_when_the_setting_adds_it() {
        let (mut awake, held, started) = counted();
        awake.working(true, &settings(true, true));
        assert_eq!(*started.lock().unwrap(), [(Keeps::ComputerAndScreen, None)]);
        // Turning the setting off mid-work swaps the hold for one without the screen.
        awake.working(true, &settings(true, false));
        assert_eq!(held.load(Ordering::SeqCst), 1);
        assert_eq!(
            started.lock().unwrap().last(),
            Some(&(Keeps::Computer, None))
        );
        assert_eq!(started.lock().unwrap().len(), 2);
    }

    #[test]
    fn awake_holds_the_screen_too_until_you_quit_and_off_ends_every_hold() {
        let (mut awake, held, started) = counted();
        let on = settings(true, false);
        let said = awake.until_quit();
        assert_eq!(
            said,
            Said {
                text: "Keeping the computer and its screen awake until you quit.".into(),
                undo: Some("/awake off lets them sleep again.".into()),
                caveat: Some("On battery, closing the lid still puts the Mac to sleep.".into()),
            }
        );
        assert_eq!(held.load(Ordering::SeqCst), 1);
        assert_eq!(awake.held(), Some(AwakeHold::UntilQuit));
        assert_eq!(*started.lock().unwrap(), [(Keeps::ComputerAndScreen, None)]);
        awake.working(true, &on);
        awake.working(false, &on);
        assert_eq!(held.load(Ordering::SeqCst), 1, "yours stays when work ends");

        awake.working(true, &on);
        let said = awake.off();
        assert_eq!(
            said.text,
            "The computer and its screen may sleep again, also while agents work."
        );
        assert_eq!(said.undo.as_deref(), Some("/awake keeps them awake."));
        assert_eq!(said.caveat, None);
        assert_eq!(held.load(Ordering::SeqCst), 0, "not even while agents work");
        assert_eq!(awake.held(), None);
        // Asking again brings both back.
        awake.until_quit();
        assert_eq!(held.load(Ordering::SeqCst), 2);
        assert!(
            started
                .lock()
                .unwrap()
                .iter()
                .all(|(_, secs)| secs.is_none())
        );
    }

    #[test]
    fn a_time_is_given_to_the_hold_and_reaches_the_bottom_line() {
        let (mut awake, held, started) = counted();
        let now = time::macros::datetime!(2026-10-07 13:45 UTC);
        let said = awake.for_a_time(Duration::from_secs(2 * 3600), "2h", now);
        assert_eq!(
            said.text,
            "Keeping the computer and its screen awake for 2h."
        );
        assert_eq!(
            said.undo.as_deref(),
            Some("/awake off lets them sleep again.")
        );
        assert_eq!(
            *started.lock().unwrap(),
            [(Keeps::ComputerAndScreen, Some(7200))]
        );
        assert_eq!(held.load(Ordering::SeqCst), 1);
        let until = time::macros::datetime!(2026-10-07 15:45 UTC);
        assert_eq!(awake.held(), Some(AwakeHold::Until { at: until }));
    }

    #[test]
    fn the_command_says_what_it_did_and_work_under_way_holds_sleep_off_too() {
        use argonauts_core::app::AppMode;
        use argonauts_core::names::TurnId;

        use crate::controller::test_support::{CliOptions, TestCtx};

        let (mut parts, _) = TestCtx::new(CliOptions::default());
        let (awake, held, _) = counted();
        parts.ctx.awake = awake;
        let ctx = &mut parts.ctx;
        let effects = command(ctx, None).unwrap();
        assert!(
            matches!(effects.as_slice(), [Effect::Status]),
            "{effects:?}"
        );
        assert_eq!(held.load(Ordering::SeqCst), 1);
        assert_eq!(ctx.awake.held(), Some(AwakeHold::UntilQuit));

        // An answer under way holds one more, and its end lets that one go.
        let turn = TurnId::numbered(1);
        ctx.set_mode(AppMode::Answering { turn });
        assert_eq!(held.load(Ordering::SeqCst), 2);
        ctx.set_mode(AppMode::Idle);
        assert_eq!(held.load(Ordering::SeqCst), 1);

        command(ctx, Some("off".to_owned())).unwrap();
        assert_eq!(held.load(Ordering::SeqCst), 0);
        command(ctx, Some("45m".to_owned())).unwrap();
        assert_eq!(held.load(Ordering::SeqCst), 1);
        assert!(matches!(ctx.awake.held(), Some(AwakeHold::Until { .. })));
        assert!(command(ctx, Some("soon".to_owned())).is_err());

        let mut said = Vec::new();
        while let Ok(event) = parts.events.try_recv() {
            if let AppEvent::Switched { text, undo, caveat } = event {
                said.push((text, undo, caveat.is_some()));
            }
        }
        let undo = |words: &str| Some(words.to_owned());
        assert_eq!(
            said,
            [
                (
                    "Keeping the computer and its screen awake until you quit.".to_owned(),
                    undo("/awake off lets them sleep again."),
                    true
                ),
                (
                    "The computer and its screen may sleep again, also while agents work."
                        .to_owned(),
                    undo("/awake keeps them awake."),
                    false
                ),
                (
                    "Keeping the computer and its screen awake for 45m.".to_owned(),
                    undo("/awake off lets them sleep again."),
                    true
                ),
            ]
        );
    }

    /// The real thing on a Mac: `caffeinate` runs while the hold lives, and ends with it.
    #[cfg(target_os = "macos")]
    #[test]
    fn on_a_mac_the_hold_is_caffeinate_and_it_ends_when_dropped() {
        let alive = |pid: u32| {
            std::process::Command::new("/bin/kill")
                .args(["-0", &pid.to_string()])
                .stderr(std::process::Stdio::null())
                .status()
                .is_ok_and(|status| status.success())
        };
        assert_eq!(mac::flags(Keeps::Computer), "-is");
        assert_eq!(mac::flags(Keeps::ComputerAndScreen), "-dis");
        let hold = mac::Caffeinate::start(Keeps::Computer, Some(30)).expect("caffeinate starts");
        let pid = hold.pid();
        assert!(alive(pid));
        drop(hold);
        assert!(!alive(pid));
    }

    #[test]
    fn a_computer_with_no_way_to_hold_sleep_off_says_so() {
        let mut awake = KeepAwake::never();
        assert_eq!(awake.until_quit(), Said::cant());
        assert_eq!(awake.held(), None);
        awake.working(true, &settings(true, false));
        assert_eq!(awake.held(), None);
    }
}