darwincode 1.9.69

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
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
use anyhow::Result;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use std::sync::mpsc::Sender;

use crate::app::{App, SubmitAction};
use crate::tui::events::common::{copy_to_clipboard, read_from_clipboard};
use crate::tui::{
    WorkerEvent, handle_function_action, spawn_generation_worker, spawn_models_worker,
};

pub(crate) fn handle_chat_key(
    app: &mut App,
    sender: &Sender<WorkerEvent>,
    key: KeyEvent,
) -> Result<()> {
    if matches!(
        app.pending,
        Some(crate::app::PendingTask::ConfirmFunction { .. })
    ) {
        match key.code {
            KeyCode::Char('y') | KeyCode::Char('Y') => {
                if let Some(action) = app.answer_function_confirmation(true) {
                    handle_function_action(action, sender);
                }
            }
            KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
                if let Some(action) = app.answer_function_confirmation(false) {
                    handle_function_action(action, sender);
                }
            }
            KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                app.should_quit = true;
            }
            KeyCode::Up => {
                app.confirm_scroll = app.confirm_scroll.saturating_sub(1);
            }
            KeyCode::Down => {
                app.confirm_scroll = app.confirm_scroll.saturating_add(1);
            }
            KeyCode::PageUp => {
                app.confirm_scroll = app.confirm_scroll.saturating_sub(10);
            }
            KeyCode::PageDown => {
                app.confirm_scroll = app.confirm_scroll.saturating_add(10);
            }
            _ => {
                if app
                    .keybindings
                    .matches(crate::tui::keybindings::TuiAction::ScrollUp, key)
                {
                    app.confirm_scroll = app.confirm_scroll.saturating_sub(1);
                } else if app
                    .keybindings
                    .matches(crate::tui::keybindings::TuiAction::ScrollDown, key)
                {
                    app.confirm_scroll = app.confirm_scroll.saturating_add(1);
                }
            }
        }
        return Ok(());
    }

    if app.chat.shell_focused {
        let is_ctrl_c = (key.code == KeyCode::Char('c')
            && key.modifiers.contains(KeyModifiers::CONTROL))
            || app
                .keybindings
                .matches(crate::tui::keybindings::TuiAction::Quit, key);
        let is_esc = app
            .keybindings
            .matches(crate::tui::keybindings::TuiAction::Cancel, key);

        if is_ctrl_c || is_esc {
            let mut pid = None;
            if let Ok(mut guard) = crate::tui::RUNNING_PROCESS_PID.lock() {
                pid = guard.take();
            }
            if let Some(pid) = pid {
                #[cfg(unix)]
                {
                    let _ = std::process::Command::new("kill")
                        .arg("-9")
                        .arg(format!("-{}", pid))
                        .status();
                }
                #[cfg(not(unix))]
                {
                    let _ = std::process::Command::new("taskkill")
                        .arg("/F")
                        .arg("/PID")
                        .arg(pid.to_string())
                        .status();
                }
            }
            app.cancel_generation();
            app.chat.shell_focused = false;
            for m in &mut app.chat.messages {
                if m.is_shell {
                    *m.cached_wrapped.borrow_mut() = None;
                }
            }
            app.status = "Aborted by user".to_owned();
            return Ok(());
        }

        if key.code == KeyCode::Tab {
            app.chat.shell_focused = false;
            for m in &mut app.chat.messages {
                if m.is_shell {
                    *m.cached_wrapped.borrow_mut() = None;
                }
            }
            app.status = "Ready".to_owned();
            return Ok(());
        }

        if app
            .keybindings
            .matches(crate::tui::keybindings::TuiAction::ScrollUp, key)
        {
            app.chat.scroll = app.chat.scroll.saturating_add(1);
            return Ok(());
        }
        if app
            .keybindings
            .matches(crate::tui::keybindings::TuiAction::ScrollDown, key)
        {
            app.chat.scroll = app.chat.scroll.saturating_sub(1);
            return Ok(());
        }
        if app
            .keybindings
            .matches(crate::tui::keybindings::TuiAction::PageUp, key)
        {
            app.chat.scroll = app.chat.scroll.saturating_add(15);
            return Ok(());
        }
        if app
            .keybindings
            .matches(crate::tui::keybindings::TuiAction::PageDown, key)
        {
            app.chat.scroll = app.chat.scroll.saturating_sub(15);
            return Ok(());
        }

        let mut written = false;
        let mut written_pid = None;

        // 1. Try to write to active persistent session stdin
        if let Ok(session_id_guard) = crate::tui::ACTIVE_PERSISTENT_SESSION_ID.lock()
            && let Some(ref session_id) = *session_id_guard
            && let Some(registry_mutex) = crate::tui::PERSISTENT_SESSIONS.get()
            && let Ok(mut registry_guard) = registry_mutex.lock()
            && let Some(session) = registry_guard.get_mut(session_id)
        {
            use std::io::Write;
            let data = match key.code {
                KeyCode::Char(c) => Some(c.to_string()),
                KeyCode::Enter => Some("\n".to_owned()),
                KeyCode::Backspace => Some("\x08".to_owned()),
                _ => None,
            };
            if let Some(s) = data {
                let _ = session.stdin.write_all(s.as_bytes());
                let _ = session.stdin.flush();
                written = true;
                written_pid = Some(session.pid);
            }
        }

        // 2. Try to write to non-persistent foreground process stdin
        if !written {
            let mut guard = crate::tui::RUNNING_PROCESS_STDIN.lock();
            if let Some(ref mut stdin) = guard.as_mut().ok().and_then(|g| g.as_mut()) {
                use std::io::Write;
                let data = match key.code {
                    KeyCode::Char(c) => Some(c.to_string()),
                    KeyCode::Enter => Some("\n".to_owned()),
                    KeyCode::Backspace => Some("\x08".to_owned()),
                    _ => None,
                };
                if let Some(s) = data {
                    let _ = stdin.write_all(s.as_bytes());
                    let _ = stdin.flush();
                    written = true;
                    if let Ok(pid_guard) = crate::tui::RUNNING_PROCESS_PID.lock() {
                        written_pid = *pid_guard;
                    }
                }
            }
        }

        if written {
            // Find the shell message line and truncate "\nRunning...\n" if it's there
            let mut found_msg = None;
            if let Some(wp) = written_pid {
                found_msg = app
                    .chat
                    .messages
                    .iter_mut()
                    .rev()
                    .find(|m| m.is_shell && m.shell_pid == Some(wp));
            }
            if found_msg.is_none() {
                found_msg = app.chat.messages.iter_mut().rev().find(|m| m.is_shell);
            }
            if let Some(msg) = found_msg
                && msg.text.ends_with("\nRunning...\n")
            {
                msg.text.truncate(msg.text.len() - 11);
                *msg.cached_wrapped.borrow_mut() = None;
            }
        }

        return Ok(());
    }

    if app
        .keybindings
        .matches(crate::tui::keybindings::TuiAction::Quit, key)
    {
        if app.pending.is_some() {
            let mut pid = None;
            if let Ok(mut guard) = crate::tui::RUNNING_PROCESS_PID.lock() {
                pid = guard.take();
            }
            if let Some(pid) = pid {
                #[cfg(unix)]
                {
                    let _ = std::process::Command::new("kill")
                        .arg("-9")
                        .arg(format!("-{}", pid))
                        .status();
                }
                #[cfg(not(unix))]
                {
                    let _ = std::process::Command::new("taskkill")
                        .arg("/F")
                        .arg("/PID")
                        .arg(pid.to_string())
                        .status();
                }
            }
            app.cancel_generation();
            app.status = "Aborted by user".to_owned();
            return Ok(());
        } else {
            app.should_quit = true;
            return Ok(());
        }
    }

    if app
        .keybindings
        .matches(crate::tui::keybindings::TuiAction::Cancel, key)
    {
        let mut pid = None;
        if let Ok(mut guard) = crate::tui::RUNNING_PROCESS_PID.lock() {
            pid = guard.take();
        }
        if let Some(pid) = pid {
            #[cfg(unix)]
            {
                let _ = std::process::Command::new("kill")
                    .arg("-9")
                    .arg(format!("-{}", pid))
                    .status();
            }
            #[cfg(not(unix))]
            {
                let _ = std::process::Command::new("taskkill")
                    .arg("/F")
                    .arg("/PID")
                    .arg(pid.to_string())
                    .status();
            }
        }
        app.cancel_generation();
        app.status = "Stopped".to_owned();
        return Ok(());
    }

    if app
        .keybindings
        .matches(crate::tui::keybindings::TuiAction::ToggleSetup, key)
    {
        app.open_setup();
        return Ok(());
    }

    if app
        .keybindings
        .matches(crate::tui::keybindings::TuiAction::ToggleModels, key)
    {
        if let Some(config) = app.begin_load_chat_models() {
            spawn_models_worker(config, sender.clone());
        }
        return Ok(());
    }

    if app
        .keybindings
        .matches(crate::tui::keybindings::TuiAction::ToggleSessions, key)
    {
        app.open_sessions();
        return Ok(());
    }

    if app
        .keybindings
        .matches(crate::tui::keybindings::TuiAction::Submit, key)
    {
        if let Some(action) = app.submit_chat_input() {
            match action {
                SubmitAction::Generate(request) => {
                    spawn_generation_worker(
                        request.config,
                        request.history,
                        request.cancel_token,
                        request.generation_id,
                        sender.clone(),
                    );
                }
                SubmitAction::LoadModels(config) => {
                    spawn_models_worker(config, sender.clone());
                }
                SubmitAction::ExecuteFunction { name, args, config } => {
                    handle_function_action(
                        crate::app::FunctionAction::Execute { name, args, config },
                        sender,
                    );
                }
            }
        }
        return Ok(());
    }

    if app
        .keybindings
        .matches(crate::tui::keybindings::TuiAction::ScrollUp, key)
    {
        if app.chat.input.contains('\n') {
            let old_cursor = app.chat.cursor;
            app.chat.move_cursor_up();
            if app.chat.cursor == old_cursor {
                app.chat.scroll = app.chat.scroll.saturating_add(1);
            }
        } else {
            app.chat.scroll = app.chat.scroll.saturating_add(1);
        }
        return Ok(());
    }

    if app
        .keybindings
        .matches(crate::tui::keybindings::TuiAction::ScrollDown, key)
    {
        if app.chat.input.contains('\n') {
            let old_cursor = app.chat.cursor;
            app.chat.move_cursor_down();
            if app.chat.cursor == old_cursor {
                app.chat.scroll = app.chat.scroll.saturating_sub(1);
            }
        } else {
            app.chat.scroll = app.chat.scroll.saturating_sub(1);
        }
        return Ok(());
    }

    if app
        .keybindings
        .matches(crate::tui::keybindings::TuiAction::PageUp, key)
    {
        app.chat.scroll = app.chat.scroll.saturating_add(15);
        return Ok(());
    }

    if app
        .keybindings
        .matches(crate::tui::keybindings::TuiAction::PageDown, key)
    {
        app.chat.scroll = app.chat.scroll.saturating_sub(15);
        return Ok(());
    }

    if app
        .keybindings
        .matches(crate::tui::keybindings::TuiAction::HistoryUp, key)
    {
        app.chat.navigate_history_up();
        return Ok(());
    }

    if app
        .keybindings
        .matches(crate::tui::keybindings::TuiAction::HistoryDown, key)
    {
        app.chat.navigate_history_down();
        return Ok(());
    }

    match (key.code, key.modifiers) {
        (KeyCode::Char('z'), KeyModifiers::CONTROL) => {
            app.chat.undo();
        }
        (KeyCode::Char('r'), KeyModifiers::CONTROL) => {
            app.chat.redo();
        }
        (KeyCode::Char('k'), KeyModifiers::CONTROL) => {
            let text = app.chat.input.clone();
            if !text.is_empty() {
                if copy_to_clipboard(&text).is_ok() {
                    app.status = "Copied input to clipboard".to_owned();
                }
                app.chat.save_history();
                app.chat.input.clear();
                app.chat.cursor = 0;
                app.chat.input_scroll = 0;
            }
        }
        (KeyCode::Char('y'), KeyModifiers::CONTROL) => {
            if let Ok(text) = read_from_clipboard() {
                app.chat.insert_text(&text);
            }
        }
        (KeyCode::Char('l'), KeyModifiers::CONTROL) => {
            let mut last_response = None;
            for msg in app.chat.messages.iter().rev() {
                if msg.author == "Darwin" && !msg.is_tool && !msg.is_shell && !msg.pending {
                    let mut text = msg.text.trim();
                    if text.starts_with("(empty)") {
                        text = text["(empty)".len()..].trim();
                    }
                    let mut clean_text = text.to_owned();
                    if clean_text.starts_with("Thinking...") {
                        clean_text = clean_text["Thinking...".len()..].to_owned();
                    } else if clean_text.starts_with("Thinking:") {
                        if let Some(first_newline_idx) = clean_text.find('\n') {
                            clean_text = clean_text[first_newline_idx + 1..].to_owned();
                        } else {
                            clean_text = clean_text["Thinking:".len()..].to_owned();
                        }
                    } else if clean_text.starts_with("░ Thinking...") {
                        clean_text = clean_text["░ Thinking...".len()..].to_owned();
                    } else if clean_text.starts_with("░ Thinking:") {
                        if let Some(first_newline_idx) = clean_text.find('\n') {
                            clean_text = clean_text[first_newline_idx + 1..].to_owned();
                        } else {
                            clean_text = clean_text["░ Thinking:".len()..].to_owned();
                        }
                    }
                    let final_text = clean_text.trim().to_owned();
                    if !final_text.is_empty() {
                        last_response = Some(final_text);
                        break;
                    }
                }
            }
            if let Some(text) = last_response {
                if copy_to_clipboard(&text).is_ok() {
                    app.status = "Copied last response to clipboard".to_owned();
                }
            } else {
                app.status = "No assistant response to copy".to_owned();
            }
        }
        (KeyCode::Tab, _) => {
            let suggestions = app.command_suggestions();
            if !suggestions.is_empty() {
                app.accept_command_suggestion();
            } else {
                app.chat.shell_focused = !app.chat.shell_focused;
                for m in &mut app.chat.messages {
                    if m.is_shell {
                        *m.cached_wrapped.borrow_mut() = None;
                    }
                }
                if app.chat.shell_focused {
                    app.chat.scroll = 0; // Automatically scroll to the bottom to show the last shell block
                    app.status = "Shell/Messages focused. Press Tab to return, or Ctrl+C to abort running command.".to_owned();
                } else {
                    app.status = "Ready".to_owned();
                }
            }
        }
        (KeyCode::Enter, modifiers) if !modifiers.is_empty() => {
            app.chat.insert_char('\n');
        }
        (KeyCode::Backspace, _) => app.chat.remove_char(),
        (KeyCode::Delete, _) => app.chat.delete_char(),
        (KeyCode::Left, _) => app.chat.move_cursor_left(),
        (KeyCode::Right, _) => app.chat.move_cursor_right(),
        (KeyCode::Home, _) => app.chat.move_cursor_start(),
        (KeyCode::End, _) => app.chat.move_cursor_end(),
        (KeyCode::Char(value), modifiers)
            if !modifiers.contains(KeyModifiers::CONTROL)
                && !modifiers.contains(KeyModifiers::ALT) =>
        {
            app.chat.insert_char(value);
        }
        _ => {}
    }

    Ok(())
}