main
Drew Owens 0.11.1 source a674891 5d ago
//! WHO PUT THAT DIALOG UP? (0.11.1) — the File ▸ Open of 2026-10-15.
//!
//! MEASURED on adom_drew2: title "Open " (trailing space), `#32770`, hwnd
//! 205698, owned by the SOLIDWORKS main frame, style 0x96CC02C4, exstyle
//! 0x10101, rect (0,0)-(853,533), file name EMPTY. It appeared between 14:57
//! and 15:00Z during a bridge battery with Drew away, and blocked every
//! swx_stop after it; the census called it `kind:"unknown"`,
//! `bridgeCaused:false`, and swx_state once reported `blockingDialogs: []`
//! while it was up. Everything here runs in the simulator.

mod common;

use common::{Bridge, TempDir};
use serde_json::{json, Value};

fn s(v: &Value) -> String {
    serde_json::to_string_pretty(v).unwrap_or_default()
}

/// The window as measured, owned by the simulated main frame (6622700) and
/// with that frame DISABLED — a modal.
fn file_open(hwnd: i64) -> Value {
    json!({"hwnd": hwnd, "className": "#32770", "title": "Open ", "visible": true,
           "owner": 6622700, "ownerEnabled": false, "style": 0x96CC_02C4u64, "exStyle": 0x10101u64, "rect": [0, 0, 853, 533]})
}

struct Machine {
    dir: TempDir,
}

impl Machine {
    fn new(tag: &str) -> Machine {
        let dir = TempDir::new(tag);
        std::fs::write(dir.join("quit-script.json"), json!({"a": "exited"}).to_string()).unwrap();
        std::fs::write(dir.join("sldworks.json"), json!({"responding": true, "hwnd": 6622700, "privateMB": 900, "handles": 4000}).to_string()).unwrap();
        std::fs::write(dir.join("windows.json"), "[]").unwrap();
        // Nobody has touched the machine for an hour.
        std::fs::write(dir.join("last-input-secs"), "3600").unwrap();
        Machine { dir }
    }
    fn write(&self, name: &str, v: Value) {
        std::fs::write(self.dir.join(name), v.to_string()).unwrap();
    }
    fn boot(&self) -> Bridge {
        let b = Bridge::start_in(
            TempDir::new("dialogs-scratch"),
            &[
                ("SWX_LAUNCH_FAKE_DIR", Box::leak(self.dir.path().into_boxed_str())),
                ("SWX_ALLOW_USER_WRITES", "1"),
                ("SWX_QUIT_SETTLE_MS", "80"),
                ("SWX_QUIT_EXIT_WAIT_SECS", "3"),
                ("SWX_OWNER_SETTLE_MS", "10"),
            ],
        );
        b.call("swx_start", json!({}));
        b
    }
    fn windows(&self) -> Vec<Value> {
        serde_json::from_str::<Vec<Value>>(&std::fs::read_to_string(self.dir.join("windows.json")).unwrap()).unwrap()
    }
}

fn stop(b: &Bridge) -> Value {
    b.call("swx_stop", json!({"userAuthorized": true, "confirm": true, "reason": "test: end the session", "maxRung": "a"}))
}

fn cancel(b: &Bridge) -> Value {
    b.call("swx_dismiss_blocking_dialogs", json!({"close": true, "confirm": true, "reason": "test: cancel the bridge's own Open dialog"}))
}

#[test]
fn the_census_is_native_deterministic_and_never_drops_a_visible_modal() {
    let m = Machine::new("dlg-census");
    let mut second = file_open(205699);
    second["title"] = json!("SOLIDWORKS");
    m.write("windows.json", json!([file_open(205698), second]));
    let b = m.boot();
    let mut seen = Vec::new();
    for shot in [true, false, false] {
        let r = b.call("swx_state", json!({"screenshot": shot}));
        let hw: Vec<i64> = r["blockingDialogs"].as_array().cloned().unwrap_or_default().iter().filter_map(|d| d["hwnd"].as_i64()).collect();
        seen.push(hw.clone());
        check!(
            b,
            &format!("swx_state (screenshot:{shot}): BOTH visible modals, from the native census, every time"),
            r["dialogCensusSource"] == "native" && r["blockingDialogsKnown"] == true && hw == vec![205698, 205699],
            s(&r)
        );
    }
    let d = &b.call("swx_state", json!({"screenshot": false}))["blockingDialogs"][0];
    check!(
        b,
        "...each with hwnd, title, class, owner, rect and visibility",
        d["hwnd"] == 205698 && d["title"] == "Open " && d["className"] == "#32770" && d["owner"] == 6622700
            && d["rect"] == json!([0, 0, 853, 533]) && d["visible"] == true,
        s(d)
    );
    let st = stop(&b);
    check!(
        b,
        "swx_stop refuses on the first, and REPORTS the second too",
        st["errorCode"] == "stop_blocked_by_dialog" && st["preconditions"]["moreBlockingDialogs"][0]["hwnd"] == 205699,
        s(&st)
    );
}

#[test]
fn a_file_dialog_a_bridge_verb_raised_is_attributed_and_the_bridge_may_cancel_it() {
    let m = Machine::new("dlg-ours");
    let b = m.boot();
    // The File ▸ Open goes up while swx_docs runs.
    m.write("dialog-on-docs.json", json!([file_open(205698)]));
    m.write("file-dialogs.json", json!({"205698": {"standard": true, "fileName": ""}}));
    let docs = b.call("swx_docs", json!({}));
    check!(
        b,
        "swx_docs says a dialog appeared while it ran, and which",
        docs["dialogsAppeared"][0]["hwnd"] == 205698 && docs["dialogsAppeared"][0]["appearedDuring"][0]["verb"] == "swx_docs",
        s(&docs)
    );
    let st = stop(&b);
    let d = &st["preconditions"]["dialog"];
    check!(
        b,
        "swx_stop's refusal names the dialog: title, hwnd, owner, age and attribution — bridge-caused, by swx_docs",
        st["errorCode"] == "stop_blocked_by_dialog"
            && st["error"].as_str().unwrap_or("").contains("hwnd 205698")
            && st["error"].as_str().unwrap_or("").contains("owned by 6622700")
            && d["attribution"]["bridgeCaused"] == true
            && d["attribution"]["bridgeCausedBy"] == "swx_docs"
            && d["attribution"]["ageSeconds"].is_u64()
            && d["bridgeMayCancel"] == true
            && d["fileDialog"]["fileNameEmpty"] == true,
        s(&st)
    );
    let c = cancel(&b);
    check!(
        b,
        "swx_dismiss_blocking_dialogs CANCELS it (IDCANCEL), without the process-level opt-in it needs for anything else",
        c["cancelled"][0]["hwnd"] == 205698 && c["cancelled"][0]["ok"] == true && c["cancelled"][0]["raisedDuring"] == "swx_docs",
        s(&c)
    );
    check!(b, "...the window is gone", m.windows().is_empty(), "");
    let led = b.call("swx_action_ledger", json!({"limit": 50}));
    check!(
        b,
        "...and the cancel is ledgered with its attribution",
        led["actions"].as_array().map(|a| a.iter().any(|e| e["action"] == "dialog_cancelled" && e["detail"]["raisedDuring"] == "swx_docs")).unwrap_or(false)
            && led["actions"].as_array().map(|a| a.iter().any(|e| e["action"] == "dialog_appeared")).unwrap_or(false),
        s(&led)
    );
    let after = stop(&b);
    check!(b, "and swx_stop goes through", after["success"] == true && after["stopped"] == true, s(&after));
}

#[test]
fn a_dialog_with_text_typed_or_input_since_or_of_unknown_origin_is_never_cancelled() {
    // 1. Text typed into the file name: the user's.
    let m = Machine::new("dlg-typed");
    let b = m.boot();
    m.write("dialog-on-docs.json", json!([file_open(205698)]));
    m.write("file-dialogs.json", json!({"205698": {"standard": true, "fileName": "crate-v3"}}));
    b.call("swx_docs", json!({}));
    let c = cancel(&b);
    check!(
        b,
        "typed text: refused, and the window stays",
        c["cancelled"].as_array().map(|a| a.is_empty()).unwrap_or(false)
            && c["cancelRefused"][0]["why"].as_str().unwrap_or("").contains("typed")
            && m.windows().len() == 1
            && !m.dir.join("cancelled-dialogs.jsonl").exists(),
        s(&c)
    );
    let st = stop(&b);
    check!(b, "...and swx_stop says the user cancels it", st["preconditions"]["dialog"]["whoAnswers"] == "the user cancels it", s(&st));

    // 2. The user gave input after the verb began.
    let m = Machine::new("dlg-input");
    let b = m.boot();
    m.write("dialog-on-docs.json", json!([file_open(205698)]));
    m.write("file-dialogs.json", json!({"205698": {"standard": true, "fileName": ""}}));
    b.call("swx_docs", json!({}));
    std::fs::write(m.dir.join("last-input-secs"), "0").unwrap();
    let c = cancel(&b);
    check!(b, "input since: refused", c["cancelled"].as_array().map(|a| a.is_empty()).unwrap_or(false) && m.windows().len() == 1, s(&c));

    // 3. Up before the bridge ever looked: origin unknown.
    let m = Machine::new("dlg-before");
    m.write("windows.json", json!([file_open(205698)]));
    m.write("file-dialogs.json", json!({"205698": {"standard": true, "fileName": ""}}));
    let b = m.boot();
    let st = stop(&b);
    check!(
        b,
        "a dialog up before the first census: unattributed, never claimed",
        st["preconditions"]["dialog"]["attribution"]["bridgeCaused"] == false && st["preconditions"]["dialog"]["bridgeMayCancel"] == false,
        s(&st["preconditions"]["dialog"])
    );
    let c = cancel(&b);
    check!(b, "...and never cancelled", c["cancelled"].as_array().map(|a| a.is_empty()).unwrap_or(false) && m.windows().len() == 1, s(&c));

    // 4. Not the standard file dialog.
    let m = Machine::new("dlg-other");
    let b = m.boot();
    let mut other = file_open(205700);
    other["title"] = json!("Rebuild Errors");
    m.write("dialog-on-docs.json", json!([other]));
    m.write("file-dialogs.json", json!({"205700": {"standard": false, "fileName": ""}}));
    b.call("swx_docs", json!({}));
    let c = cancel(&b);
    check!(
        b,
        "another dialog (even raised by a bridge verb, nothing typed): never cancelled",
        c["cancelled"].as_array().map(|a| a.is_empty()).unwrap_or(false)
            && c["cancelRefused"][0]["why"].as_str().unwrap_or("").contains("not the standard Windows file dialog")
            && m.windows().len() == 1,
        s(&c)
    );
}