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
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
//! tmux process driver.
//!
//! Why: `trusty-mpm-core::tmux` builds tmux argv vectors but never spawns a
//! process — that keeps it pure and testable. The daemon needs the other half:
//! actually running `tmux` and interpreting its exit status. This module is
//! distilled from `ai-commander`'s `commander-tmux` orchestrator and
//! `trusty-agents`'s `tm` manager — find the binary once, run argv, classify the
//! "no server running" empty-list case.
//! What: [`TmuxDriver`] wraps the resolved `tmux` path; it can create/kill/list
//! sessions, send keystrokes, and capture pane output. [`SessionInfo`] is one
//! parsed `list-sessions` row.
//! Test: `cargo test -p trusty-mpm-daemon` covers binary discovery degradation
//! and `list-sessions` row parsing without requiring tmux to be installed.
// The session-start command path (which spawns Claude Code into a tmux
// session) lands in a follow-up issue; until then this driver is exercised
// only by its own tests, so its public surface is intentionally unused.
#![allow(dead_code)]
use std::process::Command;
use tracing::warn;
use crate::core::external_session::ExternalSession;
use crate::core::oauth_token::OAUTH_TOKEN_ENV_VAR;
use crate::core::tmux::{TmuxCommand, TmuxTarget, tmux_argv};
use crate::core::{Error, Result};
use crate::session_manager::SupervisorFloor;
/// Find the end (one PAST the true closing `'`, byte offset into `s`) of a
/// POSIX shell single-quoted value, given `s` is the text immediately AFTER
/// the opening quote.
///
/// Why: [`shell_single_quote`](crate::runtime::claude_code) escapes an
/// embedded literal `'` as the 4-byte close-escape-reopen sequence `'\''`
/// (close the current quote, backslash-escape a literal `'`, reopen a new
/// quote) — POSIX shells have no in-quote escape, so this is the standard
/// way to embed a quote inside a single-quoted string. A naive scan for the
/// FIRST `'` after the opener mistakes that sequence's first byte for the
/// closer, truncating the redaction and leaking every byte of the value AFTER
/// the embedded quote in cleartext (a real reviewer-caught edge case: a token
/// containing `'` would leak its tail). This walks the value treating `'\''`
/// as one escaped-quote unit to skip over, so only a BARE `'` — one not
/// followed by `\''` — is treated as the true closer.
/// What: scans byte-by-byte (safe: the only bytes it compares against are `'`
/// and `\`, both single-byte ASCII, so it can never land mid-codepoint of a
/// multi-byte UTF-8 sequence in an untouched run of bytes). At each `'`, if
/// the next three bytes spell `\''` the whole 4-byte run is an escaped
/// literal quote — skipped, continue scanning; otherwise this `'` is the true
/// closer and its index + 1 is returned. Falls back to `s.len()` if no closer
/// is found (malformed input — treat the rest of the string as the value
/// rather than panic or leak).
/// Test: `find_quoted_value_end_stops_at_bare_closer`,
/// `find_quoted_value_end_skips_escaped_embedded_quote`,
/// `redact_oauth_token_masks_value_with_embedded_single_quote`.
fn find_quoted_value_end(s: &str) -> usize {
let bytes = s.as_bytes();
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'\'' {
if bytes[i..].starts_with(b"'\\''") {
i += 4; // escaped embedded quote unit — not the closer
continue;
}
return i + 1; // bare closer — include it in the consumed span
}
i += 1;
}
bytes.len()
}
/// Mask any `CLAUDE_CODE_OAUTH_TOKEN=<value>` secret in `s` before it reaches a
/// log or a persisted record.
///
/// Why: managed-session pane commands interpolate a cleartext
/// `CLAUDE_CODE_OAUTH_TOKEN='<token>'` (#2246). When [`TmuxDriver::run`] maps a
/// failed `send-keys` to an error it formats the full argv — which would
/// otherwise carry that OAuth secret into every downstream `warn!` log in
/// `daemon::managed_routes::lifecycle` AND into the persisted session `task`
/// field via `session_manager::manager::mark_errored`, where `tm session ls`
/// surfaces it. Redacting at this single source closes every one of those
/// paths at once, so no caller has to remember to scrub.
/// What: replaces the value of each `CLAUDE_CODE_OAUTH_TOKEN=` assignment with
/// `<redacted>`, handling both the single-quoted form
/// (`CLAUDE_CODE_OAUTH_TOKEN='…'` → `CLAUDE_CODE_OAUTH_TOKEN='<redacted>'`,
/// via [`find_quoted_value_end`] so a value containing an escaped embedded
/// quote is masked in full, not just up to its first byte) and a bare
/// unquoted form (value ends at the next ASCII whitespace). All other bytes
/// are copied through unchanged, so a string with no token is returned
/// verbatim.
/// Test: `redact_oauth_token_masks_quoted_value`,
/// `redact_oauth_token_masks_unquoted_value`,
/// `redact_oauth_token_masks_value_with_embedded_single_quote`,
/// `redact_oauth_token_leaves_unrelated_text_untouched`,
/// `run_style_error_message_does_not_leak_oauth_token`.
fn redact_oauth_token(s: &str) -> String {
let needle = format!("{OAUTH_TOKEN_ENV_VAR}=");
let mut out = String::with_capacity(s.len());
let mut rest = s;
while let Some(pos) = rest.find(&needle) {
out.push_str(&rest[..pos + needle.len()]);
let after = &rest[pos + needle.len()..];
if let Some(stripped) = after.strip_prefix('\'') {
// Single-quoted value: mask up to and including the TRUE closing
// quote, correctly skipping any escaped embedded quotes.
let end = find_quoted_value_end(stripped);
out.push_str("'<redacted>'");
rest = &stripped[end..];
} else {
// Bare value: mask up to the next whitespace (or end of string).
let end = after.find(char::is_whitespace).unwrap_or(after.len());
out.push_str("<redacted>");
rest = &after[end..];
}
}
out.push_str(rest);
out
}
/// A parsed `tmux list-sessions` row.
///
/// Why: the dashboard wants structured session data, not raw tmux text.
/// What: the fields from `SESSION_LIST_FORMAT` — name, creation epoch, attached.
/// Test: `parses_session_row`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionInfo {
/// tmux session name.
pub name: String,
/// Unix epoch seconds the session was created.
pub created: i64,
/// Whether at least one client is currently attached.
pub attached: bool,
}
impl SessionInfo {
/// Parse one `name:created:attached` row from `list-sessions`.
///
/// Why: a single parser keeps the format in sync with
/// `core::tmux::SESSION_LIST_FORMAT`. The third field is
/// `#{session_attached}`, which tmux documents as the NUMBER of clients the
/// session is attached to — not a boolean. Comparing it to the literal
/// `"1"` therefore read every session with two or more clients as detached,
/// and `tm ls` labelled it `(active)` instead of `(attached)`.
/// What: splits on `:`; the attachment field is parsed as a count and any
/// value `> 0` means attached. A missing or unparseable field still
/// degrades to `false` rather than failing the row.
/// Test: `parses_session_row`, `parses_multi_client_session_row_as_attached`,
/// `attachment_flips_to_detached_when_client_count_drops_to_zero`.
pub fn parse(line: &str) -> Result<Self> {
let mut parts = line.splitn(3, ':');
let name = parts
.next()
.filter(|s| !s.is_empty())
.ok_or_else(|| Error::Protocol(format!("empty tmux session row: {line:?}")))?
.to_string();
let created = parts
.next()
.and_then(|s| s.parse::<i64>().ok())
.ok_or_else(|| Error::Protocol(format!("bad tmux created field: {line:?}")))?;
// PR #4983: `#{session_attached}` is a client COUNT, not a flag — a
// session with a second terminal on it reports `2`, and the old
// `== "1"` test read that as detached.
let attached = parts
.next()
.and_then(|s| s.trim().parse::<u32>().ok())
.is_some_and(|clients| clients > 0);
Ok(Self {
name,
created,
attached,
})
}
}
/// True when a non-zero `tmux` listing means "the server is up but empty".
///
/// Why: `list-sessions` and `list-panes -a` both exit non-zero on a quiet host,
/// and three call sites classified that stderr independently. Naming the rule
/// once keeps them from drifting, and the name matters because the rule is
/// NARROW on purpose. A host where no tmux server has ever run does not print
/// `no server running`; it prints
/// `error connecting to <socket> (No such file or directory)`, which this
/// refuses, so the caller gets an `Err` and
/// [`DaemonState::reap_dead_sessions`](crate::daemon::state::DaemonState::reap_dead_sessions)
/// reaps nothing rather than mistaking an unreachable server for an empty one
/// and deleting every registered session.
///
/// The consequence for callers is the one that made `main` red in #6411:
/// `TmuxDriver::discover().is_ok()` says the BINARY resolves, which is a
/// strictly weaker claim than "a listing will succeed". Never use the former to
/// predict the latter.
/// What: matches the two tmux spellings for an empty server, and nothing else.
/// Test: `empty_server_stderr_is_an_empty_list`,
/// `unreachable_socket_stderr_is_not_an_empty_list`.
fn stderr_means_empty_server(stderr: &str) -> bool {
stderr.contains("no server running") || stderr.contains("no sessions")
}
/// True when a failed `new-session` (issued WITHOUT `-A`) failed because the
/// name is already live (#3707).
///
/// Why: [`TmuxDriver::create_session_exclusive`] must tell a lost create race
/// apart from a real tmux failure. Reading every non-zero exit as "the name is
/// taken" would send the caller into a rename-and-retry loop over a server that
/// is actually broken; reading none of them that way puts the aliasing bug back.
/// What: matches tmux's `duplicate session: <name>` spelling and nothing else.
/// Test: `duplicate_session_stderr_is_recognised`,
/// `unrelated_stderr_is_not_a_name_collision`.
fn stderr_means_duplicate_session(stderr: &str) -> bool {
stderr.contains("duplicate session")
}
/// Whether [`TmuxDriver::create_session_exclusive`] created the pane or lost
/// the name to somebody else (#3707).
///
/// Why: "the name was taken" is an ordinary, retryable outcome of a concurrent
/// create, not an error — modelling it as one would force every caller to
/// pattern-match on an error string to find out which failure it had.
/// What: two variants; `NameTaken` carries no payload because the caller
/// already knows the name it asked for.
/// Test: `duplicate_session_stderr_is_recognised`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExclusiveCreate {
/// tmux created the session; the caller now owns it.
Created,
/// A session of that name already existed; nothing was created.
NameTaken,
}
/// Drives the `tmux` binary on behalf of the daemon's session manager.
///
/// Why: hosting Claude Code inside tmux is the primary control model; the
/// daemon needs a thin, fallible wrapper rather than scattering `Command`
/// calls. Holding the resolved path means PATH is consulted only once.
/// What: stores the `tmux` executable path; methods execute typed
/// [`TmuxCommand`]s built by `core::tmux`.
/// Test: `driver_reports_availability`.
#[derive(Debug, Clone)]
pub struct TmuxDriver {
/// Absolute path to the `tmux` binary.
tmux_path: String,
/// #8942: the protected-name check [`Self::kill_session`] asks first.
floor: SupervisorFloor,
}
impl TmuxDriver {
/// Resolve the `tmux` binary, or fail if it cannot be found.
///
/// Why: the daemon should refuse the tmux control model up front rather
/// than fail on the first session start. Under launchd the daemon inherits
/// a minimal `PATH` (`/usr/bin:/bin:/usr/sbin:/sbin`) that omits Homebrew,
/// so a bare `PATH` lookup of `tmux` (which lives at `/opt/homebrew/bin`)
/// returns nothing and every managed-session spawn 500s after a restart
/// (#1298). Resolving via the well-known dirs makes discovery survive the
/// minimal inherited `PATH`.
/// What: delegates to [`crate::core::tmux::resolve_tmux_binary`] — the
/// `with_tmux_binary` test override when one is in scope, else
/// [`trusty_common::bin_resolve::resolve_binary`], which consults the live
/// `PATH` first and then falls back to the well-known daemon dirs
/// (Homebrew + user bins). Errors with a clear message if no `tmux` is
/// found anywhere.
///
/// Scratch-environment gate (#5784): before resolving anything, this asks
/// [`crate::core::host_state_gate::host_state_access`] whether the process
/// is running in the operator's real environment. It is not when `$HOME`
/// has been reassigned away from this uid's password-database home, and a
/// tmux server is keyed to the uid, not to `$HOME` — so a scratch daemon
/// that resolved a driver here would list, adopt, and later kill the
/// operator's live panes. This is the crate's ONLY constructor for
/// `TmuxDriver` (the `tmux_path` field is private), so every path that
/// HOLDS a driver is covered: startup auto-discovery, the reap loop,
/// orphan-GC, the idle reaper, the session services, and the session
/// manager's `RealTmuxDriver`.
///
/// It does NOT cover the paths that never construct one — `tm launch` and
/// `tm connect` create and kill sessions through
/// [`crate::core::tmux::create_managed_session`] and
/// [`crate::core::tmux::run_tmux`] directly. Those are gated at the spawn
/// itself by `core::tmux`'s `host_state_guard`, which is why the check
/// lives in two places rather than one; this one exists so a gated daemon
/// fails fast with a diagnosable message instead of N refused subprocesses.
///
/// The gate fails CLOSED: an environment it cannot classify is refused, and
/// `TRUSTY_MPM_ALLOW_HOST_STATE=1` is the explicit way back in.
/// Test: `driver_reports_availability` (skips assertion when tmux
/// missing); `scratch_home_daemon_does_not_spawn_tmux`
/// proves no tmux process is spawned once this refuses;
/// `tmux_backend_constructs_without_spawning` resolves through a
/// `with_tmux_binary` scope.
pub fn discover() -> Result<Self> {
let access = crate::core::host_state_gate::host_state_access();
if let Some(reason) = access.skip_reason() {
tracing::warn!("#5784: tmux access refused — {reason}");
return Err(Error::Protocol(format!("tmux access refused: {reason}")));
}
// #6542: `resolve_tmux_binary`, not `bin_resolve` directly, so a test
// inside a `with_tmux_binary` scope reaches its private server here too.
let path = crate::core::tmux::resolve_tmux_binary().ok_or_else(|| {
Error::Protocol(
"tmux not found on PATH or in well-known dirs (e.g. /opt/homebrew/bin); \
use the PTY or SDK control model"
.into(),
)
})?;
let path = path
.to_str()
.ok_or_else(|| Error::Protocol("resolved tmux path is not valid UTF-8".into()))?
.to_string();
let floor = SupervisorFloor::host();
Ok(Self {
tmux_path: path,
floor,
})
}
/// A driver bound to `tmux_path` with no discovery — tests only, so a test
/// can point it at a private `-L` server shim (#8443).
#[cfg(test)]
pub(crate) fn with_tmux_path_for_test(tmux_path: impl Into<String>) -> Self {
Self {
tmux_path: tmux_path.into(),
floor: SupervisorFloor::host(),
}
}
/// This driver with its kill floor replaced — tests only (#8942).
#[cfg(test)]
pub(crate) fn with_floor(self, floor: SupervisorFloor) -> Self {
Self { floor, ..self }
}
/// The protected-name check this driver's kills ask (#8942).
pub fn supervisor_floor(&self) -> &SupervisorFloor {
&self.floor
}
/// True if a `tmux` binary is available on this host.
pub fn is_available() -> bool {
Self::discover().is_ok()
}
/// Confirm the tmux SERVER exists, starting it if necessary (#3823).
///
/// Why: on a machine where tmux has never run, the socket directory
/// itself does not exist yet — `list-sessions` fails with a raw "No such
/// file or directory"/"error connecting to" message that
/// [`Self::list_sessions`]'s "no server running"/"no sessions" empty-list
/// classification does not recognize, so it propagates as an `Err`. The
/// session-creation flow's FIRST tmux call is exactly this
/// `list-sessions` (`SessionManager::resolve_session_name` →
/// `names_for_serial_allocation` and `SessionManager::dedupe_session_name`,
/// both called before the #3386/#3722 `create_managed_session` choke
/// point is ever reached), so that choke point's own `ensure_server_up`
/// call comes too late to help — the caller already 500'd. This method
/// lets `SessionManager::create_with_id`/`create_with_reserved_name`/
/// `resume` (`session_manager/create.rs`, `session_manager/manager.rs`)
/// guarantee the server is up BEFORE issuing that first `list-sessions`.
/// What: delegates to [`crate::core::tmux::ensure_server_up`] (the same
/// retried-with-backoff `tmux start-server` primitive #3722 added),
/// mapping its `Err(String)` to `Error::Protocol`.
/// Test: `ensure_server_up_issues_start_server_on_a_fresh_socket`,
/// `ensure_server_up_fails_loudly_when_the_server_never_comes_up`
/// (`tmux_tests.rs`, both drive a scripted fake `tmux` binary).
pub fn ensure_server_up(&self) -> Result<()> {
crate::core::tmux::ensure_server_up(&self.tmux_path).map_err(Error::Protocol)
}
/// Run a typed tmux command, returning captured stdout on success.
///
/// Why: every other method routes through here so exit-status handling
/// lives in one place. The actual process spawn is delegated to
/// [`crate::core::tmux::run_tmux_with_bin`] (#2398 architecture
/// consolidation) — `TmuxDriver` WRAPS that single crate-wide entry point
/// rather than spawning independently, using its own already-resolved
/// `self.tmux_path` (cached at [`Self::discover`] time for the
/// fail-fast-if-absent contract) instead of re-resolving on every call.
/// What: renders argv via `core::tmux::tmux_argv` (for the error message
/// only — the actual spawn happens inside `run_tmux_with_bin`), runs
/// `tmux`, and maps a non-zero exit to `Error::Protocol` carrying stderr.
/// Test: exercised indirectly by the `#[ignore]` integration tests.
fn run(&self, cmd: &TmuxCommand) -> Result<String> {
let output = crate::core::tmux::run_tmux_with_bin(&self.tmux_path, cmd)?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
} else {
let argv = tmux_argv(cmd);
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
// #2246: the argv can embed a cleartext CLAUDE_CODE_OAUTH_TOKEN
// (managed-spawn pane command). Redact at this single source so the
// secret can never reach the ~5 warn! sites in
// daemon::managed_routes::lifecycle nor the persisted session `task`
// field (mark_errored → `tm session ls`). stderr is redacted too in
// case tmux echoes the offending keys back.
Err(Error::Protocol(redact_oauth_token(&format!(
"tmux {argv:?} failed: {stderr}"
))))
}
}
/// Create a detached tmux session named `name`, optionally in `workdir`.
///
/// Idempotent: if a session with the same name already exists, the
/// underlying `tmux new-session -A` attaches to it instead of failing
/// with a "duplicate session" error.
///
/// Why (#2398): the scrollback/mouse server options MUST be applied
/// before this method's `new-session` call — `history-limit` is captured
/// into a pane's ring buffer at creation time. Delegates to
/// [`crate::core::tmux::create_managed_session`], the crate-wide session-
/// creation choke point EVERY session-creating call site (daemon, CLI,
/// TUI client, control-plane backend) now routes through, so the
/// ordering can never be bypassed by a future call site again.
///
/// #3386 review: [`crate::core::tmux::warn_if_options_unverified`] logs
/// an `error!` naming the session when the ergonomics could not be
/// verified — the "at minimum" operator-visible surface the review
/// requires (a `warn!`-only log is the exact silent-degrade #3386 was
/// filed against).
pub fn create_session(&self, name: &str, workdir: Option<&str>) -> Result<()> {
let outcome =
crate::core::tmux::create_managed_session(Some(&self.tmux_path), name, workdir)
.inspect(|o| crate::core::tmux::warn_if_options_unverified(o, name))?;
if outcome.output.status.success() {
Ok(())
} else {
let stderr = String::from_utf8_lossy(&outcome.output.stderr).into_owned();
Err(Error::Protocol(redact_oauth_token(&format!(
"tmux new-session for {name} failed: {stderr}"
))))
}
}
/// Create a detached tmux session named `name` that FAILS when the name is
/// already live (#3707).
///
/// Why: [`Self::create_session`] renders `-A`, which attaches to an
/// existing session instead of failing. That makes a lost create race
/// invisible: both creators return success and two session records end up
/// driving one pane. The managed create path needs the opposite — a refusal
/// it can retry under a fresh name — and tmux gives exactly that when `-A`
/// is absent, decided atomically by the server rather than by a probe the
/// caller ran a moment earlier.
/// What: [`crate::core::tmux::create_managed_session_exclusive`], which
/// applies the same #2398 option ordering and then issues `new-session`
/// without `-A`. A non-zero exit whose stderr says the name is a duplicate
/// becomes [`ExclusiveCreate::NameTaken`]; any other non-zero exit is an
/// error, so a real tmux failure is never mistaken for a lost race.
/// Test: `duplicate_session_stderr_is_recognised`,
/// `unrelated_stderr_is_not_a_name_collision`.
pub fn create_session_exclusive(
&self,
name: &str,
workdir: Option<&str>,
) -> Result<ExclusiveCreate> {
let outcome = crate::core::tmux::create_managed_session_exclusive(
Some(&self.tmux_path),
name,
workdir,
)
.inspect(|o| crate::core::tmux::warn_if_options_unverified(o, name))?;
if outcome.output.status.success() {
return Ok(ExclusiveCreate::Created);
}
let stderr = String::from_utf8_lossy(&outcome.output.stderr).into_owned();
if stderr_means_duplicate_session(&stderr) {
return Ok(ExclusiveCreate::NameTaken);
}
Err(Error::Protocol(redact_oauth_token(&format!(
"tmux new-session for {name} failed: {stderr}"
))))
}
/// Apply the configured scrollback + mouse ergonomics to the tmux
/// SERVER, before any pane is created (#2398).
///
/// Why: tmux's own default `history-limit` is 2000 lines — a long-running
/// PM session scrolls off the top almost immediately. `history-limit` is
/// captured into a pane's ring buffer AT CREATION TIME; a per-session
/// `set-option` issued after a pane already exists does not retroactively
/// grow it (a tmux limitation — existing panes are unaffected by this
/// call; only NEW panes/sessions created after it benefit). Because
/// trusty-mpm runs every managed session on the ONE default tmux server
/// (no dedicated `-S` socket — confirmed: no call site in this crate
/// passes `-S`/`-L`), setting these as GLOBAL (`-g`) options once, right
/// before [`Self::create_session`]'s `new-session`, benefits every
/// session subsequently created without per-session bookkeeping. `mouse
/// on` additionally maps the wheel to pane-scroll/copy-mode entry, the
/// actual "scroll" gesture operators expect.
/// What: loads [`crate::core::trusty_tools_config::TrustyToolsConfig`],
/// resolves the `tmux:` section via
/// [`crate::core::trusty_tools_config::resolve_tmux_options`] (defaults:
/// 100,000-line history-limit, mouse on, alternate-screen off since
/// #5364), and runs
/// each [`crate::core::tmux::scrollback_option_commands`] entry via
/// [`Self::run`] — including the `-wg`-scoped `alternate-screen` entry
/// (#5151). Best-effort: `set-option` is idempotent (safe to
/// call before every session creation) and virtually never fails on a
/// tmux new enough to run trusty-mpm at all, but a failure here must
/// never block session creation/restart — each failure is logged and the
/// next option (or the caller's subsequent tmux call) still runs.
/// Test: argv construction is covered by `core::tmux`'s
/// `scrollback_option_commands_*` tests and config resolution by
/// `core::trusty_tools_config`'s `tmux_options_*` tests; this method's
/// live-server call site is exercised transitively by every
/// `create_session` caller with a real `tmux` binary (`#[ignore]` tests).
pub fn apply_scrollback_options(&self) {
let config = crate::core::trusty_tools_config::TrustyToolsConfig::load();
let opts = crate::core::trusty_tools_config::resolve_tmux_options(&config);
for cmd in crate::core::tmux::scrollback_option_commands(
opts.history_limit,
opts.mouse,
opts.alternate_screen,
) {
if let Err(e) = self.run(&cmd) {
warn!("tmux scrollback/mouse option {cmd:?} failed (non-fatal): {e}");
}
}
}
/// Kill the tmux session named `name`, unless the #8942 floor refuses it.
///
/// Why: every daemon kill-by-name funnels through here; a stale record
/// carrying the Architect's name must not reach its pane (#8935).
/// What: [`SupervisorFloor::refuse`] first — a protected or undeterminable
/// name is `Err` and no tmux process runs; otherwise `kill-session -t =name`.
/// Test: `kill_by_name_fails_closed_when_architect_sidecars_cannot_be_read`,
/// `a_record_with_an_unknown_kind_is_never_torn_down`.
#[track_caller]
pub fn kill_session(&self, name: &str) -> Result<()> {
let caller = format!(
"TmuxDriver::kill_session from {}",
std::panic::Location::caller()
);
if let Some(why) = self.floor.refuse(name, &caller) {
return Err(Error::Protocol(why));
}
self.run(&TmuxCommand::KillSession {
name: name.to_string(),
})?;
Ok(())
}
/// List all tmux sessions on this host.
///
/// Why: the multi-session dashboard enumerates every running session.
/// What: runs `list-sessions`; tmux exits non-zero with "no server running"
/// when there are zero sessions — that is mapped to an empty `Vec`.
/// Test: row parsing covered by `parses_session_row`.
pub fn list_sessions(&self) -> Result<Vec<SessionInfo>> {
let argv = tmux_argv(&TmuxCommand::ListSessions);
let output = Command::new(&self.tmux_path).args(&argv).output()?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if stderr_means_empty_server(&stderr) {
return Ok(Vec::new());
}
return Err(Error::Protocol(format!("tmux list-sessions: {stderr}")));
}
let stdout = String::from_utf8_lossy(&output.stdout);
let mut sessions = Vec::new();
for line in stdout.lines().filter(|l| !l.is_empty()) {
sessions.push(SessionInfo::parse(line)?);
}
Ok(sessions)
}
/// Send literal text to a session/pane, then press Enter to execute it.
///
/// Why: launching Claude Code or feeding it a prompt means typing a line
/// and submitting it; tmux needs the text sent with `-l` (literal) and the
/// `Enter` keypress sent separately.
/// What: two `send-keys` invocations — literal text, then the `Enter` key.
/// Test: argv shapes covered in `core::tmux` tests.
pub fn send_line(&self, target: &TmuxTarget, text: &str) -> Result<()> {
self.run(&TmuxCommand::SendKeys {
target: target.clone(),
keys: text.to_string(),
literal: true,
})?;
self.run(&TmuxCommand::SendKeys {
target: target.clone(),
keys: "Enter".to_string(),
literal: false,
})?;
Ok(())
}
/// [`send_line`](Self::send_line) for a SHELL COMMAND, refusing a line the
/// pane's tty would truncate (#8233).
///
/// Why: every launch path types a composed `claude` invocation at a pane's
/// shell prompt, where the tty is in canonical mode and drops everything past
/// `MAX_CANON` (1024 bytes on macOS) with no error. A 1054-byte launch line
/// killed session `dd0e2fb8-…` that way. Refusing is the only place the
/// failure can be made visible, and it is scoped to COMMAND lines so task
/// injection into Claude Code's raw-mode TUI — legitimately multi-kilobyte —
/// is untouched.
/// What: [`crate::core::tmux::refuse_oversized_pane_command`] first; on
/// refusal NOTHING is typed and the message is returned as a
/// `Error::Protocol`. Otherwise delegates to [`send_line`](Self::send_line).
/// Test: `driver_send_command_line_refuses_an_oversized_line`.
pub fn send_command_line(&self, target: &TmuxTarget, text: &str) -> Result<()> {
if let Some(msg) = crate::core::tmux::refuse_oversized_pane_command(text) {
return Err(Error::Protocol(msg));
}
self.send_line(target, text)
}
/// Send literal text to a session/pane WITHOUT a trailing Enter.
///
/// Why: the harness-agnostic no-submit inject intent (#1461) types into the
/// pane but leaves the line uncommitted (vs. [`send_line`](Self::send_line),
/// which appends Enter). Keeping it a separate one-shot avoids the second
/// `Enter` send-keys call.
/// What: a single `send-keys -l` invocation (literal, no key-name follow-up).
/// Test: argv shape covered by `trusty_common::tmux`'s `send_keys_literal_argv`.
pub fn send_keys_literal(&self, target: &TmuxTarget, text: &str) -> Result<()> {
self.run(&TmuxCommand::SendKeys {
target: target.clone(),
keys: text.to_string(),
literal: true,
})?;
Ok(())
}
/// Send a Ctrl-C interrupt to a session/pane.
///
/// Why: restarting Claude Code in place means interrupting the running
/// process before relaunching it; `C-c` is the clean stop.
/// What: one `send-keys` invocation with the `C-c` key name (non-literal).
/// Test: argv shape covered by `trusty_common::tmux`'s `send_keys_keyname_argv`.
pub fn send_interrupt(&self, target: &TmuxTarget) -> Result<()> {
self.run(&TmuxCommand::SendKeys {
target: target.clone(),
keys: "C-c".to_string(),
literal: false,
})?;
Ok(())
}
/// Capture the last `lines` of a pane's output (whole scrollback if `None`).
pub fn capture(&self, target: &TmuxTarget, lines: Option<u32>) -> Result<String> {
self.run(&TmuxCommand::CapturePane {
target: target.clone(),
lines,
})
}
/// Durably publish `key=value` into the tmux SESSION environment (#2157 item 1).
///
/// Why: `runtime::claude_code::session_id_export_prefix` exports
/// `TM_MANAGED_SESSION_ID` into the ONE pane shell that ran the spawn/resume
/// command line — a sibling pane/window in the same session, or a pane
/// spawned before this fix landed, never sees it, which is why the
/// in-place-relaunch gate (`bin/tm/commands/guided_inplace.rs`) could fail
/// silently and bare `tm` fell through to spawning a nested session
/// (issue #2157). `set-environment` writes into the session's own
/// environment table, queryable via `tmux show-environment` from ANY
/// pane/shell in that session regardless of vintage.
/// What: runs `tmux set-environment -t <session> <key> <value>`; maps a
/// non-zero exit to `Error::Protocol`. Callers treat this as best-effort —
/// the shell-export prefix remains the primary mechanism.
/// Test: argv shape covered by `core::tmux::set_environment_argv`.
pub fn set_environment(&self, session: &str, key: &str, value: &str) -> Result<()> {
self.run(&TmuxCommand::SetEnvironment {
session: session.to_string(),
key: key.to_string(),
value: value.to_string(),
})?;
Ok(())
}
/// List every pane on the host as `session_name pane_current_command`.
///
/// Why: session auto-discovery scans all panes to find ones running Claude
/// Code; `list-panes -a` reports every pane across every session in one
/// call, so the daemon need not iterate sessions itself.
/// What: runs `tmux list-panes -a -F "#{session_name} #{pane_current_command}"`
/// directly (this cross-session form has no `core::tmux::TmuxCommand`
/// variant) and returns its raw stdout. An empty tmux server (`no server
/// running`) yields an empty string rather than an error.
/// Test: parsing of the output is covered by `discovery::parse_pane_line`;
/// this listing path is exercised by the `discovery` tmux-absent test.
pub fn list_claude_panes(&self) -> Result<String> {
let output = Command::new(&self.tmux_path)
.args([
"list-panes",
"-a",
"-F",
"#{session_name} #{pane_current_command}",
])
.output()?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if stderr_means_empty_server(&stderr) {
return Ok(String::new());
}
return Err(Error::Protocol(format!("tmux list-panes -a: {stderr}")));
}
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}
/// Enumerate every pane as a structured [`orphan_gc::PaneInfo`](crate::daemon::orphan_gc::PaneInfo) row.
///
/// Why: the orphan-GC must reconcile live tmux against the registries, and
/// to decide whether a session is idle it needs each pane's
/// `pane_current_command` (and, for the belt-and-braces liveness check, the
/// pane's shell PID). The reactivate-reconcile path (#2789) additionally
/// needs each pane's stable `pane_id` to identify the caller's OWN pane and
/// treat it as idle. `list-panes -a` reports all of that across every
/// session in a single tmux call.
/// What: runs
/// `tmux list-panes -a -F "#{session_name}\t#{pane_current_command}\t#{pane_pid}\t#{pane_id}"`
/// and parses each row into a [`orphan_gc::PaneInfo`](crate::daemon::orphan_gc::PaneInfo). A tab delimiter avoids
/// colliding with the colons in session names. An empty tmux server (`no
/// server running`) yields an empty `Vec` rather than an error, so a quiet
/// host reaps nothing rather than failing the sweep.
///
/// The spawn goes through [`crate::core::tmux::force_utf8_client_env`]
/// because tmux deletes this format's delimiters from its own output when
/// the client does not declare a UTF-8 locale — see that function and
/// #6529. A row that still arrives malformed is DROPPED, never coerced, and
/// the drop is reported once per listing rather than once per row.
/// Test: row parsing covered by `parses_managed_pane_row`,
/// `sanitized_pane_row_is_dropped_not_coerced`; the live listing path is
/// exercised by the `#[ignore]` integration test.
pub fn list_managed_panes(&self) -> Result<Vec<crate::daemon::orphan_gc::PaneInfo>> {
let mut cmd = Command::new(&self.tmux_path);
cmd.args([
"list-panes",
"-a",
"-F",
// #6118: `pane_current_path` is the evidence the cwd-gone reap path
// needs. Asking for it in the SAME listing keeps the sweep at one
// tmux call rather than one per untracked pane.
"#{session_name}\t#{pane_current_command}\t#{pane_pid}\t#{pane_id}\t#{pane_current_path}",
]);
// #6529: without a UTF-8 client locale tmux rewrites every tab to `_`.
crate::core::tmux::force_utf8_client_env(&mut cmd);
let output = cmd.output()?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if stderr_means_empty_server(&stderr) {
return Ok(Vec::new());
}
return Err(Error::Protocol(format!("tmux list-panes -a: {stderr}")));
}
let stdout = String::from_utf8_lossy(&output.stdout);
Ok(Self::parse_managed_pane_rows(&stdout))
}
/// Parse a whole `list-panes -a -F` listing, reporting dropped rows once.
///
/// Why: a malformed listing is a whole-listing condition, not a per-row one
/// — every row of a sanitized reply is malformed the same way, so a warning
/// per row is the 478-lines-per-sweep log flood #1813 already paid for. One
/// line naming the count and a single sample says the same thing.
/// What: keeps the rows [`Self::parse_managed_pane_row`] accepts and counts
/// the rest, emitting one `warn!` that names the likely cause when any were
/// dropped. Never coerces a malformed row into a pane.
/// Test: `sanitized_pane_row_is_dropped_not_coerced`,
/// `parses_a_real_tab_delimited_listing`.
pub(super) fn parse_managed_pane_rows(stdout: &str) -> Vec<crate::daemon::orphan_gc::PaneInfo> {
let mut panes = Vec::new();
let mut dropped = 0usize;
let mut sample = String::new();
for line in stdout.lines().filter(|l| !l.is_empty()) {
match Self::parse_managed_pane_row(line) {
Some(pane) => panes.push(pane),
None => {
dropped += 1;
if sample.is_empty() {
sample = line.chars().take(80).collect();
}
}
}
}
if dropped > 0 {
tracing::warn!(
dropped,
sample = %sample,
"tmux list-panes returned rows without the requested tab columns — \
dropping them rather than guessing which field is which; the usual \
cause is a tmux client without a UTF-8 locale, which rewrites the \
delimiters to `_` (#6529)"
);
}
panes
}
/// Parse one `session_name\tpane_current_command\tpane_pid\tpane_id` row.
///
/// Why: keeping the parse separate from the subprocess call makes it
/// unit-testable without spawning tmux.
/// What: requires EXACTLY the four tab-separated columns the format string
/// asked for, with a non-empty session name and command and a numeric pid;
/// anything else is `None`. Fails CLOSED on purpose: the failure this
/// replaces silently handed `classify_session` a `session_name` holding an
/// entire joined row, which matched no registry entry and read as a busy
/// session forever (#6529, and the #1813 shape before it). A dropped row
/// makes a pane invisible to the sweep, which can only ever spare a session
/// — never kill one.
///
/// #6118 added a FIFTH column, `pane_current_path`. It is the only optional
/// one: an empty value parses to `None`, which the orphan-GC reads as "no
/// evidence about this pane's cwd" and so can never reap on. A row carrying
/// only the old four columns is REJECTED like any other shape mismatch —
/// accepting it would mean guessing that the absent column is the trailing
/// one.
/// Test: `parses_managed_pane_row`, `sanitized_pane_row_is_dropped_not_coerced`,
/// `parses_pane_row_with_empty_current_path`,
/// `four_column_pane_row_is_dropped`.
fn parse_managed_pane_row(line: &str) -> Option<crate::daemon::orphan_gc::PaneInfo> {
let mut parts = line.split('\t');
let session_name = parts.next()?.trim();
let pane_current_command = parts.next()?.trim();
let pane_pid = parts.next()?.trim();
let pane_id = parts.next()?.trim();
// #6118: the pane's working directory, as tmux recorded it.
let pane_current_path = parts.next()?.trim();
// More columns than the format asked for means this is not the reply we
// requested — refuse to guess which column is which.
if parts.next().is_some() {
return None;
}
if session_name.is_empty() || pane_current_command.is_empty() || pane_id.is_empty() {
return None;
}
Some(crate::daemon::orphan_gc::PaneInfo {
session_name: session_name.to_string(),
pane_current_command: pane_current_command.to_string(),
pane_pid: Some(pane_pid.parse::<u32>().ok()?),
pane_id: Some(pane_id.to_string()),
// Empty is NO evidence, never a path to test against the filesystem.
pane_current_path: (!pane_current_path.is_empty())
.then(|| pane_current_path.to_string()),
})
}
/// List every tmux session, tagged with its [`SessionOrigin`](crate::core::external_session::SessionOrigin).
///
/// Why: the universal-session dashboard manages *all* tmux sessions, not
/// just the ones trusty-mpm created; each row must carry its origin so the
/// UI can offer to adopt external sessions.
/// What: runs `list-sessions` (same as [`list_sessions`](Self::list_sessions))
/// and maps each row into an origin-classified [`ExternalSession`]. An empty
/// tmux server yields an empty `Vec`.
/// Test: classification covered by `core::external_session` tests; the
/// listing path is exercised by the `#[ignore]` integration test.
pub fn list_all_sessions(&self) -> Result<Vec<ExternalSession>> {
Ok(self
.list_sessions()?
.into_iter()
.map(|s| ExternalSession::new(s.name, s.attached, s.created))
.collect())
}
/// Capture the current state of any session for monitoring.
///
/// Why: trusty-mpm oversees external sessions read-only; the daemon must be
/// able to snapshot a session's windows, panes, and recent output without
/// modifying it.
/// What: runs `list-windows` / `list-panes` / `capture-pane` against `name`
/// and bundles the results into a [`SessionSnapshot`]. tmux being absent or
/// the session not existing surfaces as an `Err`.
/// Test: `#[ignore]` integration test `monitor_session_snapshots_state`.
pub fn monitor_session(&self, name: &str, lines: u32) -> Result<SessionSnapshot> {
let windows = self.list_windows(name)?;
let panes = self.list_panes(name)?;
let output = self.capture(&TmuxTarget::session(name), Some(lines))?;
Ok(SessionSnapshot {
name: name.to_string(),
windows,
panes,
output,
captured_at: chrono::Utc::now().timestamp(),
})
}
/// Return the pane's current working directory via `display-message`.
///
/// Why: the snapshot-before-stop path (#1816) needs the pane's cwd to
/// restore it on resume; `tmux display-message -p '#{pane_current_path}'`
/// is the standard mechanism. The call is best-effort — callers must handle
/// `None` gracefully (resume falls back to workspace_path/cwd).
/// What: runs `tmux display-message -t =<name>: -p '#{pane_current_path}'`,
/// trims the output, and returns `Some(path)` on success or `None` if the
/// session does not exist, tmux is unavailable, or the path is empty.
/// Test: exercised indirectly via `snapshot::capture_into` with a live tmux;
/// `RealTmuxDriver::get_pane_cwd` wraps this method.
pub fn pane_current_path(&self, session_name: &str) -> Option<std::path::PathBuf> {
// #8443: an empty name would render a target matching no pane; say so.
crate::core::tmux::check_session_name(session_name).ok()?;
let output = Command::new(&self.tmux_path)
.args([
"display-message",
"-t",
// #8443: pane-typed target — `=name:`, never a bare name.
&crate::core::tmux::exact_window_target(session_name),
"-p",
"#{pane_current_path}",
])
.output()
.ok()?;
if !output.status.success() {
return None;
}
let raw = String::from_utf8_lossy(&output.stdout);
let trimmed = raw.trim();
if trimmed.is_empty() {
None
} else {
Some(std::path::PathBuf::from(trimmed))
}
}
/// Return the pane's stable tmux `pane_id` (e.g. `"%5"`) via `display-message`.
///
/// Why: `#2453` review finding 1 (round 2) — pane-identity confirmation for
/// the bare-`tm` in-pane relaunch's nested-session guard needs a signal
/// that is NEVER inherited across panes, unlike a tmux session-scoped env
/// var (`set-environment` is applied to every new pane/window created in
/// that session afterward, defeating an env-var-only gate — see
/// [`crate::session_manager::record::SessionRecord::pane_id`]'s doc for
/// the full empirical proof). tmux's own `pane_id` (distinct from
/// `pane_pid`, which the OS can reuse across a pane's lifetime) is that
/// signal.
/// What: runs `tmux display-message -t =<name>: -p '#{pane_id}'`, trims the
/// output, and returns `Some(id)` on success or `None` if the session does
/// not exist, tmux is unavailable, or the id is empty. Mirrors
/// [`Self::pane_current_path`]'s exact shape.
/// Test: exercised indirectly via `SessionManager::create`/
/// `mark_runtime_exited_stopped` with a live tmux;
/// `RealTmuxDriver::get_pane_id` wraps this method.
pub fn pane_id(&self, session_name: &str) -> Option<String> {
crate::core::tmux::check_session_name(session_name).ok()?; // #8443
let output = Command::new(&self.tmux_path)
.args([
"display-message",
"-t",
&crate::core::tmux::exact_window_target(session_name),
"-p",
"#{pane_id}",
])
.output()
.ok()?;
if !output.status.success() {
return None;
}
let raw = String::from_utf8_lossy(&output.stdout);
let trimmed = raw.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
}
}
/// Register an external session for oversight without modifying it.
///
/// Why: before trusty-mpm watches an externally-created session it records
/// the session's current shape; adoption is explicitly *non-destructive* —
/// it never kills, renames, or sends keys to the session.
/// What: probes the session exists, captures its window/pane lists, and
/// returns an [`AdoptedSession`] describing it. An unknown session is an
/// `Err`.
/// Test: `#[ignore]` integration test `adopt_session_captures_state`.
pub fn adopt_session(&self, name: &str) -> Result<AdoptedSession> {
let windows = self.list_windows(name)?;
let panes = self.list_panes(name)?;
let origin = crate::core::external_session::SessionOrigin::classify(name);
Ok(AdoptedSession {
name: name.to_string(),
origin,
windows,
panes,
adopted_at: chrono::Utc::now().timestamp(),
})
}
/// List the window `index:name` rows for a session.
///
/// Why: snapshot and adoption both need a session's window list.
/// What: runs `list-windows -F` and returns each row verbatim.
/// Test: argv shape covered by `core::tmux::list_windows_argv`.
fn list_windows(&self, name: &str) -> Result<Vec<String>> {
let raw = self.run(&TmuxCommand::ListWindows {
name: name.to_string(),
})?;
Ok(raw
.lines()
.filter(|l| !l.is_empty())
.map(String::from)
.collect())
}
/// List the pane `id:active` rows for a session, across ALL of its
/// windows.
///
/// Why: snapshot and adoption both need a session's FULL pane list, not
/// just the currently active window's — a plain `list-panes -t <session>`
/// (no `-s`) resolves the session target down to its active window only,
/// which silently drops any pane living in a non-active window (exactly
/// the sibling-window-hijack shape this feature guards against). This bug
/// was caught by the live-tmux test written for the #2467 follow-up, not
/// by the mock-only unit tests.
/// What: runs `list-panes -s -t <name> -F` and returns each row verbatim.
/// Test: argv shape covered by `core::tmux::list_panes_argv`.
/// #9313: crate-visible for `RealTmuxDriver::session_pane_ids`.
pub(crate) fn list_panes(&self, name: &str) -> Result<Vec<String>> {
let raw = self.run(&TmuxCommand::ListPanes {
name: name.to_string(),
})?;
Ok(raw
.lines()
.filter(|l| !l.is_empty())
.map(String::from)
.collect())
}
/// Return whether `pane_id` still exists as a live pane within
/// `session_name`'s tmux session (sibling-window hijack, follow-up to
/// #2456).
///
/// Why: `session_exists` alone cannot distinguish "the recorded pane
/// survived" from "the tmux SESSION merely has some OTHER pane alive"
/// (e.g. a sibling window opened after the recorded pane was closed) —
/// `SessionManager::resume`'s reuse branch needs the stronger,
/// pane-specific answer before it trusts a session-scoped respawn target.
/// What: runs `list-panes -t <session_name> -F` (via [`Self::list_panes`],
/// format `#{pane_id}:#{pane_active}`) and checks whether `pane_id`
/// matches the id portion of any row. Returns `false` on any query
/// failure (session gone, tmux unavailable) — the safe direction for a
/// presence check feeding a refusal path is to treat "cannot confirm" as
/// "not present" (fail toward refusing the unsafe respawn, never toward
/// silently trusting a pane that might not be there).
/// Test: argv shape covered by `core::tmux::list_panes_argv`; behavior
/// (true for a real pane, false for a fabricated pane id in a live,
/// still-alive session) is exercised by the `#[ignore]` live integration
/// test `live_pane_scoped_send_targets_original_pane_not_sibling` in
/// `tests/session_manager_mvp.rs` — that test also covers
/// `RealTmuxDriver::pane_exists`'s call-through and
/// `send_line`/`send_line_to_pane`'s pane-scoped `-t` targeting.
pub fn pane_exists(&self, session_name: &str, pane_id: &str) -> bool {
match self.list_panes(session_name) {
Ok(rows) => rows
.iter()
.any(|row| row.split(':').next() == Some(pane_id)),
Err(_) => false,
}
}
/// Tri-state variant of [`Self::pane_exists`] distinguishing "confirmed
/// present" (`Some(true)`), "confirmed absent" (`Some(false)`), and
/// "could not determine" (`None`) — #3714 review finding 2.
///
/// Why: [`Self::pane_exists`]'s bare `bool` deliberately collapses
/// "confirmed absent" and "query failed" into the same `false` — correct
/// fail-closed behavior for a MUTATION guard (a rename must never trust
/// an unverifiable pane as safe to physically retarget). A DISPLAY-only
/// consumer has the opposite risk: collapsing "could not determine" into
/// "not live" flips a genuinely live record's SHOWN `state` to
/// `"stopped"` on a transient `tmux list-panes` hiccup — reproducing the
/// exact `state`/`persisted_state` disagreement #3714 exists to fix,
/// just from a different trigger (a query error rather than a
/// duplicate-name collision). This lets a display-only caller fall back
/// to a weaker signal (e.g. name-only) on `None` instead of asserting
/// absence it cannot actually prove.
/// What: identical query to `pane_exists`, but `Err` maps to `None`
/// instead of `false`.
/// Test: `daemon::managed_routes::summary`'s
/// `reconcile_live_state_pane_query_error_does_not_flip_live_record_to_stopped`
/// exercises the consumer; this method's own argv shape is covered by
/// the same `core::tmux::list_panes_argv` coverage `pane_exists` uses.
pub fn pane_exists_checked(&self, session_name: &str, pane_id: &str) -> Option<bool> {
match self.list_panes(session_name) {
Ok(rows) => Some(
rows.iter()
.any(|row| row.split(':').next() == Some(pane_id)),
),
Err(_) => None,
}
}
}
/// A non-destructive registration of an external tmux session.
///
/// Why: `POST /tmux/adopt` brings a pre-existing session under trusty-mpm
/// oversight; the response documents what was adopted without implying any
/// modification was made.
/// What: the session name, its classified origin, the window/pane lists at
/// adoption time, and the adoption epoch.
/// Test: `adopt_session_captures_state` (integration, `#[ignore]`).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct AdoptedSession {
/// tmux session name.
pub name: String,
/// Whether the session is a trusty-mpm session or external.
pub origin: crate::core::external_session::SessionOrigin,
/// Window `index:name` rows captured at adoption time.
pub windows: Vec<String>,
/// Pane `id:active` rows captured at adoption time.
pub panes: Vec<String>,
/// Unix epoch seconds the session was adopted.
pub adopted_at: i64,
}
/// A point-in-time snapshot of any tmux session's state.
///
/// Why: `GET /tmux/sessions/{name}/snapshot` lets the dashboard inspect any
/// session (internal or external) without attaching to it.
/// What: the session name, its window/pane lists, the captured pane output,
/// and the capture epoch.
/// Test: `monitor_session_snapshots_state` (integration, `#[ignore]`).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SessionSnapshot {
/// tmux session name.
pub name: String,
/// Window `index:name` rows.
pub windows: Vec<String>,
/// Pane `id:active` rows.
pub panes: Vec<String>,
/// Captured pane output (last `lines` requested).
pub output: String,
/// Unix epoch seconds the snapshot was taken.
pub captured_at: i64,
}
// #9004: pane identity and kill-by-id, split out for the SLOC cap.
#[path = "tmux_pane_identity.rs"]
mod pane_identity;
#[cfg(test)]
#[path = "tmux_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "tmux_exact_target_tests.rs"]
mod exact_target_tests;