fix(acp): send session usage updates after each provider call (#12006)
This commit is contained in:
@@ -2091,12 +2091,31 @@ impl GooseAcpAgent {
|
||||
)
|
||||
}
|
||||
|
||||
async fn resolve_context_limit(
|
||||
session: &Session,
|
||||
agent: &Arc<Agent>,
|
||||
) -> Result<usize, agent_client_protocol::Error> {
|
||||
let provider = agent
|
||||
.provider()
|
||||
.await
|
||||
.internal_err_ctx("Failed to resolve session provider")?;
|
||||
let model = session.model_config.as_ref().ok_or_else(|| {
|
||||
agent_client_protocol::Error::internal_error().data("Session has no model")
|
||||
})?;
|
||||
crate::context_limit::get_context_limit(provider.as_ref(), &model.model_name)
|
||||
.await
|
||||
.internal_err_ctx("Failed to resolve context limit")
|
||||
}
|
||||
|
||||
/// Updates sent during one turn share `cached_context_limit`, so the provider
|
||||
/// limit is resolved once per turn rather than on every usage event.
|
||||
async fn send_session_usage_updates(
|
||||
&self,
|
||||
cx: &ConnectionTo<Client>,
|
||||
acp_session_id: &SessionId,
|
||||
session_id: &str,
|
||||
agent: &Arc<Agent>,
|
||||
cached_context_limit: &mut Option<usize>,
|
||||
) -> Result<Session, agent_client_protocol::Error> {
|
||||
let session = self
|
||||
.session_manager
|
||||
@@ -2108,17 +2127,14 @@ impl GooseAcpAgent {
|
||||
.get_session_usage_totals(session_id)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let provider = agent
|
||||
.provider()
|
||||
.await
|
||||
.internal_err_ctx("Failed to resolve session provider")?;
|
||||
let model = session.model_config.as_ref().ok_or_else(|| {
|
||||
agent_client_protocol::Error::internal_error().data("Session has no model")
|
||||
})?;
|
||||
let context_limit =
|
||||
crate::context_limit::get_context_limit(provider.as_ref(), &model.model_name)
|
||||
.await
|
||||
.internal_err_ctx("Failed to resolve context limit")?;
|
||||
let context_limit = match *cached_context_limit {
|
||||
Some(limit) => limit,
|
||||
None => {
|
||||
let limit = Self::resolve_context_limit(&session, agent).await?;
|
||||
*cached_context_limit = Some(limit);
|
||||
limit
|
||||
}
|
||||
};
|
||||
let updates = build_usage_updates(&session, &totals, context_limit);
|
||||
if self.supports_goose_custom_notifications() {
|
||||
cx.send_notification(updates.custom)?;
|
||||
@@ -2144,6 +2160,7 @@ impl GooseAcpAgent {
|
||||
let mut output_token_limit_reached = false;
|
||||
let mut tool_requests = HashMap::new();
|
||||
let mut chain_tracker = ToolChainTracker::default();
|
||||
let mut context_limit = None;
|
||||
let target = SessionAgentTarget {
|
||||
agent: agent.clone(),
|
||||
session_id: session_id.to_string(),
|
||||
@@ -2224,6 +2241,23 @@ impl GooseAcpAgent {
|
||||
})?;
|
||||
}
|
||||
}
|
||||
Ok(crate::agents::AgentEvent::Usage(_)) => {
|
||||
// Both agent loops persist usage before emitting this event. A failed
|
||||
// mid-turn update must not abort the turn; the end-of-turn update
|
||||
// still reports errors.
|
||||
if let Err(error) = self
|
||||
.send_session_usage_updates(
|
||||
cx,
|
||||
acp_session_id,
|
||||
session_id,
|
||||
agent,
|
||||
&mut context_limit,
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!(session_id, ?error, "Failed to send mid-turn usage update");
|
||||
}
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(error) => {
|
||||
return Err(agent_client_protocol::Error::internal_error()
|
||||
@@ -2356,7 +2390,7 @@ impl GooseAcpAgent {
|
||||
let outcome = stream_result?;
|
||||
|
||||
let session = self
|
||||
.send_session_usage_updates(cx, &args.session_id, &session_id, &agent)
|
||||
.send_session_usage_updates(cx, &args.session_id, &session_id, &agent, &mut None)
|
||||
.await?;
|
||||
|
||||
let stop_reason =
|
||||
|
||||
@@ -327,6 +327,7 @@ impl GooseAcpAgent {
|
||||
&task_acp_session_id,
|
||||
&task_session_id,
|
||||
&task_agent,
|
||||
&mut None,
|
||||
)
|
||||
.await
|
||||
{
|
||||
|
||||
@@ -3,16 +3,18 @@
|
||||
#[path = "acp_common_tests/mod.rs"]
|
||||
mod common_tests;
|
||||
use agent_client_protocol::schema::v1::{
|
||||
ContentBlock, ListSessionsRequest, ListSessionsResponse, NewSessionRequest, PromptRequest,
|
||||
SessionConfigKind, SessionConfigOptionCategory, SessionConfigOptionValue, SessionInfo,
|
||||
SetSessionConfigOptionRequest, StopReason, TextContent,
|
||||
ContentBlock, ListSessionsRequest, ListSessionsResponse, McpServer, McpServerHttp,
|
||||
NewSessionRequest, PromptRequest, SessionConfigKind, SessionConfigOptionCategory,
|
||||
SessionConfigOptionValue, SessionInfo, SessionUpdate, SetSessionConfigOptionRequest,
|
||||
StopReason, TextContent,
|
||||
};
|
||||
use agent_client_protocol::ErrorCode;
|
||||
use common_tests::fixtures::server::{
|
||||
assert_session_response_precedes_available_commands, AcpServerConnection,
|
||||
};
|
||||
use common_tests::fixtures::{
|
||||
run_test, spawn_acp_server_in_process, Connection, OpenAiFixture, Session, TestConnectionConfig,
|
||||
run_test, spawn_acp_server_in_process, Connection, OpenAiFixture, PermissionDecision, Session,
|
||||
SessionData, TestConnectionConfig,
|
||||
};
|
||||
#[cfg(feature = "code-mode")]
|
||||
use common_tests::run_prompt_codemode;
|
||||
@@ -37,6 +39,7 @@ use goose::custom_requests::{
|
||||
use goose::recipe::{Recipe, Settings};
|
||||
use goose::recipe_deeplink;
|
||||
use goose::session::{SessionManager, SessionType};
|
||||
use goose_test_support::{McpFixture, FAKE_CODE};
|
||||
use std::path::Path;
|
||||
|
||||
tests_config_option_set_error!(AcpServerConnection);
|
||||
@@ -1209,6 +1212,92 @@ fn test_prompt_mcp() {
|
||||
run_test(async { run_prompt_mcp::<AcpServerConnection>().await });
|
||||
}
|
||||
|
||||
/// Selects the agent loop until dropped. Only use inside `run_test`: it holds the
|
||||
/// ACP test lock, so no other test in this binary observes the override.
|
||||
struct AgentLoopOverride(Option<std::ffi::OsString>);
|
||||
|
||||
impl AgentLoopOverride {
|
||||
fn new(state_machine: bool) -> Self {
|
||||
let previous = std::env::var_os("GOOSE_STATE_MACHINE");
|
||||
std::env::set_var("GOOSE_STATE_MACHINE", if state_machine { "1" } else { "0" });
|
||||
Self(previous)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for AgentLoopOverride {
|
||||
fn drop(&mut self) {
|
||||
match self.0.take() {
|
||||
Some(previous) => std::env::set_var("GOOSE_STATE_MACHINE", previous),
|
||||
None => std::env::remove_var("GOOSE_STATE_MACHINE"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Two provider calls separated by a tool call. The canned responses report 2469
|
||||
/// and then 2631 total tokens, so 2469 can only arrive in an update sent while
|
||||
/// the prompt is still running.
|
||||
async fn assert_usage_updates_during_prompt(state_machine: bool) {
|
||||
let _agent_loop = AgentLoopOverride::new(state_machine);
|
||||
let prompt = "Use the get_code tool and output only its result.";
|
||||
let mcp = McpFixture::new().await;
|
||||
let openai = OpenAiFixture::new(
|
||||
vec![
|
||||
(
|
||||
prompt.to_string(),
|
||||
include_str!("acp_test_data/openai_tool_call.txt"),
|
||||
),
|
||||
(
|
||||
FAKE_CODE.to_string(),
|
||||
include_str!("acp_test_data/openai_tool_result.txt"),
|
||||
),
|
||||
],
|
||||
<AcpServerConnection as Connection>::expected_session_id(),
|
||||
)
|
||||
.await;
|
||||
let config = TestConnectionConfig {
|
||||
mcp_servers: vec![McpServer::Http(McpServerHttp::new("mcp-fixture", &mcp.url))],
|
||||
..Default::default()
|
||||
};
|
||||
let mut conn = <AcpServerConnection as Connection>::new(config, openai).await;
|
||||
let SessionData { mut session, .. } = conn.new_session().await.unwrap();
|
||||
|
||||
let output = session
|
||||
.prompt(prompt, PermissionDecision::Cancel)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let mut used = Vec::new();
|
||||
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2);
|
||||
while used.len() < 3 && tokio::time::Instant::now() < deadline {
|
||||
used.extend(
|
||||
session
|
||||
.session_updates()
|
||||
.into_iter()
|
||||
.filter_map(|update| match update {
|
||||
SessionUpdate::UsageUpdate(usage) => Some(usage.used),
|
||||
_ => None,
|
||||
}),
|
||||
);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
||||
}
|
||||
assert_eq!(
|
||||
used,
|
||||
[2469, 2631, 2631],
|
||||
"state_machine={state_machine}, agent text: {}",
|
||||
output.text
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_prompt_usage_updates_during_turn_legacy_loop() {
|
||||
run_test(async { assert_usage_updates_during_prompt(false).await });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_prompt_usage_updates_during_turn_state_machine() {
|
||||
run_test(async { assert_usage_updates_during_prompt(true).await });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_prompt_model_mismatch() {
|
||||
run_test(async { run_prompt_model_mismatch::<AcpServerConnection>().await });
|
||||
|
||||
Reference in New Issue
Block a user