diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index 48d5942..be7e4b8 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -289,10 +289,22 @@ the browser runs headless with a note. points the driver at it (`HKLM\SOFTWARE\MikeTheTech\VirtualDisplayDriver` `VDDPATH`), creates the device (`Root\MttVDD`, display class) and installs the driver; Windows then asks once whether to install software from the SignPath Foundation. The new monitor is taken off the desktop at once. + A failed install, also the person answering no to that question ("취소했습니다"), undoes what + that attempt made (the device it created, and the registry value and settings folder when the + driver was not ours before), so nothing looks installed and the next attempt starts clean. The + status counts as installed only when the driver is ours and its monitor is there, so a device left + without its driver can be installed again. Devices are found by the hardware ID among all root + devices, whatever their class (a device whose driver was declined has none). The settings: one monitor, one mode (1280x720 at 30 Hz), no custom EDID. When another program's copy of the same driver is installed (its `VDDPATH` is not ours) the app refuses to install or - remove and never touches its monitors. Uninstall removes the device, the driver package, the - registry key and the settings folder. + remove and never touches its monitors. Uninstall removes the device, then the driver package (one + not in the driver store counts as gone), and only then the registry key, which makes it ours, and + the settings folder; when a device or the package stays, it fails with the reason and keeps the + registry key, so a retry is still allowed. +- **Never under running services**: installing or removing is refused unless the services are + stopped (or failed, which has stopped the bot browser already), so the monitor never vanishes + under the bot browser's window; while one runs, a service start or restart is refused, and a + second driver task too. - **On only while used**: a service start first takes the monitor off the desktop (left over from a run that ended badly). With `browserShare` it then attaches the monitor (no administrator needed) right of and below the rightmost real monitor, touching it only at that monitor's bottom-right @@ -387,7 +399,7 @@ back as Korean messages for the screen. The Tauri shell passes the screens' `inv | `discord_channel_info` `{id}` / `channel_sync_status` | a channel's Discord name and topic / each synced chat channel's last result (above) | | `collect_results` `{target, limit}` | `{targets, items}`: every target folder with results, and the collected items newest first (`target` null: every target; `limit` 1-500, default 100) | | `mcp_env_status` / `mcp_env_set` `{server, name, value}` | which MCP environment values are stored (`{server: {NAME: bool}}`, never the values) / store one (an empty value removes it); only for a saved server and name | -| `display_driver_status` / `display_driver_install` / `display_driver_uninstall` | the virtual monitor's driver: `{supported, installed, other}` (Windows only; `other`: another program's copy) / install or remove it elevated (above), then its status | +| `display_driver_status` / `display_driver_install` / `display_driver_uninstall` | the virtual monitor's driver: `{supported, installed, other}` (Windows only; `other`: another program's copy) / install or remove it elevated (above), then its status; refused unless the services are stopped or failed, and `service_start` / `service_restart` are refused meanwhile | | `install_status` / `install_start` / `install_cancel` | the install steps and their state, bytes and last line / run what is not done in the background / stop it | | `logs_query` `{tab, level, find, after, limit}` / `logs_error_report` / `logs_export` `{from, to}` | the log hub; the zip goes to `logs/` and its path comes back | @@ -497,9 +509,12 @@ log screen, error copy, zip export, and closing the window ending the process wi to `%APPDATA%` or `%LOCALAPPDATA%`. The virtual monitor (`tests/vdisplay_elevated.rs`, no harness: started elevated, the same program is the elevated half; `tests/bot_browser.rs` with a screen): the driver installed through the elevated start (Windows' SignPath question answered once) with the -settings folder's permissions, the monitor off after install, on at the rightmost monitor's corner +settings folder's permissions, a declined install leaving no device, package, registry key or +settings folder and the next install giving one working device, the monitor off after install, on at the rightmost monitor's corner while the bot browser runs and off after, one Chrome window there filling the work area and holding the bot's tab, the focus staying in the program the user types into, no taskbar button, no Chrome left after the stop, and the uninstall leaving no device, driver package, registry key or settings -folder. On Linux the same window test runs on an X display (one window at the given place and +folder. On every system: a removal forgets the driver only when no device is left and the package +is gone or was not in the store; driver tasks refused while the services start, and a start (and a +second task) refused while one runs, also after it failed. On Linux the same window test runs on an X display (one window at the given place and size, the bot's tab in it). diff --git a/app/src/admin_api.rs b/app/src/admin_api.rs index 8faeeed..c30f20a 100644 --- a/app/src/admin_api.rs +++ b/app/src/admin_api.rs @@ -23,6 +23,8 @@ pub struct AdminApi { installer: Mutex>>, syncer: Mutex>>, hub: Arc, + /// The virtual monitor's driver is being installed or removed: no service start meanwhile. + driver_busy: Mutex, } fn arg<'a>(args: &'a Value, key: &str) -> Result<&'a Value, String> { @@ -51,7 +53,7 @@ impl AdminApi { hub.set_secrets(Secrets::new(&d.secrets_file()).values()); } Self { location_file: location_file.to_path_buf(), dir: Mutex::new(dir), controller: Mutex::new(None), installer: Mutex::new(None), - syncer: Mutex::new(None), hub } + syncer: Mutex::new(None), hub, driver_busy: Mutex::new(false) } } fn dir(&self) -> Result { @@ -100,6 +102,33 @@ impl AdminApi { Arc::new(crate::channel_sync::DiscordRest::new(dir.secrets_file())), dir.settings_file())).clone()) } + /// Start the services in the background, unless the virtual monitor's driver is being installed + /// or removed (its monitor would vanish under the bot browser, or appear half made). + fn start_services(&self, c: &Arc) -> Result { + let busy = self.driver_busy.lock().unwrap(); + if *busy { + return Err("가상 모니터 드라이버 작업이 끝난 뒤에 시작해 주세요".into()); + } + c.start_in_background().map(|_| json!({"ok": true})) + } + + /// Mark a driver install or removal as running; only while the services are stopped (a failed + /// run has stopped the bot browser already) and no other driver task runs. + fn begin_driver_task(&self) -> Result<(), String> { + let mut busy = self.driver_busy.lock().unwrap(); + if *busy { + return Err("가상 모니터 드라이버 작업이 이미 진행 중입니다".into()); + } + let controller = self.controller.lock().unwrap().clone(); + if let Some(state) = controller.map(|c| c.state()) { + if !matches!(state, State::Stopped | State::Failed) { + return Err("서비스를 정지한 뒤에 가상 모니터 드라이버를 설치하거나 제거해 주세요".into()); + } + } + *busy = true; + Ok(()) + } + fn controller(&self) -> Result, String> { let dir = self.dir()?; let mut c = self.controller.lock().unwrap(); @@ -286,7 +315,10 @@ impl AdminApi { "display_driver_status" => Ok(json!(crate::vdisplay::status())), "display_driver_install" | "display_driver_uninstall" => { let action = if command == "display_driver_install" { "install" } else { "uninstall" }; - if let Err(e) = crate::vdisplay::run_elevated(action).await { + self.begin_driver_task()?; + let done = crate::vdisplay::run_elevated(action).await; + *self.driver_busy.lock().unwrap() = false; + if let Err(e) = done { crate::warn_log!("admin", "Warning: display driver {action} failed: {e}"); return Err(e); } @@ -308,14 +340,14 @@ impl AdminApi { } // Starting can take long (the LLM's first start downloads the model), so it runs in the // background and the dashboard shows how it goes; stop also cancels a start. - "service_start" => self.controller()?.start_in_background().map(|_| json!({"ok": true})), + "service_start" => self.start_services(&self.controller()?), "service_restart" => { let c = self.controller()?; if c.state() != State::Running { return Err(format!("cannot restart while {:?}", c.state()).to_lowercase()); } c.stop().await?; - c.start_in_background().map(|_| json!({"ok": true})) + self.start_services(&c) } "service_stop" => self.controller()?.stop().await.map(|_| json!({"ok": true})), "dashboard" => Ok(self.controller()?.snapshot().await), @@ -355,7 +387,7 @@ mod tests { let base = temp_dir(tag); let loc = base.join("cfg").join("location.json"); (AdminApi { location_file: loc, dir: Mutex::new(None), controller: Mutex::new(None), installer: Mutex::new(None), syncer: Mutex::new(None), - hub: LogHub::new(None) }, + hub: LogHub::new(None), driver_busy: Mutex::new(false) }, base) } @@ -572,6 +604,33 @@ mod tests { assert_eq!(std::fs::read_to_string(&file).unwrap(), before); } + #[tokio::test] + async fn the_display_driver_and_the_services_never_change_at_the_same_time() { + let (a, base) = api("api5"); + a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap(); + // While the services start (or run), the driver is neither installed nor removed. + a.call("service_start", json!({})).await.unwrap(); + for cmd in ["display_driver_install", "display_driver_uninstall"] { + assert!(a.call(cmd, json!({})).await.unwrap_err().contains("정지"), "{cmd}"); + } + a.call("service_stop", json!({})).await.unwrap(); + for _ in 0..200 { + if a.call("dashboard", json!({})).await.unwrap()["state"] == json!("stopped") { break; } + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + // While a driver task runs, the services do not start and no second task begins. + a.begin_driver_task().unwrap(); + assert!(a.call("service_start", json!({})).await.unwrap_err().contains("드라이버")); + assert!(a.begin_driver_task().is_err()); + assert_eq!(a.call("dashboard", json!({})).await.unwrap()["state"], json!("stopped")); + // A finished task (here off Windows it fails at once) frees both again. + *a.driver_busy.lock().unwrap() = false; + assert!(a.call("display_driver_install", json!({})).await.is_err()); + assert!(!*a.driver_busy.lock().unwrap(), "a failed task does not stay running"); + a.call("service_start", json!({})).await.unwrap(); + a.call("service_stop", json!({})).await.unwrap(); + } + #[tokio::test] async fn a_start_is_starting_when_it_answers_so_a_stop_right_after_it_is_not_refused() { let (a, base) = api("api4"); diff --git a/app/src/vdisplay.rs b/app/src/vdisplay.rs index 3fde306..675fba6 100644 --- a/app/src/vdisplay.rs +++ b/app/src/vdisplay.rs @@ -232,10 +232,12 @@ mod win { devices().into_iter().find(|d| d.string == ADAPTER_NAME) } + /// Installed means ours with its monitor there (the driver loaded), so a device left without + /// its driver shows as not installed and can be installed again. pub fn status() -> DriverStatus { - let present = adapter().is_some() || !hardware_devices(false).is_empty(); + let present = adapter().is_some() || !hardware_devices().is_empty(); let ours = ours(); - DriverStatus { supported: true, installed: ours && present, other: present && !ours } + DriverStatus { supported: true, installed: ours && adapter().is_some(), other: present && !ours } } /// Put the virtual monitor on the desktop at `corner` and return where it is. @@ -316,9 +318,10 @@ mod win { changed } - /// The display-class devices with the driver's hardware ID (`present`: only those plugged in). - fn hardware_devices(present: bool) -> Vec { - let (set, list) = hardware_set(present); + /// The root devices with the driver's hardware ID, in any class (a device whose driver install + /// was declined has none), present or not. + fn hardware_devices() -> Vec { + let (set, list) = hardware_set(); if set != INVALID_HANDLE_VALUE as HDEVINFO { // SAFETY: the list from `hardware_set`, no longer used. unsafe { SetupDiDestroyDeviceInfoList(set) }; @@ -326,9 +329,11 @@ mod win { list } - fn hardware_set(present: bool) -> (HDEVINFO, Vec) { - // SAFETY: a device list for the display class; destroyed by the callers that keep it. - let set = unsafe { SetupDiGetClassDevsW(&GUID_DEVCLASS_DISPLAY, std::ptr::null(), std::ptr::null_mut(), if present { DIGCF_PRESENT } else { 0 }) }; + fn hardware_set() -> (HDEVINFO, Vec) { + let root = wide("ROOT"); + let flags = DIGCF_ALLCLASSES; + // SAFETY: a device list of the root enumerator; destroyed by the callers that keep it. + let set = unsafe { SetupDiGetClassDevsW(std::ptr::null(), root.as_ptr(), std::ptr::null_mut(), flags) }; let mut out = vec![]; if set == INVALID_HANDLE_VALUE as HDEVINFO { return (set, out); @@ -361,16 +366,33 @@ mod win { } /// Elevated: settings folder, the driver's registry value, the device, and its driver. Windows - /// asks the user once whether to install software from the SignPath Foundation. + /// asks the user once whether to install software from the SignPath Foundation. A failure (also + /// the user saying no) undoes what this attempt made, so nothing looks installed and the next + /// attempt starts clean. pub(super) fn install(driver: &Path) -> Result<(), String> { let inf = driver.join("MttVDD.inf"); if !inf.is_file() { return Err("드라이버 파일이 없습니다 (display-driver\\MttVDD.inf)".into()); } - let (present, ours) = (adapter().is_some() || !hardware_devices(false).is_empty(), ours()); - if present && !ours { + let (was_ours, had_device) = (ours(), !hardware_devices().is_empty()); + if (had_device || adapter().is_some()) && !was_ours { return Err("다른 프로그램이 설치한 가상 디스플레이 드라이버가 이미 있습니다".into()); } + let result = install_steps(&inf, had_device); + if result.is_err() { + if !had_device { + remove_devices(); + } + if !was_ours { + let _ = uninstall_package(&inf); + let _ = run("reg", &["delete", &format!("HKLM\\{REG_KEY}"), "/f"]); + remove_config_dir(); + } + } + result + } + + fn install_steps(inf: &Path, had_device: bool) -> Result<(), String> { let dir = config_dir().ok_or("ProgramData 폴더를 찾지 못했습니다")?; std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; std::fs::write(dir.join("vdd_settings.xml"), settings_xml()).map_err(|e| e.to_string())?; @@ -380,16 +402,19 @@ mod win { run("icacls", &[&d, "/inheritance:r", "/grant:r", "*S-1-5-18:(OI)(CI)F", "*S-1-5-32-544:(OI)(CI)F", "*S-1-5-19:(OI)(CI)RX", "*S-1-5-32-545:(OI)(CI)RX"])?; run("reg", &["add", &format!("HKLM\\{REG_KEY}"), "/v", "VDDPATH", "/t", "REG_SZ", "/d", &d, "/f"])?; - if hardware_devices(false).is_empty() { + if !had_device { create_device()?; } - let (hw, inf_w) = (wide(HARDWARE_ID), wide_path(&inf)); + let (hw, inf_w) = (wide(HARDWARE_ID), wide_path(inf)); let mut reboot: BOOL = 0; // SAFETY: valid NUL-terminated strings; no parent window. if unsafe { UpdateDriverForPlugAndPlayDevicesW(std::ptr::null_mut(), hw.as_ptr(), inf_w.as_ptr(), INSTALLFLAG_FORCE, &mut reboot) } == 0 { // SAFETY: plain call. let e = unsafe { GetLastError() }; - return Err(if e == ERROR_CANCELLED { "드라이버 설치를 취소했습니다".into() } else { format!("드라이버를 설치하지 못했습니다 ({e})") }); + // No to Windows' question about the publisher comes back as "publisher not trusted". + const PUBLISHER_NOT_TRUSTED: u32 = 0xE000_0243; + return Err(if e == ERROR_CANCELLED || e == PUBLISHER_NOT_TRUSTED { "드라이버 설치를 취소했습니다".into() } + else { format!("드라이버를 설치하지 못했습니다 ({e})") }); } // The new monitor joins the desktop at once; it stays off until the bot browser uses it. for _ in 0..50 { @@ -402,6 +427,41 @@ mod win { Ok(()) } + /// Remove every device with the driver's hardware ID; returns how many are left. + fn remove_devices() -> usize { + let (set, list) = hardware_set(); + for di in &list { + // SAFETY: removing a device of the list `set`, which is destroyed after the loop. + unsafe { SetupDiCallClassInstaller(DIF_REMOVE, set, di) }; + } + if set != INVALID_HANDLE_VALUE as HDEVINFO { + // SAFETY: the list from `hardware_set`. + unsafe { SetupDiDestroyDeviceInfoList(set) }; + } + hardware_devices().len() + } + + /// Remove the driver package from the driver store; `Err` with the Windows error code. + fn uninstall_package(inf: &Path) -> Result<(), u32> { + let inf = wide_path(inf); + let mut reboot: BOOL = 0; + // SAFETY: valid NUL-terminated path; no parent window. + if unsafe { DiUninstallDriverW(std::ptr::null_mut(), inf.as_ptr(), 0, &mut reboot) } != 0 { + return Ok(()); + } + // SAFETY: plain call. + Err(unsafe { GetLastError() }) + } + + fn remove_config_dir() { + if let Some(dir) = config_dir() { + let _ = std::fs::remove_dir_all(&dir); + if let Some(parent) = dir.parent() { + let _ = std::fs::remove_dir(parent); + } + } + } + fn create_device() -> Result<(), String> { let (name, hw) = (wide("Display"), { let mut v: Vec = HARDWARE_ID.encode_utf16().collect(); @@ -426,32 +486,19 @@ mod win { } /// Elevated: remove the device, the driver, the registry value and the settings folder; only - /// when this app installed it. + /// when this app installed it. The registry value (what makes it ours) goes only once the + /// device and the driver are gone, so a failed removal can be retried. pub(super) fn uninstall(driver: &Path) -> Result<(), String> { if !ours() { return Err("이 앱이 설치한 가상 디스플레이 드라이버가 아닙니다".into()); } - let (set, list) = hardware_set(false); - for di in &list { - // SAFETY: removing a device of the list `set`, which is destroyed after the loop. - unsafe { SetupDiCallClassInstaller(DIF_REMOVE, set, di) }; - } - if set != INVALID_HANDLE_VALUE as HDEVINFO { - // SAFETY: the list from `hardware_set`. - unsafe { SetupDiDestroyDeviceInfoList(set) }; - } - let inf = wide_path(&driver.join("MttVDD.inf")); - let mut reboot: BOOL = 0; - // SAFETY: valid NUL-terminated path; a driver not in the store is just a failure we ignore. - unsafe { DiUninstallDriverW(std::ptr::null_mut(), inf.as_ptr(), 0, &mut reboot) }; - let _ = run("reg", &["delete", &format!("HKLM\\{REG_KEY}"), "/f"]); - if let Some(dir) = config_dir() { - let _ = std::fs::remove_dir_all(&dir); - if let Some(parent) = dir.parent() { - let _ = std::fs::remove_dir(parent); - } - } - if hardware_devices(false).is_empty() { Ok(()) } else { Err("가상 모니터 장치를 지우지 못했습니다".into()) } + let left = remove_devices(); + let package = if left == 0 { uninstall_package(&driver.join("MttVDD.inf")) } else { Ok(()) }; + removal_done(left, package)?; + run("reg", &["delete", &format!("HKLM\\{REG_KEY}"), "/f"]) + .map_err(|e| format!("드라이버 등록 정보를 지우지 못했습니다: {e}"))?; + remove_config_dir(); + Ok(()) } /// Run `jarvis.exe --display-driver ` as administrator (Windows asks the user) and wait. @@ -494,10 +541,31 @@ mod win { } } +/// Whether a removal may forget the driver was ours: no device left, and the driver package +/// removed or not in the driver store (Windows error 1168, ERROR_NOT_FOUND). +#[cfg_attr(not(windows), allow(dead_code))] +fn removal_done(devices_left: usize, package: Result<(), u32>) -> Result<(), String> { + if devices_left > 0 { + return Err(format!("가상 모니터 장치 {devices_left}개를 지우지 못했습니다. 다시 시도해 주세요")); + } + match package { + Ok(()) | Err(1168) => Ok(()), + Err(e) => Err(format!("드라이버 패키지를 지우지 못했습니다 ({e}). 다시 시도해 주세요")), + } +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn a_removal_forgets_the_driver_only_when_device_and_package_are_gone() { + assert_eq!(removal_done(0, Ok(())), Ok(())); + assert_eq!(removal_done(0, Err(1168)), Ok(()), "a package not in the store is already gone"); + assert!(removal_done(1, Ok(())).is_err(), "a device left keeps it ours, so it can be retried"); + assert!(removal_done(0, Err(5)).is_err()); + } + #[test] fn the_monitor_touches_the_rightmost_monitor_only_at_its_corner() { let one = [Rect { x: 0, y: 0, w: 1920, h: 1080 }]; diff --git a/app/tests/vdisplay_elevated.rs b/app/tests/vdisplay_elevated.rs index a30d79e..54d3500 100644 --- a/app/tests/vdisplay_elevated.rs +++ b/app/tests/vdisplay_elevated.rs @@ -1,7 +1,9 @@ //! Installing and removing the virtual monitor's driver through the app's elevated half //! (admin.spec.md, "Virtual monitor"). Windows only, with the driver files in `display-driver/` next -//! to this program and `JARVIS_TEST_VDISPLAY=install` or `uninstall`; Windows asks for the -//! administrator (and on install whether to trust the SignPath Foundation). Elsewhere it skips. +//! to this program and `JARVIS_TEST_VDISPLAY=install` or `uninstall`, or `install-declined` (the +//! person answers no to Windows' question: the install fails and leaves nothing installed); Windows +//! asks for the administrator (and on install whether to trust the SignPath Foundation). Elsewhere +//! it skips. //! No test harness: started elevated, this same program is the elevated half. fn main() { @@ -10,14 +12,19 @@ fn main() { std::process::exit(code); } let Ok(action) = std::env::var("JARVIS_TEST_VDISPLAY") else { - eprintln!("skipped: set JARVIS_TEST_VDISPLAY=install|uninstall"); + eprintln!("skipped: set JARVIS_TEST_VDISPLAY=install|install-declined|uninstall"); return; }; let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); - let outcome = rt.block_on(jarvis_app::vdisplay::run_elevated(&action)); + let declined = action == "install-declined"; + let outcome = rt.block_on(jarvis_app::vdisplay::run_elevated(if declined { "install" } else { &action })); let status = jarvis_app::vdisplay::status(); println!("{action}: {outcome:?} -> {status:?}"); - outcome.expect("the elevated half succeeds"); + if declined { + assert!(outcome.is_err(), "a declined install fails"); + } else { + outcome.expect("the elevated half succeeds"); + } assert_eq!(status.installed, action == "install"); - assert!(!status.other); + assert!(!status.other, "nothing this app made looks like another program's driver"); }