fix(windows): fix native runtime compatibility and enable workspace t… (#3378)

* fix(windows): fix native runtime compatibility and enable workspace tests

Fix shell discovery, hook quoting, native path handling and OAuth
randomness on Windows, make the test fixtures portable, and run the
full workspace test suite in the Windows CI job.

* test(plugins): make lifecycle fixtures Windows-compatible

* fix(windows): address workspace test failures

---------

Co-authored-by: clawdbot <clawdbot@ultraworkers.dev>
This commit is contained in:
Dror Meirovichandclawdbot authored and GitHub committed 2026-11-08 19:45:52 +00:00
1 parent ca48ec7500
commit 407a6c62f8
31 files changed
+873 -371

No files matched your search

@@ -1,5 +1,7 @@
#![allow(clippy::while_let_on_iterator)]
mod support;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
@@ -655,12 +657,12 @@ fn run_claw(
command
.current_dir(cwd)
.env_clear()
.envs(support::process_environment())
.env("ANTHROPIC_API_KEY", "test-compact-key")
.env("ANTHROPIC_BASE_URL", base_url)
.env("CLAW_CONFIG_HOME", config_home)
.env("HOME", home)
.env("NO_COLOR", "1")
.env("PATH", "/usr/bin:/bin")
.args(args);
command.output().expect("claw should launch")
}
@@ -676,12 +678,12 @@ fn run_claw_with_stdin(
let mut child = Command::new(env!("CARGO_BIN_EXE_claw"))
.current_dir(cwd)
.env_clear()
.envs(support::process_environment())
.env("ANTHROPIC_API_KEY", "test-compact-key")
.env("ANTHROPIC_BASE_URL", base_url)
.env("CLAW_CONFIG_HOME", config_home)
.env("HOME", home)
.env("NO_COLOR", "1")
.env("PATH", "/usr/bin:/bin")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
@@ -708,10 +710,10 @@ fn run_claw_closed_stdin_with_timeout(
let mut child = Command::new(env!("CARGO_BIN_EXE_claw"))
.current_dir(cwd)
.env_clear()
.envs(support::process_environment())
.env("CLAW_CONFIG_HOME", config_home)
.env("HOME", home)
.env("NO_COLOR", "1")
.env("PATH", "/usr/bin:/bin")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
@@ -1,3 +1,5 @@
mod support;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
@@ -55,15 +57,15 @@ fn run_claw_repl(
home: &std::path::Path,
stdin: &str,
) -> Output {
let mut command = python_pty_command(env!("CARGO_BIN_EXE_claw"));
let mut command = python_terminal_command(env!("CARGO_BIN_EXE_claw"));
let mut child = command
.current_dir(cwd)
.env_clear()
.envs(support::process_environment())
.env("ANTHROPIC_API_KEY", "test-compact-repl-key")
.env("CLAW_CONFIG_HOME", config_home)
.env("HOME", home)
.env("NO_COLOR", "1")
.env("PATH", "/usr/bin:/bin")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
@@ -80,30 +82,12 @@ fn run_claw_repl(
child.wait_with_output().expect("claw should finish")
}
fn python_pty_command(claw: &str) -> Command {
let mut command = Command::new("python3");
command.args([
"-c",
r#"
import os
import pty
import subprocess
import sys
claw = sys.argv[1]
payload = sys.stdin.buffer.read()
master, slave = pty.openpty()
child = subprocess.Popen([claw], stdin=slave, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
os.close(slave)
os.write(master, payload)
stdout, stderr = child.communicate(timeout=30)
os.close(master)
sys.stdout.buffer.write(stdout)
sys.stderr.buffer.write(stderr)
raise SystemExit(child.returncode)
"#,
claw,
]);
fn python_terminal_command(claw: &str) -> Command {
let mut command = Command::new(if cfg!(windows) { "python" } else { "python3" });
command.arg(
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/support/repl_console.py"),
);
command.arg(claw);
command
}
@@ -1,3 +1,5 @@
mod support;
use std::collections::BTreeMap;
use std::fs;
use std::io::Write;
@@ -312,12 +314,12 @@ fn run_case(case: ScenarioCase, workspace: &HarnessWorkspace, base_url: &str) ->
command
.current_dir(&workspace.root)
.env_clear()
.envs(support::process_environment())
.env("ANTHROPIC_API_KEY", "test-parity-key")
.env("ANTHROPIC_BASE_URL", base_url)
.env("CLAW_CONFIG_HOME", &workspace.config_home)
.env("HOME", &workspace.home)
.env("NO_COLOR", "1")
.env("PATH", "/usr/bin:/bin")
.args([
"--model",
"sonnet",
@@ -411,6 +413,33 @@ fn prepare_multi_tool_fixture(workspace: &HarnessWorkspace) {
}
fn prepare_plugin_fixture(workspace: &HarnessWorkspace) {
// A Windows `python` command can be an install-manager launcher whose
// bootstrap messages go to stdout. Resolve it before entering the isolated
// CLI environment, then execute the interpreter itself for the JSON tool.
let python = Command::new(if cfg!(windows) { "python" } else { "python3" })
.args([
"-I",
"-c",
"import json, sys; print(json.dumps(sys.executable))",
])
.output()
.expect("Python interpreter discovery should launch");
assert!(
python.status.success(),
"Python interpreter discovery failed: {}",
String::from_utf8_lossy(&python.stderr)
);
let discovery_stdout = String::from_utf8(python.stdout).expect("Python discovery UTF-8");
let interpreter: String = serde_json::from_str(
discovery_stdout
.lines()
.last()
.expect("Python interpreter path"),
)
.expect("Python discovery must end with its JSON-encoded executable path");
assert!(Path::new(&interpreter).is_absolute());
assert!(Path::new(&interpreter).is_file());
let plugin_root = workspace
.root
.join("external-plugins")
@@ -420,45 +449,36 @@ fn prepare_plugin_fixture(workspace: &HarnessWorkspace) {
fs::create_dir_all(&tool_dir).expect("plugin tools dir");
fs::create_dir_all(&manifest_dir).expect("plugin manifest dir");
let script_path = tool_dir.join("echo-json.sh");
let script_path = tool_dir.join("echo-json.py");
fs::write(
&script_path,
"#!/bin/sh\nINPUT=$(cat)\nprintf '{\"plugin\":\"%s\",\"tool\":\"%s\",\"input\":%s}\\n' \"$CLAWD_PLUGIN_ID\" \"$CLAWD_TOOL_NAME\" \"$INPUT\"\n",
r#"import json, os, sys
print(json.dumps({"plugin": os.environ["CLAWD_PLUGIN_ID"], "tool": os.environ["CLAWD_TOOL_NAME"], "input": json.load(sys.stdin)}))
"#,
)
.expect("plugin script should write");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut permissions = fs::metadata(&script_path)
.expect("plugin script metadata")
.permissions();
permissions.set_mode(0o755);
fs::set_permissions(&script_path, permissions).expect("plugin script should be executable");
}
fs::write(
manifest_dir.join("plugin.json"),
r#"{
"name": "parity-plugin",
"version": "1.0.0",
"description": "mock parity plugin",
"tools": [
{
"name": "plugin_echo",
"description": "Echo JSON input",
"inputSchema": {
"type": "object",
"properties": {
"message": { "type": "string" }
},
"required": ["message"],
"additionalProperties": false
},
"command": "./tools/echo-json.sh",
"requiredPermission": "workspace-write"
}
]
}"#,
json!({
"name": "parity-plugin",
"version": "1.0.0",
"description": "mock parity plugin",
"tools": [{
"name": "plugin_echo",
"description": "Echo JSON input",
"inputSchema": {
"type": "object",
"properties": {"message": {"type": "string"}},
"required": ["message"],
"additionalProperties": false
},
"command": interpreter,
"args": ["-I", "tools/echo-json.py"],
"requiredPermission": "workspace-write"
}]
})
.to_string(),
)
.expect("plugin manifest should write");
@@ -504,8 +524,16 @@ fn assert_read_file_roundtrip(workspace: &HarnessWorkspace, run: &ScenarioRun) {
let output = run.response["tool_results"][0]["output"]
.as_str()
.expect("tool output");
assert!(output.contains(&workspace.root.join("fixture.txt").display().to_string()));
assert!(output.contains("alpha parity line"));
let payload: Value = serde_json::from_str(output).expect("read_file output JSON");
let actual_path = payload["file"]["filePath"].as_str().expect("filePath");
assert_eq!(
fs::canonicalize(actual_path).expect("canonical reported file"),
fs::canonicalize(workspace.root.join("fixture.txt")).expect("canonical fixture file")
);
assert!(payload["file"]["content"]
.as_str()
.expect("file content")
.contains("alpha parity line"));
}
fn assert_grep_chunk_assembly(_: &HarnessWorkspace, run: &ScenarioRun) {
@@ -536,10 +564,11 @@ fn assert_write_file_allowed(workspace: &HarnessWorkspace, run: &ScenarioRun) {
run.response["tool_uses"][0]["name"],
Value::String("write_file".to_string())
);
assert!(run.response["message"]
.as_str()
.expect("message text")
.contains("generated/output.txt"));
let message = run.response["message"].as_str().expect("message text");
assert!(
message.contains("write_file succeeded"),
"expected successful write confirmation in assistant message: {message:?}"
);
let generated = workspace.root.join("generated").join("output.txt");
let contents = fs::read_to_string(&generated).expect("generated file should exist");
assert_eq!(contents, "created by mock service\n");
@@ -676,7 +705,13 @@ fn assert_plugin_tool_roundtrip(_: &HarnessWorkspace, run: &ScenarioRun) {
let tool_output = run.response["tool_results"][0]["output"]
.as_str()
.expect("tool output");
let parsed: Value = serde_json::from_str(tool_output).expect("plugin output json");
assert_eq!(
run.response["tool_results"][0]["is_error"],
Value::Bool(false),
"plugin tool failed: {tool_output}"
);
let parsed: Value = serde_json::from_str(tool_output)
.unwrap_or_else(|err| panic!("plugin output is not JSON: {err}; output: {tool_output:?}"));
assert_eq!(
parsed["plugin"],
Value::String("parity-plugin@external".to_string())
@@ -638,13 +638,25 @@ fn global_cwd_flag_routes_status_workspace_and_short_alias_429() {
&["--cwd", workspace_str, "--output-format", "json", "status"],
);
assert_eq!(status["kind"], "status");
assert_eq!(status["workspace"]["cwd"], expected_cwd);
assert_eq!(
fs::canonicalize(status["workspace"]["cwd"].as_str().expect("cwd"))
.expect("canonical cwd")
.display()
.to_string(),
expected_cwd
);
let short_status = assert_json_command(
&launcher,
&["-C", workspace_str, "status", "--output-format", "json"],
);
assert_eq!(short_status["workspace"]["cwd"], expected_cwd);
assert_eq!(
fs::canonicalize(short_status["workspace"]["cwd"].as_str().expect("cwd"))
.expect("canonical cwd")
.display()
.to_string(),
expected_cwd
);
let directory_status = assert_json_command(
&launcher,
@@ -655,7 +667,13 @@ fn global_cwd_flag_routes_status_workspace_and_short_alias_429() {
"status",
],
);
assert_eq!(directory_status["workspace"]["cwd"], expected_cwd);
assert_eq!(
fs::canonicalize(directory_status["workspace"]["cwd"].as_str().expect("cwd"))
.expect("canonical cwd")
.display()
.to_string(),
expected_cwd
);
}
#[test]
@@ -2295,7 +2313,7 @@ fn config_json_attributes_precedence_and_shadowed_keys_425() {
file["source"] == "project"
&& file["path"]
.as_str()
.is_some_and(|path| path.ends_with(".claw/settings.json"))
.is_some_and(|path| std::path::Path::new(path).ends_with(".claw/settings.json"))
})
.expect("project .claw/settings.json entry");
@@ -5320,7 +5338,7 @@ fn agents_create_scaffolds_toml_and_lists_locally_431() {
assert_eq!(create_json["status"], "ok");
assert_eq!(create_json["format"], "toml");
assert_eq!(
reported_agent_path,
fs::canonicalize(&reported_agent_path).expect("canonical reported agent path"),
fs::canonicalize(&agent_path).expect("canonical agent path")
);
assert!(agent_path.is_file());
@@ -5337,7 +5355,8 @@ fn agents_create_scaffolds_toml_and_lists_locally_431() {
.iter()
.any(|agent| {
agent["name"] == "my-agent"
&& *agent["path"].as_str().expect("listed agent path")
&& fs::canonicalize(agent["path"].as_str().expect("listed agent path"))
.expect("canonical reported list path")
== fs::canonicalize(&agent_path).expect("canonical listed agent path")
}));
}
@@ -13,6 +13,8 @@
//! mock service does not validate pairing itself, which is why the assertion
//! lives here.
mod support;
use std::fs;
use std::path::PathBuf;
use std::process::{Command, Output};
@@ -121,12 +123,12 @@ fn run_claw(workspace: &PathBuf, config_home: &PathBuf, home: &PathBuf, base_url
Command::new(env!("CARGO_BIN_EXE_claw"))
.current_dir(workspace)
.env_clear()
.envs(support::process_environment())
.env("ANTHROPIC_API_KEY", "test-parallel-tool-key")
.env("ANTHROPIC_BASE_URL", base_url)
.env("CLAW_CONFIG_HOME", config_home)
.env("HOME", home)
.env("NO_COLOR", "1")
.env("PATH", "/usr/bin:/bin")
.args([
"--model",
"sonnet",
@@ -0,0 +1,27 @@
use std::ffi::OsString;
// Keep credentials, proxy variables and user configuration out of subprocess
// tests, but preserve the operating-system environment needed to load DLLs,
// initialize networking and find the installed test interpreters on Windows.
pub fn process_environment() -> Vec<(&'static str, OsString)> {
#[cfg(windows)]
{
[
"PATH",
"SYSTEMROOT",
"WINDIR",
"SYSTEMDRIVE",
"COMSPEC",
"PATHEXT",
"TEMP",
"TMP",
]
.into_iter()
.filter_map(|name| std::env::var_os(name).map(|value| (name, value)))
.collect()
}
#[cfg(not(windows))]
{
vec![("PATH", OsString::from("/usr/bin:/bin"))]
}
}
@@ -0,0 +1,92 @@
"""Give the CLI terminal stdin and captured stdout, using only Python's stdlib."""
import os
import subprocess
import sys
def run_unix(claw, payload):
import pty
master, slave = pty.openpty()
try:
with subprocess.Popen([claw], stdin=slave, stdout=subprocess.PIPE,
stderr=subprocess.PIPE) as child:
os.close(slave)
slave = None
os.write(master, payload)
try:
stdout, stderr = child.communicate(timeout=30)
except subprocess.TimeoutExpired:
child.kill()
child.communicate()
raise
return child.returncode, stdout, stderr
finally:
if slave is not None:
os.close(slave)
os.close(master)
def run_windows(claw, payload):
import ctypes
import msvcrt
from ctypes import wintypes
class KeyEvent(ctypes.Structure):
_fields_ = [("down", wintypes.BOOL), ("repeat", wintypes.WORD),
("virtual_key", wintypes.WORD), ("scan", wintypes.WORD),
("char", wintypes.WCHAR), ("control", wintypes.DWORD)]
class Event(ctypes.Union):
_fields_ = [("key", KeyEvent), ("storage", ctypes.c_byte * 16)]
class InputRecord(ctypes.Structure):
_fields_ = [("kind", wintypes.WORD), ("event", Event)]
kernel = ctypes.WinDLL("kernel32", use_last_error=True)
kernel.AllocConsole.argtypes = []
kernel.AllocConsole.restype = wintypes.BOOL
kernel.FreeConsole.argtypes = []
kernel.FreeConsole.restype = wintypes.BOOL
kernel.WriteConsoleInputW.argtypes = [wintypes.HANDLE, ctypes.POINTER(InputRecord),
wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)]
kernel.WriteConsoleInputW.restype = wintypes.BOOL
# This affects only this helper process, never the test runner's console.
kernel.FreeConsole()
if not kernel.AllocConsole():
raise ctypes.WinError(ctypes.get_last_error())
try:
with open("CONIN$", "r+b", buffering=0) as console:
records = []
for char in payload.decode("utf-8").replace("\r\n", "\n").replace("\n", "\r"):
for down in (True, False):
record = InputRecord()
record.kind = 1 # KEY_EVENT
record.event.key = KeyEvent(down, 1, 13 if char == "\r" else 0,
0, char, 0)
records.append(record)
inputs = (InputRecord * len(records))(*records)
written = wintypes.DWORD()
if not kernel.WriteConsoleInputW(msvcrt.get_osfhandle(console.fileno()),
inputs, len(inputs), ctypes.byref(written)):
raise ctypes.WinError(ctypes.get_last_error())
if written.value != len(inputs):
raise RuntimeError("incomplete console input")
with subprocess.Popen([claw], stdin=console, stdout=subprocess.PIPE,
stderr=subprocess.PIPE) as child:
try:
stdout, stderr = child.communicate(timeout=30)
except subprocess.TimeoutExpired:
child.kill()
child.communicate()
raise
return child.returncode, stdout, stderr
finally:
kernel.FreeConsole()
if __name__ == "__main__":
run = run_windows if os.name == "nt" else run_unix
code, stdout, stderr = run(sys.argv[1], sys.stdin.buffer.read())
sys.stdout.buffer.write(stdout)
sys.stderr.buffer.write(stderr)
raise SystemExit(code)