← Commit history

1.9.59: pup player works again (issue #10): opens behind your windows and plays without a click, every Bridge call names the adom-tts player thread, refused opens reported instead of counted as success, restart says whether the window opened and keeps the pup surface, adom-bridge found in ~/.local/bin from ssh and cron shells

Colby Knox ·9b834cf69b · ·parent 0208606
4 files changed +177−49
Cargo.toml+1−1
@@ -1,6 +1,6 @@ [package] name = "adom-tts"-version = "1.9.57"+version = "1.9.59" edition = "2021" license = "AGPL-3.0-or-later" repository = "https://github.com/adom-inc/adom-tts"
VERSION+1−1
@@ -1 +1 @@-1.9.57+1.9.59
bin/adom-tts

  
src/play.rs+175−47
@@ -1308,7 +1308,7 @@ fn open_desktop_window(url: &str) -> Result<()> {         anyhow::bail!("AMBIGUOUS desktop target: {count} Bridge machines connected and no ADOM_BRIDGE_TARGET set. \ Pin it: `export ADOM_BRIDGE_TARGET=<host>` then `adom-tts reopen`");     }-    let mut cmd = Command::new("adom-bridge");+    let mut cmd = Command::new(adom_bridge_bin());     if let Some(t) = &target { cmd.arg("--target").arg(t); }     let body = serde_json::json!({ "method": "POST", "path": "/hbw/open", "body": { "url": url }, "timeoutSeconds": 20 }).to_string();     let out = cmd.args(["--ai-thread", "adom-tts player", "hd_api", &body]).output()@@ -1642,13 +1642,79 @@ fn find_panel_id_for_tab(name: &str) -> Result<Option<String>> { }  fn close_pup_window(session: &str) -> Result<()> {+    // Same identity and machine as the open (issue #10): without them ab refuses the close and the+    // window is left behind on the user's desktop.+    let (target, _) = resolve_bridge_target();     let payload = serde_json::json!({"sessionId": session}).to_string();-    let _ = Command::new("adom-bridge")-        .args(["pup_close_window", &payload])-        .output();+    let _ = bridge_cmd(target.as_deref()).args(["pup_close_window", &payload]).output();     Ok(()) } +/// The thread name adom-tts gives Adom Bridge on every call. ab refuses a call that names no+/// thread (`caller_identity_required`), and pup scopes windows to it, so the open, the playback+/// unlock and the close must all carry the same one (issue #10).+const BRIDGE_THREAD: &str = "adom-tts player";++/// Where the adom-bridge CLI is. PATH first; then the places the installer puts it, because a+/// non-login ssh shell or a cron job has no ~/.local/bin on PATH and every pup call failed to+/// start there (issue #10, case B).+fn adom_bridge_bin() -> PathBuf {+    if let Ok(p) = std::env::var("ADOM_BRIDGE_BIN") {+        if !p.trim().is_empty() { return PathBuf::from(p.trim()); }+    }+    if let Some(path) = std::env::var_os("PATH") {+        for dir in std::env::split_paths(&path) {+            let c = dir.join("adom-bridge");+            if c.is_file() { return c; }+        }+    }+    let home = std::env::var("HOME").unwrap_or_default();+    for c in [format!("{home}/.local/bin/adom-bridge"), "/usr/local/bin/adom-bridge".into(),+              format!("{home}/.local/bin/adom-bridge-cli"), "/usr/local/bin/adom-bridge-cli".into()] {+        if !c.starts_with('/') { continue; }+        if Path::new(&c).is_file() { return PathBuf::from(c); }+    }+    PathBuf::from("adom-bridge")+}++/// An adom-bridge command with the machine pinned (when known) and adom-tts's thread name.+fn bridge_cmd(target: Option<&str>) -> Command {+    let mut c = Command::new(adom_bridge_bin());+    if let Some(t) = target { c.arg("--target").arg(t); }+    c.args(["--ai-thread", BRIDGE_THREAD]);+    c+}++/// Run one adom-bridge verb and read its JSON answer. The CLI exits 0 when ab or the bridge+/// REFUSES a verb (the refusal is in the JSON), so the exit status alone reported every refused+/// pup open as a success (issue #10). Ok only when the reply says ok/success and names no error.+fn bridge_call(target: Option<&str>, verb: &str, args: &serde_json::Value) -> Result<serde_json::Value> {+    let bin = adom_bridge_bin();+    let out = bridge_cmd(target).arg(verb).arg(args.to_string()).output()+        .with_context(|| format!("could not run {} (is Adom Bridge's CLI installed? `adom-wiki pkg install adom/adom-bridge`)", bin.display()))?;+    let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap_or(serde_json::Value::Null);+    if let Some(reason) = bridge_refusal(&v) {+        let detail = if v.is_null() { String::from_utf8_lossy(&out.stderr).trim().chars().take(200).collect() } else { reason };+        anyhow::bail!("{verb} did not succeed on {}: {detail}", target.unwrap_or("the connected machine"));+    }+    Ok(v)+}++/// Why an ab reply is a failure, or None when it succeeded.+fn bridge_refusal(v: &serde_json::Value) -> Option<String> {+    if !v.is_object() { return Some("no JSON answer".into()); }+    let said_ok = v.get("ok").and_then(|b| b.as_bool()) == Some(true) || v.get("success").and_then(|b| b.as_bool()) == Some(true);+    let said_no = v.get("ok").and_then(|b| b.as_bool()) == Some(false) || v.get("success").and_then(|b| b.as_bool()) == Some(false)+        || v.get("status").and_then(|s| s.as_str()) == Some("error");+    let code = v.get("errorCode").and_then(|c| c.as_str()).filter(|c| !c.is_empty());+    if said_ok && !said_no && code.is_none() { return None; }+    let msg = v.get("error").and_then(|e| e.as_str()).filter(|e| !e.is_empty())+        .or_else(|| v.get("_hint").and_then(|h| h.as_str()).filter(|h| !h.is_empty()))+        .unwrap_or("refused");+    let msg: String = msg.chars().take(200).collect();+    Some(match code { Some(c) => format!("{c}: {msg}"), None => msg })+}+ /// Which Bridge machine should pup open on? (Bridge = ab, the app formerly /// named "Adom Desktop"; the 2026-08 cutover renamed the CLI to /// `adom-bridge` (Linux; `adom-bridge-cli` remains a linked alias) and every@@ -1676,7 +1742,7 @@ fn resolve_bridge_target() -> (Option<String>, usize) {         }     }     // Ask Bridge how many machines are connected.-    let names: Vec<String> = Command::new("adom-bridge").arg("targets").output().ok()+    let names: Vec<String> = Command::new(adom_bridge_bin()).arg("targets").output().ok()         .filter(|o| o.status.success())         .and_then(|o| serde_json::from_slice::<serde_json::Value>(&o.stdout).ok())         .and_then(|v| v.get("targets").and_then(|t| t.as_array()).map(|a|@@ -1694,48 +1760,53 @@ fn open_pup_window(url: &str, session: &str, profile: &str) -> Result<()> {         anyhow::bail!("AMBIGUOUS pup target: {count} Bridge machines connected and no ADOM_BRIDGE_TARGET set. \ Pin it so the drainer knows which screen: `export ADOM_BRIDGE_TARGET=<host>` then `adom-tts restart`");     }-    let with_target = |c: &mut Command| { if let Some(t) = &target { c.arg("--target").arg(t); } };+    let target = target.as_deref(); -    let open_args = serde_json::json!({+    // BACKGROUND (issue #10). This used to ask for foreground:true, which pup refuses without a+    // foregroundReason, so the window never opened. pup opens a background window behind the+    // user's own windows (never minimized) and the clip plays there once playback is unlocked+    // below; the player is heard, it does not need to take the screen on every clip.+    let opened = bridge_call(target, "pup_open_window", &serde_json::json!({         "sessionId": session,         "profile": profile,         "url": url,-        // VISIBLE ON PURPOSE (ralph-test discovery): Chrome SUSPENDS the media-        // pipeline in a fully-occluded background window — the page polls and-        // "plays" but audio never loads (netState stuck LOADING on a local-        // blob). An audio player the user explicitly routed to pup MUST be a-        // visible window or it is silent by construction. This was the true-        // root of the original "--surface pup never plays" field report.-        "foreground": true,-    }).to_string();-    let mut open_cmd = Command::new("adom-bridge");-    with_target(&mut open_cmd);-    let out = open_cmd-        .arg("pup_open_window")-        .arg(&open_args)-        .output()-        .context("invoke adom-bridge pup_open_window")?;-    if !out.status.success() {-        anyhow::bail!("adom-bridge pup_open_window failed: {}",-            String::from_utf8_lossy(&out.stderr));+    }))?;++    // Confirm the PLAYER loaded, not just a window: pup answers ok for a window whose page failed+    // (an unreachable URL shows Chrome's error page). The player page has an <audio> element.+    let mut loaded = false;+    for _ in 0..10 {+        let probe = bridge_call(target, "pup_eval", &serde_json::json!({+            "sessionId": session, "expr": "!!document.querySelector('audio')",+        }));+        if let Ok(v) = &probe {+            if v.get("result").and_then(|r| r.as_bool()) == Some(true) || v.get("value").and_then(|r| r.as_bool()) == Some(true) {+                loaded = true; break;+            }+        }+        thread::sleep(Duration::from_millis(500));+    }+    if !loaded {+        let _ = close_pup_window(session);+        anyhow::bail!("pup opened a window on {} but the player page did not load at {url} (can that machine reach it?)",+            target.unwrap_or("the connected machine"));     } -    // Defeat any first-load autoplay block. The HTML's own retry covers-    // most cases; this is belt-and-braces for a stricter Chrome policy.-    // GUARD: only kick playback if it hasn't STARTED yet (paused at 0 and not-    // ended) — an unconditional play() here would RESTART a clip that already-    // finished (short clips that end before this 1.5s eval), i.e. loop it.-    thread::sleep(Duration::from_millis(1500));-    let eval_args = serde_json::json!({+    // Unlock autoplay. Chrome blocks play() in a page nobody clicked; a DevTools evaluate with+    // userGesture:true counts as one. GUARD: only start a clip that has not started yet (paused at+    // 0 and not ended), or a short clip that already finished would replay.+    let unlock = bridge_call(target, "pup_devtools", &serde_json::json!({         "sessionId": session,-        "expr": "(function(){var el=document.querySelector('audio');if(el&&el.paused&&!el.ended&&el.currentTime===0)el.play();})()",-    }).to_string();-    let mut eval_cmd = Command::new("adom-bridge");-    with_target(&mut eval_cmd);-    let _ = eval_cmd-        .arg("pup_eval")-        .arg(&eval_args)-        .output();+        "method": "Runtime.evaluate",+        "params": {+            "expression": "(function(){var el=document.querySelector('audio');if(el&&el.paused&&!el.ended&&el.currentTime===0){var p=el.play();if(p&&p.catch)p.catch(function(){});}return true;})()",+            "userGesture": true,+            "awaitPromise": false,+        },+    }));+    log_event("pup_window_opened", serde_json::json!({ "target": target, "session": session, "url": url,+        "windowId": opened.get("windowId"), "playbackUnlocked": unlock.is_ok(),+        "unlockError": unlock.as_ref().err().map(|e| e.to_string()) }));     Ok(()) } @@ -2659,6 +2730,31 @@ pub fn reopen() -> Result<()> { /// (good, pinned) env — the real reset the field issue asked for. `reopen` /// re-offers the tab but keeps a broken player; this replaces the player. /// Queued clips survive (they live in the queue dir, not the drainer).+/// Byte length of events.jsonl now, so a caller can read only the lines a fresh drainer adds.+fn events_log_len() -> u64 {+    tts_home().ok().and_then(|h| std::fs::metadata(h.join(".adom/tts/events.jsonl")).ok()).map(|m| m.len()).unwrap_or(0)+}++/// Wait for a fresh drainer's first surface-open outcome in events.jsonl after byte `from`.+fn wait_surface_outcome(from: u64, wait: Duration) -> Option<Result<(), String>> {+    let path = tts_home().ok()?.join(".adom/tts/events.jsonl");+    let start = Instant::now();+    while start.elapsed() < wait {+        let raw = std::fs::read(&path).unwrap_or_default();+        let tail = raw.get(from as usize..).unwrap_or(&[]);+        for line in String::from_utf8_lossy(tail).lines() {+            let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else { continue };+            match v.get("kind").and_then(|k| k.as_str()) {+                Some("pup_window_opened") | Some("desktop_window_opened") => return Some(Ok(())),+                Some("open_surface_failed") => return Some(Err(v.get("error").and_then(|e| e.as_str()).unwrap_or("unknown error").to_string())),+                _ => {}+            }+        }+        thread::sleep(Duration::from_millis(400));+    }+    None+}+ pub fn restart(force: bool) -> Result<()> {     persist_surface_env();   // capture THIS shell's env (incl ADOM_BRIDGE_TARGET)     // PAUSE-IS-SACRED, RESTART EDITION. Field incident: the human paused a clip@@ -2684,11 +2780,15 @@ pub fn restart(force: bool) -> Result<()> {             }         }     }+    // Read the old drainer's command line BEFORE killing it: it names the surface to restart in+    // kind, and /proc/<pid>/cmdline is gone once the process is (a pup player used to come back+    // as the default surface every time, issue #10).+    let mut old_cmdline = String::new();     let killed = lock_owner().and_then(|(pid, _)| {-        let is_drain = std::fs::read(format!("/proc/{pid}/cmdline")).ok()-            .map(|b| { let c = String::from_utf8_lossy(&b); c.contains("adom-tts") && c.contains("__drain") })-            .unwrap_or(false);-        if is_drain { let _ = Command::new("kill").arg("-9").arg(pid.to_string()).output(); Some(pid) } else { None }+        let c = std::fs::read(format!("/proc/{pid}/cmdline")).ok()+            .map(|b| String::from_utf8_lossy(&b).replace('\0', " ")).unwrap_or_default();+        let is_drain = c.contains("adom-tts") && c.contains("__drain");+        if is_drain { old_cmdline = c; let _ = Command::new("kill").arg("-9").arg(pid.to_string()).output(); Some(pid) } else { None }     });     if let Ok(home) = tts_home() {         let _ = std::fs::remove_file(home.join(LOCK_FILE));@@ -2704,18 +2804,30 @@ pub fn restart(force: bool) -> Result<()> {     // (`__drain --surface pup`) so a pup session doesn't silently come back as     // hydrogen. Fall back to the configured default.     let cfg = config::load();-    let surface = killed-        .and_then(|pid| std::fs::read(format!("/proc/{pid}/cmdline")).ok())-        .map(|b| String::from_utf8_lossy(&b).replace('\0', " "))+    let surface = Some(old_cmdline.as_str()).filter(|c| !c.is_empty())         .and_then(|c| if c.contains("--surface pup") { Some(Surface::Pup) }                       else if c.contains("--surface hydrogen") { Some(Surface::Hydrogen) }+                      else if c.contains("--surface desktop") { Some(Surface::Desktop) }                       else { None })         .unwrap_or_else(|| config::resolve_surface(None, &cfg.play));+    let events_before = events_log_len();     ensure_drainer(surface)?;     match killed {         Some(p) => println!("→ restarted: killed stale drainer {p}; spawned a fresh {} player.", surface.as_str()),         None => println!("→ restarted: no drainer owned the lock; spawned a fresh {} player.", surface.as_str()),     }+    // Say whether the window really opened (issue #10: a refused pup open printed only the line+    // above, so the caller believed a player was up). The drainer logs the outcome of its open.+    if matches!(surface, Surface::Pup | Surface::Desktop) {+        match wait_surface_outcome(events_before, Duration::from_secs(25)) {+            Some(Ok(())) => println!("  the {} window is open.", surface.as_str()),+            Some(Err(e)) => {+                println!("✗ the {} window did NOT open: {e}", surface.as_str());+                println!("# hint: `adom-tts logs` has the details; `adom-tts settings set surface hydrogen` then `adom-tts restart` uses the Hydrogen tab instead.");+            }+            None => println!("  (the {} window has not reported yet; check with `adom-tts status`)", surface.as_str()),+        }+    }     let (t, n) = resolve_bridge_target();     match (surface, &t) {         (Surface::Pup, Some(t)) => println!("  pinned to Bridge target: {t}"),@@ -2970,6 +3082,22 @@ pub fn ui_toast(text: &str, kind: &str) -> Result<()> { mod tests {     use super::*; +    // Issue #10: the CLI exits 0 on these, so only the JSON tells a refusal from a success.+    #[test]+    fn bridge_refusal_reads_the_reply_not_the_exit_status() {+        let refused_identity = serde_json::json!({ "ok": false, "status": "error", "errorCode": "caller_identity_required", "error": "name your thread" });+        let refused_fg = serde_json::json!({ "success": false, "errorCode": "foreground_reason_required", "_hint": "pass foregroundReason" });+        let bare_error = serde_json::json!({ "status": "error", "error": "Frame with ID 0 is showing error page" });+        let ok_but_code = serde_json::json!({ "ok": true, "errorCode": "ext_command_failed" });+        let opened = serde_json::json!({ "ok": true, "success": true, "status": "ok", "error": "", "windowId": 7 });+        assert!(bridge_refusal(&refused_identity).unwrap().starts_with("caller_identity_required"));+        assert!(bridge_refusal(&refused_fg).unwrap().contains("foregroundReason"));+        assert!(bridge_refusal(&bare_error).is_some());+        assert!(bridge_refusal(&ok_but_code).is_some());+        assert!(bridge_refusal(&serde_json::Value::Null).is_some());+        assert_eq!(bridge_refusal(&opened), None);+    }+     #[test]     fn player_page_html_substitutes_version_and_polls() {         let h = player_page_html();