A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.
Swift ai-agentsanthropicantigravityclaudeclaude-codecodexcursordynamic-islandgemini-cliiosiphonlinuxmacosmacos-appmenubar-appnotchopen-sourceswiftswiftuiwindows
Plan usage relay: coucou-hook --statusline and its installer
Claude1190fab3e697
diff --git a/windows/hook/src/main.rs b/windows/hook/src/main.rsindex 4cd62465..3fa87d1b 100644--- a/windows/hook/src/main.rs+++ b/windows/hook/src/main.rs@@ -14,7 +14,10 @@//! island is the whole point. No answer means empty stdout, and Claude Code//! asks in the terminal exactly as if Coucou were not installed.//!-//! Usage: `coucou-hook <EventName>` (the name is also read from the JSON).+//! Usage: `coucou-hook <EventName>` (the name is also read from the JSON), or+//! `coucou-hook --statusline` as Claude Code's status line command (plan usage,+//! see statusline.rs): it passes the plan limits on and runs the status line the+//! user had before, so that keeps working.use std::io::{Read, Write};use std::sync::mpsc;@@ -34,6 +37,8 @@ const DROPPED_FIELDS: &[&str] = &["tool_response", "transcript_path"];/// less than this anyway.const MAX_FIELD_LEN: usize = 2_000;+mod statusline;+#[cfg(windows)]mod win;#[cfg(windows)]@@ -45,6 +50,9 @@ mod unix;use unix::connect;fn main() {+ if std::env::args().skip(1).any(|a| a == "--statusline") {+ statusline::run();+ }let Some((payload, event, question)) = read_event() else { std::process::exit(0) };let waits_for_answer = event == "PermissionRequest";diff --git a/windows/hook/src/statusline.rs b/windows/hook/src/statusline.rsnew file mode 100644index 00000000..2d135eb6--- /dev/null+++ b/windows/hook/src/statusline.rs@@ -0,0 +1,338 @@+//! `coucou-hook --statusline`: Claude Code's status line command, for the plan+//! usage pill.+//!+//! Claude Code hands its status line command the session's JSON on stdin, and+//! whatever that command prints becomes the status line. Coucou only wants the+//! plan limits (`rate_limits`) out of it: they go on to the app in the+//! background and nothing else of the input does. If the user had a status line+//! of their own, it is run the way Claude Code runs it — `/bin/sh -c` on Linux,+//! Git Bash's `bash -c` on Windows — with the same input, and what it prints is+//! passed on untouched, so it keeps working.+//!+//! Never blocking Claude Code: the app gets [`APP_BUDGET`] at most, the user's+//! own status line [`PREVIOUS_BUDGET`] (then it is killed and prints nothing), and+//! no more than [`MAX_OUTPUT`] bytes of what it prints are kept.++use std::io::{Read, Write};+use std::path::{Path, PathBuf};+use std::process::{Command, Stdio};+use std::sync::{mpsc, Arc, Mutex};+use std::time::{Duration, Instant};++use crate::{talk, truncate_strings, CONNECT_TIMEOUT};++/// How long the app may take to take the limits. Same 300 ms as a hook connect.+const APP_BUDGET: Duration = CONNECT_TIMEOUT;+/// How long the user's own status line may take before we give up on it (the+/// Mac's relay allows the same).+const PREVIOUS_BUDGET: Duration = Duration::from_secs(10);+/// What is kept of the user's status line output. A status line is a line or+/// two; anything past this is drained and dropped so the command never stalls+/// on a full pipe.+const MAX_OUTPUT: usize = 64 * 1024;+/// After the command has exited, how long its output may still take to arrive+/// (a background child of it can hold the pipe open forever).+const DRAIN_GRACE: Duration = Duration::from_millis(200);++/// Saved by the app next to this program when the relay took the status line.+const PREVIOUS_FILE: &str = "statusline-previous.json";++pub fn run() -> ! {+ let mut raw = Vec::new();+ let _ = std::io::stdin().read_to_end(&mut raw);+ if raw.starts_with(&[0xEF, 0xBB, 0xBF]) {+ raw.drain(..3);+ }++ // The limits go on in the background, never delaying the status line.+ let sent = serde_json::from_slice::<serde_json::Value>(&raw)+ .ok()+ .and_then(|v| payload(v.as_object()?))+ .map(|line| {+ let (tx, rx) = mpsc::channel();+ std::thread::spawn(move || {+ let _ = tx.send(talk(&line, false));+ });+ rx+ });++ if let Some(command) = previous_command() {+ if let Some(out) = run_previous(&command, &raw, PREVIOUS_BUDGET) {+ let mut stdout = std::io::stdout();+ let _ = stdout.write_all(&out);+ let _ = stdout.flush();+ }+ }+ if let Some(rx) = sent {+ let _ = rx.recv_timeout(APP_BUDGET);+ }+ std::process::exit(0);+}++/// The one line the app gets from a status line call: the limits and which+/// session they came from, nothing else (no cwd, no model, no transcript).+/// Without limits — API-key users — there is nothing to send.+pub fn payload(map: &serde_json::Map<String, serde_json::Value>) -> Option<String> {+ let limits = map.get("rate_limits").filter(|v| v.is_object())?;+ let mut value = serde_json::json!({+ "hook_event_name": "StatusLine",+ "session_id": map.get("session_id").cloned().unwrap_or(serde_json::Value::Null),+ "rate_limits": limits,+ });+ truncate_strings(&mut value);+ let mut line = value.to_string();+ line.push('\n');+ Some(line)+}++/// The command of the status line the user had before the relay took its place.+fn previous_command() -> Option<String> {+ let path = std::env::current_exe().ok()?.with_file_name(PREVIOUS_FILE);+ let saved: serde_json::Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;+ saved.get("command")?.as_str().filter(|c| !c.trim().is_empty()).map(str::to_string)+}++/// The shell Claude Code runs a status line command with.+#[cfg(unix)]+fn shell(command: &str) -> Option<Command> {+ let mut c = Command::new("/bin/sh");+ c.args(["-c", command]);+ Some(c)+}++/// On Windows Claude Code runs status line commands through Git Bash, so a+/// command written for it (`~/bin/line.sh`, `$HOME`, pipes into `jq`…) only+/// works there. No Git Bash found: nothing is run rather than guessing with+/// `cmd`, which would mangle such a command.+#[cfg(windows)]+fn shell(command: &str) -> Option<Command> {+ use std::os::windows::process::CommandExt;+ const CREATE_NO_WINDOW: u32 = 0x0800_0000;+ let bash = git_bash_candidates(|k| std::env::var_os(k), |p| p.is_file()).into_iter().next()?;+ let mut c = Command::new(bash);+ c.args(["-c", command]).creation_flags(CREATE_NO_WINDOW);+ Some(c)+}++/// Where Git Bash may be, best first, keeping only those `exists` accepts:+/// Claude Code's own override (`CLAUDE_CODE_GIT_BASH_PATH`), the Git for Windows+/// that `git.exe` on PATH belongs to, the usual install folders, then any+/// `bash.exe` on PATH — except Windows' own WSL launcher (System32, WindowsApps),+/// which would run the command in Linux instead.+#[cfg_attr(not(windows), allow(dead_code))]+fn git_bash_candidates(+ var: impl Fn(&str) -> Option<std::ffi::OsString>,+ exists: impl Fn(&Path) -> bool,+) -> Vec<PathBuf> {+ let mut out: Vec<PathBuf> = Vec::new();+ if let Some(p) = var("CLAUDE_CODE_GIT_BASH_PATH").filter(|p| !p.is_empty()) {+ out.push(PathBuf::from(p));+ }+ let path_dirs: Vec<PathBuf> = var("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default();+ // …\Git\cmd\git.exe, …\Git\bin\git.exe or …\Git\mingw64\bin\git.exe.+ for dir in path_dirs.iter().filter(|d| exists(&d.join("git.exe"))) {+ if let Some(root) = dir.parent() {+ out.push(root.join("bin").join("bash.exe"));+ if let Some(up) = root.parent() {+ out.push(up.join("bin").join("bash.exe"));+ }+ }+ }+ for base in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {+ if let Some(dir) = var(base).filter(|p| !p.is_empty()) {+ out.push(PathBuf::from(dir).join("Git").join("bin").join("bash.exe"));+ }+ }+ if let Some(dir) = var("LOCALAPPDATA").filter(|p| !p.is_empty()) {+ out.push(PathBuf::from(dir).join("Programs").join("Git").join("bin").join("bash.exe"));+ }+ for dir in &path_dirs {+ let windows_own = dir.components().any(|c| {+ let c = c.as_os_str().to_string_lossy();+ c.eq_ignore_ascii_case("system32") || c.eq_ignore_ascii_case("windowsapps")+ });+ if !windows_own {+ out.push(dir.join("bash.exe"));+ }+ }+ let mut seen = Vec::new();+ out.retain(|p| {+ let fresh = !seen.contains(p) && exists(p);+ seen.push(p.clone());+ fresh+ });+ out+}++/// Runs `command` through the status line shell with `input` on stdin and+/// returns what it printed (at most [`MAX_OUTPUT`] bytes), or nothing if it could+/// not start or ran past `budget` (then it is killed).+pub fn run_previous(command: &str, input: &[u8], budget: Duration) -> Option<Vec<u8>> {+ let mut child = shell(command)?+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .spawn()+ .ok()?;++ // Feed and drain on their own threads: a long input or output cannot wedge us.+ let mut stdin = child.stdin.take()?;+ let data = input.to_vec();+ std::thread::spawn(move || {+ let _ = stdin.write_all(&data);+ // Dropped here: the command sees the end of its input.+ });+ let mut stdout = child.stdout.take()?;+ let kept = Arc::new(Mutex::new(Vec::new()));+ let (done_tx, done_rx) = mpsc::channel::<()>();+ {+ let kept = Arc::clone(&kept);+ std::thread::spawn(move || {+ let mut chunk = [0u8; 8192];+ loop {+ match stdout.read(&mut chunk) {+ Ok(0) | Err(_) => break,+ Ok(n) => {+ let mut buf = kept.lock().unwrap_or_else(|e| e.into_inner());+ let room = MAX_OUTPUT.saturating_sub(buf.len());+ buf.extend_from_slice(&chunk[..n.min(room)]);+ }+ }+ }+ let _ = done_tx.send(());+ });+ }++ let deadline = Instant::now() + budget;+ loop {+ match child.try_wait() {+ Ok(Some(_)) => break,+ Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(10)),+ _ => {+ let _ = child.kill();+ let _ = child.wait();+ return None;+ }+ }+ }+ // Whatever arrived; a child process of the command holding the pipe open+ // does not get to hold us too.+ let _ = done_rx.recv_timeout(DRAIN_GRACE);+ let out = std::mem::take(&mut *kept.lock().unwrap_or_else(|e| e.into_inner()));+ Some(out)+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::collections::HashMap;+ use std::ffi::OsString;++ #[test]+ fn only_the_limits_and_the_session_go_to_the_app() {+ let input = serde_json::json!({+ "session_id": "s1", "cwd": "/secret", "model": { "id": "x" },+ "transcript_path": "/home/me/.claude/x.jsonl",+ "rate_limits": { "five_hour": { "used_percentage": 42, "resets_at": 1 } }+ });+ let line = payload(input.as_object().unwrap()).unwrap();+ assert!(line.ends_with('\n'));+ let v: serde_json::Value = serde_json::from_str(line.trim()).unwrap();+ assert_eq!(v["hook_event_name"], "StatusLine");+ assert_eq!(v["session_id"], "s1");+ assert_eq!(v["rate_limits"]["five_hour"]["used_percentage"], 42);+ assert_eq!(v.as_object().unwrap().len(), 3);+ }++ #[test]+ fn without_limits_nothing_is_sent() {+ // API-key users get no rate_limits.+ assert!(payload(serde_json::json!({ "session_id": "s1" }).as_object().unwrap()).is_none());+ assert!(payload(serde_json::json!({ "rate_limits": "x" }).as_object().unwrap()).is_none());+ }++ #[cfg(unix)]+ #[test]+ fn the_users_own_status_line_gets_the_same_input_and_its_output_comes_back() {+ let out = run_previous("cat; echo ' tail'", b"{\"a\":1}", Duration::from_secs(5)).unwrap();+ assert_eq!(String::from_utf8(out).unwrap(), "{\"a\":1} tail\n");+ }++ #[cfg(unix)]+ #[test]+ fn a_status_line_that_hangs_is_killed_and_prints_nothing() {+ let started = Instant::now();+ assert!(run_previous("sleep 5", b"{}", Duration::from_millis(200)).is_none());+ assert!(started.elapsed() < Duration::from_secs(2));+ }++ #[cfg(unix)]+ #[test]+ fn a_flood_of_output_is_cut_and_never_stalls_the_command() {+ let started = Instant::now();+ let out = run_previous("head -c 1000000 /dev/zero", b"", Duration::from_secs(5)).unwrap();+ assert_eq!(out.len(), MAX_OUTPUT);+ assert!(started.elapsed() < Duration::from_secs(3));+ }++ #[cfg(unix)]+ #[test]+ fn a_background_child_holding_the_pipe_does_not_hold_us() {+ let started = Instant::now();+ let out = run_previous("echo hi; (sleep 5 &) ", b"", Duration::from_secs(5)).unwrap();+ assert_eq!(String::from_utf8(out).unwrap(), "hi\n");+ assert!(started.elapsed() < Duration::from_secs(2));+ }++ fn env(pairs: &[(&str, OsString)]) -> impl Fn(&str) -> Option<OsString> {+ let map: HashMap<String, OsString> = pairs.iter().map(|(k, v)| (k.to_string(), v.clone())).collect();+ move |k| map.get(k).cloned()+ }++ fn path_var(dirs: &[&str]) -> OsString {+ std::env::join_paths(dirs.iter().map(PathBuf::from)).unwrap()+ }++ #[test]+ fn git_bash_is_found_the_way_claude_code_finds_it() {+ let files = [+ "/override/bash.exe",+ "/git/cmd/git.exe",+ "/git/bin/bash.exe",+ "/pf/Git/bin/bash.exe",+ "/wsl/System32/bash.exe",+ "/msys/usr/bin/bash.exe",+ ];+ let exists = |p: &Path| files.iter().any(|f| Path::new(f) == p);++ // Claude Code's own override wins.+ let all = git_bash_candidates(+ env(&[+ ("CLAUDE_CODE_GIT_BASH_PATH", "/override/bash.exe".into()),+ ("PATH", path_var(&["/wsl/System32", "/git/cmd", "/msys/usr/bin"])),+ ("ProgramFiles", "/pf".into()),+ ]),+ exists,+ );+ assert_eq!(+ all,+ vec![+ PathBuf::from("/override/bash.exe"),+ PathBuf::from("/git/bin/bash.exe"),+ PathBuf::from("/pf/Git/bin/bash.exe"),+ PathBuf::from("/msys/usr/bin/bash.exe"),+ ]+ );++ // The WSL launcher in System32 is never taken for Git Bash.+ let none = git_bash_candidates(env(&[("PATH", path_var(&["/wsl/System32"]))]), exists);+ assert!(none.is_empty());++ // A missing override falls through to git.exe's own install.+ let found = git_bash_candidates(+ env(&[("CLAUDE_CODE_GIT_BASH_PATH", "/nope/bash.exe".into()), ("PATH", path_var(&["/git/cmd"]))]),+ exists,+ );+ assert_eq!(found, vec![PathBuf::from("/git/bin/bash.exe")]);+ }+}diff --git a/windows/src-tauri/src/hooks.rs b/windows/src-tauri/src/hooks.rsindex 3da1d0e5..31ee2cd5 100644--- a/windows/src-tauri/src/hooks.rs+++ b/windows/src-tauri/src/hooks.rs@@ -40,6 +40,8 @@ const MARKER: &str = "coucou-hook";#[serde(rename_all = "camelCase")]pub struct HookStatus {pub installed: bool,+ /// Coucou's status line relay (plan usage) is the one in settings.json.+ pub plan_relay_installed: bool,pub settings_path: String,pub hook_path: String,pub hook_ready: bool,@@ -139,6 +141,12 @@ fn entry_is_ours(entry: &Value) -> bool {.unwrap_or(false)}+/// The status line in settings.json is Coucou's relay (old installs wrote+/// `coucou-hook StatusLine`, new ones `coucou-hook --statusline`; both match).+fn status_line_is_ours(v: &Value) -> bool {+ v.get("command").and_then(Value::as_str).is_some_and(|c| c.contains(MARKER))+}+/// Settings with Coucou's hooks added; everything else is left untouched.fn merged(existing: &Value) -> Value {let mut root = existing.as_object().cloned().unwrap_or_default();@@ -253,6 +261,7 @@ pub fn status() -> HookStatus {let hook_path = settings::hook_exe_path();HookStatus {installed,+ plan_relay_installed: plan_relay_installed(¤t),settings_path: settings_path().to_string_lossy().to_string(),hook_ready: hook_path.exists(),hook_path: hook_path.to_string_lossy().to_string(),@@ -260,10 +269,19 @@ pub fn status() -> HookStatus {}pub fn preview(install: bool) -> Result<HookPreview, String> {+ preview_with(|current| if install { merged(current) } else { without_ours(current) }, pretty)+}++/// The diff of what `next` makes of settings.json, shown with `view` (the whole+/// file, or just the key that changes).+fn preview_with(+ next: impl Fn(&Value) -> Value,+ view: fn(&Value) -> String,+) -> Result<HookPreview, String> {let current = read_settings()?;- let next = if install { merged(¤t) } else { without_ours(¤t) };+ let next = next(¤t);Ok(HookPreview {- diff: unified_diff(&pretty(¤t), &pretty(&next)),+ diff: unified_diff(&view(¤t), &view(&next)),backup: backup_path().to_string_lossy().to_string(),settings_path: settings_path().to_string_lossy().to_string(),fingerprint: current_fingerprint(),@@ -277,6 +295,10 @@ pub fn preview(install: bool) -> Result<HookPreview, String> {/// and make them look at a fresh diff, because the only thing worse than not/// installing the hooks is silently reverting somebody else's edit.pub fn write(install: bool, fingerprint: &str) -> Result<String, String> {+ write_with(|current| if install { merged(current) } else { without_ours(current) }, fingerprint)+}++fn write_with(next: impl Fn(&Value) -> Value, fingerprint: &str) -> Result<String, String> {let path = settings_path();let dir = path.parent().unwrap_or(Path::new("."));std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;@@ -296,7 +318,7 @@ pub fn write(install: bool, fingerprint: &str) -> Result<String, String> {std::fs::copy(&path, &backup).map_err(|e| format!("backup failed: {e}"))?;}- let next = if install { merged(¤t) } else { without_ours(¤t) };+ let next = next(¤t);let mut text = pretty(&next);text.push('\n');@@ -319,6 +341,99 @@ pub fn write(install: bool, fingerprint: &str) -> Result<String, String> {Ok(backup.to_string_lossy().to_string())}+// ── Status line (plan usage) ──────────────────────────────────────────────────+//+// Claude Code runs one `statusLine` command and hands it the plan limits. Coucou+// puts its relay there; a status line the user already had is kept in+// statusline-previous.json beside the relay, and the relay still runs it, so it+// keeps working. Installing and removing it is separate from the hooks.++/// Where the user's own status line waits while the relay stands in for it.+pub fn status_line_previous_path() -> PathBuf {+ settings::hook_exe_path().with_file_name("statusline-previous.json")+}++fn read_status_line_previous() -> Option<Value> {+ let bytes = std::fs::read(status_line_previous_path()).ok()?;+ serde_json::from_slice::<Value>(&bytes).ok().filter(Value::is_object)+}++/// True when the `statusLine` in settings.json is Coucou's relay.+pub fn plan_relay_installed(settings: &Value) -> bool {+ settings.get("statusLine").is_some_and(status_line_is_ours)+}++/// `statusLine` as it reads after installing or removing the relay. `None`: the+/// key goes. Installing swaps only `command`, so `padding`, `refreshInterval`+/// and the rest of the user's status line stay as they were.+fn status_line_after(existing: Option<&Value>, install: bool, previous: Option<&Value>) -> Option<Value> {+ if install {+ let mut sl = existing.filter(|v| v.is_object()).cloned().unwrap_or_else(|| json!({}));+ let obj = sl.as_object_mut().expect("an object");+ obj.entry("type").or_insert_with(|| json!("command"));+ obj.insert("command".into(), json!(hook_command("--statusline")));+ Some(sl)+ } else if existing.is_some_and(status_line_is_ours) {+ previous.cloned()+ } else {+ existing.cloned() // not ours any more (the user changed it): leave it alone+ }+}++fn status_line_settings(current: &Value, install: bool, previous: Option<&Value>) -> Value {+ let mut root = current.as_object().cloned().unwrap_or_default();+ match status_line_after(root.get("statusLine"), install, previous) {+ Some(sl) => root.insert("statusLine".into(), sl),+ None => root.remove("statusLine"),+ };+ Value::Object(root)+}++/// Only the `statusLine` key, which is all the diff of this change is about.+fn status_line_view(settings: &Value) -> String {+ pretty(&json!({ "statusLine": settings.get("statusLine").cloned().unwrap_or(Value::Null) }))+}++/// The diff the user has to look at before the relay goes in or out.+pub fn status_line_preview(install: bool) -> Result<HookPreview, String> {+ let previous = read_status_line_previous();+ preview_with(|current| status_line_settings(current, install, previous.as_ref()), status_line_view)+}++/// Installs or removes the relay, after the same backup and fingerprint checks as+/// the hooks. Installing first saves a status line of the user's own, removing+/// puts it back (or removes the key if there was none).+pub fn status_line_write(install: bool, fingerprint: &str) -> Result<String, String> {+ let before = read_settings()?;+ let previous = read_status_line_previous();+ let own = before.get("statusLine").filter(|v| !status_line_is_ours(v)).cloned();+ let saved = install && own.is_some() && save_status_line_previous(own.as_ref().expect("some")).is_ok();+ if install && own.is_some() && !saved {+ return Err("could not save your current status line next to the relay; nothing was changed".into());+ }+ let backup = write_with(|current| status_line_settings(current, install, previous.as_ref()), fingerprint);+ match &backup {+ // Back in settings.json: the saved copy has done its job.+ Ok(_) if !install => {+ let _ = std::fs::remove_file(status_line_previous_path());+ }+ // Nothing was written: do not leave a stale copy behind.+ Err(_) if saved => {+ let _ = std::fs::remove_file(status_line_previous_path());+ }+ _ => {}+ }+ backup+}++fn save_status_line_previous(status_line: &Value) -> std::io::Result<()> {+ let path = status_line_previous_path();+ if let Some(dir) = path.parent() {+ std::fs::create_dir_all(dir)?;+ }+ write_like(&path, &path, pretty(status_line).as_bytes())+}+/// Writes `bytes` to `temp`, which is about to replace `original`.////// On Linux a fresh file would get the umask's 0644, and settings.json can hold@@ -511,6 +626,49 @@ mod tests {const WHERE: &str = "settings.json";+ #[test]+ fn the_hooks_leave_the_status_line_alone() {+ let theirs = json!({ "statusLine": { "type": "command", "command": "~/bin/my-line" } });+ assert_eq!(merged(&theirs)["statusLine"], theirs["statusLine"]);+ assert_eq!(without_ours(&theirs)["statusLine"], theirs["statusLine"]);+ assert!(merged(&json!({})).get("statusLine").is_none());+ }++ #[test]+ fn the_relay_takes_the_status_line_and_keeps_the_users_other_fields() {+ // None yet: ours is added.+ let fresh = status_line_settings(&json!({ "model": "opus" }), true, None);+ assert!(status_line_is_ours(&fresh["statusLine"]));+ assert_eq!(fresh["statusLine"]["type"], "command");+ assert_eq!(fresh["model"], "opus");++ // Their own: only the command is swapped; padding and refresh stay.+ let own = json!({ "statusLine": { "type": "command", "command": "~/bin/my-line", "padding": 2, "refreshInterval": 5 } });+ let taken = status_line_settings(&own, true, None);+ assert!(status_line_is_ours(&taken["statusLine"]));+ assert_eq!(taken["statusLine"]["padding"], 2);+ assert_eq!(taken["statusLine"]["refreshInterval"], 5);++ // Installing again keeps ours and its extra fields.+ let again = status_line_settings(&taken, true, None);+ assert_eq!(again["statusLine"]["padding"], 2);+ assert!(status_line_is_ours(&again["statusLine"]));+ }++ #[test]+ fn removing_the_relay_restores_what_was_there_and_never_touches_anything_else() {+ let previous = json!({ "type": "command", "command": "~/bin/my-line", "padding": 2 });+ let ours = status_line_settings(&json!({}), true, None);++ // There was one before: it comes back exactly.+ assert_eq!(status_line_settings(&ours, false, Some(&previous))["statusLine"], previous);+ // There was none: the key goes.+ assert!(status_line_settings(&ours, false, None).get("statusLine").is_none());+ // The user changed it since: not ours, so untouched.+ let theirs = json!({ "statusLine": { "type": "command", "command": "~/bin/other" } });+ assert_eq!(status_line_settings(&theirs, false, Some(&previous))["statusLine"], theirs["statusLine"]);+ }+#[test]fn a_utf8_bom_is_stripped_not_treated_as_corruption() {// PowerShell 5's `Set-Content -Encoding utf8` produces exactly this.