darwincode 1.9.97

The open source terminal AI coding agent
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
use crate::app::chat::MessageLine;
use crate::app::core::App;

pub fn run(app: &mut App, session_arg: Option<String>) {
    if let Some(session_id) = session_arg {
        // Switch/focus to a specific session or active process
        let mut found = false;
        let registry = crate::tui::PERSISTENT_SESSIONS
            .get_or_init(|| parking_lot::Mutex::new(std::collections::HashMap::new()));
        let has_session = {
            let map = registry.lock();
            map.contains_key(session_id.as_str())
        };

        let is_bg_process = {
            let bg_registry = crate::tui::BACKGROUND_PROCESSES
                .get_or_init(|| parking_lot::Mutex::new(std::collections::HashMap::new()));
            let map = bg_registry.lock();
            map.keys().any(|k| k.to_string() == session_id)
        };

        if has_session {
            *crate::tui::ACTIVE_PERSISTENT_SESSION_ID.lock() = Some(session_id.clone());
            app.chat.focused_shell_session_id = Some(session_id.clone());
            app.chat.focused_shell_pid = None;
            app.chat.shell_focused = true;

            for m in &mut app.chat.messages {
                if m.is_shell {
                    *m.cached_wrapped.borrow_mut() = None;
                }
            }

            let mut scrolled = false;
            let target_msg_idx = app
                .chat
                .messages
                .iter()
                .enumerate()
                .rev()
                .find(|(_, m)| m.is_shell && m.shell_session_id.as_ref() == Some(&session_id))
                .map(|(idx, _)| idx);
            if let Some(msg_idx) = target_msg_idx
                && let Some(&(_, start_line, end_line)) = app
                    .chat
                    .message_line_ranges
                    .borrow()
                    .iter()
                    .find(|&&(idx, _, _)| idx == msg_idx)
            {
                let total_lines = app
                    .chat
                    .message_line_ranges
                    .borrow()
                    .last()
                    .map(|(_, _, end)| *end)
                    .unwrap_or(0);
                let viewport_height = app
                    .chat
                    .messages_area
                    .get()
                    .map(|r| r.height as usize)
                    .unwrap_or(20);
                let max_scroll = total_lines.saturating_sub(viewport_height);
                let msg_height = end_line.saturating_sub(start_line);
                let mid_line = start_line + msg_height / 2;
                let target_scroll_y = mid_line.saturating_sub(viewport_height / 2);
                let scroll_val = max_scroll.saturating_sub(target_scroll_y);
                app.chat.scroll.set(scroll_val as u16);
                scrolled = true;
            }
            if !scrolled {
                app.chat.scroll.set(0);
            }

            *app.chat.message_line_ranges.borrow_mut() = Vec::new();
            app.status = "Ready".to_owned();
            found = true;
        } else if let Some(pid) = *crate::tui::RUNNING_PROCESS_PID.lock()
            && pid.to_string() == session_id
        {
            *crate::tui::ACTIVE_PERSISTENT_SESSION_ID.lock() = None;
            app.chat.focused_shell_session_id = None;
            app.chat.focused_shell_pid = Some(pid);
            app.chat.shell_focused = true;

            for m in &mut app.chat.messages {
                if m.is_shell {
                    *m.cached_wrapped.borrow_mut() = None;
                }
            }

            let mut scrolled = false;
            let target_msg_idx = app
                .chat
                .messages
                .iter()
                .enumerate()
                .rev()
                .find(|(_, m)| m.is_shell && m.shell_pid == Some(pid))
                .map(|(idx, _)| idx);
            if let Some(msg_idx) = target_msg_idx
                && let Some(&(_, start_line, end_line)) = app
                    .chat
                    .message_line_ranges
                    .borrow()
                    .iter()
                    .find(|&&(idx, _, _)| idx == msg_idx)
            {
                let total_lines = app
                    .chat
                    .message_line_ranges
                    .borrow()
                    .last()
                    .map(|(_, _, end)| *end)
                    .unwrap_or(0);
                let viewport_height = app
                    .chat
                    .messages_area
                    .get()
                    .map(|r| r.height as usize)
                    .unwrap_or(20);
                let max_scroll = total_lines.saturating_sub(viewport_height);
                let msg_height = end_line.saturating_sub(start_line);
                let mid_line = start_line + msg_height / 2;
                let target_scroll_y = mid_line.saturating_sub(viewport_height / 2);
                let scroll_val = max_scroll.saturating_sub(target_scroll_y);
                app.chat.scroll.set(scroll_val as u16);
                scrolled = true;
            }
            if !scrolled {
                app.chat.scroll.set(0);
            }

            *app.chat.message_line_ranges.borrow_mut() = Vec::new();
            app.status = "Ready".to_owned();
            found = true;
        } else if is_bg_process {
            let pid = session_id.parse::<u32>().unwrap();
            *crate::tui::ACTIVE_PERSISTENT_SESSION_ID.lock() = None;
            app.chat.focused_shell_session_id = None;
            app.chat.focused_shell_pid = Some(pid);
            app.chat.shell_focused = true;

            for m in &mut app.chat.messages {
                if m.is_shell {
                    *m.cached_wrapped.borrow_mut() = None;
                }
            }

            let mut scrolled = false;
            let target_msg_idx = app
                .chat
                .messages
                .iter()
                .enumerate()
                .rev()
                .find(|(_, m)| m.is_shell && m.shell_pid == Some(pid))
                .map(|(idx, _)| idx);
            if let Some(msg_idx) = target_msg_idx
                && let Some(&(_, start_line, end_line)) = app
                    .chat
                    .message_line_ranges
                    .borrow()
                    .iter()
                    .find(|&&(idx, _, _)| idx == msg_idx)
            {
                let total_lines = app
                    .chat
                    .message_line_ranges
                    .borrow()
                    .last()
                    .map(|(_, _, end)| *end)
                    .unwrap_or(0);
                let viewport_height = app
                    .chat
                    .messages_area
                    .get()
                    .map(|r| r.height as usize)
                    .unwrap_or(20);
                let max_scroll = total_lines.saturating_sub(viewport_height);
                let msg_height = end_line.saturating_sub(start_line);
                let mid_line = start_line + msg_height / 2;
                let target_scroll_y = mid_line.saturating_sub(viewport_height / 2);
                let scroll_val = max_scroll.saturating_sub(target_scroll_y);
                app.chat.scroll.set(scroll_val as u16);
                scrolled = true;
            }
            if !scrolled {
                app.chat.scroll.set(0);
            }

            *app.chat.message_line_ranges.borrow_mut() = Vec::new();
            app.status = "Ready".to_owned();
            found = true;
        }
        if !found {
            app.chat.messages.push(MessageLine::error(format!(
                "Shell session or active process '{}' not found or cannot be focused.",
                session_id
            )));
        }
    } else {
        // List all active sessions
        let registry = crate::tui::PERSISTENT_SESSIONS
            .get_or_init(|| parking_lot::Mutex::new(std::collections::HashMap::new()));

        let mut session_infos = Vec::new();

        // 1. Persistent Sessions
        {
            let map = registry.lock();
            for (id, session) in map.iter() {
                let is_running = matches!(session.child.lock().try_wait(), Ok(None));
                if is_running {
                    let active_str = if app.chat.shell_focused
                        && app.chat.focused_shell_session_id.as_ref() == Some(id)
                    {
                        " (focused)"
                    } else {
                        ""
                    };
                    session_infos.push(format!(
                        "- **Persistent Session: {}** (PID: {}) [active]{}",
                        id, session.pid, active_str
                    ));
                }
            }
        }

        // 2. Non-persistent Background Processes
        let bg_registry = crate::tui::BACKGROUND_PROCESSES
            .get_or_init(|| parking_lot::Mutex::new(std::collections::HashMap::new()));
        {
            let map = bg_registry.lock();
            for (pid, proc) in map.iter() {
                let is_running = proc.exit_status.lock().is_none();
                if is_running {
                    session_infos.push(format!(
                        "- **Background Process: {}** (PID: {}) [active]",
                        proc._command, pid
                    ));
                }
            }
        }

        // 3. Foreground Process
        if let Some(pid) = *crate::tui::RUNNING_PROCESS_PID.lock() {
            let is_focused = app.chat.shell_focused && app.chat.focused_shell_pid == Some(pid);
            let active_str = if is_focused { " (focused)" } else { "" };
            session_infos.push(format!(
                "- **Foreground Process** (PID: {}) [active]{}",
                pid, active_str
            ));
        }

        if session_infos.is_empty() {
            app.chat.messages.push(MessageLine::info(
                "No active shell sessions at this time.".to_owned(),
            ));
        } else {
            session_infos.sort();
            let info_text = format!(
                "Active shell sessions:\n{}\nUse `/shell [session_id_or_pid]` to focus a session.",
                session_infos.join("\n")
            );
            app.chat.messages.push(MessageLine::info(info_text));
        }
    }
}

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

    #[test]
    fn test_shell_run_list_empty() {
        let mut app = App::new(Some(StoredConfig::default()));
        // Clear registries or make sure they are empty
        if let Some(r) = crate::tui::PERSISTENT_SESSIONS.get() {
            r.lock().clear();
        }
        if let Some(bg) = crate::tui::BACKGROUND_PROCESSES.get() {
            bg.lock().clear();
        }
        *crate::tui::RUNNING_PROCESS_PID.lock() = None;

        run(&mut app, None);
        assert!(!app.chat.messages.is_empty());
        assert!(
            app.chat.messages[0]
                .text
                .contains("No active shell sessions")
        );
    }

    #[test]
    fn test_shell_run_list_with_active_sessions() {
        let mut app = App::new(Some(StoredConfig::default()));

        // Clear registries first
        let registry = crate::tui::PERSISTENT_SESSIONS
            .get_or_init(|| parking_lot::Mutex::new(std::collections::HashMap::new()));
        registry.lock().clear();

        let bg_registry = crate::tui::BACKGROUND_PROCESSES
            .get_or_init(|| parking_lot::Mutex::new(std::collections::HashMap::new()));
        bg_registry.lock().clear();

        // Spawn a dummy process for persistent session with piped stdin
        let mut child_p = std::process::Command::new("sleep")
            .arg("100")
            .stdin(std::process::Stdio::piped())
            .spawn()
            .unwrap();

        let pid_p = child_p.id();
        let stdin_p = child_p.stdin.take().unwrap();

        let sess_p = crate::tui::PersistentSession {
            pid: pid_p,
            child: std::sync::Arc::new(parking_lot::Mutex::new(child_p)),
            stdin: stdin_p,
            stdout_accumulator: std::sync::Arc::new(parking_lot::Mutex::new(String::new())),
            stderr_accumulator: std::sync::Arc::new(parking_lot::Mutex::new(String::new())),
        };
        registry.lock().insert("test_sess".to_owned(), sess_p);

        // Spawn a dummy process for background process
        let child_bg = std::process::Command::new("sleep")
            .arg("100")
            .spawn()
            .unwrap();
        let pid_bg = child_bg.id();
        let proc_bg = crate::tui::BackgroundProcess {
            _command: "sleep 100".to_owned(),
            child: std::sync::Arc::new(parking_lot::Mutex::new(child_bg)),
            stdin: None,
            stdout_accumulator: std::sync::Arc::new(parking_lot::Mutex::new(String::new())),
            stderr_accumulator: std::sync::Arc::new(parking_lot::Mutex::new(String::new())),
            exit_status: std::sync::Arc::new(parking_lot::Mutex::new(None)),
        };
        bg_registry.lock().insert(pid_bg, proc_bg);

        // Foreground process
        *crate::tui::RUNNING_PROCESS_PID.lock() = Some(9999);

        // Run list
        run(&mut app, None);

        assert!(!app.chat.messages.is_empty());
        let msg = &app.chat.messages[0].text;

        // Print for debugging if it fails
        println!("Active sessions message: {}", msg);

        // Verify child status
        {
            let reg = registry.lock();
            if let Some(sess) = reg.get("test_sess") {
                println!("test_sess try_wait: {:?}", sess.child.lock().try_wait());
            }
        }

        assert!(msg.contains("Persistent Session: test_sess"));
        assert!(msg.contains("Background Process: sleep 100"));
        assert!(msg.contains("Foreground Process"));

        // Focus persistent session
        run(&mut app, Some("test_sess".to_owned()));
        assert_eq!(
            app.chat.focused_shell_session_id,
            Some("test_sess".to_owned())
        );
        assert!(app.chat.shell_focused);

        // Focus background process
        run(&mut app, Some(pid_bg.to_string()));
        assert_eq!(app.chat.focused_shell_pid, Some(pid_bg));
        assert!(app.chat.shell_focused);

        // Focus foreground process
        run(&mut app, Some("9999".to_owned()));
        assert_eq!(app.chat.focused_shell_pid, Some(9999));

        // Focus nonexistent session
        run(&mut app, Some("nonexistent".to_owned()));
        assert!(
            app.chat
                .messages
                .iter()
                .any(|m| m.text.contains("not found"))
        );

        // Cleanup
        if let Some(sess) = registry.lock().remove("test_sess") {
            let _ = sess.child.lock().kill();
        }
        if let Some(proc) = bg_registry.lock().remove(&pid_bg) {
            let _ = proc.child.lock().kill();
        }
        *crate::tui::RUNNING_PROCESS_PID.lock() = None;
    }
}