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
|
use std::time::Duration;
use bytes::Bytes;
use crate::api::schema::{
AgentPromptParams, AgentRenameParams, AgentSendKeysParams, AgentStartParams, AgentTarget,
PaneReadResult, ResponseResult,
};
use crate::app::App;
use super::responses::{encode_error, encode_error_body, encode_success};
const AGENT_PROMPT_SUBMIT_DELAY: Duration = Duration::from_millis(300);
// Codex's Windows input reader does not surface bracketed paste. It detects the prompt as a
// "paste burst" and, while that burst is buffered, rewrites a following Enter into a newline
// instead of submitting. The burst only flushes after an idle timeout, so any size-based delay is
// a timing guess that fails when ConPTY delivery lags it. Codex flushes a buffered burst
// synchronously when it receives a non-character key, so appending one after the paste gives the
// submission a deterministic paste boundary regardless of prompt size or delivery speed.
#[cfg(windows)]
fn append_codex_paste_boundary(runtime: &crate::terminal::TerminalRuntime, text: &mut Vec<u8>) {
let keys = match crate::app::api_helpers::encode_api_keys(runtime, &["right".to_string()]) {
Ok(keys) => keys,
Err(key) => {
tracing::warn!(key = %key, "failed to encode Codex paste boundary key");
return;
}
};
if let Some(key) = keys.into_iter().find(|bytes| !bytes.is_empty()) {
text.extend_from_slice(&key);
}
}
impl App {
pub(super) fn handle_agent_list(&mut self, id: String) -> String {
encode_success(
id,
ResponseResult::AgentList {
agents: self.collect_agent_infos(),
},
)
}
pub(super) fn handle_agent_get(&mut self, id: String, target: AgentTarget) -> String {
self.reconcile_managed_agent_target(&target.target);
let agent = match self.agent_info_for_target(&target.target) {
Ok(agent) => agent,
Err(err) => return encode_error_body(id, self.agent_target_error_body(err)),
};
encode_success(id, ResponseResult::AgentInfo { agent })
}
pub(super) fn handle_agent_focus(&mut self, id: String, target: AgentTarget) -> String {
let agent = match self.focus_agent_target(&target.target) {
Ok(agent) => agent,
Err(err) => return encode_error_body(id, self.agent_target_error_body(err)),
};
encode_success(id, ResponseResult::AgentInfo { agent })
}
pub(super) fn handle_agent_rename(&mut self, id: String, params: AgentRenameParams) -> String {
let agent = match self.rename_agent_target(¶ms.target, params.name) {
Ok(agent) => agent,
Err(err) => return encode_error_body(id, self.agent_rename_error_body(err)),
};
encode_success(id, ResponseResult::AgentInfo { agent })
}
pub(super) fn handle_agent_start(&mut self, id: String, params: AgentStartParams) -> String {
let (agent, argv) = match self.start_agent(params) {
Ok(started) => started,
Err(err) => return encode_error_body(id, self.agent_start_error_body(err)),
};
encode_success(id, ResponseResult::AgentStarted { agent, argv })
}
pub(crate) fn handle_deferred_agent_api_request(
&mut self,
request: crate::api::schema::Request,
respond_to: std::sync::mpsc::Sender<String>,
) -> bool {
let crate::api::schema::Method::AgentPrompt(params) = request.method else {
return false;
};
match self.queue_agent_prompt(request.id, params) {
Ok((id, agent, completion)) => {
std::thread::spawn(move || {
let response = match completion.recv() {
Ok(Ok(())) => encode_success(id, ResponseResult::AgentPrompted { agent }),
Ok(Err(err)) if err.kind() == std::io::ErrorKind::TimedOut => {
encode_error(id, "timeout", err.to_string())
}
Ok(Err(err)) => encode_error(id, "agent_prompt_failed", err.to_string()),
Err(_) => encode_error(id, "agent_prompt_failed", "pty actor closed"),
};
let _ = respond_to.send(response);
});
}
Err(response) => {
let _ = respond_to.send(response);
}
}
true
}
fn queue_agent_prompt(
&mut self,
id: String,
params: AgentPromptParams,
) -> Result<
(
String,
crate::api::schema::AgentInfo,
std::sync::mpsc::Receiver<std::io::Result<()>>,
),
String,
> {
if params.text.is_empty() {
return Err(encode_error(
id,
"empty_agent_prompt",
"agent prompt must not be empty",
));
}
let resolved = match self.resolve_agent_target(¶ms.target) {
Ok(resolved) => resolved,
Err(err) => return Err(encode_error_body(id, self.agent_target_error_body(err))),
};
let Some(terminal_id) = self
.state
.workspaces
.get(resolved.ws_idx)
.and_then(|workspace| workspace.terminal_id(resolved.pane_id))
.cloned()
else {
return Err(agent_not_found(id, ¶ms.target));
};
let Some(terminal) = self.state.terminals.get(&terminal_id) else {
return Err(agent_not_found(id, ¶ms.target));
};
if terminal.state == crate::detect::AgentState::Blocked {
return Err(encode_error(
id,
"agent_blocked",
format!(
"agent {} is blocked and requires interactive input",
params.target
),
));
}
let Some(expected_agent) = terminal.effective_known_agent() else {
return Err(agent_not_ready(id, ¶ms.target));
};
if terminal.managed_agent_launch_pending() {
return Err(agent_not_ready(id, ¶ms.target));
}
let Some(runtime) = self.lookup_runtime_sender(resolved.ws_idx, resolved.pane_id) else {
return Err(agent_not_found(id, ¶ms.target));
};
if !super::super::agents::runtime_hosts_agent(runtime, expected_agent) {
return Err(encode_error(
id,
"agent_not_ready",
format!(
"agent {} is no longer the pane foreground process",
params.target
),
));
}
#[cfg(windows)]
let submit_deadline = params
.wait
.as_ref()
.and_then(|wait| wait.submission_deadline);
#[cfg(not(windows))]
let submit_deadline = None;
if expected_agent == crate::detect::Agent::GithubCopilot {
// Copilot ignores synthetic Enter after focus loss until it receives focus gained.
let focus = match crate::ghostty::encode_focus(crate::ghostty::FocusEvent::Gained) {
Ok(focus) => focus,
Err(err) => {
return Err(encode_error(id, "agent_prompt_failed", err.to_string()));
}
};
if let Err(err) = runtime.try_send_bytes(Bytes::from(focus)) {
return Err(encode_error(id, "agent_prompt_failed", err.to_string()));
}
}
let (text, enter) =
crate::app::api_helpers::encode_api_submission_parts(runtime, ¶ms.text);
#[cfg(windows)]
let text = if expected_agent == crate::detect::Agent::Codex {
let mut text = text;
append_codex_paste_boundary(runtime, &mut text);
text
} else {
text
};
let Some(agent) = self.agent_info(resolved.ws_idx, resolved.pane_id) else {
return Err(agent_not_found(id, ¶ms.target));
};
let completion = runtime
.queue_user_input_submission(
Bytes::from(text),
Bytes::from(enter),
AGENT_PROMPT_SUBMIT_DELAY,
submit_deadline,
)
.map_err(|err| encode_error(id.clone(), "agent_prompt_failed", err.to_string()))?;
Ok((id, agent, completion))
}
pub(super) fn handle_agent_read(
&mut self,
id: String,
params: crate::api::schema::AgentReadParams,
) -> String {
let resolved = match self.resolve_agent_target(¶ms.target) {
Ok(resolved) => resolved,
Err(err) => return encode_error_body(id, self.agent_target_error_body(err)),
};
let Some((pane, workspace_id)) = self.lookup_runtime(resolved.ws_idx, resolved.pane_id)
else {
return agent_not_found(id, ¶ms.target);
};
let snapshot = crate::app::api_helpers::read_terminal_snapshot(
pane,
params.source,
params.format,
params.lines,
);
encode_success(
id,
ResponseResult::PaneRead {
read: PaneReadResult {
pane_id: self
.public_pane_id(resolved.ws_idx, resolved.pane_id)
.unwrap_or_else(|| params.target.clone()),
workspace_id,
tab_id: self
.public_tab_id(resolved.ws_idx, resolved.tab_idx)
.unwrap(),
source: params.source,
format: params.format,
text: snapshot.text,
revision: 0,
truncated: snapshot.truncated,
},
},
)
}
pub(super) fn handle_agent_explain(&mut self, id: String, target: AgentTarget) -> String {
let resolved = match self.resolve_agent_target(&target.target) {
Ok(resolved) => resolved,
Err(err) => return encode_error_body(id, self.agent_target_error_body(err)),
};
let Some((pane, _workspace_id)) = self.lookup_runtime(resolved.ws_idx, resolved.pane_id)
else {
return agent_not_found(id, &target.target);
};
let Some(terminal_id) = self
.state
.workspaces
.get(resolved.ws_idx)
.and_then(|workspace| workspace.terminal_id(resolved.pane_id))
else {
return agent_not_found(id, &target.target);
};
let Some(terminal) = self.state.terminals.get(terminal_id) else {
return agent_not_found(id, &target.target);
};
if terminal.full_lifecycle_hook_authority_active() {
let explain = serde_json::json!({
"agent": terminal.effective_agent_label().unwrap_or("unknown"),
"state": crate::detect::manifest::agent_state_label(terminal.state),
"manifest_source": null,
"manifest_version": null,
"cached_remote_version": null,
"local_override_shadowing_remote": false,
"remote_update_status": null,
"remote_update_error": null,
"matched_rule": null,
"visible_idle": false,
"visible_blocker": false,
"visible_working": false,
"screen_detection_skipped": true,
"screen_detection_skip_reason": "full_lifecycle_hook_authority",
"skip_state_update": false,
"skipped_update_reason": null,
"fallback_reason": null,
"warning": null,
"evaluated_rules": [],
});
return encode_success(id, ResponseResult::AgentExplain { explain });
}
let Some(agent) = terminal.effective_known_agent().or(terminal.detected_agent) else {
return encode_error(
id,
"agent_explain_unavailable",
format!(
"agent target {} does not have a detected agent label",
target.target
),
);
};
let screen = pane.detection_text();
let osc_title = pane.agent_osc_title();
let osc_progress = pane.agent_osc_progress();
let explain = crate::detect::manifest::explain_with_input(
agent,
crate::detect::manifest::DetectionInput {
screen: &screen,
osc_title: &osc_title,
osc_progress: &osc_progress,
},
);
let value = crate::detect::manifest::explain_to_json_value(&explain);
encode_success(id, ResponseResult::AgentExplain { explain: value })
}
pub(super) fn handle_agent_send_keys(
&mut self,
id: String,
params: AgentSendKeysParams,
) -> String {
let resolved = match self.resolve_agent_target(¶ms.target) {
Ok(resolved) => resolved,
Err(err) => return encode_error_body(id, self.agent_target_error_body(err)),
};
let Some(terminal_id) = self
.state
.workspaces
.get(resolved.ws_idx)
.and_then(|workspace| workspace.terminal_id(resolved.pane_id))
else {
return agent_not_found(id, ¶ms.target);
};
let Some(expected_agent) = self
.state
.terminals
.get(terminal_id)
.and_then(|terminal| terminal.effective_known_agent())
else {
return agent_not_ready(id, ¶ms.target);
};
let Some(runtime) = self.lookup_runtime_sender(resolved.ws_idx, resolved.pane_id) else {
return agent_not_found(id, ¶ms.target);
};
if !super::super::agents::runtime_hosts_agent(runtime, expected_agent) {
return agent_not_ready(id, ¶ms.target);
}
let encoded = match super::super::api_helpers::encode_api_keys(runtime, ¶ms.keys) {
Ok(encoded) => encoded,
Err(key) => {
return encode_error(id, "invalid_key", format!("unsupported key {key}"));
}
};
let bytes: Vec<u8> = encoded.into_iter().flatten().collect();
if let Err(err) = runtime.try_send_bytes(Bytes::from(bytes)) {
return encode_error(id, "agent_send_keys_failed", err.to_string());
}
encode_success(id, ResponseResult::Ok {})
}
}
fn agent_not_ready(id: String, target: &str) -> String {
encode_error(
id,
"agent_not_ready",
format!("agent {target} is not an active named agent"),
)
}
fn agent_not_found(id: String, target: &str) -> String {
encode_error(
id,
"agent_not_found",
format!("agent target {target} not found"),
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
api::schema::{AgentStatus, SuccessResponse},
app::Mode,
config::Config,
detect::{Agent, AgentState},
workspace::Workspace,
};
fn app_with_agent() -> App {
let (_api_tx, api_rx) = tokio::sync::mpsc::unbounded_channel();
let mut app = App::new(
&Config::default(),
crate::app::AppPolicy::TEST,
None,
api_rx,
crate::api::EventHub::default(),
);
app.state.workspaces = vec![Workspace::test_new("agent")];
app.state.ensure_test_terminals();
app.state.active = Some(0);
app.state.selected = 0;
app.state.mode = Mode::Terminal;
app
}
fn start_deferred_agent_prompt(
app: &mut App,
id: &str,
params: AgentPromptParams,
) -> std::sync::mpsc::Receiver<String> {
let (respond_to, response_rx) = std::sync::mpsc::channel();
assert!(app.handle_deferred_agent_api_request(
crate::api::schema::Request {
id: id.into(),
method: crate::api::schema::Method::AgentPrompt(params),
},
respond_to,
));
response_rx
}
fn run_deferred_agent_prompt(app: &mut App, id: &str, params: AgentPromptParams) -> String {
start_deferred_agent_prompt(app, id, params)
.recv_timeout(Duration::from_secs(1))
.expect("agent prompt responds after submission")
}
#[cfg(windows)]
#[tokio::test]
async fn windows_codex_prompt_flushes_paste_burst_before_enter() {
let mut app = app_with_agent();
let pane_id = app.state.workspaces[0].tabs[0].root_pane;
let terminal_id = app.state.workspaces[0].tabs[0].panes[&pane_id]
.attached_terminal_id
.clone();
let terminal = app.state.terminals.get_mut(&terminal_id).unwrap();
terminal.set_agent_name("reviewer".into());
terminal.set_detected_state(Some(Agent::Codex), AgentState::Idle);
let (runtime, mut rx) = crate::terminal::TerminalRuntime::test_with_channel(80, 24);
app.state.insert_test_runtime(pane_id, runtime);
let response = run_deferred_agent_prompt(
&mut app,
"req",
AgentPromptParams {
target: "reviewer".into(),
text: "A != B".into(),
wait: None,
},
);
let success: SuccessResponse = serde_json::from_str(&response).unwrap();
assert!(matches!(
success.result,
ResponseResult::AgentPrompted { .. }
));
// The non-character key must precede Enter so Codex commits the paste burst first.
assert_eq!(rx.try_recv().unwrap(), Bytes::from_static(b"A != B\x1b[C"));
assert_eq!(rx.try_recv().unwrap(), Bytes::from_static(b"\r"));
}
#[tokio::test]
async fn a_false_process_exit_makes_a_named_live_agent_unreachable_by_name() {
// Reproduces the registration loss reported on #3225 by rszrszrsz:
// a live agent pane with an assigned name stops resolving by that name
// while its process keeps running, and renaming is the only recovery.
let mut app = app_with_agent();
let pane_id = app.state.workspaces[0].tabs[0].root_pane;
let terminal_id = app.state.workspaces[0].tabs[0].panes[&pane_id]
.attached_terminal_id
.clone();
let observed_at = std::time::Instant::now();
let terminal = app.state.terminals.get_mut(&terminal_id).unwrap();
terminal.set_detected_state(Some(Agent::Pi), AgentState::Working);
terminal.set_agent_name("reviewer".into());
let found = app.handle_agent_get(
"req:before".into(),
AgentTarget {
target: "reviewer".into(),
},
);
assert!(
serde_json::from_str::<SuccessResponse>(&found).is_ok(),
"the assigned name must resolve while the agent is running: {found}"
);
// One process-exit observation, then the same agent is observed alive
// again on the next probe - the process never actually went away.
app.handle_internal_event(crate::events::AppEvent::StateChanged {
pane_id,
agent: Some(Agent::Pi),
state: AgentState::Idle,
visible_blocker: false,
visible_working: false,
process_exited: true,
observed_at,
});
app.handle_internal_event(crate::events::AppEvent::AgentProcessDetected {
pane_id,
agent: Agent::Pi,
observed_at: observed_at + std::time::Duration::from_secs(1),
});
let terminal = &app.state.terminals[&terminal_id];
assert_eq!(
terminal.detected_agent,
Some(Agent::Pi),
"the agent process is still there"
);
let after = app.handle_agent_get(
"req:after".into(),
AgentTarget {
target: "reviewer".into(),
},
);
assert!(
serde_json::from_str::<SuccessResponse>(&after).is_ok(),
"a live agent must stay reachable by its assigned name: {after}"
);
}
#[tokio::test]
async fn agent_prompt_sends_text_then_delays_enter() {
let mut app = app_with_agent();
let pane_id = app.state.workspaces[0].tabs[0].root_pane;
let terminal_id = app.state.workspaces[0].tabs[0].panes[&pane_id]
.attached_terminal_id
.clone();
let terminal = app.state.terminals.get_mut(&terminal_id).unwrap();
terminal.set_agent_name("reviewer".into());
terminal.set_detected_state(Some(Agent::OpenCode), AgentState::Working);
let (runtime, mut rx) =
crate::terminal::TerminalRuntime::test_with_channel_and_scrollback_bytes(
80, 24, 0, b"", 2,
);
runtime.test_process_pty_bytes(b"\x1b[?2004h");
app.state.insert_test_runtime(pane_id, runtime);
let public_pane_id = app.public_pane_id(0, pane_id).unwrap();
let bracketed_started = std::time::Instant::now();
let response_rx = start_deferred_agent_prompt(
&mut app,
"req",
AgentPromptParams {
target: public_pane_id,
text: "A != B".into(),
wait: None,
},
);
assert!(response_rx.try_recv().is_err());
let response = response_rx
.recv_timeout(Duration::from_secs(1))
.expect("agent prompt responds after submission");
let success: SuccessResponse = serde_json::from_str(&response).unwrap();
let ResponseResult::AgentPrompted { agent, .. } = success.result else {
panic!("expected prompted response");
};
assert_eq!(agent.name.as_deref(), Some("reviewer"));
assert_eq!(
rx.try_recv().unwrap(),
Bytes::from_static(b"\x1b[200~A != B\x1b[201~")
);
assert_eq!(rx.try_recv().unwrap(), Bytes::from_static(b"\r"));
assert!(bracketed_started.elapsed() >= AGENT_PROMPT_SUBMIT_DELAY);
app.lookup_runtime_sender(0, pane_id)
.unwrap()
.test_process_pty_bytes(b"\x1b[?2004l");
let raw_started = std::time::Instant::now();
let raw = run_deferred_agent_prompt(
&mut app,
"req-raw",
AgentPromptParams {
target: "reviewer".into(),
text: "A != B".into(),
wait: None,
},
);
let raw: SuccessResponse = serde_json::from_str(&raw).unwrap();
assert!(matches!(raw.result, ResponseResult::AgentPrompted { .. }));
assert_eq!(rx.try_recv().unwrap(), Bytes::from_static(b"A != B"));
assert_eq!(rx.try_recv().unwrap(), Bytes::from_static(b"\r"));
assert!(raw_started.elapsed() >= AGENT_PROMPT_SUBMIT_DELAY);
let rejected = run_deferred_agent_prompt(
&mut app,
"req-label",
AgentPromptParams {
target: "opencode".into(),
text: "wrong target".into(),
wait: None,
},
);
let error: crate::api::schema::ErrorResponse = serde_json::from_str(&rejected).unwrap();
assert_eq!(error.error.code, "agent_not_found");
assert!(rx.try_recv().is_err());
}
#[tokio::test]
async fn agent_prompt_rejects_blocked_agent_without_writing() {
let mut app = app_with_agent();
let pane_id = app.state.workspaces[0].tabs[0].root_pane;
let terminal_id = app.state.workspaces[0].tabs[0].panes[&pane_id]
.attached_terminal_id
.clone();
let terminal = app.state.terminals.get_mut(&terminal_id).unwrap();
terminal.set_agent_name("reviewer".into());
terminal.set_detected_state(Some(Agent::GithubCopilot), AgentState::Blocked);
let (runtime, mut rx) = crate::terminal::TerminalRuntime::test_with_channel(80, 24);
app.state.insert_test_runtime(pane_id, runtime);
let response = run_deferred_agent_prompt(
&mut app,
"req",
AgentPromptParams {
target: "reviewer".into(),
text: "unrelated prompt".into(),
wait: None,
},
);
let error: crate::api::schema::ErrorResponse = serde_json::from_str(&response).unwrap();
assert_eq!(error.error.code, "agent_blocked");
assert!(
tokio::time::timeout(
AGENT_PROMPT_SUBMIT_DELAY + Duration::from_millis(100),
rx.recv()
)
.await
.is_err(),
"blocked prompt wrote or scheduled terminal input"
);
}
#[tokio::test]
async fn agent_prompt_focuses_copilot_before_submitting() {
let mut app = app_with_agent();
let pane_id = app.state.workspaces[0].tabs[0].root_pane;
let terminal_id = app.state.workspaces[0].tabs[0].panes[&pane_id]
.attached_terminal_id
.clone();
let terminal = app.state.terminals.get_mut(&terminal_id).unwrap();
terminal.set_agent_name("reviewer".into());
terminal.set_detected_state(Some(Agent::GithubCopilot), AgentState::Idle);
let (runtime, mut rx) =
crate::terminal::TerminalRuntime::test_with_channel_and_scrollback_bytes(
80, 24, 0, b"", 3,
);
runtime.test_process_pty_bytes(b"\x1b[?2004h");
app.state.insert_test_runtime(pane_id, runtime);
let response = run_deferred_agent_prompt(
&mut app,
"req",
AgentPromptParams {
target: "reviewer".into(),
text: "A != B".into(),
wait: None,
},
);
let success: SuccessResponse = serde_json::from_str(&response).unwrap();
assert!(matches!(
success.result,
ResponseResult::AgentPrompted { .. }
));
assert_eq!(rx.try_recv().unwrap(), Bytes::from_static(b"\x1b[I"));
assert_eq!(
rx.try_recv().unwrap(),
Bytes::from_static(b"\x1b[200~A != B\x1b[201~")
);
assert_eq!(rx.try_recv().unwrap(), Bytes::from_static(b"\r"));
}
#[tokio::test]
async fn agent_send_keys_validates_every_key_before_writing() {
let mut app = app_with_agent();
let pane_id = app.state.workspaces[0].tabs[0].root_pane;
let terminal_id = app.state.workspaces[0].tabs[0].panes[&pane_id]
.attached_terminal_id
.clone();
let terminal = app.state.terminals.get_mut(&terminal_id).unwrap();
terminal.set_agent_name("reviewer".into());
terminal.set_detected_state(Some(Agent::Pi), AgentState::Idle);
let (runtime, mut rx) = crate::terminal::TerminalRuntime::test_with_channel(80, 24);
app.state.insert_test_runtime(pane_id, runtime);
let rejected = app.handle_agent_send_keys(
"req-invalid".into(),
AgentSendKeysParams {
target: "reviewer".into(),
keys: vec!["enter".into(), "not-a-key".into()],
},
);
let error: crate::api::schema::ErrorResponse = serde_json::from_str(&rejected).unwrap();
assert_eq!(error.error.code, "invalid_key");
assert!(rx.try_recv().is_err());
let sent = app.handle_agent_send_keys(
"req-valid".into(),
AgentSendKeysParams {
target: "reviewer".into(),
keys: vec!["up".into(), "enter".into()],
},
);
let success: SuccessResponse = serde_json::from_str(&sent).unwrap();
assert!(matches!(success.result, ResponseResult::Ok {}));
assert_eq!(rx.try_recv().unwrap(), Bytes::from_static(b"\x1b[A\r"));
assert!(rx.try_recv().is_err());
}
#[tokio::test]
async fn agent_prompt_rejects_managed_agent_while_startup_is_pending() {
let mut app = app_with_agent();
let pane_id = app.state.workspaces[0].tabs[0].root_pane;
let terminal_id = app.state.workspaces[0].tabs[0].panes[&pane_id]
.attached_terminal_id
.clone();
let terminal = app.state.terminals.get_mut(&terminal_id).unwrap();
let now = std::time::Instant::now();
terminal.begin_managed_agent(
"reviewer".into(),
Agent::OpenCode,
now,
std::time::Duration::from_secs(3),
std::time::Duration::from_secs(10),
);
terminal.set_detected_state(Some(Agent::OpenCode), AgentState::Idle);
let (runtime, mut rx) = crate::terminal::TerminalRuntime::test_with_channel(80, 24);
app.state.insert_test_runtime(pane_id, runtime);
let response = run_deferred_agent_prompt(
&mut app,
"req-pending",
AgentPromptParams {
target: "reviewer".into(),
text: "A != B".into(),
wait: None,
},
);
let error: crate::api::schema::ErrorResponse = serde_json::from_str(&response).unwrap();
assert_eq!(error.error.code, "agent_not_ready");
assert!(rx.try_recv().is_err());
}
#[test]
fn agent_focus_marks_already_focused_done_agent_seen() {
let mut app = app_with_agent();
app.state.outer_terminal_focus = Some(false);
let pane_id = app.state.workspaces[0].tabs[0].root_pane;
let terminal_id = app.state.workspaces[0].tabs[0].panes[&pane_id]
.attached_terminal_id
.clone();
app.state
.terminals
.get_mut(&terminal_id)
.unwrap()
.set_detected_state(Some(Agent::Pi), AgentState::Idle);
app.state.workspaces[0].tabs[0]
.panes
.get_mut(&pane_id)
.unwrap()
.seen = false;
app.state.workspaces[0].tabs[0].layout.focus_pane(pane_id);
let response = app.handle_agent_focus(
"req".into(),
AgentTarget {
target: app.public_pane_id(0, pane_id).unwrap(),
},
);
let success: SuccessResponse = serde_json::from_str(&response).unwrap();
let ResponseResult::AgentInfo { agent } = success.result else {
panic!("expected agent info response");
};
assert_eq!(agent.agent_status, AgentStatus::Idle);
}
#[test]
fn agent_rename_does_not_replace_the_pane_label() {
let mut app = app_with_agent();
let pane_id = app.state.workspaces[0].tabs[0].root_pane;
let terminal_id = app.state.workspaces[0].tabs[0].panes[&pane_id]
.attached_terminal_id
.clone();
let terminal = app.state.terminals.get_mut(&terminal_id).unwrap();
terminal.set_manual_label("shell-pane".into());
terminal.set_detected_state(Some(Agent::Pi), AgentState::Idle);
let target = app.public_pane_id(0, pane_id).unwrap();
for name in [Some("reviewer".to_string()), None] {
let response = app.handle_agent_rename(
"req".into(),
AgentRenameParams {
target: target.clone(),
name,
},
);
let success: SuccessResponse = serde_json::from_str(&response).unwrap();
assert!(matches!(success.result, ResponseResult::AgentInfo { .. }));
assert_eq!(
app.state.terminals[&terminal_id].manual_label.as_deref(),
Some("shell-pane")
);
}
}
}
|