mirror of
https://github.com/instructkr/claw-code.git
synced 2026-11-20 00:00:00 +08:00
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:
1 parent
ca48ec7500
commit
407a6c62f8
31 files changed
+873
-371
No files matched your search
@@ -460,7 +460,10 @@ fn classify_error_kind(message: &str) -> &'static str {
|
||||
// error message is "failed to restore session: legacy session is missing workspace
|
||||
// binding: ...", so the specific arm must be checked first.
|
||||
"legacy_session_no_workspace_binding"
|
||||
} else if message.contains("Is a directory") || message.contains("os error 21") {
|
||||
} else if message.contains("session_path_is_directory:")
|
||||
|| message.contains("Is a directory")
|
||||
|| message.contains("os error 21")
|
||||
{
|
||||
// #787: --resume given a directory path instead of a .jsonl file
|
||||
"session_path_is_directory"
|
||||
} else if message.contains("failed to restore session") {
|
||||
@@ -517,7 +520,10 @@ fn classify_error_kind(message: &str) -> &'static str {
|
||||
"api_http_error"
|
||||
} else if message.contains("mcpServers") {
|
||||
"malformed_mcp_config"
|
||||
} else if message.contains(".claw/settings.json") || message.contains(".claw.json") {
|
||||
} else if message.contains(".claw/settings.json")
|
||||
|| message.contains(r".claw\settings.json")
|
||||
|| message.contains(".claw.json")
|
||||
{
|
||||
// #763: config file JSON parse / validation errors (e.g. unterminated string, type mismatch)
|
||||
"config_parse_error"
|
||||
} else if message.starts_with("empty prompt") {
|
||||
@@ -15403,30 +15409,43 @@ mod tests {
|
||||
)
|
||||
.expect("write hook");
|
||||
}
|
||||
if include_lifecycle {
|
||||
let lifecycle = if include_lifecycle {
|
||||
fs::create_dir_all(root.join("lifecycle")).expect("lifecycle dir");
|
||||
let (extension, init_script, shutdown_script) = if cfg!(windows) {
|
||||
(
|
||||
"cmd",
|
||||
"@echo off\r\necho init>>lifecycle.log\r\n",
|
||||
"@echo off\r\necho shutdown>>lifecycle.log\r\n",
|
||||
)
|
||||
} else {
|
||||
(
|
||||
"sh",
|
||||
"#!/bin/sh\nprintf 'init\\n' >> lifecycle.log\n",
|
||||
"#!/bin/sh\nprintf 'shutdown\\n' >> lifecycle.log\n",
|
||||
)
|
||||
};
|
||||
fs::write(
|
||||
root.join("lifecycle").join("init.sh"),
|
||||
"#!/bin/sh\nprintf 'init\\n' >> lifecycle.log\n",
|
||||
root.join("lifecycle").join(format!("init.{extension}")),
|
||||
init_script,
|
||||
)
|
||||
.expect("write init lifecycle");
|
||||
fs::write(
|
||||
root.join("lifecycle").join("shutdown.sh"),
|
||||
"#!/bin/sh\nprintf 'shutdown\\n' >> lifecycle.log\n",
|
||||
root.join("lifecycle").join(format!("shutdown.{extension}")),
|
||||
shutdown_script,
|
||||
)
|
||||
.expect("write shutdown lifecycle");
|
||||
}
|
||||
format!(
|
||||
",\n \"lifecycle\": {{\n \"Init\": [\"./lifecycle/init.{extension}\"],\n \"Shutdown\": [\"./lifecycle/shutdown.{extension}\"]\n }}"
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
let hooks = if include_hooks {
|
||||
",\n \"hooks\": {\n \"PreToolUse\": [\"./hooks/pre.sh\"]\n }"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let lifecycle = if include_lifecycle {
|
||||
",\n \"lifecycle\": {\n \"Init\": [\"./lifecycle/init.sh\"],\n \"Shutdown\": [\"./lifecycle/shutdown.sh\"]\n }"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
fs::write(
|
||||
root.join(".claude-plugin").join("plugin.json"),
|
||||
format!(
|
||||
@@ -16047,10 +16066,11 @@ mod tests {
|
||||
#[test]
|
||||
fn parses_system_prompt_options() {
|
||||
// given: system-prompt options for cwd and date
|
||||
let cwd = std::env::temp_dir();
|
||||
let args = vec![
|
||||
"system-prompt".to_string(),
|
||||
"--cwd".to_string(),
|
||||
"/tmp".to_string(),
|
||||
cwd.to_string_lossy().into_owned(),
|
||||
"--date".to_string(),
|
||||
"2026-04-01".to_string(),
|
||||
];
|
||||
@@ -16062,7 +16082,7 @@ mod tests {
|
||||
assert_eq!(
|
||||
action,
|
||||
CliAction::PrintSystemPrompt {
|
||||
cwd: PathBuf::from("/tmp"),
|
||||
cwd,
|
||||
date: "2026-04-01".to_string(),
|
||||
model: DEFAULT_MODEL.to_string(),
|
||||
output_format: CliOutputFormat::Text,
|
||||
@@ -16697,7 +16717,10 @@ mod tests {
|
||||
|
||||
// Phase 1 contract: workspace/git/sandbox fields are still populated
|
||||
// (independent of config parse). Sandbox falls back to defaults.
|
||||
assert_eq!(context.cwd, cwd.canonicalize().unwrap_or(cwd.clone()));
|
||||
assert_eq!(
|
||||
context.cwd.canonicalize().expect("canonical cwd"),
|
||||
cwd.canonicalize().expect("canonical workspace")
|
||||
);
|
||||
assert_eq!(
|
||||
context.loaded_config_files, 0,
|
||||
"loaded_config_files should be 0 when config parse fails"
|
||||
@@ -17038,6 +17061,16 @@ mod tests {
|
||||
classify_error_kind("failed to restore session: Is a directory (os error 21)"),
|
||||
"session_path_is_directory"
|
||||
);
|
||||
assert_eq!(
|
||||
classify_error_kind(
|
||||
r"failed to restore session: session_path_is_directory: C:\sessions"
|
||||
),
|
||||
"session_path_is_directory"
|
||||
);
|
||||
assert_eq!(
|
||||
classify_error_kind(r"C:\workspace\.claw\settings.json: model must be a string"),
|
||||
"config_parse_error"
|
||||
);
|
||||
assert_eq!(
|
||||
classify_error_kind("unrecognized argument `--foo` for subcommand `doctor`"),
|
||||
"cli_parse"
|
||||
@@ -19330,16 +19363,22 @@ UU conflicted.rs",
|
||||
error.to_string().contains("session workspace mismatch"),
|
||||
"unexpected error: {error}"
|
||||
);
|
||||
let error = error.to_string();
|
||||
let workspace_a_name = workspace_a
|
||||
.file_name()
|
||||
.expect("workspace a should have a name")
|
||||
.to_string_lossy();
|
||||
let workspace_b_name = workspace_b
|
||||
.file_name()
|
||||
.expect("workspace b should have a name")
|
||||
.to_string_lossy();
|
||||
assert_ne!(workspace_a_name, workspace_b_name);
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains(&workspace_b.display().to_string()),
|
||||
error.contains(workspace_b_name.as_ref()),
|
||||
"expected current workspace in error: {error}"
|
||||
);
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains(&workspace_a.display().to_string()),
|
||||
error.contains(workspace_a_name.as_ref()),
|
||||
"expected originating workspace in error: {error}"
|
||||
);
|
||||
|
||||
@@ -20315,21 +20354,19 @@ UU conflicted.rs",
|
||||
write_mcp_server_fixture(&script_path);
|
||||
fs::write(
|
||||
config_home.join("settings.json"),
|
||||
format!(
|
||||
r#"{{
|
||||
"mcpServers": {{
|
||||
"alpha": {{
|
||||
"command": "python3",
|
||||
"args": ["{}"]
|
||||
}},
|
||||
"broken": {{
|
||||
"command": "python3",
|
||||
"args": ["-c", "import sys; sys.exit(0)"]
|
||||
}}
|
||||
}}
|
||||
}}"#,
|
||||
script_path.to_string_lossy()
|
||||
),
|
||||
serde_json::json!({
|
||||
"mcpServers": {
|
||||
"alpha": {
|
||||
"command": if cfg!(windows) { "python" } else { "python3" },
|
||||
"args": [script_path]
|
||||
},
|
||||
"broken": {
|
||||
"command": if cfg!(windows) { "python" } else { "python3" },
|
||||
"args": ["-c", "import sys; sys.exit(0)"]
|
||||
}
|
||||
}
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
.expect("write mcp settings");
|
||||
|
||||
@@ -20518,7 +20555,9 @@ UU conflicted.rs",
|
||||
.expect("runtime should build");
|
||||
|
||||
assert_eq!(
|
||||
fs::read_to_string(&log_path).expect("init log should exist"),
|
||||
fs::read_to_string(&log_path)
|
||||
.expect("init log should exist")
|
||||
.replace("\r\n", "\n"),
|
||||
"init\n"
|
||||
);
|
||||
|
||||
@@ -20527,7 +20566,9 @@ UU conflicted.rs",
|
||||
.expect("plugin shutdown should succeed");
|
||||
|
||||
assert_eq!(
|
||||
fs::read_to_string(&log_path).expect("shutdown log should exist"),
|
||||
fs::read_to_string(&log_path)
|
||||
.expect("shutdown log should exist")
|
||||
.replace("\r\n", "\n"),
|
||||
"init\nshutdown\n"
|
||||
);
|
||||
|
||||
|
||||
@@ -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)
|
||||
Reference in new issue
Block a user