thirdshift 0.32.0

Turn a GitHub issue into a ready-for-review pull request, unattended
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
//! `thirdshift plan-usage`'s rows: every subscription Harness the User
//! config routes to, in route order, then any other with a saved
//! observation or a signed-in CLI.

use std::collections::BTreeMap;
use std::fmt;

use chrono::{DateTime, Local, Utc};
use serde::{Deserialize, Serialize};

use super::observation::SUBSCRIPTION;
use super::route::{Route, Routing};
use super::store::State;
use crate::config::UserConfig;
use crate::harness::Harness;

/// Where the User config names a route.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Setting {
    #[serde(rename = "harness.default")]
    Default,
    #[serde(rename = "harness.routes")]
    Routes,
    #[serde(rename = "security.harness")]
    SecurityHarness,
    #[serde(rename = "security.routes")]
    SecurityRoutes,
}

impl fmt::Display for Setting {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Default => "harness.default",
            Self::Routes => "harness.routes",
            Self::SecurityHarness => "security.harness",
            Self::SecurityRoutes => "security.routes",
        })
    }
}

/// Whether a route could take a session now.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Availability {
    Available,
    /// Its cooldown passed with no sign it works again: the next session
    /// may try it once.
    Revalidating,
    /// A Plan window is at or above the route's ceiling.
    AtCeiling,
    Cooldown,
    SignedOut,
    NotInstalled,
}

impl Availability {
    pub(super) fn usable(self) -> bool {
        matches!(self, Self::Available | Self::Revalidating)
    }

    /// Whether the route's subscription is used up or at its ceiling: what
    /// the Console header warns of.
    pub fn limited(self) -> bool {
        matches!(self, Self::Cooldown | Self::AtCeiling)
    }
}

impl fmt::Display for Availability {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Available => "available",
            Self::Revalidating => "revalidating",
            Self::AtCeiling => "at its ceiling",
            Self::Cooldown => "in cooldown",
            Self::SignedOut => "signed out",
            Self::NotInstalled => "not installed",
        })
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ConfiguredRoute {
    pub setting: Setting,
    /// 1-based position in a `routes` list.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub position: Option<usize>,
    pub model: Option<String>,
    pub effort: Option<String>,
    pub max_utilization: u8,
    pub allow_credits: bool,
    pub availability: Availability,
    /// The route a factory session would start on now.
    pub active: bool,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Row {
    #[serde(
        serialize_with = "super::route::harness_name",
        deserialize_with = "subscription_harness"
    )]
    pub harness: Harness,
    pub installed: bool,
    pub active: bool,
    pub routes: Vec<ConfiguredRoute>,
    #[serde(flatten)]
    pub state: State,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct View {
    pub version: u8,
    pub harnesses: Vec<Row>,
    /// When availability was judged, so the text agrees with it.
    #[serde(skip, default = "Utc::now")]
    pub now: DateTime<Utc>,
}

/// A row's Harness, read from another machine's view: only a subscription
/// Harness Plan usage watches.
fn subscription_harness<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> Result<Harness, D::Error> {
    let name = String::deserialize(deserializer)?;
    Harness::named(&name)
        .filter(|harness| SUBSCRIPTION.contains(harness))
        .ok_or_else(|| serde::de::Error::custom(format!("not a subscription Harness: {name:?}")))
}

/// Each place the User config names a route, in route order: the default
/// Harness and `harness.routes`, then `security.harness` and
/// `security.routes`.
fn configured(config: &UserConfig) -> Vec<(Setting, Option<usize>, Route)> {
    let routing = &config.routing;
    let default = config.harness.default.unwrap_or(Harness::Claude);
    let mut all = vec![(Setting::Default, None, Route::named(default))];
    all.extend(
        routing
            .routes
            .iter()
            .enumerate()
            .map(|(index, route)| (Setting::Routes, Some(index + 1), route.clone())),
    );
    if let Some(security) = config.security_harness {
        all.push((Setting::SecurityHarness, None, Route::named(security)));
    }
    all.extend(
        routing
            .security_routes
            .iter()
            .enumerate()
            .map(|(index, route)| (Setting::SecurityRoutes, Some(index + 1), route.clone())),
    );
    all
}

impl State {
    /// Whether `route` could take a session on this Harness now.
    pub(super) fn availability(
        &self,
        route: &Route,
        routing: &Routing,
        installed: bool,
        now: DateTime<Utc>,
    ) -> Availability {
        let state = self;
        if !installed {
            return Availability::NotInstalled;
        }
        if state.account.as_ref().and_then(|account| account.signed_in) == Some(false) {
            return Availability::SignedOut;
        }
        let credits = route.allow_credits
            && state.spend_control_reached != Some(true)
            && state
                .credits
                .as_ref()
                .and_then(|credits| credits.has_credits)
                == Some(true);
        if let Some(cooldown) = &state.cooldown {
            if cooldown.until > now {
                if !credits {
                    return Availability::Cooldown;
                }
            } else {
                return Availability::Revalidating;
            }
        }
        let ceiling = f64::from(routing.ceiling(route));
        let full = state.windows.iter().any(|window| {
            !window.reset_by(now) && window.used_percent.is_some_and(|used| used >= ceiling)
        });
        if full && !(credits && ceiling >= 100.0) {
            return Availability::AtCeiling;
        }
        Availability::Available
    }
}

impl View {
    pub fn of(
        config: &UserConfig,
        mut saved: BTreeMap<String, State>,
        installed: impl Fn(Harness) -> bool,
        now: DateTime<Utc>,
    ) -> Self {
        let mut rows: Vec<Row> = Vec::new();
        for (setting, position, route) in configured(config) {
            if !SUBSCRIPTION.contains(&route.harness) {
                continue;
            }
            let index = match rows.iter().position(|row| row.harness == route.harness) {
                Some(index) => index,
                None => {
                    rows.push(Row {
                        harness: route.harness,
                        installed: installed(route.harness),
                        active: false,
                        routes: Vec::new(),
                        state: saved.remove(route.harness.name()).unwrap_or_default(),
                    });
                    rows.len() - 1
                }
            };
            let row = &mut rows[index];
            let set = config.harness.of(route.harness);
            row.routes.push(ConfiguredRoute {
                setting,
                position,
                model: route.model.clone().or(set.model.clone()),
                effort: route.effort.clone().or(set.effort.clone()),
                max_utilization: config.routing.ceiling(&route),
                allow_credits: route.allow_credits,
                availability: row
                    .state
                    .availability(&route, &config.routing, row.installed, now),
                active: false,
            });
        }
        // The primary route list: harness.routes, else harness.default.
        let primary = if config.routing.routes.is_empty() {
            Setting::Default
        } else {
            Setting::Routes
        };
        // Walk it in order, API-key routes included: the first usable route
        // is active, even when it is one Plan usage does not watch.
        let walk: Vec<(Option<usize>, Harness)> = configured(config)
            .into_iter()
            .filter(|(setting, ..)| *setting == primary)
            .map(|(_, position, route)| (position, route.harness))
            .collect();
        for (position, harness) in walk {
            let Some(index) = rows.iter().position(|row| row.harness == harness) else {
                // Not watched: an installed API-key Harness takes the session.
                if installed(harness) {
                    break;
                }
                continue;
            };
            let Some(at) = rows[index]
                .routes
                .iter()
                .position(|route| route.setting == primary && route.position == position)
            else {
                continue;
            };
            if rows[index].routes[at].availability.usable() {
                rows[index].active = true;
                rows[index].routes[at].active = true;
                break;
            }
        }
        for harness in SUBSCRIPTION {
            if rows.iter().any(|row| row.harness == harness) {
                continue;
            }
            let Some(state) = saved.remove(harness.name()) else {
                continue;
            };
            let signed_in = state.account.as_ref().and_then(|account| account.signed_in);
            let installed = installed(harness);
            if state.observed() || (installed && signed_in == Some(true)) {
                rows.push(Row {
                    harness,
                    installed,
                    active: false,
                    routes: Vec::new(),
                    state,
                });
            }
        }
        View {
            version: 1,
            harnesses: rows,
            now,
        }
    }
}

pub(super) fn local(time: DateTime<Utc>) -> String {
    time.with_timezone(&Local)
        .format("%a %b %-d %H:%M %Z")
        .to_string()
}

impl fmt::Display for ConfiguredRoute {
    /// Where the route is named, its settings and its availability.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.setting)?;
        if let Some(position) = self.position {
            write!(f, " {position}")?;
        }
        if let Some(model) = &self.model {
            write!(f, ", {model}")?;
        }
        if let Some(effort) = &self.effort {
            write!(f, ", {effort}")?;
        }
        if self.max_utilization < super::route::FULL {
            write!(f, ", ceiling {}%", self.max_utilization)?;
        }
        if self.allow_credits {
            f.write_str(", credits allowed")?;
        }
        write!(f, ": {}", self.availability)?;
        if self.active {
            f.write_str(", active")?;
        }
        Ok(())
    }
}

/// A saved state's lines, each indented and ending in a newline but the
/// last: account, windows, credits, limits, cooldown, and when it was
/// observed.
pub(super) fn write_state(
    f: &mut fmt::Formatter<'_>,
    state: &State,
    installed: bool,
    now: DateTime<Utc>,
) -> fmt::Result {
    if let Some(account) = &state.account {
        let mut parts = Vec::new();
        match account.signed_in {
            Some(true) => parts.push("signed in".to_owned()),
            Some(false) => parts.push("signed out".to_owned()),
            None => {}
        }
        parts.extend(account.plan.iter().map(|plan| format!("plan {plan}")));
        parts.extend(account.tier.iter().map(|tier| format!("tier {tier}")));
        parts.extend(account.label.clone());
        if !parts.is_empty() {
            writeln!(f, "  account: {}", parts.join(", "))?;
        }
    }
    for window in &state.windows {
        write!(f, "  {}:", window.name)?;
        match window.used_percent {
            Some(used) if !window.reset_by(now) => write!(f, " {used:.0}% used")?,
            Some(_) => f.write_str(" reset since observed")?,
            None => f.write_str(" utilization not reported")?,
        }
        if let Some(status) = &window.status {
            write!(f, ", {status}")?;
        }
        if let Some(reset) = window.resets_at.filter(|reset| *reset > now) {
            write!(f, ", resets {}", local(reset))?;
        }
        writeln!(f)?;
    }
    if let Some(credits) = &state.credits {
        match (&credits.balance, credits.has_credits) {
            (Some(balance), _) => writeln!(f, "  credits: {balance}")?,
            (None, Some(has)) => writeln!(f, "  credits: {}", if has { "some" } else { "none" })?,
            (None, None) => {}
        }
    }
    if state.ordinary_usage_allowed == Some(false) {
        writeln!(f, "  included usage not allowed")?;
    }
    if state.spend_control_reached == Some(true) {
        writeln!(f, "  spend control reached")?;
    }
    if let Some(cooldown) = &state.cooldown {
        if cooldown.until > now {
            write!(f, "  cooldown until {}", local(cooldown.until))?;
        } else {
            write!(f, "  revalidating since {}", local(cooldown.until))?;
        }
        let mut why = Vec::new();
        why.extend(
            cooldown
                .window
                .iter()
                .map(|window| format!("{window} window")),
        );
        why.extend(
            cooldown
                .overage
                .iter()
                .map(|overage| format!("overage {overage}")),
        );
        if let Some(minutes) = cooldown.backoff_minutes {
            why.push(format!("no reset reported, backoff {minutes} minutes"));
        }
        if !why.is_empty() {
            write!(f, " ({})", why.join(", "))?;
        }
        writeln!(f)?;
    }
    match (state.observed_at, &state.source) {
        (Some(at), Some(source)) => write!(f, "  observed {} by {source}", local(at)),
        (Some(at), None) => write!(f, "  observed {}", local(at)),
        (None, _) if !installed => f.write_str("  CLI not on PATH"),
        (None, _) => f.write_str("  nothing observed yet"),
    }
}

impl fmt::Display for View {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.harnesses.is_empty() {
            return f.write_str(EMPTY);
        }
        for (index, row) in self.harnesses.iter().enumerate() {
            if index > 0 {
                writeln!(f)?;
            }
            write!(f, "{}", row.harness.name())?;
            if row.active {
                f.write_str(" (active)")?;
            }
            writeln!(f)?;
            for route in &row.routes {
                writeln!(f, "  route: {route}")?;
            }
            write_state(f, &row.state, row.installed, self.now)?;
        }
        Ok(())
    }
}

/// What a view with no rows says.
pub(crate) const EMPTY: &str = "No Plan usage to show: no configured subscription Harness, no saved observation and no signed-in CLI";

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plan_usage::observation::Window;
    use crate::plan_usage::store::{Account, Cooldown};
    use chrono::TimeDelta;

    fn config(text: &str) -> UserConfig {
        let home = std::path::Path::new("/home/me");
        UserConfig::parse(text, &home.join(".thirdshift/config.toml"), home).unwrap()
    }

    fn names(view: &View) -> Vec<&'static str> {
        view.harnesses
            .iter()
            .map(|row| row.harness.name())
            .collect()
    }

    #[test]
    fn configured_routes_come_first_in_order_and_others_only_when_observed_or_signed_in() {
        let config = config(
            "[harness]\ndefault = \"codex\"\nroutes = [\"codex\", \"opencode\", { harness = \"agy\", max_utilization = 80 }]\n\
             [security]\nharness = \"muse\"\n",
        );
        let now = Utc::now();
        let signed_in = State {
            account: Some(Account {
                signed_in: Some(true),
                ..Account::default()
            }),
            ..State::default()
        };
        let observed = State {
            observed_at: Some(now),
            ..State::default()
        };
        let saved = BTreeMap::from([
            ("claude".to_owned(), signed_in.clone()),
            ("grok".to_owned(), observed),
            ("kimi".to_owned(), signed_in),
        ]);
        let view = View::of(&config, saved, |harness| harness != Harness::Muse, now);
        assert_eq!(names(&view), ["codex", "agy", "muse", "claude", "grok"]);
        let muse = &view.harnesses[2];
        assert_eq!(muse.routes[0].availability, Availability::NotInstalled);
        assert!(view.harnesses[0].active);
        assert_eq!(view.harnesses[1].routes[0].max_utilization, 80);
    }

    #[test]
    fn the_active_route_is_the_first_usable_one_and_a_ceiling_skips_a_route() {
        let config = config("[harness]\nroutes = [\"claude\", \"codex\"]\nmax_utilization = 85\n");
        let now = Utc::now();
        let near = State {
            windows: vec![Window {
                used_percent: Some(90.0),
                resets_at: Some(now + TimeDelta::hours(1)),
                ..Window::named("five_hour").unwrap()
            }],
            observed_at: Some(now),
            ..State::default()
        };
        let cooled = State {
            cooldown: Some(Cooldown {
                since: now,
                until: now + TimeDelta::hours(1),
                window: None,
                overage: None,
                backoff_minutes: Some(60),
            }),
            ..State::default()
        };
        let view = View::of(
            &config,
            BTreeMap::from([("claude".to_owned(), near.clone())]),
            |_| true,
            now,
        );
        assert_eq!(
            view.harnesses[0].routes[1].availability,
            Availability::AtCeiling
        );
        assert!(!view.harnesses[0].active);
        assert!(view.harnesses[1].active);
        let view = View::of(
            &config,
            BTreeMap::from([("claude".to_owned(), near), ("codex".to_owned(), cooled)]),
            |_| true,
            now,
        );
        assert!(view.harnesses.iter().all(|row| !row.active));
        assert_eq!(
            view.harnesses[1].routes[0].availability,
            Availability::Cooldown
        );
    }

    #[test]
    fn an_api_key_route_ahead_leaves_no_subscription_route_active() {
        let config = config("[harness]\nroutes = [\"opencode\", \"claude\"]\n");
        let view = View::of(&config, BTreeMap::new(), |_| true, Utc::now());
        assert!(
            view.harnesses
                .iter()
                .all(|row| !row.active && row.routes.iter().all(|r| !r.active))
        );
    }
}