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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
//! The [`ManagedTmuxDriver`] trait seam used by the session manager.
//!
//! Why: split out of `manager.rs` (issue #1955) purely to keep that file under
//! the 500-SLOC production cap after the serial-numbered naming rework added a
//! new error variant and helper method. The trait itself has no behavior
//! change — it is a mechanical move.
//! What: [`ManagedTmuxDriver`], the minimal tmux operation surface the manager
//! depends on, with default implementations for the operations most drivers
//! do not need to override (`send_keys_literal`, `send_interrupt`,
//! `get_pane_cwd`, `session_exists`, `graceful_stop`).
//! Test: exercised via [`crate::session_manager::real_tmux::RealTmuxDriver`]
//! and the `FakeTmuxDriver` test double in `tests.rs`.
use super::manager::ManagedError;
use super::supervisor_floor::SupervisorFloor;
/// Trait seam over tmux operations used by the session manager.
///
/// Why: the manager must be fully unit-testable without a live tmux binary;
/// a trait lets tests inject a `FakeTmuxDriver` instead of the real
/// [`crate::daemon::tmux::TmuxDriver`].
/// What: minimal surface — create session, kill session, send a line, capture
/// pane output, list session names, and probe existence.
/// Test: `FakeTmuxDriver` in `manager.rs`'s test section (`tests.rs`).
pub trait ManagedTmuxDriver: Send + Sync {
/// Confirm the tmux SERVER exists (starting it if necessary) before any
/// OTHER tmux call in this driver relies on it (#3823).
///
/// Why: on a machine where tmux has never run, the very FIRST tmux call a
/// session-creation/resume flow issues is a `list-sessions` probe
/// (`SessionManager::resolve_session_name`/`dedupe_session_name`'s
/// name-collision checks, `SessionManager::resume`'s
/// `session_exists`/`ensure_pane_alive` checks) — well before the
/// #3386/#3722 `create_managed_session` choke point (which already
/// guarantees server-up, but only for the `set-option -g`/`new-session`
/// sequence it directly issues) is ever reached. Without an explicit
/// guard here, that first `list-sessions` fails on the missing socket and
/// the whole flow 500s instead of transparently starting tmux.
/// What: the default is `Ok(())` — a safe no-op for every test double
/// (`FakeTmuxDriver`, `FakeNoopTmuxDriver`) and the `NoopTmuxDriver`
/// tmux-absent fallback, none of which spawn a real tmux process.
/// [`super::real_tmux::RealTmuxDriver`] overrides this to call
/// [`crate::daemon::tmux::TmuxDriver::ensure_server_up`], which retries
/// `tmux start-server` with backoff via
/// [`crate::core::tmux::ensure_server_up`] (the same #3722 primitive
/// `create_managed_session` uses).
/// Test: `session_manager::server_up_tests` (`create_ensures_server_up_
/// before_creating_session`, `create_fails_loudly_when_server_cannot_
/// start`, `create_with_reserved_name_ensures_server_up_before_creating_
/// session`, `resume_fails_loudly_when_server_cannot_start`) exercises
/// `RealTmuxDriver`'s override via a call-counting/failure-injecting
/// `FakeTmuxDriver`; `daemon::tmux::tests::ensure_server_up_issues_
/// start_server_on_a_fresh_socket`/`_fails_loudly_when_the_server_
/// never_comes_up` cover the underlying `TmuxDriver::ensure_server_up`
/// this override delegates to. The trait default is exercised
/// transitively by every `FakeTmuxDriver`-backed manager test (never
/// errors).
fn ensure_server_up(&self) -> Result<(), ManagedError> {
Ok(())
}
/// Create a detached tmux session named `name`, rooted at `workdir`.
fn create_session(&self, name: &str, workdir: &str) -> Result<(), ManagedError>;
/// Create a detached tmux session named `name` that FAILS when the name is
/// already live, instead of attaching to whatever holds it (#3707).
///
/// Why: [`Self::create_session`] renders `tmux new-session -A`, and `-A`
/// attaches to an existing session of the same name rather than failing.
/// Two concurrent creators that computed the same name therefore both
/// "succeed": one creates the pane, the other silently joins it, and two
/// records are persisted driving one pane. A lost race must be an error the
/// caller can retry under a fresh name, which is what this method makes it.
/// What: the default probes [`Self::session_exists_checked`] first and
/// returns [`ManagedError::NameCollision`] when the name is taken —
/// propagating an unobservable tmux rather than reading it as free.
/// [`super::real_tmux::RealTmuxDriver`] overrides it with a `new-session`
/// that carries no `-A`, so tmux itself decides the race atomically.
/// Test: `two_creators_of_one_name_never_share_a_pane` in
/// `super::create_race_tests`; `RealTmuxDriver`'s override is exercised by the
/// `#[ignore]` live tmux tests.
fn create_session_exclusive(&self, name: &str, workdir: &str) -> Result<(), ManagedError> {
if self.session_exists_checked(name)? {
return Err(ManagedError::NameCollision(format!(
"tmux session `{name}` already exists"
)));
}
self.create_session(name, workdir)
}
/// Apply the configured scrollback/mouse ergonomics to the tmux SERVER.
///
/// Why: a tmux server that came up without tm creating the session — a
/// tmux-resurrect/continuum restore after a server restart runs its own
/// bare `new-session` (#6469) — never passes through
/// [`crate::core::tmux::create_managed_session`], so the server globals tm
/// specifies are simply absent and restored panes bake tmux's factory
/// 2000-line `history-limit`. The daemon's boot reconcile is the one place
/// that observes such a server, so it is the place to re-assert them.
/// What: the default is a no-op — every test double and the tmux-absent
/// fallback have no server to configure.
/// [`super::real_tmux::RealTmuxDriver`] overrides it with
/// [`crate::daemon::tmux::TmuxDriver::apply_scrollback_options`].
/// Test: `reconcile_on_boot_reapplies_the_scrollback_server_options` in
/// `super::tests`.
fn apply_scrollback_options(&self) {}
/// Kill the tmux session named `name`.
fn kill_session(&self, name: &str) -> Result<(), ManagedError>;
/// Rename the live tmux session `old` → `new`.
///
/// Why: `tm sessions rename` keeps the tmux entity's name in sync with the
/// record's `tmux_name` so `tmux attach`/`list-sessions` show the new name.
/// What: the default FAILS CLOSED — a driver that cannot rename must not
/// silently succeed and let the stored name drift from the live session;
/// [`super::real_tmux::RealTmuxDriver`] runs `tmux rename-session`.
/// Test: `RealTmuxDriver` override via the `#[ignore]` live test;
/// `FakeTmuxDriver` overrides to rename in its in-memory session map.
fn rename_session(&self, old: &str, new: &str) -> Result<(), ManagedError> {
Err(ManagedError::TmuxUnavailable(format!(
"rename-session not implemented for this driver ({old} -> {new})"
)))
}
/// Rename the session whose `$N` id is `session_id`, which carries `name`,
/// to `new` (#9101).
///
/// Why: a rename by name reaches whichever session holds the name when
/// tmux runs; the id names the session ownership was proved for.
/// What: the default fails closed, as [`Self::rename_session`] does.
/// [`super::real_tmux::RealTmuxDriver`] runs `rename-session -t $N`.
/// Test: `rename_renames_live_tmux_session`.
fn rename_session_id(
&self,
name: &str,
session_id: &str,
new: &str,
) -> Result<(), ManagedError> {
Err(ManagedError::TmuxUnavailable(format!(
"this driver cannot rename session {session_id} ('{name}') by id to {new}"
)))
}
/// Names of tmux sessions with a client currently ATTACHED.
///
/// Why: the `tm ls` list reconciliation distinguishes an ATTACHED session
/// from a merely-live detached one so the picker renders `attached` and
/// offers connect rather than a destructive restart.
/// What: the default is EMPTY (best-effort — a driver that cannot report
/// attachment simply never marks a session attached);
/// [`super::real_tmux::RealTmuxDriver`] overrides it via tmux
/// `#{session_attached}`.
/// Test: `RealTmuxDriver` override is exercised by the `#[ignore]` live
/// test; `FakeTmuxDriver` seeds attachment for `list_reconciles_*` coverage.
fn attached_session_names(&self) -> Vec<String> {
Vec::new()
}
/// Send literal text followed by Enter to the session named `name`.
fn send_line(&self, name: &str, text: &str) -> Result<(), ManagedError>;
/// Send a SHELL COMMAND line, refusing one the pane's tty would truncate
/// (#8233).
///
/// Why: a pane's tty is in CANONICAL mode until its shell's line editor
/// takes over, and that line discipline holds at most `MAX_CANON` bytes —
/// 1024 on macOS. `tmux send-keys` writes into that buffer, so a longer
/// command loses its tail in the KERNEL, where nothing downstream can see
/// it: session `dd0e2fb8-…` died with a 1054-byte launch line cut off
/// mid-path. Every builder that types a command at a shell prompt goes
/// through here so an over-length line fails LOUDLY.
///
/// Deliberately NOT applied to [`Self::send_line`] itself: `inject` and the
/// pending-decision answer share that primitive and type into Claude Code's
/// RAW-mode TUI, where `MAX_CANON` does not apply and a multi-kilobyte task
/// is routine. Guarding the shared primitive would break task delivery to
/// enforce a limit that is not in force there.
/// What: [`crate::core::tmux::refuse_oversized_pane_command`] first — on
/// refusal NOTHING is typed and the message comes back as an `InvalidInput`
/// I/O error — then [`Self::send_line_to_pane`] when `pane_id` is `Some`,
/// else [`Self::send_line`].
/// Test: `send_command_line_refuses_an_oversized_line`,
/// `send_command_line_targets_the_named_pane`.
fn send_command_line(
&self,
name: &str,
pane_id: Option<&str>,
text: &str,
) -> Result<(), ManagedError> {
if let Some(msg) = crate::core::tmux::refuse_oversized_pane_command(text) {
return Err(ManagedError::Io(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
msg,
)));
}
match pane_id {
Some(pane) => self.send_line_to_pane(name, pane, text),
None => self.send_line(name, text),
}
}
/// Send literal text to `name` WITHOUT a trailing Enter (#1461).
///
/// Why: the harness-agnostic [`Submit::NoSubmit`](crate::core::sm::control::Submit::NoSubmit)
/// intent must type into the pane without committing the line (e.g. staging a
/// partial command a human will edit). Splitting this out keeps `send_line`
/// (literal + Enter) and this (literal only) as distinct, testable primitives.
/// What: sends `text` literally. The default returns an explicit
/// `TmuxUnavailable` error rather than silently falling back to `send_line`:
/// delegating to `send_line` would append an Enter and SUBMIT a line the
/// caller asked NOT to submit (`Submit::NoSubmit`) — a silent-wrong-behavior
/// trap. Any driver actually used with `inject(.., NoSubmit)` MUST override
/// this (the real `RealTmuxDriver` does); an un-overriding driver fails loudly.
/// Test: `RealTmuxDriver` override is asserted via `core::tmux` argv tests;
/// the no-submit dispatch is asserted by `inject_dispatch_nosubmit_sends_literal_only`.
fn send_keys_literal(&self, _name: &str, _text: &str) -> Result<(), ManagedError> {
Err(ManagedError::TmuxUnavailable(
"send_keys_literal not implemented for this driver".into(),
))
}
/// Send literal text followed by Enter to a SPECIFIC pane within `name`'s
/// tmux session, rather than whichever pane happens to be active.
///
/// Why (sibling-window hijack, follow-up to #2456): `send_line` addresses
/// the tmux SESSION only. tmux resolves a session-scoped target to
/// whichever pane/window is currently ACTIVE — not necessarily the pane
/// this call is actually about. `SessionManager::resume`'s reuse branch
/// discovered this the hard way: a sibling window opened after the
/// original pane, left active, silently received the respawned `claude`
/// process while the original pane sat at a bare shell. This method is
/// the pane-scoped alternative: it must land in the exact pane addressed
/// by `pane_id`, regardless of tmux's notion of "active".
/// What: sends `text` + Enter to the pane addressed by `name:pane_id`
/// (tmux's `-t <session>:<pane_id>` form). The default falls back to
/// [`Self::send_line`] (session-scoped) — correct for any driver that
/// predates pane-level addressing or has no pane to target yet (e.g. a
/// freshly created session, where the session-scoped target IS the only
/// pane). [`super::real_tmux::RealTmuxDriver`] overrides this to build an
/// actual pane-scoped `TmuxTarget`.
/// Test: `RealTmuxDriver`'s override is exercised by `core::tmux`'s
/// pane-target argv coverage (`TmuxTarget::pane`); call-site assertions
/// live in `runtime::test_helpers::FakeTmux` (`pane_sends`) and
/// `claude_code`'s `spawn_resume_targets_stored_pane_id_when_known` test.
fn send_line_to_pane(&self, name: &str, pane_id: &str, text: &str) -> Result<(), ManagedError> {
let _ = pane_id;
self.send_line(name, text)
}
/// Send literal text WITHOUT a trailing Enter to a SPECIFIC pane (#2468,
/// same rationale as [`Self::send_line_to_pane`]).
///
/// What: the pane-scoped counterpart to [`Self::send_keys_literal`],
/// used by `SessionManager::inject`'s `Submit::NoSubmit` dispatch when
/// `record.pane_id` is known. The default returns an explicit
/// `TmuxUnavailable` error rather than silently falling back to
/// `send_keys_literal(name, text)` (#2514 review, minor finding 5): a
/// silent session-scoped fallback here is exactly the sibling-window
/// hijack #2468 exists to close, and a future driver that forgets to
/// override this method would silently REGAIN the vulnerability with no
/// compiler signal. Mirrors the fail-closed pattern already used by
/// [`Self::send_keys_literal`]'s own default. Any driver actually used
/// with a known `pane_id` MUST override this — both
/// [`super::real_tmux::RealTmuxDriver`] and the test-only
/// `FakeTmuxDriver` do.
/// Test: `inject_nosubmit_targets_pane_when_pane_id_known` in
/// `pane_scoped_tests.rs`; `send_keys_literal_to_pane_default_fails_closed`
/// in this module's tests.
fn send_keys_literal_to_pane(
&self,
name: &str,
pane_id: &str,
text: &str,
) -> Result<(), ManagedError> {
let _ = (name, pane_id, text);
Err(ManagedError::TmuxUnavailable(
"send_keys_literal_to_pane not implemented for this driver".into(),
))
}
/// Report whether `pane_id` still exists as a live pane within `name`'s
/// tmux session.
///
/// Why (sibling-window hijack, follow-up to #2456): `resume`'s reuse
/// branch must distinguish "the recorded pane is still there" from "the
/// tmux SESSION merely has some OTHER pane alive" (e.g. a sibling window
/// opened after the original pane was closed) — `session_exists` alone
/// conflates the two, which is exactly how the hijack happens: the
/// session look-alive check passes, so the code reuses it, then respawns
/// via a session-scoped target that resolves to the sibling.
/// What: returns `true` when the pane is confirmed present, `false` when
/// confirmed absent. The default is `true` — "cannot verify" is treated
/// as "assume present," so a driver that does not implement pane-level
/// listing keeps today's session-scoped reuse behavior; this is a
/// STRICTER check layered on top for drivers that opt in, not a new
/// failure mode for ones that do not.
/// [`super::real_tmux::RealTmuxDriver`] overrides this to actually query
/// `tmux list-panes`.
/// Test: `RealTmuxDriver`'s override is covered by `core::tmux`'s
/// `list_panes_argv`; the manager-level refusal path is covered by
/// `resume_refuses_when_stored_pane_gone_but_session_alive` in
/// `resume_reattach_tests.rs`.
fn pane_exists(&self, _name: &str, _pane_id: &str) -> bool {
true
}
/// Tri-state variant of [`Self::pane_exists`] distinguishing "confirmed
/// present", "confirmed absent", and "could not determine" (#3714 review
/// finding 2).
///
/// Why: [`Self::pane_exists`]'s bare `bool` deliberately collapses
/// "confirmed absent" and "query failed" into `false` — correct,
/// fail-closed behavior for a MUTATION guard (e.g.
/// `SessionManager::rename` must never trust an unverifiable pane as
/// safe to physically retarget — that call site keeps using
/// [`Self::pane_exists`] unchanged). A DISPLAY-only reconciler
/// (`daemon::managed_routes::summary::reconcile_live_state`) has the
/// opposite risk: collapsing "could not determine" into "not live"
/// would flip a genuinely live record's SHOWN `state` to `"stopped"` on
/// a transient tmux query hiccup — reproducing the exact
/// `state`/`persisted_state` disagreement #3714 exists to fix, just
/// from a different trigger. This lets that caller fall back to a
/// weaker signal (name-only) on `None` instead of asserting an absence
/// it cannot actually prove.
/// What: the default derives from [`Self::pane_exists`] — `true` maps to
/// `Some(true)`, `false` maps to `Some(false)`; a driver that never
/// overrides `pane_exists` therefore never produces `None`, matching its
/// existing "cannot verify → assume present" semantics exactly.
/// [`super::real_tmux::RealTmuxDriver`] overrides this to call
/// `TmuxDriver::pane_exists_checked` directly, so a genuine
/// `list-panes` query failure reports `None` rather than `Some(false)`.
/// Test: `RealTmuxDriver`'s override is covered by the same
/// `core::tmux::list_panes_argv` coverage `pane_exists` uses; the
/// display-reconciliation consumer is covered by
/// `reconcile_live_state_pane_query_error_does_not_flip_live_record_to_stopped`
/// in `daemon::managed_routes::tests`.
fn pane_exists_checked(&self, name: &str, pane_id: &str) -> Option<bool> {
Some(self.pane_exists(name, pane_id))
}
/// Send an interrupt (Ctrl-C) to the session named `name` (#1461).
///
/// Why: the [`Submit::Interrupt`](crate::core::sm::control::Submit::Interrupt)
/// intent stops a running task in place (the clean precursor to relaunching a
/// runtime). Exposing it on the trait keeps the interrupt path runtime-neutral.
/// What: sends the runtime's interrupt. The default returns an explicit
/// `TmuxUnavailable` error rather than a silent no-op `Ok(())`: Interrupt is
/// the verb used to STOP a running task, so a silent no-op would leave the
/// task running while the caller believes it was interrupted — a dangerous
/// silent-wrong-behavior trap. Any driver actually used with
/// `inject(.., Interrupt)` MUST override this (the real `RealTmuxDriver` sends
/// `C-c`); an un-overriding driver fails loudly.
/// Test: `RealTmuxDriver` override via `core::tmux::send_keys_keyname_argv`;
/// dispatch asserted by `inject_dispatch_interrupt_sends_ctrl_c`.
fn send_interrupt(&self, _name: &str) -> Result<(), ManagedError> {
Err(ManagedError::TmuxUnavailable(
"send_interrupt not implemented for this driver".into(),
))
}
/// Send Ctrl-C to a SPECIFIC pane rather than the session (#2468, same
/// rationale as [`Self::send_line_to_pane`]).
///
/// What: the pane-scoped counterpart to [`Self::send_interrupt`], used by
/// `SessionManager::inject`'s `Submit::Interrupt` dispatch when
/// `record.pane_id` is known. The default returns an explicit
/// `TmuxUnavailable` error rather than silently falling back to
/// `send_interrupt(name)` (#2514 review, minor finding 5) — the same
/// fail-closed rationale as [`Self::send_keys_literal_to_pane`]'s default:
/// a silent session-scoped fallback would regain the sibling-window
/// hijack #2468 fixed, with no compiler signal warning a future driver
/// that it forgot to override this. Any driver actually used with a known
/// `pane_id` MUST override this — both
/// [`super::real_tmux::RealTmuxDriver`] and the test-only
/// `FakeTmuxDriver` do.
/// Test: `inject_interrupt_targets_pane_when_pane_id_known` in
/// `pane_scoped_tests.rs`; `send_interrupt_to_pane_default_fails_closed`
/// in this module's tests.
fn send_interrupt_to_pane(&self, name: &str, pane_id: &str) -> Result<(), ManagedError> {
let _ = (name, pane_id);
Err(ManagedError::TmuxUnavailable(
"send_interrupt_to_pane not implemented for this driver".into(),
))
}
/// Capture the last `lines` of pane output for the session named `name`.
///
/// `lines` is `usize` to match the harness-agnostic
/// [`SessionControl::observe`](crate::core::sm::control::SessionControl::observe)
/// contract end-to-end; the single `usize → u32` narrowing the underlying
/// tmux `-S` argv requires is confined to the real-tmux driver edge, so no
/// caller in the observe path needs a `try_from`.
fn capture(&self, name: &str, lines: usize) -> Result<String, ManagedError>;
/// Capture the last `lines` of output from a SPECIFIC pane rather than
/// whichever pane the session name currently resolves to (#2468).
///
/// Why: `SessionManager::observe`'s LLM-free pane read had the same
/// sibling-window-hijack hole #2467 fixed for resume/restart — a
/// session-scoped capture reads whatever pane tmux considers active,
/// which need not be the pane this record is actually about.
/// What: the pane-scoped counterpart to [`Self::capture`]. The default
/// returns an explicit `TmuxUnavailable` error rather than silently
/// falling back to `capture(name, lines)` (session-scoped) (#2514 review,
/// minor finding 5) — the same fail-closed rationale as
/// [`Self::send_keys_literal_to_pane`]'s default: a silent session-scoped
/// fallback would regain the sibling-window hijack #2468 fixed for reads
/// too, with no compiler signal warning a future driver that it forgot to
/// override this. Any driver actually used with a known `pane_id` MUST
/// override this — both [`super::real_tmux::RealTmuxDriver`] and the
/// test-only `FakeTmuxDriver` do.
/// Test: `observe_captures_pane_scoped_when_pane_id_known` in
/// `pane_scoped_tests.rs`; `capture_pane_default_fails_closed` in this
/// module's tests.
fn capture_pane(
&self,
name: &str,
pane_id: &str,
lines: usize,
) -> Result<String, ManagedError> {
let _ = (name, pane_id, lines);
Err(ManagedError::TmuxUnavailable(
"capture_pane not implemented for this driver".into(),
))
}
/// Return the pane's current working directory for snapshot-before-stop (#1816).
///
/// Why: the idle auto-stop path captures cwd just before killing tmux so
/// `resume()` can restore the operator's working directory instead of always
/// starting at the workspace root. Returning `None` (the default) is safe —
/// resume falls back to `workspace_path`/`cwd` as before.
/// What: returns the `pane_current_path` tmux format string value, or `None`
/// if the driver does not support it or the call fails.
/// Test: `RealTmuxDriver` runs `tmux display-message`; fake drivers return `None`.
fn get_pane_cwd(&self, _name: &str) -> Option<std::path::PathBuf> {
None
}
/// Return the session's pane's stable tmux `pane_id` (e.g. `"%5"`),
/// captured at spawn/reconcile time for pane-identity confirmation
/// (#2453 review finding 1, round 2).
///
/// Why: a session-name or process-env-var match is not proof the
/// operator's CURRENT pane is the one bound to a record — see
/// [`super::record::SessionRecord::pane_id`]'s doc for the full
/// rationale (session-scoped `tmux set-environment` is inherited by
/// sibling panes created afterward, which defeats an env-var-only gate).
/// `pane_id` is tmux's own identifier and is never inherited across
/// panes.
/// What: returns the `pane_id` tmux format string value, or `None` if
/// the driver does not support it or the call fails — the safe default,
/// mirroring [`Self::get_pane_cwd`]. Callers MUST treat `None` as
/// "identity unconfirmed," never as an implicit match.
/// Test: `RealTmuxDriver` runs `tmux display-message`; fake drivers
/// return `None` unless a test explicitly seeds one.
fn get_pane_id(&self, _name: &str) -> Option<String> {
None
}
/// The identity of pane `pane_id` on the live tmux server (#9004).
///
/// Why: a `%N` id is unique within one server only, so ownership also
/// needs the server instance and the session's `$N` id to kill by.
/// What: the default is `Err` — a driver that cannot read the identity
/// never proves ownership. [`super::real_tmux::RealTmuxDriver`] reads it
/// with one `display-message -t %N`.
/// Test: `an_unreadable_pane_identity_leaves_the_runtime_running`.
fn pane_identity(
&self,
pane_id: &str,
) -> Result<super::pane_identity::PaneIdentity, ManagedError> {
Err(ManagedError::TmuxUnavailable(format!(
"this driver cannot read the identity of pane {pane_id}"
)))
}
/// The `%N` id of every pane in session `name`, across all its windows
/// (#9313).
///
/// Why: a rebind may bind a record only to the ONE pane a session holds;
/// it must see every pane to tell one from many.
/// What: the default is `Err`, so a driver that cannot list panes never
/// rebinds a record. [`super::real_tmux::RealTmuxDriver`] runs
/// `list-panes -s -t '=name:'`.
/// Test: `a_pane_list_error_leaves_that_record_unchanged_and_rebinds_the_rest`.
fn session_pane_ids(&self, name: &str) -> Result<Vec<String>, ManagedError> {
Err(ManagedError::TmuxUnavailable(format!(
"this driver cannot list the panes of session '{name}'"
)))
}
/// The process in the foreground of pane `pane_id` (#9566).
///
/// Why: an in-place reactivate may proceed only from a pane whose agent is
/// gone; a pane id proves where the caller is, not what still runs there.
/// What: the default is `Err`, so a driver that cannot read the command
/// never lets an in-place reactivate through.
/// [`super::real_tmux::RealTmuxDriver`] runs one `display-message -t %N`.
/// Test: `a_stopped_record_whose_pane_runs_a_live_agent_is_never_reactivated_in_place`.
fn pane_foreground_command(&self, pane_id: &str) -> Result<String, ManagedError> {
Err(ManagedError::TmuxUnavailable(format!(
"this driver cannot read the foreground command of pane {pane_id}"
)))
}
/// Kill the session whose `$N` id is `session_id`, which carries `name`,
/// unless the [`Self::supervisor_floor`] refuses `name` (#9004).
///
/// Why: a kill by name reaches whichever session holds the name at that
/// instant; a session id is never reused within one server instance.
/// What: the default is `Err`, so a driver that cannot kill by id kills
/// nothing. [`super::real_tmux::RealTmuxDriver`] runs
/// `kill-session -t $N`.
/// Test: `stopping_a_record_whose_pane_is_live_still_kills_it`.
fn kill_session_id(&self, name: &str, session_id: &str) -> Result<(), ManagedError> {
Err(ManagedError::TmuxUnavailable(format!(
"this driver cannot kill session {session_id} ('{name}') by id"
)))
}
/// Return all live tmux session names on the host.
fn list_sessions(&self) -> Result<Vec<String>, ManagedError>;
/// Whether a tmux session with this name currently exists, keeping
/// "confirmed absent" and "could not tell" apart (#5859).
///
/// Why: [`Self::session_exists`] answers `false` for both, and two
/// destructive guards used to read that `false` as proof of death — the
/// delete/prune running-guard ([`super::prune::is_running`]) and
/// [`super::SessionManager::resume`]'s reuse-or-recreate branch. A
/// transient `list-sessions` failure, or the
/// [`super::real_tmux::NoopTmuxDriver`] installed whenever
/// `RealTmuxDriver::discover()` fails, then read a live attached pane as
/// prunable without `--force`, or as a dead pane to kill and rebuild.
/// This is the same "a liveness check that cannot see tmux is not proof of
/// death" rule [`super::SessionManager::observed_live_managed_names`]
/// already applies to the boot-time passes (#5856).
/// What: propagates [`Self::list_sessions`]'s error instead of folding it
/// into `false`. A driver that can probe one session more cheaply than
/// listing them all may override this; overriding THIS method (rather than
/// `session_exists`) keeps both spellings of the question consistent.
/// Test: `delete_record_refuses_when_the_tmux_probe_fails`,
/// `prune_refuses_when_the_tmux_probe_fails`,
/// `resume_refuses_when_the_tmux_probe_fails`.
fn session_exists_checked(&self, name: &str) -> Result<bool, ManagedError> {
self.list_sessions()
.map(|names| names.iter().any(|n| n == name))
}
/// True if a tmux session with this name currently exists, reading an
/// undeterminable probe as absent.
///
/// Why: display and best-effort callers (status rendering, name-collision
/// avoidance, the worktree inventory report) already tolerate an unknown
/// answer and must not fail for it. A caller that ACTS destructively on
/// `false` must call [`Self::session_exists_checked`] instead (#5859).
/// What: [`Self::session_exists_checked`] with `Err` mapped to `false`.
/// Test: covered through its callers; the error arm is pinned by
/// `session_exists_reads_an_unobservable_probe_as_absent`.
fn session_exists(&self, name: &str) -> bool {
self.session_exists_checked(name).unwrap_or(false)
}
/// Probe whether the runtime inside `name`'s pane is READY to accept typed
/// input (issue #1903 / #1299).
///
/// Why: turnkey task injection (`SessionManager::inject_task_when_ready`)
/// must not type the task into the pane before the runtime (`claude`) has
/// actually launched — keystrokes sent to a pane whose shell is still
/// exec-ing the runtime are lost or mangled. This is the readiness signal
/// the injection loop polls (with bounded backoff) before delivering the
/// task, replacing the blind fixed sleep the meta-launch prototype used.
/// What: the default is `session_exists(name)` — sufficient for the test
/// doubles (a fake reports its created session as existing) and a safe
/// lower bound for any driver that cannot inspect the pane's process tree.
/// [`super::real_tmux::RealTmuxDriver`] overrides this to the stronger
/// signal: the `claude` child PID has appeared under the pane shell (the
/// same probe `daemon::services::session_service::spawn_pid_capture` uses).
/// Test: `RealTmuxDriver`'s override is exercised by the `#[ignore]` live
/// integration test; the default is exercised via `FakeTmuxDriver` in
/// `session_manager::task_inject`'s tests.
fn runtime_ready(&self, name: &str) -> bool {
self.session_exists(name)
}
/// Whether a `claude` runs in session `name`'s pane (#8942).
///
/// What: the default is `Unknown`, so a driver that cannot inspect the
/// pane never passes for a claude-free one. The real driver asks
/// [`crate::core::process::pane_claude`].
/// Test: `a_helper_whose_pane_pid_cannot_be_read_is_not_registered`.
fn pane_claude(&self, _name: &str) -> crate::core::process::PaneClaude {
crate::core::process::PaneClaude::Unknown
}
/// Durably publish `key=value` into the named session's tmux environment
/// (#2157 item 1) — belt-and-suspenders alongside the pane-shell `export …;`
/// prefix `runtime::claude_code`/`runtime::tcode` already send.
///
/// Why: the pane-shell export only lands in the ONE shell process that ran
/// the spawn/resume command line; a sibling pane/window in the same tmux
/// session (or a pane spawned before this method existed) never sees it.
/// `tmux set-environment` writes into the SESSION's own environment table,
/// which `tmux show-environment` can read from ANY pane in that session
/// regardless of vintage — this is what lets the in-place-relaunch gate
/// (`bin/tm/commands/guided_inplace.rs`) fall back to a tmux-side read when
/// the process environment does not carry `TM_MANAGED_SESSION_ID`.
/// What: the default is a silent `Ok(())` no-op — this is best-effort
/// durability plumbing, not a caller-visible control action like
/// `send_keys_literal`/`send_interrupt`, so a driver that cannot support it
/// (e.g. tmux absent) must never fail the spawn/resume it is attached to.
/// [`super::real_tmux::RealTmuxDriver`] overrides this to actually call
/// tmux; test doubles record the call for assertions.
/// Test: `RealTmuxDriver` override is asserted via `core::tmux::
/// set_environment_argv`; call-site assertions live in
/// `runtime::test_helpers::FakeTmux` and `session_manager::tests::
/// FakeTmuxDriver`.
fn set_environment(&self, _name: &str, _key: &str, _value: &str) -> Result<(), ManagedError> {
Ok(())
}
/// The protected-name floor [`Self::signal_terminate`] asks (#8942).
///
/// Why: the signal half of a teardown reaches the pane by name too.
/// What: the host floor; [`super::real_tmux::RealTmuxDriver`] returns
/// the one its `TmuxDriver` kills under.
/// Test: `stopping_a_stale_record_never_kills_a_session_named_by_an_architect_sidecar`.
fn supervisor_floor(&self) -> SupervisorFloor {
SupervisorFloor::host()
}
/// Signal a session's process to stop, then kill the tmux session.
///
/// Why: abruptly killing a session (`kill_session`) discards any in-flight
/// work the claude process was persisting. Sending a termination signal first
/// gives the process a chance to flush state — the async caller is responsible
/// for inserting the ~2 s grace window before calling this (see
/// `SessionManager::shutdown` in `restart_ops.rs`). This method is
/// intentionally synchronous so it can live on the non-async trait; the delay
/// is owned by the async shutdown path to avoid blocking a Tokio worker thread.
/// What: if `claude_pid` is known, sends SIGTERM via `nix::signal::kill`;
/// then unconditionally calls `kill_session`. If `claude_pid` is `None`,
/// falls back to `send_interrupt` (Ctrl-C) before the kill. Signal errors are
/// logged as warnings (the process may have already exited); only
/// `kill_session` failure is returned as `Err`. Does NOT sleep — callers
/// must insert an async delay (`tokio::time::sleep`) between the signal phase
/// and calling this if a grace window is desired.
/// Test: `fake_driver_graceful_stop_with_pid` (pid known, records kill),
/// `fake_driver_graceful_stop_without_pid` (no pid, falls back to C-c).
///
/// #9101: deprecated, not removed, because the trait is public API. It
/// signals and kills by the reusable session NAME, so it can reach a
/// session that took a stale record's name. No production path calls it;
/// a teardown classifies with `runtime_ownership` and kills by `$N` id.
#[deprecated(
note = "#9101: kills by session name; prove ownership with runtime_ownership and \
kill with kill_session_id"
)]
fn graceful_stop(&self, name: &str, claude_pid: Option<u32>) -> Result<(), ManagedError> {
self.signal_terminate(name, claude_pid);
self.kill_session(name)
}
/// Signal a session's `claude` process to stop WITHOUT killing the pane.
///
/// Why: a truly graceful teardown sends the termination signal, waits a grace
/// window so `claude` can flush state, and only THEN reclaims the pane. That
/// ordering requires the signal and the kill to be separate steps — so this is
/// the signal-only half, letting an async caller insert a `tokio::time::sleep`
/// grace window between it and `kill_session` (see
/// [`SessionManager::graceful_terminate_runtime`](crate::session_manager::SessionManager::graceful_terminate_runtime) for the CLI stop/decommission
/// path). `graceful_stop` composes this with an immediate kill for the
/// batched, one-grace-window-for-all shutdown path.
/// What: SIGTERMs the known `claude_pid` via `nix::signal::kill` (unix only);
/// when the pid is unknown, falls back to a single `send_interrupt` (Ctrl-C).
/// Signal errors are logged and swallowed — the process may already be gone —
/// so this method is infallible (the fallible reclaim lives in `kill_session`).
/// #8942: a name the [`Self::supervisor_floor`] refuses gets no signal
/// at all — neither the SIGTERM nor the Ctrl-C.
/// Test: `fake_driver_graceful_stop_with_pid` / `_without_pid` cover the
/// composed `graceful_stop`; the CLI drain is covered by
/// `graceful_terminate_runtime_signals_then_kills` in `restart_ops`; the
/// floor by `stopping_a_stale_record_never_kills_a_session_named_by_an_architect_sidecar`.
fn signal_terminate(&self, name: &str, claude_pid: Option<u32>) {
let floor = self.supervisor_floor();
if floor
.refuse(name, "ManagedTmuxDriver::signal_terminate")
.is_some()
{
return;
}
if let Some(pid) = claude_pid {
#[cfg(unix)]
{
use nix::sys::signal::{Signal, kill};
use nix::unistd::Pid;
if let Err(e) = kill(Pid::from_raw(pid as i32), Signal::SIGTERM) {
tracing::warn!(pid, name, "signal_terminate: SIGTERM failed: {e}");
}
}
#[cfg(not(unix))]
{
let _ = pid; // SIGTERM not applicable on non-unix
}
} else {
// No pid — best effort interrupt via tmux send-keys.
let _ = self.send_interrupt(name);
}
}
/// [`Self::signal_terminate`] for one known pane of `name` (#8935).
///
/// Why: with no `claude` pid, `signal_terminate`'s Ctrl-C goes to the
/// session's ACTIVE pane, which need not be the pane the record owns.
/// What: a known pid gets `signal_terminate`'s SIGTERM; otherwise, unless
/// the [`Self::supervisor_floor`] refuses `name`, one
/// [`Self::send_interrupt_to_pane`] to `pane_id`. Errors are swallowed,
/// as in `signal_terminate`.
/// Test: `stopping_a_record_whose_pane_is_live_still_kills_it`.
fn signal_terminate_pane(&self, name: &str, pane_id: &str, claude_pid: Option<u32>) {
if claude_pid.is_some() {
return self.signal_terminate(name, claude_pid);
}
let floor = self.supervisor_floor();
if floor
.refuse(name, "ManagedTmuxDriver::signal_terminate_pane")
.is_some()
{
return;
}
let _ = self.send_interrupt_to_pane(name, pane_id);
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A minimal driver that overrides only the REQUIRED (non-defaulted)
/// trait methods, so `send_keys_literal_to_pane`, `send_interrupt_to_pane`,
/// and `capture_pane` all run the trait's own default bodies — exactly
/// the "a driver forgot to override this" scenario minor finding 5
/// (#2514 review) is guarding against.
struct MinimalDriver;
impl ManagedTmuxDriver for MinimalDriver {
fn create_session(&self, _name: &str, _workdir: &str) -> Result<(), ManagedError> {
Ok(())
}
fn kill_session(&self, _name: &str) -> Result<(), ManagedError> {
Ok(())
}
fn send_line(&self, _name: &str, _text: &str) -> Result<(), ManagedError> {
Ok(())
}
fn capture(&self, _name: &str, _lines: usize) -> Result<String, ManagedError> {
Ok(String::new())
}
fn list_sessions(&self) -> Result<Vec<String>, ManagedError> {
Ok(Vec::new())
}
}
/// #8233: a command line the pane's tty would truncate must be REFUSED, not
/// typed. `MinimalDriver::send_line` always succeeds, so a `Ok` here would
/// mean the guard never ran.
#[test]
fn send_command_line_refuses_an_oversized_line() {
let line = "x".repeat(crate::core::tmux::MAX_PANE_COMMAND_BYTES + 1);
let err = MinimalDriver
.send_command_line("sess", None, &line)
.expect_err("an over-length command line must be refused, never truncated");
let ManagedError::Io(io) = &err else {
panic!("expected an I/O refusal, got {err}");
};
assert_eq!(io.kind(), std::io::ErrorKind::InvalidInput);
assert!(err.to_string().contains("#8233"), "{err}");
}
/// The guard must not change WHERE an accepted line lands: a `pane_id`
/// still routes through the pane-scoped send (sibling-window hijack, #2456).
#[test]
fn send_command_line_targets_the_named_pane() {
use std::sync::Mutex;
struct PaneRecorder(Mutex<Vec<(Option<String>, String)>>);
impl ManagedTmuxDriver for PaneRecorder {
fn create_session(&self, _n: &str, _w: &str) -> Result<(), ManagedError> {
Ok(())
}
fn kill_session(&self, _n: &str) -> Result<(), ManagedError> {
Ok(())
}
fn send_line(&self, _n: &str, text: &str) -> Result<(), ManagedError> {
self.0.lock().expect("mutex").push((None, text.to_owned()));
Ok(())
}
fn send_line_to_pane(
&self,
_n: &str,
pane: &str,
text: &str,
) -> Result<(), ManagedError> {
self.0
.lock()
.expect("mutex")
.push((Some(pane.to_owned()), text.to_owned()));
Ok(())
}
fn capture(&self, _n: &str, _l: usize) -> Result<String, ManagedError> {
Ok(String::new())
}
fn list_sessions(&self) -> Result<Vec<String>, ManagedError> {
Ok(Vec::new())
}
}
let driver = PaneRecorder(Mutex::new(Vec::new()));
driver
.send_command_line("sess", Some("%7"), "echo hi")
.expect("send");
driver
.send_command_line("sess", None, "echo ho")
.expect("send");
let log = driver.0.lock().expect("mutex").clone();
assert_eq!(
log,
vec![
(Some("%7".to_owned()), "echo hi".to_owned()),
(None, "echo ho".to_owned())
]
);
}
#[test]
fn send_keys_literal_to_pane_default_fails_closed() {
let err = MinimalDriver
.send_keys_literal_to_pane("sess", "%1", "text")
.expect_err(
"a driver that does not override this must fail loudly, never \
silently fall back to the session-scoped send",
);
assert!(matches!(err, ManagedError::TmuxUnavailable(_)));
}
#[test]
fn send_interrupt_to_pane_default_fails_closed() {
let err = MinimalDriver
.send_interrupt_to_pane("sess", "%1")
.expect_err(
"a driver that does not override this must fail loudly, never \
silently fall back to the session-scoped interrupt",
);
assert!(matches!(err, ManagedError::TmuxUnavailable(_)));
}
#[test]
fn capture_pane_default_fails_closed() {
let err = MinimalDriver.capture_pane("sess", "%1", 50).expect_err(
"a driver that does not override this must fail loudly, never \
silently fall back to the session-scoped capture",
);
assert!(matches!(err, ManagedError::TmuxUnavailable(_)));
}
}