Initial public release
Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
223
crates/luxe-providers/tests/incremental_streaming.rs
Normal file
223
crates/luxe-providers/tests/incremental_streaming.rs
Normal file
@@ -0,0 +1,223 @@
|
||||
//! Provider adapters must stream, not buffer.
|
||||
//!
|
||||
//! Every adapter used to call `response.text().await` before parsing, so reasoning and answer text
|
||||
//! reached the UI only after the provider had finished the whole call. These tests keep an SSE body
|
||||
//! deliberately open and assert the first events arrive while it is still open — the one property
|
||||
//! whole-body parsing cannot satisfy.
|
||||
|
||||
use futures::StreamExt;
|
||||
use luxe_core::message::Message;
|
||||
use luxe_core::provider::{
|
||||
CompletionRequest, ModelInfo, ModelRef, Provider, ProviderEvent, ThinkingLevel,
|
||||
};
|
||||
use luxe_providers::anthropic::{AnthropicCompat, AnthropicProvider};
|
||||
use luxe_providers::config::{CompatFlags, ProviderConfig};
|
||||
use luxe_providers::openai_compat::OpenaiCompatProvider;
|
||||
use std::io::Write;
|
||||
use std::time::Duration;
|
||||
|
||||
/// How long the server holds the body open after the first records.
|
||||
const HOLD: Duration = Duration::from_millis(1_500);
|
||||
/// Budget for opening the call *and* seeing its first event. Comfortably under `HOLD`, so passing
|
||||
/// means "did not wait for the body to finish" rather than "was quick".
|
||||
///
|
||||
/// The budget has to cover `Provider::stream` too: whole-body parsing blocks *there*, before the
|
||||
/// stream is even returned, so timing only the first `next()` would pass either way.
|
||||
const FIRST_EVENT_BUDGET: Duration = Duration::from_millis(600);
|
||||
|
||||
/// Serves one HTTP response whose SSE body arrives in two halves, `HOLD` apart.
|
||||
///
|
||||
/// No `Content-Length`: HTTP/1.1 then frames the body by connection close, which is exactly how
|
||||
/// the real providers stream, and lets us write the halves whenever we like.
|
||||
fn serve_split_sse(first: String, second: String) -> u16 {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
|
||||
let port = listener.local_addr().expect("addr").port();
|
||||
std::thread::spawn(move || {
|
||||
let (mut socket, _) = listener.accept().expect("accept");
|
||||
read_request_head(&mut socket);
|
||||
let head =
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n";
|
||||
socket.write_all(head.as_bytes()).expect("head");
|
||||
socket.write_all(first.as_bytes()).expect("first half");
|
||||
socket.flush().expect("flush");
|
||||
std::thread::sleep(HOLD);
|
||||
socket.write_all(second.as_bytes()).expect("second half");
|
||||
let _ = socket.flush();
|
||||
});
|
||||
port
|
||||
}
|
||||
|
||||
/// Reads request headers (and any body) off `socket` far enough to reply.
|
||||
fn read_request_head(socket: &mut std::net::TcpStream) {
|
||||
use std::io::Read;
|
||||
|
||||
let mut buffer = Vec::new();
|
||||
let mut chunk = [0u8; 2048];
|
||||
loop {
|
||||
let read = socket.read(&mut chunk).unwrap_or(0);
|
||||
if read == 0 {
|
||||
return;
|
||||
}
|
||||
buffer.extend_from_slice(&chunk[..read]);
|
||||
let text = String::from_utf8_lossy(&buffer);
|
||||
if let Some(head_end) = text.find("\r\n\r\n") {
|
||||
let length = text
|
||||
.lines()
|
||||
.find_map(|line| {
|
||||
line.to_ascii_lowercase()
|
||||
.strip_prefix("content-length:")
|
||||
.map(|value| value.trim().parse::<usize>().unwrap_or(0))
|
||||
})
|
||||
.unwrap_or(0);
|
||||
if buffer.len() >= head_end + 4 + length {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn model(provider: &str) -> ModelInfo {
|
||||
ModelInfo {
|
||||
r#ref: ModelRef::new(provider, "test-model"),
|
||||
max_tokens: 1024,
|
||||
context_window: 8192,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn request(model: ModelInfo) -> CompletionRequest {
|
||||
CompletionRequest {
|
||||
model,
|
||||
messages: vec![Message::user("hello")],
|
||||
system: None,
|
||||
tools: vec![],
|
||||
thinking: ThinkingLevel::Off,
|
||||
max_tokens: Some(256),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Anthropic: a thinking delta in the first half must be observable before the second half exists.
|
||||
#[tokio::test]
|
||||
async fn anthropic_thinking_deltas_arrive_while_the_body_is_still_open() {
|
||||
let first = "event: content_block_delta\n\
|
||||
data: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"thinking_delta\",\"thinking\":\"pondering\"}}\n\n"
|
||||
.to_string();
|
||||
let second = "event: content_block_delta\n\
|
||||
data: {\"type\":\"content_block_delta\",\"index\":1,\"delta\":{\"type\":\"text_delta\",\"text\":\"answer\"}}\n\n\
|
||||
event: message_stop\n\
|
||||
data: {\"type\":\"message_stop\"}\n\n"
|
||||
.to_string();
|
||||
let port = serve_split_sse(first, second);
|
||||
|
||||
let model = model("anthropic");
|
||||
let provider = AnthropicProvider::new(
|
||||
"test-key".into(),
|
||||
Some(format!("http://127.0.0.1:{port}/v1")),
|
||||
model.clone(),
|
||||
AnthropicCompat::default(),
|
||||
);
|
||||
let (_keep, cancel) = tokio::sync::watch::channel(false);
|
||||
let (stream, event) = tokio::time::timeout(FIRST_EVENT_BUDGET, async {
|
||||
let mut stream = provider.stream(request(model), cancel).await.expect("stream opens");
|
||||
let event = stream.next().await;
|
||||
(stream, event)
|
||||
})
|
||||
.await
|
||||
.expect("the first reasoning delta must not wait for the whole response");
|
||||
assert!(
|
||||
matches!(event, Some(ProviderEvent::ThinkingDelta { ref delta, .. }) if delta == "pondering"),
|
||||
"expected a streamed thinking delta, got {event:?}"
|
||||
);
|
||||
|
||||
// The rest still arrives once the server sends it, terminator included.
|
||||
let rest: Vec<ProviderEvent> = stream.collect().await;
|
||||
assert!(
|
||||
rest.iter().any(
|
||||
|event| matches!(event, ProviderEvent::TextDelta { delta, .. } if delta == "answer")
|
||||
),
|
||||
"{rest:?}"
|
||||
);
|
||||
assert!(matches!(rest.last(), Some(ProviderEvent::Done { .. })), "{rest:?}");
|
||||
}
|
||||
|
||||
/// OpenAI-compatible: same property, plus the reasoning field these servers actually use.
|
||||
#[tokio::test]
|
||||
async fn openai_compat_deltas_arrive_while_the_body_is_still_open() {
|
||||
let first = concat!(
|
||||
r#"data: {"choices":[{"index":0,"delta":{"reasoning_content":"pondering"}}]}"#,
|
||||
"\n\n",
|
||||
r#"data: {"choices":[{"index":0,"delta":{"content":"ans"}}]}"#,
|
||||
"\n\n"
|
||||
)
|
||||
.to_string();
|
||||
let second = concat!(
|
||||
r#"data: {"choices":[{"index":0,"finish_reason":"stop"}],"usage":{"prompt_tokens":9,"completion_tokens":2,"total_tokens":11}}"#,
|
||||
"\n\n",
|
||||
"data: [DONE]\n\n"
|
||||
)
|
||||
.to_string();
|
||||
let port = serve_split_sse(first, second);
|
||||
|
||||
let provider = OpenaiCompatProvider::new(
|
||||
ProviderConfig {
|
||||
api_key: Some("test-key".into()),
|
||||
base_url: Some(format!("http://127.0.0.1:{port}/v1")),
|
||||
..Default::default()
|
||||
},
|
||||
CompatFlags::default(),
|
||||
);
|
||||
let (_keep, cancel) = tokio::sync::watch::channel(false);
|
||||
let (stream, event) = tokio::time::timeout(FIRST_EVENT_BUDGET, async {
|
||||
let mut stream =
|
||||
provider.stream(request(model("openai_compat")), cancel).await.expect("stream opens");
|
||||
let event = stream.next().await;
|
||||
(stream, event)
|
||||
})
|
||||
.await
|
||||
.expect("the first reasoning delta must not wait for the whole response");
|
||||
assert!(
|
||||
matches!(event, Some(ProviderEvent::ThinkingDelta { ref delta, .. }) if delta == "pondering"),
|
||||
"expected a streamed reasoning delta, got {event:?}"
|
||||
);
|
||||
|
||||
let rest: Vec<ProviderEvent> = stream.collect().await;
|
||||
let usage_before_done = rest
|
||||
.iter()
|
||||
.position(|event| matches!(event, ProviderEvent::Usage(_)))
|
||||
.zip(rest.iter().position(|event| matches!(event, ProviderEvent::Done { .. })))
|
||||
.is_some_and(|(usage, done)| usage < done);
|
||||
assert!(usage_before_done, "usage must still land before Done: {rest:?}");
|
||||
}
|
||||
|
||||
/// A cancelled turn drops the connection instead of waiting out a provider that has gone quiet.
|
||||
#[tokio::test]
|
||||
async fn cancelling_ends_the_stream_without_waiting_for_the_body() {
|
||||
let first = "event: content_block_delta\n\
|
||||
data: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"partial\"}}\n\n"
|
||||
.to_string();
|
||||
let port = serve_split_sse(first, String::new());
|
||||
|
||||
let model = model("anthropic");
|
||||
let provider = AnthropicProvider::new(
|
||||
"test-key".into(),
|
||||
Some(format!("http://127.0.0.1:{port}/v1")),
|
||||
model.clone(),
|
||||
AnthropicCompat::default(),
|
||||
);
|
||||
let (cancel_tx, cancel) = tokio::sync::watch::channel(false);
|
||||
let (mut stream, first_event) = tokio::time::timeout(FIRST_EVENT_BUDGET, async {
|
||||
let mut stream = provider.stream(request(model), cancel).await.expect("stream opens");
|
||||
let event = stream.next().await;
|
||||
(stream, event)
|
||||
})
|
||||
.await
|
||||
.expect("the first delta must not wait for the whole response");
|
||||
assert!(matches!(first_event, Some(ProviderEvent::TextDelta { .. })), "{first_event:?}");
|
||||
|
||||
cancel_tx.send(true).expect("cancel");
|
||||
let ended =
|
||||
tokio::time::timeout(FIRST_EVENT_BUDGET, async { while stream.next().await.is_some() {} })
|
||||
.await;
|
||||
assert!(ended.is_ok(), "a cancelled stream must end without waiting out the body");
|
||||
}
|
||||
82
crates/luxe-providers/tests/live_codex_probe.rs
Normal file
82
crates/luxe-providers/tests/live_codex_probe.rs
Normal file
@@ -0,0 +1,82 @@
|
||||
//! Live smoke test: does the ChatGPT-account Codex backend still report plan headroom?
|
||||
//!
|
||||
//! Ignored, so it never runs in CI or on a machine without a ChatGPT plan, and reports as ignored
|
||||
//! rather than passed. Run on purpose, it needs a stored credential and fails without one. It
|
||||
//! exists because the `x-codex-*` headers Luxe's plan meter reads are undocumented: they were read
|
||||
//! off a live response, and the only way to learn they have moved is to ask. A failure here means the meter has gone quiet, not that the login is broken.
|
||||
//!
|
||||
//! Run it with `--no-capture` to also see the raw headers, which is what you want when it fails:
|
||||
//!
|
||||
//! ```text
|
||||
//! cargo nextest run -p luxe-providers -E 'binary(live_codex_probe)' --run-ignored only --no-capture
|
||||
//! ```
|
||||
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use luxe_providers::auth::{AuthStore, Credential};
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "needs a stored ChatGPT credential and a network"]
|
||||
async fn codex_still_reports_plan_headroom() {
|
||||
let Some(Credential::OAuth(credential)) = AuthStore::default_path().credential("openai-codex")
|
||||
else {
|
||||
panic!("no stored openai-codex credential — run `luxe auth login codex`");
|
||||
};
|
||||
let account = credential.account.clone().expect("credential carries an account id");
|
||||
|
||||
// The smallest request that still gets a real response: one word in, one word out.
|
||||
let body = serde_json::json!({
|
||||
"model": "gpt-5.6-sol",
|
||||
"stream": true,
|
||||
"store": false,
|
||||
"instructions": "Answer in one word.",
|
||||
"input": [{
|
||||
"type": "message",
|
||||
"role": "user",
|
||||
"content": [{ "type": "input_text", "text": "ping" }],
|
||||
}],
|
||||
});
|
||||
|
||||
let response = reqwest::Client::new()
|
||||
.post("https://chatgpt.com/backend-api/codex/responses")
|
||||
.header("Authorization", format!("Bearer {}", credential.access.expose()))
|
||||
.header("chatgpt-account-id", account)
|
||||
.header("OpenAI-Beta", "responses=experimental")
|
||||
.header("originator", "luxe")
|
||||
.header("Accept", "text/event-stream")
|
||||
.header("Content-Type", "application/json")
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.expect("the Codex backend is reachable");
|
||||
|
||||
// Print the headers unconditionally: when the assertions below fail, this is the diagnosis.
|
||||
println!("status: {}", response.status());
|
||||
for (name, value) in response.headers() {
|
||||
if name.as_str().starts_with("x-codex-") {
|
||||
println!(" {name}: {}", value.to_str().unwrap_or("<binary>"));
|
||||
}
|
||||
}
|
||||
|
||||
assert!(
|
||||
response.status().is_success(),
|
||||
"Codex refused the request ({}) — the credential or the model list may have moved",
|
||||
response.status()
|
||||
);
|
||||
|
||||
let plan = luxe_providers::openai_responses::plan_usage_from_headers(response.headers())
|
||||
.expect(
|
||||
"no x-codex-* plan headers on the response: the meter has gone quiet, and \
|
||||
`plan_usage_from_headers` needs the new names (see the dump above)",
|
||||
);
|
||||
println!("parsed: {:?}", plan.summary());
|
||||
|
||||
assert!(plan.plan.is_some(), "the response should name the plan: {plan:?}");
|
||||
let primary = plan.primary.expect("a plan has a primary allowance window");
|
||||
assert!(primary.window_minutes > 0, "a window with no length can't be rendered: {primary:?}");
|
||||
assert!(
|
||||
(0.0..=100.0).contains(&primary.used_percent),
|
||||
"used percent out of range: {primary:?}"
|
||||
);
|
||||
assert!(plan.summary().is_some(), "a parsed plan must render");
|
||||
}
|
||||
117
crates/luxe-providers/tests/live_foundry_probe.rs
Normal file
117
crates/luxe-providers/tests/live_foundry_probe.rs
Normal file
@@ -0,0 +1,117 @@
|
||||
//! Live smoke test: do both halves of a Microsoft Foundry resource still answer?
|
||||
//!
|
||||
//! Ignored, so it never runs in CI or on a machine without a Foundry resource, and reports as
|
||||
//! ignored rather than passed. Run on purpose, it needs a stored credential for at least one half.
|
||||
//! It exists because the two things Luxe had to decide from documentation — that the Anthropic
|
||||
//! passthrough authenticates on `x-api-key`/`api-key` rather than a bearer token, and that the
|
||||
//! OpenAI half takes a bearer — are only really settled by a 200. A failure here means Foundry moved, not that the login is broken.
|
||||
//!
|
||||
//! Run it with `--no-capture` to see each response's status and first bytes, which is what you want
|
||||
//! when it fails:
|
||||
//!
|
||||
//! ```text
|
||||
//! cargo nextest run -p luxe-providers \
|
||||
//! -E 'binary(live_foundry_probe)' --run-ignored only --no-capture
|
||||
//! ```
|
||||
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use luxe_providers::auth::{provider_descriptor, AuthStore, Credential};
|
||||
use luxe_providers::config::{load_models_config, ApiKey};
|
||||
|
||||
/// The smallest turn that still proves streaming, tool-free, one word each way.
|
||||
const PROMPT: &str = "Reply with the single word: pong";
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "needs a configured Foundry resource and a network"]
|
||||
async fn both_foundry_surfaces_accept_the_stored_key() {
|
||||
let mut checked = 0usize;
|
||||
for (id, model_env, default_model) in [
|
||||
("foundry-anthropic", "LUXE_TEST_FOUNDRY_CLAUDE", "claude-sonnet-5"),
|
||||
("foundry-openai", "LUXE_TEST_FOUNDRY_GPT", "gpt-5.6-sol"),
|
||||
] {
|
||||
let Some(key) = stored_key(id) else {
|
||||
eprintln!("skipping {id}: nothing stored — run `luxe auth login foundry`");
|
||||
continue;
|
||||
};
|
||||
let Some(base_url) = configured_base_url(id) else {
|
||||
eprintln!("skipping {id}: no base_url in models.json — run `luxe auth login foundry`");
|
||||
continue;
|
||||
};
|
||||
let model = std::env::var(model_env).unwrap_or_else(|_| default_model.to_string());
|
||||
let descriptor = provider_descriptor(id).expect("in catalog");
|
||||
|
||||
let (url, body) = match id {
|
||||
"foundry-anthropic" => (
|
||||
format!("{base_url}/messages"),
|
||||
serde_json::json!({
|
||||
"model": model,
|
||||
"max_tokens": 64,
|
||||
"stream": true,
|
||||
"messages": [{ "role": "user", "content": PROMPT }],
|
||||
}),
|
||||
),
|
||||
_ => (
|
||||
format!("{base_url}/responses"),
|
||||
serde_json::json!({
|
||||
"model": model,
|
||||
"stream": true,
|
||||
"store": false,
|
||||
"max_output_tokens": 1024,
|
||||
"input": [{
|
||||
"type": "message",
|
||||
"role": "user",
|
||||
"content": [{ "type": "input_text", "text": PROMPT }],
|
||||
}],
|
||||
}),
|
||||
),
|
||||
};
|
||||
|
||||
let mut request = reqwest::Client::new()
|
||||
.post(&url)
|
||||
.header("Accept", "text/event-stream")
|
||||
.header("Content-Type", "application/json");
|
||||
if descriptor.api == luxe_core::auth::ApiKind::AnthropicMessages {
|
||||
request = request.header("anthropic-version", "2023-06-01");
|
||||
}
|
||||
request = descriptor.key_style().headers(&key).apply(request);
|
||||
|
||||
let response = request.json(&body).send().await.expect("Foundry is reachable");
|
||||
let status = response.status();
|
||||
let text = response.text().await.unwrap_or_default();
|
||||
println!("{id} -> {url}\n status: {status}\n body: {}", &text[..text.len().min(400)]);
|
||||
|
||||
assert!(
|
||||
status.is_success(),
|
||||
"{id} refused the request ({status}) at {url}. A 401 means the key headers moved \
|
||||
(Luxe sends {:?}); a 404 means the path did; a 400 naming the model means \
|
||||
'{model}' is not a deployment on this resource.\n{text}",
|
||||
descriptor.key_style(),
|
||||
);
|
||||
assert!(
|
||||
text.contains("data:"),
|
||||
"{id} answered {status} but not as a stream — the SSE decoder would see nothing:\n{text}"
|
||||
);
|
||||
checked += 1;
|
||||
}
|
||||
|
||||
assert!(checked > 0, "nothing was configured to probe — run `luxe auth login foundry` first");
|
||||
}
|
||||
|
||||
/// The stored credential for `id`, resolved the way a request resolves it.
|
||||
fn stored_key(id: &str) -> Option<ApiKey> {
|
||||
match AuthStore::default_path().credential(id)? {
|
||||
Credential::ApiKey(api) => {
|
||||
let resolved = luxe_providers::config::resolve_value(api.key.expose());
|
||||
(!resolved.trim().is_empty()).then(|| ApiKey::new(resolved))
|
||||
}
|
||||
Credential::OAuth(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The base URL the login recorded for `id`.
|
||||
fn configured_base_url(id: &str) -> Option<String> {
|
||||
let path = luxe_providers::auth::ConfigFile::default_path().path().to_path_buf();
|
||||
let base = load_models_config(&path).ok()?.providers.get(id)?.base_url.clone()?;
|
||||
Some(base.trim_end_matches('/').to_string())
|
||||
}
|
||||
519
crates/luxe-providers/tests/oauth_flows.rs
Normal file
519
crates/luxe-providers/tests/oauth_flows.rs
Normal file
@@ -0,0 +1,519 @@
|
||||
//! OAuth flows end to end against a local mock server.
|
||||
//!
|
||||
//! The unit tests cover the pieces (URL building, JWT claims, poll classification); these drive the
|
||||
//! real code paths over a real socket, so a wrong verb, a missing form field, or a mis-parsed
|
||||
//! response fails here rather than in front of a user. Nothing in this file touches the network:
|
||||
//! every flow is pointed at a `127.0.0.1` listener whose scripted replies are the shapes the
|
||||
//! providers actually send.
|
||||
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use base64::Engine as _;
|
||||
use luxe_providers::auth::credential::OAuthCredential;
|
||||
use luxe_providers::auth::oauth::{github_copilot, openai_codex, openrouter};
|
||||
use luxe_providers::auth::Credential;
|
||||
use luxe_providers::config::ApiKey;
|
||||
|
||||
/// A request the mock server saw.
|
||||
#[derive(Debug, Clone)]
|
||||
struct Seen {
|
||||
method: String,
|
||||
path: String,
|
||||
body: String,
|
||||
authorization: Option<String>,
|
||||
}
|
||||
|
||||
/// A scripted local HTTP server.
|
||||
///
|
||||
/// Replies come from a per-path queue, so a poll can answer "pending" once and then succeed —
|
||||
/// which is the behavior that matters for a device flow.
|
||||
struct MockServer {
|
||||
base: String,
|
||||
seen: Arc<Mutex<Vec<Seen>>>,
|
||||
task: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl Drop for MockServer {
|
||||
fn drop(&mut self) {
|
||||
self.task.abort();
|
||||
}
|
||||
}
|
||||
|
||||
impl MockServer {
|
||||
/// Serve `replies` (path → queued `(status, body)` responses) on a free loopback port.
|
||||
async fn start(replies: HashMap<String, Vec<(u16, String)>>) -> Self {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let base = format!("http://{}", listener.local_addr().unwrap());
|
||||
let seen = Arc::new(Mutex::new(Vec::new()));
|
||||
let log = seen.clone();
|
||||
let queues = Arc::new(Mutex::new(replies));
|
||||
|
||||
let task = tokio::spawn(async move {
|
||||
loop {
|
||||
let Ok((mut socket, _)) = listener.accept().await else { return };
|
||||
let Some(request) = read_request(&mut socket).await else { continue };
|
||||
log.lock().unwrap().push(request.clone());
|
||||
let (status, body) = queues
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get_mut(&request.path)
|
||||
.and_then(|queue| {
|
||||
// The last scripted reply repeats, so a poller can keep polling.
|
||||
if queue.len() > 1 {
|
||||
Some(queue.remove(0))
|
||||
} else {
|
||||
queue.first().cloned()
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|| (404, "{}".to_string()));
|
||||
respond(&mut socket, status, &body).await;
|
||||
}
|
||||
});
|
||||
Self { base, seen, task }
|
||||
}
|
||||
|
||||
fn url(&self, path: &str) -> String {
|
||||
format!("{}{path}", self.base)
|
||||
}
|
||||
|
||||
fn requests(&self) -> Vec<Seen> {
|
||||
self.seen.lock().unwrap().clone()
|
||||
}
|
||||
|
||||
fn request_to(&self, path: &str) -> Seen {
|
||||
self.requests()
|
||||
.into_iter()
|
||||
.find(|request| request.path == path)
|
||||
.unwrap_or_else(|| panic!("no request to {path}; saw {:?}", self.requests()))
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_request(socket: &mut tokio::net::TcpStream) -> Option<Seen> {
|
||||
use tokio::io::AsyncReadExt;
|
||||
let mut buffer = vec![0u8; 16 * 1024];
|
||||
let read = socket.read(&mut buffer).await.ok()?;
|
||||
let text = String::from_utf8_lossy(&buffer[..read]).to_string();
|
||||
let mut lines = text.lines();
|
||||
let start = lines.next()?;
|
||||
let mut parts = start.split_whitespace();
|
||||
let method = parts.next()?.to_string();
|
||||
let target = parts.next()?.to_string();
|
||||
let path = target.split('?').next().unwrap_or(&target).to_string();
|
||||
let authorization = text
|
||||
.lines()
|
||||
.find(|line| line.to_ascii_lowercase().starts_with("authorization:"))
|
||||
.map(|line| line[14..].trim().to_string());
|
||||
let body = text.split_once("\r\n\r\n").map(|(_, body)| body.to_string()).unwrap_or_default();
|
||||
Some(Seen { method, path, body, authorization })
|
||||
}
|
||||
|
||||
async fn respond(socket: &mut tokio::net::TcpStream, status: u16, body: &str) {
|
||||
use tokio::io::AsyncWriteExt;
|
||||
let response = format!(
|
||||
"HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\
|
||||
Connection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
);
|
||||
let _ = socket.write_all(response.as_bytes()).await;
|
||||
let _ = socket.flush().await;
|
||||
}
|
||||
|
||||
fn replies(pairs: &[(&str, &[(u16, &str)])]) -> HashMap<String, Vec<(u16, String)>> {
|
||||
pairs
|
||||
.iter()
|
||||
.map(|(path, queue)| {
|
||||
let queue = queue.iter().map(|(status, body)| (*status, (*body).to_string())).collect();
|
||||
((*path).to_string(), queue)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A ChatGPT access token carrying the account-id claim the Codex backend requires.
|
||||
fn chatgpt_token(account: &str) -> String {
|
||||
let claims =
|
||||
serde_json::json!({ "https://api.openai.com/auth": { "chatgpt_account_id": account } });
|
||||
let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.encode(serde_json::to_vec(&claims).unwrap());
|
||||
format!("header.{payload}.signature")
|
||||
}
|
||||
|
||||
// === OpenAI Codex ===
|
||||
|
||||
#[tokio::test]
|
||||
async fn codex_exchanges_an_authorization_code_for_a_credential() {
|
||||
let access = chatgpt_token("acct-42");
|
||||
let token_body = serde_json::json!({
|
||||
"access_token": access,
|
||||
"refresh_token": "refresh-1",
|
||||
"expires_in": 3600,
|
||||
})
|
||||
.to_string();
|
||||
let server =
|
||||
MockServer::start(replies(&[("/oauth/token", &[(200, token_body.as_str())])])).await;
|
||||
let endpoints = openai_codex::Endpoints::at(&server.url(""));
|
||||
|
||||
let credential = openai_codex::exchange_code(
|
||||
&endpoints,
|
||||
"the-code",
|
||||
"the-verifier",
|
||||
"http://localhost:1455/auth/callback",
|
||||
)
|
||||
.await
|
||||
.expect("exchanges");
|
||||
|
||||
assert_eq!(credential.account.as_deref(), Some("acct-42"));
|
||||
assert_eq!(credential.refresh.expose(), "refresh-1");
|
||||
assert!(credential.expires_at_ms > 0);
|
||||
|
||||
// The wire contract: a form POST carrying the PKCE verifier and the redirect it was issued for.
|
||||
let request = server.request_to("/oauth/token");
|
||||
assert_eq!(request.method, "POST");
|
||||
for expected in [
|
||||
"grant_type=authorization_code",
|
||||
"code=the-code",
|
||||
"code_verifier=the-verifier",
|
||||
"client_id=",
|
||||
] {
|
||||
assert!(request.body.contains(expected), "missing {expected} in {}", request.body);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn codex_refresh_keeps_the_old_token_when_the_response_omits_one() {
|
||||
let body = serde_json::json!({
|
||||
"access_token": chatgpt_token("acct-42"),
|
||||
"expires_in": 3600,
|
||||
})
|
||||
.to_string();
|
||||
let server = MockServer::start(replies(&[("/oauth/token", &[(200, body.as_str())])])).await;
|
||||
let endpoints = openai_codex::Endpoints::at(&server.url(""));
|
||||
|
||||
let existing = OAuthCredential {
|
||||
access: ApiKey::new("stale"),
|
||||
refresh: ApiKey::new("keep-me"),
|
||||
expires_at_ms: 1,
|
||||
..Default::default()
|
||||
};
|
||||
let refreshed = openai_codex::refresh_with(&endpoints, &existing).await.expect("refreshes");
|
||||
|
||||
assert_eq!(
|
||||
refreshed.refresh.expose(),
|
||||
"keep-me",
|
||||
"a provider that doesn't rotate the refresh token must not lose it"
|
||||
);
|
||||
assert!(server.request_to("/oauth/token").body.contains("grant_type=refresh_token"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn codex_reports_the_providers_own_message_when_a_token_is_refused() {
|
||||
let body =
|
||||
serde_json::json!({ "error": "invalid_grant", "error_description": "expired" }).to_string();
|
||||
let server = MockServer::start(replies(&[("/oauth/token", &[(400, body.as_str())])])).await;
|
||||
let endpoints = openai_codex::Endpoints::at(&server.url(""));
|
||||
|
||||
let error = openai_codex::exchange_code(&endpoints, "c", "v", "http://localhost/cb")
|
||||
.await
|
||||
.expect_err("must fail");
|
||||
assert!(error.to_string().contains("expired"), "unhelpful: {error}");
|
||||
}
|
||||
|
||||
// === GitHub Copilot ===
|
||||
|
||||
#[tokio::test]
|
||||
async fn copilot_exchanges_a_github_token_and_learns_its_endpoint() {
|
||||
let expires_at = (luxe_providers::auth::credential::now_ms() / 1000) + 3600;
|
||||
let body = serde_json::json!({
|
||||
"token": "tid=abc;exp=1;proxy-ep=proxy.business.githubcopilot.com",
|
||||
"expires_at": expires_at,
|
||||
})
|
||||
.to_string();
|
||||
let server =
|
||||
MockServer::start(replies(&[("/copilot_internal/v2/token", &[(200, body.as_str())])]))
|
||||
.await;
|
||||
// `Endpoints` builds `https://api.{domain}/…`; point every field at the mock instead.
|
||||
let endpoints = github_copilot::Endpoints {
|
||||
device_code: server.url("/login/device/code"),
|
||||
access_token: server.url("/login/oauth/access_token"),
|
||||
copilot_token: server.url("/copilot_internal/v2/token"),
|
||||
};
|
||||
|
||||
let credential = github_copilot::exchange_copilot_token(&endpoints, "gho_token", None)
|
||||
.await
|
||||
.expect("exchanges");
|
||||
|
||||
assert_eq!(credential.refresh.expose(), "gho_token", "the GitHub token is the refresh token");
|
||||
assert_eq!(
|
||||
credential.endpoint.as_deref(),
|
||||
Some("https://api.business.githubcopilot.com"),
|
||||
"the account's proxy endpoint decides where requests go"
|
||||
);
|
||||
assert!(credential.expires_at_ms > 0);
|
||||
|
||||
// Copilot authenticates this call with the GitHub token and requires its editor headers.
|
||||
let request = server.request_to("/copilot_internal/v2/token");
|
||||
assert_eq!(request.authorization.as_deref(), Some("Bearer gho_token"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn copilot_explains_a_missing_subscription_rather_than_echoing_a_403() {
|
||||
let server = MockServer::start(replies(&[(
|
||||
"/copilot_internal/v2/token",
|
||||
&[(403, r#"{"message":"forbidden"}"#)],
|
||||
)]))
|
||||
.await;
|
||||
let endpoints = github_copilot::Endpoints {
|
||||
device_code: server.url("/login/device/code"),
|
||||
access_token: server.url("/login/oauth/access_token"),
|
||||
copilot_token: server.url("/copilot_internal/v2/token"),
|
||||
};
|
||||
|
||||
let error = github_copilot::exchange_copilot_token(&endpoints, "gho_token", None)
|
||||
.await
|
||||
.expect_err("must fail");
|
||||
assert!(
|
||||
error.to_string().contains("Copilot subscription"),
|
||||
"the error should name the actual problem: {error}"
|
||||
);
|
||||
}
|
||||
|
||||
// === OpenRouter ===
|
||||
|
||||
#[tokio::test]
|
||||
async fn openrouter_mints_an_api_key_from_the_callback_code() {
|
||||
let server = MockServer::start(replies(&[(
|
||||
"/api/v1/auth/keys",
|
||||
&[(200, r#"{"key":"sk-or-v1-minted"}"#)],
|
||||
)]))
|
||||
.await;
|
||||
let endpoints = openrouter::Endpoints {
|
||||
authorize: server.url("/auth"),
|
||||
keys: server.url("/api/v1/auth/keys"),
|
||||
};
|
||||
|
||||
// Drive the flow the way the UI does: it opens a URL, then the loopback callback answers.
|
||||
let interaction = CallbackDriver::new();
|
||||
let credential = openrouter::login_with(&endpoints, &interaction).await.expect("mints a key");
|
||||
|
||||
match credential {
|
||||
Credential::ApiKey(api) => assert_eq!(api.key.expose(), "sk-or-v1-minted"),
|
||||
Credential::OAuth(_) => panic!("OpenRouter mints a durable key, not a token pair"),
|
||||
}
|
||||
let request = server.request_to("/api/v1/auth/keys");
|
||||
assert!(request.body.contains("code_verifier"), "PKCE verifier must be sent: {}", request.body);
|
||||
assert!(request.body.contains("\"code\""), "the callback code must be sent: {}", request.body);
|
||||
}
|
||||
|
||||
/// An interaction that completes a loopback flow by fetching the redirect URL itself.
|
||||
///
|
||||
/// This is the browser's half of the handshake: the flow publishes an authorization URL carrying a
|
||||
/// `callback_url`, and something has to actually hit that callback.
|
||||
struct CallbackDriver {
|
||||
events: Mutex<Vec<luxe_core::auth::AuthEvent>>,
|
||||
}
|
||||
|
||||
impl CallbackDriver {
|
||||
fn new() -> Self {
|
||||
Self { events: Mutex::new(Vec::new()) }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl luxe_core::auth::AuthInteraction for CallbackDriver {
|
||||
async fn prompt(
|
||||
&self,
|
||||
_prompt: luxe_core::auth::AuthPrompt,
|
||||
) -> Result<secrecy::SecretString, luxe_core::auth::AuthError> {
|
||||
// The paste fallback never wins here: the callback does. Wait rather than answering, so the
|
||||
// test exercises the loopback path and the race between them.
|
||||
std::future::pending().await
|
||||
}
|
||||
|
||||
fn notify(&self, event: luxe_core::auth::AuthEvent) {
|
||||
if let luxe_core::auth::AuthEvent::OpenUrl { url, .. } = &event {
|
||||
// Extract the callback the flow asked the browser to return to, and hit it.
|
||||
if let Ok(parsed) = reqwest::Url::parse(url) {
|
||||
if let Some(callback) = parsed
|
||||
.query_pairs()
|
||||
.find(|(key, _)| key == "callback_url")
|
||||
.map(|(_, value)| value.into_owned())
|
||||
{
|
||||
tokio::spawn(async move {
|
||||
// a page guessing the fixed path first must not end the sign-in
|
||||
let mut guessed = reqwest::Url::parse(&callback).unwrap();
|
||||
guessed.set_path("/openrouter/callback");
|
||||
guessed.set_query(Some("error=forged"));
|
||||
let forged = reqwest::get(guessed).await.unwrap();
|
||||
assert_eq!(forged.status().as_u16(), 404, "only the issued path answers");
|
||||
let redirect = format!("{callback}?code=the-code");
|
||||
let _ = reqwest::get(&redirect).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
self.events.lock().unwrap().push(event);
|
||||
}
|
||||
}
|
||||
|
||||
// === GitHub Copilot: the login's question order ===
|
||||
|
||||
/// A scripted interaction that records the prompts it was asked, in order.
|
||||
struct PromptRecorder {
|
||||
answers: Mutex<Vec<String>>,
|
||||
asked: Arc<Mutex<Vec<luxe_core::auth::AuthPrompt>>>,
|
||||
}
|
||||
|
||||
impl PromptRecorder {
|
||||
fn new(answers: &[&str]) -> (Self, Arc<Mutex<Vec<luxe_core::auth::AuthPrompt>>>) {
|
||||
let asked = Arc::new(Mutex::new(Vec::new()));
|
||||
let recorder = Self {
|
||||
answers: Mutex::new(answers.iter().rev().map(|a| a.to_string()).collect()),
|
||||
asked: asked.clone(),
|
||||
};
|
||||
(recorder, asked)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl luxe_core::auth::AuthInteraction for PromptRecorder {
|
||||
async fn prompt(
|
||||
&self,
|
||||
prompt: luxe_core::auth::AuthPrompt,
|
||||
) -> Result<secrecy::SecretString, luxe_core::auth::AuthError> {
|
||||
self.asked.lock().unwrap().push(prompt);
|
||||
match self.answers.lock().unwrap().pop() {
|
||||
Some(answer) => Ok(secrecy::SecretString::from(answer)),
|
||||
// Out of scripted answers: stop the flow before it reaches the network.
|
||||
None => Err(luxe_core::auth::AuthError::Cancelled),
|
||||
}
|
||||
}
|
||||
|
||||
fn notify(&self, _event: luxe_core::auth::AuthEvent) {}
|
||||
}
|
||||
|
||||
/// Picking "GitHub" must not ask for a domain — that question only exists for Enterprise.
|
||||
#[tokio::test]
|
||||
async fn copilot_asks_which_github_before_anything_else() {
|
||||
let (recorder, asked) = PromptRecorder::new(&["github"]);
|
||||
let domain = github_copilot::choose_domain(&recorder).await.expect("resolves");
|
||||
assert_eq!(domain, None, "github.com is the default, expressed as no enterprise domain");
|
||||
|
||||
let asked = asked.lock().unwrap();
|
||||
assert_eq!(asked.len(), 1, "github.com needs exactly one question: {asked:?}");
|
||||
match &asked[0].kind {
|
||||
luxe_core::auth::AuthPromptKind::Select(choices) => {
|
||||
let ids: Vec<&str> = choices.iter().map(|choice| choice.id.as_str()).collect();
|
||||
assert_eq!(ids, vec!["github", "enterprise"], "GitHub leads as the default");
|
||||
}
|
||||
other => panic!("expected a choice, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Picking Enterprise asks for the domain, and only then.
|
||||
#[tokio::test]
|
||||
async fn copilot_asks_for_a_domain_only_when_enterprise_is_chosen() {
|
||||
let (recorder, asked) = PromptRecorder::new(&["enterprise", "company.ghe.com"]);
|
||||
let domain = github_copilot::choose_domain(&recorder).await.expect("resolves");
|
||||
assert_eq!(domain.as_deref(), Some("company.ghe.com"));
|
||||
|
||||
let asked = asked.lock().unwrap();
|
||||
assert_eq!(asked.len(), 2, "{asked:?}");
|
||||
assert!(asked[1].message.contains("domain"), "{:?}", asked[1]);
|
||||
assert!(
|
||||
!asked[1].allow_empty,
|
||||
"having chosen Enterprise, an empty domain is a mistake rather than a default"
|
||||
);
|
||||
}
|
||||
|
||||
/// An Enterprise choice with an unusable domain fails with a reason instead of silently using
|
||||
/// github.com — which would send the credential to the wrong host.
|
||||
#[tokio::test]
|
||||
async fn copilot_refuses_an_unusable_enterprise_domain() {
|
||||
let (recorder, _asked) = PromptRecorder::new(&["enterprise", "not a domain"]);
|
||||
let error = github_copilot::choose_domain(&recorder).await.expect_err("must refuse");
|
||||
assert!(matches!(error, luxe_core::auth::AuthError::Input(_)), "got {error:?}");
|
||||
}
|
||||
|
||||
/// The whole device flow over a socket: issue a code, poll once as pending, then authorize and
|
||||
/// exchange. This is the path a user walks, minus GitHub.
|
||||
#[tokio::test]
|
||||
async fn copilot_device_flow_runs_end_to_end() {
|
||||
let expires_at = (luxe_providers::auth::credential::now_ms() / 1000) + 1800;
|
||||
let token_body = serde_json::json!({
|
||||
"token": "tid=abc;proxy-ep=proxy.individual.githubcopilot.com",
|
||||
"expires_at": expires_at,
|
||||
})
|
||||
.to_string();
|
||||
let server = MockServer::start(replies(&[
|
||||
(
|
||||
"/login/device/code",
|
||||
&[(
|
||||
200,
|
||||
r#"{"device_code":"dev-1","user_code":"WXYZ-9876",
|
||||
"verification_uri":"https://github.com/login/device",
|
||||
"interval":1,"expires_in":900}"#,
|
||||
)],
|
||||
),
|
||||
(
|
||||
"/login/oauth/access_token",
|
||||
&[
|
||||
// GitHub answers a not-yet-authorized poll with HTTP 200 and an error field.
|
||||
(200, r#"{"error":"authorization_pending"}"#),
|
||||
(200, r#"{"access_token":"gho_authorized"}"#),
|
||||
],
|
||||
),
|
||||
("/copilot_internal/v2/token", &[(200, token_body.as_str())]),
|
||||
]))
|
||||
.await;
|
||||
let endpoints = github_copilot::Endpoints {
|
||||
device_code: server.url("/login/device/code"),
|
||||
access_token: server.url("/login/oauth/access_token"),
|
||||
copilot_token: server.url("/copilot_internal/v2/token"),
|
||||
};
|
||||
|
||||
let recorder = EventRecorder::default();
|
||||
let credential =
|
||||
github_copilot::run_device_flow(&endpoints, None, &recorder).await.expect("completes");
|
||||
|
||||
assert_eq!(credential.refresh.expose(), "gho_authorized");
|
||||
assert_eq!(credential.endpoint.as_deref(), Some("https://api.individual.githubcopilot.com"));
|
||||
// The user has to be shown the code and where to type it.
|
||||
let codes: Vec<String> = recorder
|
||||
.events
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
luxe_core::auth::AuthEvent::DeviceCode { user_code, .. } => Some(user_code.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(codes, vec!["WXYZ-9876".to_string()]);
|
||||
// And the pending poll must not have aborted the flow.
|
||||
assert!(
|
||||
server.requests().iter().filter(|r| r.path == "/login/oauth/access_token").count() >= 2,
|
||||
"the poller should have retried after `authorization_pending`"
|
||||
);
|
||||
}
|
||||
|
||||
/// Records events; answers no prompts (this flow asks none once the domain is settled).
|
||||
#[derive(Default)]
|
||||
struct EventRecorder {
|
||||
events: Mutex<Vec<luxe_core::auth::AuthEvent>>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl luxe_core::auth::AuthInteraction for EventRecorder {
|
||||
async fn prompt(
|
||||
&self,
|
||||
_prompt: luxe_core::auth::AuthPrompt,
|
||||
) -> Result<secrecy::SecretString, luxe_core::auth::AuthError> {
|
||||
Err(luxe_core::auth::AuthError::Cancelled)
|
||||
}
|
||||
|
||||
fn notify(&self, event: luxe_core::auth::AuthEvent) {
|
||||
self.events.lock().unwrap().push(event);
|
||||
}
|
||||
}
|
||||
102
crates/luxe-providers/tests/request_headers.rs
Normal file
102
crates/luxe-providers/tests/request_headers.rs
Normal file
@@ -0,0 +1,102 @@
|
||||
//! Every adapter's request carries each header once.
|
||||
//!
|
||||
//! `json` sets `Content-Type` and `header` appends, so a request built by hand can send it twice,
|
||||
//! and a strict HTTP/1.1 server refuses that outright. One owner builds the request for all three
|
||||
//! adapters; these read the head off the wire to hold it.
|
||||
|
||||
use futures::StreamExt;
|
||||
use luxe_core::message::Message;
|
||||
use luxe_core::provider::{CompletionRequest, ModelInfo, ModelRef, Provider, ThinkingLevel};
|
||||
use luxe_providers::anthropic::{AnthropicCompat, AnthropicProvider};
|
||||
use luxe_providers::config::{CompatFlags, ProviderConfig};
|
||||
use luxe_providers::openai_compat::OpenaiCompatProvider;
|
||||
use luxe_providers::openai_responses::OpenaiResponsesProvider;
|
||||
use std::io::{Read, Write};
|
||||
|
||||
/// Answers one request with an empty event stream and hands back what the request looked like.
|
||||
fn serve_once() -> (u16, std::thread::JoinHandle<String>) {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
|
||||
let port = listener.local_addr().expect("addr").port();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (mut socket, _) = listener.accept().expect("accept");
|
||||
let mut raw = Vec::new();
|
||||
let mut chunk = [0u8; 4096];
|
||||
while !raw.windows(4).any(|window| window == b"\r\n\r\n") {
|
||||
let read = socket.read(&mut chunk).unwrap_or(0);
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
raw.extend_from_slice(&chunk[..read]);
|
||||
}
|
||||
let reply =
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n";
|
||||
let _ = socket.write_all(reply.as_bytes());
|
||||
String::from_utf8_lossy(&raw).to_string()
|
||||
});
|
||||
(port, server)
|
||||
}
|
||||
|
||||
fn request() -> CompletionRequest {
|
||||
CompletionRequest {
|
||||
model: ModelInfo {
|
||||
r#ref: ModelRef::new("test", "test-model"),
|
||||
max_tokens: 1024,
|
||||
context_window: 8192,
|
||||
..Default::default()
|
||||
},
|
||||
messages: vec![Message::user("hello")],
|
||||
thinking: ThinkingLevel::Off,
|
||||
max_tokens: Some(256),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// How many times the head names `header`, whatever its case.
|
||||
fn times(head: &str, header: &str) -> usize {
|
||||
let prefix = format!("{header}:");
|
||||
head.lines().filter(|line| line.to_ascii_lowercase().starts_with(&prefix)).count()
|
||||
}
|
||||
|
||||
async fn sent_by(provider: &dyn Provider, server: std::thread::JoinHandle<String>) -> String {
|
||||
let (_keep, cancel) = tokio::sync::watch::channel(false);
|
||||
let stream = provider.stream(request(), cancel).await.expect("the stream opens");
|
||||
let _: Vec<_> = stream.collect().await;
|
||||
server.join().expect("the server saw a request")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_chat_completions_request_has_one_content_type() {
|
||||
let (port, server) = serve_once();
|
||||
let provider = OpenaiCompatProvider::new(
|
||||
ProviderConfig { api_key: Some("sk-test".into()), ..Default::default() },
|
||||
CompatFlags::default(),
|
||||
)
|
||||
.with_base_url(format!("http://127.0.0.1:{port}/v1"));
|
||||
let head = sent_by(&provider, server).await;
|
||||
assert_eq!(times(&head, "content-type"), 1, "{head}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_responses_request_has_one_content_type() {
|
||||
let (port, server) = serve_once();
|
||||
let provider = OpenaiResponsesProvider::new(ProviderConfig {
|
||||
api_key: Some("sk-test".into()),
|
||||
base_url: Some(format!("http://127.0.0.1:{port}/v1")),
|
||||
..Default::default()
|
||||
});
|
||||
let head = sent_by(&provider, server).await;
|
||||
assert_eq!(times(&head, "content-type"), 1, "{head}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_messages_request_has_one_content_type() {
|
||||
let (port, server) = serve_once();
|
||||
let provider = AnthropicProvider::new(
|
||||
"sk-test".into(),
|
||||
Some(format!("http://127.0.0.1:{port}/v1")),
|
||||
request().model,
|
||||
AnthropicCompat::default(),
|
||||
);
|
||||
let head = sent_by(&provider, server).await;
|
||||
assert_eq!(times(&head, "content-type"), 1, "{head}");
|
||||
}
|
||||
Reference in New Issue
Block a user