zshrs 0.13.3

The first JIT-compiled Unix shell — bytecode VM, Cranelift JIT, worker pool, AOP intercept, Rkyv caching
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
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
//! Executor-side bg-job tracker. NOT a port of `Src/jobs.c`.
//!
//! `Src/jobs.c` uses a flat `struct job jobtab[]` global keyed by pid
//! (ported to `crate::ported::jobs::JOBTAB`). C tracks child processes
//! through their pid + waitpid(2). Rust prefers safe-Rust ownership
//! of `std::process::Child` handles so the executor needs a parallel
//! registry that owns those handles. That's what this file is.
//!
//! This module is segregated from `src/ported/jobs.rs` (the faithful
//! C port) so the port file contains only direct ports of jobs.c
//! decls. `JobState` / `JobInfo` / `JobTable` here are zshrs runtime
//! state with no C counterpart by design.

use std::process::Child;
use std::sync::Mutex;

use crate::ported::jobs::stat;
use crate::ported::jobs::{deletejob, CURJOB, MAXJOB, PREVJOB, THISJOB};
use crate::ported::zsh_h::job;

/// !!! WARNING: RUST-ONLY ADAPTER !!! The job status C derives from a
/// finished process's wait status — update_job's `val`
/// (c:Src/jobs.c:492-496): `WIFSIGNALED ? 0200 | WTERMSIG : WIFSTOPPED ?
/// 0200 | WSTOPSIG : WEXITSTATUS`. zshrs waits on its foreground externals
/// through `std::process::ExitStatus`, whose `code()` is `None` for a
/// signalled child; the call sites turned that into 1, so
/// `sh -c 'kill $$'; print $?` printed 1 where zsh prints 143.
pub fn wait_status_val(s: std::process::ExitStatus) -> i32 {
    use std::os::unix::process::ExitStatusExt as _;
    if let Some(sig) = s.signal() {
        0o200 | sig // c:493
    } else if let Some(sig) = s.stopped_signal() {
        0o200 | sig // c:495
    } else {
        s.code().unwrap_or(0) // c:496
    }
}

thread_local! {
    /// Non-zero while a pipeline's in-shell last stage runs. update_job's
    /// foreground tail reads the status of the job's process-group leader
    /// (c:Src/jobs.c:497-498), which is the FIRST stage, so the externals
    /// the last stage waits for do not drive it.
    ///
    /// !!! WARNING: RUST-ONLY COUNTER — C READS `jn->gleader` !!!
    pub static NOT_JOB_LEADER: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
}

/// !!! WARNING: RUST-ONLY HELPER — C WRITES THROUGH THE `shout` FILE* !!!
/// printjob's asynchronous report goes to `fout = (synch == 2 || !shout) ?
/// stdout : shout` (c:Src/jobs.c:1153), and an interactive shell's `shout`
/// is the terminal, `fdopen(SHTTY, "w")`, or stderr when there is no tty
/// (c:Src/init.c:734-748). Writing to fd 2 instead sent the report through
/// the command's own redirection: `sh -c 'kill -HUP $$' 2>/dev/null` lost
/// its `zsh: hangup` line.
fn shout_write(s: &str) {
    let tty = crate::ported::init::SHTTY.load(std::sync::atomic::Ordering::Relaxed);
    let fd = if tty >= 0 { tty } else { libc::STDERR_FILENO };
    let _ = crate::ported::utils::write_loop(fd, s.as_bytes());
}

/// !!! WARNING: RUST-ONLY ADAPTER !!! update_job's report for the foreground
/// job (c:Src/jobs.c:645-650), for a simple external zshrs waited for outside
/// the job table: `if ((isset(NOTIFY) || job == thisjob) && (jn->stat &
/// STAT_LOCKED)) printjob(jn, !!isset(LONGLISTJOBS), 0);`. The job is one
/// process whose text is the command's job text (`None` when the dispatch
/// carried none, e.g. inside a function, c:Src/exec.c:3536-3538).
///
/// printjob prints nothing for a job marked STAT_NOPRINT, and execpline marks
/// every job run while another pipeline is executing (`pline_level`,
/// c:Src/exec.c:1829-1831): a command inside a function, `eval`, a loop, a
/// `{ … }` or an `if` is never reported, only one at the top of the command
/// line — including either side of `&&`/`||`. `nested` is the caller's
/// in-process `( … )` (C forks it, and the child has no MONITOR).
///
/// Then printjob's own gate (exec_jobs::printjob_async): an interactive
/// shell with MONITOR reports a signal other than SIGINT/SIGPIPE as
/// `zsh: terminated  cmd`, and a SIGINT only with a newline (c:1203-1205,
/// c:1260-1263, c:1338-1341).
pub fn foreground_job_report(status: i32, text: Option<String>, nested: bool) {
    use crate::ported::zsh_h::{CS_CMDAND, CS_CMDOR, SFC_NONE};
    use std::sync::atomic::Ordering;
    let Some(text) = text else { return };
    if nested
        || !libc::WIFSIGNALED(status)
        || NOT_JOB_LEADER.with(|d| d.get()) > 0
        || crate::ported::exec::sfcontext.load(Ordering::Relaxed) != SFC_NONE
        || crate::vm_helper::EVAL_RECURSION_DEPTH.with(|d| d.get()) > 0
    {
        return;
    }
    // c:Src/exec.c:1829-1831 — nested in a compound command (cmdstack holds
    // more than the `&&`/`||` list connectors).
    let in_compound = crate::ported::prompt::CMDSTACK.with(|s| {
        s.borrow()
            .iter()
            .any(|&cs| cs as i32 != CS_CMDAND as i32 && cs as i32 != CS_CMDOR as i32)
    });
    if in_compound {
        return;
    }
    let jn = job {
        stat: stat::INUSE | stat::LOCKED | stat::DONE | stat::CHANGED,
        procs: vec![crate::ported::zsh_h::process {
            pid: 0,
            text,
            status,
            ti: Default::default(),
            bgtime: None,
            endtime: None,
        }],
        ..Default::default()
    };
    // The job sits at index 1 and is `thisjob` (c:Src/jobs.c:645).
    let tab = vec![job::default(), jn];
    printjob_async(&tab, 1, 1);
}

/// !!! WARNING: RUST-ONLY ADAPTER !!! The tail of C `update_job` for the
/// FOREGROUND job (`job == thisjob`, not STAT_CURSH, so `inforeground = 2`,
/// c:Src/jobs.c:558-561), for an external zshrs waited for outside the job
/// table. `status` is the raw wait status of the job's last process.
///
/// c:Src/jobs.c:654-679 —
/// ```c
/// /* When MONITOR is set, the foreground process runs in a different *
///  * process group from the shell, so the shell will not receive     *
///  * terminal signals, therefore we pretend that the shell got       *
///  * the signal too.                                                 */
/// if (inforeground == 2 && isset(MONITOR) && WIFSIGNALED(status)) {
///     int sig = WTERMSIG(status);
///     if (sig == SIGINT || sig == SIGQUIT) {
///         if (sigtrapped[sig]) {
///             dotrap(sig);
///             if (errflag) breaks = loops;
///         } else {
///             breaks = loops;
///             errflag |= ERRFLAG_INT;
///         }
///         check_cursh_sig(sig);
///     }
/// }
/// ```
/// So a child that dies of SIGINT/SIGQUIT ends the rest of the command line
/// (`for i in 1 2; do sh -c 'kill -INT $$'; print $i; done` prints nothing)
/// unless a trap for the signal returns zero.
pub fn foreground_job_signalled(status: i32) {
    use crate::ported::zsh_h::{isset, ERRFLAG_INT, MONITOR};
    use std::sync::atomic::Ordering;
    if NOT_JOB_LEADER.with(|d| d.get()) > 0 || !isset(MONITOR) || !libc::WIFSIGNALED(status) {
        return;
    }
    let sig = libc::WTERMSIG(status); // c:659
    if sig != libc::SIGINT && sig != libc::SIGQUIT {
        return; // c:661
    }
    let loops = crate::ported::builtin::LOOPS.load(Ordering::Relaxed);
    let trapped = crate::ported::signals::sigtrapped
        .lock()
        .ok()
        .and_then(|t| t.get(sig as usize).copied())
        .unwrap_or(0);
    if trapped != 0 {
        crate::ported::signals::dotrap(sig); // c:663
        if crate::ported::utils::errflag.load(Ordering::Relaxed) != 0 {
            crate::ported::builtin::BREAKS.store(loops, Ordering::Relaxed); // c:671-672
        }
    } else {
        crate::ported::builtin::BREAKS.store(loops, Ordering::Relaxed); // c:674
        crate::ported::utils::errflag.fetch_or(ERRFLAG_INT, Ordering::Relaxed); // c:675
    }
    // c:677 — `check_cursh_sig(sig);`
    if let Some(tab) = crate::ported::jobs::JOBTAB.get() {
        if let Ok(jt) = tab.lock() {
            crate::ported::jobs::check_cursh_sig(&jt, sig);
        }
    }
}

/// Executor-side stand-in for C `printjob`'s done-job delete tail,
/// `Src/jobs.c:1350-1363`:
/// ```c
/// if (jn->stat & STAT_DONE) {
///     ...
///     deletejob(jn, 0);
///     if (job == curjob) { curjob = prevjob; prevjob = job; }
///     if (job == prevjob) setprevjob();
/// }
/// ```
/// The ported `printjob` (src/ported/jobs.rs) is a pure formatter
/// returning a String; C's version mutates the table as a side
/// effect. Every site that calls (or would call) printjob on a
/// possibly-done job runs this tail so finished jobs leave the table
/// exactly when they do in C. Lives here (not src/ported/) because
/// it has no C name of its own — it is the side-effect half of
/// printjob, split out by the Rust purity refactor.
pub fn printjob_delete_tail(tab: &mut [job], idx: usize) {
    if idx >= tab.len() || (tab[idx].stat & stat::DONE) == 0 {
        return;
    }
    deletejob(&mut tab[idx], false); // c:Src/jobs.c:1356
    let mut cj = CURJOB.get_or_init(|| Mutex::new(-1)).lock().unwrap();
    let mut pj = PREVJOB.get_or_init(|| Mutex::new(-1)).lock().unwrap();
    if *cj == idx as i32 {
        // c:Src/jobs.c:1357-1360
        *cj = *pj;
        *pj = idx as i32;
    }
    let need_setprev = *pj == idx as i32; // c:Src/jobs.c:1361
    drop(cj);
    drop(pj);
    if need_setprev {
        setprevjob_locked(tab); // c:Src/jobs.c:1362
    }
}

/// `printjob(jn, !!isset(LONGLISTJOBS), 0)` — the asynchronous (synch 0)
/// report update_job issues at `Src/jobs.c:647` when a job changes state.
/// Returns 1-as-true when something was printed (C's `doneprint`).
///
/// Lives here (not src/ported/) because it has no C name of its own. The Rust `printjob` is a pure formatter with no
/// print gate; this is the gate + output half of C's printjob for synch 0.
/// The done-job delete tail (c:1350-1363) stays with the caller
/// (`printjob_delete_tail`), which runs it whether or not this printed —
/// exactly as C falls through to it.
///
/// This path was missing entirely: update_bg_job deleted a finished job
/// without reporting it, so `: &` + `wait` never said `[1]  + done  :`,
/// `kill %1` never said `[1]  + terminated  ...`, and a foreground job
/// killed by a signal never said `zsh: terminated  ...`.
///
/// NOT PORTED: the STAT_SUPERJOB -> subjob redirect (c:1171-1185) and the
/// `(pwd now: …)` line (c:1349-1353).
///
/// WARNING: param names don't match C — Rust=(tab, ji, thisjob) vs
/// C=(jn, lng, synch)
pub fn printjob_async(tab: &[job], ji: usize, thisjob: i32) -> bool {
    use crate::ported::builtins::sched::zleactive;
    use crate::ported::zsh_h::{isset, INTERACTIVE, LONGLISTJOBS, PRINTEXITVALUE, SHINSTDIN, SP_RUNNING};
    use std::sync::atomic::Ordering;
    let jn = &tab[ji];
    // c:1163-1164 — `if (jn->stat & STAT_NOPRINT) skip_print = 1;`
    let mut skip_print = (jn.stat & stat::NOPRINT) != 0;
    let mut sflag = false; // c:1150
    let mut doputnl = false; // c:1151
    let is_thisjob = ji as i32 == thisjob;
    // c:1190-1221 — does any finished process force a report?
    for pn in jn.procs.iter() {
        if pn.status == SP_RUNNING {
            continue; // c:1193
        }
        if libc::WIFSIGNALED(pn.status) {
            let sig = libc::WTERMSIG(pn.status); // c:1195
            if sig != libc::SIGINT && sig != libc::SIGPIPE {
                sflag = true; // c:1202-1203
            }
            if is_thisjob && sig == libc::SIGINT {
                doputnl = true; // c:1204-1205
            }
            if isset(PRINTEXITVALUE) && isset(SHINSTDIN) {
                sflag = true; // c:1206-1208
                skip_print = false;
            }
        } else if libc::WIFSTOPPED(pn.status) {
            let sig = libc::WSTOPSIG(pn.status); // c:1210
            if is_thisjob && sig == libc::SIGTSTP {
                doputnl = true; // c:1214-1215
            }
        } else if isset(PRINTEXITVALUE) && isset(SHINSTDIN) && libc::WEXITSTATUS(pn.status) != 0
        {
            sflag = true; // c:1216-1219
            skip_print = false;
        }
    }
    // c:1224-1238 — a skipped job is only deleted (caller's tail).
    if skip_print {
        return false;
    }
    let interact = isset(INTERACTIVE);
    let stopped = (jn.stat & stat::STOPPED) != 0;
    // c:1248-1250 — `(interact || synch) && jobbing &&
    //                ((jn->stat & STAT_STOPPED) || sflag || job != thisjob)`
    if interact && crate::ported::zsh_h::jobbing() && (stopped || sflag || !is_thisjob) {
        // c:1258-1259 — `if (!synch) zleentry(ZLE_CMD_TRASH);` (trashzle
        // itself is a no-op unless zleactive).
        if zleactive.load(Ordering::Relaxed) != 0 {
            crate::ported::init::zleentry(crate::ported::zsh_h::ZLE_CMD_TRASH);
        }
        let curjob = *CURJOB.get_or_init(|| Mutex::new(-1)).lock().unwrap();
        let prevjob = *PREVJOB.get_or_init(|| Mutex::new(-1)).lock().unwrap();
        let s = crate::ported::jobs::printjob(
            jn,
            ji,
            isset(LONGLISTJOBS) as i32,
            (curjob >= 0).then_some(curjob as usize),
            (prevjob >= 0).then_some(prevjob as usize),
            is_thisjob, // c:1255 — `thisfmt = job == thisjob && synch != 2`
        );
        // c:1260-1263 — `if (doputnl && !synch) putc('\n', fout);`
        let nl = if doputnl { "\n" } else { "" };
        shout_write(&format!("{}{}\n", nl, s));
        return true;
    } else if doputnl && interact {
        // c:1338-1341
        shout_write("\n");
        return true;
    }
    false
}


/// `setprevjob` (Src/jobs.c:698-717) body operating on an
/// already-locked table slice — `printjob_delete_tail` callers hold
/// the JOBTAB lock, so the re-locking ported `setprevjob()` would
/// deadlock. Same walk, same candidate order.
fn setprevjob_locked(tab: &[job]) {
    let maxjob = *MAXJOB
        .get_or_init(|| Mutex::new(0))
        .lock()
        .expect("maxjob poisoned");
    let curjob = *CURJOB.get_or_init(|| Mutex::new(-1)).lock().unwrap();
    let thisjob = *THISJOB.get_or_init(|| Mutex::new(-1)).lock().unwrap();
    let pick = |want_stopped: bool| -> i32 {
        for i in (1..=maxjob).rev() {
            if i >= tab.len() {
                continue;
            }
            let j = &tab[i];
            let stat_ok = if want_stopped {
                (j.stat & (stat::INUSE | stat::STOPPED)) == (stat::INUSE | stat::STOPPED)
            } else {
                (j.stat & stat::INUSE) != 0
            };
            if stat_ok && (j.stat & stat::SUBJOB) == 0 && i as i32 != curjob && i as i32 != thisjob
            {
                return i as i32;
            }
        }
        -1
    };
    let mut found = pick(true); // c:Src/jobs.c:702-707
    if found < 0 {
        found = pick(false); // c:Src/jobs.c:709-714
    }
    *PREVJOB.get_or_init(|| Mutex::new(-1)).lock().unwrap() = found; // c:716
}

/// Running-job state tracked alongside each `Child` handle.
/// Maps to C's `STAT_*` bits but is exposed as a typed enum since
/// the executor's safe-Rust path doesn't manipulate the bitfield.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum JobState {
    /// `Running` variant.
    Running,
    /// `Stopped` variant.
    Stopped,
    /// `Done` variant.
    Done,
}

/// One entry in the executor's bg-job registry.
#[derive(Debug)]
pub struct JobInfo {
    /// `id` field.
    pub id: usize,
    /// `pid` field.
    pub pid: i32,
    /// `child` field.
    pub child: Option<Child>,
    /// `command` field.
    pub command: String,
    /// `state` field.
    pub state: JobState,
    /// `is_current` field.
    pub is_current: bool,
}

/// The executor's bg-job registry. Distinct from the C-port
/// `JOBTAB` (a `Vec<Job>` keyed by index that mirrors `jobtab[]`):
/// this table owns the `std::process::Child` handles needed for
/// `try_wait` / `kill` on the safe-Rust path.
pub struct JobTable {
    /// `jobs` field.
    jobs: Vec<Option<JobInfo>>,
    /// `current_id` field.
    current_id: Option<usize>,
    /// `next_id` field.
    next_id: usize,
}

impl Default for JobTable {
    fn default() -> Self {
        Self::new()
    }
}

impl JobTable {
    /// `new` — see implementation.
    pub fn new() -> Self {
        JobTable {
            jobs: Vec::with_capacity(16),
            current_id: None,
            next_id: 1,
        }
    }

    /// Peek at the next id that would be assigned by `add_job`/`add_pid`.
    /// Used by `wait %N` to distinguish a never-issued id (clear user
    /// error) from a job that was issued and already reaped (silent
    /// success in zshrs to keep the `cmd & wait %1` idiom working
    /// across the races introduced by the threaded job table).
    pub fn peek_next_id(&self) -> usize {
        self.next_id
    }

    /// Add a job with a Child process
    pub fn add_job(&mut self, child: Child, command: String, state: JobState) -> usize {
        let id = self.next_id;
        self.next_id += 1;

        let pid = child.id() as i32;
        let job = JobInfo {
            id,
            pid,
            child: Some(child),
            command,
            state,
            is_current: true,
        };

        // Mark previous current as not current
        if let Some(cur_id) = self.current_id {
            if let Some(j) = self.get_mut_internal(cur_id) {
                j.is_current = false;
            }
        }

        // Add new job
        let slot = self.get_free_slot();
        if slot >= self.jobs.len() {
            self.jobs.resize_with(slot + 1, || None);
        }
        self.jobs[slot] = Some(job);
        self.current_id = Some(id);

        id
    }

    /// Register a backgrounded job that was forked via raw `libc::fork()`
    /// (no `std::process::Child` wrapper). The wait path then has to
    /// `waitpid(pid)` instead of `Child::wait()`. Used by
    /// BUILTIN_RUN_BG so `wait` (no args) can synchronize on it.
    pub fn add_pid_job(&mut self, pid: i32, command: String, state: JobState) -> usize {
        let id = self.next_id;
        self.next_id += 1;
        let job = JobInfo {
            id,
            pid,
            child: None,
            command,
            state,
            is_current: true,
        };
        if let Some(cur_id) = self.current_id {
            if let Some(j) = self.get_mut_internal(cur_id) {
                j.is_current = false;
            }
        }
        let slot = self.get_free_slot();
        if slot >= self.jobs.len() {
            self.jobs.resize_with(slot + 1, || None);
        }
        self.jobs[slot] = Some(job);
        self.current_id = Some(id);
        id
    }

    fn get_free_slot(&self) -> usize {
        for (i, slot) in self.jobs.iter().enumerate() {
            if slot.is_none() {
                return i;
            }
        }
        self.jobs.len()
    }

    fn get_mut_internal(&mut self, id: usize) -> Option<&mut JobInfo> {
        self.jobs.iter_mut().flatten().find(|job| job.id == id)
    }

    /// Get a job by ID
    pub fn get(&self, id: usize) -> Option<&JobInfo> {
        self.jobs
            .iter()
            .flatten()
            .find(|&job| job.id == id)
            .map(|v| v as _)
    }

    /// Get a mutable job by ID
    pub fn get_mut(&mut self, id: usize) -> Option<&mut JobInfo> {
        self.get_mut_internal(id)
    }

    /// Remove a job by ID
    pub fn remove(&mut self, id: usize) -> Option<JobInfo> {
        for slot in self.jobs.iter_mut() {
            if slot.as_ref().map(|j| j.id == id).unwrap_or(false) {
                let job = slot.take();
                if self.current_id == Some(id) {
                    self.current_id = None;
                }
                return job;
            }
        }
        None
    }

    /// List all active jobs
    pub fn list(&self) -> Vec<&JobInfo> {
        self.jobs.iter().filter_map(|j| j.as_ref()).collect()
    }

    /// Iterate over jobs with their IDs (for compatibility)
    pub fn iter(&self) -> impl Iterator<Item = (usize, &JobInfo)> {
        self.jobs
            .iter()
            .filter_map(|j| j.as_ref().map(|job| (job.id, job)))
    }

    /// Count number of active jobs
    pub fn count(&self) -> usize {
        self.jobs.iter().filter(|j| j.is_some()).count()
    }

    /// Check if there are any jobs
    pub fn is_empty(&self) -> bool {
        self.count() == 0
    }

    /// Get current job
    pub fn current(&self) -> Option<&JobInfo> {
        self.current_id.and_then(|id| self.get(id))
    }

    /// Reap finished jobs (check for completed processes)
    pub fn reap_finished(&mut self) -> Vec<JobInfo> {
        let mut finished = Vec::new();

        for job in self.jobs.iter_mut().flatten() {
            if let Some(ref mut child) = job.child {
                // Try to check if child has finished without blocking
                match child.try_wait() {
                    Ok(Some(_status)) => {
                        // Child finished
                        job.state = JobState::Done;
                    }
                    Ok(None) => {
                        // Still running
                    }
                    Err(_) => {
                        // Error checking, assume done
                        job.state = JobState::Done;
                    }
                }
            }
        }

        // Remove done jobs
        for slot in self.jobs.iter_mut() {
            if slot
                .as_ref()
                .map(|j| j.state == JobState::Done)
                .unwrap_or(false)
            {
                if let Some(job) = slot.take() {
                    finished.push(job);
                }
            }
        }

        finished
    }
}

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

    #[test]
    fn test_job_table_new() {
        let _g = crate::test_util::global_state_lock();
        let table = JobTable::new();
        assert!(table.is_empty());
    }

    #[test]
    fn test_job_state_enum() {
        let _g = crate::test_util::global_state_lock();
        let state = JobState::Running;
        assert_eq!(state, JobState::Running);
        assert_ne!(state, JobState::Stopped);
        assert_ne!(state, JobState::Done);
    }

    #[test]
    fn test_add_pid_job_assigns_id() {
        let _g = crate::test_util::global_state_lock();
        let mut t = JobTable::new();
        let id1 = t.add_pid_job(1234, "cmd1".into(), JobState::Running);
        let id2 = t.add_pid_job(5678, "cmd2".into(), JobState::Running);
        assert_ne!(id1, id2);
        assert_eq!(t.list().len(), 2);
        assert_eq!(t.current().map(|j| j.id), Some(id2));
    }

    #[test]
    fn test_remove_drops_current() {
        let _g = crate::test_util::global_state_lock();
        let mut t = JobTable::new();
        let id = t.add_pid_job(99, "x".into(), JobState::Running);
        assert!(t.remove(id).is_some());
        assert!(t.is_empty());
        assert!(t.current().is_none());
    }
}