User decision 2026-11-19 (mixed way). agent-desktop only presses keys in the window in front, so the app now picks one way before any key is sent: - behind: one key without modifiers that types or moves is posted to the window's one shown text control (Edit, RichEdit, RichEditD2DPT, Scintilla); the person's screen and focus stay. Windows does not tell a background thread's focused control (win-ci VM: GetFocus is null even attached), so only windows with exactly one text control get keys behind. - in front for a moment: combinations, other keys and every other window; the window that was in front is brought back after (also after a failed press). A window already in front gets the keys there. - never in front while game mode is on or the window in front is full screen. - never both ways, so a key is never pressed twice. Specs: admin.spec.md "PC control" (Keys), pc-features.md, pc_control.spec.md. Tests: six new fake-desktop tests in pc.rs; tests/pc_keys_windows.rs on a real desktop (win-ci VM: letters behind Notepad with Character Map kept in front, ctrl+a in front and back, the classic Calculator in front and back). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
131 lines
6.6 KiB
Rust
131 lines
6.6 KiB
Rust
//! PC control's keys on a real Windows desktop (admin.spec.md, "PC control", "Keys"): with another
|
|
//! window in front, letters and Enter reach Notepad behind it and the window in front stays; a
|
|
//! combination and the Calculator's keys go in front for a moment and the window in front comes
|
|
//! back. Runs only on Windows with `JARVIS_TEST_PC_KEYS=1` and agent-desktop at
|
|
//! `JARVIS_AGENT_DESKTOP` (it opens Notepad, Character Map and the Calculator); elsewhere it skips.
|
|
|
|
use std::path::PathBuf;
|
|
use std::time::{Duration, Instant};
|
|
|
|
use jarvis_app::pc::{Cli, Desktop, Pc, Stop};
|
|
use jarvis_app::settings::{Level, Settings};
|
|
use jarvis_app::worker_client::PcAction;
|
|
use serde_json::{json, Value};
|
|
|
|
const USER: &str = "42";
|
|
|
|
fn act(pc: &Pc, action: &str, extra: Value) -> Value {
|
|
let mut v = json!({"id": "k1", "action": action, "user": USER, "via": "voice"});
|
|
v.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
|
let a: PcAction = serde_json::from_value(v).unwrap();
|
|
let t = Instant::now();
|
|
let o = pc.act(&a);
|
|
println!("{action} {extra}: {} in {} ms", o.code, t.elapsed().as_millis());
|
|
o.reply
|
|
}
|
|
|
|
/// Every element's name and value of a reading, joined.
|
|
fn text(reply: &Value) -> String {
|
|
reply["item"]["elements"].as_array().into_iter().flatten()
|
|
.map(|e| format!("{} {}", e["name"].as_str().unwrap_or(""), e["value"].as_str().unwrap_or(""))).collect::<Vec<_>>().join(" | ")
|
|
}
|
|
|
|
/// Closed however the test ends (by name too: a program may hand over to another process).
|
|
struct Closed(Vec<String>, Vec<std::process::Child>);
|
|
|
|
impl Drop for Closed {
|
|
fn drop(&mut self) {
|
|
for p in &self.0 {
|
|
let _ = std::process::Command::new("taskkill").args(["/f", "/im", p]).output();
|
|
}
|
|
for c in &mut self.1 {
|
|
let _ = c.kill();
|
|
let _ = c.wait();
|
|
}
|
|
}
|
|
}
|
|
|
|
fn wait_window(pc: &Pc, f: impl Fn(&Value) -> bool) -> String {
|
|
let until = Instant::now() + Duration::from_secs(15);
|
|
loop {
|
|
let list = act(pc, "windows", json!({}));
|
|
if let Some(w) = list["item"]["windows"].as_array().into_iter().flatten().find(|w| f(w)) {
|
|
return w["id"].as_str().unwrap().to_owned();
|
|
}
|
|
assert!(Instant::now() < until, "the window did not show");
|
|
std::thread::sleep(Duration::from_millis(500));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn keys_go_behind_or_in_front_for_a_moment_and_the_window_in_front_stays() {
|
|
if std::env::var("JARVIS_TEST_PC_KEYS").is_err() {
|
|
eprintln!("skipped: set JARVIS_TEST_PC_KEYS=1 and JARVIS_AGENT_DESKTOP");
|
|
return;
|
|
}
|
|
let exe = PathBuf::from(std::env::var("JARVIS_AGENT_DESKTOP").expect("JARVIS_AGENT_DESKTOP"));
|
|
let data = std::env::temp_dir().join(format!("jarvis-pc-keys-{}", std::process::id()));
|
|
std::fs::create_dir_all(&data).unwrap();
|
|
let mut s = Settings::default();
|
|
s.pc_control.allowed_users = vec![USER.parse().unwrap()];
|
|
s.pc_control.type_text = Level::Auto;
|
|
s.pc_control.run = Level::Auto;
|
|
let stop: &'static Stop = Box::leak(Box::new(Stop::new()));
|
|
let desktop = Cli::new(&exe, &data);
|
|
let probe = Cli::new(&exe, &data.join("probe"));
|
|
let pc = Pc::new(s, Box::new(desktop), stop, Box::new(|| None));
|
|
// Only programs this test starts are closed: none of them may run before it.
|
|
let ours = ["notepad.exe", "charmap.exe", "calculatorapp.exe", "win32calc.exe"];
|
|
let running: Vec<String> = probe.processes().into_iter().filter(|p| ours.contains(&p.as_str())).collect();
|
|
assert!(running.is_empty(), "close these first: {running:?}");
|
|
let mut closed = Closed(ours.iter().map(|p| p.to_string()).collect(), vec![]);
|
|
|
|
let file = data.join("pckeys.txt");
|
|
std::fs::write(&file, "").unwrap();
|
|
closed.1.push(std::process::Command::new("notepad.exe").arg(&file).spawn().unwrap());
|
|
let notepad = wait_window(&pc, |w| w["title"].as_str().is_some_and(|t| t.contains("pckeys")));
|
|
closed.1.push(std::process::Command::new("charmap.exe").spawn().unwrap());
|
|
let front = wait_window(&pc, |w| w["program"] == "charmap");
|
|
std::thread::sleep(Duration::from_secs(1));
|
|
let _ = probe.run(&["focus-window".into(), "--window-id".into(), front.clone()], None, stop);
|
|
println!("notepad {notepad}; in front {front}: {:?}", probe.foreground());
|
|
assert_eq!(probe.foreground().as_deref(), Some(front.as_str()), "Character Map is in front");
|
|
assert!(probe.takes_keys_behind(¬epad), "Notepad takes keys behind");
|
|
|
|
// Letters and Enter behind Notepad: they arrive and the window in front stays.
|
|
for k in ["h", "i", "enter", "o", "k"] {
|
|
let r = act(&pc, "keys", json!({"window": notepad, "keys": k}));
|
|
assert_eq!(r["ok"], true, "{k}: {r}");
|
|
assert_eq!(probe.foreground().as_deref(), Some(front.as_str()), "{k}: the window in front stays");
|
|
}
|
|
let read = act(&pc, "read", json!({"window": notepad}));
|
|
println!("notepad after behind: {}", text(&read).chars().take(300).collect::<String>());
|
|
assert!(text(&read).contains("hi") && text(&read).contains("ok"), "the letters reached Notepad behind");
|
|
|
|
// A combination goes in front for a moment, then the window in front is back.
|
|
let r = act(&pc, "keys", json!({"window": notepad, "keys": "ctrl+a"}));
|
|
assert_eq!(r["ok"], true, "ctrl+a: {r}");
|
|
assert_eq!(probe.foreground().as_deref(), Some(front.as_str()), "ctrl+a: the window in front is back");
|
|
let r = act(&pc, "keys", json!({"window": notepad, "keys": "x"}));
|
|
assert_eq!(r["ok"], true, "x: {r}");
|
|
let after = text(&act(&pc, "read", json!({"window": notepad})));
|
|
println!("notepad after ctrl+a, x: {}", after.chars().take(300).collect::<String>());
|
|
assert!(!after.contains("hi"), "ctrl+a selected the text and x replaced it");
|
|
|
|
// The Calculator: in front for a moment when it does not take keys behind (the Store app).
|
|
let calc = act(&pc, "run", json!({"program": "calc"}));
|
|
let calc = calc["item"]["window"]["id"].as_str().expect("the Calculator's window").to_owned();
|
|
std::thread::sleep(Duration::from_secs(1));
|
|
let _ = probe.run(&["focus-window".into(), "--window-id".into(), front.clone()], None, stop);
|
|
println!("calculator {calc}; takes keys behind: {}", probe.takes_keys_behind(&calc));
|
|
for k in ["escape", "1", "2"] {
|
|
let r = act(&pc, "keys", json!({"window": calc, "keys": k}));
|
|
assert_eq!(r["ok"], true, "{k}: {r}");
|
|
assert_eq!(probe.foreground().as_deref(), Some(front.as_str()), "{k}: the window in front stays or is back");
|
|
}
|
|
let shown = text(&act(&pc, "read", json!({"window": calc})));
|
|
println!("calculator after 1 2: {}", shown.chars().take(300).collect::<String>());
|
|
assert!(shown.contains("12"), "the Calculator shows 12");
|
|
let _ = std::fs::remove_dir_all(&data);
|
|
}
|