All your machines, one app. For you and your AI agents: agent sessions, desktops, files, logs and GitHub across your Macs, Linux and Windows machines, with an MCP server.
Windows ops scripts: errors as their message, logs that don't stop, UTF-8 both ways (#28)
Adib Hanna965f6d8b56b0
diff --git a/src/fleet/workspaces/transport.rs b/src/fleet/workspaces/transport.rsindex a7aeea5..a56c6df 100644--- a/src/fleet/workspaces/transport.rs+++ b/src/fleet/workspaces/transport.rs@@ -15,7 +15,7 @@ use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};use tokio::process::Command;use crate::config::MachineSpec;-use crate::ops::remote::clean_line;+use crate::ops::remote::{clean_line, clixml_text};use crate::probe;/// sh-family login shells read the script from stdin as a login shell; anything@@ -75,20 +75,6 @@ impl Output {}}-/// The text of PowerShell's CLIXML error records (`<S S="Error">…</S>`), as-/// lines; anything else as it is.-pub fn clixml_text(stderr: &str) -> String {- if !stderr.contains("<S S=\"Error\">") {- return stderr.to_string();- }- let mut out = String::new();- for part in stderr.split("<S S=\"Error\">").skip(1) {- let text = part.split("</S>").next().unwrap_or("");- out.push_str(&text.replace("_x000D__x000A_", "\n").replace("'", "'").replace(""", "\"").replace("<", "<").replace(">", ">").replace("&", "&"));- }- out-}-pub fn new_marker() -> String {format!("__muxen_{}__", super::random_id(12))}diff --git a/src/ops/mod.rs b/src/ops/mod.rsindex 63b9ac9..2a70311 100644--- a/src/ops/mod.rs+++ b/src/ops/mod.rs@@ -1522,6 +1522,66 @@ mod engine_tests {let _ = std::fs::remove_dir_all(&tmp);}+ /// How Muxin reads what its PowerShell scripts print on a real Windows+ /// machine, which keeps nothing: text both ways, output that isn't UTF-8,+ /// and errors as their message, not CLIXML.+ /// Run with: MUXEN_TEST_WINDOWS_HOST=<ssh host> cargo test windows_script_output -- --ignored+ #[tokio::test(flavor = "multi_thread")]+ #[ignore = "needs a Windows machine: MUXEN_TEST_WINDOWS_HOST=<ssh host>"]+ async fn windows_script_output_on_real_host() {+ let Ok(host) = std::env::var("MUXEN_TEST_WINDOWS_HOST") else { return };+ let tmp = std::env::temp_dir().join(format!("muxen-windows-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&tmp);+ std::fs::create_dir_all(&tmp).unwrap();+ std::fs::write(tmp.join("config.toml"), format!("[[machine]]\nname = \"Box\"\nhost = \"{host}\"\n")).unwrap();+ let engine = Engine::new(Paths::resolve(Some(tmp.clone()), None), false);+ engine.run_check(None).await;+ let (spec, probe) = engine.machine("box").unwrap();+ let probe = probe.expect("checked");+ assert!(probe.ok, "{:?}", probe.error);+ let shell = remote::shell_for(&spec, Some(&probe));+ assert_eq!(shell, Shell::Powershell, "{host} isn't Windows");+ let run_script = |script: String| {+ let engine = engine.clone();+ let spec = spec.clone();+ async move {+ let op = engine.begin_op("test", "test".into(), Some("box".into()), None);+ let ran = remote::run(&engine, op, &spec, shell, script, &[], CONTROL_TIMEOUT).await;+ engine.op_finish(op, Ok(()));+ (ran, op_log(&engine, op).await)+ }+ };++ // 1. Text both ways; a program printing in the console's code page, as+ // config.cmd does; and bytes that aren't UTF-8, with output after them.+ let script = "$arch = 'x64'\nWrite-Output \"for win-$arch…\"\nWrite-Output '✓ café'\n\+ & powershell -NoProfile -Command \"[Console]::Out.WriteLine([string][char]0x221A + ' Connected to GitHub')\"\n\+ $o = [Console]::OpenStandardOutput(); $o.Write([byte[]](0xFB, 0x20, 0x34, 0x33, 0x37, 0x0A), 0, 6); $o.Flush()\n\+ Write-Output 'read after it'\n";+ let (ran, log) = run_script(script.into()).await;+ assert!(ran.is_ok(), "{ran:?} {log:?}");+ for line in ["for win-x64…", "✓ café", "√ Connected to GitHub", "\u{FFFD} 437", "read after it"] {+ assert!(log.contains(&line.to_string()), "{line:?} not in {log:?}");+ }++ // 2. control.ps1's trap: the error is the message.+ let dir = format!("C:\\muxen-test-no-such-dir-{}", std::process::id());+ let params = [("OR_ACTION", Param::Str("logs")), ("OR_DIR", Param::Str(&dir)), ("OR_TOKEN", Param::Str("")), ("OR_DELETE", Param::Bool(false))];+ let (ran, log) = run_script(with_params(shell, ¶ms, CONTROL_PS1)).await;+ assert_eq!(ran, Err(format!("{dir} doesn't exist.")), "{log:?}");++ // 3. PowerShell's own records (a warning, an error that doesn't stop it),+ // which it writes as CLIXML when it exits, after the trap's line.+ let script = "$ErrorActionPreference = 'Stop'\ntrap { [Console]::Error.WriteLine(\"error: \" + $_.Exception.Message); exit 1 }\n\+ Write-Warning 'careful'\nWrite-Error 'not the end' -ErrorAction Continue\nthrow 'the end, ünïcode'\n";+ let (ran, log) = run_script(script.into()).await;+ assert_eq!(ran, Err("the end, ünïcode".to_string()), "{log:?}");+ assert!(log.iter().all(|l| !l.contains("<Objs") && !l.contains("CLIXML") && !l.contains("Invoke-Expression")), "{log:?}");+ assert!(log.contains(&"WARNING: careful".to_string()) && log.contains(&"not the end".to_string()), "{log:?}");++ let _ = std::fs::remove_dir_all(&tmp);+ }+#[tokio::test(flavor = "multi_thread")]#[ignore = "slow: runs the demo's simulated delays (~15s)"]async fn demo_install_stop_remove() {diff --git a/src/ops/remote.rs b/src/ops/remote.rsindex 806ed13..0283f9f 100644--- a/src/ops/remote.rs+++ b/src/ops/remote.rs@@ -6,7 +6,7 @@ use std::process::Stdio;use std::sync::Arc;use std::time::Duration;-use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};+use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncRead, AsyncWriteExt, BufReader};use tokio::process::Command;use crate::config::MachineSpec;@@ -17,8 +17,13 @@ use crate::probe::{self, ProbeResult, Shell};/// stdin line by line and breaks multi-line blocks, so the script is read/// whole; and Windows' OpenSSH doesn't always pass on the end of stdin once/// a script is a few KB, so reading to the end could wait forever.)+///+/// The script is read as UTF-8 (`[Console]::In` would read it in the console's+/// code page, and "…" would turn into letters that join a variable's name), and+/// written out as UTF-8: PowerShell's own output, and through the console's code+/// page, programs it runs that honor it.pub(crate) const PS_END: &str = "#muxen-end";-const PS_READ_STDIN: &str = "$ProgressPreference = 'SilentlyContinue'; $b = New-Object Text.StringBuilder; while ((($l = [Console]::In.ReadLine()) -ne $null) -and ($l -ne '#muxen-end')) { [void]$b.AppendLine($l) }; $b.ToString() | Invoke-Expression";+const PS_READ_STDIN: &str = "$ProgressPreference = 'SilentlyContinue'; $or_utf8 = New-Object Text.UTF8Encoding $false; try { [Console]::OutputEncoding = $or_utf8 } catch {}; $or_in = New-Object IO.StreamReader -ArgumentList ([Console]::OpenStandardInput()), $or_utf8; $b = New-Object Text.StringBuilder; while ((($l = $or_in.ReadLine()) -ne $null) -and ($l -ne '#muxen-end')) { [void]$b.AppendLine($l) }; $b.ToString() | Invoke-Expression";/// PowerShell's arguments to run a script sent on stdin (see `ps_sendable`),/// encoded so no shell on the way changes them.@@ -33,7 +38,6 @@ pub(crate) fn ps_stdin_args() -> Vec<String> {pub(crate) fn ps_sendable(script: &str) -> String {format!("{}\n{PS_END}\n", script.trim_end_matches(['\r', '\n']))}-const STDERR_TAIL: usize = 4;/// The shell a machine speaks: pinned in config.toml, else what the last check used, else by OS.pub fn shell_for(spec: &MachineSpec, probe: Option<&ProbeResult>) -> Shell {@@ -94,8 +98,8 @@ pub(crate) fn ps_quote(s: &str) -> String {}/// Runs `script` on the machine, forwarding every output line (secrets masked) to-/// the operation log. Errors carry the last stderr lines, which is where the-/// scripts put their `error: ...` explanation.+/// the operation log. Errors carry the script's `error: ...` explanation from+/// stderr, else its last stderr line.pub async fn run(engine: &Arc<Engine>,op: u64,@@ -136,49 +140,15 @@ pub async fn run_lines(let _ = stdin.write_all(script.as_bytes()).await;drop(stdin);- let mut out_lines = BufReader::new(stdout).lines();- let mut err_lines = BufReader::new(stderr).lines();- let mut tail: Vec<String> = Vec::new();- let mut printed: Vec<String> = Vec::new();- let (mut out_open, mut err_open) = (true, true);- while out_open || err_open {- tokio::select! {- line = out_lines.next_line(), if out_open => match line {- Ok(Some(l)) => {- log_line(engine, op, &l, secrets);- printed.push(l);- }- _ => out_open = false,- },- line = err_lines.next_line(), if err_open => match line {- Ok(Some(l)) => {- let clean = clean_line(&l, secrets);- if !clean.trim().is_empty() {- tail.push(clean.clone());- if tail.len() > STDERR_TAIL {- tail.remove(0);- }- engine.op_log(op, clean);- }- }- _ => err_open = false,- },- }- }+ let (printed, reason) = read_output(stdout, stderr, shell, secrets, |l| engine.op_log(op, l)).await;let status = child.wait().await.map_err(|e| e.to_string())?;if status.success() {Ok(printed)} else {- let reason = tail- .iter()- .rev()- .find_map(|l| l.strip_prefix("error: ").map(str::to_string))- .or_else(|| tail.last().cloned())- .unwrap_or_else(|| match status.code() {- Some(c) => format!("The script exited with status {c}."),- None => "The script was terminated.".into(),- });- Err(reason.trim_start_matches("Write-Error: ").to_string())+ Err(reason.unwrap_or_else(|| match status.code() {+ Some(c) => format!("The script exited with status {c}."),+ None => "The script was terminated.".into(),+ }))}};@@ -188,6 +158,179 @@ pub async fn run_lines(}}+/// Reads a script's stdout and stderr to their ends, passing each cleaned line+/// to `log`. Returns what it printed (stdout, line by line) and what stderr+/// says went wrong, if anything (see `Reason`).+///+/// Lines are read as bytes: Windows programs write in the console's code page+/// (config.cmd's "√ Connected to GitHub"), which isn't always UTF-8, and a line+/// like that mustn't end the reading (or leave the script blocked on a full pipe).+async fn read_output(+ stdout: impl AsyncRead + Unpin,+ stderr: impl AsyncRead + Unpin,+ shell: Shell,+ secrets: &[String],+ mut log: impl FnMut(String),+) -> (Vec<String>, Option<String>) {+ let (mut stdout, mut stderr) = (BufReader::new(stdout), BufReader::new(stderr));+ let (mut out_buf, mut err_buf) = (Vec::new(), Vec::new());+ let mut printed: Vec<String> = Vec::new();+ let mut reason = Reason::default();+ let (mut out_open, mut err_open) = (true, true);+ while out_open || err_open {+ tokio::select! {+ line = read_line(&mut stdout, &mut out_buf), if out_open => match line {+ Some(l) => {+ let clean = clean_line(&l, secrets);+ if !clean.trim().is_empty() {+ log(clean);+ }+ printed.push(l);+ }+ None => out_open = false,+ },+ line = read_line(&mut stderr, &mut err_buf), if err_open => match line {+ Some(l) => {+ for clean in stderr_lines(shell, &l, secrets) {+ reason.see(shell, &clean);+ log(clean);+ }+ }+ None => err_open = false,+ },+ }+ }+ (printed, reason.get())+}++/// The next line (without its line ending), with bytes that aren't UTF-8+/// replaced; None at the end. Partial lines stay in `buf`, so a `select!` can+/// drop this and call it again.+async fn read_line(r: &mut (impl AsyncBufRead + Unpin), buf: &mut Vec<u8>) -> Option<String> {+ match r.read_until(b'\n', buf).await {+ Ok(_) if !buf.is_empty() => {+ let line = String::from_utf8_lossy(buf).trim_end_matches(['\n', '\r']).to_string();+ buf.clear();+ Some(line)+ }+ _ => None,+ }+}++/// A stderr line as the lines of text it holds, cleaned, blank ones left out.+/// PowerShell writes its errors as CLIXML when stderr isn't a terminal.+fn stderr_lines(shell: Shell, line: &str, secrets: &[String]) -> Vec<String> {+ let text = if shell == Shell::Powershell { clixml_text(line) } else { line.to_string() };+ text.lines().map(|l| clean_line(l, secrets)).filter(|l| !l.trim().is_empty()).collect()+}++/// Why a script failed, from its stderr: its last `error: ...` line, else its+/// last line. Any `error:` line counts, not only the last few: PowerShell writes+/// its error records when it exits, after the trap's `error: ...` line.+#[derive(Default)]+struct Reason {+ error: Option<String>,+ last: Option<String>,+}++impl Reason {+ fn see(&mut self, shell: Shell, line: &str) {+ // The lines PowerShell puts under an error's message (`At line:1 char:5`,+ // `+ <the code>`, `+ CategoryInfo ...`) never say why.+ let line = line.trim();+ if shell == Shell::Powershell && (line.starts_with("At line:") || line.starts_with('+')) {+ return;+ }+ let line = line.trim_start_matches("Write-Error: ");+ // PowerShell can put the command's name first: "Name : error: ...".+ if let Some(message) = line.strip_prefix("error: ").or_else(|| line.split_once(" : error: ").map(|(_, m)| m)) {+ self.error = Some(message.to_string());+ }+ self.last = Some(line.to_string());+ }++ fn get(self) -> Option<String> {+ self.error.or(self.last)+ }+}++/// The text of PowerShell's CLIXML output: `#< CLIXML`, then `<Objs …>` lines+/// whose `<S S="Error">` (and other streams') strings hold the text, one or more+/// lines each. Progress records are left out, other lines kept as they are.+pub fn clixml_text(text: &str) -> String {+ if !text.contains("#< CLIXML") && !text.contains("<Objs ") {+ return text.to_string();+ }+ let mut out = String::new();+ for line in text.lines() {+ let trimmed = line.trim();+ if trimmed == "#< CLIXML" {+ continue;+ }+ if !trimmed.starts_with("<Objs ") {+ out.push_str(line);+ out.push('\n');+ continue;+ }+ for part in trimmed.split("<S S=\"").skip(1) {+ let Some((stream, s)) = part.split_once("\">") else { continue };+ let label = match stream {+ "warning" => "WARNING: ",+ "verbose" => "VERBOSE: ",+ "debug" => "DEBUG: ",+ _ => "",+ };+ for l in clixml_unescape(s.split("</S>").next().unwrap_or("")).lines() {+ if let Some(l) = without_reader(l) {+ out.push_str(label);+ out.push_str(l);+ out.push('\n');+ }+ }+ }+ }+ out+}++/// PowerShell 5.1 starts an error record with the command it ran, Muxin's stdin+/// reader, wrapped to the console's width: "$ProgressPreference = ...", ...,+/// "}; $b.ToString() | Invoke-Expression : <the message>". Keeps the message.+fn without_reader(line: &str) -> Option<&str> {+ let trimmed = line.trim();+ if trimmed.len() >= 20 && PS_READ_STDIN.contains(trimmed) {+ return None;+ }+ match trimmed.split_once(" : ") {+ Some((head, message)) if head.len() >= "Invoke-Expression".len() && PS_READ_STDIN.ends_with(head) => Some(message),+ _ => Some(line),+ }+}++/// A CLIXML string's text: XML's entities, then PowerShell's `_xHHHH_` escapes+/// (UTF-16 code units: line breaks, escape characters; `_x005F_` is "_").+fn clixml_unescape(s: &str) -> String {+ let xml = s.replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'").replace("&", "&");+ let mut out = String::with_capacity(xml.len());+ let mut units: Vec<u16> = Vec::new();+ let mut rest = xml.as_str();+ while let Some(c) = rest.chars().next() {+ let b = rest.as_bytes();+ let escaped = (b.len() >= 7 && b.starts_with(b"_x") && b[6] == b'_' && b[2..6].iter().all(u8::is_ascii_hexdigit))+ .then(|| u16::from_str_radix(&rest[2..6], 16).ok())+ .flatten();+ if let Some(unit) = escaped {+ units.push(unit);+ rest = &rest[7..];+ continue;+ }+ out.extend(char::decode_utf16(units.drain(..)).map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER)));+ out.push(c);+ rest = &rest[c.len_utf8()..];+ }+ out.extend(char::decode_utf16(units.drain(..)).map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER)));+ out+}+/// Runs `script` on the machine and returns what it printed, or why it/// failed (its last `error: ...` line, else its last stderr line).pub async fn output(spec: &MachineSpec, shell: Shell, script: String, timeout: Duration) -> Result<String, String> {@@ -206,15 +349,11 @@ pub async fn output(spec: &MachineSpec, shell: Shell, script: String, timeout: Dif out.status.success() {return Ok(String::from_utf8_lossy(&out.stdout).to_string());}- let err = String::from_utf8_lossy(&out.stderr).to_string();- let lines: Vec<&str> = err.lines().map(str::trim).filter(|l| !l.is_empty()).collect();- Err(lines- .iter()- .rev()- .find_map(|l| l.strip_prefix("error: "))- .or(lines.last().copied())- .map(str::to_string)- .unwrap_or_else(|| format!("It exited with status {}.", out.status.code().unwrap_or(-1))))+ let mut reason = Reason::default();+ for line in String::from_utf8_lossy(&out.stderr).lines().flat_map(|l| stderr_lines(shell, l, &[])) {+ reason.see(shell, &line);+ }+ Err(reason.get().unwrap_or_else(|| format!("It exited with status {}.", out.status.code().unwrap_or(-1))))}fn command(spec: &MachineSpec, shell: Shell) -> Command {@@ -242,13 +381,6 @@ fn command(spec: &MachineSpec, shell: Shell) -> Command {}}-fn log_line(engine: &Arc<Engine>, op: u64, line: &str, secrets: &[String]) {- let clean = clean_line(line, secrets);- if !clean.trim().is_empty() {- engine.op_log(op, clean);- }-}-/// Masks secrets, drops ANSI escapes and carriage-return progress redraws.pub fn clean_line(line: &str, secrets: &[String]) -> String {let line = line.rsplit('\r').find(|s| !s.is_empty()).unwrap_or("");@@ -340,6 +472,118 @@ mod tests {assert_eq!(clean_line("10%\r50%\r100%", &[]), "100%");}+ /// Reads `stdout` and `stderr` like `run_lines`: what it printed, what it+ /// logged, and the failure reason.+ async fn read(shell: Shell, stdout: &[u8], stderr: &[u8]) -> (Vec<String>, Vec<String>, Option<String>) {+ let mut logged = Vec::new();+ let (printed, reason) = read_output(stdout, stderr, shell, &[], |l| logged.push(l)).await;+ (printed, logged, reason)+ }++ /// An error record as Windows PowerShell 5.1 writes it to a redirected+ /// stderr (seen on Windows 11): the command that ran (the stdin reader) and+ /// the message, wrapped at spaces to the console's width, then where it was.+ fn clixml_record(message: &str) -> String {+ let mut pieces = vec![String::new()];+ for word in format!("{PS_READ_STDIN} : {message}").split_inclusive(' ') {+ if pieces.last().unwrap().len() + word.len() > 100 {+ pieces.push(String::new());+ }+ pieces.last_mut().unwrap().push_str(word);+ }+ pieces.extend(+ [+ "At line:3 char:8",+ "+ trap { Write-Error (\"error: \" + $_.Exception.Message); exit 1 }",+ "+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~",+ " + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException",+ " + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException",+ " ",+ ]+ .map(String::from),+ );+ let strings: String = pieces+ .iter()+ .map(|p| format!("<S S=\"Error\">{}_x000D__x000A_</S>", p.replace('&', "&").replace('<', "<").replace('>', ">")))+ .collect();+ format!("<Objs Version=\"1.1.0.1\" xmlns=\"http://schemas.microsoft.com/powershell/2004/04\">{strings}</Objs>")+ }++ #[tokio::test]+ async fn powershell_errors_are_their_message() {+ // What Muxin 0.5.8 got from a failing script on Windows 11 (its reader).+ let seen = "#< CLIXML\r\n<Objs Version=\"1.1.0.1\" xmlns=\"http://schemas.microsoft.com/powershell/2004/04\"><S S=\"Error\">$ProgressPreference = 'SilentlyContinue'; $b = New-Object Text.StringBuilder; while ((($l = _x000D__x000A_</S><S S=\"Error\">[Console]::In.ReadLine()) -ne $null) -and ($l -ne '#muxen-end')) { [void]$b.AppendLine($l) }; _x000D__x000A_</S><S S=\"Error\">$b.ToString() | Invoke-Expression : error: the folder doesn't exist & <stuff>_x000D__x000A_</S><S S=\"Error\">At line:3 char:8_x000D__x000A_</S><S S=\"Error\">+ trap { Write-Error (\"error: \" + $_.Exception.Message); exit 1 }_x000D__x000A_</S><S S=\"Error\">+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~_x000D__x000A_</S><S S=\"Error\"> + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException_x000D__x000A_</S><S S=\"Error\"> + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException_x000D__x000A_</S><S S=\"Error\"> _x000D__x000A_</S></Objs>\r\n";+ let (_, logged, reason) = read(Shell::Powershell, b"", seen.as_bytes()).await;+ assert_eq!(reason.as_deref(), Some("the folder doesn't exist & <stuff>"));+ assert!(logged.iter().all(|l| !l.contains("<Objs") && !l.contains("CLIXML")), "{logged:?}");++ // With this reader, its wrapped text goes and the message stays.+ let long = format!("C:\\actions-runner\\x belongs to someone else, {}", "so that account could change what the runners run. ".repeat(3));+ let (_, logged, reason) = read(Shell::Powershell, b"", format!("#< CLIXML\r\n{}\r\n", clixml_record(&format!("error: {long}"))).as_bytes()).await;+ assert!(logged[0].starts_with("error: C:\\actions-runner\\x belongs"), "{logged:?}");+ assert!(logged.iter().all(|l| !l.contains("Invoke-Expression") && !l.contains("$ProgressPreference")), "{logged:?}");+ assert!(long.starts_with(reason.as_deref().unwrap()), "{reason:?}");++ // The traps print their error as a plain line; PowerShell writes its+ // records (a warning, a non-terminating error) as it exits, after it.+ let records = clixml_record("a non-terminating one").replacen("\">", "\"><S S=\"warning\">a _x005F_x000D_ warning</S>", 1);+ let stderr = format!("#< CLIXML\r\nerror: C:\\actions-runner\\café is in use\r\n{records}\r\n");+ let (_, logged, reason) = read(Shell::Powershell, b"", stderr.as_bytes()).await;+ assert_eq!(reason.as_deref(), Some("C:\\actions-runner\\café is in use"));+ assert!(logged.contains(&"WARNING: a _x000D_ warning".to_string()), "{logged:?}");+ assert!(logged.contains(&"a non-terminating one".to_string()), "{logged:?}");++ // Without an `error:` line: the last line that isn't the code or the category.+ let (_, _, reason) = read(Shell::Powershell, b"", clixml_record("Get-Item : Cannot find path").as_bytes()).await;+ assert_eq!(reason.as_deref(), Some("Get-Item : Cannot find path"));+ // sh's stderr is read as it is.+ let (_, logged, reason) = read(Shell::Sh, b"", b"error: no docker\n+ set -x line\n").await;+ assert_eq!((logged.len(), reason.as_deref()), (2, Some("no docker")));+ }++ #[test]+ fn unescapes_clixml() {+ assert_eq!(clixml_unescape("a_x000D__x000A_b"), "a\r\nb");+ assert_eq!(clixml_unescape("_x005F_x000D_ stays"), "_x000D_ stays");+ assert_eq!(clixml_unescape("_x001B_[31mred_x001B_[0m"), "\u{1b}[31mred\u{1b}[0m");+ assert_eq!(clixml_unescape("_xD83D__xDE00_ and _xD83D_ alone"), "😀 and \u{FFFD} alone");+ assert_eq!(clixml_unescape("_xZZZZ_ _x12_ é_x00E9_ &lt; "q""), "_xZZZZ_ _x12_ éé < \"q\"");+ assert_eq!(clixml_text("plain\nlines"), "plain\nlines");+ }++ #[tokio::test]+ async fn keeps_reading_past_lines_that_are_not_utf8() {+ // config.cmd prints its check marks in the console's code page (here 437).+ let stdout = b"# Authentication\r\n\r\n\xfb Connected to GitHub\r\n\r\n# Runner Registration\r\nStarted r1 in the background\r\n\xe2\x9c\x93 r1 is installed";+ let (printed, logged, _) = read(Shell::Powershell, stdout, b"\xfb from stderr\r\nerror: it broke\r\n").await;+ assert_eq!(printed[2], "\u{FFFD} Connected to GitHub");+ assert_eq!(printed.last().map(String::as_str), Some("✓ r1 is installed"));+ assert_eq!(printed.len(), 7);+ for l in ["\u{FFFD} Connected to GitHub", "Started r1 in the background", "✓ r1 is installed", "\u{FFFD} from stderr", "error: it broke"] {+ assert!(logged.contains(&l.to_string()), "{l:?} not in {logged:?}");+ }+ }++ #[tokio::test]+ async fn lines_split_across_reads_stay_whole() {+ use tokio::io::AsyncWriteExt as _;+ let (mut out_w, out_r) = tokio::io::duplex(64);+ let (mut err_w, err_r) = tokio::io::duplex(64);+ let writer = tokio::spawn(async move {+ let pause = || tokio::time::sleep(Duration::from_millis(20));+ out_w.write_all(b"half a li").await.unwrap();+ pause().await;+ err_w.write_all(b"a warning\n").await.unwrap();+ pause().await;+ out_w.write_all(b"ne\n\xfb\n").await.unwrap();+ });+ let mut logged = Vec::new();+ let (printed, _) = read_output(out_r, err_r, Shell::Sh, &[], |l| logged.push(l)).await;+ writer.await.unwrap();+ assert_eq!(printed, ["half a line", "\u{FFFD}"]);+ assert_eq!(logged, ["a warning", "half a line", "\u{FFFD}"]);+ }+#[test]fn picks_shells() {let spec: MachineSpec = toml::from_str("name = \"w\"\nhost = \"win\"").unwrap();diff --git a/src/ops/scripts/control.ps1 b/src/ops/scripts/control.ps1index 47df15a..fff1ff6 100644--- a/src/ops/scripts/control.ps1+++ b/src/ops/scripts/control.ps1@@ -4,7 +4,9 @@$ErrorActionPreference = 'Stop'$ProgressPreference = 'SilentlyContinue'-trap { Write-Error ("error: " + $_.Exception.Message); exit 1 }+# A plain line, not an error record: PowerShell writes those as CLIXML when+# stderr isn't a terminal.+trap { [Console]::Error.WriteLine("error: " + $_.Exception.Message); exit 1 }function say($m) { Write-Output $m }if (-not $OR_DIR -or -not (Test-Path $OR_DIR)) { throw "$OR_DIR doesn't exist." }@@ -36,7 +38,7 @@ function Start-Detached($file, $dir) {function Start-Runner {if ($svcName) {- say "Starting service $svcName…"+ say "Starting service ${svcName}…"Start-Service -Name $svcName} elseif (Get-RunnerProcesses) {say 'Already running.'@@ -57,7 +59,7 @@ function Start-Runner {function Stop-Runner {if ($svcName) {- say "Stopping service $svcName…"+ say "Stopping service ${svcName}…"Stop-Service -Name $svcName -Forcereturn}diff --git a/src/ops/scripts/install.ps1 b/src/ops/scripts/install.ps1index fd48437..177e016 100644--- a/src/ops/scripts/install.ps1+++ b/src/ops/scripts/install.ps1@@ -5,7 +5,9 @@$ErrorActionPreference = 'Stop'$ProgressPreference = 'SilentlyContinue'-trap { Write-Error ("error: " + $_.Exception.Message); exit 1 }+# A plain line, not an error record: PowerShell writes those as CLIXML when+# stderr isn't a terminal.+trap { [Console]::Error.WriteLine("error: " + $_.Exception.Message); exit 1 }function say($m) { Write-Output $m }# Starts a program that outlives this session. Muxin runs this script over ssh,@@ -103,7 +105,7 @@ if ((Test-Path -LiteralPath $zip) -and (Test-Cached $zip)) {}# A new file, not one someone else made: its owner could still change it.Remove-Item -LiteralPath "$zip.part" -Force -ErrorAction SilentlyContinue- say "Downloading actions-runner $OR_VERSION for win-$arch…"+ say "Downloading actions-runner $OR_VERSION for win-${arch}…"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12Invoke-WebRequest -Uri $url -OutFile "$zip.part" -UseBasicParsing$got = Get-Sha256 "$zip.part"