aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
10
akode-rs/core/tests/common/BUILD.bazel
Normal file
10
akode-rs/core/tests/common/BUILD.bazel
Normal file
@@ -0,0 +1,10 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "common",
|
||||
crate_name = "core_test_support",
|
||||
crate_srcs = glob([
|
||||
"*.rs",
|
||||
"context_snapshot/*.rs",
|
||||
]),
|
||||
)
|
||||
62
akode-rs/core/tests/common/Cargo.toml
Normal file
62
akode-rs/core/tests/common/Cargo.toml
Normal file
@@ -0,0 +1,62 @@
|
||||
[package]
|
||||
name = "core_test_support"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lib]
|
||||
path = "lib.rs"
|
||||
doctest = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
akode-agent-message-board-host = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
assert_cmd = { workspace = true }
|
||||
base64 = { workspace = true }
|
||||
akode-agent-graph-store = { workspace = true }
|
||||
akode-arg0 = { workspace = true }
|
||||
akode-attachment-store = { workspace = true }
|
||||
akode-config = { workspace = true }
|
||||
akode-core = { workspace = true }
|
||||
akode-extension-api = { workspace = true }
|
||||
akode-exec-server = { workspace = true }
|
||||
akode-guardian-v2 = { workspace = true }
|
||||
akode-home = { workspace = true }
|
||||
akode-features = { workspace = true }
|
||||
akode-hooks = { workspace = true }
|
||||
akode-login = { workspace = true }
|
||||
akode-model-provider-info = { workspace = true }
|
||||
akode-models-manager = { workspace = true }
|
||||
akode-network-proxy = { workspace = true }
|
||||
akode-protocol = { workspace = true }
|
||||
akode-thread-store = { workspace = true }
|
||||
akode-utils-absolute-path = { workspace = true }
|
||||
akode-utils-cargo-bin = { workspace = true }
|
||||
akode-utils-path-uri = { workspace = true }
|
||||
akode-utils-rustls-provider = { workspace = true }
|
||||
ctor = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
notify = { workspace = true }
|
||||
opentelemetry = { workspace = true }
|
||||
opentelemetry_sdk = { workspace = true }
|
||||
rcgen = { workspace = true }
|
||||
regex-lite = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
tokio = { workspace = true, features = ["net", "test-util", "time"] }
|
||||
tokio-rustls = { workspace = true }
|
||||
tokio-tungstenite = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-opentelemetry = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
walkdir = { workspace = true }
|
||||
wiremock = { workspace = true }
|
||||
shlex = { workspace = true }
|
||||
zstd = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
akode-http-client = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
59
akode-rs/core/tests/common/code_mode_host.rs
Normal file
59
akode-rs/core/tests/common/code_mode_host.rs
Normal file
@@ -0,0 +1,59 @@
|
||||
//! Records launches of the real code-mode host through a Unix wrapper. Each log
|
||||
//! line represents one process spawn and its arguments, independently of sessions.
|
||||
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use tempfile::TempDir;
|
||||
|
||||
/// Observes host process launches without replacing either transport implementation.
|
||||
pub struct CodeModeHostRecorder {
|
||||
_directory: TempDir,
|
||||
program: PathBuf,
|
||||
invocations: PathBuf,
|
||||
pid: PathBuf,
|
||||
}
|
||||
|
||||
impl CodeModeHostRecorder {
|
||||
pub fn new() -> Result<Self> {
|
||||
let directory = tempfile::tempdir()?;
|
||||
let program = directory.path().join("code mode host wrapper");
|
||||
let invocations = directory.path().join("host invocations");
|
||||
let pid = directory.path().join("host pid");
|
||||
fs::write(&invocations, "")?;
|
||||
let host_program = akode_utils_cargo_bin::cargo_bin("akode-code-mode-host")?;
|
||||
let quoted_host =
|
||||
shlex::try_quote(host_program.to_str().context("host path is not UTF-8")?)?;
|
||||
let quoted_log = shlex::try_quote(invocations.to_str().context("log path is not UTF-8")?)?;
|
||||
let quoted_pid = shlex::try_quote(pid.to_str().context("PID path is not UTF-8")?)?;
|
||||
akode_utils_cargo_bin::write_executable(
|
||||
&program,
|
||||
&format!(
|
||||
"#!/bin/sh\nprintf '%s\\n' \"$*\" >> {quoted_log}\nprintf '%s\\n' \"$$\" > {quoted_pid}\nexec {quoted_host} \"$@\"\n"
|
||||
),
|
||||
)?;
|
||||
Ok(Self {
|
||||
_directory: directory,
|
||||
program,
|
||||
invocations,
|
||||
pid,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn program(&self) -> PathBuf {
|
||||
self.program.clone()
|
||||
}
|
||||
|
||||
pub fn invocations(&self) -> Result<Vec<String>> {
|
||||
Ok(fs::read_to_string(&self.invocations)?
|
||||
.lines()
|
||||
.map(str::to_string)
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn pid(&self) -> Result<u32> {
|
||||
Ok(fs::read_to_string(&self.pid)?.trim().parse()?)
|
||||
}
|
||||
}
|
||||
838
akode-rs/core/tests/common/context_snapshot.rs
Normal file
838
akode-rs/core/tests/common/context_snapshot.rs
Normal file
@@ -0,0 +1,838 @@
|
||||
//! Readable snapshots of captured model context.
|
||||
//!
|
||||
//! Capturing and grouping requests only decides which input items are new. All entry points
|
||||
//! render items with the same formatter, which then normalizes volatile text or replaces routine
|
||||
//! context blocks according to the caller's options.
|
||||
|
||||
use crate::responses::ResponsesRequest;
|
||||
use crate::responses::strip_metadata_from_json;
|
||||
use crate::responses::strip_response_item_ids_from_json;
|
||||
use normalize::Normalizer;
|
||||
use normalize::TextSource;
|
||||
use normalize::fingerprint;
|
||||
use normalize::is_bundled_model_instructions;
|
||||
use normalize::portable_tool_schema;
|
||||
use serde_json::Value;
|
||||
use text::render_text;
|
||||
|
||||
mod normalize;
|
||||
#[cfg(test)]
|
||||
#[path = "context_snapshot/context_snapshot_tests.rs"]
|
||||
mod tests;
|
||||
mod text;
|
||||
|
||||
const MAX_SNAPSHOT_LINE_CHARS: usize = 160;
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ContextSnapshotOptions {
|
||||
rewrite_known_segments: bool,
|
||||
preserve_environment_context: bool,
|
||||
include_request_settings: bool,
|
||||
}
|
||||
|
||||
impl ContextSnapshotOptions {
|
||||
/// Replace known guidance with one-line tags such as `<PERMISSIONS_INSTRUCTIONS>`.
|
||||
/// The default retains the text and only truncates long lines or sections. Both normalize
|
||||
/// dynamic values such as paths and IDs before rendering.
|
||||
pub fn rewrite_known_segments(mut self) -> Self {
|
||||
self.rewrite_known_segments = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Keep normalized environment text when rewriting other known segments.
|
||||
pub fn preserve_environment_context(mut self) -> Self {
|
||||
self.preserve_environment_context = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Render model, instructions, tools, and other settings at window boundaries.
|
||||
/// Settings still participate in grouping when this is disabled.
|
||||
pub fn include_request_settings(mut self) -> Self {
|
||||
self.include_request_settings = true;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
// Capture and group: compare complete, normalized request inputs and request settings.
|
||||
// The first request in a window retains all its input; later requests retain their suffix index.
|
||||
#[derive(Clone, Copy)]
|
||||
enum SnapshotSource<'a> {
|
||||
Captured(&'a ResponsesRequest),
|
||||
Body(&'a Value),
|
||||
Items(&'a [Value]),
|
||||
}
|
||||
|
||||
pub struct SnapshotEntry<'a> {
|
||||
label: Option<&'a str>,
|
||||
source: SnapshotSource<'a>,
|
||||
}
|
||||
|
||||
impl<'a> SnapshotEntry<'a> {
|
||||
pub fn captured(request: &'a ResponsesRequest) -> Self {
|
||||
Self {
|
||||
label: None,
|
||||
source: SnapshotSource::Captured(request),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn body(body: &'a Value) -> Self {
|
||||
Self {
|
||||
label: None,
|
||||
source: SnapshotSource::Body(body),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn items(items: &'a [Value]) -> Self {
|
||||
Self {
|
||||
label: None,
|
||||
source: SnapshotSource::Items(items),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn labeled(mut self, label: &'a str) -> Self {
|
||||
self.label = Some(label);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
struct CapturedRequest {
|
||||
number: usize,
|
||||
kind: String,
|
||||
label: Option<String>,
|
||||
input: Vec<Value>,
|
||||
model_instruction_parts: Vec<(usize, usize)>,
|
||||
settings: Option<Value>,
|
||||
}
|
||||
|
||||
struct Window<'a> {
|
||||
settings: Option<&'a Value>,
|
||||
boundary: Option<InputBoundary>,
|
||||
requests: Vec<WindowRequest<'a>>,
|
||||
}
|
||||
|
||||
struct WindowRequest<'a> {
|
||||
request: &'a CapturedRequest,
|
||||
suffix_start: usize,
|
||||
}
|
||||
|
||||
enum InputBoundary {
|
||||
Truncated(usize),
|
||||
Diverged(usize),
|
||||
Repeated,
|
||||
SettingsUnavailable,
|
||||
}
|
||||
|
||||
fn capture_request(number: usize, entry: &SnapshotEntry<'_>) -> CapturedRequest {
|
||||
let (kind, input, settings) = match entry.source {
|
||||
SnapshotSource::Captured(request) => {
|
||||
let kind = request
|
||||
.header("x-codex-turn-metadata")
|
||||
.and_then(|header| serde_json::from_str::<Value>(&header).ok())
|
||||
.and_then(|metadata| metadata["request_kind"].as_str().map(str::to_owned))
|
||||
.unwrap_or_else(|| "request".to_string());
|
||||
let (input, settings) = capture_body(request.body_json());
|
||||
(kind, input, Some(settings))
|
||||
}
|
||||
SnapshotSource::Body(body) => {
|
||||
let (input, settings) = capture_body(body.clone());
|
||||
("request".to_string(), input, Some(settings))
|
||||
}
|
||||
SnapshotSource::Items(items) => ("items".to_string(), Value::Array(items.to_vec()), None),
|
||||
};
|
||||
// Base instructions live in an annotated developer content part. Keep its
|
||||
// location for rendering, while still excluding transport metadata from window comparison.
|
||||
let mut model_instruction_parts: Vec<_> = input
|
||||
.as_array()
|
||||
.expect("request input should be an array")
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, item)| item["role"] == "developer")
|
||||
.flat_map(|(item_index, item)| {
|
||||
item["internal_chat_message_metadata_passthrough"]["content_item_kinds"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.enumerate()
|
||||
.filter(|(_, kind)| **kind == "model.base_instructions")
|
||||
.map(move |(part_index, _)| (item_index, part_index))
|
||||
})
|
||||
.collect();
|
||||
// Providers can remove annotations. The prefix still identifies the position, but an
|
||||
// empty base prompt also leaves ordinary developer guidance there; require a complete catalog prompt.
|
||||
let instructions_index = usize::from(input[0]["type"] == "additional_tools");
|
||||
let instructions = &input[instructions_index];
|
||||
if model_instruction_parts.is_empty()
|
||||
&& instructions["type"] == "message"
|
||||
&& instructions["role"] == "developer"
|
||||
&& instructions["content"]
|
||||
.as_array()
|
||||
.is_some_and(|content| content.len() == 1)
|
||||
&& instructions["internal_chat_message_metadata_passthrough"]["content_item_kinds"][0]
|
||||
.is_null()
|
||||
&& let Some(text) = instructions["content"][0]["text"].as_str()
|
||||
&& is_bundled_model_instructions(text)
|
||||
{
|
||||
model_instruction_parts.push((instructions_index, 0));
|
||||
}
|
||||
let input = strip_metadata_from_json(strip_response_item_ids_from_json(input));
|
||||
CapturedRequest {
|
||||
number,
|
||||
kind,
|
||||
label: entry.label.map(str::to_owned),
|
||||
input: input
|
||||
.as_array()
|
||||
.expect("request input should be an array")
|
||||
.clone(),
|
||||
model_instruction_parts,
|
||||
settings,
|
||||
}
|
||||
}
|
||||
|
||||
fn capture_body(mut body: Value) -> (Value, Value) {
|
||||
let settings = body
|
||||
.as_object_mut()
|
||||
.expect("request body should be an object");
|
||||
let input = settings
|
||||
.remove("input")
|
||||
.expect("request should contain input");
|
||||
// Telemetry does not affect request context. Keep the cache key in settings so
|
||||
// a change to it starts a new window.
|
||||
settings.remove("client_metadata");
|
||||
(input, body)
|
||||
}
|
||||
|
||||
fn group_requests(requests: &[CapturedRequest]) -> Vec<Window<'_>> {
|
||||
let mut windows: Vec<Window> = Vec::new();
|
||||
for request in requests {
|
||||
let previous = windows
|
||||
.last()
|
||||
.and_then(|window| window.requests.last())
|
||||
.map(|entry| entry.request);
|
||||
let shared = previous
|
||||
.map(|previous| {
|
||||
previous
|
||||
.input
|
||||
.iter()
|
||||
.zip(&request.input)
|
||||
.take_while(|(left, right)| left == right)
|
||||
.count()
|
||||
})
|
||||
.unwrap_or(0);
|
||||
let boundary = previous.and_then(|previous| {
|
||||
if shared < previous.input.len() {
|
||||
Some(if shared == request.input.len() {
|
||||
InputBoundary::Truncated(shared)
|
||||
} else {
|
||||
InputBoundary::Diverged(shared)
|
||||
})
|
||||
} else if shared == request.input.len() {
|
||||
Some(InputBoundary::Repeated)
|
||||
} else if request.settings.is_none() {
|
||||
Some(InputBoundary::SettingsUnavailable)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
let new_window = boundary.is_some()
|
||||
|| previous.is_none_or(|previous| previous.settings != request.settings);
|
||||
if new_window {
|
||||
windows.push(Window {
|
||||
settings: request.settings.as_ref(),
|
||||
boundary,
|
||||
requests: Vec::new(),
|
||||
});
|
||||
}
|
||||
windows
|
||||
.last_mut()
|
||||
.expect("first request starts a window")
|
||||
.requests
|
||||
.push(WindowRequest {
|
||||
request,
|
||||
suffix_start: if new_window { 0 } else { shared },
|
||||
});
|
||||
}
|
||||
windows
|
||||
}
|
||||
|
||||
// Render: labeled snapshots and complete histories feed the same item renderer.
|
||||
pub fn format_labeled_requests_snapshot(
|
||||
scenario: &str,
|
||||
sections: &[(&str, &ResponsesRequest)],
|
||||
options: &ContextSnapshotOptions,
|
||||
) -> String {
|
||||
let entries = sections
|
||||
.iter()
|
||||
.map(|(title, request)| SnapshotEntry::captured(request).labeled(title))
|
||||
.collect::<Vec<_>>();
|
||||
format_context_snapshot(scenario, &entries, options)
|
||||
}
|
||||
|
||||
/// Show every captured `/responses` request. A new window starts when a request no longer
|
||||
/// extends its predecessor's input or changes request settings. No server window IDs are
|
||||
/// used to infer boundaries.
|
||||
pub fn format_request_history_snapshot(
|
||||
scenario: &str,
|
||||
requests: &[ResponsesRequest],
|
||||
options: &ContextSnapshotOptions,
|
||||
) -> String {
|
||||
let entries = requests
|
||||
.iter()
|
||||
.map(SnapshotEntry::captured)
|
||||
.collect::<Vec<_>>();
|
||||
format_context_snapshot(scenario, &entries, options)
|
||||
}
|
||||
|
||||
pub fn format_context_snapshot(
|
||||
scenario: &str,
|
||||
entries: &[SnapshotEntry<'_>],
|
||||
options: &ContextSnapshotOptions,
|
||||
) -> String {
|
||||
let requests = entries
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, entry)| capture_request(index + 1, entry))
|
||||
.collect::<Vec<_>>();
|
||||
let windows = group_requests(&requests);
|
||||
let mut normalizer = Normalizer::default();
|
||||
let mut result = format!("Scenario: {scenario}");
|
||||
for (index, window) in windows.iter().enumerate() {
|
||||
result.push_str(&format!("\n\n## Window {}", index + 1));
|
||||
if let Some(previous) = index.checked_sub(1) {
|
||||
result.push_str(&format!(
|
||||
" (after request {}",
|
||||
window.requests[0].request.number - 1
|
||||
));
|
||||
if let Some(boundary) = &window.boundary {
|
||||
result.push_str(&match boundary {
|
||||
InputBoundary::Truncated(at) => format!(": input truncated at item {at:02}"),
|
||||
InputBoundary::Diverged(at) => format!(": input diverged at item {at:02}"),
|
||||
InputBoundary::Repeated => ": input repeated".to_string(),
|
||||
InputBoundary::SettingsUnavailable => ": settings unavailable".to_string(),
|
||||
});
|
||||
}
|
||||
if !options.include_request_settings {
|
||||
let changed = windows[previous]
|
||||
.settings
|
||||
.zip(window.settings)
|
||||
.filter(|(old, new)| old != new)
|
||||
.map(|(old, new)| changed_setting_keys(new, Some(old)).join(", "));
|
||||
if let Some(changed) = changed {
|
||||
let separator = if window.boundary.is_some() {
|
||||
", "
|
||||
} else {
|
||||
": "
|
||||
};
|
||||
result.push_str(&format!("{separator}settings changed ({changed})"));
|
||||
}
|
||||
}
|
||||
result.push(')');
|
||||
}
|
||||
if options.include_request_settings {
|
||||
render_window_settings(&mut result, &windows, index, options, &mut normalizer);
|
||||
}
|
||||
for WindowRequest {
|
||||
request,
|
||||
suffix_start,
|
||||
} in &window.requests
|
||||
{
|
||||
normalizer.observe_request(&request.input);
|
||||
let label = request
|
||||
.label
|
||||
.as_deref()
|
||||
.map(|label| format!("; {label}"))
|
||||
.unwrap_or_default();
|
||||
result.push_str(&format!(
|
||||
"\n-- request {} ({}{label}) --",
|
||||
request.number, request.kind
|
||||
));
|
||||
let suffix = &request.input[*suffix_start..];
|
||||
if !suffix.is_empty() {
|
||||
result.push('\n');
|
||||
result.push_str(&render_items(
|
||||
suffix,
|
||||
*suffix_start,
|
||||
&request.model_instruction_parts,
|
||||
options,
|
||||
&mut normalizer,
|
||||
));
|
||||
} else if request.number == window.requests[0].request.number {
|
||||
result.push_str("\n<EMPTY_INPUT>");
|
||||
}
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Sort standalone JSON object lines embedded in rendered context. Cargo and Bazel can enable
|
||||
/// different serde_json map ordering features, but the model-visible values are the same.
|
||||
pub fn normalize_json_lines(snapshot: &str) -> String {
|
||||
snapshot
|
||||
.lines()
|
||||
.map(|line| {
|
||||
let json = line.trim_start();
|
||||
if !json.starts_with('{') {
|
||||
return line.to_owned();
|
||||
}
|
||||
let Ok(mut value) = serde_json::from_str::<Value>(json) else {
|
||||
return line.to_owned();
|
||||
};
|
||||
value.sort_all_objects();
|
||||
format!("{}{}", &line[..line.len() - json.len()], value)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
fn render_window_settings(
|
||||
result: &mut String,
|
||||
windows: &[Window<'_>],
|
||||
index: usize,
|
||||
options: &ContextSnapshotOptions,
|
||||
normalizer: &mut Normalizer,
|
||||
) {
|
||||
let Some(settings) = windows[index].settings else {
|
||||
result.push_str("\nSettings: unavailable (items only)");
|
||||
return;
|
||||
};
|
||||
let Some(previous) = index.checked_sub(1) else {
|
||||
result.push_str("\nSettings:");
|
||||
result.push_str(&render_settings(
|
||||
settings, /*previous*/ None, options, normalizer,
|
||||
));
|
||||
return;
|
||||
};
|
||||
if let Some(same) = windows[..index]
|
||||
.iter()
|
||||
.position(|earlier| earlier.settings == Some(settings))
|
||||
{
|
||||
result.push_str(&format!("\nSettings: same as window {}", same + 1));
|
||||
return;
|
||||
}
|
||||
if windows[previous].settings.is_some() {
|
||||
result.push_str(&format!("\nSettings: relative to window {}", previous + 1));
|
||||
} else {
|
||||
result.push_str("\nSettings:");
|
||||
}
|
||||
result.push_str(&render_settings(
|
||||
settings,
|
||||
windows[previous].settings,
|
||||
options,
|
||||
normalizer,
|
||||
));
|
||||
}
|
||||
|
||||
fn render_settings(
|
||||
settings: &Value,
|
||||
previous: Option<&Value>,
|
||||
options: &ContextSnapshotOptions,
|
||||
normalizer: &mut Normalizer,
|
||||
) -> String {
|
||||
let mut lines = Vec::new();
|
||||
let fields = settings.as_object().expect("request settings object");
|
||||
for key in changed_setting_keys(settings, previous) {
|
||||
let Some(value) = fields.get(&key) else {
|
||||
lines.push(format!(" {key}: <removed>"));
|
||||
continue;
|
||||
};
|
||||
match (key.as_str(), value) {
|
||||
("prompt_cache_key", Value::String(key)) => {
|
||||
lines.push(format!(
|
||||
" prompt_cache_key: \"{}\"",
|
||||
normalizer.prompt_cache_key(key)
|
||||
));
|
||||
}
|
||||
("instructions", Value::String(text)) => {
|
||||
lines.push(format!(
|
||||
" instructions: {}",
|
||||
render_text(text, TextSource::ModelInstructions, options, normalizer)
|
||||
.replace('\n', "\n ")
|
||||
));
|
||||
}
|
||||
("tools", Value::Array(tools)) => {
|
||||
let prior = previous
|
||||
.and_then(|old| old.get("tools"))
|
||||
.and_then(Value::as_array)
|
||||
.map(Vec::as_slice);
|
||||
lines.push(format!(
|
||||
" tools ({}; hash={}):",
|
||||
tools.len(),
|
||||
fingerprint(&Value::Array(
|
||||
tools.iter().map(portable_tool_schema).collect()
|
||||
))
|
||||
));
|
||||
lines.extend(render_tools(tools, prior));
|
||||
}
|
||||
_ => {
|
||||
let normalized = normalizer.json(value);
|
||||
lines.push(format!(" {key}: {normalized}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if lines.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("\n{}", lines.join("\n"))
|
||||
}
|
||||
}
|
||||
|
||||
fn changed_setting_keys(settings: &Value, previous: Option<&Value>) -> Vec<String> {
|
||||
let fields = settings.as_object().expect("request settings object");
|
||||
let mut keys = fields
|
||||
.keys()
|
||||
.chain(
|
||||
previous
|
||||
.into_iter()
|
||||
.flat_map(|old| old.as_object().expect("previous settings object").keys()),
|
||||
)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
keys.sort();
|
||||
keys.dedup();
|
||||
keys.retain(|key| previous.is_none_or(|old| old.get(key) != fields.get(key)));
|
||||
keys
|
||||
}
|
||||
|
||||
fn render_tools(tools: &[Value], previous: Option<&[Value]>) -> Vec<String> {
|
||||
let Some(previous) = previous else {
|
||||
return tools.iter().map(|tool| render_tool(tool, '-')).collect();
|
||||
};
|
||||
let mut labels = std::collections::HashSet::new();
|
||||
if !previous.iter().all(|tool| labels.insert(tool_label(tool))) {
|
||||
return vec![" - inventory changed (ambiguous tool names)".to_string()];
|
||||
}
|
||||
labels.clear();
|
||||
if !tools.iter().all(|tool| labels.insert(tool_label(tool))) {
|
||||
return vec![" - inventory changed (ambiguous tool names)".to_string()];
|
||||
}
|
||||
let mut changes = Vec::new();
|
||||
for old in previous {
|
||||
if !tools.iter().any(|tool| tool_label(tool) == tool_label(old)) {
|
||||
changes.push(format!(" - removed {}", tool_label(old)));
|
||||
}
|
||||
}
|
||||
for tool in tools {
|
||||
match previous
|
||||
.iter()
|
||||
.find(|old| tool_label(old) == tool_label(tool))
|
||||
{
|
||||
None => changes.push(render_tool(tool, '+')),
|
||||
Some(old) if old != tool => {
|
||||
changes.push(render_tool(tool, '~'));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if changes.is_empty() {
|
||||
changes.push(" - order changed".to_string());
|
||||
}
|
||||
changes
|
||||
}
|
||||
|
||||
fn render_tool(tool: &Value, marker: char) -> String {
|
||||
let stable = portable_tool_schema(tool);
|
||||
let tool = &stable;
|
||||
let label = tool_label(tool);
|
||||
let definition = tool.get("function").unwrap_or(tool);
|
||||
let description = definition
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|text| !text.is_empty())
|
||||
.map(|text| {
|
||||
let text = text.replace('\n', " ");
|
||||
if text.chars().count() > 100 {
|
||||
format!(": {}...", text.chars().take(97).collect::<String>())
|
||||
} else {
|
||||
format!(": {text}")
|
||||
}
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let args = definition
|
||||
.get("parameters")
|
||||
.and_then(|parameters| parameters.get("properties"))
|
||||
.and_then(Value::as_object)
|
||||
.map(|properties| {
|
||||
let mut names = properties.keys().cloned().collect::<Vec<_>>();
|
||||
names.sort();
|
||||
format!("; args=[{}]", names.join(", "))
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let mut rendered = format!(
|
||||
" {marker} {label}{description}{args}; hash={}",
|
||||
fingerprint(tool)
|
||||
);
|
||||
if let Some(members) = definition.get("tools").and_then(Value::as_array) {
|
||||
for member in members {
|
||||
rendered.push_str(&format!("\n - {}", tool_label(member)));
|
||||
}
|
||||
}
|
||||
rendered
|
||||
}
|
||||
|
||||
fn tool_label(tool: &Value) -> String {
|
||||
let kind = tool
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("unknown");
|
||||
let definition = tool.get("function").unwrap_or(tool);
|
||||
let name = definition
|
||||
.get("name")
|
||||
.or_else(|| tool.get("server_label"))
|
||||
.and_then(Value::as_str);
|
||||
name.map_or_else(|| kind.to_string(), |name| format!("{kind}/{name}"))
|
||||
}
|
||||
|
||||
fn render_items(
|
||||
items: &[Value],
|
||||
start_index: usize,
|
||||
model_instruction_parts: &[(usize, usize)],
|
||||
options: &ContextSnapshotOptions,
|
||||
normalizer: &mut Normalizer,
|
||||
) -> String {
|
||||
items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(offset, item)| {
|
||||
let rendered = render_item(
|
||||
start_index + offset,
|
||||
item,
|
||||
model_instruction_parts,
|
||||
options,
|
||||
normalizer,
|
||||
)
|
||||
.replace('\n', "\n ");
|
||||
rendered
|
||||
.split('\n')
|
||||
.map(str::trim_end)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
fn render_item(
|
||||
index: usize,
|
||||
item: &Value,
|
||||
model_instruction_parts: &[(usize, usize)],
|
||||
options: &ContextSnapshotOptions,
|
||||
normalizer: &mut Normalizer,
|
||||
) -> String {
|
||||
let Some(kind) = item.get("type").and_then(Value::as_str) else {
|
||||
return format!("{index:02}:<MISSING_TYPE>");
|
||||
};
|
||||
match kind {
|
||||
"message" => render_message(index, item, model_instruction_parts, options, normalizer),
|
||||
"additional_tools" => {
|
||||
let Some(tools) = item.get("tools").and_then(Value::as_array) else {
|
||||
return format!("{index:02}:additional_tools:<MISSING_TOOLS>");
|
||||
};
|
||||
let portable = tools.iter().map(portable_tool_schema).collect();
|
||||
let mut lines = vec![format!(
|
||||
"{index:02}:additional_tools/{} ({}; hash={}):",
|
||||
item.get("role")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("unknown"),
|
||||
tools.len(),
|
||||
fingerprint(&Value::Array(portable))
|
||||
)];
|
||||
lines.extend(render_tools(tools, /*previous*/ None));
|
||||
lines.join("\n")
|
||||
}
|
||||
"function_call" => {
|
||||
let name = call_name(item);
|
||||
let args = item
|
||||
.get("arguments")
|
||||
.and_then(Value::as_str)
|
||||
.map(|text| render_text(text, TextSource::FunctionArguments, options, normalizer))
|
||||
.unwrap_or_else(|| "<NO_ARGUMENTS>".to_string());
|
||||
format!("{index:02}:function_call/{name}:{args}")
|
||||
}
|
||||
"custom_tool_call" => {
|
||||
let name = call_name(item);
|
||||
let input = item
|
||||
.get("input")
|
||||
.and_then(Value::as_str)
|
||||
.map(|input| render_text(input, TextSource::Other, options, normalizer))
|
||||
.unwrap_or_else(|| "<NO_INPUT>".to_string());
|
||||
format!("{index:02}:custom_tool_call/{name}:{input}")
|
||||
}
|
||||
"function_call_output" | "custom_tool_call_output" => {
|
||||
let name = item
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.map(|_| format!("/{}", call_name(item)))
|
||||
.or_else(|| {
|
||||
item.get("namespace")
|
||||
.and_then(Value::as_str)
|
||||
.map(|namespace| format!("[namespace={namespace}]"))
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let output = item
|
||||
.get("output")
|
||||
.map(|output| match output {
|
||||
Value::String(text) => {
|
||||
render_text(text, TextSource::Other, options, normalizer)
|
||||
}
|
||||
Value::Array(parts) => parts
|
||||
.iter()
|
||||
.map(|part| {
|
||||
part.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.map(|text| {
|
||||
render_text(text, TextSource::Other, options, normalizer)
|
||||
})
|
||||
.unwrap_or_else(|| format!("<{}>", tool_label(part)))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" | "),
|
||||
Value::Object(fields) => {
|
||||
let content = fields
|
||||
.get("content")
|
||||
.and_then(Value::as_str)
|
||||
.map(|text| render_text(text, TextSource::Other, options, normalizer))
|
||||
.unwrap_or_else(|| "<NO_TEXT>".to_string());
|
||||
match fields.get("success").and_then(Value::as_bool) {
|
||||
Some(success) => format!("success={success}:{content}"),
|
||||
None => content,
|
||||
}
|
||||
}
|
||||
_ => "<NON_TEXT_OUTPUT>".to_string(),
|
||||
})
|
||||
.unwrap_or_else(|| "<NO_OUTPUT>".to_string());
|
||||
format!("{index:02}:{kind}{name}:{output}")
|
||||
}
|
||||
"local_shell_call" => {
|
||||
let command = item
|
||||
.get("action")
|
||||
.and_then(|action| action.get("command"))
|
||||
.and_then(Value::as_array)
|
||||
.map(|parts| {
|
||||
parts
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
})
|
||||
.filter(|text| !text.is_empty())
|
||||
.map(|text| render_text(&text, TextSource::Other, options, normalizer))
|
||||
.unwrap_or_else(|| "<NO_COMMAND>".to_string());
|
||||
format!("{index:02}:local_shell_call:{command}")
|
||||
}
|
||||
"configuration_update" => {
|
||||
let reasoning = normalizer.json(&item["reasoning"]);
|
||||
format!("{index:02}:configuration_update:reasoning={reasoning}")
|
||||
}
|
||||
"reasoning" => {
|
||||
let summary = item
|
||||
.get("summary")
|
||||
.and_then(Value::as_array)
|
||||
.and_then(|entries| entries.first())
|
||||
.and_then(|entry| entry.get("text"))
|
||||
.and_then(Value::as_str)
|
||||
.map(|text| render_text(text, TextSource::Other, options, normalizer))
|
||||
.unwrap_or_else(|| "<NO_SUMMARY>".to_string());
|
||||
let encrypted = has_encrypted_content(item);
|
||||
format!("{index:02}:reasoning:summary={summary}:encrypted={encrypted}")
|
||||
}
|
||||
"compaction" => {
|
||||
let encrypted = item
|
||||
.get("encrypted_content")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|text| !text.is_empty());
|
||||
match encrypted {
|
||||
Some(content) => format!(
|
||||
"{index:02}:compaction:encrypted=true; chars={}; hash={}",
|
||||
content.chars().count(),
|
||||
fingerprint(&Value::String(content.to_owned()))
|
||||
),
|
||||
None => format!("{index:02}:compaction:encrypted=false"),
|
||||
}
|
||||
}
|
||||
other => format!("{index:02}:{other}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn call_name(item: &Value) -> String {
|
||||
let name = item
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("unknown");
|
||||
match item.get("namespace").and_then(Value::as_str) {
|
||||
Some(namespace) => format!("{namespace}.{name}"),
|
||||
None => name.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn has_encrypted_content(item: &Value) -> bool {
|
||||
item.get("encrypted_content")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|text| !text.is_empty())
|
||||
}
|
||||
|
||||
fn render_message(
|
||||
index: usize,
|
||||
item: &Value,
|
||||
model_instruction_parts: &[(usize, usize)],
|
||||
options: &ContextSnapshotOptions,
|
||||
normalizer: &mut Normalizer,
|
||||
) -> String {
|
||||
let role = item
|
||||
.get("role")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("unknown");
|
||||
let parts = item
|
||||
.get("content")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.enumerate()
|
||||
.map(|(part_index, part)| {
|
||||
if let Some(text) = part.get("text").and_then(Value::as_str) {
|
||||
let source = if model_instruction_parts.contains(&(index, part_index)) {
|
||||
TextSource::ModelInstructions
|
||||
} else {
|
||||
TextSource::Message(role)
|
||||
};
|
||||
return render_text(text, source, options, normalizer);
|
||||
}
|
||||
let Some(kind) = part.get("type").and_then(Value::as_str) else {
|
||||
return "<UNKNOWN_CONTENT_ITEM>".to_string();
|
||||
};
|
||||
let mut keys = part
|
||||
.as_object()
|
||||
.into_iter()
|
||||
.flat_map(|part| part.keys())
|
||||
.filter(|key| *key != "type" && *key != "text")
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
keys.sort();
|
||||
if keys.is_empty() {
|
||||
format!("<{kind}>")
|
||||
} else {
|
||||
format!("<{kind}:{}>", keys.join(","))
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let role = if parts.len() > 1 {
|
||||
format!("{role}[{}]", parts.len())
|
||||
} else {
|
||||
role.to_string()
|
||||
};
|
||||
match parts.as_slice() {
|
||||
[] => format!("{index:02}:message/{role}:\n<NO_TEXT>"),
|
||||
[part] => format!("{index:02}:message/{role}:\n{part}"),
|
||||
_ => format!(
|
||||
"{index:02}:message/{role}:\n{}",
|
||||
parts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(number, part)| format!(
|
||||
"[{:02}] {}",
|
||||
number + 1,
|
||||
part.replace('\n', "\n ")
|
||||
))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,923 @@
|
||||
//! Check window boundaries, shared item rendering, and stable context normalization.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
fn render_test_items(items: &[Value], options: &ContextSnapshotOptions) -> String {
|
||||
render_items(
|
||||
items,
|
||||
/*start_index*/ 0,
|
||||
&[],
|
||||
options,
|
||||
&mut Normalizer::default(),
|
||||
)
|
||||
}
|
||||
|
||||
fn message(role: &str, text: &str) -> Value {
|
||||
json!({"type": "message", "role": role, "content": [{"type": "input_text", "text": text}]})
|
||||
}
|
||||
|
||||
fn tagged_message(role: &str, tag: &str, body: &str) -> Value {
|
||||
message(role, &format!("<{tag}>{body}</{tag}>"))
|
||||
}
|
||||
|
||||
fn detailed(items: &[Value]) -> String {
|
||||
render_test_items(items, &ContextSnapshotOptions::default())
|
||||
}
|
||||
|
||||
fn rewritten(items: &[Value]) -> String {
|
||||
render_test_items(
|
||||
items,
|
||||
&ContextSnapshotOptions::default().rewrite_known_segments(),
|
||||
)
|
||||
}
|
||||
|
||||
fn captured(body: &Value) -> String {
|
||||
format_context_snapshot(
|
||||
"test",
|
||||
&[SnapshotEntry::body(body)],
|
||||
&ContextSnapshotOptions::default(),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lite_tool_catalog_and_code_calls_are_visible() {
|
||||
let rendered = render_test_items(
|
||||
&[
|
||||
json!({ "type": "additional_tools", "role": "developer", "tools": [
|
||||
{ "type": "namespace", "name": "functions", "tools": [
|
||||
{ "type": "custom", "name": "exec", "description": "Run JavaScript" },
|
||||
{ "type": "function", "name": "update_plan" }
|
||||
] }
|
||||
] }),
|
||||
json!({ "type": "custom_tool_call", "name": "exec", "input": "text('ready');" }),
|
||||
json!({ "type": "custom_tool_call_output", "output": [
|
||||
{ "type": "output_text", "text": "Script completed\nWall time 0.1 seconds\nOutput:\n" },
|
||||
{ "type": "output_text", "text": "ready" }
|
||||
] }),
|
||||
json!({ "type": "custom_tool_call_output", "output": {
|
||||
"content": "plan updated", "success": true
|
||||
} }),
|
||||
json!({ "type": "function_call_output", "output": "Wall time: 0.0025 seconds\nOutput: Report ready." }),
|
||||
],
|
||||
&ContextSnapshotOptions::default(),
|
||||
);
|
||||
assert!(rendered.contains("00:additional_tools/developer (1; hash="));
|
||||
assert!(rendered.contains("- custom/exec"));
|
||||
assert!(rendered.contains("- namespace/functions"));
|
||||
assert!(rendered.contains("- function/update_plan"));
|
||||
assert!(rendered.contains("01:custom_tool_call/exec:text('ready');"));
|
||||
assert!(rendered.contains(
|
||||
"02:custom_tool_call_output:Script completed\n Wall time <DURATION> seconds\n Output:"
|
||||
));
|
||||
assert!(rendered.contains(" | ready"));
|
||||
assert!(rendered.contains("03:custom_tool_call_output:success=true:plan updated"));
|
||||
assert!(rendered.contains("04:function_call_output:Wall time: <DURATION> seconds"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_mode_timing_normalization_preserves_status_and_user_output() {
|
||||
for status in ["Script completed", "Script failed", "Script terminated"] {
|
||||
let text = format!(
|
||||
"{status}\nWall time 1.000 seconds (code-mode 1.001 seconds; overhead -0.001 seconds)\nOutput:\nWall time 2.0 seconds"
|
||||
);
|
||||
assert_eq!(
|
||||
Normalizer::default().text(
|
||||
&text,
|
||||
TextSource::Other,
|
||||
&ContextSnapshotOptions::default(),
|
||||
),
|
||||
format!(
|
||||
"{status}\nWall time <DURATION> seconds (code-mode <DURATION> seconds; overhead <DURATION> seconds)\nOutput:\nWall time 2.0 seconds"
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_outputs_show_only_their_own_names_and_namespaces() {
|
||||
let items = [
|
||||
json!({ "type": "function_call", "call_id": "lookup", "namespace": "collaboration", "name": "lookup", "arguments": "{}" }),
|
||||
json!({ "type": "custom_tool_call", "call_id": "custom", "namespace": "functions", "name": "exec", "input": "" }),
|
||||
json!({ "type": "function_call_output", "call_id": "lookup", "output": "ordinary function result" }),
|
||||
json!({ "type": "custom_tool_call_output", "call_id": "custom", "output": "ordinary custom result" }),
|
||||
json!({ "type": "custom_tool_call_output", "call_id": "custom", "name": "exec", "output": "Code Mode notification" }),
|
||||
json!({ "type": "function_call_output", "call_id": "lookup", "name": "lookup", "output": "explicit name only" }),
|
||||
json!({ "type": "function_call_output", "name": "notifications", "namespace": "slack", "output": "standalone" }),
|
||||
json!({ "type": "function_call_output", "call_id": "lookup", "namespace": "slack", "output": "explicit namespace only" }),
|
||||
];
|
||||
let rendered = render_test_items(&items, &ContextSnapshotOptions::default());
|
||||
let outputs = rendered
|
||||
.lines()
|
||||
.filter(|line| line.contains("call_output"))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
outputs,
|
||||
[
|
||||
"02:function_call_output:ordinary function result",
|
||||
"03:custom_tool_call_output:ordinary custom result",
|
||||
"04:custom_tool_call_output/exec:Code Mode notification",
|
||||
"05:function_call_output/lookup:explicit name only",
|
||||
"06:function_call_output/slack.notifications:standalone",
|
||||
"07:function_call_output[namespace=slack]:explicit namespace only",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encrypted_compaction_payload_changes_are_visible_without_exposing_contents() {
|
||||
let render = |encrypted_content| {
|
||||
render_test_items(
|
||||
&[json!({ "type": "compaction", "encrypted_content": encrypted_content })],
|
||||
&ContextSnapshotOptions::default(),
|
||||
)
|
||||
};
|
||||
let before = render("checkpoint A");
|
||||
assert!(before.contains("compaction:encrypted=true; chars=12; hash="));
|
||||
assert!(!before.contains("checkpoint A"));
|
||||
assert_ne!(before, render("checkpoint B"));
|
||||
assert_eq!(render(""), "00:compaction:encrypted=false");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grouping_only_continues_when_input_extends_and_settings_match() {
|
||||
let request = |number, input: Vec<Value>, effort| CapturedRequest {
|
||||
number,
|
||||
kind: "turn".to_string(),
|
||||
label: None,
|
||||
input,
|
||||
model_instruction_parts: Vec::new(),
|
||||
settings: Some(json!({ "reasoning": { "effort": effort } })),
|
||||
};
|
||||
let one = json!({ "type": "message", "role": "user", "content": [] });
|
||||
let two = json!({ "type": "message", "role": "assistant", "content": [] });
|
||||
let requests = [
|
||||
request(1, vec![one.clone()], "medium"),
|
||||
request(2, vec![one.clone(), two.clone()], "medium"),
|
||||
request(3, vec![one.clone(), two], "high"),
|
||||
request(4, vec![one.clone()], "high"),
|
||||
request(5, vec![one], "high"),
|
||||
];
|
||||
let windows = group_requests(&requests);
|
||||
assert_eq!(windows.len(), 4);
|
||||
assert_eq!(windows[0].requests[1].suffix_start, 1);
|
||||
assert_eq!(windows[1].requests[0].suffix_start, 0);
|
||||
assert!(matches!(
|
||||
windows[2].boundary,
|
||||
Some(InputBoundary::Truncated(1))
|
||||
));
|
||||
assert!(matches!(windows[3].boundary, Some(InputBoundary::Repeated)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_key_changes_split_windows_and_render_distinct_stable_labels() {
|
||||
let items = [
|
||||
json!({ "type": "message", "role": "user", "content": [] }),
|
||||
json!({ "type": "message", "role": "assistant", "content": [] }),
|
||||
json!({ "type": "message", "role": "user", "content": [] }),
|
||||
json!({ "type": "message", "role": "assistant", "content": [] }),
|
||||
];
|
||||
let body = |count, key, metadata| {
|
||||
json!({
|
||||
"input": items[..count],
|
||||
"model": "test",
|
||||
"prompt_cache_key": key,
|
||||
"client_metadata": metadata,
|
||||
})
|
||||
};
|
||||
let first_key = "11111111-1111-1111-1111-111111111111";
|
||||
let second_key = "22222222-2222-2222-2222-222222222222";
|
||||
let bodies = [
|
||||
body(1, first_key, "first"),
|
||||
body(2, second_key, "second"),
|
||||
body(3, second_key, "third"),
|
||||
body(4, first_key, "fourth"),
|
||||
];
|
||||
let entries = bodies.iter().map(SnapshotEntry::body).collect::<Vec<_>>();
|
||||
let rendered = format_context_snapshot(
|
||||
"cache keys",
|
||||
&entries,
|
||||
&ContextSnapshotOptions::default().include_request_settings(),
|
||||
);
|
||||
assert_eq!(rendered.matches("## Window").count(), 3);
|
||||
assert!(rendered.contains("## Window 2 (after request 1)"));
|
||||
assert!(
|
||||
rendered.contains(
|
||||
"Settings: relative to window 1\n prompt_cache_key: \"<PROMPT_CACHE_KEY 2>\""
|
||||
)
|
||||
);
|
||||
assert!(rendered.contains("-- request 3 (request) --\n02:message/user"));
|
||||
assert!(rendered.contains("Settings: same as window 1"));
|
||||
assert!(rendered.contains("prompt_cache_key: \"<PROMPT_CACHE_KEY 1>\""));
|
||||
assert!(!rendered.contains(first_key));
|
||||
assert!(!rendered.contains(second_key));
|
||||
let without_settings =
|
||||
format_context_snapshot("cache keys", &entries, &ContextSnapshotOptions::default());
|
||||
assert!(
|
||||
without_settings
|
||||
.contains("## Window 2 (after request 1: settings changed (prompt_cache_key))")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn body_entries_group_while_item_only_entries_keep_unknown_settings_explicit() {
|
||||
let first =
|
||||
json!({ "input": [{ "type": "message", "role": "user", "content": [] }], "model": "test" });
|
||||
let second = json!({ "input": [first["input"][0], { "type": "message", "role": "assistant", "content": [] }], "model": "test" });
|
||||
let options = ContextSnapshotOptions::default();
|
||||
let bodies = format_context_snapshot(
|
||||
"raw request bodies",
|
||||
&[
|
||||
SnapshotEntry::body(&first).labeled("first"),
|
||||
SnapshotEntry::body(&second).labeled("second"),
|
||||
],
|
||||
&options,
|
||||
);
|
||||
assert_eq!(bodies.matches("## Window").count(), 1);
|
||||
assert!(bodies.contains("-- request 2 (request; second) --\n01:message/assistant"));
|
||||
assert!(!bodies.contains("Settings:"));
|
||||
|
||||
let changed = json!({ "input": second["input"], "model": "other" });
|
||||
let changed_settings = format_context_snapshot(
|
||||
"settings still split windows",
|
||||
&[SnapshotEntry::body(&first), SnapshotEntry::body(&changed)],
|
||||
&options,
|
||||
);
|
||||
assert!(changed_settings.contains("## Window 2 (after request 1: settings changed (model))"));
|
||||
assert!(!changed_settings.contains("Settings:"));
|
||||
|
||||
let diverged = json!({ "input": [], "model": "other" });
|
||||
let input_and_settings_changed = format_context_snapshot(
|
||||
"both input and settings changed",
|
||||
&[SnapshotEntry::body(&first), SnapshotEntry::body(&diverged)],
|
||||
&options,
|
||||
);
|
||||
assert!(input_and_settings_changed.contains(
|
||||
"## Window 2 (after request 1: input truncated at item 00, settings changed (model))"
|
||||
));
|
||||
|
||||
let opt_in = format_context_snapshot(
|
||||
"settings rendered on request",
|
||||
&[SnapshotEntry::body(&first)],
|
||||
&options.clone().include_request_settings(),
|
||||
);
|
||||
assert!(opt_in.contains("Settings:\n model: \"test\""));
|
||||
|
||||
let first_input = first["input"].as_array().expect("input array");
|
||||
let second_input = second["input"].as_array().expect("input array");
|
||||
let items = format_context_snapshot(
|
||||
"items without settings",
|
||||
&[
|
||||
SnapshotEntry::items(first_input),
|
||||
SnapshotEntry::items(second_input),
|
||||
],
|
||||
&options,
|
||||
);
|
||||
assert_eq!(items.matches("## Window").count(), 2);
|
||||
assert!(items.contains("settings unavailable"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_tools_show_only_the_inventory_delta() {
|
||||
let old = json!({ "tools": [
|
||||
{ "type": "function", "function": { "name": "read", "description": "Read a file" } },
|
||||
{ "type": "function", "function": { "name": "write", "description": "Write a file" } }
|
||||
] });
|
||||
let new = json!({ "tools": [
|
||||
{ "type": "function", "function": { "name": "read", "description": "Read a changed file" } },
|
||||
{ "type": "function", "function": { "name": "search", "description": "Find a file" } }
|
||||
] });
|
||||
let rendered = render_settings(
|
||||
&new,
|
||||
Some(&old),
|
||||
&ContextSnapshotOptions::default(),
|
||||
&mut Normalizer::default(),
|
||||
);
|
||||
assert!(rendered.contains("- removed function/write"));
|
||||
assert!(rendered.contains("~ function/read:"));
|
||||
assert!(rendered.contains("+ function/search:"));
|
||||
assert!(!rendered.contains("Write a file"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unnamed_tools_with_shared_type_do_not_get_misreported_as_order_changes() {
|
||||
let old = json!({ "tools": [
|
||||
{ "type": "mcp", "server_label": "calendar" },
|
||||
{ "type": "mcp", "server_label": "mail" }
|
||||
] });
|
||||
let new = json!({ "tools": [{ "type": "mcp", "server_label": "calendar" }] });
|
||||
let rendered = render_settings(
|
||||
&new,
|
||||
Some(&old),
|
||||
&ContextSnapshotOptions::default(),
|
||||
&mut Normalizer::default(),
|
||||
);
|
||||
assert!(rendered.contains("- removed mcp/mail"));
|
||||
assert!(!rendered.contains("order changed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portable_tool_schema_keeps_non_platform_changes_visible() {
|
||||
let mut unix = json!({
|
||||
"type": "function",
|
||||
"name": "exec_command",
|
||||
"description": "Runs a command in a PTY, returning output or a session ID for ongoing interaction.",
|
||||
"parameters": { "properties": {
|
||||
"cmd": { "description": "Shell command to execute." },
|
||||
"yield_time_ms": { "description": "Wait before yielding output. Defaults to 10000 ms; effective range is 250-30000 ms." }
|
||||
} }
|
||||
});
|
||||
let mut windows = unix.clone();
|
||||
windows["parameters"]["properties"]["yield_time_ms"]["description"] = json!(
|
||||
"Maximum time to wait before returning a session ID for a still-running command. Commands that finish sooner return immediately. For ordinary commands, omit this parameter to use the 10000 ms default. Effective range on Windows is 10000-30000 ms."
|
||||
);
|
||||
assert_eq!(portable_tool_schema(&unix), portable_tool_schema(&windows));
|
||||
|
||||
windows["description"] = json!(format!(
|
||||
"{}\n\nWindows safety rules:\nNew guidance.",
|
||||
unix["description"].as_str().expect("shell description")
|
||||
));
|
||||
assert_ne!(portable_tool_schema(&unix), portable_tool_schema(&windows));
|
||||
windows["description"] = unix["description"].clone();
|
||||
unix["parameters"]["properties"]["cmd"]["description"] =
|
||||
json!("Different shell command guidance.");
|
||||
assert_ne!(portable_tool_schema(&unix), portable_tool_schema(&windows));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portable_tool_schema_normalizes_embedded_code_mode_shell_guidance() {
|
||||
let base = "Runs a command in a PTY, returning output or a session ID for ongoing interaction.";
|
||||
let windows_guidance = r#"Windows safety rules:
|
||||
- Do not compose destructive filesystem commands across shells. Do not enumerate paths in PowerShell and then pass them to `cmd /c`, batch builtins, or another shell for deletion or moving. Use one shell end-to-end, prefer native PowerShell cmdlets such as `Remove-Item` / `Move-Item` with `-LiteralPath`, and avoid string-built shell commands for file operations.
|
||||
- Before any recursive delete or move on Windows, verify the resolved absolute target paths stay within the intended workspace or explicitly named target directory. Never issue a recursive delete or move against a computed path if the final target has not been checked.
|
||||
- When using `Start-Process` to launch a background helper or service, pass `-WindowStyle Hidden` unless the user explicitly asked for a visible interactive window. Use visible windows only for interactive tools the user needs to see or control."#;
|
||||
let description = |shell: String, wait: &str| {
|
||||
format!("### `exec_command`\n{shell}\n\nexec tool declaration:\n```ts\n // {wait}\n```")
|
||||
};
|
||||
let nested = |description: String| {
|
||||
let shell_description = description
|
||||
.strip_prefix("### `exec_command`\n")
|
||||
.expect("embedded shell guidance")
|
||||
.to_string();
|
||||
json!({ "type": "namespace", "name": "functions", "tools": [
|
||||
{ "type": "custom", "name": "exec", "description": description },
|
||||
{ "type": "function", "name": "exec_command", "description": shell_description }
|
||||
] })
|
||||
};
|
||||
let unix = nested(description(
|
||||
base.to_string(),
|
||||
"Wait before yielding output. Defaults to 10000 ms; effective range is 250-30000 ms.",
|
||||
));
|
||||
let windows = nested(description(
|
||||
format!("{base}\n\n{windows_guidance}"),
|
||||
"Maximum time to wait before returning a session ID for a still-running command. Commands that finish sooner return immediately. For ordinary commands, omit this parameter to use the 10000 ms default. Effective range on Windows is 10000-30000 ms.",
|
||||
));
|
||||
assert_eq!(portable_tool_schema(&unix), portable_tool_schema(&windows));
|
||||
|
||||
let changed = nested(description(
|
||||
format!("{base}\n\n{windows_guidance}\nA new restriction."),
|
||||
"Maximum time to wait before returning a session ID for a still-running command. Commands that finish sooner return immediately. For ordinary commands, omit this parameter to use the 10000 ms default. Effective range on Windows is 10000-30000 ms.",
|
||||
));
|
||||
assert_ne!(portable_tool_schema(&unix), portable_tool_schema(&changed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_renderer_handles_text_image_and_function_calls() {
|
||||
let items = vec![
|
||||
json!({ "type": "message", "role": "developer", "content": [{ "type": "input_text", "text": "<skills_instructions>\nbody\n</skills_instructions>" }] }),
|
||||
json!({ "type": "message", "role": "user", "content": [{ "type": "input_text", "text": "Look" }, { "type": "input_image", "image_url": "data:image/png;base64,AAAA" }] }),
|
||||
json!({ "type": "function_call", "namespace": "collaboration", "name": "lookup", "arguments": "{\"key\":\"value\"}" }),
|
||||
];
|
||||
let rendered = render_test_items(
|
||||
&items,
|
||||
&ContextSnapshotOptions::default().rewrite_known_segments(),
|
||||
);
|
||||
assert_eq!(
|
||||
rendered,
|
||||
"00:message/developer:\n <SKILLS_INSTRUCTIONS>\n01:message/user[2]:\n [01] Look\n [02] <input_image:image_url>\n02:function_call/collaboration.lookup:{\"key\":\"value\"}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uuid_labels_preserve_identity_across_message_and_function_content() {
|
||||
let first = "11111111-1111-1111-1111-111111111111";
|
||||
let second = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
|
||||
let items = [
|
||||
json!({ "type": "message", "role": "user", "content": [{ "text": first }] }),
|
||||
json!({ "type": "function_call", "name": "lookup", "arguments": json!({"id": second.to_uppercase()}).to_string() }),
|
||||
json!({ "type": "message", "role": "user", "content": [{ "text": format!("{first} {second}") }] }),
|
||||
];
|
||||
let rendered = render_test_items(&items, &ContextSnapshotOptions::default());
|
||||
assert!(rendered.contains("00:message/user:\n <UUID 1>"));
|
||||
assert!(rendered.contains("01:function_call/lookup:{\"id\":\"<UUID 2>\"}"));
|
||||
assert!(rendered.contains("02:message/user:\n <UUID 1> <UUID 2>"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewritten_model_and_personality_use_plain_tags() {
|
||||
let render = |text| {
|
||||
render_test_items(
|
||||
&[json!({ "type": "message", "role": "developer", "content": [{ "text": text }] })],
|
||||
&ContextSnapshotOptions::default().rewrite_known_segments(),
|
||||
)
|
||||
};
|
||||
assert_eq!(
|
||||
render("<model_switch>\nOriginal intro\n\nlong instructions\n</model_switch>"),
|
||||
"00:message/developer:\n <MODEL_SWITCH>"
|
||||
);
|
||||
assert_eq!(
|
||||
render("<personality_spec> Original intro \nlong instructions\n</personality_spec>"),
|
||||
"00:message/developer:\n <PERSONALITY_SPEC>"
|
||||
);
|
||||
assert_ne!(render("<model_switch>"), render("<model_switch>New intro"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base_instructions_use_the_same_mode_in_settings_and_annotated_developer_content() {
|
||||
let prompt = "My model instructions\nA rule below the prefix";
|
||||
let developer = |metadata: Value| {
|
||||
json!({
|
||||
"type": "message", "role": "developer",
|
||||
"content": [{ "type": "input_text", "text": "Neighbor stays literal" },
|
||||
{ "type": "input_text", "text": prompt }],
|
||||
"internal_chat_message_metadata_passthrough": metadata
|
||||
})
|
||||
};
|
||||
let annotated = developer(json!({"content_item_kinds": [null, "model.base_instructions"]}));
|
||||
let plain = developer(Value::Null);
|
||||
let first = json!({"instructions": prompt, "input": [annotated]});
|
||||
let second = json!({"instructions": prompt, "input": [plain,
|
||||
{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "Next turn"}]}]});
|
||||
let render = |options: ContextSnapshotOptions| {
|
||||
format_context_snapshot(
|
||||
"transport",
|
||||
&[SnapshotEntry::body(&first), SnapshotEntry::body(&second)],
|
||||
&options.include_request_settings(),
|
||||
)
|
||||
};
|
||||
let detailed = render(ContextSnapshotOptions::default());
|
||||
let shape = render(ContextSnapshotOptions::default().rewrite_known_segments());
|
||||
for rendered in [&detailed, &shape] {
|
||||
assert!(rendered.contains("Neighbor stays literal"));
|
||||
assert_eq!(rendered.matches("## Window").count(), 1);
|
||||
}
|
||||
assert_eq!(detailed.matches("My model instructions").count(), 2);
|
||||
assert_eq!(detailed.matches("A rule below the prefix").count(), 2);
|
||||
assert_eq!(shape.matches("<MODEL_INSTRUCTIONS>").count(), 2);
|
||||
assert!(!shape.contains("A rule below the prefix"));
|
||||
let unmarked = captured(&json!({"input": [plain]}));
|
||||
assert!(unmarked.contains("A rule below the prefix"));
|
||||
|
||||
let catalog_prompt = akode_models_manager::model_info::BASE_INSTRUCTIONS;
|
||||
let lite = |prompt: &str| {
|
||||
json!({"input": [
|
||||
{"type": "additional_tools", "role": "developer", "tools": []},
|
||||
{"type": "message", "role": "developer", "content": [{"type": "input_text", "text": prompt}]},
|
||||
{"type": "message", "role": "developer", "content": [{"type": "input_text", "text": catalog_prompt}]}
|
||||
]})
|
||||
};
|
||||
let rewrite = |body: &Value| {
|
||||
format_context_snapshot(
|
||||
"test",
|
||||
&[SnapshotEntry::body(body)],
|
||||
&ContextSnapshotOptions::default().rewrite_known_segments(),
|
||||
)
|
||||
};
|
||||
let known = rewrite(&lite(catalog_prompt));
|
||||
assert_eq!(known.matches("<MODEL_INSTRUCTIONS>").count(), 1);
|
||||
let custom = rewrite(&lite(&format!("{catalog_prompt}\nKeep this line")));
|
||||
assert!(!custom.contains("<MODEL_INSTRUCTIONS>"));
|
||||
assert!(custom.contains("Keep this line"));
|
||||
let mut annotated_other = lite(catalog_prompt);
|
||||
annotated_other["input"][1]["internal_chat_message_metadata_passthrough"] =
|
||||
json!({"content_item_kinds": ["developer_instructions"]});
|
||||
assert!(!rewrite(&annotated_other).contains("<MODEL_INSTRUCTIONS>"));
|
||||
let mut multipart = lite(catalog_prompt);
|
||||
multipart["input"][1]["content"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.push(json!({"type": "input_text", "text": "Keep neighboring guidance"}));
|
||||
let multipart = rewrite(&multipart);
|
||||
assert!(!multipart.contains("<MODEL_INSTRUCTIONS>"));
|
||||
assert!(multipart.contains("Keep neighboring guidance"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_harness_text_stays_literal_unless_rewriting_is_enabled() {
|
||||
let developer = |tag, body| tagged_message("developer", tag, body);
|
||||
let items = [
|
||||
developer(
|
||||
"collaboration_mode",
|
||||
"# Collaboration Mode: Plan\nHidden rule",
|
||||
),
|
||||
developer("multi_agent_role", "You are `/root`\nHidden rule"),
|
||||
developer("multi_agent_mode", "Delegation is enabled.\nHidden rule"),
|
||||
developer(
|
||||
"permissions instructions",
|
||||
"Sandbox policy\nApproval policy is currently never.\nHidden rule",
|
||||
),
|
||||
tagged_message(
|
||||
"user",
|
||||
"environment_context",
|
||||
"\n<cwd>/tmp/fixture</cwd>\n<shell>zsh</shell>\n<subagents>\n- running\n</subagents>\n",
|
||||
),
|
||||
developer("skills_instructions", "Plugin-specific skill inventory"),
|
||||
tagged_message("user", "skill", "Scenario-specific skill"),
|
||||
message(
|
||||
"developer",
|
||||
"<collaboration_mode>unclosed developer instruction",
|
||||
),
|
||||
tagged_message("user", "collaboration_mode", "user-supplied tags"),
|
||||
json!({"type": "function_call_output", "output": "<collaboration_mode>tool-supplied tags</collaboration_mode>"}),
|
||||
message(
|
||||
"developer",
|
||||
"<collaboration_mode>One</collaboration_mode>\nIndependent instruction\n<collaboration_mode>Two</collaboration_mode>",
|
||||
),
|
||||
tagged_message(
|
||||
"user",
|
||||
"permissions instructions",
|
||||
"\n The writable root is `/tmp/fixture/user`.\n",
|
||||
),
|
||||
json!({"type": "function_call_output", "output": "<permissions instructions>\n The writable root is `/tmp/fixture/tool`.\n</permissions instructions>"}),
|
||||
];
|
||||
let rendered = detailed(&items);
|
||||
for visible in [
|
||||
"# Collaboration Mode: Plan",
|
||||
"You are `/root`",
|
||||
"Delegation is enabled.",
|
||||
"Sandbox policy",
|
||||
"Approval policy is currently never.",
|
||||
"<environment_context>",
|
||||
"<cwd><CWD></cwd>",
|
||||
"<shell><HOST_SHELL></shell>",
|
||||
"- running",
|
||||
"Hidden rule",
|
||||
"Plugin-specific skill inventory",
|
||||
"Scenario-specific skill",
|
||||
"unclosed developer instruction",
|
||||
"user-supplied tags",
|
||||
"tool-supplied tags",
|
||||
"Independent instruction",
|
||||
"`/tmp/fixture/user`",
|
||||
"`/tmp/fixture/tool`",
|
||||
] {
|
||||
assert!(rendered.contains(visible), "{visible}: {rendered}");
|
||||
}
|
||||
assert!(!rendered.contains("[hash="));
|
||||
let collaboration = |body| detailed(&[developer("collaboration_mode", body)]);
|
||||
assert!(collaboration("# Collaboration Mode: Plan\nChanged rule").contains("Changed rule"));
|
||||
let nested = collaboration(
|
||||
"# Collaboration Mode: Plan\nQuote `<collaboration_mode>...</collaboration_mode>`.",
|
||||
);
|
||||
assert!(nested.contains("Quote `<collaboration_mode>...</collaboration_mode>`."));
|
||||
let environment = |path: &str, shell: &str, agent: &str| {
|
||||
detailed(&[tagged_message(
|
||||
"user",
|
||||
"environment_context",
|
||||
&format!(
|
||||
"\n<cwd>{path}</cwd>\n<shell>{shell}</shell>\n<subagents>\n- {agent}\n</subagents>\n"
|
||||
),
|
||||
)])
|
||||
};
|
||||
let first_environment = environment("/tmp/one", "zsh", "one");
|
||||
assert_eq!(first_environment, environment("/tmp/two", "bash", "one"));
|
||||
assert_ne!(first_environment, environment("/tmp/two", "bash", "two"));
|
||||
let inputs = [
|
||||
message("user", "<environment_context><cwd>/fake</cwd>"),
|
||||
tagged_message("user", "environment_context", "<cwd>/real</cwd>"),
|
||||
json!({"type": "function_call_output", "output": "<environment_context><cwd>/real/tool</cwd></environment_context>"}),
|
||||
];
|
||||
let malformed = captured(&json!({"input": inputs}));
|
||||
assert!(malformed.contains("<cwd>/fake</cwd>"));
|
||||
assert!(malformed.contains("<environment_context><cwd><CWD></cwd></environment_context>"));
|
||||
assert!(malformed.contains("<cwd>/real/tool</cwd>"));
|
||||
|
||||
let shape = rewritten(&items);
|
||||
assert!(shape.contains("<COLLABORATION_MODE>"));
|
||||
assert!(shape.contains("<MULTI_AGENT_ROLE>"));
|
||||
assert!(shape.contains("<MULTI_AGENT_MODE>"));
|
||||
assert!(shape.contains("<PERMISSIONS_INSTRUCTIONS>"));
|
||||
assert!(shape.contains("<SKILLS_INSTRUCTIONS>"));
|
||||
assert!(shape.contains("<ENVIRONMENT_CONTEXT>"));
|
||||
assert!(!shape.contains("Sandbox policy"));
|
||||
assert!(!shape.contains("Hidden rule"));
|
||||
for lookalike in [
|
||||
"Scenario-specific skill",
|
||||
"unclosed developer instruction",
|
||||
"user-supplied tags",
|
||||
"tool-supplied tags",
|
||||
"Independent instruction",
|
||||
] {
|
||||
assert!(shape.contains(lookalike));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detailed_skills_use_the_same_truncation_and_dynamic_normalization_as_other_text() {
|
||||
let catalog = "## Skills\nRead the skill before using it.\n### Skill roots\n- `r0` = `/home/test/skills`\n### Available skills\n- notes:summarize: Find owners. (file: r0/summarize/SKILL.md)";
|
||||
let render = |body: &str| detailed(&[tagged_message("developer", "skills_instructions", body)]);
|
||||
let rendered = render(catalog);
|
||||
assert_eq!(
|
||||
rendered,
|
||||
"00:message/developer:\n <skills_instructions>## Skills\n Read the skill before using it.\n ### Skill roots\n - `r0` = `<SKILLS_ROOT>`\n ### Available skills\n - notes:summarize: Find owners. (file: r0/summarize/SKILL.md)</skills_instructions>"
|
||||
);
|
||||
assert_eq!(rendered, render(&catalog.replace("/home/test", "/other")));
|
||||
assert_eq!(
|
||||
rewritten(&[tagged_message("developer", "skills_instructions", catalog)]),
|
||||
"00:message/developer:\n <SKILLS_INSTRUCTIONS>"
|
||||
);
|
||||
assert_eq!(
|
||||
rewritten(&[tagged_message("user", "skills_instructions", catalog)]),
|
||||
rendered.replace("message/developer", "message/user")
|
||||
);
|
||||
|
||||
let large = (0..30)
|
||||
.map(|index| format!("- skill-{index}: Description"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let large_text =
|
||||
format!("<skills_instructions>### Available skills\n{large}</skills_instructions>");
|
||||
let large = render(&format!("### Available skills\n{large}"));
|
||||
assert_eq!(
|
||||
large,
|
||||
detailed(&[message("user", &large_text)]).replace("message/user", "message/developer")
|
||||
);
|
||||
assert!(large.contains("skill-0"));
|
||||
assert!(large.contains("skill-29"));
|
||||
assert!(large.contains("<OMITTED 15 LINES;"));
|
||||
assert!(!large.contains("skill-15"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewritten_segments_share_one_tag_format_and_keep_compaction_data() {
|
||||
let developer = |tag, body| tagged_message("developer", tag, body);
|
||||
let items = [
|
||||
developer("apps_instructions", "Apps guidance"),
|
||||
developer("plugins_instructions", "Plugins guidance"),
|
||||
message(
|
||||
"developer",
|
||||
"You are judging one planned coding-agent action.\nRoutine guidance.",
|
||||
),
|
||||
message(
|
||||
"developer",
|
||||
"# Transcript provenance\nRoutine guidance.\n\nYou are judging one planned coding-agent action.",
|
||||
),
|
||||
message(
|
||||
"user",
|
||||
"# AGENTS.md instructions for project\n\n<INSTRUCTIONS>\nProject rules\n</INSTRUCTIONS>",
|
||||
),
|
||||
message(
|
||||
"user",
|
||||
"You are performing a CONTEXT CHECKPOINT COMPACTION. Routine guidance.",
|
||||
),
|
||||
message(
|
||||
"user",
|
||||
"Another language model started to solve this problem.\nGenerated summary",
|
||||
),
|
||||
];
|
||||
let original = rewritten(&items);
|
||||
let lines = original
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix(" "))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
lines,
|
||||
[
|
||||
"<APPS_INSTRUCTIONS>",
|
||||
"<PLUGINS_INSTRUCTIONS>",
|
||||
"<GUARDIAN_INSTRUCTIONS>",
|
||||
"<GUARDIAN_INSTRUCTIONS>",
|
||||
"<AGENTS_MD>",
|
||||
"<SUMMARIZATION_PROMPT>",
|
||||
"<COMPACTION_SUMMARY>",
|
||||
"Generated summary",
|
||||
]
|
||||
);
|
||||
let full = detailed(&items);
|
||||
assert!(full.contains("Routine guidance."));
|
||||
assert!(full.contains("Project rules"));
|
||||
assert!(full.contains("Another language model started to solve this problem."));
|
||||
assert!(full.contains("Generated summary"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detailed_permissions_normalize_paths_and_keep_policy_changes_visible() {
|
||||
let render = |cwd: &str, external: &str, separator: &str, network: &str, denied: &str| {
|
||||
let permissions = format!(
|
||||
"<permissions instructions>\nFilesystem sandboxing defines which files can be read or written. `sandbox_mode` is `workspace-write`: {} Network access is {network}.\nApproval policy is currently never.\n The writable roots are `{cwd}`, `{external}`.\n- path `{cwd}{separator}{denied}`\n- glob `{external}{separator}*.key`\n</permissions instructions>",
|
||||
"Some additional sandbox guidance. ".repeat(5)
|
||||
);
|
||||
let environment = format!(
|
||||
"<environment_context>\n<cwd>{cwd}</cwd>\n<filesystem><root>{external}</root><path>{external}</path><path>{cwd}{separator}{denied}</path></filesystem>\n</environment_context>"
|
||||
);
|
||||
let body = json!({"input": [
|
||||
{"type": "message", "role": "developer", "content": [{"type": "input_text", "text": permissions}]},
|
||||
{"type": "message", "role": "user", "content": [{"type": "input_text", "text": environment}]}
|
||||
]});
|
||||
captured(&body)
|
||||
};
|
||||
let unix = render("/tmp/random", "/private/random", "/", "enabled", "secret");
|
||||
assert_eq!(
|
||||
unix,
|
||||
render(r"C:\Temp\random", r"D:\Random", r"\", "enabled", "secret")
|
||||
);
|
||||
assert!(unix.contains("`workspace-write`"));
|
||||
assert!(unix.contains("Network access is enabled."));
|
||||
assert!(unix.contains("Approval policy is currently never."));
|
||||
let changed = |network, denied| render("/tmp/random", "/private/random", "/", network, denied);
|
||||
assert_ne!(unix, changed("restricted", "secret"));
|
||||
assert_ne!(unix, changed("enabled", "different"));
|
||||
|
||||
let external = |root: &str, denied: &str| {
|
||||
let text = format!(
|
||||
"<permissions instructions>Policy\nApproval\n The writable root is `{root}`.\n- path `{denied}`\n</permissions instructions>"
|
||||
);
|
||||
detailed(&[message("developer", &text)])
|
||||
};
|
||||
assert_ne!(
|
||||
external("/policy/secret", "/policy/secret"),
|
||||
external("/policy/public", "/policy/secret")
|
||||
);
|
||||
assert_ne!(
|
||||
external("/policy/secret", "/policy/secret"),
|
||||
external("/policy/secret", "/policy/public")
|
||||
);
|
||||
let temp_path = |name: &str| {
|
||||
std::env::temp_dir()
|
||||
.join(name)
|
||||
.join("secret")
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
};
|
||||
assert_eq!(
|
||||
external("/policy/stable", &temp_path(".tmpAbc123")),
|
||||
external("/policy/stable", &temp_path(".tmpDef456"))
|
||||
);
|
||||
assert_ne!(
|
||||
external("/policy/stable", &temp_path("named-one")),
|
||||
external("/policy/stable", &temp_path("named-two"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalization_labels_distinct_working_directories_and_retains_permissions() {
|
||||
let mut normalizer = Normalizer::default();
|
||||
let render = |normalizer: &mut Normalizer, cwd: &str| {
|
||||
normalizer.environment(
|
||||
&format!("<environment_context>\n<cwd>{cwd}</cwd>\n<shell>zsh</shell>\n<filesystem><root>{cwd}/src</root></filesystem>\n</environment_context>"),
|
||||
)
|
||||
};
|
||||
assert!(render(&mut normalizer, "/tmp/one").contains("<cwd><CWD></cwd>"));
|
||||
let second = render(&mut normalizer, "/tmp/two");
|
||||
assert!(second.contains("<cwd><CWD 2></cwd>"));
|
||||
assert!(second.contains("<root><CWD 2>/src</root>"));
|
||||
let nested = render(&mut normalizer, "/tmp/one/PRETURN_CONTEXT_DIFF_CWD");
|
||||
assert!(nested.contains("<cwd><CWD>/PRETURN_CONTEXT_DIFF_CWD</cwd>"));
|
||||
let permissions = render_text(
|
||||
"<permissions instructions>\nAsk approval\n</permissions instructions>",
|
||||
TextSource::Message("developer"),
|
||||
&ContextSnapshotOptions::default(),
|
||||
&mut normalizer,
|
||||
);
|
||||
assert!(permissions.contains("Ask approval"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skill_paths_are_stable_across_hosts_without_rewriting_uris() {
|
||||
let path =
|
||||
"<skill>\n<path>/tmp/fixture/plugins/cache/test/agenda/SKILL.md</path>\nAgenda\n</skill>";
|
||||
let windows =
|
||||
"<skill>\n<path>C:\\Temp\\plugins\\cache\\test\\agenda\\SKILL.md</path>\nAgenda\n</skill>";
|
||||
let render = |text| {
|
||||
render_test_items(
|
||||
&[
|
||||
json!({ "type": "message", "role": "user", "content": [{ "type": "input_text", "text": text }] }),
|
||||
],
|
||||
&ContextSnapshotOptions::default(),
|
||||
)
|
||||
};
|
||||
assert_eq!(render(path), render(windows));
|
||||
assert!(
|
||||
render("<skill>\n<path>skill://agenda/SKILL.md</path>\n</skill>")
|
||||
.contains("<path>skill://agenda/SKILL.md</path>")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cwd_aliases_match_path_components_only() {
|
||||
let mut normalizer = Normalizer::default();
|
||||
let text = normalizer.environment(
|
||||
"<environment_context><cwd>/tmp/repo</cwd><root>/tmp/repo/src</root><root>/tmp/repo-other</root></environment_context>",
|
||||
);
|
||||
assert!(text.contains("<root><CWD>/src</root>"));
|
||||
assert!(text.contains("<root><WORKSPACE_ROOT 1></root>"));
|
||||
|
||||
let mut windows = Normalizer::default();
|
||||
let first = windows.environment(
|
||||
r"<environment_context><cwd>C:\tmp\repo</cwd><root>C:\tmp\repo\src</root></environment_context>",
|
||||
);
|
||||
assert!(first.contains("<root><CWD>/src</root>"));
|
||||
let nested = windows.environment(
|
||||
r"<environment_context><cwd>C:\tmp\repo\PRETURN_CONTEXT_DIFF_CWD</cwd></environment_context>",
|
||||
);
|
||||
assert!(nested.contains("<cwd><CWD>/PRETURN_CONTEXT_DIFF_CWD</cwd>"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indented_lines_distinguish_literal_escapes_from_newlines() {
|
||||
let render = |text| {
|
||||
render_test_items(
|
||||
&[
|
||||
json!({ "type": "message", "role": "user", "content": [{ "type": "input_text", "text": text }] }),
|
||||
],
|
||||
&ContextSnapshotOptions::default(),
|
||||
)
|
||||
};
|
||||
assert_ne!(render("line one\\nline two"), render("line one\nline two"));
|
||||
assert!(render("line one\nline two").contains("00:message/user:\n line one\n line two"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_changes_remain_visible_in_fingerprints() {
|
||||
let options = ContextSnapshotOptions::default();
|
||||
let render = |word| {
|
||||
render_test_items(
|
||||
&[
|
||||
json!({ "type": "message", "role": "developer", "content": [{ "type": "input_text", "text": format!("<permissions instructions>\n{} {word}\n</permissions instructions>", "long line ".repeat(40)) }] }),
|
||||
],
|
||||
&options,
|
||||
)
|
||||
};
|
||||
let before = render("before");
|
||||
assert!(before.contains("[hash="));
|
||||
assert_ne!(before, render("after"));
|
||||
|
||||
let ordinary = |word| {
|
||||
render_test_items(
|
||||
&[
|
||||
json!({ "type": "message", "role": "user", "content": [{ "type": "input_text", "text": format!("{} {word}", "long line ".repeat(40)) }] }),
|
||||
],
|
||||
&options,
|
||||
)
|
||||
};
|
||||
assert_ne!(ordinary("before"), ordinary("after"));
|
||||
|
||||
let guardian = |policy| {
|
||||
message(
|
||||
"developer",
|
||||
&format!("You are judging one planned coding-agent action.\n{policy}"),
|
||||
)
|
||||
};
|
||||
let before = detailed(&[guardian("Original policy")]);
|
||||
assert!(before.contains("Original policy"));
|
||||
assert_ne!(before, detailed(&[guardian("Changed policy")]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_content_parts_keep_both_ends_and_fingerprint_only_the_omitted_middle() {
|
||||
let render = |middle: &str, first: &str| {
|
||||
let text = (0..80)
|
||||
.map(|index| match index {
|
||||
0 => first.to_string(),
|
||||
40 => middle.to_string(),
|
||||
_ => format!("line {index:02}"),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
render_test_items(
|
||||
&[json!({ "type": "message", "role": "user", "content": [
|
||||
{ "type": "input_text", "text": text }
|
||||
] })],
|
||||
&ContextSnapshotOptions::default(),
|
||||
)
|
||||
};
|
||||
let before = render("hidden before", "visible before");
|
||||
let hidden_change = render("hidden after", "visible before");
|
||||
let visible_change = render("hidden before", "visible after");
|
||||
assert!(before.contains("visible before"));
|
||||
assert!(before.contains("line 79"));
|
||||
assert!(!before.contains("hidden before"));
|
||||
assert!(before.contains("<OMITTED 64 LINES; ~129 TOKENS; hash="));
|
||||
assert!(render(&"é".repeat(13), "visible before").contains("~129 TOKENS; hash="));
|
||||
assert_ne!(before, hidden_change);
|
||||
assert_eq!(
|
||||
before.lines().find(|line| line.contains("<OMITTED")),
|
||||
visible_change
|
||||
.lines()
|
||||
.find(|line| line.contains("<OMITTED"))
|
||||
);
|
||||
let near_threshold = (0..24)
|
||||
.map(|index| format!("line {index:02}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
assert!(
|
||||
!render_test_items(
|
||||
&[json!({ "type": "message", "role": "user", "content": [
|
||||
{ "type": "input_text", "text": near_threshold }
|
||||
] })],
|
||||
&ContextSnapshotOptions::default(),
|
||||
)
|
||||
.contains("<OMITTED")
|
||||
);
|
||||
}
|
||||
564
akode-rs/core/tests/common/context_snapshot/normalize.rs
Normal file
564
akode-rs/core/tests/common/context_snapshot/normalize.rs
Normal file
@@ -0,0 +1,564 @@
|
||||
//! All display normalization for context snapshots: known text, volatile values and tool schemas.
|
||||
//! Request grouping stays independent of these display rules.
|
||||
|
||||
use super::ContextSnapshotOptions;
|
||||
use regex_lite::Regex;
|
||||
use serde_json::Value;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
const GUARDIAN_INSTRUCTIONS_PREFIX: &str = "You are judging one planned coding-agent action.";
|
||||
const GUARDIAN_PROVENANCE_PREFIX: &str = "# Transcript provenance\n";
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum TextSource<'a> {
|
||||
ModelInstructions,
|
||||
Message(&'a str),
|
||||
FunctionArguments,
|
||||
Other,
|
||||
}
|
||||
|
||||
// Normalize or replace text in one place, after the structural renderer selects a content item.
|
||||
// Per-snapshot state gives distinct working directories stable labels without fixture-specific names.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Normalizer {
|
||||
working_directories: Vec<String>,
|
||||
workspace_roots: Vec<String>,
|
||||
temporary_directories: Vec<String>,
|
||||
prompt_cache_keys: Vec<String>,
|
||||
uuids: Vec<String>,
|
||||
}
|
||||
|
||||
impl Normalizer {
|
||||
pub(super) fn observe_request(&mut self, input: &[Value]) {
|
||||
// Permissions precede environment context, but can cite the same paths.
|
||||
for item in input.iter().filter(|item| item["role"] == "user") {
|
||||
for part in item["content"].as_array().into_iter().flatten() {
|
||||
if let Some(text) = part["text"].as_str()
|
||||
&& guidance_tag(text) == Some("environment_context")
|
||||
{
|
||||
self.environment(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn text(
|
||||
&mut self,
|
||||
text: &str,
|
||||
source: TextSource<'_>,
|
||||
options: &ContextSnapshotOptions,
|
||||
) -> String {
|
||||
let text = if matches!(source, TextSource::FunctionArguments) {
|
||||
self.arguments(text)
|
||||
} else {
|
||||
text.to_string()
|
||||
};
|
||||
let text = normalize_line_endings(&text);
|
||||
let segment = known_segment_name(&text, source);
|
||||
let text = match segment.as_deref() {
|
||||
Some("PERMISSIONS_INSTRUCTIONS") => self.permissions(&text),
|
||||
Some("ENVIRONMENT_CONTEXT") => self.environment(&text),
|
||||
_ => text,
|
||||
};
|
||||
let text = self.normalize_values(&text);
|
||||
if options.rewrite_known_segments
|
||||
&& let Some(segment) = segment
|
||||
&& !(options.preserve_environment_context && segment == "ENVIRONMENT_CONTEXT")
|
||||
{
|
||||
let marker = format!("<{segment}>");
|
||||
if segment == "COMPACTION_SUMMARY"
|
||||
&& let Some((_, summary)) = text.split_once('\n')
|
||||
&& !summary.is_empty()
|
||||
{
|
||||
// Only the standard preamble is guidance; the generated summary is conversation data.
|
||||
format!("{marker}\n{summary}")
|
||||
} else {
|
||||
marker
|
||||
}
|
||||
} else {
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn json(&mut self, value: &Value) -> Value {
|
||||
let mut value = value.clone();
|
||||
normalize_json(&mut value, &mut |text| {
|
||||
normalize_stable_text(&self.normalize_uuids(text))
|
||||
});
|
||||
value
|
||||
}
|
||||
|
||||
fn arguments(&mut self, text: &str) -> String {
|
||||
serde_json::from_str::<Value>(text)
|
||||
.map(|value| self.json(&value).to_string())
|
||||
.unwrap_or_else(|_| text.to_string())
|
||||
}
|
||||
|
||||
fn normalize_uuids(&mut self, text: &str) -> String {
|
||||
uuid_regex()
|
||||
.replace_all(text, |captures: ®ex_lite::Captures<'_>| {
|
||||
let id = captures[0].to_ascii_lowercase();
|
||||
format!("<UUID {}>", stable_index(&mut self.uuids, &id))
|
||||
})
|
||||
.into_owned()
|
||||
}
|
||||
|
||||
pub(super) fn prompt_cache_key(&mut self, key: &str) -> String {
|
||||
format!(
|
||||
"<PROMPT_CACHE_KEY {}>",
|
||||
stable_index(&mut self.prompt_cache_keys, key)
|
||||
)
|
||||
}
|
||||
|
||||
fn normalize_values(&mut self, text: &str) -> String {
|
||||
// Tool calls report elapsed times in an otherwise stable output header.
|
||||
let text = if text.starts_with("Script ") || text.starts_with("Wall time: ") {
|
||||
static WALL_TIME: OnceLock<Regex> = OnceLock::new();
|
||||
WALL_TIME
|
||||
.get_or_init(|| {
|
||||
Regex::new(r"(?m)^(Wall time:?) [0-9]+(?:\.[0-9]+)? seconds( \(code-mode [0-9]+(?:\.[0-9]+)? seconds; overhead -?[0-9]+(?:\.[0-9]+)? seconds\))?$")
|
||||
.expect("tool wall time regex")
|
||||
})
|
||||
.replace(text, |captures: ®ex_lite::Captures<'_>| {
|
||||
let prefix = &captures[1];
|
||||
if captures.get(2).is_some() {
|
||||
format!("{prefix} <DURATION> seconds (code-mode <DURATION> seconds; overhead <DURATION> seconds)")
|
||||
} else {
|
||||
format!("{prefix} <DURATION> seconds")
|
||||
}
|
||||
})
|
||||
.into_owned()
|
||||
} else {
|
||||
text.to_string()
|
||||
};
|
||||
let text = if text.starts_with("# AGENTS.md instructions for ") {
|
||||
let (header, body) = text.split_once('\n').unwrap_or((&text, ""));
|
||||
if let Some((_, directory)) = header.split_once("for ")
|
||||
&& (directory.starts_with('/') || directory.as_bytes().get(1) == Some(&b':'))
|
||||
{
|
||||
format!("# AGENTS.md instructions for <AGENTS_DIRECTORY>\n{body}")
|
||||
} else {
|
||||
text
|
||||
}
|
||||
} else {
|
||||
text
|
||||
};
|
||||
normalize_skill_references(&self.normalize_uuids(&text))
|
||||
}
|
||||
|
||||
pub(super) fn environment(&mut self, text: &str) -> String {
|
||||
static CWD: OnceLock<Regex> = OnceLock::new();
|
||||
static PATH: OnceLock<Regex> = OnceLock::new();
|
||||
static HOST: OnceLock<Regex> = OnceLock::new();
|
||||
let cwd = CWD.get_or_init(|| Regex::new(r"<cwd>([^<]+)</cwd>").expect("cwd regex"));
|
||||
let path = PATH.get_or_init(|| {
|
||||
Regex::new(r"(<(cwd|root|path|glob)>)([^<]*)").expect("environment path regex")
|
||||
});
|
||||
let host = HOST.get_or_init(|| {
|
||||
Regex::new(r"(<(shell|shell_version|current_date|timezone)>)[^<]*")
|
||||
.expect("host context regex")
|
||||
});
|
||||
for captures in cwd.captures_iter(text) {
|
||||
let directory = captures[1].to_string();
|
||||
if !self.working_directories.iter().any(|known| {
|
||||
directory.strip_prefix(known).is_some_and(|suffix| {
|
||||
suffix.is_empty() || suffix.starts_with('/') || suffix.starts_with('\\')
|
||||
})
|
||||
}) {
|
||||
self.working_directories.push(directory);
|
||||
}
|
||||
}
|
||||
for captures in path.captures_iter(text) {
|
||||
if &captures[2] != "root" {
|
||||
continue;
|
||||
}
|
||||
let root = &captures[3];
|
||||
let is_under = |base: &str| {
|
||||
root.strip_prefix(base).is_some_and(|suffix| {
|
||||
suffix.is_empty() || suffix.starts_with('/') || suffix.starts_with('\\')
|
||||
})
|
||||
};
|
||||
if (root.starts_with('/') || root.as_bytes().get(1) == Some(&b':'))
|
||||
&& !self.working_directories.iter().any(|cwd| is_under(cwd))
|
||||
&& !self.workspace_roots.iter().any(|known| is_under(known))
|
||||
{
|
||||
self.workspace_roots.push(root.to_string());
|
||||
}
|
||||
}
|
||||
let aliases = self.path_aliases();
|
||||
let text = path.replace_all(text, |captures: ®ex_lite::Captures<'_>| {
|
||||
let value = &captures[3];
|
||||
format!(
|
||||
"{}{}",
|
||||
&captures[1],
|
||||
normalize_path(value, &aliases).as_deref().unwrap_or(value)
|
||||
)
|
||||
});
|
||||
host.replace_all(&text, |captures: ®ex_lite::Captures<'_>| {
|
||||
let label = match &captures[2] {
|
||||
"shell" => "HOST_SHELL",
|
||||
"shell_version" => "HOST_SHELL_VERSION",
|
||||
"current_date" => "CURRENT_DATE",
|
||||
"timezone" => "HOST_TIMEZONE",
|
||||
_ => unreachable!(),
|
||||
};
|
||||
format!("{}<{label}>", &captures[1])
|
||||
})
|
||||
.into_owned()
|
||||
}
|
||||
|
||||
fn path_aliases(&self) -> Vec<(String, String)> {
|
||||
let mut aliases = self
|
||||
.working_directories
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, path)| {
|
||||
let label = if index == 0 {
|
||||
"<CWD>".to_string()
|
||||
} else {
|
||||
format!("<CWD {}>", index + 1)
|
||||
};
|
||||
(path.clone(), label)
|
||||
})
|
||||
.chain(
|
||||
self.workspace_roots
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, path)| (path.clone(), format!("<WORKSPACE_ROOT {}>", index + 1))),
|
||||
)
|
||||
.collect::<Vec<_>>();
|
||||
aliases.sort_by_key(|(path, _)| std::cmp::Reverse(path.len()));
|
||||
aliases
|
||||
}
|
||||
|
||||
fn permissions(&mut self, text: &str) -> String {
|
||||
static PATH: OnceLock<Regex> = OnceLock::new();
|
||||
let path = PATH.get_or_init(|| Regex::new(r"`([^`]+)`").expect("permission path regex"));
|
||||
let aliases = self.path_aliases();
|
||||
text.split('\n')
|
||||
.map(|line| {
|
||||
let writable = line.trim_start().starts_with("The writable root");
|
||||
if !writable && !line.starts_with("- path `") && !line.starts_with("- glob `") {
|
||||
return line.to_string();
|
||||
}
|
||||
path.replace_all(line, |captures: ®ex_lite::Captures<'_>| {
|
||||
let value = &captures[1];
|
||||
let normalized =
|
||||
normalize_path(value, &aliases).or_else(|| self.temporary_path(value));
|
||||
format!("`{}`", normalized.as_deref().unwrap_or(value))
|
||||
})
|
||||
.into_owned()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
fn temporary_path(&mut self, value: &str) -> Option<String> {
|
||||
// tempfile uses randomized `.tmp…` directories under the host's configured temp root.
|
||||
// Keep other names, including stable policy paths, visible to the fingerprint.
|
||||
let temp_dir = std::env::temp_dir().to_string_lossy().replace('\\', "/");
|
||||
let value = value.replace('\\', "/");
|
||||
let suffix = value.strip_prefix(temp_dir.trim_end_matches('/'))?;
|
||||
if suffix.is_empty() {
|
||||
return Some("<TEMP_DIR>".to_string());
|
||||
}
|
||||
let suffix = suffix.strip_prefix('/')?;
|
||||
let first = suffix.split('/').next()?;
|
||||
let tail = &suffix[first.len()..];
|
||||
if !first.strip_prefix(".tmp").is_some_and(|random| {
|
||||
!random.is_empty()
|
||||
&& random
|
||||
.chars()
|
||||
.all(|character| character.is_ascii_alphanumeric())
|
||||
}) {
|
||||
return Some(format!("<TEMP_DIR>/{suffix}"));
|
||||
}
|
||||
let index = stable_index(&mut self.temporary_directories, first);
|
||||
Some(format!("<TEMP_DIR>/<TEMP {index}>{tail}"))
|
||||
}
|
||||
}
|
||||
|
||||
fn stable_index(values: &mut Vec<String>, value: &str) -> usize {
|
||||
if let Some(index) = values.iter().position(|known| known == value) {
|
||||
index + 1
|
||||
} else {
|
||||
values.push(value.to_string());
|
||||
values.len()
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_path(value: &str, aliases: &[(String, String)]) -> Option<String> {
|
||||
aliases.iter().find_map(|(path, label)| {
|
||||
let suffix = value.strip_prefix(path)?;
|
||||
(suffix.is_empty() || suffix.starts_with('/') || suffix.starts_with('\\'))
|
||||
.then(|| format!("{label}{}", suffix.replace('\\', "/")))
|
||||
})
|
||||
}
|
||||
|
||||
fn known_segment_name(text: &str, source: TextSource<'_>) -> Option<String> {
|
||||
let prefixes: &[(&str, &str)] = match source {
|
||||
TextSource::ModelInstructions => &[
|
||||
(GUARDIAN_INSTRUCTIONS_PREFIX, "GUARDIAN_INSTRUCTIONS"),
|
||||
(GUARDIAN_PROVENANCE_PREFIX, "GUARDIAN_INSTRUCTIONS"),
|
||||
("", "MODEL_INSTRUCTIONS"),
|
||||
],
|
||||
TextSource::Message("developer") => &[
|
||||
(GUARDIAN_INSTRUCTIONS_PREFIX, "GUARDIAN_INSTRUCTIONS"),
|
||||
(GUARDIAN_PROVENANCE_PREFIX, "GUARDIAN_INSTRUCTIONS"),
|
||||
],
|
||||
TextSource::Message("user") => &[
|
||||
("# AGENTS.md instructions", "AGENTS_MD"),
|
||||
(
|
||||
"You are performing a CONTEXT CHECKPOINT COMPACTION.",
|
||||
"SUMMARIZATION_PROMPT",
|
||||
),
|
||||
(
|
||||
"Another language model started to solve this problem",
|
||||
"COMPACTION_SUMMARY",
|
||||
),
|
||||
],
|
||||
_ => &[],
|
||||
};
|
||||
if let Some((_, name)) = prefixes
|
||||
.iter()
|
||||
.find(|(prefix, _)| text.starts_with(*prefix))
|
||||
{
|
||||
return Some((*name).to_string());
|
||||
}
|
||||
let tag = guidance_tag(text)?;
|
||||
matches!(
|
||||
(source, tag),
|
||||
(
|
||||
TextSource::Message("developer"),
|
||||
"permissions instructions"
|
||||
| "collaboration_mode"
|
||||
| "multi_agent_role"
|
||||
| "multi_agent_mode"
|
||||
| "model_catalog"
|
||||
| "apps_instructions"
|
||||
| "skills_instructions"
|
||||
| "plugins_instructions"
|
||||
| "model_switch"
|
||||
| "personality_spec"
|
||||
) | (TextSource::Message("user"), "environment_context")
|
||||
)
|
||||
.then(|| tag.replace(' ', "_").to_ascii_uppercase())
|
||||
}
|
||||
|
||||
fn normalize_skill_references(text: &str) -> String {
|
||||
text.split('\n')
|
||||
.map(|line| {
|
||||
let line = if let Some((before, after)) = line.split_once("<path>")
|
||||
&& let Some((path, rest)) = after.split_once("</path>")
|
||||
{
|
||||
format!("{before}<path>{}</path>{rest}", normalize_skill_path(path))
|
||||
} else if let Some((before, path)) = line.split_once(" = `")
|
||||
&& before.starts_with("- `r")
|
||||
&& let Some(path) = path.strip_suffix('`')
|
||||
{
|
||||
format!("{before} = `{}`", normalize_skill_path(path))
|
||||
} else if let Some((before, path)) = line.split_once("(file: ")
|
||||
&& let Some(path) = path.strip_suffix(')')
|
||||
{
|
||||
format!("{before}(file: {})", normalize_skill_path(path))
|
||||
} else {
|
||||
line.to_string()
|
||||
};
|
||||
normalize_stable_text(&line)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
fn normalize_skill_path(path: &str) -> String {
|
||||
if !path.starts_with('/') && !path.starts_with('\\') && path.as_bytes().get(1) != Some(&b':') {
|
||||
return path.to_string();
|
||||
}
|
||||
let path = path.replace('\\', "/");
|
||||
if let Some((_, rest)) = path.rsplit_once("/plugins/cache/") {
|
||||
format!("<PLUGINS_CACHE>/{rest}")
|
||||
} else if let Some((_, rest)) = path.rsplit_once("/.agents/skills/") {
|
||||
format!("<PROJECT_SKILLS>/{rest}")
|
||||
} else if let Some((_, rest)) = path.rsplit_once("/skills/") {
|
||||
format!("<SKILLS_ROOT>/{rest}")
|
||||
} else if path.ends_with("/skills") {
|
||||
"<SKILLS_ROOT>".to_string()
|
||||
} else {
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_line_endings(text: &str) -> String {
|
||||
text.replace("\r\n", "\n").replace('\r', "\n")
|
||||
}
|
||||
|
||||
fn normalize_stable_text(text: &str) -> String {
|
||||
static SYSTEM_SKILL_PATH: OnceLock<Regex> = OnceLock::new();
|
||||
static TURN_TIME: OnceLock<Regex> = OnceLock::new();
|
||||
static SANDBOX: OnceLock<Regex> = OnceLock::new();
|
||||
let skill = SYSTEM_SKILL_PATH.get_or_init(|| {
|
||||
Regex::new(r"/[^)\n]*/skills/\.system/([^/\n]+)/SKILL\.md")
|
||||
.expect("system skill path regex")
|
||||
});
|
||||
let time = TURN_TIME
|
||||
.get_or_init(|| Regex::new(r#""turn_started_at_unix_ms":\d+"#).expect("turn time regex"));
|
||||
let sandbox =
|
||||
SANDBOX.get_or_init(|| Regex::new(r#""sandbox":"[^"]+""#).expect("sandbox regex"));
|
||||
let text = normalize_line_endings(text);
|
||||
let text = skill.replace_all(&text, "<SYSTEM_SKILLS_ROOT>/$1/SKILL.md");
|
||||
let text = uuid_regex().replace_all(&text, "<UUID>");
|
||||
let text = time.replace_all(&text, r#""turn_started_at_unix_ms":<UNIX_MS>"#);
|
||||
sandbox
|
||||
.replace_all(&text, r#""sandbox":"<SANDBOX>""#)
|
||||
.into_owned()
|
||||
}
|
||||
|
||||
fn uuid_regex() -> &'static Regex {
|
||||
static UUID: OnceLock<Regex> = OnceLock::new();
|
||||
UUID.get_or_init(|| {
|
||||
Regex::new(
|
||||
r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b",
|
||||
)
|
||||
.expect("uuid regex")
|
||||
})
|
||||
}
|
||||
|
||||
// Hash complete normalized values whenever the readable rendering clips content.
|
||||
pub(super) fn fingerprint(value: &Value) -> String {
|
||||
let mut normalized = value.clone();
|
||||
normalize_json(&mut normalized, &mut normalize_stable_text);
|
||||
let bytes = serde_json::to_vec(&normalized).expect("snapshot value should serialize");
|
||||
format!("{:016x}", fnv1a(&bytes))
|
||||
}
|
||||
|
||||
fn fnv1a(bytes: &[u8]) -> u64 {
|
||||
bytes.iter().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
|
||||
(hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3)
|
||||
})
|
||||
}
|
||||
|
||||
fn normalize_json(value: &mut Value, normalize: &mut impl FnMut(&str) -> String) {
|
||||
match value {
|
||||
Value::String(text) => *text = normalize(text),
|
||||
Value::Array(values) => values
|
||||
.iter_mut()
|
||||
.for_each(|value| normalize_json(value, normalize)),
|
||||
Value::Object(map) => {
|
||||
map.sort_keys();
|
||||
for value in map.values_mut() {
|
||||
normalize_json(value, normalize);
|
||||
}
|
||||
}
|
||||
Value::Null | Value::Bool(_) | Value::Number(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Shell guidance and its yield-time wording intentionally differ on Windows. Compare all other
|
||||
// tool schema fields, while keeping the context snapshots identical across operating systems.
|
||||
pub(super) fn portable_tool_schema(tool: &Value) -> Value {
|
||||
const BASE: &str =
|
||||
"Runs a command in a PTY, returning output or a session ID for ongoing interaction.";
|
||||
// Exact current Windows-only suffix. A change to its wording must be reviewed explicitly.
|
||||
const WINDOWS_SAFETY_SUFFIX_HASH: u64 = 0x6de3_23e4_7060_6128;
|
||||
const UNIX_WAIT: &str =
|
||||
"Wait before yielding output. Defaults to 10000 ms; effective range is 250-30000 ms.";
|
||||
const WINDOWS_WAIT: &str = "Maximum time to wait before returning a session ID for a still-running command. Commands that finish sooner return immediately. For ordinary commands, omit this parameter to use the 10000 ms default. Effective range on Windows is 10000-30000 ms.";
|
||||
let mut stable = tool.clone();
|
||||
if let Some(Value::Array(members)) = stable.get_mut("tools") {
|
||||
for member in members {
|
||||
*member = portable_tool_schema(member);
|
||||
}
|
||||
}
|
||||
let definition = if stable.get("function").is_some() {
|
||||
stable
|
||||
.get_mut("function")
|
||||
.expect("function tool definition")
|
||||
} else {
|
||||
&mut stable
|
||||
};
|
||||
if definition.get("name").and_then(Value::as_str) == Some("exec") {
|
||||
if let Some(Value::String(description)) = definition.get_mut("description") {
|
||||
// Code mode embeds the exec_command description and its TypeScript declaration
|
||||
// inside the exec tool. Apply the same narrow platform normalization there.
|
||||
if let Some((start, section)) = description.split_once("### `exec_command`\n")
|
||||
&& let Some(rest) = section.strip_prefix(BASE)
|
||||
&& let Some((suffix, _)) = rest.split_once("\n\nexec tool declaration:")
|
||||
&& suffix.starts_with("\n\nWindows safety rules:")
|
||||
&& fnv1a(normalize_line_endings(suffix).as_bytes()) == WINDOWS_SAFETY_SUFFIX_HASH
|
||||
{
|
||||
*description =
|
||||
format!("{start}### `exec_command`\n{BASE}{}", &rest[suffix.len()..]);
|
||||
}
|
||||
for platform_wait in [UNIX_WAIT, WINDOWS_WAIT] {
|
||||
*description = description.replace(
|
||||
&format!(" // {platform_wait}"),
|
||||
" // <PLATFORM_WAIT_GUIDANCE>",
|
||||
);
|
||||
}
|
||||
}
|
||||
return stable;
|
||||
}
|
||||
if definition.get("name").and_then(Value::as_str) != Some("exec_command") {
|
||||
return stable;
|
||||
}
|
||||
if let Some(Value::String(description)) = definition.get_mut("description") {
|
||||
if let Some(rest) = description.strip_prefix(BASE) {
|
||||
let suffix = rest
|
||||
.split_once("\n\nexec tool declaration:")
|
||||
.map_or(rest, |(suffix, _)| suffix);
|
||||
if suffix.starts_with("\n\nWindows safety rules:")
|
||||
&& fnv1a(normalize_line_endings(suffix).as_bytes()) == WINDOWS_SAFETY_SUFFIX_HASH
|
||||
{
|
||||
*description = format!("{BASE}{}", &rest[suffix.len()..]);
|
||||
}
|
||||
}
|
||||
*description = description.replace(
|
||||
&format!(" // {WINDOWS_WAIT}"),
|
||||
&format!(" // {UNIX_WAIT}"),
|
||||
);
|
||||
}
|
||||
if let Some(Value::String(wait)) =
|
||||
definition.pointer_mut("/parameters/properties/yield_time_ms/description")
|
||||
&& (wait == UNIX_WAIT || wait == WINDOWS_WAIT)
|
||||
{
|
||||
*wait = "<PLATFORM_WAIT_GUIDANCE>".to_string();
|
||||
}
|
||||
stable
|
||||
}
|
||||
|
||||
pub(super) fn is_bundled_model_instructions(text: &str) -> bool {
|
||||
static PROMPTS: OnceLock<Vec<String>> = OnceLock::new();
|
||||
text == akode_models_manager::model_info::BASE_INSTRUCTIONS
|
||||
|| PROMPTS
|
||||
.get_or_init(|| {
|
||||
akode_models_manager::bundled_models_response()
|
||||
.expect("bundled model catalog")
|
||||
.models
|
||||
.into_iter()
|
||||
.filter_map(|model| model.model_messages?.instructions_template)
|
||||
.collect()
|
||||
})
|
||||
.iter()
|
||||
.any(|prompt| prompt == text)
|
||||
}
|
||||
|
||||
// Only complete, balanced wrappers identify guidance. Adjacent or malformed wrappers remain text.
|
||||
fn guidance_tag(text: &str) -> Option<&str> {
|
||||
let text = text.trim();
|
||||
let (tag, rest) = text.strip_prefix('<')?.split_once('>')?;
|
||||
let open = &text[..tag.len() + 2];
|
||||
let close = format!("</{tag}>");
|
||||
let mut depth = 1;
|
||||
for (offset, _) in rest.match_indices('<') {
|
||||
let after = &rest[offset..];
|
||||
if after.starts_with(open) {
|
||||
depth += 1;
|
||||
} else if after.starts_with(&close) {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
return (after == close.as_str()).then_some(tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
63
akode-rs/core/tests/common/context_snapshot/text.rs
Normal file
63
akode-rs/core/tests/common/context_snapshot/text.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
//! Layout and clipping for text already normalized by the context snapshot normalizer.
|
||||
|
||||
use super::ContextSnapshotOptions;
|
||||
use super::MAX_SNAPSHOT_LINE_CHARS;
|
||||
use super::normalize::Normalizer;
|
||||
use super::normalize::TextSource;
|
||||
use super::normalize::fingerprint;
|
||||
use serde_json::Value;
|
||||
|
||||
const RETAINED_SEGMENT_EDGE_LINES: usize = 8;
|
||||
|
||||
pub(super) fn render_text(
|
||||
text: &str,
|
||||
source: TextSource<'_>,
|
||||
options: &ContextSnapshotOptions,
|
||||
normalizer: &mut Normalizer,
|
||||
) -> String {
|
||||
if text.is_empty() && matches!(source, TextSource::ModelInstructions) {
|
||||
return "\"\"".to_string();
|
||||
}
|
||||
let normalized = normalizer.text(text, source, options);
|
||||
let mut lines = normalized.split('\n').collect::<Vec<_>>();
|
||||
// Trim only when the omitted middle is larger than one retained edge.
|
||||
// The hidden middle has a fingerprint; visible edits change only their own lines.
|
||||
let marker = (lines.len() > RETAINED_SEGMENT_EDGE_LINES * 3).then(|| {
|
||||
let omitted =
|
||||
&lines[RETAINED_SEGMENT_EDGE_LINES..lines.len() - RETAINED_SEGMENT_EDGE_LINES];
|
||||
let omitted_text = omitted.join("\n");
|
||||
format!(
|
||||
"<OMITTED {} LINES; ~{} TOKENS; hash={}>",
|
||||
omitted.len(),
|
||||
omitted_text.chars().count() / 4,
|
||||
fingerprint(&Value::String(omitted_text))
|
||||
)
|
||||
});
|
||||
if let Some(marker) = &marker {
|
||||
lines.splice(
|
||||
RETAINED_SEGMENT_EDGE_LINES..lines.len() - RETAINED_SEGMENT_EDGE_LINES,
|
||||
[marker.as_str()],
|
||||
);
|
||||
}
|
||||
lines
|
||||
.into_iter()
|
||||
.map(|line| {
|
||||
let line = line.trim_end();
|
||||
let len = line.chars().count();
|
||||
let line = if len > MAX_SNAPSHOT_LINE_CHARS {
|
||||
let head = (MAX_SNAPSHOT_LINE_CHARS - 3) * 2 / 3;
|
||||
let tail = MAX_SNAPSHOT_LINE_CHARS - 3 - head;
|
||||
format!(
|
||||
"{}...{} [hash={}]",
|
||||
line.chars().take(head).collect::<String>(),
|
||||
line.chars().skip(len - tail).collect::<String>(),
|
||||
fingerprint(&Value::String(line.to_string()))
|
||||
)
|
||||
} else {
|
||||
line.to_string()
|
||||
};
|
||||
line.replace('\\', "\\\\")
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
100
akode-rs/core/tests/common/exec_server.rs
Normal file
100
akode-rs/core/tests/common/exec_server.rs
Normal file
@@ -0,0 +1,100 @@
|
||||
//! Shared native exec-server process fixture; dropping it stops the child process.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
use tempfile::TempDir;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::process::Child;
|
||||
use tokio::process::ChildStdout;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::Instant;
|
||||
use tokio::time::timeout;
|
||||
|
||||
const EXEC_SERVER_START_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
pub struct ExecServerProcess {
|
||||
_codex_home: TempDir,
|
||||
child: Child,
|
||||
_stdout: BufReader<ChildStdout>,
|
||||
pub websocket_url: String,
|
||||
}
|
||||
|
||||
impl ExecServerProcess {
|
||||
pub async fn start() -> Result<Self> {
|
||||
Self::start_with_env(&[]).await
|
||||
}
|
||||
|
||||
pub async fn start_with_env(env: &[(&str, &str)]) -> Result<Self> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let mut command = Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
|
||||
command.envs(env.iter().copied());
|
||||
Self::start_command(command, codex_home).await
|
||||
}
|
||||
|
||||
pub async fn start_with_version(version: &str) -> Result<Self> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let package = codex_home.path().join("package");
|
||||
let bin = package.join("bin");
|
||||
std::fs::create_dir_all(&bin)?;
|
||||
let executable = bin.join(format!("codex{}", std::env::consts::EXE_SUFFIX));
|
||||
akode_utils_cargo_bin::copy_executable(
|
||||
&akode_utils_cargo_bin::cargo_bin("akode")?,
|
||||
&executable,
|
||||
)?;
|
||||
std::fs::write(
|
||||
package.join("akode-package.json"),
|
||||
serde_json::to_vec(&serde_json::json!({"version": version}))?,
|
||||
)?;
|
||||
Self::start_command(Command::new(executable), codex_home).await
|
||||
}
|
||||
|
||||
async fn start_command(mut command: Command, codex_home: TempDir) -> Result<Self> {
|
||||
let mut child = command
|
||||
.args(["exec-server", "--listen", "ws://127.0.0.1:0"])
|
||||
.env("AKODE_HOME", codex_home.path())
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.kill_on_drop(true)
|
||||
.spawn()?;
|
||||
let stdout = child
|
||||
.stdout
|
||||
.take()
|
||||
.context("exec-server stdout should be piped")?;
|
||||
let mut stdout = BufReader::new(stdout);
|
||||
let deadline = Instant::now() + EXEC_SERVER_START_TIMEOUT;
|
||||
let websocket_url = loop {
|
||||
let remaining = deadline
|
||||
.checked_duration_since(Instant::now())
|
||||
.context("timed out waiting for exec-server listen URL")?;
|
||||
let mut line = String::new();
|
||||
let bytes_read = timeout(remaining, stdout.read_line(&mut line))
|
||||
.await
|
||||
.context("timed out reading exec-server listen URL")??;
|
||||
if bytes_read == 0 {
|
||||
bail!("exec-server exited before printing its listen URL");
|
||||
}
|
||||
let line = line.trim();
|
||||
if line.starts_with("ws://") {
|
||||
break line.to_string();
|
||||
}
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
_codex_home: codex_home,
|
||||
child,
|
||||
_stdout: stdout,
|
||||
websocket_url,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ExecServerProcess {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.start_kill();
|
||||
}
|
||||
}
|
||||
69
akode-rs/core/tests/common/hooks.rs
Normal file
69
akode-rs/core/tests/common/hooks.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
use akode_config::CONFIG_TOML_FILE;
|
||||
use akode_config::ConfigLayerStack;
|
||||
use akode_config::TomlValue;
|
||||
use akode_core::config::Config;
|
||||
use akode_features::Feature;
|
||||
use akode_hooks::HookListEntry;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
|
||||
pub fn trust_discovered_hooks(config: &mut Config) {
|
||||
config
|
||||
.features
|
||||
.enable(Feature::CodexHooks)
|
||||
.expect("test config should allow feature update");
|
||||
|
||||
let listed = akode_hooks::list_hooks(akode_hooks::HooksConfig {
|
||||
feature_enabled: true,
|
||||
config_layer_stack: Some(config.config_layer_stack.clone()),
|
||||
..codex_hooks::HooksConfig::default()
|
||||
});
|
||||
assert!(
|
||||
!listed.hooks.is_empty(),
|
||||
"trusted hook fixture should discover at least one hook"
|
||||
);
|
||||
trust_hooks(config, listed.hooks);
|
||||
}
|
||||
|
||||
pub fn trust_hooks(config: &mut Config, hooks: Vec<HookListEntry>) {
|
||||
config.config_layer_stack =
|
||||
trusted_config_layer_stack(&config.config_layer_stack, &config.codex_home, hooks);
|
||||
}
|
||||
|
||||
pub fn trusted_config_layer_stack(
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
codex_home: &AbsolutePathBuf,
|
||||
hooks: Vec<HookListEntry>,
|
||||
) -> ConfigLayerStack {
|
||||
let mut user_config = config_layer_stack
|
||||
.get_active_user_layer()
|
||||
.map(|layer| layer.config.clone())
|
||||
.unwrap_or_else(|| TomlValue::Table(Default::default()));
|
||||
let user_table = user_config
|
||||
.as_table_mut()
|
||||
.expect("user config should be a table");
|
||||
let hooks_table = user_table
|
||||
.entry("hooks")
|
||||
.or_insert_with(|| TomlValue::Table(Default::default()))
|
||||
.as_table_mut()
|
||||
.expect("hooks config should be a table");
|
||||
let state_table = hooks_table
|
||||
.entry("state")
|
||||
.or_insert_with(|| TomlValue::Table(Default::default()))
|
||||
.as_table_mut()
|
||||
.expect("hook state config should be a table");
|
||||
for hook in hooks {
|
||||
let mut hook_state = TomlValue::Table(Default::default());
|
||||
let hook_state_table = hook_state
|
||||
.as_table_mut()
|
||||
.expect("hook state should be a table");
|
||||
hook_state_table.insert(
|
||||
"trusted_hash".to_string(),
|
||||
TomlValue::String(hook.current_hash),
|
||||
);
|
||||
state_table.insert(hook.key, hook_state);
|
||||
}
|
||||
|
||||
config_layer_stack
|
||||
.with_user_config(&codex_home.join(CONFIG_TOML_FILE), user_config)
|
||||
.expect("hook user config should be valid")
|
||||
}
|
||||
796
akode-rs/core/tests/common/lib.rs
Normal file
796
akode-rs/core/tests/common/lib.rs
Normal file
@@ -0,0 +1,796 @@
|
||||
#![allow(clippy::expect_used)]
|
||||
|
||||
use anyhow::Context as _;
|
||||
use anyhow::ensure;
|
||||
use akode_arg0::Arg0PathEntryGuard;
|
||||
use akode_utils_cargo_bin::CargoBinError;
|
||||
use ctor::ctor;
|
||||
use std::sync::OnceLock;
|
||||
use tempfile::TempDir;
|
||||
|
||||
use akode_config::test_support::ManagedConfigFixture;
|
||||
use akode_core::CodexThread;
|
||||
use akode_core::config::Config;
|
||||
use akode_core::config::ConfigBuilder;
|
||||
use akode_core::config::ConfigOverrides;
|
||||
pub use akode_core::test_support::TestCodexResponsesRequestKind;
|
||||
pub use akode_core::test_support::responses_metadata;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
pub use akode_utils_absolute_path::test_support::PathBufExt;
|
||||
pub use akode_utils_absolute_path::test_support::PathExt;
|
||||
use regex_lite::Regex;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(unix)]
|
||||
pub mod code_mode_host;
|
||||
pub mod context_snapshot;
|
||||
pub mod exec_server;
|
||||
pub mod hooks;
|
||||
pub mod mcp_test_server;
|
||||
pub mod network_policy_mcp;
|
||||
pub mod oauth;
|
||||
pub mod process;
|
||||
pub mod responses;
|
||||
pub mod startup;
|
||||
pub mod streaming_sse;
|
||||
pub mod test_codex;
|
||||
pub mod test_codex_exec;
|
||||
mod test_environment;
|
||||
pub mod tracing;
|
||||
|
||||
pub(crate) use test_environment::TestEnvironment;
|
||||
pub use test_environment::TestTargetOs;
|
||||
pub use test_environment::is_remote_test_environment;
|
||||
#[doc(hidden)]
|
||||
pub use test_environment::is_wine_exec_test_environment;
|
||||
#[doc(hidden)]
|
||||
pub use test_environment::test_docker_container_name;
|
||||
pub(crate) use test_environment::test_environment;
|
||||
pub use test_environment::test_target_os;
|
||||
|
||||
static TEST_ARG0_PATH_ENTRY: OnceLock<Option<Arg0PathEntryGuard>> = OnceLock::new();
|
||||
|
||||
#[ctor]
|
||||
fn enable_deterministic_unified_exec_process_ids_for_tests() {
|
||||
akode_core::test_support::set_thread_manager_test_mode(/*enabled*/ true);
|
||||
akode_core::test_support::set_deterministic_process_ids(/*enabled*/ true);
|
||||
}
|
||||
|
||||
#[ctor]
|
||||
fn configure_arg0_dispatch_for_test_binaries() {
|
||||
let _ = TEST_ARG0_PATH_ENTRY.get_or_init(akode_arg0::arg0_dispatch);
|
||||
}
|
||||
|
||||
#[ctor]
|
||||
fn configure_insta_workspace_root_for_snapshot_tests() {
|
||||
if std::env::var_os("INSTA_WORKSPACE_ROOT").is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let workspace_root = akode_utils_cargo_bin::repo_root()
|
||||
.ok()
|
||||
.map(|root| root.join("akode-rs"));
|
||||
|
||||
if let Some(workspace_root) = workspace_root
|
||||
&& let Ok(workspace_root) = workspace_root.canonicalize()
|
||||
{
|
||||
// Safety: this ctor runs at process startup before test threads begin.
|
||||
unsafe {
|
||||
std::env::set_var("INSTA_WORKSPACE_ROOT", workspace_root);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
pub fn assert_regex_match<'s>(pattern: &str, actual: &'s str) -> regex_lite::Captures<'s> {
|
||||
let regex = Regex::new(pattern).expect("failed to compile regex");
|
||||
regex
|
||||
.captures(actual)
|
||||
.expect("regex did not match actual value")
|
||||
}
|
||||
|
||||
pub fn test_path_buf_with_windows(unix_path: &str, windows_path: Option<&str>) -> PathBuf {
|
||||
if cfg!(windows) {
|
||||
if let Some(windows) = windows_path {
|
||||
PathBuf::from(windows)
|
||||
} else {
|
||||
let mut path = PathBuf::from(r"C:\");
|
||||
path.extend(
|
||||
unix_path
|
||||
.trim_start_matches('/')
|
||||
.split('/')
|
||||
.filter(|segment| !segment.is_empty()),
|
||||
);
|
||||
path
|
||||
}
|
||||
} else {
|
||||
PathBuf::from(unix_path)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn test_path_buf(unix_path: &str) -> PathBuf {
|
||||
test_path_buf_with_windows(unix_path, /*windows_path*/ None)
|
||||
}
|
||||
|
||||
pub fn test_absolute_path_with_windows(
|
||||
unix_path: &str,
|
||||
windows_path: Option<&str>,
|
||||
) -> AbsolutePathBuf {
|
||||
AbsolutePathBuf::from_absolute_path(test_path_buf_with_windows(unix_path, windows_path))
|
||||
.expect("test path should be absolute")
|
||||
}
|
||||
|
||||
pub fn test_absolute_path(unix_path: &str) -> AbsolutePathBuf {
|
||||
test_absolute_path_with_windows(unix_path, /*windows_path*/ None)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[allow(clippy::expect_used)]
|
||||
pub fn create_directory_symlink(source: &Path, link: &Path) {
|
||||
std::os::unix::fs::symlink(source, link).expect("create directory symlink");
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[allow(clippy::expect_used)]
|
||||
pub fn create_directory_symlink(source: &Path, link: &Path) {
|
||||
// Running this test locally may require Windows Developer Mode or an elevated process.
|
||||
std::os::windows::fs::symlink_dir(source, link)
|
||||
.expect("create directory symlink; enable Developer Mode or run the test elevated");
|
||||
}
|
||||
|
||||
pub trait TempDirExt {
|
||||
fn abs(&self) -> AbsolutePathBuf;
|
||||
}
|
||||
|
||||
impl TempDirExt for TempDir {
|
||||
fn abs(&self) -> AbsolutePathBuf {
|
||||
self.path().abs()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn test_tmp_path() -> AbsolutePathBuf {
|
||||
test_absolute_path_with_windows("/tmp", Some(r"C:\Users\codex\AppData\Local\Temp"))
|
||||
}
|
||||
|
||||
pub fn test_tmp_path_buf() -> PathBuf {
|
||||
test_tmp_path().into_path_buf()
|
||||
}
|
||||
|
||||
/// Fetch a DotSlash resource and return the resolved executable/file path.
|
||||
pub fn fetch_dotslash_file(
|
||||
dotslash_file: &std::path::Path,
|
||||
dotslash_cache: Option<&std::path::Path>,
|
||||
) -> anyhow::Result<PathBuf> {
|
||||
let mut command = std::process::Command::new("dotslash");
|
||||
command.arg("--").arg("fetch").arg(dotslash_file);
|
||||
if let Some(dotslash_cache) = dotslash_cache {
|
||||
command.env("DOTSLASH_CACHE", dotslash_cache);
|
||||
}
|
||||
let output = command.output().with_context(|| {
|
||||
format!(
|
||||
"failed to run dotslash to fetch resource {}",
|
||||
dotslash_file.display()
|
||||
)
|
||||
})?;
|
||||
ensure!(
|
||||
output.status.success(),
|
||||
"dotslash fetch failed for {}: {}",
|
||||
dotslash_file.display(),
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
);
|
||||
let fetched_path = String::from_utf8(output.stdout)
|
||||
.context("dotslash fetch output was not utf8")?
|
||||
.trim()
|
||||
.to_string();
|
||||
ensure!(!fetched_path.is_empty(), "dotslash fetch output was empty");
|
||||
let fetched_path = PathBuf::from(fetched_path);
|
||||
ensure!(
|
||||
fetched_path.is_file(),
|
||||
"dotslash returned non-file path: {}",
|
||||
fetched_path.display()
|
||||
);
|
||||
Ok(fetched_path)
|
||||
}
|
||||
|
||||
/// Returns a default `Config` whose on-disk state is confined to the provided
|
||||
/// temporary directory. Using a per-test directory keeps tests hermetic and
|
||||
/// avoids clobbering a developer’s real `~/.akode`.
|
||||
pub async fn load_default_config_for_test(codex_home: &TempDir) -> Config {
|
||||
load_default_config_for_test_with_managed_config(codex_home, ManagedConfigFixture::default())
|
||||
.await
|
||||
}
|
||||
|
||||
/// Returns a default `Config` with test-provided local managed requirements and
|
||||
/// config applied. The fixture is written below `codex_home` and loaded as the
|
||||
/// system `requirements.toml` / `config.toml`.
|
||||
pub async fn load_default_config_for_test_with_managed_config(
|
||||
codex_home: &TempDir,
|
||||
managed_config: ManagedConfigFixture,
|
||||
) -> Config {
|
||||
let mut config = load_config_with_test_provider(codex_home, managed_config).await;
|
||||
if config.model_catalog.is_none() && config.model_provider.model_catalog_url.is_none() {
|
||||
config.model_catalog = akode_models_manager::bundled_models_response().ok();
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
/// Like [`load_default_config_for_test_with_managed_config`], without injecting the bundled
|
||||
/// catalog into `config.model_catalog`. `test_codex` serves the bundled catalog through its
|
||||
/// models manager instead, so an explicit config catalog keeps its upstream meaning.
|
||||
pub(crate) async fn load_config_with_test_provider(
|
||||
codex_home: &TempDir,
|
||||
managed_config: ManagedConfigFixture,
|
||||
) -> Config {
|
||||
let loader_overrides = managed_config
|
||||
.loader_overrides_for_tests(codex_home.path())
|
||||
.expect("managed config fixture should be writable");
|
||||
let mut config = ConfigBuilder::default()
|
||||
.loader_overrides(loader_overrides)
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.harness_overrides(default_test_overrides())
|
||||
.build()
|
||||
.await
|
||||
.expect("defaults for test should always succeed");
|
||||
// aKode has no built-in OpenAI provider: give tests a mock Responses provider (stored-key
|
||||
// auth, unreachable endpoint unless a test overrides it) and the bundled model catalog.
|
||||
if !config.model_provider_configured() {
|
||||
let provider =
|
||||
crate::test_codex::test_model_provider_info(Some("http://127.0.0.1:9/v1".to_string()));
|
||||
config.model_provider_id = crate::test_codex::TEST_MODEL_PROVIDER_ID.to_string();
|
||||
config.model_providers.insert(
|
||||
crate::test_codex::TEST_MODEL_PROVIDER_ID.to_string(),
|
||||
provider.clone(),
|
||||
);
|
||||
config.model_provider = provider;
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
pub fn managed_network_requirements() -> ManagedConfigFixture {
|
||||
ManagedConfigFixture::requirements(
|
||||
r#"
|
||||
[experimental_network]
|
||||
enabled = true
|
||||
allow_local_binding = true
|
||||
"#,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn default_test_overrides() -> ConfigOverrides {
|
||||
ConfigOverrides {
|
||||
codex_linux_sandbox_exe: Some(
|
||||
find_codex_linux_sandbox_exe().expect("should find binary for akode-linux-sandbox"),
|
||||
),
|
||||
..ConfigOverrides::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn default_test_overrides() -> ConfigOverrides {
|
||||
ConfigOverrides::default()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn find_codex_linux_sandbox_exe() -> Result<PathBuf, CargoBinError> {
|
||||
if let Some(path) = TEST_ARG0_PATH_ENTRY
|
||||
.get()
|
||||
.and_then(Option::as_ref)
|
||||
.and_then(|path_entry| path_entry.paths().codex_linux_sandbox_exe.clone())
|
||||
{
|
||||
return Ok(path);
|
||||
}
|
||||
|
||||
if let Ok(path) = std::env::current_exe() {
|
||||
return Ok(path);
|
||||
}
|
||||
|
||||
akode_utils_cargo_bin::cargo_bin("akode-linux-sandbox")
|
||||
}
|
||||
|
||||
pub async fn wait_for_event<F>(
|
||||
codex: &CodexThread,
|
||||
predicate: F,
|
||||
) -> akode_protocol::protocol::EventMsg
|
||||
where
|
||||
F: FnMut(&akode_protocol::protocol::EventMsg) -> bool,
|
||||
{
|
||||
use tokio::time::Duration;
|
||||
wait_for_event_with_timeout(codex, predicate, Duration::from_secs(1)).await
|
||||
}
|
||||
|
||||
pub async fn wait_for_successful_turn(codex: &CodexThread) {
|
||||
use akode_protocol::protocol::EventMsg;
|
||||
|
||||
let event = wait_for_event(codex, |event| matches!(event, EventMsg::TurnComplete(_))).await;
|
||||
assert!(
|
||||
matches!(&event, EventMsg::TurnComplete(completed) if completed.error.is_none()),
|
||||
"turn failed: {event:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Waits for a configured MCP server to finish startup and requires it to be ready.
|
||||
pub async fn wait_for_mcp_server(codex: &CodexThread, server_name: &str) -> anyhow::Result<()> {
|
||||
use akode_protocol::protocol::EventMsg;
|
||||
|
||||
// Wait for the startup summary regardless of outcome, then interpret the
|
||||
// requested server's ready, failed, or cancelled entry below.
|
||||
let summary = loop {
|
||||
let event = codex
|
||||
.next_event()
|
||||
.await
|
||||
.expect("stream ended unexpectedly while waiting for MCP startup");
|
||||
if let EventMsg::McpStartupComplete(summary) = event.msg {
|
||||
break summary;
|
||||
}
|
||||
};
|
||||
if let Some(failure) = summary
|
||||
.failed
|
||||
.iter()
|
||||
.find(|failure| failure.server == server_name)
|
||||
{
|
||||
let error = &failure.error;
|
||||
anyhow::bail!("MCP server {server_name} failed to start: {error}");
|
||||
}
|
||||
if summary.cancelled.iter().any(|server| server == server_name) {
|
||||
anyhow::bail!("MCP server {server_name} startup was cancelled");
|
||||
}
|
||||
assert!(
|
||||
summary.ready.iter().any(|server| server == server_name),
|
||||
"expected MCP server {server_name} to be ready; startup summary: {summary:?}"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn submit_thread_settings(
|
||||
codex: &CodexThread,
|
||||
thread_settings: akode_protocol::protocol::ThreadSettingsOverrides,
|
||||
) -> anyhow::Result<()> {
|
||||
use akode_protocol::protocol::EventMsg;
|
||||
use akode_protocol::protocol::Op;
|
||||
use tokio::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
|
||||
let submission_id = codex
|
||||
.submit(Op::ThreadSettings {
|
||||
thread_settings,
|
||||
reply: None,
|
||||
})
|
||||
.await?;
|
||||
loop {
|
||||
let ev = timeout(Duration::from_secs(10), codex.next_event())
|
||||
.await
|
||||
.expect("timeout waiting for thread settings update")
|
||||
.expect("stream ended unexpectedly");
|
||||
if ev.id == submission_id {
|
||||
match ev.msg {
|
||||
EventMsg::ThreadSettingsApplied(_) => return Ok(()),
|
||||
EventMsg::Error(err) => panic!("thread settings update failed: {}", err.message),
|
||||
other => panic!("unexpected thread settings update event: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// For sequential tests, register this contributor and wait once after every completed turn.
|
||||
/// Notifications are thread-scoped so a child or sibling cannot satisfy the wait.
|
||||
pub struct ThreadIdle;
|
||||
|
||||
#[derive(Default)]
|
||||
struct ThreadIdleNotification(tokio::sync::Notify);
|
||||
|
||||
impl akode_extension_api::ThreadLifecycleContributor<Config> for ThreadIdle {
|
||||
fn on_thread_idle<'a>(
|
||||
&'a self,
|
||||
input: akode_extension_api::ThreadIdleInput<'a>,
|
||||
) -> akode_extension_api::ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
input
|
||||
.thread_store
|
||||
.get_or_init(ThreadIdleNotification::default)
|
||||
.0
|
||||
.notify_one();
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadIdle {
|
||||
pub async fn wait(thread: &CodexThread) {
|
||||
// TurnComplete is sent before active-turn cleanup. Rollback requires the later idle signal.
|
||||
let idle = thread
|
||||
.thread_extension_data()
|
||||
.get_or_init(ThreadIdleNotification::default);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), idle.0.notified())
|
||||
.await
|
||||
.expect("thread should become idle after turn completion");
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn wait_for_event_match<T, F>(codex: &CodexThread, matcher: F) -> T
|
||||
where
|
||||
F: Fn(&akode_protocol::protocol::EventMsg) -> Option<T>,
|
||||
{
|
||||
let ev = wait_for_event(codex, |ev| matcher(ev).is_some()).await;
|
||||
matcher(&ev).expect("EventMsg should match matcher predicate")
|
||||
}
|
||||
|
||||
pub async fn wait_for_event_with_timeout<F>(
|
||||
codex: &CodexThread,
|
||||
mut predicate: F,
|
||||
wait_time: tokio::time::Duration,
|
||||
) -> akode_protocol::protocol::EventMsg
|
||||
where
|
||||
F: FnMut(&akode_protocol::protocol::EventMsg) -> bool,
|
||||
{
|
||||
use tokio::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
loop {
|
||||
// Allow a bit more time to accommodate async startup work (e.g. config IO, tool discovery)
|
||||
let ev = timeout(wait_time.max(Duration::from_secs(10)), codex.next_event())
|
||||
.await
|
||||
.expect("timeout waiting for event")
|
||||
.expect("stream ended unexpectedly");
|
||||
if predicate(&ev.msg) {
|
||||
return ev.msg;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn sandbox_env_var() -> &'static str {
|
||||
akode_core::spawn::AKODE_SANDBOX_ENV_VAR
|
||||
}
|
||||
|
||||
pub fn sandbox_network_env_var() -> &'static str {
|
||||
akode_core::spawn::AKODE_SANDBOX_NETWORK_DISABLED_ENV_VAR
|
||||
}
|
||||
|
||||
pub fn format_with_current_shell(command: &str) -> Vec<String> {
|
||||
akode_core::shell::default_user_shell().derive_exec_args(command, /*use_login_shell*/ true)
|
||||
}
|
||||
|
||||
pub fn format_with_current_shell_display(command: &str) -> String {
|
||||
let args = format_with_current_shell(command);
|
||||
shlex::try_join(args.iter().map(String::as_str)).expect("serialize current shell command")
|
||||
}
|
||||
|
||||
pub fn format_with_current_shell_non_login(command: &str) -> Vec<String> {
|
||||
akode_core::shell::default_user_shell()
|
||||
.derive_exec_args(command, /*use_login_shell*/ false)
|
||||
}
|
||||
|
||||
pub fn format_with_current_shell_display_non_login(command: &str) -> String {
|
||||
let args = format_with_current_shell_non_login(command);
|
||||
shlex::try_join(args.iter().map(String::as_str))
|
||||
.expect("serialize current shell command without login")
|
||||
}
|
||||
|
||||
pub fn stdio_server_bin() -> Result<String, CargoBinError> {
|
||||
akode_utils_cargo_bin::cargo_bin("test_stdio_server").map(|p| p.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
pub mod fs_wait {
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use notify::RecursiveMode;
|
||||
use notify::Watcher;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc;
|
||||
use std::sync::mpsc::RecvTimeoutError;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
use tokio::task;
|
||||
use walkdir::WalkDir;
|
||||
|
||||
pub async fn wait_for_path_exists(
|
||||
path: impl Into<PathBuf>,
|
||||
timeout: Duration,
|
||||
) -> Result<PathBuf> {
|
||||
let path = path.into();
|
||||
task::spawn_blocking(move || wait_for_path_exists_blocking(path, timeout)).await?
|
||||
}
|
||||
|
||||
pub async fn wait_for_matching_file(
|
||||
root: impl Into<PathBuf>,
|
||||
timeout: Duration,
|
||||
predicate: impl FnMut(&Path) -> bool + Send + 'static,
|
||||
) -> Result<PathBuf> {
|
||||
let root = root.into();
|
||||
task::spawn_blocking(move || {
|
||||
let mut predicate = predicate;
|
||||
blocking_find_matching_file(root, timeout, &mut predicate)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
fn wait_for_path_exists_blocking(path: PathBuf, timeout: Duration) -> Result<PathBuf> {
|
||||
if path.exists() {
|
||||
return Ok(path);
|
||||
}
|
||||
|
||||
let watch_root = nearest_existing_ancestor(&path);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let mut watcher = notify::recommended_watcher(move |res| {
|
||||
let _ = tx.send(res);
|
||||
})?;
|
||||
watcher.watch(&watch_root, RecursiveMode::Recursive)?;
|
||||
|
||||
let deadline = Instant::now() + timeout;
|
||||
loop {
|
||||
if path.exists() {
|
||||
return Ok(path);
|
||||
}
|
||||
let now = Instant::now();
|
||||
if now >= deadline {
|
||||
break;
|
||||
}
|
||||
let remaining = deadline.saturating_duration_since(now);
|
||||
match rx.recv_timeout(remaining) {
|
||||
Ok(Ok(_event)) => {
|
||||
if path.exists() {
|
||||
return Ok(path);
|
||||
}
|
||||
}
|
||||
Ok(Err(err)) => return Err(err.into()),
|
||||
Err(RecvTimeoutError::Timeout) => break,
|
||||
Err(RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
}
|
||||
|
||||
if path.exists() {
|
||||
Ok(path)
|
||||
} else {
|
||||
Err(anyhow!("timed out waiting for {path:?}"))
|
||||
}
|
||||
}
|
||||
|
||||
fn blocking_find_matching_file(
|
||||
root: PathBuf,
|
||||
timeout: Duration,
|
||||
predicate: &mut impl FnMut(&Path) -> bool,
|
||||
) -> Result<PathBuf> {
|
||||
let root = wait_for_path_exists_blocking(root, timeout)?;
|
||||
|
||||
if let Some(found) = scan_for_match(&root, predicate) {
|
||||
return Ok(found);
|
||||
}
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let mut watcher = notify::recommended_watcher(move |res| {
|
||||
let _ = tx.send(res);
|
||||
})?;
|
||||
watcher.watch(&root, RecursiveMode::Recursive)?;
|
||||
|
||||
let deadline = Instant::now() + timeout;
|
||||
|
||||
while Instant::now() < deadline {
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
match rx.recv_timeout(remaining) {
|
||||
Ok(Ok(_event)) => {
|
||||
if let Some(found) = scan_for_match(&root, predicate) {
|
||||
return Ok(found);
|
||||
}
|
||||
}
|
||||
Ok(Err(err)) => return Err(err.into()),
|
||||
Err(RecvTimeoutError::Timeout) => break,
|
||||
Err(RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(found) = scan_for_match(&root, predicate) {
|
||||
Ok(found)
|
||||
} else {
|
||||
Err(anyhow!("timed out waiting for matching file in {root:?}"))
|
||||
}
|
||||
}
|
||||
|
||||
fn scan_for_match(root: &Path, predicate: &mut impl FnMut(&Path) -> bool) -> Option<PathBuf> {
|
||||
for entry in WalkDir::new(root).into_iter().filter_map(Result::ok) {
|
||||
let path = entry.path();
|
||||
if !entry.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
if predicate(path) {
|
||||
return Some(path.to_path_buf());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn nearest_existing_ancestor(path: &Path) -> PathBuf {
|
||||
let mut current = path;
|
||||
loop {
|
||||
if current.exists() {
|
||||
return current.to_path_buf();
|
||||
}
|
||||
match current.parent() {
|
||||
Some(parent) => current = parent,
|
||||
None => return PathBuf::from("."),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! skip_if_sandbox {
|
||||
() => {{
|
||||
if ::std::env::var($crate::sandbox_env_var())
|
||||
== ::core::result::Result::Ok("seatbelt".to_string())
|
||||
{
|
||||
eprintln!(
|
||||
"{} is set to 'seatbelt', skipping test.",
|
||||
$crate::sandbox_env_var()
|
||||
);
|
||||
return;
|
||||
}
|
||||
}};
|
||||
($return_value:expr $(,)?) => {{
|
||||
if ::std::env::var($crate::sandbox_env_var())
|
||||
== ::core::result::Result::Ok("seatbelt".to_string())
|
||||
{
|
||||
eprintln!(
|
||||
"{} is set to 'seatbelt', skipping test.",
|
||||
$crate::sandbox_env_var()
|
||||
);
|
||||
return $return_value;
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! skip_if_no_network {
|
||||
() => {{
|
||||
if ::std::env::var($crate::sandbox_network_env_var()).is_ok() {
|
||||
println!(
|
||||
"Skipping test because it cannot execute when network is disabled in a Codex sandbox."
|
||||
);
|
||||
return;
|
||||
}
|
||||
}};
|
||||
($return_value:expr $(,)?) => {{
|
||||
if ::std::env::var($crate::sandbox_network_env_var()).is_ok() {
|
||||
println!(
|
||||
"Skipping test because it cannot execute when network is disabled in a Codex sandbox."
|
||||
);
|
||||
return $return_value;
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
// Exported so the public skip macros can expand in downstream test crates.
|
||||
#[macro_export]
|
||||
#[doc(hidden)]
|
||||
macro_rules! skip_if_test_condition {
|
||||
($condition:expr, $environment:expr, $reason:expr $(,)?) => {{
|
||||
if $condition {
|
||||
eprintln!("Skipping test in {}: {}", $environment, $reason);
|
||||
return;
|
||||
}
|
||||
}};
|
||||
($return_value:expr, $condition:expr, $environment:expr, $reason:expr $(,)?) => {{
|
||||
if $condition {
|
||||
eprintln!("Skipping test in {}: {}", $environment, $reason);
|
||||
return $return_value;
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! skip_if_remote {
|
||||
($reason:expr $(,)?) => {{
|
||||
$crate::skip_if_test_condition!(
|
||||
$crate::is_remote_test_environment(),
|
||||
"a remote test environment",
|
||||
$reason,
|
||||
);
|
||||
}};
|
||||
($return_value:expr, $reason:expr $(,)?) => {{
|
||||
$crate::skip_if_test_condition!(
|
||||
$return_value,
|
||||
$crate::is_remote_test_environment(),
|
||||
"a remote test environment",
|
||||
$reason,
|
||||
);
|
||||
}};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! skip_if_no_remote_env {
|
||||
() => {{
|
||||
if !$crate::is_remote_test_environment() {
|
||||
eprintln!("Skipping test because it requires a remote test environment.");
|
||||
return;
|
||||
}
|
||||
}};
|
||||
($return_value:expr $(,)?) => {{
|
||||
if !$crate::is_remote_test_environment() {
|
||||
eprintln!("Skipping test because it requires a remote test environment.");
|
||||
return $return_value;
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! skip_if_wine_exec {
|
||||
($reason:expr $(,)?) => {{
|
||||
$crate::skip_if_test_condition!(
|
||||
$crate::is_wine_exec_test_environment(),
|
||||
"the Wine-exec test environment",
|
||||
$reason,
|
||||
);
|
||||
}};
|
||||
($return_value:expr, $reason:expr $(,)?) => {{
|
||||
$crate::skip_if_test_condition!(
|
||||
$return_value,
|
||||
$crate::is_wine_exec_test_environment(),
|
||||
"the Wine-exec test environment",
|
||||
$reason,
|
||||
);
|
||||
}};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! skip_if_target_windows {
|
||||
($reason:expr $(,)?) => {{
|
||||
$crate::skip_if_test_condition!(
|
||||
$crate::test_target_os() == $crate::TestTargetOs::Windows,
|
||||
"a Windows target environment",
|
||||
$reason,
|
||||
);
|
||||
}};
|
||||
($return_value:expr, $reason:expr $(,)?) => {{
|
||||
$crate::skip_if_test_condition!(
|
||||
$return_value,
|
||||
$crate::test_target_os() == $crate::TestTargetOs::Windows,
|
||||
"a Windows target environment",
|
||||
$reason,
|
||||
);
|
||||
}};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! codex_linux_sandbox_exe_or_skip {
|
||||
() => {{
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
match $crate::find_codex_linux_sandbox_exe() {
|
||||
Ok(path) => Some(path),
|
||||
Err(err) => {
|
||||
eprintln!("akode-linux-sandbox binary not available, skipping test: {err}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
None
|
||||
}
|
||||
}};
|
||||
($return_value:expr $(,)?) => {{
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
match $crate::find_codex_linux_sandbox_exe() {
|
||||
Ok(path) => Some(path),
|
||||
Err(err) => {
|
||||
eprintln!("akode-linux-sandbox binary not available, skipping test: {err}");
|
||||
return $return_value;
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
None
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! skip_if_host_windows {
|
||||
($return_value:expr $(,)?) => {{
|
||||
if cfg!(target_os = "windows") {
|
||||
println!("Skipping test because it cannot execute on Windows.");
|
||||
return $return_value;
|
||||
}
|
||||
}};
|
||||
}
|
||||
662
akode-rs/core/tests/common/mcp_test_server.rs
Normal file
662
akode-rs/core/tests/common/mcp_test_server.rs
Normal file
@@ -0,0 +1,662 @@
|
||||
//! Mock streamable HTTP MCP server for tests that exercise generic MCP behaviour through a
|
||||
//! user-configured `[mcp_servers.calendar]` registration.
|
||||
|
||||
use crate::test_codex::TestCodexBuilder;
|
||||
use crate::test_codex::test_codex;
|
||||
use anyhow::Result;
|
||||
use akode_config::types::AppToolApproval;
|
||||
use akode_core::config::Config;
|
||||
use akode_login::CodexAuth;
|
||||
use akode_models_manager::bundled_models_response;
|
||||
use akode_protocol::config_types::ApprovalsReviewer;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::mpsc;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::Request;
|
||||
use wiremock::Respond;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path_regex;
|
||||
|
||||
/// Name of the user-configured MCP server registration backed by this mock.
|
||||
pub const MCP_TEST_SERVER_NAME: &str = "calendar";
|
||||
/// URL path of the mock MCP endpoint.
|
||||
pub const MCP_TEST_SERVER_PATH: &str = "/mcp";
|
||||
const MCP_PATH_REGEX: &str = "^/mcp/?$";
|
||||
const PROTOCOL_VERSION: &str = "2025-11-25";
|
||||
const SERVER_NAME: &str = "calendar-mcp-test";
|
||||
const SERVER_VERSION: &str = "1.0.0";
|
||||
const SEARCHABLE_TOOL_COUNT: usize = 100;
|
||||
pub const CALENDAR_CREATE_EVENT_TOOL_NAME: &str = "calendar_create_event";
|
||||
pub const CALENDAR_APP_ONLY_TOOL_NAME: &str = "calendar_app_only_action";
|
||||
pub const CALENDAR_EXTRACT_TEXT_TOOL_NAME: &str = "calendar_extract_text";
|
||||
pub const CALENDAR_LIST_EVENTS_TOOL_NAME: &str = "calendar_list_events";
|
||||
/// Model-visible namespace of the mock server's tools.
|
||||
pub const CALENDAR_NAMESPACE: &str = "mcp__calendar";
|
||||
/// Flattened model-visible names (namespace + raw tool name).
|
||||
pub const DIRECT_CALENDAR_CREATE_EVENT_TOOL: &str = "mcp__calendar__calendar_create_event";
|
||||
pub const DIRECT_CALENDAR_APP_ONLY_TOOL: &str = "mcp__calendar__calendar_app_only_action";
|
||||
pub const DIRECT_CALENDAR_LIST_EVENTS_TOOL: &str = "mcp__calendar__calendar_list_events";
|
||||
pub const DIRECT_CALENDAR_EXTRACT_TEXT_TOOL: &str = "mcp__calendar__calendar_extract_text";
|
||||
pub const CALENDAR_CREATE_EVENT_MCP_APP_RESOURCE_URI: &str =
|
||||
"ui://widget/calendar-create-event.html";
|
||||
|
||||
type McpStartupInitializeGate = Arc<Mutex<VecDeque<mpsc::Receiver<()>>>>;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct McpTestServer {
|
||||
/// Base URL of the mock server; the MCP endpoint lives at [`MCP_TEST_SERVER_PATH`].
|
||||
pub base_url: String,
|
||||
}
|
||||
|
||||
impl McpTestServer {
|
||||
/// Full URL of the mock MCP endpoint.
|
||||
pub fn mcp_url(&self) -> String {
|
||||
mcp_test_server_url(&self.base_url)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mcp_test_server_url(base_url: &str) -> String {
|
||||
format!("{}{MCP_TEST_SERVER_PATH}", base_url.trim_end_matches('/'))
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct McpTestServerStartupControl {
|
||||
initialize_attempts: Arc<AtomicUsize>,
|
||||
remaining_initialize_failures: Arc<AtomicUsize>,
|
||||
successful_initialize_gate: McpStartupInitializeGate,
|
||||
}
|
||||
|
||||
impl McpTestServerStartupControl {
|
||||
pub fn fail_next_initialize_attempts(&self, attempts: usize) {
|
||||
self.remaining_initialize_failures
|
||||
.store(attempts, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
pub fn initialize_attempts(&self) -> usize {
|
||||
self.initialize_attempts.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Holds one successful startup without turning recovery into a fresh runtime refresh.
|
||||
/// Multiple holds are consumed in order, so tests can gate startup and recovery in advance.
|
||||
pub fn hold_next_successful_initialize(&self) -> mpsc::Sender<()> {
|
||||
let (release, gate) = mpsc::channel();
|
||||
self.successful_initialize_gate
|
||||
.lock()
|
||||
.expect("MCP initialization gate lock should not be poisoned")
|
||||
.push_back(gate);
|
||||
release
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum McpTestToolLoading {
|
||||
Direct,
|
||||
Searchable,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
enum McpTestToolsListBehavior {
|
||||
AlwaysAvailable,
|
||||
AvailableWhen(Arc<AtomicBool>),
|
||||
AlwaysUnavailable,
|
||||
Custom(Arc<Mutex<Vec<Value>>>),
|
||||
}
|
||||
|
||||
impl McpTestServer {
|
||||
pub async fn mount(server: &MockServer) -> Result<Self> {
|
||||
Self::mount_with(
|
||||
server,
|
||||
/*searchable*/ false,
|
||||
/*include_app_only_tool*/ false,
|
||||
McpTestToolsListBehavior::AlwaysAvailable,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Mounts the server with enough extra tools to push tool loading into search mode.
|
||||
pub async fn mount_searchable(server: &MockServer) -> Result<Self> {
|
||||
Self::mount_with(
|
||||
server,
|
||||
/*searchable*/ true,
|
||||
/*include_app_only_tool*/ false,
|
||||
McpTestToolsListBehavior::AlwaysAvailable,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn mount_with_app_only_tool(
|
||||
server: &MockServer,
|
||||
tool_loading: McpTestToolLoading,
|
||||
) -> Result<Self> {
|
||||
Self::mount_with(
|
||||
server,
|
||||
matches!(tool_loading, McpTestToolLoading::Searchable),
|
||||
/*include_app_only_tool*/ true,
|
||||
McpTestToolsListBehavior::AlwaysAvailable,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn mount_with_startup_control(
|
||||
server: &MockServer,
|
||||
) -> Result<(Self, McpTestServerStartupControl)> {
|
||||
let control = McpTestServerStartupControl {
|
||||
initialize_attempts: Arc::new(AtomicUsize::new(0)),
|
||||
remaining_initialize_failures: Arc::new(AtomicUsize::new(0)),
|
||||
successful_initialize_gate: Arc::new(Mutex::new(VecDeque::new())),
|
||||
};
|
||||
mount_streamable_http_json_rpc(
|
||||
server,
|
||||
McpJsonRpcResponder {
|
||||
searchable: true,
|
||||
include_app_only_tool: false,
|
||||
tools_list_behavior: McpTestToolsListBehavior::AlwaysAvailable,
|
||||
initialize_attempts: Some(Arc::clone(&control.initialize_attempts)),
|
||||
remaining_initialize_failures: Some(Arc::clone(
|
||||
&control.remaining_initialize_failures,
|
||||
)),
|
||||
successful_initialize_gate: Some(Arc::clone(&control.successful_initialize_gate)),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
Ok((
|
||||
Self {
|
||||
base_url: server.uri(),
|
||||
},
|
||||
control,
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn mount_with_tools_available_when(
|
||||
server: &MockServer,
|
||||
tools_available: Arc<AtomicBool>,
|
||||
) -> Result<Self> {
|
||||
Self::mount_with(
|
||||
server,
|
||||
/*searchable*/ false,
|
||||
/*include_app_only_tool*/ false,
|
||||
McpTestToolsListBehavior::AvailableWhen(tools_available),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn mount_with_tools(
|
||||
server: &MockServer,
|
||||
tools: Arc<Mutex<Vec<Value>>>,
|
||||
) -> Result<Self> {
|
||||
Self::mount_with(
|
||||
server,
|
||||
/*searchable*/ false,
|
||||
/*include_app_only_tool*/ false,
|
||||
McpTestToolsListBehavior::Custom(tools),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn mount_without_tools(server: &MockServer) -> Result<Self> {
|
||||
Self::mount_with(
|
||||
server,
|
||||
/*searchable*/ false,
|
||||
/*include_app_only_tool*/ false,
|
||||
McpTestToolsListBehavior::AlwaysUnavailable,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn mount_with(
|
||||
server: &MockServer,
|
||||
searchable: bool,
|
||||
include_app_only_tool: bool,
|
||||
tools_list_behavior: McpTestToolsListBehavior,
|
||||
) -> Result<Self> {
|
||||
mount_streamable_http_json_rpc(
|
||||
server,
|
||||
McpJsonRpcResponder {
|
||||
searchable,
|
||||
include_app_only_tool,
|
||||
tools_list_behavior,
|
||||
initialize_attempts: None,
|
||||
remaining_initialize_failures: None,
|
||||
successful_initialize_gate: None,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
Ok(Self {
|
||||
base_url: server.uri(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn configure_search_capable_model(config: &mut Config) {
|
||||
let mut model_catalog = bundled_models_response().expect("bundled models.json should parse");
|
||||
let model = model_catalog
|
||||
.models
|
||||
.iter_mut()
|
||||
.find(|model| model.slug == "gpt-5.5")
|
||||
.expect("gpt-5.5 exists in bundled models.json");
|
||||
config.model = Some("gpt-5.5".to_string());
|
||||
model.supports_search_tool = true;
|
||||
config.model_catalog = Some(model_catalog);
|
||||
}
|
||||
|
||||
/// The `[mcp_servers.calendar]` registration pointing at the mock server.
|
||||
pub fn mcp_test_server_config(base_url: &str) -> akode_config::McpServerConfig {
|
||||
#[expect(clippy::expect_used, reason = "static test config is valid")]
|
||||
serde_json::from_value(json!({
|
||||
"url": mcp_test_server_url(base_url),
|
||||
"startup_timeout_sec": 30,
|
||||
}))
|
||||
.expect("valid mock MCP server config")
|
||||
}
|
||||
|
||||
/// Adds the mock server as the user-configured `calendar` MCP server.
|
||||
pub fn configure_mcp_test_server(config: &mut Config, base_url: &str) {
|
||||
let mut servers = config.mcp_servers.get().clone();
|
||||
servers.insert(
|
||||
MCP_TEST_SERVER_NAME.to_string(),
|
||||
mcp_test_server_config(base_url),
|
||||
);
|
||||
config
|
||||
.mcp_servers
|
||||
.set(servers)
|
||||
.expect("test config should accept MCP servers");
|
||||
}
|
||||
|
||||
/// Updates the `calendar` registration in place.
|
||||
pub fn update_mcp_test_server_config(
|
||||
config: &mut Config,
|
||||
update: impl FnOnce(&mut akode_config::McpServerConfig),
|
||||
) {
|
||||
let mut servers = config.mcp_servers.get().clone();
|
||||
let server = servers
|
||||
.get_mut(MCP_TEST_SERVER_NAME)
|
||||
.expect("calendar MCP server should be configured");
|
||||
update(server);
|
||||
config
|
||||
.mcp_servers
|
||||
.set(servers)
|
||||
.expect("test config should accept MCP servers");
|
||||
}
|
||||
|
||||
pub fn configure_search_capable_mcp_test_server(config: &mut Config, base_url: &str) {
|
||||
configure_mcp_test_server(config, base_url);
|
||||
configure_search_capable_model(config);
|
||||
}
|
||||
|
||||
pub fn mcp_server_builder(base_url: impl Into<String>) -> TestCodexBuilder {
|
||||
let base_url = base_url.into();
|
||||
test_codex()
|
||||
.with_auth(CodexAuth::from_api_key("Test API Key"))
|
||||
.with_config(move |config| configure_mcp_test_server(config, base_url.as_str()))
|
||||
}
|
||||
|
||||
/// Sets the default tool approval mode of the `calendar` server and the session reviewer.
|
||||
pub fn set_mcp_test_server_approval_mode_and_reviewer(
|
||||
config: &mut Config,
|
||||
approval_mode: AppToolApproval,
|
||||
reviewer: ApprovalsReviewer,
|
||||
) {
|
||||
update_mcp_test_server_config(config, |server| {
|
||||
server.default_tools_approval_mode = Some(approval_mode);
|
||||
});
|
||||
config.approvals_reviewer = reviewer;
|
||||
}
|
||||
|
||||
pub fn search_capable_mcp_server_builder(base_url: impl Into<String>) -> TestCodexBuilder {
|
||||
let base_url = base_url.into();
|
||||
test_codex()
|
||||
.with_auth(CodexAuth::from_api_key("Test API Key"))
|
||||
.with_config(move |config| {
|
||||
configure_search_capable_mcp_test_server(config, base_url.as_str())
|
||||
})
|
||||
}
|
||||
|
||||
fn mcp_tool_call_id(body: &Value) -> Option<&str> {
|
||||
body.pointer("/params/_meta/callId")?.as_str()
|
||||
}
|
||||
|
||||
pub async fn recorded_mcp_tool_calls(server: &MockServer) -> Vec<Value> {
|
||||
server
|
||||
.received_requests()
|
||||
.await
|
||||
.expect("mock server should capture requests")
|
||||
.into_iter()
|
||||
.filter_map(|request| {
|
||||
let body: Value = serde_json::from_slice(&request.body).ok()?;
|
||||
(request.url.path() == MCP_TEST_SERVER_PATH
|
||||
&& body.get("method").and_then(Value::as_str) == Some("tools/call"))
|
||||
.then_some(body)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub async fn recorded_mcp_tool_call_by_call_id(server: &MockServer, call_id: &str) -> Value {
|
||||
let matches = recorded_mcp_tool_calls(server)
|
||||
.await
|
||||
.into_iter()
|
||||
.filter(|body| mcp_tool_call_id(body) == Some(call_id))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
matches.len(),
|
||||
1,
|
||||
"expected exactly one MCP tools/call request for call_id {call_id}"
|
||||
);
|
||||
matches
|
||||
.into_iter()
|
||||
.next()
|
||||
.expect("matching MCP tools/call request should be recorded")
|
||||
}
|
||||
|
||||
pub async fn recorded_mcp_tool_call_by_name(server: &MockServer, tool_name: &str) -> Value {
|
||||
let matches = recorded_mcp_tool_calls(server)
|
||||
.await
|
||||
.into_iter()
|
||||
.filter(|body| body.pointer("/params/name").and_then(Value::as_str) == Some(tool_name))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
matches.len(),
|
||||
1,
|
||||
"expected exactly one MCP tools/call request for tool {tool_name}"
|
||||
);
|
||||
matches
|
||||
.into_iter()
|
||||
.next()
|
||||
.expect("matching MCP tools/call request should be recorded")
|
||||
}
|
||||
|
||||
async fn mount_streamable_http_json_rpc(server: &MockServer, responder: McpJsonRpcResponder) {
|
||||
Mock::given(method("POST"))
|
||||
.and(path_regex(MCP_PATH_REGEX))
|
||||
.respond_with(responder)
|
||||
.mount(server)
|
||||
.await;
|
||||
}
|
||||
|
||||
struct McpJsonRpcResponder {
|
||||
searchable: bool,
|
||||
include_app_only_tool: bool,
|
||||
tools_list_behavior: McpTestToolsListBehavior,
|
||||
initialize_attempts: Option<Arc<AtomicUsize>>,
|
||||
remaining_initialize_failures: Option<Arc<AtomicUsize>>,
|
||||
successful_initialize_gate: Option<McpStartupInitializeGate>,
|
||||
}
|
||||
|
||||
impl Respond for McpJsonRpcResponder {
|
||||
fn respond(&self, request: &Request) -> ResponseTemplate {
|
||||
let body: Value = match serde_json::from_slice(&request.body) {
|
||||
Ok(body) => body,
|
||||
Err(error) => {
|
||||
return ResponseTemplate::new(400).set_body_json(json!({
|
||||
"error": format!("invalid JSON-RPC body: {error}"),
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
let Some(method) = body.get("method").and_then(Value::as_str) else {
|
||||
return ResponseTemplate::new(400).set_body_json(json!({
|
||||
"error": "missing method in JSON-RPC request",
|
||||
}));
|
||||
};
|
||||
|
||||
match method {
|
||||
"initialize" => {
|
||||
if let Some(initialize_attempts) = &self.initialize_attempts {
|
||||
initialize_attempts.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
if self
|
||||
.remaining_initialize_failures
|
||||
.as_ref()
|
||||
.is_some_and(|remaining| {
|
||||
remaining
|
||||
.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |remaining| {
|
||||
remaining.checked_sub(1)
|
||||
})
|
||||
.is_ok()
|
||||
})
|
||||
{
|
||||
return ResponseTemplate::new(400).set_body_json(json!({
|
||||
"error": "simulated non-retryable MCP startup failure",
|
||||
}));
|
||||
}
|
||||
let gate = self.successful_initialize_gate.as_ref().and_then(|gate| {
|
||||
gate.lock()
|
||||
.expect("MCP initialization gate lock should not be poisoned")
|
||||
.pop_front()
|
||||
});
|
||||
// This responder's dedicated mock server stays paused while the test controls
|
||||
// when this existing client's background retry may finish.
|
||||
if let Some(gate) = gate
|
||||
&& gate.recv().is_err()
|
||||
{
|
||||
return ResponseTemplate::new(500).set_body_json(json!({
|
||||
"error": "MCP initialization gate was dropped before release",
|
||||
}));
|
||||
}
|
||||
let id = body.get("id").cloned().unwrap_or(Value::Null);
|
||||
let protocol_version = body
|
||||
.pointer("/params/protocolVersion")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or(PROTOCOL_VERSION);
|
||||
ResponseTemplate::new(200).set_body_json(json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"result": {
|
||||
"protocolVersion": protocol_version,
|
||||
"capabilities": {
|
||||
"tools": {
|
||||
"listChanged": true
|
||||
}
|
||||
},
|
||||
"serverInfo": {
|
||||
"name": SERVER_NAME,
|
||||
"version": SERVER_VERSION
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
"notifications/initialized" => ResponseTemplate::new(202),
|
||||
"tools/list" => {
|
||||
let tools_available = match &self.tools_list_behavior {
|
||||
McpTestToolsListBehavior::AlwaysAvailable
|
||||
| McpTestToolsListBehavior::Custom(_) => true,
|
||||
McpTestToolsListBehavior::AvailableWhen(tools_available) => {
|
||||
tools_available.load(Ordering::SeqCst)
|
||||
}
|
||||
McpTestToolsListBehavior::AlwaysUnavailable => false,
|
||||
};
|
||||
let id = body.get("id").cloned().unwrap_or(Value::Null);
|
||||
let mut response = json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"result": {
|
||||
"tools": [
|
||||
{
|
||||
"name": CALENDAR_CREATE_EVENT_TOOL_NAME,
|
||||
"description": "Create a calendar event.",
|
||||
"annotations": {
|
||||
"readOnlyHint": false,
|
||||
"destructiveHint": false,
|
||||
"openWorldHint": false
|
||||
},
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"title": { "type": "string" },
|
||||
"starts_at": { "type": "string" },
|
||||
"timezone": { "type": "string" }
|
||||
},
|
||||
"required": ["title", "starts_at"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"_meta": {
|
||||
"openai/outputTemplate": CALENDAR_CREATE_EVENT_MCP_APP_RESOURCE_URI
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": CALENDAR_LIST_EVENTS_TOOL_NAME,
|
||||
"description": "List calendar events.",
|
||||
"annotations": {
|
||||
"readOnlyHint": true
|
||||
},
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": { "type": "string" },
|
||||
"limit": { "type": "integer" }
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"_meta": {
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": CALENDAR_EXTRACT_TEXT_TOOL_NAME,
|
||||
"description": "Extract text from an uploaded document.",
|
||||
"annotations": {
|
||||
"readOnlyHint": false
|
||||
},
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"file": {
|
||||
"type": "object",
|
||||
"description": "Document file payload.",
|
||||
"properties": {
|
||||
"download_url": { "type": "string" },
|
||||
"file_id": { "type": "string" }
|
||||
},
|
||||
"required": ["download_url", "file_id"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": ["file"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"_meta": {
|
||||
"openai/fileParams": ["file"]
|
||||
}
|
||||
}
|
||||
],
|
||||
"nextCursor": null
|
||||
}
|
||||
});
|
||||
if let McpTestToolsListBehavior::Custom(tools) = &self.tools_list_behavior {
|
||||
response["result"]["tools"] = json!(
|
||||
tools
|
||||
.lock()
|
||||
.expect("MCP test tools lock should not be poisoned")
|
||||
.clone()
|
||||
);
|
||||
}
|
||||
if !tools_available
|
||||
&& let Some(tools) = response
|
||||
.pointer_mut("/result/tools")
|
||||
.and_then(Value::as_array_mut)
|
||||
{
|
||||
tools.clear();
|
||||
}
|
||||
if tools_available
|
||||
&& self.searchable
|
||||
&& let Some(tools) = response
|
||||
.pointer_mut("/result/tools")
|
||||
.and_then(Value::as_array_mut)
|
||||
{
|
||||
for index in 3..SEARCHABLE_TOOL_COUNT {
|
||||
tools.push(json!({
|
||||
"name": format!("calendar_timezone_option_{index}"),
|
||||
"description": format!("Read timezone option {index}."),
|
||||
"annotations": {
|
||||
"readOnlyHint": true
|
||||
},
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"timezone": { "type": "string" }
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"_meta": {}
|
||||
}));
|
||||
}
|
||||
}
|
||||
if tools_available
|
||||
&& self.include_app_only_tool
|
||||
&& let Some(tools) = response
|
||||
.pointer_mut("/result/tools")
|
||||
.and_then(Value::as_array_mut)
|
||||
{
|
||||
tools.push(json!({
|
||||
"name": CALENDAR_APP_ONLY_TOOL_NAME,
|
||||
"description": "Open a calendar app-only action.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"_meta": {
|
||||
"ui": {
|
||||
"visibility": ["app"]
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
ResponseTemplate::new(200).set_body_json(response)
|
||||
}
|
||||
"tools/call" => {
|
||||
let id = body.get("id").cloned().unwrap_or(Value::Null);
|
||||
let tool_name = body
|
||||
.pointer("/params/name")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
let title = body
|
||||
.pointer("/params/arguments/title")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
let starts_at = body
|
||||
.pointer("/params/arguments/starts_at")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
let file_id = body
|
||||
.pointer("/params/arguments/file/file_id")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
|
||||
ResponseTemplate::new(200).set_body_json(json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"result": {
|
||||
"content": [{
|
||||
"type": "text",
|
||||
"text": format!("called {tool_name} for {title} at {starts_at} with {file_id}")
|
||||
}],
|
||||
"structuredContent": {
|
||||
"called": tool_name,
|
||||
},
|
||||
"isError": false
|
||||
}
|
||||
}))
|
||||
}
|
||||
method if method.starts_with("notifications/") => ResponseTemplate::new(202),
|
||||
_ => {
|
||||
let id = body.get("id").cloned().unwrap_or(Value::Null);
|
||||
ResponseTemplate::new(200).set_body_json(json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"error": {
|
||||
"code": -32601,
|
||||
"message": format!("method not found: {method}")
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
183
akode-rs/core/tests/common/network_policy_mcp.rs
Normal file
183
akode-rs/core/tests/common/network_policy_mcp.rs
Normal file
@@ -0,0 +1,183 @@
|
||||
//! Mocks one trusted MCP HTTP endpoint while forwarding real executor RPCs unchanged.
|
||||
|
||||
use crate::exec_server::ExecServerProcess;
|
||||
use crate::is_remote_test_environment;
|
||||
use anyhow::Context;
|
||||
use akode_config::types::McpServerConfig;
|
||||
use akode_exec_server::HttpHeader;
|
||||
use akode_exec_server::HttpRequestParams;
|
||||
use akode_exec_server::HttpRequestResponse;
|
||||
use akode_exec_server::REMOTE_ENVIRONMENT_ID;
|
||||
use futures::SinkExt;
|
||||
use futures::StreamExt;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::task::JoinSet;
|
||||
use tokio_tungstenite::accept_async;
|
||||
use tokio_tungstenite::connect_async;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use tokio_tungstenite::tungstenite::http::Uri;
|
||||
|
||||
pub const TRUSTED_MCP_URL: &str = "https://chatgpt.com/backend-api/ps/mcp";
|
||||
|
||||
pub struct NetworkPolicyMcp {
|
||||
pub executor_url: String,
|
||||
task: JoinHandle<anyhow::Result<()>>,
|
||||
_executor: Option<ExecServerProcess>,
|
||||
}
|
||||
|
||||
impl NetworkPolicyMcp {
|
||||
pub fn server_config() -> McpServerConfig {
|
||||
serde_json::from_value(json!({
|
||||
"url": TRUSTED_MCP_URL,
|
||||
"environment_id": REMOTE_ENVIRONMENT_ID,
|
||||
}))
|
||||
.expect("trusted network policy MCP configuration")
|
||||
}
|
||||
|
||||
pub async fn start_with_capabilities(experimental: Value) -> anyhow::Result<Self> {
|
||||
let experimental = Arc::new(experimental);
|
||||
let executor = if is_remote_test_environment() {
|
||||
None
|
||||
} else {
|
||||
Some(ExecServerProcess::start().await?)
|
||||
};
|
||||
let upstream_url = match &executor {
|
||||
Some(executor) => executor.websocket_url.clone(),
|
||||
None => std::env::var("AKODE_TEST_REMOTE_EXEC_SERVER_URL")?,
|
||||
};
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let executor_url = format!("ws://{}", listener.local_addr()?);
|
||||
let task = tokio::spawn(async move {
|
||||
let mut sessions = JoinSet::new();
|
||||
loop {
|
||||
tokio::select! {
|
||||
accepted = listener.accept() => {
|
||||
let (stream, _) = accepted?;
|
||||
let upstream_url = upstream_url.clone();
|
||||
let experimental = Arc::clone(&experimental);
|
||||
sessions.spawn(async move {
|
||||
let mut downstream = accept_async(stream).await?;
|
||||
let (mut upstream, _) = connect_async(upstream_url).await?;
|
||||
let mut responses = JoinSet::new();
|
||||
loop {
|
||||
tokio::select! {
|
||||
frame = downstream.next() => {
|
||||
let Some(frame) = frame else { break; };
|
||||
let frame = frame?;
|
||||
if frame.is_close() { break; }
|
||||
let request = match &frame {
|
||||
Message::Text(text) => serde_json::from_str::<Value>(text).ok(),
|
||||
Message::Binary(bytes) => serde_json::from_slice(bytes).ok(),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(request) = request
|
||||
&& request["method"] == "http/request"
|
||||
{
|
||||
let url: Uri = request["params"]["url"].as_str().context("HTTP request URL")?.parse()?;
|
||||
anyhow::ensure!(
|
||||
url.host().is_none_or(|host| !host.eq_ignore_ascii_case("chatgpt.com"))
|
||||
|| request["params"]["url"] == TRUSTED_MCP_URL,
|
||||
"unsupported request to ChatGPT fixture origin: {url}"
|
||||
);
|
||||
if request["params"]["url"] == TRUSTED_MCP_URL {
|
||||
responses.spawn(respond(request, Arc::clone(&experimental)));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
upstream.send(frame).await?;
|
||||
}
|
||||
frame = upstream.next() => {
|
||||
let Some(frame) = frame else { break; };
|
||||
let frame = frame?;
|
||||
if frame.is_close() { break; }
|
||||
downstream.send(frame).await?;
|
||||
}
|
||||
Some(response) = responses.join_next(), if !responses.is_empty() => {
|
||||
for message in response?? {
|
||||
downstream.send(Message::Text(message.to_string().into())).await?;
|
||||
}
|
||||
}
|
||||
else => break,
|
||||
}
|
||||
}
|
||||
anyhow::Ok(())
|
||||
});
|
||||
}
|
||||
Some(session) = sessions.join_next(), if !sessions.is_empty() => session??,
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(Self {
|
||||
executor_url,
|
||||
task,
|
||||
_executor: executor,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for NetworkPolicyMcp {
|
||||
fn drop(&mut self) {
|
||||
self.task.abort();
|
||||
}
|
||||
}
|
||||
|
||||
async fn respond(request: Value, experimental: Arc<Value>) -> anyhow::Result<Vec<Value>> {
|
||||
let params: HttpRequestParams = serde_json::from_value(request["params"].clone())?;
|
||||
anyhow::ensure!(params.url == TRUSTED_MCP_URL, "unexpected MCP endpoint");
|
||||
let mut response = HttpRequestResponse {
|
||||
status: 405,
|
||||
headers: Vec::new(),
|
||||
body: Vec::new().into(),
|
||||
};
|
||||
if params.method == "POST" {
|
||||
let body: Value =
|
||||
serde_json::from_slice(params.body.as_ref().context("MCP body")?.as_ref())?;
|
||||
let result = match body["method"].as_str() {
|
||||
Some("initialize") => json!({
|
||||
"protocolVersion": body["params"]["protocolVersion"],
|
||||
"capabilities": {"tools": {}, "experimental": *experimental},
|
||||
"serverInfo": {"name": "network-policy", "version": "1"}
|
||||
}),
|
||||
Some("tools/list") => json!({"tools": [{
|
||||
"name": "network_policy_meta", "inputSchema": {"type": "object"},
|
||||
"annotations": {"readOnlyHint": true}
|
||||
}]}),
|
||||
Some("tools/call") => {
|
||||
anyhow::ensure!(
|
||||
body["params"]["name"] == "network_policy_meta",
|
||||
"unknown MCP tool"
|
||||
);
|
||||
let metadata = body["params"]["_meta"].clone();
|
||||
json!({"content": [{"type": "text", "text": metadata.to_string()}],
|
||||
"structuredContent": metadata, "isError": false})
|
||||
}
|
||||
Some("notifications/initialized") => Value::Null,
|
||||
method => anyhow::bail!("unexpected MCP method {method:?}"),
|
||||
};
|
||||
response.status = if body.get("id").is_some() { 200 } else { 202 };
|
||||
response.headers = vec![HttpHeader {
|
||||
name: "content-type".to_string(),
|
||||
value: "application/json".to_string(),
|
||||
value_env_var: None,
|
||||
}];
|
||||
if response.status == 200 {
|
||||
response.body =
|
||||
serde_json::to_vec(&json!({"jsonrpc": "2.0", "id": body["id"], "result": result}))?
|
||||
.into();
|
||||
}
|
||||
}
|
||||
let body = params
|
||||
.stream_response
|
||||
.then(|| std::mem::replace(&mut response.body, Vec::new().into()));
|
||||
let mut messages = vec![json!({"id": request["id"], "result": response})];
|
||||
if let Some(body) = body {
|
||||
messages.push(json!({"method": "http/request/bodyDelta", "params": {
|
||||
"requestId": params.request_id, "seq": 1, "deltaBase64": body, "done": true
|
||||
}}));
|
||||
}
|
||||
Ok(messages)
|
||||
}
|
||||
36
akode-rs/core/tests/common/oauth.rs
Normal file
36
akode-rs/core/tests/common/oauth.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
//! Mock OAuth endpoints for device sign-in tests.
|
||||
|
||||
use serde_json::json;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockGuard;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::body_string_contains;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
/// Issues a challenge and answers one token poll. The guard lets a test wait for that poll.
|
||||
pub async fn mount_device_code_grant(
|
||||
server: &MockServer,
|
||||
token_response: ResponseTemplate,
|
||||
) -> MockGuard {
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/devicecode"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"device_code": "secret-device-code", "user_code": "ABCD-EFGH",
|
||||
"verification_uri": "https://login.example/device", "expires_in": 60, "interval": 1,
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(server)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/token"))
|
||||
.and(body_string_contains(
|
||||
"grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code",
|
||||
))
|
||||
.and(body_string_contains("device_code=secret-device-code"))
|
||||
.respond_with(token_response)
|
||||
.expect(1)
|
||||
.mount_as_scoped(server)
|
||||
.await
|
||||
}
|
||||
49
akode-rs/core/tests/common/process.rs
Normal file
49
akode-rs/core/tests/common/process.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
use anyhow::Context;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
pub async fn wait_for_pid_file(path: &Path) -> anyhow::Result<String> {
|
||||
let pid = tokio::time::timeout(Duration::from_secs(2), async {
|
||||
loop {
|
||||
if let Ok(contents) = fs::read_to_string(path) {
|
||||
let trimmed = contents.trim();
|
||||
if !trimmed.is_empty() {
|
||||
return trimmed.to_string();
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.context("timed out waiting for pid file")?;
|
||||
|
||||
Ok(pid)
|
||||
}
|
||||
|
||||
pub fn process_is_alive(pid: &str) -> anyhow::Result<bool> {
|
||||
let status = std::process::Command::new("kill")
|
||||
.args(["-0", pid])
|
||||
.status()
|
||||
.context("failed to probe process liveness with kill -0")?;
|
||||
Ok(status.success())
|
||||
}
|
||||
|
||||
async fn wait_for_process_exit_inner(pid: String) -> anyhow::Result<()> {
|
||||
loop {
|
||||
if !process_is_alive(&pid)? {
|
||||
return Ok(());
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn wait_for_process_exit(pid: &str) -> anyhow::Result<()> {
|
||||
let pid = pid.to_string();
|
||||
// A stdio process group can keep its leader's PID for the two-second shutdown grace.
|
||||
tokio::time::timeout(Duration::from_secs(5), wait_for_process_exit_inner(pid))
|
||||
.await
|
||||
.context("timed out waiting for process to exit")??;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
1757
akode-rs/core/tests/common/responses.rs
Normal file
1757
akode-rs/core/tests/common/responses.rs
Normal file
File diff suppressed because it is too large
Load Diff
22
akode-rs/core/tests/common/startup.rs
Normal file
22
akode-rs/core/tests/common/startup.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
//! Bounded startup assertions that preserve fixture failures during teardown.
|
||||
|
||||
use anyhow::Result;
|
||||
use std::future::Future;
|
||||
use std::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
|
||||
/// Allow local configuration and state-database setup on loaded CI workers.
|
||||
pub const STARTUP_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 30);
|
||||
|
||||
/// Fail before the caller's mock server drops and verifies downstream requests.
|
||||
/// Returning an error instead would let an unmet mock expectation mask its cause.
|
||||
pub async fn expect_startup<T>(startup: impl Future<Output = Result<T>>) -> T {
|
||||
timeout(STARTUP_TIMEOUT, startup)
|
||||
.await
|
||||
.expect("test fixture startup timed out")
|
||||
.expect("test fixture startup failed")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "startup_tests.rs"]
|
||||
mod tests;
|
||||
43
akode-rs/core/tests/common/startup_tests.rs
Normal file
43
akode-rs/core/tests/common/startup_tests.rs
Normal file
@@ -0,0 +1,43 @@
|
||||
//! Keeps startup failures visible even when downstream mocks have unmet expectations.
|
||||
|
||||
use super::expect_startup;
|
||||
use crate::responses::ev_completed;
|
||||
use crate::responses::mount_sse_sequence;
|
||||
use crate::responses::sse;
|
||||
use crate::responses::start_mock_server;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::future::pending;
|
||||
use std::future::ready;
|
||||
use std::time::Duration;
|
||||
use tokio::time::sleep;
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn startup_can_complete_after_five_seconds() {
|
||||
let value = expect_startup(async {
|
||||
sleep(Duration::from_secs(/*secs*/ 6)).await;
|
||||
Ok("ready")
|
||||
})
|
||||
.await;
|
||||
assert_eq!(value, "ready");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
#[should_panic(expected = "test fixture startup timed out")]
|
||||
async fn startup_timeout_is_not_masked_by_mock_expectations() {
|
||||
let server = start_mock_server().await;
|
||||
mount_sse_sequence(&server, vec![sse(vec![ev_completed("unused")])]).await;
|
||||
|
||||
expect_startup(pending::<Result<()>>()).await;
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
#[should_panic(expected = "injected startup failure")]
|
||||
async fn startup_error_is_not_masked_by_mock_expectations() {
|
||||
let server = start_mock_server().await;
|
||||
mount_sse_sequence(&server, vec![sse(vec![ev_completed("unused")])]).await;
|
||||
let startup: Result<()> = Err(anyhow!("injected startup failure"));
|
||||
|
||||
expect_startup(ready(startup)).await;
|
||||
}
|
||||
731
akode-rs/core/tests/common/streaming_sse.rs
Normal file
731
akode-rs/core/tests/common/streaming_sse.rs
Normal file
@@ -0,0 +1,731 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
use std::time::SystemTime;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::Mutex as TokioMutex;
|
||||
use tokio::sync::Notify;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
/// Streaming SSE chunk payload gated by a per-chunk signal.
|
||||
#[derive(Debug)]
|
||||
pub struct StreamingSseChunk {
|
||||
pub gate: Option<oneshot::Receiver<()>>,
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
/// Minimal streaming SSE server for tests that need gated per-chunk delivery.
|
||||
pub struct StreamingSseServer {
|
||||
uri: String,
|
||||
requests: Arc<TokioMutex<Vec<Vec<u8>>>>,
|
||||
request_notify: Arc<Notify>,
|
||||
shutdown: oneshot::Sender<()>,
|
||||
task: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl StreamingSseServer {
|
||||
pub fn uri(&self) -> &str {
|
||||
&self.uri
|
||||
}
|
||||
|
||||
pub async fn requests(&self) -> Vec<Vec<u8>> {
|
||||
self.requests.lock().await.clone()
|
||||
}
|
||||
|
||||
/// Waits for `count` requests; panics after a generous bound instead of hanging the suite.
|
||||
pub async fn wait_for_request_count(&self, count: usize) {
|
||||
let wait = async {
|
||||
loop {
|
||||
if self.requests.lock().await.len() >= count {
|
||||
return;
|
||||
}
|
||||
self.request_notify.notified().await;
|
||||
}
|
||||
};
|
||||
if tokio::time::timeout(std::time::Duration::from_secs(60), wait)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
let received = self.requests.lock().await.len();
|
||||
panic!("timed out waiting for {count} streaming requests; received {received}");
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn shutdown(self) {
|
||||
let _ = self.shutdown.send(());
|
||||
let _ = self.task.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts a lightweight HTTP server that supports:
|
||||
/// - GET /v1/models -> empty models response
|
||||
/// - GET responses routes -> 426 to select the HTTP fallback
|
||||
/// - POST responses and Guardian routes -> SSE stream gated per-chunk, served in order
|
||||
///
|
||||
/// Returns the server handle and a list of receivers that fire when each
|
||||
/// response stream finishes sending its final chunk.
|
||||
pub async fn start_streaming_sse_server(
|
||||
responses: Vec<Vec<StreamingSseChunk>>,
|
||||
) -> (StreamingSseServer, Vec<oneshot::Receiver<i64>>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("bind streaming SSE server");
|
||||
let addr = listener.local_addr().expect("streaming SSE server address");
|
||||
let uri = format!("http://{addr}");
|
||||
|
||||
let mut completion_senders = Vec::with_capacity(responses.len());
|
||||
let mut completion_receivers = Vec::with_capacity(responses.len());
|
||||
for _ in 0..responses.len() {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
completion_senders.push(tx);
|
||||
completion_receivers.push(rx);
|
||||
}
|
||||
|
||||
let state = Arc::new(TokioMutex::new(StreamingSseState {
|
||||
responses: VecDeque::from(responses),
|
||||
completions: VecDeque::from(completion_senders),
|
||||
}));
|
||||
let requests = Arc::new(TokioMutex::new(Vec::new()));
|
||||
let request_notify = Arc::new(Notify::new());
|
||||
let requests_for_task = Arc::clone(&requests);
|
||||
let request_notify_for_task = Arc::clone(&request_notify);
|
||||
let (shutdown_tx, mut shutdown_rx) = oneshot::channel();
|
||||
|
||||
let task = tokio::spawn(async move {
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = &mut shutdown_rx => break,
|
||||
accept_res = listener.accept() => {
|
||||
let (mut stream, _) = accept_res.expect("accept streaming SSE connection");
|
||||
let state = Arc::clone(&state);
|
||||
let requests = Arc::clone(&requests_for_task);
|
||||
let request_notify = Arc::clone(&request_notify_for_task);
|
||||
tokio::spawn(async move {
|
||||
let (request, body_prefix) = read_http_request(&mut stream).await;
|
||||
let Some((method, path)) = parse_request_line(&request) else {
|
||||
let _ = write_http_response(&mut stream, /*status*/ 400, "bad request", "text/plain").await;
|
||||
return;
|
||||
};
|
||||
|
||||
if method == "GET" && path == "/v1/models" {
|
||||
if read_request_body(&mut stream, &request, body_prefix)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
let _ = write_http_response(&mut stream, /*status*/ 400, "bad request", "text/plain").await;
|
||||
return;
|
||||
}
|
||||
let body = serde_json::json!({
|
||||
"data": [],
|
||||
"object": "list"
|
||||
})
|
||||
.to_string();
|
||||
let _ = write_http_response(&mut stream, /*status*/ 200, &body, "application/json").await;
|
||||
return;
|
||||
}
|
||||
|
||||
let responses_route = matches!(path, "/v1/responses" | "/backend-api/codex/responses");
|
||||
if method == "GET" && responses_route {
|
||||
let _ = write_http_response(&mut stream, /*status*/ 426, "websockets unsupported", "text/plain").await;
|
||||
return;
|
||||
}
|
||||
|
||||
if method == "POST" && (responses_route || path == "/backend-api/codex/guardian") {
|
||||
let body = match read_request_body(&mut stream, &request, body_prefix)
|
||||
.await
|
||||
{
|
||||
Ok(body) => body,
|
||||
Err(_) => {
|
||||
let _ = write_http_response(&mut stream, /*status*/ 400, "bad request", "text/plain").await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
requests.lock().await.push(body);
|
||||
request_notify.notify_one();
|
||||
let Some((chunks, completion)) = take_next_stream(&state).await else {
|
||||
let _ = write_http_response(&mut stream, /*status*/ 500, "no responses queued", "text/plain").await;
|
||||
return;
|
||||
};
|
||||
|
||||
if write_sse_headers(&mut stream).await.is_err() {
|
||||
return;
|
||||
}
|
||||
|
||||
for chunk in chunks {
|
||||
if let Some(gate) = chunk.gate
|
||||
&& gate.await.is_err() {
|
||||
return;
|
||||
}
|
||||
if stream.write_all(chunk.body.as_bytes()).await.is_err() {
|
||||
return;
|
||||
}
|
||||
let _ = stream.flush().await;
|
||||
}
|
||||
|
||||
let _ = completion.send(unix_ms_now());
|
||||
let _ = stream.shutdown().await;
|
||||
return;
|
||||
}
|
||||
|
||||
let _ = write_http_response(&mut stream, /*status*/ 404, "not found", "text/plain").await;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
(
|
||||
StreamingSseServer {
|
||||
uri,
|
||||
requests,
|
||||
request_notify,
|
||||
shutdown: shutdown_tx,
|
||||
task,
|
||||
},
|
||||
completion_receivers,
|
||||
)
|
||||
}
|
||||
|
||||
struct StreamingSseState {
|
||||
responses: VecDeque<Vec<StreamingSseChunk>>,
|
||||
completions: VecDeque<oneshot::Sender<i64>>,
|
||||
}
|
||||
|
||||
async fn take_next_stream(
|
||||
state: &TokioMutex<StreamingSseState>,
|
||||
) -> Option<(Vec<StreamingSseChunk>, oneshot::Sender<i64>)> {
|
||||
let mut guard = state.lock().await;
|
||||
let chunks = guard.responses.pop_front()?;
|
||||
let completion = guard.completions.pop_front()?;
|
||||
Some((chunks, completion))
|
||||
}
|
||||
|
||||
async fn read_http_request(stream: &mut tokio::net::TcpStream) -> (String, Vec<u8>) {
|
||||
let mut buf = Vec::new();
|
||||
let mut scratch = [0u8; 1024];
|
||||
loop {
|
||||
let read = stream.read(&mut scratch).await.unwrap_or(0);
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
buf.extend_from_slice(&scratch[..read]);
|
||||
if let Some(end) = header_terminator_index(&buf) {
|
||||
let header_end = end + 4;
|
||||
let header = String::from_utf8_lossy(&buf[..header_end]).into_owned();
|
||||
let rest = buf[header_end..].to_vec();
|
||||
return (header, rest);
|
||||
}
|
||||
}
|
||||
(String::from_utf8_lossy(&buf).into_owned(), Vec::new())
|
||||
}
|
||||
|
||||
fn parse_request_line(request: &str) -> Option<(&str, &str)> {
|
||||
let line = request.lines().next()?;
|
||||
let mut parts = line.split_whitespace();
|
||||
let method = parts.next()?;
|
||||
let path = parts.next()?;
|
||||
Some((method, path))
|
||||
}
|
||||
|
||||
fn header_terminator_index(buf: &[u8]) -> Option<usize> {
|
||||
buf.windows(4).position(|w| w == b"\r\n\r\n")
|
||||
}
|
||||
|
||||
fn content_length(headers: &str) -> Option<usize> {
|
||||
headers.lines().skip(1).find_map(|line| {
|
||||
let mut parts = line.splitn(2, ':');
|
||||
let name = parts.next()?.trim();
|
||||
let value = parts.next()?.trim();
|
||||
if name.eq_ignore_ascii_case("content-length") {
|
||||
value.parse::<usize>().ok()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn read_request_body(
|
||||
stream: &mut tokio::net::TcpStream,
|
||||
headers: &str,
|
||||
mut body_prefix: Vec<u8>,
|
||||
) -> std::io::Result<Vec<u8>> {
|
||||
let Some(content_len) = content_length(headers) else {
|
||||
return Ok(body_prefix);
|
||||
};
|
||||
|
||||
if body_prefix.len() > content_len {
|
||||
body_prefix.truncate(content_len);
|
||||
}
|
||||
|
||||
let remaining = content_len.saturating_sub(body_prefix.len());
|
||||
if remaining == 0 {
|
||||
return Ok(body_prefix);
|
||||
}
|
||||
|
||||
let mut rest = vec![0u8; remaining];
|
||||
stream.read_exact(&mut rest).await?;
|
||||
body_prefix.extend_from_slice(&rest);
|
||||
Ok(body_prefix)
|
||||
}
|
||||
|
||||
async fn write_sse_headers(stream: &mut tokio::net::TcpStream) -> std::io::Result<()> {
|
||||
let headers = "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ncache-control: no-cache\r\nconnection: close\r\n\r\n";
|
||||
stream.write_all(headers.as_bytes()).await
|
||||
}
|
||||
|
||||
async fn write_http_response(
|
||||
stream: &mut tokio::net::TcpStream,
|
||||
status: i64,
|
||||
body: &str,
|
||||
content_type: &str,
|
||||
) -> std::io::Result<()> {
|
||||
let body_len = body.len();
|
||||
let headers = format!(
|
||||
"HTTP/1.1 {status} OK\r\ncontent-type: {content_type}\r\ncontent-length: {body_len}\r\nconnection: close\r\n\r\n"
|
||||
);
|
||||
stream.write_all(headers.as_bytes()).await?;
|
||||
stream.write_all(body.as_bytes()).await?;
|
||||
stream.shutdown().await
|
||||
}
|
||||
|
||||
fn unix_ms_now() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis() as i64
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use akode_http_client::ClientRouteClass;
|
||||
use akode_http_client::HttpClientFactory;
|
||||
use akode_http_client::OutboundProxyPolicy;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
|
||||
fn split_response(response: &str) -> (&str, &str) {
|
||||
response
|
||||
.split_once("\r\n\r\n")
|
||||
.expect("response missing header separator")
|
||||
}
|
||||
|
||||
fn status_code(headers: &str) -> u16 {
|
||||
let line = headers.lines().next().expect("status line");
|
||||
let mut parts = line.split_whitespace();
|
||||
let _ = parts.next();
|
||||
let status = parts.next().expect("status code");
|
||||
status.parse().expect("parse status code")
|
||||
}
|
||||
|
||||
fn header_value<'a>(headers: &'a str, name: &str) -> Option<&'a str> {
|
||||
headers.lines().skip(1).find_map(|line| {
|
||||
let mut parts = line.splitn(2, ':');
|
||||
let key = parts.next()?.trim();
|
||||
let value = parts.next()?.trim();
|
||||
if key.eq_ignore_ascii_case(name) {
|
||||
Some(value)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn connect(uri: &str) -> TcpStream {
|
||||
let addr = uri.strip_prefix("http://").expect("uri should be http");
|
||||
TcpStream::connect(addr)
|
||||
.await
|
||||
.expect("connect to streaming SSE server")
|
||||
}
|
||||
|
||||
async fn read_to_end(stream: &mut TcpStream) -> String {
|
||||
let mut buf = Vec::new();
|
||||
stream.read_to_end(&mut buf).await.expect("read response");
|
||||
String::from_utf8_lossy(&buf).into_owned()
|
||||
}
|
||||
|
||||
async fn read_until(stream: &mut TcpStream, needle: &str) -> (String, String) {
|
||||
let mut buf = Vec::new();
|
||||
let mut scratch = [0u8; 256];
|
||||
let needle_bytes = needle.as_bytes();
|
||||
loop {
|
||||
let read = stream.read(&mut scratch).await.expect("read response");
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
buf.extend_from_slice(&scratch[..read]);
|
||||
if let Some(pos) = buf
|
||||
.windows(needle_bytes.len())
|
||||
.position(|window| window == needle_bytes)
|
||||
{
|
||||
let end = pos + needle_bytes.len();
|
||||
let headers = String::from_utf8_lossy(&buf[..end]).into_owned();
|
||||
let remainder = String::from_utf8_lossy(&buf[end..]).into_owned();
|
||||
return (headers, remainder);
|
||||
}
|
||||
}
|
||||
(String::from_utf8_lossy(&buf).into_owned(), String::new())
|
||||
}
|
||||
|
||||
async fn send_request(stream: &mut TcpStream, request: &str) {
|
||||
stream
|
||||
.write_all(request.as_bytes())
|
||||
.await
|
||||
.expect("write request");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_models_returns_empty_list() {
|
||||
let (server, _) = start_streaming_sse_server(Vec::new()).await;
|
||||
let mut stream = connect(server.uri()).await;
|
||||
send_request(
|
||||
&mut stream,
|
||||
"GET /v1/models HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n",
|
||||
)
|
||||
.await;
|
||||
let response = read_to_end(&mut stream).await;
|
||||
let (headers, body) = split_response(&response);
|
||||
assert_eq!(status_code(headers), 200);
|
||||
assert_eq!(
|
||||
header_value(headers, "content-type"),
|
||||
Some("application/json")
|
||||
);
|
||||
let parsed: serde_json::Value = serde_json::from_str(body).expect("parse json body");
|
||||
assert_eq!(
|
||||
parsed,
|
||||
serde_json::json!({
|
||||
"data": [],
|
||||
"object": "list"
|
||||
})
|
||||
);
|
||||
server.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn post_responses_streams_in_order_and_closes() {
|
||||
let chunks = vec![
|
||||
StreamingSseChunk {
|
||||
gate: None,
|
||||
body: "event: one\n\n".to_string(),
|
||||
},
|
||||
StreamingSseChunk {
|
||||
gate: None,
|
||||
body: "event: two\n\n".to_string(),
|
||||
},
|
||||
];
|
||||
let (server, mut completions) = start_streaming_sse_server(vec![chunks]).await;
|
||||
let mut stream = connect(server.uri()).await;
|
||||
send_request(
|
||||
&mut stream,
|
||||
"POST /v1/responses HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 0\r\n\r\n",
|
||||
)
|
||||
.await;
|
||||
let response = read_to_end(&mut stream).await;
|
||||
let (headers, body) = split_response(&response);
|
||||
assert_eq!(status_code(headers), 200);
|
||||
assert_eq!(
|
||||
header_value(headers, "content-type"),
|
||||
Some("text/event-stream")
|
||||
);
|
||||
assert_eq!(body, "event: one\n\nevent: two\n\n");
|
||||
let mut extra = [0u8; 1];
|
||||
let read = stream.read(&mut extra).await.expect("read after eof");
|
||||
assert_eq!(read, 0);
|
||||
let completion = completions.pop().expect("completion receiver");
|
||||
let timestamp = completion.await.expect("completion timestamp");
|
||||
assert!(timestamp > 0);
|
||||
server.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn none_gate_streams_immediately() {
|
||||
let chunks = vec![StreamingSseChunk {
|
||||
gate: None,
|
||||
body: "event: immediate\n\n".to_string(),
|
||||
}];
|
||||
let (server, _) = start_streaming_sse_server(vec![chunks]).await;
|
||||
let mut stream = connect(server.uri()).await;
|
||||
send_request(
|
||||
&mut stream,
|
||||
"POST /v1/responses HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 0\r\n\r\n",
|
||||
)
|
||||
.await;
|
||||
let (headers, remainder) = read_until(&mut stream, "\r\n\r\n").await;
|
||||
let (headers, _) = split_response(&headers);
|
||||
assert_eq!(status_code(headers), 200);
|
||||
let immediate = format!("{remainder}{}", read_to_end(&mut stream).await);
|
||||
assert_eq!(immediate, "event: immediate\n\n");
|
||||
server.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn post_responses_with_no_queue_returns_500() {
|
||||
let (server, _) = start_streaming_sse_server(Vec::new()).await;
|
||||
let mut stream = connect(server.uri()).await;
|
||||
send_request(
|
||||
&mut stream,
|
||||
"POST /v1/responses HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 0\r\n\r\n",
|
||||
)
|
||||
.await;
|
||||
let response = read_to_end(&mut stream).await;
|
||||
let (headers, body) = split_response(&response);
|
||||
assert_eq!(status_code(headers), 500);
|
||||
assert_eq!(header_value(headers, "content-type"), Some("text/plain"));
|
||||
assert_eq!(body, "no responses queued");
|
||||
server.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gated_chunks_wait_for_signal_and_preserve_order() {
|
||||
let (gate_one_tx, gate_one_rx) = oneshot::channel();
|
||||
let (gate_two_tx, gate_two_rx) = oneshot::channel();
|
||||
let chunks = vec![
|
||||
StreamingSseChunk {
|
||||
gate: Some(gate_one_rx),
|
||||
body: "event: one\n\n".to_string(),
|
||||
},
|
||||
StreamingSseChunk {
|
||||
gate: Some(gate_two_rx),
|
||||
body: "event: two\n\n".to_string(),
|
||||
},
|
||||
];
|
||||
let (server, _) = start_streaming_sse_server(vec![chunks]).await;
|
||||
let mut stream = connect(server.uri()).await;
|
||||
send_request(
|
||||
&mut stream,
|
||||
"POST /v1/responses HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 0\r\n\r\n",
|
||||
)
|
||||
.await;
|
||||
let (headers, remainder) = read_until(&mut stream, "\r\n\r\n").await;
|
||||
let (headers, _) = split_response(&headers);
|
||||
assert_eq!(status_code(headers), 200);
|
||||
assert_eq!(
|
||||
header_value(headers, "content-type"),
|
||||
Some("text/event-stream")
|
||||
);
|
||||
assert!(
|
||||
remainder.is_empty(),
|
||||
"unexpected body before gate: {remainder:?}"
|
||||
);
|
||||
let mut scratch = [0u8; 32];
|
||||
let pending = timeout(Duration::from_millis(200), stream.read(&mut scratch)).await;
|
||||
assert!(pending.is_err());
|
||||
|
||||
let _ = gate_one_tx.send(());
|
||||
let mut first_chunk = vec![0u8; "event: one\n\n".len()];
|
||||
stream
|
||||
.read_exact(&mut first_chunk)
|
||||
.await
|
||||
.expect("read first chunk");
|
||||
assert_eq!(String::from_utf8_lossy(&first_chunk), "event: one\n\n");
|
||||
let pending = timeout(Duration::from_millis(200), stream.read(&mut scratch)).await;
|
||||
assert!(pending.is_err());
|
||||
|
||||
let _ = gate_two_tx.send(());
|
||||
let remaining = read_to_end(&mut stream).await;
|
||||
assert_eq!(remaining, "event: two\n\n");
|
||||
server.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn multiple_responses_are_fifo_and_completion_timestamps_monotonic() {
|
||||
let first_chunks = vec![StreamingSseChunk {
|
||||
gate: None,
|
||||
body: "event: first\n\n".to_string(),
|
||||
}];
|
||||
let second_chunks = vec![StreamingSseChunk {
|
||||
gate: None,
|
||||
body: "event: second\n\n".to_string(),
|
||||
}];
|
||||
let (server, mut completions) =
|
||||
start_streaming_sse_server(vec![first_chunks, second_chunks]).await;
|
||||
|
||||
let mut first_stream = connect(server.uri()).await;
|
||||
send_request(
|
||||
&mut first_stream,
|
||||
"POST /v1/responses HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 0\r\n\r\n",
|
||||
)
|
||||
.await;
|
||||
let first_response = read_to_end(&mut first_stream).await;
|
||||
let (_, first_body) = split_response(&first_response);
|
||||
assert_eq!(first_body, "event: first\n\n");
|
||||
|
||||
let mut second_stream = connect(server.uri()).await;
|
||||
send_request(
|
||||
&mut second_stream,
|
||||
"POST /v1/responses HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 0\r\n\r\n",
|
||||
)
|
||||
.await;
|
||||
let second_response = read_to_end(&mut second_stream).await;
|
||||
let (_, second_body) = split_response(&second_response);
|
||||
assert_eq!(second_body, "event: second\n\n");
|
||||
|
||||
let first_completion = completions.remove(0);
|
||||
let second_completion = completions.remove(0);
|
||||
let first_timestamp = first_completion.await.expect("first completion");
|
||||
let second_timestamp = second_completion.await.expect("second completion");
|
||||
assert!(first_timestamp > 0);
|
||||
assert!(second_timestamp > 0);
|
||||
assert!(first_timestamp <= second_timestamp);
|
||||
assert!(completions.is_empty());
|
||||
server.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unknown_route_returns_404() {
|
||||
let (server, _) = start_streaming_sse_server(Vec::new()).await;
|
||||
let mut stream = connect(server.uri()).await;
|
||||
send_request(
|
||||
&mut stream,
|
||||
"GET /v1/unknown HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n",
|
||||
)
|
||||
.await;
|
||||
let response = read_to_end(&mut stream).await;
|
||||
let (headers, body) = split_response(&response);
|
||||
assert_eq!(status_code(headers), 404);
|
||||
assert_eq!(header_value(headers, "content-type"), Some("text/plain"));
|
||||
assert_eq!(body, "not found");
|
||||
server.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn malformed_request_returns_400() {
|
||||
let (server, _) = start_streaming_sse_server(Vec::new()).await;
|
||||
let mut stream = connect(server.uri()).await;
|
||||
send_request(&mut stream, "BAD\r\n\r\n").await;
|
||||
let response = read_to_end(&mut stream).await;
|
||||
let (headers, body) = split_response(&response);
|
||||
assert_eq!(status_code(headers), 400);
|
||||
assert_eq!(header_value(headers, "content-type"), Some("text/plain"));
|
||||
assert_eq!(body, "bad request");
|
||||
server.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn responses_post_drains_request_body() {
|
||||
let response_body = r#"event: response.completed
|
||||
data: {"type":"response.completed","response":{"id":"resp-1"}}
|
||||
|
||||
"#;
|
||||
let (server, mut completions) = start_streaming_sse_server(vec![vec![StreamingSseChunk {
|
||||
gate: None,
|
||||
body: response_body.to_string(),
|
||||
}]])
|
||||
.await;
|
||||
|
||||
let url = format!("{}/v1/responses", server.uri());
|
||||
let payload = serde_json::json!({
|
||||
"model": "gpt-5.4",
|
||||
"instructions": "test",
|
||||
"input": [{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "hello"}]}],
|
||||
"stream": true
|
||||
});
|
||||
|
||||
let client = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
|
||||
.build_client(&url, ClientRouteClass::Other)
|
||||
.expect("build HTTP client");
|
||||
let resp = client
|
||||
.post(url)
|
||||
.json(&payload)
|
||||
.send()
|
||||
.await
|
||||
.expect("send request");
|
||||
assert_eq!(resp.status().as_u16(), 200);
|
||||
|
||||
let bytes = resp.bytes().await.expect("read response body");
|
||||
assert_eq!(bytes, response_body.as_bytes());
|
||||
|
||||
let completion = completions.remove(0);
|
||||
let completed_at = completion.await.expect("completion timestamp");
|
||||
assert!(completed_at > 0);
|
||||
|
||||
server.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_http_request_returns_after_header_terminator() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("bind test listener");
|
||||
let addr = listener.local_addr().expect("listener address");
|
||||
let (tx, rx) = oneshot::channel();
|
||||
let server_task = tokio::spawn(async move {
|
||||
let (mut stream, _) = listener.accept().await.expect("accept client");
|
||||
let (request, body) = read_http_request(&mut stream).await;
|
||||
let _ = tx.send((request, body));
|
||||
});
|
||||
|
||||
let mut client = TcpStream::connect(addr)
|
||||
.await
|
||||
.expect("connect to test listener");
|
||||
let request = "GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n";
|
||||
client
|
||||
.write_all(request.as_bytes())
|
||||
.await
|
||||
.expect("write request");
|
||||
let (received, body) = timeout(Duration::from_millis(200), rx)
|
||||
.await
|
||||
.expect("read_http_request timed out")
|
||||
.expect("receive request");
|
||||
assert_eq!(received, request);
|
||||
assert!(body.is_empty());
|
||||
drop(client);
|
||||
let _ = server_task.await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_request_line_handles_valid_and_invalid() {
|
||||
assert_eq!(parse_request_line(""), None);
|
||||
assert_eq!(parse_request_line("BAD"), None);
|
||||
assert_eq!(
|
||||
parse_request_line("GET /v1/models HTTP/1.1"),
|
||||
Some(("GET", "/v1/models"))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn take_next_stream_consumes_in_lockstep() {
|
||||
let (first_tx, first_rx) = oneshot::channel();
|
||||
let (second_tx, second_rx) = oneshot::channel();
|
||||
let state = TokioMutex::new(StreamingSseState {
|
||||
responses: VecDeque::from(vec![
|
||||
vec![StreamingSseChunk {
|
||||
gate: None,
|
||||
body: "first".to_string(),
|
||||
}],
|
||||
vec![StreamingSseChunk {
|
||||
gate: None,
|
||||
body: "second".to_string(),
|
||||
}],
|
||||
]),
|
||||
completions: VecDeque::from(vec![first_tx, second_tx]),
|
||||
});
|
||||
|
||||
let (first_chunks, first_completion) =
|
||||
take_next_stream(&state).await.expect("first stream");
|
||||
assert_eq!(first_chunks[0].body, "first");
|
||||
let _ = first_completion.send(11);
|
||||
assert_eq!(first_rx.await.expect("first completion"), 11);
|
||||
|
||||
let (second_chunks, second_completion) =
|
||||
take_next_stream(&state).await.expect("second stream");
|
||||
assert_eq!(second_chunks[0].body, "second");
|
||||
let _ = second_completion.send(22);
|
||||
assert_eq!(second_rx.await.expect("second completion"), 22);
|
||||
|
||||
let third = take_next_stream(&state).await;
|
||||
assert!(third.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shutdown_terminates_accept_loop() {
|
||||
let (server, _) = start_streaming_sse_server(Vec::new()).await;
|
||||
let shutdown = timeout(Duration::from_millis(200), server.shutdown()).await;
|
||||
assert!(shutdown.is_ok());
|
||||
}
|
||||
}
|
||||
1731
akode-rs/core/tests/common/test_codex.rs
Normal file
1731
akode-rs/core/tests/common/test_codex.rs
Normal file
File diff suppressed because it is too large
Load Diff
78
akode-rs/core/tests/common/test_codex_exec.rs
Normal file
78
akode-rs/core/tests/common/test_codex_exec.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
use akode_login::AKODE_API_KEY_ENV_VAR;
|
||||
use std::path::Path;
|
||||
use tempfile::TempDir;
|
||||
use wiremock::MockServer;
|
||||
|
||||
pub struct TestCodexExecBuilder {
|
||||
home: TempDir,
|
||||
cwd: TempDir,
|
||||
}
|
||||
|
||||
impl TestCodexExecBuilder {
|
||||
/// `akode-exec` with no model provider configured at all.
|
||||
pub fn cmd_without_provider(&self) -> assert_cmd::Command {
|
||||
let mut cmd = assert_cmd::Command::new(
|
||||
akode_utils_cargo_bin::cargo_bin("akode-exec")
|
||||
.expect("should find binary for akode-exec"),
|
||||
);
|
||||
cmd.current_dir(self.cwd.path())
|
||||
.env("AKODE_HOME", self.home.path())
|
||||
.env("AKODE_SQLITE_HOME", self.home.path())
|
||||
.env(AKODE_API_KEY_ENV_VAR, "dummy");
|
||||
cmd
|
||||
}
|
||||
|
||||
/// `akode-exec` with a mock provider at an unreachable endpoint and the bundled catalog.
|
||||
pub fn cmd(&self) -> assert_cmd::Command {
|
||||
self.cmd_with_base_url("http://127.0.0.1:9/v1")
|
||||
}
|
||||
|
||||
pub fn cmd_with_server(&self, server: &MockServer) -> assert_cmd::Command {
|
||||
self.cmd_with_base_url(&format!("{}/v1", server.uri()))
|
||||
}
|
||||
|
||||
fn cmd_with_base_url(&self, base: &str) -> assert_cmd::Command {
|
||||
let mut cmd = self.cmd_without_provider();
|
||||
// aKode has no built-in OpenAI provider: point a mock provider at the server, use
|
||||
// the env test key, and keep the bundled catalog the removed provider defaulted to.
|
||||
let catalog = self.home.path().join("test-models.json");
|
||||
if !catalog.exists() {
|
||||
std::fs::write(
|
||||
&catalog,
|
||||
include_str!("../../../models-manager/models.json"),
|
||||
)
|
||||
.expect("write test model catalog");
|
||||
}
|
||||
cmd.arg("-c")
|
||||
.arg("model_provider=\"mock\"")
|
||||
.arg("-c")
|
||||
.arg(format!(
|
||||
"model_providers.mock={{name=\"mock\",base_url={},requires_openai_auth=true,supports_websockets=false,merge_system_messages=false}}",
|
||||
toml_string_literal(base)
|
||||
))
|
||||
.arg("-c")
|
||||
.arg(format!(
|
||||
"model_catalog_json={}",
|
||||
toml_string_literal(&catalog.display().to_string())
|
||||
));
|
||||
cmd
|
||||
}
|
||||
|
||||
pub fn cwd_path(&self) -> &Path {
|
||||
self.cwd.path()
|
||||
}
|
||||
pub fn home_path(&self) -> &Path {
|
||||
self.home.path()
|
||||
}
|
||||
}
|
||||
|
||||
fn toml_string_literal(value: &str) -> String {
|
||||
serde_json::to_string(value).expect("serialize TOML string literal")
|
||||
}
|
||||
|
||||
pub fn test_codex_exec() -> TestCodexExecBuilder {
|
||||
TestCodexExecBuilder {
|
||||
home: TempDir::new().expect("create temp home"),
|
||||
cwd: TempDir::new().expect("create temp cwd"),
|
||||
}
|
||||
}
|
||||
186
akode-rs/core/tests/common/test_environment.rs
Normal file
186
akode-rs/core/tests/common/test_environment.rs
Normal file
@@ -0,0 +1,186 @@
|
||||
use std::ffi::OsStr;
|
||||
|
||||
use anyhow::Result;
|
||||
use akode_utils_path_uri::LegacyAppPathString;
|
||||
use akode_utils_path_uri::PathConvention;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
|
||||
pub const TEST_ENVIRONMENT_ENV_VAR: &str = "AKODE_TEST_ENVIRONMENT";
|
||||
pub const LEGACY_REMOTE_ENV_ENV_VAR: &str = "AKODE_TEST_REMOTE_ENV";
|
||||
pub const DOCKER_CONTAINER_ENV_VAR: &str = "AKODE_TEST_REMOTE_ENV_CONTAINER_NAME";
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum TestTargetOs {
|
||||
Linux,
|
||||
MacOs,
|
||||
Windows,
|
||||
}
|
||||
|
||||
impl TestTargetOs {
|
||||
const fn host() -> Self {
|
||||
if cfg!(target_os = "macos") {
|
||||
Self::MacOs
|
||||
} else if cfg!(target_os = "windows") {
|
||||
Self::Windows
|
||||
} else if cfg!(target_os = "linux") {
|
||||
Self::Linux
|
||||
} else {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
|
||||
const fn path_convention(self) -> PathConvention {
|
||||
match self {
|
||||
Self::Linux | Self::MacOs => PathConvention::Posix,
|
||||
Self::Windows => PathConvention::Windows,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum TestEnvironment {
|
||||
Local,
|
||||
Docker { container_name: String },
|
||||
WineExec,
|
||||
}
|
||||
|
||||
impl TestEnvironment {
|
||||
pub(crate) fn is_remote(&self) -> bool {
|
||||
!matches!(self, Self::Local)
|
||||
}
|
||||
|
||||
pub(crate) fn docker_container_name(&self) -> Option<&str> {
|
||||
match self {
|
||||
Self::Docker { container_name } => Some(container_name),
|
||||
Self::Local | Self::WineExec => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const fn target_os(&self) -> TestTargetOs {
|
||||
match self {
|
||||
Self::Local => TestTargetOs::host(),
|
||||
Self::Docker { .. } => TestTargetOs::Linux,
|
||||
Self::WineExec => TestTargetOs::Windows,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn remote_cwd(&self, instance_id: &str) -> Result<Option<LegacyAppPathString>> {
|
||||
let path_uri = match self {
|
||||
Self::Local => return Ok(None),
|
||||
Self::Docker { .. } => {
|
||||
PathUri::parse(&format!("file:///tmp/codex-core-test-cwd-{instance_id}"))?
|
||||
}
|
||||
Self::WineExec => {
|
||||
// Each Wine-exec test process has an isolated filesystem root, so this drive-root
|
||||
// path cannot collide with a different Bazel shard.
|
||||
PathUri::parse(&format!("file:///C:/codex-core-test-cwd-{instance_id}"))?
|
||||
}
|
||||
};
|
||||
Ok(Some(LegacyAppPathString::from_path_uri(
|
||||
&path_uri,
|
||||
self.path_convention(),
|
||||
)?))
|
||||
}
|
||||
|
||||
pub(crate) fn path_convention(&self) -> PathConvention {
|
||||
self.target_os().path_convention()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn test_environment() -> TestEnvironment {
|
||||
let environment = parse_test_environment(
|
||||
std::env::var_os(TEST_ENVIRONMENT_ENV_VAR).as_deref(),
|
||||
std::env::var_os(LEGACY_REMOTE_ENV_ENV_VAR).as_deref(),
|
||||
std::env::var_os(DOCKER_CONTAINER_ENV_VAR).as_deref(),
|
||||
)
|
||||
.expect("invalid test environment configuration");
|
||||
|
||||
if matches!(environment, TestEnvironment::WineExec) && !cfg!(target_os = "linux") {
|
||||
panic!("{TEST_ENVIRONMENT_ENV_VAR}=wine-exec is only supported on Linux");
|
||||
}
|
||||
|
||||
environment
|
||||
}
|
||||
|
||||
/// Returns the operating system used by the selected test execution environment.
|
||||
pub fn test_target_os() -> TestTargetOs {
|
||||
test_environment().target_os()
|
||||
}
|
||||
|
||||
/// Returns whether the selected test execution environment is remote.
|
||||
pub fn is_remote_test_environment() -> bool {
|
||||
test_environment().is_remote()
|
||||
}
|
||||
|
||||
/// Returns the selected Docker test container, when the harness requires direct access to it.
|
||||
#[doc(hidden)]
|
||||
pub fn test_docker_container_name() -> Option<String> {
|
||||
match test_environment() {
|
||||
TestEnvironment::Docker { container_name } => Some(container_name),
|
||||
TestEnvironment::Local | TestEnvironment::WineExec => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether the Wine-backed executor is selected.
|
||||
#[doc(hidden)]
|
||||
pub fn is_wine_exec_test_environment() -> bool {
|
||||
matches!(test_environment(), TestEnvironment::WineExec)
|
||||
}
|
||||
|
||||
fn parse_test_environment(
|
||||
configured_environment: Option<&OsStr>,
|
||||
legacy_remote_environment: Option<&OsStr>,
|
||||
docker_container: Option<&OsStr>,
|
||||
) -> Result<TestEnvironment, String> {
|
||||
let configured_environment = configured_environment
|
||||
.map(|value| {
|
||||
value
|
||||
.to_str()
|
||||
.ok_or_else(|| format!("{TEST_ENVIRONMENT_ENV_VAR} must contain valid UTF-8"))
|
||||
})
|
||||
.transpose()?;
|
||||
|
||||
match configured_environment {
|
||||
None => match legacy_remote_environment {
|
||||
Some(container_name) => Ok(TestEnvironment::Docker {
|
||||
container_name: non_empty_utf8(LEGACY_REMOTE_ENV_ENV_VAR, container_name)?,
|
||||
}),
|
||||
None => Ok(TestEnvironment::Local),
|
||||
},
|
||||
Some("local") => Ok(TestEnvironment::Local),
|
||||
Some("docker") => {
|
||||
let (container_name_env_var, container_name) = match docker_container {
|
||||
Some(container_name) => (DOCKER_CONTAINER_ENV_VAR, container_name),
|
||||
None => (
|
||||
LEGACY_REMOTE_ENV_ENV_VAR,
|
||||
legacy_remote_environment.ok_or_else(|| {
|
||||
format!(
|
||||
"{DOCKER_CONTAINER_ENV_VAR} must be set when {TEST_ENVIRONMENT_ENV_VAR}=docker"
|
||||
)
|
||||
})?,
|
||||
),
|
||||
};
|
||||
Ok(TestEnvironment::Docker {
|
||||
container_name: non_empty_utf8(container_name_env_var, container_name)?,
|
||||
})
|
||||
}
|
||||
Some("wine-exec") => Ok(TestEnvironment::WineExec),
|
||||
Some(value) => Err(format!(
|
||||
"{TEST_ENVIRONMENT_ENV_VAR} must be one of local, docker, or wine-exec; got {value:?}"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn non_empty_utf8(name: &str, value: &OsStr) -> Result<String, String> {
|
||||
let value = value
|
||||
.to_str()
|
||||
.ok_or_else(|| format!("{name} must contain valid UTF-8"))?;
|
||||
if value.trim().is_empty() {
|
||||
return Err(format!("{name} must not be empty"));
|
||||
}
|
||||
Ok(value.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "test_environment_tests.rs"]
|
||||
mod tests;
|
||||
145
akode-rs/core/tests/common/test_environment_tests.rs
Normal file
145
akode-rs/core/tests/common/test_environment_tests.rs
Normal file
@@ -0,0 +1,145 @@
|
||||
use std::ffi::OsStr;
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn defaults_to_local() {
|
||||
assert_eq!(
|
||||
parse_test_environment(
|
||||
/*configured_environment*/ None, /*legacy_remote_environment*/ None,
|
||||
/*docker_container*/ None,
|
||||
),
|
||||
Ok(TestEnvironment::Local)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_each_explicit_environment() {
|
||||
assert_eq!(
|
||||
parse_test_environment(
|
||||
Some(OsStr::new("local")),
|
||||
/*legacy_remote_environment*/ None,
|
||||
/*docker_container*/ None,
|
||||
),
|
||||
Ok(TestEnvironment::Local)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_test_environment(
|
||||
Some(OsStr::new("docker")),
|
||||
/*legacy_remote_environment*/ None,
|
||||
Some(OsStr::new("container-1")),
|
||||
),
|
||||
Ok(TestEnvironment::Docker {
|
||||
container_name: "container-1".to_string(),
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
parse_test_environment(
|
||||
Some(OsStr::new("wine-exec")),
|
||||
/*legacy_remote_environment*/ None,
|
||||
/*docker_container*/ None,
|
||||
),
|
||||
Ok(TestEnvironment::WineExec)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn treats_the_legacy_remote_value_as_a_docker_container() {
|
||||
assert_eq!(
|
||||
parse_test_environment(
|
||||
/*configured_environment*/ None,
|
||||
Some(OsStr::new("legacy-container")),
|
||||
/*docker_container*/ None,
|
||||
),
|
||||
Ok(TestEnvironment::Docker {
|
||||
container_name: "legacy-container".to_string(),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_docker_accepts_the_legacy_container_value() {
|
||||
assert_eq!(
|
||||
parse_test_environment(
|
||||
Some(OsStr::new("docker")),
|
||||
Some(OsStr::new("legacy-container")),
|
||||
/*docker_container*/ None,
|
||||
),
|
||||
Ok(TestEnvironment::Docker {
|
||||
container_name: "legacy-container".to_string(),
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
parse_test_environment(
|
||||
Some(OsStr::new("docker")),
|
||||
Some(OsStr::new("")),
|
||||
/*docker_container*/ None,
|
||||
),
|
||||
Err(format!("{LEGACY_REMOTE_ENV_ENV_VAR} must not be empty"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_local_ignores_stale_remote_metadata() {
|
||||
assert_eq!(
|
||||
parse_test_environment(
|
||||
Some(OsStr::new("local")),
|
||||
Some(OsStr::new("legacy-container")),
|
||||
Some(OsStr::new("container-1")),
|
||||
),
|
||||
Ok(TestEnvironment::Local)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_or_incomplete_configuration() {
|
||||
assert_eq!(
|
||||
parse_test_environment(
|
||||
Some(OsStr::new("docker")),
|
||||
/*legacy_remote_environment*/ None,
|
||||
/*docker_container*/ None,
|
||||
),
|
||||
Err(format!(
|
||||
"{DOCKER_CONTAINER_ENV_VAR} must be set when {TEST_ENVIRONMENT_ENV_VAR}=docker"
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_test_environment(
|
||||
Some(OsStr::new("other")),
|
||||
/*legacy_remote_environment*/ None,
|
||||
/*docker_container*/ None,
|
||||
),
|
||||
Err(format!(
|
||||
"{TEST_ENVIRONMENT_ENV_VAR} must be one of local, docker, or wine-exec; got \"other\""
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derives_target_operating_system_and_placement() {
|
||||
#[cfg(target_os = "linux")]
|
||||
let expected_local_target_os = TestTargetOs::Linux;
|
||||
#[cfg(target_os = "macos")]
|
||||
let expected_local_target_os = TestTargetOs::MacOs;
|
||||
#[cfg(target_os = "windows")]
|
||||
let expected_local_target_os = TestTargetOs::Windows;
|
||||
|
||||
let environments = [
|
||||
TestEnvironment::Local,
|
||||
TestEnvironment::Docker {
|
||||
container_name: "container-1".to_string(),
|
||||
},
|
||||
TestEnvironment::WineExec,
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
environments.map(|environment| (environment.target_os(), environment.is_remote())),
|
||||
[
|
||||
(expected_local_target_os, false),
|
||||
(TestTargetOs::Linux, true),
|
||||
(TestTargetOs::Windows, true),
|
||||
]
|
||||
);
|
||||
}
|
||||
69
akode-rs/core/tests/common/tracing.rs
Normal file
69
akode-rs/core/tests/common/tracing.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
use anyhow::Context;
|
||||
use opentelemetry::global;
|
||||
use opentelemetry::trace::TracerProvider as _;
|
||||
use opentelemetry_sdk::propagation::TraceContextPropagator;
|
||||
use opentelemetry_sdk::trace::SdkTracerProvider;
|
||||
use tracing::dispatcher::DefaultGuard;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
use tracing_subscriber::util::SubscriberInitExt;
|
||||
|
||||
/// Receives named trace events on a test's current-thread runtime.
|
||||
pub struct NamedTraceEvents {
|
||||
events: tokio::sync::mpsc::UnboundedReceiver<()>,
|
||||
_subscriber: DefaultGuard,
|
||||
}
|
||||
|
||||
impl NamedTraceEvents {
|
||||
pub fn subscribe(name: &'static str) -> Self {
|
||||
struct EventLayer {
|
||||
name: &'static str,
|
||||
sender: tokio::sync::mpsc::UnboundedSender<()>,
|
||||
}
|
||||
impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for EventLayer {
|
||||
fn on_event(
|
||||
&self,
|
||||
event: &tracing::Event<'_>,
|
||||
_: tracing_subscriber::layer::Context<'_, S>,
|
||||
) {
|
||||
if event.metadata().name() == self.name {
|
||||
let _ = self.sender.send(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let (sender, events) = tokio::sync::mpsc::unbounded_channel();
|
||||
let subscriber = tracing_subscriber::registry()
|
||||
.with(EventLayer { name, sender })
|
||||
.set_default();
|
||||
Self {
|
||||
events,
|
||||
_subscriber: subscriber,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn next(&mut self) -> anyhow::Result<()> {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), self.events.recv())
|
||||
.await
|
||||
.context("timed out waiting for trace event")?
|
||||
.context("trace collector closed")
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TestTracingContext {
|
||||
_provider: SdkTracerProvider,
|
||||
_guard: DefaultGuard,
|
||||
}
|
||||
|
||||
pub fn install_test_tracing(tracer_name: &str) -> TestTracingContext {
|
||||
global::set_text_map_propagator(TraceContextPropagator::new());
|
||||
|
||||
let provider = SdkTracerProvider::builder().build();
|
||||
let tracer = provider.tracer(tracer_name.to_string());
|
||||
let subscriber =
|
||||
tracing_subscriber::registry().with(tracing_opentelemetry::layer().with_tracer(tracer));
|
||||
|
||||
TestTracingContext {
|
||||
_provider: provider,
|
||||
_guard: subscriber.set_default(),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user