pitboard-core 0.6.0

The engine behind pitboard: parking and restoring Claude Code and Codex logins. Serves pitboard's own front ends.
Documentation
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
//! What keeps a tool's login in memory while it runs, and what makes each kind take a switch.
//!
//! A tool whose running sessions never notice a switch (`Adoption::RestartRequired`) names
//! the kinds of process that run its program. One program can run in very different
//! places: Codex's runs in a terminal, inside OpenAI's ChatGPT app, as a background app
//! server and inside an editor's Codex extension. Each takes a switch its own way, and
//! advice meant for one is wrong for another: quitting a terminal session does nothing for
//! an app that stays open in the menu bar after its windows close.
//!
//! The kinds are told apart by where the program runs from, which the process list says.
//! Nothing here names a tool; a tool's own list does, most particular kind first and ending
//! with one that is anywhere, so every process is one kind and none is guessed to be an app.

use crate::context::Context;
use crate::process::Process;
use std::path::Path;

/// One kind of process that holds a tool's login.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Holder {
    /// A stable name in snake case, for a program to tell kinds apart by.
    pub kind: &'static str,
    /// How a sentence names what is running.
    pub noun: Noun,
    /// Where its program runs from.
    pub location: Location,
    /// What makes it take a switch.
    pub remedy: Remedy,
}

/// How a sentence names one kind of holder.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Noun {
    /// Each process is one of them, counted: "1 `codex` session", "2 `codex` sessions".
    Counted {
        one: &'static str,
        many: &'static str,
    },
    /// One thing however many processes it runs: an app that starts two of the program is
    /// still one app.
    One(&'static str),
}

/// Where a kind of holder runs its program from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Location {
    /// Inside a directory of exactly this name, such as an app bundle.
    Within(&'static str),
    /// Inside a directory whose name starts with this, such as an editor extension's folder,
    /// which is named for its version.
    WithinPrefixed(&'static str),
    /// Anywhere at all: the kind every process no other kind claims is.
    Anywhere,
}

/// What makes a kind of holder take a switch.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Remedy {
    /// Quit it and start it again.
    Restart,
    /// Quit the app the way Command-Q does, and open it again. Closing its windows is not
    /// enough. The menu bar app can do both for the person; the command line only says so.
    ReopenApp {
        bundle_id: &'static str,
        name: &'static str,
    },
    /// Run this command.
    Run(&'static str),
    /// Do this, somewhere pitboard cannot reach.
    Do(&'static str),
}

/// The processes of one kind of holder that are running.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Holding {
    pub holder: Holder,
    /// Their process ids, in the order the process list gave them.
    pub pids: Vec<u32>,
}

impl Location {
    /// Whether a program at `path` runs from here. Only the directories it is in are
    /// looked at, never the program's own name.
    fn holds(self, path: &Path) -> bool {
        let mut directories = path.ancestors().skip(1).filter_map(Path::file_name);
        match self {
            Location::Anywhere => true,
            Location::Within(name) => directories.any(|dir| dir == name),
            Location::WithinPrefixed(prefix) => {
                directories.any(|dir| dir.to_string_lossy().starts_with(prefix))
            }
        }
    }
}

/// `processes` sorted into `holders`, each to the first whose location holds it, in the
/// holders' order. A kind with nothing running is left out, and so is a process no holder
/// claims, which a list ending in [`Location::Anywhere`] never leaves.
pub fn classify(processes: &[Process], holders: &[Holder]) -> Vec<Holding> {
    let mut holding: Vec<Holding> = holders
        .iter()
        .map(|&holder| Holding {
            holder,
            pids: Vec::new(),
        })
        .collect();
    for process in processes {
        if let Some(found) = holding
            .iter_mut()
            .find(|h| h.holder.location.holds(&process.path))
        {
            found.pids.push(process.pid);
        }
    }
    holding.retain(|h| !h.pids.is_empty());
    holding
}

/// What is running `program` on this machine, by kind. `None` where the process list could
/// not be read, which is not the same as nothing running.
pub(crate) fn find(ctx: &Context, program: &str, holders: &[Holder]) -> Option<Vec<Holding>> {
    ctx.host()
        .processes(program)
        .map(|processes| classify(&processes, holders))
}

impl Holding {
    /// How many things are running: processes for a counted kind, one for the rest.
    fn things(&self) -> usize {
        match self.holder.noun {
            Noun::Counted { .. } => self.pids.len(),
            Noun::One(_) => 1,
        }
    }

    /// "2 `codex` sessions", "the ChatGPT app".
    pub fn phrase(&self) -> String {
        match self.holder.noun {
            Noun::Counted { one, many } => match self.pids.len() {
                1 => format!("1 {one}"),
                n => format!("{n} {many}"),
            },
            Noun::One(name) => name.to_string(),
        }
    }

    /// What to do, as a clause. Said alone it can say "it" or "them"; beside others it has
    /// to name what it is about.
    fn clause(&self, alone: bool) -> String {
        let them = if self.things() == 1 { "it" } else { "them" };
        match self.holder.remedy {
            Remedy::Restart if alone => format!("quit {them} and start again"),
            Remedy::Restart => {
                let what = match self.holder.noun {
                    Noun::Counted { one, many } => {
                        format!("the {}", if self.things() == 1 { one } else { many })
                    }
                    Noun::One(name) => name.to_string(),
                };
                format!("quit {what} and start {them} again")
            }
            Remedy::ReopenApp { name, .. } => {
                format!("quit {name} with Command-Q and open it again")
            }
            Remedy::Run(command) => format!("run `{command}`"),
            Remedy::Do(instruction) => instruction.to_string(),
        }
    }
}

/// Everything running, as one noun phrase: "2 `codex` sessions and the ChatGPT app".
pub fn described(holding: &[Holding]) -> String {
    listed(holding.iter().map(Holding::phrase).collect())
}

/// The same, with the pids of each: "2 `codex` sessions (pid 41, 42)".
pub fn described_with_pids(holding: &[Holding]) -> String {
    listed(
        holding
            .iter()
            .map(|h| format!("{} (pid {})", h.phrase(), some_of(&h.pids)))
            .collect(),
    )
}

/// Whether what is running reads as more than one thing, for "is" or "are".
pub fn plural(holding: &[Holding]) -> bool {
    holding.iter().map(Holding::things).sum::<usize>() > 1
}

/// One sentence saying what makes everything running take a switch, with `purpose`:
/// "Quit them and start again to use the new account." Several kinds are each said in turn,
/// apart, since one clause can have an "and" of its own: "To use the new account: quit the
/// `codex` sessions and start them again; quit ChatGPT with Command-Q and open it again."
pub fn remedies(holding: &[Holding], purpose: &str) -> String {
    match holding {
        [] => String::new(),
        [one] => format!("{} {purpose}.", capitalised(&one.clause(true))),
        many => format!(
            "{}: {}.",
            capitalised(purpose),
            many.iter()
                .map(|h| h.clause(false))
                .collect::<Vec<_>>()
                .join("; ")
        ),
    }
}

/// "a", "a and b", "a, b and c".
fn listed(mut items: Vec<String>) -> String {
    match items.len() {
        0 => String::new(),
        1 => items.remove(0),
        _ => {
            let last = items.pop().unwrap_or_default();
            format!("{} and {last}", items.join(", "))
        }
    }
}

/// `text` with its first letter a capital, to begin a sentence with.
pub(crate) fn capitalised(text: &str) -> String {
    let mut chars = text.chars();
    chars.next().map_or_else(String::new, |first| {
        first.to_uppercase().chain(chars).collect()
    })
}

/// A few pids and how many more, because somebody with twenty sessions open needs to know
/// there are twenty, not which twenty.
pub(crate) fn some_of(pids: &[u32]) -> String {
    const SHOWN: usize = 3;
    let named: Vec<String> = pids.iter().take(SHOWN).map(u32::to_string).collect();
    match pids.len().saturating_sub(SHOWN) {
        0 => named.join(", "),
        more => format!("{} and {more} more", named.join(", ")),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    const APP: Holder = Holder {
        kind: "app",
        noun: Noun::One("the App"),
        location: Location::Within("App.app"),
        remedy: Remedy::ReopenApp {
            bundle_id: "com.example.app",
            name: "App",
        },
    };
    const EXTENSION: Holder = Holder {
        kind: "extension",
        noun: Noun::One("the extension"),
        location: Location::WithinPrefixed("vendor.tool-"),
        remedy: Remedy::Do("reload the editor's window"),
    };
    const SESSION: Holder = Holder {
        kind: "session",
        noun: Noun::Counted {
            one: "`tool` session",
            many: "`tool` sessions",
        },
        location: Location::Anywhere,
        remedy: Remedy::Restart,
    };
    const HOLDERS: &[Holder] = &[APP, EXTENSION, SESSION];

    fn at(pid: u32, path: &str) -> Process {
        Process {
            pid,
            path: PathBuf::from(path),
        }
    }

    fn kinds(holding: &[Holding]) -> Vec<(&str, Vec<u32>)> {
        holding
            .iter()
            .map(|h| (h.holder.kind, h.pids.clone()))
            .collect()
    }

    #[test]
    fn each_process_is_the_first_kind_whose_place_holds_it() {
        let holding = classify(
            &[
                at(1, "tool"),
                at(
                    2,
                    "/Applications/App.app/Contents/Helpers/Tool.app/Contents/MacOS/tool",
                ),
                at(3, "/home/a/.editor/extensions/vendor.tool-1.2.3/bin/tool"),
                at(4, "/usr/local/bin/tool"),
            ],
            HOLDERS,
        );
        assert_eq!(
            kinds(&holding),
            [
                ("app", vec![2]),
                ("extension", vec![3]),
                ("session", vec![1, 4])
            ]
        );
    }

    /// The program's own name is not where it runs from: a program that happens to be
    /// called like a place is still wherever it is.
    #[test]
    fn only_the_directories_a_program_is_in_say_where_it_runs() {
        let holding = classify(&[at(1, "/usr/bin/App.app")], HOLDERS);
        assert_eq!(kinds(&holding), [("session", vec![1])]);
        assert!(!Location::WithinPrefixed("vendor.tool-").holds(Path::new("vendor.tool-9")));
    }

    #[test]
    fn nothing_running_is_nothing_held() {
        assert!(classify(&[], HOLDERS).is_empty());
        assert!(
            classify(&[at(1, "tool")], &[APP]).is_empty(),
            "and a process no kind claims is left out"
        );
    }

    #[test]
    fn an_app_is_one_thing_however_many_processes_it_runs() {
        let holding = classify(
            &[
                at(7, "/Applications/App.app/x/tool"),
                at(8, "/Applications/App.app/y/tool"),
            ],
            HOLDERS,
        );
        assert_eq!(described(&holding), "the App");
        assert!(!plural(&holding));
        assert_eq!(described_with_pids(&holding), "the App (pid 7, 8)");
    }

    /// Alone, a kind's advice is what it always was. Beside others, each names what it is
    /// about, and the purpose leads.
    #[test]
    fn what_to_do_is_said_once_for_each_kind() {
        let sessions = classify(&[at(1, "tool"), at(2, "tool")], HOLDERS);
        assert_eq!(described(&sessions), "2 `tool` sessions");
        assert!(plural(&sessions));
        assert_eq!(
            remedies(&sessions, "to use the new account"),
            "Quit them and start again to use the new account."
        );

        let one = classify(&[at(1, "tool")], HOLDERS);
        assert_eq!(described(&one), "1 `tool` session");
        assert_eq!(
            remedies(&one, "to go on"),
            "Quit it and start again to go on."
        );

        let all = classify(
            &[
                at(1, "tool"),
                at(2, "/Applications/App.app/x/tool"),
                at(3, "/e/vendor.tool-1/bin/tool"),
            ],
            HOLDERS,
        );
        assert_eq!(
            described(&all),
            "the App, the extension and 1 `tool` session"
        );
        assert_eq!(
            remedies(&all, "to use the new account"),
            "To use the new account: quit App with Command-Q and open it again; reload the \
             editor's window; quit the `tool` session and start it again."
        );
    }

    #[test]
    fn a_command_is_said_as_one() {
        let holding = classify(
            &[at(1, "/x/daemon/tool")],
            &[Holder {
                kind: "daemon",
                noun: Noun::One("the daemon"),
                location: Location::Within("daemon"),
                remedy: Remedy::Run("tool daemon restart"),
            }],
        );
        assert_eq!(
            remedies(&holding, "to take a switch"),
            "Run `tool daemon restart` to take a switch."
        );
    }

    #[test]
    fn some_pids_stand_for_many() {
        assert_eq!(some_of(&[4321, 99]), "4321, 99");
        let many: Vec<u32> = (1..=23).collect();
        assert_eq!(some_of(&many), "1, 2, 3 and 20 more");
    }
}