Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
uchud(agent): remove stinky error type, add / consolidate lots of tests (#4406)
Eric Hayes73978bd2e0fc
diff --git a/rust/cloud-storage/agent/src/accumulator.rs b/rust/cloud-storage/agent/src/accumulator.rsindex 467c8257a1..8c9ee7780b 100644--- a/rust/cloud-storage/agent/src/accumulator.rs+++ b/rust/cloud-storage/agent/src/accumulator.rs@@ -1,7 +1,3 @@-#[cfg(test)]-mod test;--/// Accumulation of streamed agent parts into a persistable message.use crate::convert::merge_consecutive_parts;use crate::stream::{StreamPart, ToolResponse};use crate::types::AssistantMessagePart;diff --git a/rust/cloud-storage/agent/src/agent_loop.rs b/rust/cloud-storage/agent/src/agent_loop.rsindex 94538d2a9b..b46eddfd30 100644--- a/rust/cloud-storage/agent/src/agent_loop.rs+++ b/rust/cloud-storage/agent/src/agent_loop.rs@@ -1,7 +1,4 @@/// The main entry point: [`AgentLoop`] and [`Session`].-#[cfg(test)]-mod test;-use crate::error::AgentError;use crate::hook::{RegisterFn, ToolRouter};use crate::model::PredefinedModel;diff --git a/rust/cloud-storage/agent/src/convert.rs b/rust/cloud-storage/agent/src/convert.rsindex d07c90975f..a81d3c6094 100644--- a/rust/cloud-storage/agent/src/convert.rs+++ b/rust/cloud-storage/agent/src/convert.rs@@ -1,6 +1,3 @@-#[cfg(test)]-mod test;-/// Conversions between agent message types and `rig` message types.use crate::types::{AssistantMessagePart, ChatMessage, ChatMessageContent, Role};use attachment::image::ImageData;diff --git a/rust/cloud-storage/agent/src/error.rs b/rust/cloud-storage/agent/src/error.rsindex 2fc4d3f03c..7215d1f826 100644--- a/rust/cloud-storage/agent/src/error.rs+++ b/rust/cloud-storage/agent/src/error.rs@@ -1,25 +1,6 @@use rig_core::agent::StreamingError;use rig_core::completion::{CompletionError, PromptError};-#[cfg(test)]-mod test;--/// How a failed agent turn should be surfaced to the user.-///-/// Lets callers (e.g. the chat stream endpoint) turn an opaque [`AgentError`]-/// into a well-typed, user-facing error without re-implementing the rig error-/// archaeology below.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum FailureKind {- /// The model provider returned an error or was unreachable — most likely a- /// provider outage. The user should try a different model / provider.- ProviderOutage,- /// The request exceeded the model's context window.- ContextOverflow,- /// Anything else (serialization, our own bug, etc.).- Internal,-}-/// Errors produced by the agent crate.#[derive(Debug, thiserror::Error)]pub enum AgentError {@@ -72,32 +53,14 @@ impl AgentError {}}- /// Classify this error for user-facing reporting.- ///- /// rig collapses provider HTTP failures into- /// [`CompletionError::ProviderError`] / [`CompletionError::ResponseError`]- /// (the HTTP status code is not preserved), so we inspect the innermost- /// completion error: a context-window message maps to- /// [`FailureKind::ContextOverflow`]; any other provider or transport- /// failure maps to [`FailureKind::ProviderOutage`]; everything else is- /// [`FailureKind::Internal`].- pub fn failure_kind(&self) -> FailureKind {- match self.completion_error() {- Some(CompletionError::ProviderError(msg) | CompletionError::ResponseError(msg)) => {- if is_context_overflow(msg) {- FailureKind::ContextOverflow- } else {- FailureKind::ProviderOutage- }- }- // Connection error / timeout — we couldn't reach the provider.- Some(CompletionError::HttpError(_)) => FailureKind::ProviderOutage,- _ => FailureKind::Internal,- }- }-/// The innermost rig [`CompletionError`], if this error wraps one.- fn completion_error(&self) -> Option<&CompletionError> {+ ///+ /// rig nests the underlying completion error a few different ways depending+ /// on where it surfaced (direct, prompt, or streamed); this unwraps all of+ /// them so callers can inspect the provider failure without re-implementing+ /// that archaeology. Returns `None` for errors that don't originate from a+ /// completion call (unknown model, env var, our own serialization, etc.).+ pub fn completion_error(&self) -> Option<&CompletionError> {match self {AgentError::Completion(e) => Some(e),AgentError::Prompt(e) => prompt_completion_error(e),@@ -115,14 +78,3 @@ fn prompt_completion_error(e: &PromptError) -> Option<&CompletionError> {_ => None,}}--/// Whether a provider error message describes a context-window overflow rather-/// than an outage. Anthropic returns "prompt is too long"; OpenAI returns-/// "context_length_exceeded" / "maximum context length".-fn is_context_overflow(msg: &str) -> bool {- let m = msg.to_ascii_lowercase();- m.contains("context length")- || m.contains("context_length")- || m.contains("maximum context")- || m.contains("prompt is too long")-}diff --git a/rust/cloud-storage/agent/src/error/test.rs b/rust/cloud-storage/agent/src/error/test.rsdeleted file mode 100644index 6ea99576b0..0000000000--- a/rust/cloud-storage/agent/src/error/test.rs+++ /dev/null@@ -1,98 +0,0 @@-use super::*;-use rig_core::agent::StreamingError;-use rig_core::completion::{CompletionError, PromptError};--fn prompt_cancelled() -> PromptError {- PromptError::PromptCancelled {- chat_history: Vec::new(),- reason: "user cancelled".to_string(),- }-}--#[test]-fn streaming_wrapped_cancellation_is_detected() {- // The agent loop streams its errors, so a user cancellation reaches callers- // wrapped as `Streaming(Prompt(PromptCancelled { .. }))` — not the bare- // `Prompt` variant. This is the shape DCS actually sees.- let err = AgentError::Streaming(StreamingError::Prompt(Box::new(prompt_cancelled())));- assert!(err.was_cancelled());-}--#[test]-fn direct_prompt_cancellation_is_detected() {- let err = AgentError::Prompt(prompt_cancelled());- assert!(err.was_cancelled());-}--#[test]-fn non_cancellation_streaming_error_is_not_cancelled() {- let err = AgentError::Streaming(StreamingError::Completion(CompletionError::ProviderError(- "boom".to_string(),- )));- assert!(!err.was_cancelled());-}--#[test]-fn unrelated_error_is_not_cancelled() {- let err = AgentError::UnknownModel("foo/bar".to_string());- assert!(!err.was_cancelled());-}--#[test]-fn anthropic_500_body_is_provider_outage() {- // What rig hands us for a 5xx: the raw provider body wrapped in ProviderError.- let err = AgentError::Completion(CompletionError::ProviderError(- r#"{"type":"error","error":{"type":"api_error","message":"Internal server error"}}"#- .to_string(),- ));- assert_eq!(err.failure_kind(), FailureKind::ProviderOutage);-}--#[test]-fn overloaded_is_provider_outage() {- let err = AgentError::Completion(CompletionError::ProviderError(- r#"{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}"#- .to_string(),- ));- assert_eq!(err.failure_kind(), FailureKind::ProviderOutage);-}--#[test]-fn anthropic_prompt_too_long_is_context_overflow() {- let err = AgentError::Completion(CompletionError::ProviderError(- "prompt is too long: 250000 tokens > 200000 maximum".to_string(),- ));- assert_eq!(err.failure_kind(), FailureKind::ContextOverflow);-}--#[test]-fn openai_context_length_is_context_overflow() {- let err = AgentError::Completion(CompletionError::ProviderError(- "context_length_exceeded: maximum context length exceeded".to_string(),- ));- assert_eq!(err.failure_kind(), FailureKind::ContextOverflow);-}--#[test]-fn provider_error_through_streaming_prompt_is_classified() {- // The real chat path surfaces errors as Streaming(Prompt(CompletionError)).- let err = AgentError::Streaming(StreamingError::Prompt(Box::new(- PromptError::CompletionError(CompletionError::ProviderError(- "Service Unavailable".to_string(),- )),- )));- assert_eq!(err.failure_kind(), FailureKind::ProviderOutage);-}--#[test]-fn json_error_is_internal() {- let json_err = serde_json::from_str::<serde_json::Value>("not json").unwrap_err();- let err = AgentError::Json(json_err);- assert_eq!(err.failure_kind(), FailureKind::Internal);-}--#[test]-fn unknown_model_is_internal() {- let err = AgentError::UnknownModel("bogus".to_string());- assert_eq!(err.failure_kind(), FailureKind::Internal);-}diff --git a/rust/cloud-storage/agent/src/hook.rs b/rust/cloud-storage/agent/src/hook.rsindex e78f182e7d..e5dc797991 100644--- a/rust/cloud-storage/agent/src/hook.rs+++ b/rust/cloud-storage/agent/src/hook.rs@@ -1,8 +1,5 @@/// A [`rig_core::agent::PromptHook`] that bridges RIG lifecycle events into/// [`StreamPart`] items sent through a channel.-#[cfg(test)]-mod test;-use crate::AgentError;use crate::stream::{McpInfo, StreamPart, ToolCall, ToolResponse, Usage};use ai_toolset::{SearchableTool, ToolInfo};diff --git a/rust/cloud-storage/agent/src/lib.rs b/rust/cloud-storage/agent/src/lib.rsindex 6edac857b5..fd598f2a97 100644--- a/rust/cloud-storage/agent/src/lib.rs+++ b/rust/cloud-storage/agent/src/lib.rs@@ -13,16 +13,20 @@ mod stream;/// Structured output via prompted JSON generation.pub mod structured_output;mod tool_adapter;++#[cfg(test)]+mod test;pub mod types;pub use accumulator::StreamAccumulator;pub use agent_loop::{AgentLoop, Session};pub use completion::{complete, complete_with_history};pub use convert::{merge_consecutive_parts, to_rig_messages};-pub use error::{AgentError, FailureKind};+pub use error::AgentError;pub use model::PredefinedModel;pub use stream::{ChatCompletionStream, McpInfo, StreamPart, ToolCall, ToolResponse, Usage};pub use tool_adapter::{DynToolSetAdapter, ToolsetToolAdapter, normalize_request_schema};+pub use rig_core::completion::CompletionError;pub use rig_core::message::Message;pub use rig_core::tool::{Tool, ToolDyn};diff --git a/rust/cloud-storage/agent/src/model/mod.rs b/rust/cloud-storage/agent/src/model/mod.rsindex b1f3e7f45d..519d2b5404 100644--- a/rust/cloud-storage/agent/src/model/mod.rs+++ b/rust/cloud-storage/agent/src/model/mod.rs@@ -2,11 +2,8 @@//! AgentModel exists to help the backend use AI//! Model routing takes a string and returns the appropriate clientmod predefined_model;-mod types;+pub(crate) mod types;pub use predefined_model::*;mod anthropic;mod openai;pub mod router;--#[cfg(test)]-mod test;diff --git a/rust/cloud-storage/agent/src/model/predefined_model.rs b/rust/cloud-storage/agent/src/model/predefined_model.rsindex 3a47cc95c2..2d302ebeb2 100644--- a/rust/cloud-storage/agent/src/model/predefined_model.rs+++ b/rust/cloud-storage/agent/src/model/predefined_model.rs@@ -1,3 +1,6 @@+//! Some predefined models backend convenience+//! Models are _not_ strictly verified. This is intentional so that we+//! can route to any <provider>/<model-id>use crate::model::types::Model;use rig_core::providers::anthropic::completion::{CLAUDE_HAIKU_4_5, CLAUDE_OPUS_4_7, CLAUDE_OPUS_4_8, CLAUDE_SONNET_4_6,@@ -63,18 +66,6 @@ impl From<PredefinedModel> for super::types::Model<'static> {}impl PredefinedModel {- /// Returns the provider API model identifier.- pub fn api_id(&self) -> &'static str {- match self {- Self::Smart | Self::Retired => CLAUDE_OPUS_4_8,- Self::Opus4_7 => CLAUDE_OPUS_4_7,- Self::Sonnet4_6 => CLAUDE_SONNET_4_6,- Self::Fast | Self::Haiku4_5 => CLAUDE_HAIKU_4_5,- Self::Gpt5_5 => GPT_5_5,- Self::Gpt5Mini => GPT_5_MINI,- }- }-/// Returns `additional_params` JSON to enable extended thinking / reasoning.////// - Opus 4.8 / 4.7: `adaptive` (model chooses when to think)diff --git a/rust/cloud-storage/agent/src/model/router.rs b/rust/cloud-storage/agent/src/model/router.rsindex a7a8c1cab5..dd0106e761 100644--- a/rust/cloud-storage/agent/src/model/router.rs+++ b/rust/cloud-storage/agent/src/model/router.rs@@ -366,7 +366,7 @@ impl ModelRouter {fn default_model(&self) -> RoutedModel<'static> {let model = Model {provider: Cow::Borrowed(ANTHROPIC_PROVIDER),- name: Cow::Borrowed(PredefinedModel::default().api_id()),+ name: Cow::Owned(PredefinedModel::default().to_string()),};RoutedModel::Anthropic(AnthropicModel::new(model, self.anthropic.clone()))}@@ -589,46 +589,3 @@ impl ProviderAgent {)))}}--#[cfg(test)]-mod test {- use super::*;-- fn test_router() -> ModelRouter {- let anthropic = anthropic::Client::builder()- .api_key("test-anthropic-key")- .build()- .unwrap();- let openai = openai::Client::builder()- .api_key("test-openai-key")- .build()- .unwrap();- let compatible = openai::CompletionsClient::builder()- .api_key("test-compatible-key")- .base_url("http://localhost:11434/v1")- .build()- .unwrap();-- ModelRouter::new(anthropic, openai).with_openai_client("local", compatible)- }-- #[test]- fn openai_provider_routes_to_responses() {- let router = test_router();-- assert!(matches!(- router.route("openai/gpt-5.5").unwrap(),- RoutedModel::OpenAiResponses(_)- ));- }-- #[test]- fn registered_openai_compatible_provider_routes_to_chat_completions() {- let router = test_router();-- assert!(matches!(- router.route("local/llama-3.3-70b").unwrap(),- RoutedModel::OpenAiChatCompletions(_)- ));- }-}diff --git a/rust/cloud-storage/agent/src/model/test.rs b/rust/cloud-storage/agent/src/model/test.rsdeleted file mode 100644index 561d8bc1c4..0000000000--- a/rust/cloud-storage/agent/src/model/test.rs+++ /dev/null@@ -1,49 +0,0 @@-use super::*;--#[test]-fn default_is_smart() {- assert_eq!(PredefinedModel::default(), PredefinedModel::Smart);-}--#[test]-fn smart_is_opus_4_8() {- assert_eq!(PredefinedModel::Smart.api_id(), "claude-opus-4-8");- assert_eq!(- serde_json::to_string(&PredefinedModel::Smart).unwrap(),- r#""claude-opus-4-8""#- );-}--#[test]-fn fast_is_haiku() {- assert_eq!(PredefinedModel::Fast.api_id(), "claude-haiku-4-5");- assert_eq!(- PredefinedModel::Fast.api_id(),- PredefinedModel::Haiku4_5.api_id()- );-}--#[test]-fn retired_uses_default_api_id() {- assert_eq!(- PredefinedModel::Retired.api_id(),- PredefinedModel::Smart.api_id()- );-}--#[test]-fn variants_serialize_to_their_api_id() {- for m in [- PredefinedModel::Smart,- PredefinedModel::Fast,- PredefinedModel::Opus4_7,- PredefinedModel::Sonnet4_6,- PredefinedModel::Haiku4_5,- PredefinedModel::Gpt5_5,- PredefinedModel::Gpt5Mini,- PredefinedModel::Retired,- ] {- let wire = serde_json::to_string(&m).unwrap();- assert_eq!(wire, format!(r#""{}""#, m.api_id()), "{m:?}");- }-}diff --git a/rust/cloud-storage/agent/src/model/types.rs b/rust/cloud-storage/agent/src/model/types.rsindex f3d0360ea4..333a78aec3 100644--- a/rust/cloud-storage/agent/src/model/types.rs+++ b/rust/cloud-storage/agent/src/model/types.rs@@ -37,16 +37,3 @@ impl<'a> std::fmt::Display for Model<'a> {write!(f, "{}/{}", self.provider, self.name)}}--#[cfg(test)]-mod test {- #[test]- fn test_from_string() {- let good = super::Model::try_from("anthropic/claude-big-burger").expect("good model");- assert_eq!(good.name(), "claude-big-burger");- assert_eq!(good.provider(), "anthropic");-- let bad = "claude-big-burger";- assert!(super::Model::try_from(bad).is_err());- }-}diff --git a/rust/cloud-storage/agent/src/test/agent_loop/mod.rs b/rust/cloud-storage/agent/src/test/agent_loop/mod.rsnew file mode 100644index 0000000000..4f96400aa9--- /dev/null+++ b/rust/cloud-storage/agent/src/test/agent_loop/mod.rs@@ -0,0 +1,10 @@+//! Behavior tests for the agent loop, grouped by guarantee.+//!+//! Shared setup lives in [`util`]; each `test_*` module asserts one family of+//! guarantees against the public session surface.++mod util;++mod test_cooperative_cancellation;+mod test_eager_tools;+mod test_tool;diff --git a/rust/cloud-storage/agent/src/agent_loop/test.rs b/rust/cloud-storage/agent/src/test/agent_loop/test_cooperative_cancellation.rssimilarity index 51%rename from rust/cloud-storage/agent/src/agent_loop/test.rsrename to rust/cloud-storage/agent/src/test/agent_loop/test_cooperative_cancellation.rsindex 08673ffbd0..bd9de01d83 100644--- a/rust/cloud-storage/agent/src/agent_loop/test.rs+++ b/rust/cloud-storage/agent/src/test/agent_loop/test_cooperative_cancellation.rs@@ -1,42 +1,22 @@-//! Agent loop behavior tests.+//! Cooperative cancellation.//!-//! These drive the public session surface used by DCS — [`AgentLoop`] →-//! [`super::Session::cancellable`] → [`super::Session::send_message`] — with a-//! fake completion model injected via [`AgentLoop::test_session`], so the real-//! per-session wiring (tool adapters, cancellation token) is exercised.--use crate::AgentLoop;-use crate::stream::{StreamPart, ToolResponse};-use ai_toolset::{- AsyncTool, AsyncToolCollection, RequestContext, ServiceContext, ToolResult,- ToolSet as AiToolSet,-};-use ai_usage::{AiFeature, UsageContext, UsageEvent, UsageRecorder};-use futures::StreamExt;-use macro_user_id::user_id::MacroUserIdStr;-use rig_core::message::Message;+//! A long-running tool reads the cancellation token off its [`RequestContext`]+//! and returns a normal value when the request is cancelled. Cancelling such a+//! tool mid-flight must surface its cooperative result as a tool response and+//! let the loop finish *cleanly* — no terminal error. This is distinct from the+//! abrupt path in `test_cancellation_resolution`, where the loop itself tears+//! down with a cancellation error.++use super::util;+use crate::stream::ToolResponse;+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolResult};+use async_trait::async_trait;use rig_core::test_utils::{MockCompletionModel, MockStreamEvent};use schemars::JsonSchema;use serde::Deserialize;use std::sync::Arc;use tokio::sync::Notify;-/// Records nothing — token usage isn't under test here.-struct NoOpRecorder;-impl UsageRecorder for NoOpRecorder {- fn record(&self, _event: UsageEvent) {}-}--fn test_loop() -> AgentLoop {- AgentLoop::new(Arc::new(NoOpRecorder))- .with_max_turns(8)- .with_max_tokens(1024)-}--fn test_user() -> MacroUserIdStr<'static> {- MacroUserIdStr::try_from_email("[email protected]").expect("valid user id")-}-/// Shared service state handed to the tool. `started` lets the tool announce/// that it has begun executing so the test can cancel only *after* the/// `on_tool_call` guard has passed — otherwise the agent loop would terminate@@ -57,7 +37,7 @@ struct TestCtx {)]struct InfiniteTool {}-#[async_trait::async_trait]+#[async_trait]impl AsyncTool<TestCtx> for InfiniteTool {type Output = serde_json::Value;@@ -79,10 +59,9 @@ impl AsyncTool<TestCtx> for InfiniteTool {}}-/// A fake AI stream that calls an infinite tool exercises cooperative-/// cancellation: cancelling the session while the tool is running makes the-/// tool return (via `request_context.cancel`), and that return surfaces as a-/// tool response in the message stream.+/// Cancelling the session while an infinite tool is running makes the tool+/// return (via `request_context.cancel`), and that return surfaces as a tool+/// response in the message stream.#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn cancelling_running_tool_yields_a_tool_response() {// Turn 1: the model calls the infinite tool. Turn 2 (reached once the@@ -99,13 +78,9 @@ async fn cancelling_running_tool_yields_a_tool_response() {let context = Arc::new(TestCtx {started: started.clone(),});- let toolset: Arc<dyn AiToolSet<TestCtx> + Send + Sync> =- Arc::new(AsyncToolCollection::<TestCtx>::new().add_tool::<InfiniteTool, TestCtx>());+ let toolset = util::single_tool_set::<InfiniteTool, TestCtx>();- let usage_ctx = UsageContext::new(AiFeature::Chat, test_user());- let session = test_loop()- .test_session(toolset, context, "test preamble", usage_ctx, model)- .await;+ let session = util::session(toolset, context, model).await;let (mut session, cancel) = session.cancellable();// Cancel once the tool is actually executing.@@ -114,40 +89,35 @@ async fn cancelling_running_tool_yields_a_tool_response() {cancel.cancel();});- let mut stream = session- .send_message(vec![Message::user("run the infinite tool")])- .await- .expect("send_message should start the stream");-- let mut parts = Vec::new();- while let Some(item) = stream.next().await {- if let Ok(part) = item {- parts.push(part);- }- }+ let result = util::drive(&mut session, "run the infinite tool").await;// The tool call appears in the stream...- let tool_call_id = parts- .iter()- .find_map(|part| match part {- StreamPart::ToolCall(call) if call.name == "infinite_tool" => Some(call.id.clone()),- _ => None,- })+ let tool_call_id = result+ .tool_calls()+ .into_iter()+ .find(|call| call.name == "infinite_tool")+ .map(|call| call.id.clone()).expect("expected a tool call for infinite_tool");// ...and it has a response, produced by the tool returning cooperatively// when `request_context.cancel` fired.- let response = parts- .iter()- .find_map(|part| match part {- StreamPart::ToolResponse(ToolResponse::Json { id, json, .. })- if *id == tool_call_id =>- {- Some(json.clone())- }- _ => None,- })+ let response = result+ .tool_response(&tool_call_id).expect("expected a tool response for the infinite tool call");- assert_eq!(response, serde_json::json!({ "status": "cancelled" }));+ assert!(+ matches!(+ response,+ ToolResponse::Json { json, .. } if *json == serde_json::json!({ "status": "cancelled" })+ ),+ "cooperative cancellation should surface the tool's own result, got {response:?}"+ );++ // A tool that cancels cooperatively is a *normal* return: the loop runs the+ // next turn and finishes without a terminal error.+ assert!(+ result.error.is_none(),+ "cooperative cancellation must not tear the stream down with an error, got {:?}",+ result.error+ );}diff --git a/rust/cloud-storage/agent/src/test/agent_loop/test_eager_tools.rs b/rust/cloud-storage/agent/src/test/agent_loop/test_eager_tools.rsnew file mode 100644index 0000000000..af0e2b93b9--- /dev/null+++ b/rust/cloud-storage/agent/src/test/agent_loop/test_eager_tools.rs@@ -0,0 +1,240 @@+//! Tool calls should be yielded eagerly to the stream consumer+//! This means that we should get the call before the response+//! We should not get the call when the response finishes+//!+//! This is important for long running tools like rewrite and+//! subagent+//!++use super::util;+use crate::stream::{StreamPart, ToolResponse};+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolResult};+use async_trait::async_trait;+use rig_core::message::Message;+use rig_core::test_utils::{MockCompletionModel, MockStreamEvent};+use schemars::JsonSchema;+use serde::Deserialize;+use std::sync::Arc;+use std::time::Duration;+use tokio::sync::{Mutex, oneshot};++/// How long to wait for a part that *should* already be on its way before+/// concluding none is coming. Long enough to be reliable on a loaded CI box,+/// short enough that a genuinely-missing part fails the test quickly.+const GRACE: Duration = Duration::from_millis(500);++/// A tool that never returns.+#[derive(Deserialize, JsonSchema)]+#[schemars(title = "never_tool", description = "Never returns.")]+struct NeverTool {}++#[async_trait]+impl AsyncTool<()> for NeverTool {+ type Output = serde_json::Value;++ async fn call(+ &self,+ _service_context: ServiceContext<()>,+ _request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ std::future::pending::<()>().await;+ unreachable!("pending future never resolves")+ }+}++/// This tests against an "infinite" tool (tool that never returns)+/// It shows that the consumer gets a tool call and never a response+#[tokio::test]+async fn infinite_tool_yields_call_but_never_a_response() {+ let model = MockCompletionModel::from_stream_turns([vec![+ MockStreamEvent::tool_call("call-1", "never_tool", serde_json::json!({})),+ MockStreamEvent::final_response_with_default_usage(),+ ]]);++ let toolset = util::single_tool_set::<NeverTool, ()>();+ let mut session = util::session(toolset, Arc::new(()), model).await;+ let mut stream = session+ .send_message(vec![Message::user("run the infinite tool")])+ .await+ .expect("send_message should start the stream");++ let mut saw_call = false;+ let mut saw_response = false;+ // The tool never returns, so the stream never ends — `next_within` stops us+ // once the in-flight tool leaves the consumer with nothing more to read.+ while let Some(part) = util::next_within(&mut stream, GRACE).await {+ match part {+ StreamPart::ToolCall(call) if call.name == "never_tool" => saw_call = true,+ StreamPart::ToolResponse(_) => saw_response = true,+ _ => {}+ }+ }++ assert!(+ saw_call,+ "the consumer must receive the tool call eagerly — while the tool is still running"+ );+ assert!(+ !saw_response,+ "a tool that never returns must never produce a response"+ );+}++/// Shared state gating [`GatedTool`]: the test holds the sender and releases the+/// tool by sending on it. `Option` because the receiver is consumed on first+/// (and only) call.+#[derive(Clone)]+struct Gate {+ release: Arc<Mutex<Option<oneshot::Receiver<()>>>>,+}++/// A tool that blocks until the test releases it via the oneshot channel.+#[derive(Deserialize, JsonSchema)]+#[schemars(title = "gated_tool", description = "Returns only once released.")]+struct GatedTool {}++#[async_trait]+impl AsyncTool<Gate> for GatedTool {+ type Output = serde_json::Value;++ async fn call(+ &self,+ service_context: ServiceContext<Gate>,+ _request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ let rx = service_context+ .release+ .lock()+ .await+ .take()+ .expect("gated tool is called at most once");+ let _ = rx.await;+ Ok(serde_json::json!({ "status": "released" }))+ }+}++/// This tests against a tool that will not return until it is told to+/// via oneshot. It shows that we get the call 1st then the response after+/// oneshotting it.+#[tokio::test]+async fn gated_tool_yields_call_first_then_response_once_released() {+ let model = MockCompletionModel::from_stream_turns([+ vec![+ MockStreamEvent::tool_call("call-1", "gated_tool", serde_json::json!({})),+ MockStreamEvent::final_response_with_default_usage(),+ ],+ vec![MockStreamEvent::final_response_with_default_usage()],+ ]);++ let (release_tx, release_rx) = oneshot::channel();+ let context = Arc::new(Gate {+ release: Arc::new(Mutex::new(Some(release_rx))),+ });+ let toolset = util::single_tool_set::<GatedTool, Gate>();+ let mut session = util::session(toolset, context, model).await;+ let mut stream = session+ .send_message(vec![Message::user("run the gated tool")])+ .await+ .expect("send_message should start the stream");++ // The call must arrive while the tool is still gated — before we release it.+ let mut call_id = None;+ while let Some(part) = util::next_within(&mut stream, GRACE).await {+ match part {+ StreamPart::ToolCall(call) if call.name == "gated_tool" => {+ call_id = Some(call.id.clone());+ break;+ }+ StreamPart::ToolResponse(_) => {+ panic!("response must not arrive before the tool is released")+ }+ _ => {}+ }+ }+ let call_id = call_id.expect("tool call should be yielded before the tool returns");++ // Release the tool; only now should its response land.+ release_tx.send(()).expect("receiver still alive");++ let mut response = None;+ while let Some(part) = util::next_within(&mut stream, GRACE).await {+ if let StreamPart::ToolResponse(ToolResponse::Json { id, json, .. }) = &part {+ if *id == call_id {+ response = Some(json.clone());+ break;+ }+ }+ }+ assert_eq!(+ response.expect("the response should arrive after releasing the tool"),+ serde_json::json!({ "status": "released" })+ );+}++/// A tool that returns immediately.+#[derive(Deserialize, JsonSchema)]+#[schemars(title = "echo_tool", description = "Returns immediately.")]+struct EchoTool {+ value: String,+}++#[async_trait]+impl AsyncTool<()> for EchoTool {+ type Output = serde_json::Value;++ async fn call(+ &self,+ _service_context: ServiceContext<()>,+ _request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ Ok(serde_json::json!({ "echo": self.value }))+ }+}++/// This test shows that we get the call and response in quick succession+/// for a near-instant tool (like most of our tools)+#[tokio::test]+async fn instant_tool_yields_call_then_response_in_order() {+ let model = MockCompletionModel::from_stream_turns([+ vec![+ MockStreamEvent::tool_call("call-1", "echo_tool", serde_json::json!({ "value": "hi" })),+ MockStreamEvent::final_response_with_default_usage(),+ ],+ vec![MockStreamEvent::final_response_with_default_usage()],+ ]);++ let toolset = util::single_tool_set::<EchoTool, ()>();+ let mut session = util::session(toolset, Arc::new(()), model).await;+ let result = util::drive(&mut session, "run the echo tool").await;++ let call_pos = result+ .parts+ .iter()+ .position(|part| matches!(part, StreamPart::ToolCall(call) if call.name == "echo_tool"))+ .expect("expected a tool call for echo_tool");+ let response_pos = result+ .parts+ .iter()+ .position(|part| matches!(part, StreamPart::ToolResponse(_)))+ .expect("expected a tool response");+ assert!(+ call_pos < response_pos,+ "the call must be yielded before its response"+ );++ let call = result+ .tool_calls()+ .into_iter()+ .find(|call| call.name == "echo_tool")+ .expect("expected a tool call for echo_tool");+ let response = result+ .tool_response(&call.id)+ .expect("expected a response for the echo tool call");+ assert!(+ matches!(+ response,+ ToolResponse::Json { json, .. } if *json == serde_json::json!({ "echo": "hi" })+ ),+ "the tool's own output should surface as the response, got {response:?}"+ );+}diff --git a/rust/cloud-storage/agent/src/test/agent_loop/test_tool.rs b/rust/cloud-storage/agent/src/test/agent_loop/test_tool.rsnew file mode 100644index 0000000000..9141f07bf8--- /dev/null+++ b/rust/cloud-storage/agent/src/test/agent_loop/test_tool.rs@@ -0,0 +1,255 @@+//! this tests how the agent loop handles tools+//! it aims to cover all cases of tool success and failure+use super::util;+use crate::stream::ToolResponse;+use ai_toolset::{+ AsyncTool, AsyncToolCollection, RequestContext, ServiceContext, ToolCallError, ToolResult,+};+use async_trait::async_trait;+use rig_core::test_utils::{MockCompletionModel, MockStreamEvent};+use schemars::JsonSchema;+use serde::Deserialize;+use std::sync::Arc;++/// A tool that echoes its input. Deserialization fails when `value` is absent.+#[derive(Deserialize, JsonSchema)]+#[schemars(title = "echo_tool", description = "Echoes its input back.")]+struct EchoTool {+ value: String,+}++#[async_trait]+impl AsyncTool<()> for EchoTool {+ type Output = serde_json::Value;++ async fn call(+ &self,+ _service_context: ServiceContext<()>,+ _request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ Ok(serde_json::json!({ "echo": self.value }))+ }+}++/// A tool that always fails with a [`ToolCallError`].+#[derive(Deserialize, JsonSchema)]+#[schemars(title = "boom_tool", description = "Always fails.")]+struct BoomTool {}++#[async_trait]+impl AsyncTool<()> for BoomTool {+ type Output = serde_json::Value;++ async fn call(+ &self,+ _service_context: ServiceContext<()>,+ _request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ Err(ToolCallError {+ description: "boom failed".to_string(),+ internal_error: anyhow::anyhow!("boom"),+ })+ }+}++/// A two-turn script: `tool_turn` does the tool calls, then a final turn writes+/// "done" so we can observe that the loop kept going.+fn tool_then_done(tool_turn: impl IntoIterator<Item = MockStreamEvent>) -> MockCompletionModel {+ MockCompletionModel::from_stream_turns([+ tool_turn+ .into_iter()+ .chain([MockStreamEvent::final_response_with_default_usage()])+ .collect::<Vec<_>>(),+ vec![+ MockStreamEvent::text("done"),+ MockStreamEvent::final_response_with_default_usage(),+ ],+ ])+}++/// Tool call error+/// it should not stop the loop. It should output the call and response of the tool. These should be the strongly typed events+/// yielded to the consumer+#[tokio::test]+async fn tool_call_error_emits_call_and_error_response() {+ let model = tool_then_done([MockStreamEvent::tool_call(+ "call-1",+ "boom_tool",+ serde_json::json!({}),+ )]);+ let toolset = util::single_tool_set::<BoomTool, ()>();+ let mut session = util::session(toolset, Arc::new(()), model).await;++ let result = util::drive(&mut session, "call the failing tool").await;++ let call = result+ .tool_calls()+ .into_iter()+ .find(|call| call.name == "boom_tool")+ .expect("the failing tool's call should be emitted");+ let response = result+ .tool_response(&call.id)+ .expect("the failing tool's response should be emitted");+ assert!(+ matches!(response, ToolResponse::Err { description, .. } if description.contains("boom failed")),+ "a tool error should surface as a typed error response, got {response:?}"+ );+ assert!(+ result.error.is_none(),+ "a tool error must not stop the loop, got {:?}",+ result.error+ );+ assert_eq!(result.content(), "done", "the loop should continue");+}++/// Parallel tool call success+/// Multiple tool calls are executed in one turn. They all succeed. The call/response eventsa re all emitted+#[tokio::test]+async fn parallel_success_emits_all_calls_and_responses() {+ let model = tool_then_done([+ MockStreamEvent::tool_call("call-1", "echo_tool", serde_json::json!({ "value": "a" })),+ MockStreamEvent::tool_call("call-2", "echo_tool", serde_json::json!({ "value": "b" })),+ ]);+ let toolset = util::single_tool_set::<EchoTool, ()>();+ let mut session = util::session(toolset, Arc::new(()), model).await;++ let result = util::drive(&mut session, "call echo twice").await;++ assert_eq!(result.tool_calls().len(), 2, "both calls should be emitted");+ let echoed: Vec<serde_json::Value> = result+ .tool_responses()+ .into_iter()+ .filter_map(|response| match response {+ ToolResponse::Json { json, .. } => json.get("echo").cloned(),+ ToolResponse::Err { .. } => None,+ })+ .collect();+ assert_eq!(echoed, vec![serde_json::json!("a"), serde_json::json!("b")]);+ // Every call has a matching response.+ for call in result.tool_calls() {+ assert!(+ result.tool_response(&call.id).is_some(),+ "call {} should have a response",+ call.id+ );+ }+}++// TODO: add support for concurrent execution (unsupported by rig)+/// Long enough to let a slow tool finish so we observe full ordering, short+/// enough to keep the suite quick.+// const SLOW: u64 = 200;+// const MEDIUM: u64 = 100;+// const FAST: u64 = 10;+// /// a tool that sleeps `ms` before returning its `label`. used to observe+// /// execution concurrency by completion order.++// #[derive(Deserialize, JsonSchema)]+// #[schemars(title = "sleep_tool", description = "sleeps, then returns its label.")]+// struct SleepTool {+// ms: u64,+// label: String,+// }++// #[async_trait]+// impl AsyncTool<()> for SleepTool {+// type Output = serde_json::Value;++// async fn call(+// &self,+// _service_context: ServiceContext<()>,+// _request_context: RequestContext,+// ) -> ToolResult<Self::Output> {+// tokio::time::sleep(Duration::from_millis(self.ms)).await;+// Ok(serde_json::json!({ "label": self.label }))+// }+// }++// /// The `label` of a JSON tool response, for ordering assertions.+// fn response_label(response: &ToolResponse) -> Option<&str> {+// match response {+// ToolResponse::Json { json, .. } => json.get("label").and_then(|l| l.as_str()),+// ToolResponse::Err { .. } => None,+// }+// }+// /// Parallel tool call parallel execution+// /// three tools are called in one turn. The tools have different timings. They are executed in paralle as+// /// seen by the output which shows the fast tools yield before the slow tools regardless of order in the+// /// response+// #[tokio::test(flavor = "multi_thread", worker_threads = 4)]+// async fn parallel_tools_execute_concurrently() {+// // Response order is slow, medium, fast — but if they run concurrently the+// // responses should land fast, medium, slow (by completion time).+// let model = tool_then_done([+// MockStreamEvent::tool_call(+// "call-1",+// "sleep_tool",+// serde_json::json!({ "ms": SLOW, "label": "slow" }),+// ),+// MockStreamEvent::tool_call(+// "call-2",+// "sleep_tool",+// serde_json::json!({ "ms": MEDIUM, "label": "medium" }),+// ),+// MockStreamEvent::tool_call(+// "call-3",+// "sleep_tool",+// serde_json::json!({ "ms": FAST, "label": "fast" }),+// ),+// ]);+// let toolset = util::single_tool_set::<SleepTool, ()>();+// let mut session = util::session(toolset, Arc::new(()), model).await;++// let result = util::drive(&mut session, "call three timed tools").await;++// let order: Vec<&str> = result+// .tool_responses()+// .into_iter()+// .filter_map(response_label)+// .collect();+// assert_eq!(+// order,+// vec!["fast", "medium", "slow"],+// "tools should run concurrently, so responses land in completion order"+// );+// }++/// Parallel Tool call failure+/// If one call fails it emits the failure parts correctly and the other calls succeed+#[tokio::test]+async fn parallel_failure_isolated_from_successful_calls() {+ let model = tool_then_done([+ MockStreamEvent::tool_call("call-1", "boom_tool", serde_json::json!({})),+ MockStreamEvent::tool_call("call-2", "echo_tool", serde_json::json!({ "value": "ok" })),+ ]);+ let toolset = util::tool_set(+ AsyncToolCollection::<()>::new()+ .add_tool::<BoomTool, ()>()+ .add_tool::<EchoTool, ()>(),+ );+ let mut session = util::session(toolset, Arc::new(()), model).await;++ let result = util::drive(&mut session, "call a failing and a succeeding tool").await;++ let boom = result+ .tool_calls()+ .into_iter()+ .find(|call| call.name == "boom_tool")+ .and_then(|call| result.tool_response(&call.id))+ .expect("the failing call should have a response");+ assert!(+ matches!(boom, ToolResponse::Err { description, .. } if description.contains("boom failed")),+ "the failing call should surface a typed error, got {boom:?}"+ );++ let echo = result+ .tool_calls()+ .into_iter()+ .find(|call| call.name == "echo_tool")+ .and_then(|call| result.tool_response(&call.id))+ .expect("the succeeding call should have a response");+ assert!(+ matches!(echo, ToolResponse::Json { json, .. } if *json == serde_json::json!({ "echo": "ok" })),+ "the succeeding call should still return its output, got {echo:?}"+ );+}diff --git a/rust/cloud-storage/agent/src/test/agent_loop/util.rs b/rust/cloud-storage/agent/src/test/agent_loop/util.rsnew file mode 100644index 0000000000..1c6c476597--- /dev/null+++ b/rust/cloud-storage/agent/src/test/agent_loop/util.rs@@ -0,0 +1,178 @@+//! Shared boilerplate for the agent-loop behavior tests.+//!+//! Every test in this module drives the public session surface used by DCS —+//! [`AgentLoop`] → [`Session::cancellable`] → [`Session::send_message`] — with a+//! fake completion model injected via [`AgentLoop::test_session`]. That exercises+//! the real per-session wiring (tool adapters, cancellation token) without+//! talking to a provider. The helpers here remove the repeated setup so each+//! test reads as the behavior it asserts.++use crate::AgentLoop;+use crate::Session;+use crate::error::AgentError;+use crate::stream::{ChatCompletionStream, StreamPart, ToolCall, ToolResponse};+use ai_toolset::{AsyncTool, AsyncToolCollection, ToolSet as AiToolSet};+use ai_usage::{AiFeature, UsageContext, UsageEvent, UsageRecorder};+use futures::StreamExt;+use macro_user_id::user_id::MacroUserIdStr;+use rig_core::completion::{CompletionModel, GetTokenUsage};+use rig_core::message::Message;+use schemars::JsonSchema;+use serde::Serialize;+use std::sync::Arc;++/// A [`UsageRecorder`] that drops every event. Used when token accounting is not+/// what the test is checking.+pub(crate) struct NoOpRecorder;++impl UsageRecorder for NoOpRecorder {+ fn record(&self, _event: UsageEvent) {}+}++/// An [`AgentLoop`] with small turn/token budgets that drops usage events.+pub(crate) fn test_loop() -> AgentLoop {+ AgentLoop::new(Arc::new(NoOpRecorder))+ .with_max_turns(8)+ .with_max_tokens(1024)+}++/// A stable test user id.+pub(crate) fn test_user() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from_email("[email protected]").expect("valid user id")+}++/// The usage context every test session runs under.+pub(crate) fn usage_ctx() -> UsageContext {+ UsageContext::new(AiFeature::Chat, test_user())+}++/// A toolset holding a single tool `T` whose context is the whole service+/// context `C`.+pub(crate) fn single_tool_set<T, C>() -> Arc<dyn AiToolSet<C> + Send + Sync>+where+ C: Clone + Send + Sync + 'static,+ T: JsonSchema + AsyncTool<C> + for<'de> serde::Deserialize<'de> + Send + Sync + 'static,+ T::Output: Serialize + JsonSchema + 'static,+{+ Arc::new(AsyncToolCollection::<C>::new().add_tool::<T, C>())+}++/// Erase a built [`AsyncToolCollection`] into the toolset trait object a session+/// takes. For tests that need more than one tool type registered.+pub(crate) fn tool_set<C>(collection: AsyncToolCollection<C>) -> Arc<dyn AiToolSet<C> + Send + Sync>+where+ C: Clone + Send + Sync + 'static,+{+ Arc::new(collection)+}++/// Build a session on a default [`test_loop`] backed by the scripted `model`.+pub(crate) async fn session<C, M>(+ toolset: Arc<dyn AiToolSet<C> + Send + Sync>,+ context: Arc<C>,+ model: M,+) -> Session+where+ C: Clone + Send + Sync + 'static,+ M: CompletionModel + 'static,+ M::StreamingResponse: GetTokenUsage + Send + Sync,+{+ test_loop()+ .test_session(toolset, context, "test preamble", usage_ctx(), model)+ .await+}++/// Everything a session emitted: the ordered [`StreamPart`]s plus the terminal+/// error, if the stream ended with one. The agent loop breaks on the first+/// error, so `error` is at most one and always last.+pub(crate) struct Collected {+ /// Parts yielded before the stream ended.+ pub(crate) parts: Vec<StreamPart>,+ /// The terminal error, if the stream ended with one.+ pub(crate) error: Option<AgentError>,+}++impl Collected {+ /// Every tool call the assistant made.+ pub(crate) fn tool_calls(&self) -> Vec<&ToolCall> {+ self.parts+ .iter()+ .filter_map(|part| match part {+ StreamPart::ToolCall(call) => Some(call),+ _ => None,+ })+ .collect()+ }++ /// Every tool response produced.+ pub(crate) fn tool_responses(&self) -> Vec<&ToolResponse> {+ self.parts+ .iter()+ .filter_map(|part| match part {+ StreamPart::ToolResponse(response) => Some(response),+ _ => None,+ })+ .collect()+ }++ /// The tool response for a given call id, if any.+ pub(crate) fn tool_response(&self, call_id: &str) -> Option<&ToolResponse> {+ self.tool_responses()+ .into_iter()+ .find(|response| response_id(response) == call_id)+ }++ /// The concatenated assistant text content.+ pub(crate) fn content(&self) -> String {+ self.parts+ .iter()+ .filter_map(|part| match part {+ StreamPart::Content(text) => Some(text.as_str()),+ _ => None,+ })+ .collect()+ }+}++/// The call id a tool response corresponds to.+pub(crate) fn response_id(response: &ToolResponse) -> &str {+ match response {+ ToolResponse::Json { id, .. } | ToolResponse::Err { id, .. } => id,+ }+}++/// Drain a stream to completion, separating parts from the terminal error.+pub(crate) async fn collect(mut stream: ChatCompletionStream<'_>) -> Collected {+ let mut parts = Vec::new();+ let mut error = None;+ while let Some(item) = stream.next().await {+ match item {+ Ok(part) => parts.push(part),+ Err(err) => error = Some(err),+ }+ }+ Collected { parts, error }+}++/// Pull the next stream part, returning `None` if the stream ends, errors, or+/// produces nothing within `within`. Lets a test observe the parts emitted+/// *while* a long-running tool keeps the underlying agent future busy, without+/// hanging if a part that should have arrived never does.+pub(crate) async fn next_within(+ stream: &mut ChatCompletionStream<'_>,+ within: std::time::Duration,+) -> Option<StreamPart> {+ match tokio::time::timeout(within, stream.next()).await {+ Ok(Some(Ok(part))) => Some(part),+ _ => None,+ }+}++/// Send a single user `prompt` and drain the resulting stream.+pub(crate) async fn drive(session: &mut Session, prompt: &str) -> Collected {+ let stream = session+ .send_message(vec![Message::user(prompt)])+ .await+ .expect("send_message should start the stream");+ collect(stream).await+}diff --git a/rust/cloud-storage/agent/src/test/mod.rs b/rust/cloud-storage/agent/src/test/mod.rsnew file mode 100644index 0000000000..78aa481e04--- /dev/null+++ b/rust/cloud-storage/agent/src/test/mod.rs@@ -0,0 +1,9 @@+mod agent_loop;+mod test_accumulator;+mod test_convert;+mod test_error;+mod test_hook;+mod test_model_types;+mod test_predefined_model;+mod test_router;+mod test_tool_adapter;diff --git a/rust/cloud-storage/agent/src/accumulator/test.rs b/rust/cloud-storage/agent/src/test/test_accumulator.rssimilarity index 97%rename from rust/cloud-storage/agent/src/accumulator/test.rsrename to rust/cloud-storage/agent/src/test/test_accumulator.rsindex 1e33d8a36a..1e61000f4a 100644--- a/rust/cloud-storage/agent/src/accumulator/test.rs+++ b/rust/cloud-storage/agent/src/test/test_accumulator.rs@@ -1,5 +1,6 @@-use super::*;-use crate::stream::{McpInfo, ToolCall, Usage};+use crate::accumulator::*;+use crate::stream::{McpInfo, StreamPart, ToolCall, ToolResponse, Usage};+use crate::types::AssistantMessagePart;use serde_json::json;fn content(s: &str) -> StreamPart {diff --git a/rust/cloud-storage/agent/src/convert/test.rs b/rust/cloud-storage/agent/src/test/test_convert.rssimilarity index 98%rename from rust/cloud-storage/agent/src/convert/test.rsrename to rust/cloud-storage/agent/src/test/test_convert.rsindex 4baed99a47..9d4626332b 100644--- a/rust/cloud-storage/agent/src/convert/test.rs+++ b/rust/cloud-storage/agent/src/test/test_convert.rs@@ -1,9 +1,12 @@-use super::*;+use crate::convert::*;+use crate::types::{AssistantMessagePart, ChatMessage, ChatMessageContent, Role};use attachment::image::ImageData;use attachment::{AttachmentContent, AttachmentPart, Attachments};use model_entity::EntityType;use non_empty::NonEmpty;-use rig_core::message::{AssistantContent, DocumentSourceKind, Message, UserContent};+use rig_core::message::{+ AssistantContent, DocumentSourceKind, ImageMediaType, Message, UserContent,+};use serde_json::json;/// A minimal valid 1x1 PNG, used to exercise the image-normalization path.diff --git a/rust/cloud-storage/agent/src/test/test_error.rs b/rust/cloud-storage/agent/src/test/test_error.rsnew file mode 100644index 0000000000..67a2f81866--- /dev/null+++ b/rust/cloud-storage/agent/src/test/test_error.rs@@ -0,0 +1,97 @@+use crate::error::*;+use rig_core::agent::StreamingError;+use rig_core::completion::{CompletionError, PromptError};++fn prompt_cancelled() -> PromptError {+ PromptError::PromptCancelled {+ chat_history: Vec::new(),+ reason: "user cancelled".to_string(),+ }+}++#[test]+fn streaming_wrapped_cancellation_is_detected() {+ // The agent loop streams its errors, so a user cancellation reaches callers+ // wrapped as `Streaming(Prompt(PromptCancelled { .. }))` — not the bare+ // `Prompt` variant. This is the shape DCS actually sees.+ let err = AgentError::Streaming(StreamingError::Prompt(Box::new(prompt_cancelled())));+ assert!(err.was_cancelled());+}++#[test]+fn direct_prompt_cancellation_is_detected() {+ let err = AgentError::Prompt(prompt_cancelled());+ assert!(err.was_cancelled());+}++#[test]+fn non_cancellation_streaming_error_is_not_cancelled() {+ let err = AgentError::Streaming(StreamingError::Completion(CompletionError::ProviderError(+ "boom".to_string(),+ )));+ assert!(!err.was_cancelled());+}++#[test]+fn unrelated_error_is_not_cancelled() {+ let err = AgentError::UnknownModel("foo/bar".to_string());+ assert!(!err.was_cancelled());+}++/// Assert that `err` unwraps to a [`CompletionError::ProviderError`] carrying+/// `msg`. Keeps the nesting tests below to one line each.+fn assert_provider_error(err: &AgentError, msg: &str) {+ match err.completion_error() {+ Some(CompletionError::ProviderError(got)) => assert_eq!(got, msg),+ other => panic!("expected a wrapped ProviderError, got {other:?}"),+ }+}++#[test]+fn completion_error_unwraps_direct_completion() {+ let err = AgentError::Completion(CompletionError::ProviderError("boom".to_string()));+ assert_provider_error(&err, "boom");+}++#[test]+fn completion_error_unwraps_prompt_completion() {+ let err = AgentError::Prompt(PromptError::CompletionError(+ CompletionError::ProviderError("boom".to_string()),+ ));+ assert_provider_error(&err, "boom");+}++#[test]+fn completion_error_unwraps_streaming_completion() {+ let err = AgentError::Streaming(StreamingError::Completion(CompletionError::ProviderError(+ "boom".to_string(),+ )));+ assert_provider_error(&err, "boom");+}++#[test]+fn completion_error_unwraps_streaming_prompt_completion() {+ // The real chat path surfaces provider failures as+ // `Streaming(Prompt(CompletionError))` — the deepest nesting.+ let err = AgentError::Streaming(StreamingError::Prompt(Box::new(+ PromptError::CompletionError(CompletionError::ProviderError("boom".to_string())),+ )));+ assert_provider_error(&err, "boom");+}++#[test]+fn completion_error_is_none_for_cancellation() {+ // A cancellation is not a completion failure.+ let err = AgentError::Prompt(prompt_cancelled());+ assert!(err.completion_error().is_none());+}++#[test]+fn completion_error_is_none_for_non_completion_errors() {+ let err = AgentError::UnknownModel("foo/bar".to_string());+ assert!(err.completion_error().is_none());++ let json_err = serde_json::from_str::<serde_json::Value>("not json").unwrap_err();+ let err = AgentError::Json(json_err);+ assert!(err.completion_error().is_none());+}diff --git a/rust/cloud-storage/agent/src/hook/test.rs b/rust/cloud-storage/agent/src/test/test_hook.rssimilarity index 93%rename from rust/cloud-storage/agent/src/hook/test.rsrename to rust/cloud-storage/agent/src/test/test_hook.rsindex 28af058c01..3109ac51a8 100644--- a/rust/cloud-storage/agent/src/hook/test.rs+++ b/rust/cloud-storage/agent/src/test/test_hook.rs@@ -1,7 +1,12 @@-use super::*;+use crate::hook::*;+use ai_toolset::SearchableTool;+use rig_core::agent::{HookAction, PromptHook};use rig_core::providers::anthropic::completion::CompletionModel as AnthropicModel;use schemars::Schema;+use std::pin::Pin;+use std::sync::Arc;use std::sync::Mutex;+use tokio_util::sync::CancellationToken;fn searchable(name: &str) -> SearchableTool {SearchableTool {diff --git a/rust/cloud-storage/agent/src/test/test_model_types.rs b/rust/cloud-storage/agent/src/test/test_model_types.rsnew file mode 100644index 0000000000..1d9e7dc694--- /dev/null+++ b/rust/cloud-storage/agent/src/test/test_model_types.rs@@ -0,0 +1,11 @@+use crate::model::types::Model;++#[test]+fn test_from_string() {+ let good = Model::try_from("anthropic/claude-big-burger").expect("good model");+ assert_eq!(good.name(), "claude-big-burger");+ assert_eq!(good.provider(), "anthropic");++ let bad = "claude-big-burger";+ assert!(Model::try_from(bad).is_err());+}diff --git a/rust/cloud-storage/agent/src/test/test_predefined_model.rs b/rust/cloud-storage/agent/src/test/test_predefined_model.rsnew file mode 100644index 0000000000..0bc8425e9d--- /dev/null+++ b/rust/cloud-storage/agent/src/test/test_predefined_model.rs@@ -0,0 +1,66 @@+use rig_core::providers::{+ anthropic::completion::{+ CLAUDE_HAIKU_4_5, CLAUDE_OPUS_4_7, CLAUDE_OPUS_4_8, CLAUDE_SONNET_4_6,+ },+ openai::GPT_5_5,+};++use crate::model::PredefinedModel;++#[test]+fn default_is_smart() {+ assert_eq!(PredefinedModel::default(), PredefinedModel::Smart);+}++#[test]+fn smart_is_opus_4_8() {+ // `Smart` resolves to Opus 4.8 — both as the router id (`to_string`,+ // provider-qualified) and as the serialize-only wire id (bare api id).+ assert_eq!(+ PredefinedModel::Smart.to_string(),+ format!("anthropic/{CLAUDE_OPUS_4_8}")+ );+ assert_eq!(+ serde_json::to_string(&PredefinedModel::Smart).unwrap(),+ r#""claude-opus-4-8""#+ );+}++#[test]+fn fast_is_haiku() {+ // `Fast` resolves to the same model as `Haiku4_5` (Claude Haiku 4.5).+ assert_eq!(+ PredefinedModel::Fast.to_string(),+ format!("anthropic/{CLAUDE_HAIKU_4_5}")+ );+ assert_eq!(+ PredefinedModel::Fast.to_string(),+ PredefinedModel::Haiku4_5.to_string()+ );+}++#[test]+fn retired_uses_default_api_id() {+ assert_eq!(+ PredefinedModel::Retired.to_string(),+ PredefinedModel::Smart.to_string()+ );+}++#[test]+fn variants_serialize_to_their_api_id() {+ fn ant(m: &str) -> String {+ format!("anthropic/{}", m)+ }++ assert_eq!(PredefinedModel::Opus4_7.to_string(), ant(CLAUDE_OPUS_4_7));+ assert_eq!(PredefinedModel::Haiku4_5.to_string(), ant(CLAUDE_HAIKU_4_5));+ assert_eq!(+ PredefinedModel::Sonnet4_6.to_string(),+ ant(CLAUDE_SONNET_4_6)+ );+ assert_eq!(+ PredefinedModel::Gpt5_5.to_string(),+ format!("openai/{}", GPT_5_5)+ );+}diff --git a/rust/cloud-storage/agent/src/test/test_router.rs b/rust/cloud-storage/agent/src/test/test_router.rsnew file mode 100644index 0000000000..f0fc490926--- /dev/null+++ b/rust/cloud-storage/agent/src/test/test_router.rs@@ -0,0 +1,40 @@+use crate::model::router::*;+use rig_core::providers::{anthropic, openai};++fn test_router() -> ModelRouter {+ let anthropic = anthropic::Client::builder()+ .api_key("test-anthropic-key")+ .build()+ .unwrap();+ let openai = openai::Client::builder()+ .api_key("test-openai-key")+ .build()+ .unwrap();+ let compatible = openai::CompletionsClient::builder()+ .api_key("test-compatible-key")+ .base_url("http://localhost:11434/v1")+ .build()+ .unwrap();++ ModelRouter::new(anthropic, openai).with_openai_client("local", compatible)+}++#[test]+fn openai_provider_routes_to_responses() {+ let router = test_router();++ assert!(matches!(+ router.route("openai/gpt-5.5").unwrap(),+ RoutedModel::OpenAiResponses(_)+ ));+}++#[test]+fn registered_openai_compatible_provider_routes_to_chat_completions() {+ let router = test_router();++ assert!(matches!(+ router.route("local/llama-3.3-70b").unwrap(),+ RoutedModel::OpenAiChatCompletions(_)+ ));+}diff --git a/rust/cloud-storage/agent/src/tool_adapter/test.rs b/rust/cloud-storage/agent/src/test/test_tool_adapter.rssimilarity index 98%rename from rust/cloud-storage/agent/src/tool_adapter/test.rsrename to rust/cloud-storage/agent/src/test/test_tool_adapter.rsindex affc08d4fb..be6fab8859 100644--- a/rust/cloud-storage/agent/src/tool_adapter/test.rs+++ b/rust/cloud-storage/agent/src/test/test_tool_adapter.rs@@ -1,4 +1,4 @@-use super::*;+use crate::tool_adapter::*;#[test]fn empty_object_schema_gains_properties() {diff --git a/rust/cloud-storage/agent/src/tool_adapter.rs b/rust/cloud-storage/agent/src/tool_adapter.rsindex 28a191d9cb..266ba32d01 100644--- a/rust/cloud-storage/agent/src/tool_adapter.rs+++ b/rust/cloud-storage/agent/src/tool_adapter.rs@@ -1,7 +1,4 @@/// Adapts `ai_toolset` tool types into RIG [`ToolDyn`] objects.-#[cfg(test)]-mod test;-use ai_toolset::tool_object::ToolSetCallable;use ai_toolset::{AsyncToolCollection, RequestContext, RequestSchema, ToolSet as AiToolSet};use rig_core::completion::ToolDefinition;diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rsindex 698100dc80..312a590258 100644--- a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs@@ -6,7 +6,9 @@ use super::util::chat_permissions;use crate::api::context::ApiContext;use crate::api::utils::log;use crate::core::constants::DEFAULT_CHAT_NAME;-use crate::model::stream::{ChatStream, JwtPayload, SendChatMessagePayload, StreamError, ToolSet};+use crate::model::stream::{+ AgentStreamFailure, ChatStream, JwtPayload, SendChatMessagePayload, StreamError, ToolSet,+};use crate::service::ai_stream_registry::CancellationSubscription;use crate::service::chat_renamer::spawn_initial_chat_rename;use crate::service::get_chat::get_chat;@@ -407,25 +409,6 @@ async fn create_new_chat(Ok((chat, new_chat_id))}-/// Map an [`agent::AgentError`] to the well-typed [`StreamError`] sent to the-/// client. Provider outages and context overflows get their own variants so-/// the frontend can react specifically (e.g. prompt the user to switch-/// models); anything else falls back to a generic internal error.-fn stream_error_for(err: &agent::AgentError, stream_id: &str, model: &str) -> StreamError {- match err.failure_kind() {- agent::FailureKind::ProviderOutage => StreamError::ProviderError {- stream_id: stream_id.to_string(),- model: model.to_string(),- },- agent::FailureKind::ContextOverflow => StreamError::ModelContextOverflow {- stream_id: stream_id.to_string(),- },- agent::FailureKind::Internal => StreamError::InternalError {- stream_id: stream_id.to_string(),- },- }-}-/// For every `ToolCall` in `parts` that has no matching response, insert a/// synthetic `ToolCallErr { description: "cancelled", .. }` immediately after/// it. Used on cancellation so the persisted assistant message stays@@ -551,7 +534,11 @@ fn stream_and_save_message(Ok(stream) => stream,Err(e) => {tracing::error!(error=?e, chat_id = %chat_id, user_id = %user_id, stream_id = %stream_id, "failed to create AI stream");- let stream_error = stream_error_for(&e, &stream_id, &model);+ let stream_error = StreamError::from(AgentStreamFailure {+ error: &e,+ stream_id: &stream_id,+ model: &model,+ });if let Ok(json) = serde_json::to_value(ChatStream::Error(stream_error)) {yield json;}@@ -626,7 +613,11 @@ fn stream_and_save_message(break;}tracing::error!(error=?e, chat_id = %chat_id, user_id = %user_id, stream_id = %stream_id, "error in AI stream");- let stream_error = stream_error_for(&e, &stream_id, &model);+ let stream_error = StreamError::from(AgentStreamFailure {+ error: &e,+ stream_id: &stream_id,+ model: &model,+ });if let Ok(json) = serde_json::to_value(ChatStream::Error(stream_error)) {yield json;}diff --git a/rust/cloud-storage/document_cognition_service/src/model/stream.rs b/rust/cloud-storage/document_cognition_service/src/model/stream.rsindex 9295956117..0e54cc0661 100644--- a/rust/cloud-storage/document_cognition_service/src/model/stream.rs+++ b/rust/cloud-storage/document_cognition_service/src/model/stream.rs@@ -1,8 +1,12 @@use agent::types::AssistantMessagePart;+use agent::{AgentError, CompletionError};use model_entity::Entity;use serde::{Deserialize, Serialize};use utoipa::ToSchema;+#[cfg(test)]+mod test;+#[derive(Deserialize, Serialize, ToSchema, Debug, Clone)]pub struct JwtPayload {pub token: String,@@ -80,3 +84,65 @@ pub enum StreamError {#[error("internal error")]InternalError { stream_id: String },}++/// An [`AgentError`] together with the stream context needed to render it as a+/// client-facing [`StreamError`]. The agent crate doesn't (and shouldn't) know+/// how DCS classifies failures for the frontend, so the mapping lives here as a+/// `From` and carries the `stream_id` / `model` the wire variants require.+pub struct AgentStreamFailure<'a> {+ /// The error the agent loop surfaced.+ pub error: &'a AgentError,+ /// The stream the error belongs to.+ pub stream_id: &'a str,+ /// The model the request was running against.+ pub model: &'a str,+}++impl From<AgentStreamFailure<'_>> for StreamError {+ /// Classify an agent failure for user-facing reporting.+ ///+ /// rig collapses provider HTTP failures into [`CompletionError::ProviderError`]+ /// / [`CompletionError::ResponseError`] (the HTTP status code is not+ /// preserved), so we inspect the innermost completion error: a context-window+ /// message becomes [`StreamError::ModelContextOverflow`]; any other provider+ /// or transport failure becomes [`StreamError::ProviderError`] (so the+ /// frontend can prompt the user to switch models); everything else — including+ /// errors that don't wrap a completion call — is an internal error.+ fn from(failure: AgentStreamFailure<'_>) -> Self {+ let AgentStreamFailure {+ error,+ stream_id,+ model,+ } = failure;+ let stream_id = stream_id.to_string();+ match error.completion_error() {+ Some(CompletionError::ProviderError(msg) | CompletionError::ResponseError(msg))+ if is_context_overflow(msg) =>+ {+ StreamError::ModelContextOverflow { stream_id }+ }+ // Provider error / response error / connection failure or timeout —+ // we reached the wrong answer or couldn't reach the provider at all.+ Some(+ CompletionError::ProviderError(_)+ | CompletionError::ResponseError(_)+ | CompletionError::HttpError(_),+ ) => StreamError::ProviderError {+ stream_id,+ model: model.to_string(),+ },+ _ => StreamError::InternalError { stream_id },+ }+ }+}++/// Whether a provider error message describes a context-window overflow rather+/// than an outage. Anthropic returns "prompt is too long"; OpenAI returns+/// "context_length_exceeded" / "maximum context length".+fn is_context_overflow(msg: &str) -> bool {+ let m = msg.to_ascii_lowercase();+ m.contains("context length")+ || m.contains("context_length")+ || m.contains("maximum context")+ || m.contains("prompt is too long")+}diff --git a/rust/cloud-storage/document_cognition_service/src/model/stream/test.rs b/rust/cloud-storage/document_cognition_service/src/model/stream/test.rsnew file mode 100644index 0000000000..70eba55eeb--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/model/stream/test.rs@@ -0,0 +1,76 @@+use super::*;++/// Build the [`StreamError`] DCS would send for `error`, with fixed ids.+fn classify(error: &AgentError) -> StreamError {+ StreamError::from(AgentStreamFailure {+ error,+ stream_id: "stream-1",+ model: "anthropic/claude-opus-4-8",+ })+}++#[test]+fn anthropic_500_body_is_provider_error() {+ // What rig hands us for a 5xx: the raw provider body wrapped in ProviderError.+ let err = AgentError::Completion(CompletionError::ProviderError(+ r#"{"type":"error","error":{"type":"api_error","message":"Internal server error"}}"#+ .to_string(),+ ));+ assert!(matches!(+ classify(&err),+ StreamError::ProviderError { model, .. } if model == "anthropic/claude-opus-4-8"+ ));+}++#[test]+fn overloaded_is_provider_error() {+ let err = AgentError::Completion(CompletionError::ProviderError(+ r#"{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}"#+ .to_string(),+ ));+ assert!(matches!(classify(&err), StreamError::ProviderError { .. }));+}++#[test]+fn anthropic_prompt_too_long_is_context_overflow() {+ let err = AgentError::Completion(CompletionError::ProviderError(+ "prompt is too long: 250000 tokens > 200000 maximum".to_string(),+ ));+ assert!(matches!(+ classify(&err),+ StreamError::ModelContextOverflow { .. }+ ));+}++#[test]+fn openai_context_length_is_context_overflow() {+ let err = AgentError::Completion(CompletionError::ResponseError(+ "context_length_exceeded: maximum context length exceeded".to_string(),+ ));+ assert!(matches!(+ classify(&err),+ StreamError::ModelContextOverflow { .. }+ ));+}++#[test]+fn non_completion_error_is_internal() {+ let err = AgentError::UnknownModel("bogus".to_string());+ assert!(matches!(classify(&err), StreamError::InternalError { .. }));+}++#[test]+fn json_error_is_internal() {+ let json_err = serde_json::from_str::<serde_json::Value>("not json").unwrap_err();+ let err = AgentError::Json(json_err);+ assert!(matches!(classify(&err), StreamError::InternalError { .. }));+}++#[test]+fn stream_id_is_propagated() {+ let err = AgentError::UnknownModel("bogus".to_string());+ let StreamError::InternalError { stream_id } = classify(&err) else {+ panic!("expected internal error");+ };+ assert_eq!(stream_id, "stream-1");+}