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
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
use anyhow::Result;
use log::{debug, error, warn};
// Use log crate for debugging
use crate::ansi_processor::AnsiProcessor;
use crate::circular_buffer::CircularBuffer;
use portable_pty::{CommandBuilder, MasterPty, PtySize};
use std::collections::HashMap;
use std::io::Read;
use std::sync::{Arc, Mutex};
use std::thread;
pub struct PtyProcess {
pub muxbox_id: String,
pub process_id: Option<u32>,
pub status: PtyStatus,
pub master_pty: Option<Arc<Mutex<Box<dyn MasterPty + Send>>>>,
pub can_kill: bool, // Indicates if we can kill the process
pub output_buffer: Arc<Mutex<CircularBuffer>>, // Scrollback buffer for PTY output
pub stream_id: String, // Unique stream ID for this PTY process
}
impl std::fmt::Debug for PtyProcess {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PtyProcess")
.field("muxbox_id", &self.muxbox_id)
.field("process_id", &self.process_id)
.field("status", &self.status)
.field("master_pty", &self.master_pty.is_some())
.field("can_kill", &self.can_kill)
.field(
"output_buffer_size",
&self.output_buffer.lock().unwrap().len(),
)
.field("stream_id", &self.stream_id)
.finish()
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum PtyStatus {
Starting,
Running,
Finished(i32), // exit code
Error(String),
FailedFallback, // PTY failed, fell back to regular execution
Dead(String), // PTY process died unexpectedly with reason
}
// F0122: PTY Thread Integration - Now thread-safe by creating PTY system on-demand
unsafe impl Send for PtyManager {}
unsafe impl Sync for PtyManager {}
#[derive(Debug, Clone)]
pub struct PtyManager {
active_ptys: Arc<Mutex<HashMap<String, PtyProcess>>>,
pty_failures: Arc<Mutex<HashMap<String, Vec<String>>>>, // Track failure reasons per muxbox
}
impl PtyManager {
pub fn new() -> Result<Self> {
Ok(PtyManager {
active_ptys: Arc::new(Mutex::new(HashMap::new())),
pty_failures: Arc::new(Mutex::new(HashMap::new())),
})
}
/// Handle ExecuteScript message for PTY execution
pub fn handle_execute_script(
&self,
execute_script: &crate::model::common::ExecuteScript,
sender: std::sync::mpsc::Sender<(uuid::Uuid, crate::thread_manager::Message)>,
thread_uuid: uuid::Uuid,
) -> Result<()> {
log::info!(
"PTYManager handling ExecuteScript for target_box_id: {}, stream_id: {}",
execute_script.target_box_id,
execute_script.stream_id
);
let libs = if execute_script.libs.is_empty() {
None
} else {
Some(execute_script.libs.clone())
};
self.spawn_pty_script_with_redirect(
execute_script.target_box_id.clone(),
&execute_script.script,
libs,
sender,
thread_uuid,
execute_script.redirect_output.clone(),
Some(execute_script.stream_id.clone()),
execute_script.target_bounds.clone(),
)
}
/// Spawn a script in a PTY for the given muxbox
pub fn spawn_pty_script(
&self,
muxbox_id: String,
script_commands: &[String],
libs: Option<Vec<String>>,
sender: std::sync::mpsc::Sender<(uuid::Uuid, crate::thread_manager::Message)>,
thread_uuid: uuid::Uuid,
stream_id: Option<String>,
) -> Result<()> {
self.spawn_pty_script_with_redirect(
muxbox_id,
script_commands,
libs,
sender,
thread_uuid,
None,
stream_id, // Pass provided stream_id
None, // No bounds available for direct PTY script calls
)
}
/// Spawn a script in a PTY for the given muxbox with optional output redirection
pub fn spawn_pty_script_with_redirect(
&self,
muxbox_id: String,
script_commands: &[String],
libs: Option<Vec<String>>,
sender: std::sync::mpsc::Sender<(uuid::Uuid, crate::thread_manager::Message)>,
thread_uuid: uuid::Uuid,
redirect_target: Option<String>,
stream_id: Option<String>, // Custom stream ID to use for all output
target_bounds: Option<crate::model::common::Bounds>, // Target muxbox bounds for PTY sizing
) -> Result<()> {
// SOURCE OBJECT ARCHITECTURE: stream_id must be provided from source object - no fallbacks
let pty_stream_id = stream_id.expect(
"PTY execution requires stream_id from source object - architectural issue if None",
);
log::info!(
"Starting PTY script execution for muxbox: {}, redirect: {:?}, script_lines: {}, stream_id: {}",
muxbox_id,
redirect_target,
script_commands.len(),
pty_stream_id
);
// Calculate PTY size from target muxbox bounds
let pty_size = if let Some(bounds) = &target_bounds {
// Calculate content area inside borders (subtract 4 for 2-pixel borders on each side)
let content_width = bounds.width().saturating_sub(4);
let content_height = bounds.height().saturating_sub(4);
// Use content area dimensions for PTY terminal size
let cols = content_width.max(20) as u16; // Minimum 20 columns
let rows = content_height.max(5) as u16; // Minimum 5 rows
log::debug!(
"Using content area for PTY size: {}x{} (content area of {}x{} total) for {}",
cols,
rows,
content_width,
content_height,
muxbox_id
);
PtySize {
rows,
cols,
pixel_width: 0,
pixel_height: 0,
}
} else {
// Fallback to reasonable defaults if bounds not provided
log::warn!("No bounds provided for PTY {}, using defaults", muxbox_id);
PtySize {
rows: 40, // Fallback default
cols: 120, // Fallback default
pixel_width: 0,
pixel_height: 0,
}
};
// Create PTY system on-demand for thread safety
let pty_system = portable_pty::native_pty_system();
log::info!("PTY system created, attempting to allocate PTY pair");
let pty_pair = match pty_system.openpty(pty_size) {
Ok(pair) => {
log::info!("PTY pair allocated successfully");
pair
}
Err(e) => {
let error_msg = format!("PTY allocation failed: {}", e);
log::error!("{}", error_msg);
// Track this failure for recovery purposes
self.record_pty_failure(muxbox_id.clone(), error_msg.clone());
return Err(e);
}
};
let reader = pty_pair.master;
let writer = pty_pair.slave;
// Build the script content
let mut script_content = String::new();
if let Some(paths) = libs {
for lib in paths {
script_content.push_str(&format!("source {}\n", lib));
}
}
for command in script_commands {
script_content.push_str(&format!("{}\n", command));
}
// Create command to run in PTY
let mut cmd = CommandBuilder::new("bash");
cmd.arg("-c");
cmd.arg(&script_content);
// Spawn the process
let mut child = match writer.spawn_command(cmd) {
Ok(child) => {
log::info!(
"PTY process spawned successfully - PID: {:?}",
child.process_id()
);
child
}
Err(e) => {
let error_msg = format!("PTY process spawn failed: {}", e);
log::error!("{}", error_msg);
// Track this failure for recovery purposes
self.record_pty_failure(muxbox_id.clone(), error_msg.clone());
return Err(e);
}
};
let process_id = child.process_id();
// Store master PTY for resize operations using Arc<Mutex<>> for thread-safe sharing
let master_pty_handle = Arc::new(Mutex::new(reader));
let master_pty_clone = master_pty_handle.clone();
// Create circular buffer for PTY output with configurable size (default 10,000 lines)
let output_buffer = Arc::new(Mutex::new(CircularBuffer::new(10000)));
let buffer_clone = output_buffer.clone();
// Create PTY process record - use the stream_id determined at the start of function
let pty_process = PtyProcess {
muxbox_id: muxbox_id.clone(),
process_id,
status: PtyStatus::Running,
master_pty: Some(master_pty_handle),
can_kill: true, // Process can be killed
output_buffer,
stream_id: pty_stream_id.clone(),
};
// Store in active PTYs
{
let mut active_ptys = self.active_ptys.lock().unwrap();
active_ptys.insert(muxbox_id.clone(), pty_process);
}
// Determine target muxbox for output (original muxbox or redirect target)
let output_target = redirect_target.clone().unwrap_or_else(|| muxbox_id.clone());
// Spawn reader thread for PTY output
let active_ptys_clone = self.active_ptys.clone();
let muxbox_id_clone = muxbox_id.clone();
let _pty_stream_id_clone = pty_stream_id.clone();
let thread_uuid_clone = thread_uuid; // Pass correct UUID to PTY reader thread
let pty_size_clone = pty_size; // Pass PTY size to reader thread
thread::spawn(move || {
log::info!(
"PTY reader thread started for muxbox: {}, output_target: {}",
muxbox_id_clone,
output_target
);
let mut buffer = [0u8; 4096];
// Use actual PTY dimensions for AnsiProcessor to match terminal size
let mut ansi_processor = AnsiProcessor::with_screen_size(
pty_size_clone.cols as usize,
pty_size_clone.rows as usize,
);
// Start in line mode - will auto-detect and switch to screen mode if needed
ansi_processor.set_screen_mode(false);
let mut bytes_processed = 0u64;
let mut _messages_sent = 0u32;
// F0316: Performance Optimization - Track baseline capture for differential drawing
let mut baseline_captured = false;
// Create reader once outside the loop using cloned master PTY handle
let mut pty_reader = match master_pty_clone.lock().unwrap().try_clone_reader() {
Ok(reader) => {
log::info!("PTY reader cloned successfully");
reader
}
Err(e) => {
log::error!("Failed to clone PTY reader: {}", e);
return;
}
};
loop {
// Use non-blocking read with timeout to enable live streaming
match pty_reader.read(&mut buffer) {
Ok(0) => {
// EOF - process has ended
debug!("PTY EOF for muxbox: {}", muxbox_id_clone);
// Wait for child process and get exit status
let exit_code = match child.wait() {
Ok(status) => status.exit_code(),
Err(_) => 1,
};
// Update PTY status
{
let mut active_ptys = active_ptys_clone.lock().unwrap();
if let Some(pty_proc) = active_ptys.get_mut(&muxbox_id_clone) {
pty_proc.status = PtyStatus::Finished(exit_code as i32);
}
}
// Send remaining terminal screen content for stream integration
let remaining_text = ansi_processor.get_screen_content_for_stream();
if !remaining_text.is_empty() {
let pty_reader_uuid = uuid::Uuid::new_v4();
if let Err(e) = sender.send((
pty_reader_uuid,
// T0328: Replace MuxBoxOutputUpdate with StreamUpdateMessage
crate::thread_manager::Message::StreamUpdateMessage(crate::model::common::StreamUpdate {
stream_id: pty_stream_id.clone(),
target_box_id: output_target.clone(),
content_update: format!("{}\n", remaining_text), // Add newline for final output
source_state: crate::model::common::SourceState::Pty(
crate::model::common::PtySourceState {
process_id: 0,
runtime: std::time::Duration::from_millis(0),
exit_code: None,
status: crate::model::common::ExecutionPtyStatus::Completed,
}
),
execution_mode: crate::model::common::ExecutionMode::Pty,
}),
)) {
error!("Failed to send final PTY output: {}", e);
}
}
// Send final message indicating completion
if let Err(e) = sender.send((
thread_uuid_clone,
crate::thread_manager::Message::StreamUpdateMessage(
crate::model::common::StreamUpdate {
stream_id: pty_stream_id.clone(),
target_box_id: output_target.clone(),
content_update: format!(
"\n[Process exited with code {}]\n",
exit_code
),
source_state: crate::model::common::SourceState::Pty(
crate::model::common::PtySourceState {
process_id: 0,
runtime: std::time::Duration::from_millis(0),
exit_code: Some(exit_code as i32),
status:
crate::model::common::ExecutionPtyStatus::Completed,
},
),
execution_mode: crate::model::common::ExecutionMode::Pty,
},
),
)) {
error!("Failed to send PTY completion message: {}", e);
}
break;
}
Ok(bytes_read) => {
bytes_processed += bytes_read as u64;
log::debug!(
"Read {} bytes from PTY (total: {})",
bytes_read,
bytes_processed
);
// Process raw bytes through ANSI processor
ansi_processor.process_bytes(&buffer[..bytes_read]);
// F0316: Performance Optimization - Capture baseline for differential drawing
let should_replace = ansi_processor.should_replace_content();
if should_replace && !baseline_captured {
// Full-screen program detected - capture initial state for differential drawing
ansi_processor.capture_baseline();
baseline_captured = true;
log::debug!("F0316: Captured baseline screen state for differential drawing (screen_mode={}, terminal_size={}x{})",
ansi_processor.use_screen_buffer,
ansi_processor.terminal_state.screen_width,
ansi_processor.terminal_state.screen_height);
}
// Get terminal screen content for stream integration
// This feeds PTY TerminalScreenBuffer into BoxMux's main differential drawing system
let content_to_send = ansi_processor.get_screen_content_for_stream();
if !content_to_send.trim().is_empty() {
if should_replace {
log::info!("Full-screen program detected - sending terminal screen content ({} chars) to {}",
content_to_send.len(), output_target);
} else {
log::info!("Line-based program - sending processed content ({} chars) to {}",
content_to_send.len(), output_target);
}
} else {
continue; // No content to send
}
// Send content if we have any
if !content_to_send.trim().is_empty() {
// Store content in circular buffer for scrollback
if let Ok(mut buffer) = buffer_clone.lock() {
buffer.push(content_to_send.clone());
debug!("Added content to PTY buffer (total: {})", buffer.len());
}
// F0316: Capture length for debug logging before content is moved
let content_length = content_to_send.len();
// Create appropriate content update based on program behavior
let content_update = if should_replace {
format!("REPLACE:{}", content_to_send) // Signal to replace, not append
} else {
content_to_send // Normal append behavior
};
let message = crate::thread_manager::Message::StreamUpdateMessage(
crate::model::common::StreamUpdate {
stream_id: pty_stream_id.clone(),
target_box_id: output_target.clone(),
content_update,
source_state: crate::model::common::SourceState::Pty(
crate::model::common::PtySourceState {
process_id: 0,
runtime: std::time::Duration::from_millis(0),
exit_code: None,
status:
crate::model::common::ExecutionPtyStatus::Running,
},
),
execution_mode: crate::model::common::ExecutionMode::Pty,
},
);
// Use correct thread_uuid for ThreadManager message routing
debug!(
"About to send PTY message via channel - thread_uuid: {:?}",
thread_uuid_clone
);
if let Err(e) = sender.send((thread_uuid_clone, message)) {
error!(
"PTY message send failed - channel disconnected or full: {}",
e
);
break;
} else {
debug!("PTY message sent successfully via channel");
}
_messages_sent += 1;
// F0316: Performance Optimization - Update screen state for next differential comparison
if baseline_captured && should_replace {
ansi_processor.update_screen_state();
log::debug!("F0316: Updated screen state after sending {} characters for differential comparison", content_length);
}
}
}
Err(e) => {
error!("Error reading from PTY: {}", e);
// Update PTY status to error
{
let mut active_ptys = active_ptys_clone.lock().unwrap();
if let Some(pty_proc) = active_ptys.get_mut(&muxbox_id_clone) {
pty_proc.status = PtyStatus::Error(e.to_string());
}
}
// Send error message
if let Err(e) = sender.send((
thread_uuid_clone,
crate::thread_manager::Message::StreamUpdateMessage(
crate::model::common::StreamUpdate {
stream_id: pty_stream_id.clone(),
target_box_id: muxbox_id_clone.clone(),
content_update: format!("[PTY Error: {}]", e),
source_state: crate::model::common::SourceState::Pty(
crate::model::common::PtySourceState {
process_id: 0,
runtime: std::time::Duration::from_millis(0),
exit_code: Some(1),
status:
crate::model::common::ExecutionPtyStatus::Failed(
"PTY error".to_string(),
),
},
),
execution_mode: crate::model::common::ExecutionMode::Pty,
},
),
)) {
error!("Failed to send PTY error message: {}", e);
}
break;
}
}
// Small delay to prevent busy waiting
std::thread::sleep(std::time::Duration::from_millis(10));
}
});
Ok(())
}
/// F0310: Generate terminal state-aware mouse sequence based on current terminal modes
pub fn generate_mouse_sequence(
&self,
muxbox_id: &str,
kind: crossterm::event::MouseEventKind,
column: u16,
row: u16,
modifiers: crossterm::event::KeyModifiers,
) -> Option<String> {
use crate::ansi_processor::{
MouseButton as AnsiMouseButton, MouseEventType, MouseModifiers,
};
use crossterm::event::{KeyModifiers, MouseButton as CrosstermButton, MouseEventKind};
let active_ptys = self.active_ptys.lock().unwrap();
let _pty_process = active_ptys.get(muxbox_id)?;
// Convert crossterm event to our mouse event types
let (event_type, button) = match kind {
MouseEventKind::Down(crossterm_button) => {
let button = match crossterm_button {
CrosstermButton::Left => Some(AnsiMouseButton::Left),
CrosstermButton::Right => Some(AnsiMouseButton::Right),
CrosstermButton::Middle => Some(AnsiMouseButton::Middle),
};
(MouseEventType::Press, button)
}
MouseEventKind::Up(crossterm_button) => {
let button = match crossterm_button {
CrosstermButton::Left => Some(AnsiMouseButton::Left),
CrosstermButton::Right => Some(AnsiMouseButton::Right),
CrosstermButton::Middle => Some(AnsiMouseButton::Middle),
};
(MouseEventType::Release, button)
}
MouseEventKind::Drag(_) => (MouseEventType::Motion, None),
MouseEventKind::ScrollUp => (MouseEventType::Wheel, Some(AnsiMouseButton::WheelUp)),
MouseEventKind::ScrollDown => (MouseEventType::Wheel, Some(AnsiMouseButton::WheelDown)),
MouseEventKind::ScrollLeft => (MouseEventType::Wheel, Some(AnsiMouseButton::WheelLeft)),
MouseEventKind::ScrollRight => {
(MouseEventType::Wheel, Some(AnsiMouseButton::WheelRight))
}
_ => return None,
};
// Convert crossterm modifiers to our modifier struct
let mouse_modifiers = MouseModifiers {
shift: modifiers.contains(KeyModifiers::SHIFT),
ctrl: modifiers.contains(KeyModifiers::CONTROL),
alt: modifiers.contains(KeyModifiers::ALT),
meta: modifiers.contains(KeyModifiers::SUPER),
};
// Generate basic mouse sequence (TODO: integrate with actual terminal state)
self.generate_basic_mouse_sequence(
event_type,
column as usize,
row as usize,
button,
mouse_modifiers,
)
}
/// Generate basic mouse report for initial implementation
fn generate_basic_mouse_sequence(
&self,
event_type: crate::ansi_processor::MouseEventType,
x: usize,
y: usize,
button: Option<crate::ansi_processor::MouseButton>,
modifiers: crate::ansi_processor::MouseModifiers,
) -> Option<String> {
use crate::ansi_processor::{MouseButton as AnsiMouseButton, MouseEventType};
// Only report press events and wheel for basic compatibility
if event_type != MouseEventType::Press && event_type != MouseEventType::Wheel {
return None;
}
let mut cb;
// Set button bits
match (event_type, button) {
(MouseEventType::Press, Some(AnsiMouseButton::Left)) => cb = 0,
(MouseEventType::Press, Some(AnsiMouseButton::Middle)) => cb = 1,
(MouseEventType::Press, Some(AnsiMouseButton::Right)) => cb = 2,
(MouseEventType::Wheel, Some(AnsiMouseButton::WheelUp)) => cb = 64,
(MouseEventType::Wheel, Some(AnsiMouseButton::WheelDown)) => cb = 65,
_ => return None,
}
// Add modifier bits
if modifiers.shift {
cb += 4;
}
if modifiers.ctrl {
cb += 8;
}
if modifiers.alt {
cb += 16;
}
// Add base offset
cb += 32;
// Coordinates are 1-based and offset by 32, clamped to valid range
let cx = ((x + 1).min(223)) as u8 + 32;
let cy = ((y + 1).min(223)) as u8 + 32;
Some(format!(
"\x1b[M{}{}{}",
char::from(cb),
char::from(cx),
char::from(cy)
))
}
/// Send input to a PTY
pub fn send_input(&self, muxbox_id: &str, input: &str) -> Result<()> {
debug!("PTY input for muxbox {}: {}", muxbox_id, input);
let active_ptys = self.active_ptys.lock().unwrap();
if let Some(pty_process) = active_ptys.get(muxbox_id) {
// Check if PTY is running and can accept input
match pty_process.status {
PtyStatus::Running | PtyStatus::Starting => {
if let Some(master_pty_handle) = &pty_process.master_pty {
// Real PTY - write to actual PTY by getting a writer
let master_pty = master_pty_handle.lock().unwrap();
// Get writer from master PTY
let mut writer = master_pty
.take_writer()
.map_err(|e| anyhow::anyhow!("Failed to get PTY writer: {}", e))?;
// Write input to PTY
use std::io::Write;
writer
.write_all(input.as_bytes())
.map_err(|e| anyhow::anyhow!("Failed to write to PTY: {}", e))?;
writer
.flush()
.map_err(|e| anyhow::anyhow!("Failed to flush PTY writer: {}", e))?;
debug!(
"Successfully sent {} bytes to real PTY {}",
input.len(),
muxbox_id
);
Ok(())
} else {
// Test PTY or PTY without master handle - simulate successful input
#[cfg(test)]
{
debug!(
"Test PTY - simulating successful input send for {}",
muxbox_id
);
Ok(())
}
#[cfg(not(test))]
{
Err(anyhow::anyhow!(
"No master PTY handle available for muxbox: {}",
muxbox_id
))
}
}
}
PtyStatus::Finished(_) => Err(anyhow::anyhow!(
"PTY process {} has finished and cannot accept input",
muxbox_id
)),
PtyStatus::Error(ref err) => Err(anyhow::anyhow!(
"PTY process {} is in error state: {}",
muxbox_id,
err
)),
PtyStatus::FailedFallback => Err(anyhow::anyhow!(
"PTY process {} failed and fell back to regular execution",
muxbox_id
)),
PtyStatus::Dead(ref reason) => Err(anyhow::anyhow!(
"PTY process {} is dead: {}",
muxbox_id,
reason
)),
}
} else {
Err(anyhow::anyhow!(
"No PTY process found for muxbox: {}",
muxbox_id
))
}
}
/// Resize a PTY to match muxbox content area dimensions
pub fn resize_pty(&mut self, muxbox_id: &str, rows: u16, cols: u16) -> Result<()> {
// Subtract border space from dimensions to get content area
let content_cols = cols.saturating_sub(4).max(20);
let content_rows = rows.saturating_sub(4).max(5);
debug!(
"Resizing PTY for muxbox {} to content area {}x{} (from total {}x{})",
muxbox_id, content_cols, content_rows, cols, rows
);
let active_ptys = self.active_ptys.lock().unwrap();
if let Some(pty_process) = active_ptys.get(muxbox_id) {
if let Some(master_pty_handle) = &pty_process.master_pty {
let pty_size = PtySize {
rows: content_rows,
cols: content_cols,
pixel_width: 0,
pixel_height: 0,
};
match master_pty_handle.lock().unwrap().resize(pty_size) {
Ok(_) => {
debug!(
"PTY successfully resized for muxbox {} to content area {}x{}",
muxbox_id, content_cols, content_rows
);
}
Err(e) => {
warn!("PTY resize failed for muxbox {}: {}", muxbox_id, e);
return Err(e);
}
}
} else {
debug!("No master PTY handle available for muxbox: {}", muxbox_id);
}
} else {
debug!("PTY not found for muxbox: {}", muxbox_id);
}
Ok(())
}
/// Kill a PTY process
pub fn kill_pty(&mut self, muxbox_id: &str) -> Result<()> {
let mut active_ptys = self.active_ptys.lock().unwrap();
if let Some(pty_process) = active_ptys.get_mut(muxbox_id) {
debug!("Killing PTY process for muxbox: {}", muxbox_id);
if pty_process.can_kill {
if let Some(pid) = pty_process.process_id {
// Use system kill command for cross-platform killing
#[cfg(unix)]
{
use std::process::Command;
match Command::new("kill").arg("-9").arg(pid.to_string()).output() {
Ok(_) => {
debug!(
"Successfully killed PTY process {} for muxbox: {}",
pid, muxbox_id
);
pty_process.status = PtyStatus::Finished(-9); // SIGKILL
pty_process.can_kill = false; // Already killed
}
Err(e) => {
warn!(
"Failed to kill PTY process {} for muxbox {}: {}",
pid, muxbox_id, e
);
pty_process.status =
PtyStatus::Error(format!("Kill failed: {}", e));
}
}
}
#[cfg(not(unix))]
{
warn!(
"Process killing not supported on this platform for muxbox: {}",
muxbox_id
);
pty_process.status = PtyStatus::Error("Kill not supported".to_string());
}
} else {
warn!("No process ID available for muxbox: {}", muxbox_id);
pty_process.status = PtyStatus::Error("No process ID".to_string());
}
} else {
debug!(
"Process for muxbox {} already killed or cannot be killed",
muxbox_id
);
}
// Drop the PTY handle to clean up resources
pty_process.master_pty = None;
}
Ok(())
}
/// Get status of a PTY process
pub fn get_pty_status(&self, muxbox_id: &str) -> Option<PtyStatus> {
let active_ptys = self.active_ptys.lock().unwrap();
active_ptys.get(muxbox_id).map(|p| p.status.clone())
}
/// Clean up finished PTY processes
pub fn cleanup_finished(&mut self) {
let mut active_ptys = self.active_ptys.lock().unwrap();
active_ptys.retain(|muxbox_id, pty_process| {
match &pty_process.status {
PtyStatus::Finished(_) | PtyStatus::Error(_) => {
debug!("Cleaning up finished PTY for muxbox: {}", muxbox_id);
false // Remove from map
}
_ => true, // Keep running PTYs
}
});
}
/// Get list of active PTY muxbox IDs
pub fn get_active_pty_muxboxes(&self) -> Vec<String> {
let active_ptys = self.active_ptys.lock().unwrap();
active_ptys.keys().cloned().collect()
}
/// Send signal to a PTY process (future enhancement)
pub fn send_signal(&mut self, muxbox_id: &str, _signal: i32) -> Result<()> {
debug!(
"Signal send request for muxbox: {} (not yet implemented)",
muxbox_id
);
// TODO: Implement signal sending when portable_pty supports it
// For now, only kill() is supported through kill_pty()
Ok(())
}
/// Get process information for a PTY
pub fn get_process_info(&self, muxbox_id: &str) -> Option<(u32, PtyStatus)> {
let active_ptys = self.active_ptys.lock().unwrap();
active_ptys
.get(muxbox_id)
.and_then(|p| p.process_id.map(|pid| (pid, p.status.clone())))
}
/// Check if a PTY process is still running
pub fn is_process_running(&self, muxbox_id: &str) -> bool {
let active_ptys = self.active_ptys.lock().unwrap();
active_ptys
.get(muxbox_id)
.map(|p| matches!(p.status, PtyStatus::Running | PtyStatus::Starting))
.unwrap_or(false)
}
/// Record a PTY failure for error recovery tracking
fn record_pty_failure(&self, muxbox_id: String, error_msg: String) {
let mut pty_failures = self.pty_failures.lock().unwrap();
pty_failures.entry(muxbox_id).or_default().push(error_msg);
}
/// Get PTY failure history for a muxbox
pub fn get_pty_failure_history(&self, muxbox_id: &str) -> Vec<String> {
let pty_failures = self.pty_failures.lock().unwrap();
pty_failures.get(muxbox_id).cloned().unwrap_or_default()
}
/// Check if a muxbox has had recent PTY failures (within last few attempts)
pub fn has_recent_pty_failures(&self, muxbox_id: &str, threshold: usize) -> bool {
let pty_failures = self.pty_failures.lock().unwrap();
pty_failures
.get(muxbox_id)
.map(|failures| failures.len() >= threshold)
.unwrap_or(false)
}
/// Clear PTY failure history for a muxbox (useful after successful execution)
pub fn clear_pty_failures(&self, muxbox_id: &str) {
let mut pty_failures = self.pty_failures.lock().unwrap();
pty_failures.remove(muxbox_id);
}
/// Check if PTY should be avoided for this muxbox due to repeated failures
pub fn should_avoid_pty(&self, muxbox_id: &str) -> bool {
self.has_recent_pty_failures(muxbox_id, 3) // Avoid PTY after 3 consecutive failures
}
/// Reset PTY failure tracking (useful for testing or reset operations)
pub fn reset_failure_tracking(&self) {
let mut pty_failures = self.pty_failures.lock().unwrap();
pty_failures.clear();
}
/// Get the circular buffer for a PTY muxbox (for scrollback access)
pub fn get_output_buffer(&self, muxbox_id: &str) -> Option<Arc<Mutex<CircularBuffer>>> {
let active_ptys = self.active_ptys.lock().unwrap();
active_ptys.get(muxbox_id).map(|p| p.output_buffer.clone())
}
/// Get scrollback content for a PTY muxbox
pub fn get_scrollback_content(&self, muxbox_id: &str) -> Option<String> {
let active_ptys = self.active_ptys.lock().unwrap();
active_ptys.get(muxbox_id).and_then(|p| {
p.output_buffer
.lock()
.ok()
.map(|buffer| buffer.get_content())
})
}
/// Get recent lines from a PTY muxbox's buffer
pub fn get_recent_lines(&self, muxbox_id: &str, line_count: usize) -> Option<Vec<String>> {
let active_ptys = self.active_ptys.lock().unwrap();
active_ptys.get(muxbox_id).and_then(|p| {
p.output_buffer
.lock()
.ok()
.map(|buffer| buffer.get_last_lines(line_count))
})
}
/// Search for text in a PTY muxbox's buffer
pub fn search_buffer(&self, muxbox_id: &str, query: &str) -> Option<Vec<(usize, String)>> {
let active_ptys = self.active_ptys.lock().unwrap();
active_ptys.get(muxbox_id).and_then(|p| {
p.output_buffer
.lock()
.ok()
.map(|buffer| buffer.search(query))
})
}
/// Get buffer statistics for a PTY muxbox
pub fn get_buffer_stats(&self, muxbox_id: &str) -> Option<crate::circular_buffer::BufferStats> {
let active_ptys = self.active_ptys.lock().unwrap();
active_ptys
.get(muxbox_id)
.and_then(|p| p.output_buffer.lock().ok().map(|buffer| buffer.get_stats()))
}
/// Configure buffer size for a PTY muxbox (can be called before or during execution)
pub fn set_buffer_size(&self, muxbox_id: &str, max_size: usize) -> Result<()> {
let active_ptys = self.active_ptys.lock().unwrap();
if let Some(pty_process) = active_ptys.get(muxbox_id) {
if let Ok(mut buffer) = pty_process.output_buffer.lock() {
buffer.set_max_size(max_size);
debug!("Set buffer size for muxbox {} to {}", muxbox_id, max_size);
Ok(())
} else {
Err(anyhow::anyhow!(
"Failed to lock buffer for muxbox: {}",
muxbox_id
))
}
} else {
Err(anyhow::anyhow!("PTY not found for muxbox: {}", muxbox_id))
}
}
/// Clear the buffer for a PTY muxbox
pub fn clear_buffer(&self, muxbox_id: &str) -> Result<()> {
let active_ptys = self.active_ptys.lock().unwrap();
if let Some(pty_process) = active_ptys.get(muxbox_id) {
if let Ok(mut buffer) = pty_process.output_buffer.lock() {
buffer.clear();
debug!("Cleared buffer for muxbox {}", muxbox_id);
Ok(())
} else {
Err(anyhow::anyhow!(
"Failed to lock buffer for muxbox: {}",
muxbox_id
))
}
} else {
Err(anyhow::anyhow!("PTY not found for muxbox: {}", muxbox_id))
}
}
/// Get buffer content within a specific range (for pagination/scrolling)
pub fn get_buffer_range(
&self,
muxbox_id: &str,
start: usize,
count: usize,
) -> Option<Vec<String>> {
let active_ptys = self.active_ptys.lock().unwrap();
active_ptys.get(muxbox_id).and_then(|p| {
p.output_buffer
.lock()
.ok()
.map(|buffer| buffer.get_lines_range(start, count))
})
}
/// Get the stream ID for a PTY process
pub fn get_stream_id(&self, muxbox_id: &str) -> Option<String> {
let active_ptys = self.active_ptys.lock().unwrap();
active_ptys.get(muxbox_id).map(|pty| pty.stream_id.clone())
}
/// Get detailed process information for display purposes
/// F0132: PTY Process Info - Enhanced process details for status display
pub fn get_detailed_process_info(&self, muxbox_id: &str) -> Option<ProcessInfo> {
let active_ptys = self.active_ptys.lock().unwrap();
active_ptys.get(muxbox_id).map(|p| ProcessInfo {
muxbox_id: p.muxbox_id.clone(),
process_id: p.process_id,
status: p.status.clone(),
can_kill: p.can_kill,
buffer_lines: p.output_buffer.lock().map(|buf| buf.len()).unwrap_or(0),
is_running: matches!(p.status, PtyStatus::Running | PtyStatus::Starting),
})
}
/// Get process status summary for compact display
/// F0132: PTY Process Info - Compact status for title display
/// F0135: PTY Error States - Enhanced with dead process indication
pub fn get_process_status_summary(&self, muxbox_id: &str) -> Option<String> {
self.get_process_info(muxbox_id).map(|(pid, status)| {
let status_text = match status {
PtyStatus::Starting => "Starting".to_string(),
PtyStatus::Running => "Running".to_string(),
PtyStatus::Finished(code) => {
if code == 0 {
"Done".to_string()
} else {
format!("Exit:{}", code)
}
}
PtyStatus::Error(ref msg) => {
if msg.len() > 10 {
format!("Error:{}", &msg[..7])
} else {
format!("Error:{}", msg)
}
}
PtyStatus::FailedFallback => "Fallback".to_string(),
PtyStatus::Dead(ref reason) => {
if reason.len() > 8 {
format!("Dead:{}", &reason[..5])
} else {
format!("Dead:{}", reason)
}
}
};
format!("PID:{} {}", pid, status_text)
})
}
/// Check if a PTY process is in an error state
/// F0135: PTY Error States - Detect processes requiring visual error indication
pub fn is_pty_in_error_state(&self, muxbox_id: &str) -> bool {
if let Some((_, status)) = self.get_process_info(muxbox_id) {
matches!(
status,
PtyStatus::Error(_) | PtyStatus::Dead(_) | PtyStatus::FailedFallback
)
} else {
false
}
}
/// Check if a PTY process is dead and needs recovery
/// F0135: PTY Error States - Detect dead processes needing restart
pub fn is_pty_dead(&self, muxbox_id: &str) -> bool {
if let Some((_, status)) = self.get_process_info(muxbox_id) {
matches!(status, PtyStatus::Dead(_))
} else {
false
}
}
/// Get error state details for recovery UI
/// F0135: PTY Error States - Provide error context for recovery actions
pub fn get_error_state_info(&self, muxbox_id: &str) -> Option<ErrorStateInfo> {
if let Some((pid, status)) = self.get_process_info(muxbox_id) {
match status {
PtyStatus::Error(msg) => Some(ErrorStateInfo {
muxbox_id: muxbox_id.to_string(),
error_type: ErrorType::ExecutionError,
message: msg,
pid: Some(pid),
can_retry: true,
suggested_action: "Retry PTY execution".to_string(),
}),
PtyStatus::Dead(reason) => Some(ErrorStateInfo {
muxbox_id: muxbox_id.to_string(),
error_type: ErrorType::ProcessDied,
message: reason,
pid: Some(pid),
can_retry: true,
suggested_action: "Restart PTY process".to_string(),
}),
PtyStatus::FailedFallback => Some(ErrorStateInfo {
muxbox_id: muxbox_id.to_string(),
error_type: ErrorType::FallbackUsed,
message: "PTY failed, using regular execution".to_string(),
pid: Some(pid),
can_retry: true,
suggested_action: "Reset PTY and retry".to_string(),
}),
_ => None,
}
} else {
None
}
}
/// Mark a PTY process as dead with reason
/// F0135: PTY Error States - Set dead status for error visualization
pub fn mark_pty_dead(&self, muxbox_id: &str, reason: String) -> Result<(), anyhow::Error> {
let mut active_ptys = self.active_ptys.lock().unwrap();
if let Some(pty_process) = active_ptys.get_mut(muxbox_id) {
pty_process.status = PtyStatus::Dead(reason);
Ok(())
} else {
Err(anyhow::anyhow!("PTY not found for muxbox: {}", muxbox_id))
}
}
/// Kill a PTY process via socket command
/// F0137: Socket PTY Control - Terminate PTY process remotely
pub fn kill_pty_process(&self, muxbox_id: &str) -> Result<(), anyhow::Error> {
let mut active_ptys = self.active_ptys.lock().unwrap();
if let Some(pty_process) = active_ptys.get_mut(muxbox_id) {
if let Some(pid) = pty_process.process_id {
// Use existing kill functionality
if pty_process.can_kill {
// Kill the process using system kill command
let kill_result = if cfg!(target_os = "windows") {
std::process::Command::new("taskkill")
.args(["/F", "/PID", &pid.to_string()])
.output()
} else {
std::process::Command::new("kill")
.args(["-9", &pid.to_string()])
.output()
};
match kill_result {
Ok(output) => {
if output.status.success() {
pty_process.status = PtyStatus::Finished(-9); // Killed signal
log::info!("Killed PTY process {} for muxbox {}", pid, muxbox_id);
Ok(())
} else {
let error_msg = format!(
"Kill command failed: {}",
String::from_utf8_lossy(&output.stderr)
);
pty_process.status = PtyStatus::Error(error_msg.clone());
Err(anyhow::anyhow!(error_msg))
}
}
Err(e) => {
let error_msg = format!("Failed to execute kill command: {}", e);
pty_process.status = PtyStatus::Error(error_msg.clone());
Err(anyhow::anyhow!(error_msg))
}
}
} else {
Err(anyhow::anyhow!(
"Process {} for muxbox {} cannot be killed",
pid,
muxbox_id
))
}
} else {
Err(anyhow::anyhow!(
"No process ID available for muxbox {}",
muxbox_id
))
}
} else {
Err(anyhow::anyhow!("PTY not found for muxbox: {}", muxbox_id))
}
}
/// Restart a PTY process via socket command
/// F0137: Socket PTY Control - Restart PTY process after termination
pub fn restart_pty_process(&self, muxbox_id: &str) -> Result<(), anyhow::Error> {
// First, kill the existing process if it's still running
if self.is_process_running(muxbox_id) {
if let Err(e) = self.kill_pty_process(muxbox_id) {
log::warn!("Failed to kill existing process during restart: {}", e);
}
// Give the process time to terminate
std::thread::sleep(std::time::Duration::from_millis(100));
}
// Clear the failure tracking for this muxbox to allow PTY retry
self.clear_pty_failures(muxbox_id);
// Mark the PTY as needing restart by setting it to Starting status
let mut active_ptys = self.active_ptys.lock().unwrap();
if let Some(pty_process) = active_ptys.get_mut(muxbox_id) {
pty_process.status = PtyStatus::Starting;
pty_process.process_id = None; // Clear old PID
log::info!("Marked PTY process for restart on muxbox {}", muxbox_id);
Ok(())
} else {
Err(anyhow::anyhow!("PTY not found for muxbox: {}", muxbox_id))
}
}
/// Test helper - Add a PTY process for testing purposes
#[cfg(test)]
pub fn add_test_pty_process(&self, muxbox_id: String, buffer: Arc<Mutex<CircularBuffer>>) {
let pty_process = PtyProcess {
muxbox_id: muxbox_id.clone(),
process_id: Some(12345),
status: PtyStatus::Running,
master_pty: None,
can_kill: false,
output_buffer: buffer,
stream_id: format!("pty-test-{}", &uuid::Uuid::new_v4().to_string()[..8]),
};
self.active_ptys
.lock()
.unwrap()
.insert(muxbox_id, pty_process);
}
/// Test helper - Add a PTY process with custom status
#[cfg(test)]
pub fn add_test_pty_process_with_status(
&self,
muxbox_id: String,
buffer: Arc<Mutex<CircularBuffer>>,
status: PtyStatus,
pid: u32,
) {
let pty_process = PtyProcess {
muxbox_id: muxbox_id.clone(),
process_id: Some(pid),
status,
master_pty: None,
can_kill: false,
output_buffer: buffer,
stream_id: format!("pty-test-{}", &uuid::Uuid::new_v4().to_string()[..8]),
};
self.active_ptys
.lock()
.unwrap()
.insert(muxbox_id, pty_process);
}
/// Test helper - Set PTY process killability for testing
#[cfg(test)]
pub fn set_pty_killable(&self, muxbox_id: &str, can_kill: bool) {
let mut active_ptys = self.active_ptys.lock().unwrap();
if let Some(pty_process) = active_ptys.get_mut(muxbox_id) {
pty_process.can_kill = can_kill;
}
}
}
/// F0132: PTY Process Info - Detailed process information structure
#[derive(Debug, Clone)]
pub struct ProcessInfo {
pub muxbox_id: String,
pub process_id: Option<u32>,
pub status: PtyStatus,
pub can_kill: bool,
pub buffer_lines: usize,
pub is_running: bool,
}
/// F0135: PTY Error States - Error state information for recovery UI
#[derive(Debug, Clone)]
pub struct ErrorStateInfo {
pub muxbox_id: String,
pub error_type: ErrorType,
pub message: String,
pub pid: Option<u32>,
pub can_retry: bool,
pub suggested_action: String,
}
/// F0135: PTY Error States - Types of PTY errors
#[derive(Debug, Clone, PartialEq)]
pub enum ErrorType {
ExecutionError, // Script/command execution failed
ProcessDied, // PTY process died unexpectedly
FallbackUsed, // PTY failed, using regular execution
}
impl Default for PtyManager {
fn default() -> Self {
Self::new().expect("Failed to create PTY manager")
}
}