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
use super::*;
use crate::PROTOCOL_VERSION;
use crate::domain::model::{
DEFAULT_AGENT_SESSION_NAME, LeaseView, Message, ReplicaAddress, SessionBot, SessionSource,
SessionVisibility,
};
use crate::domain::ports::NoOpRealtime;
use crate::domain::ports::{NoOpTurnObserver, NoopLifecyclePublisher};
use crate::domain::session::{HandshakeStatus, PermissionPolicy};
use crate::testing::{
InMemoryAgentSessionRepo, RecordingLifecyclePublisher, RecordingRealtime, test_agent_session,
};
use agent_fold::domain::fold::fold;
use agent_fold::domain::service::FoldedMessageService;
use agent_fold::testing::{TURN, parse_log_as, test_session};
use agent_runtime_protocol::domain::ports::{
Transport, TransportError, TransportReceiver, TransportSender,
};
use agent_runtime_protocol::domain::schema::v0::ToRuntimeMessage;
use agent_runtime_protocol::domain::schema::v0::{AcpMessage, ToServerMessage};
use entity_access::domain::models::{EntityAccessReceipt, EntityType, OwnerAccessLevel};
use macro_uuid::Uuid;
use std::sync::{Arc, Mutex};
use tokio::sync::Notify;
use tracing::instrument::WithSubscriber as _;
mod first_output;
mod presentation;
struct Fixture {
service: AgentSessionServiceImpl<
InMemoryAgentSessionRepo,
FoldedMessageService<InMemoryAgentSessionRepo>,
NoOpRealtime,
>,
repo: InMemoryAgentSessionRepo,
session: AgentSessionId,
}
fn fixture() -> Fixture {
let repo = InMemoryAgentSessionRepo::new();
let session = AgentSessionId::new_from_uuid(Uuid::from_u128(1));
repo.insert_session(test_agent_session(session));
Fixture {
// Nothing here is about streaming, so there are no viewers to publish
// to.
service: AgentSessionServiceImpl::new(
repo.clone(),
FoldedMessageService::new(repo.clone()),
NoOpRealtime,
NoOpAgentSessionNameGenerator,
Arc::new(NoOpTurnObserver),
Arc::new(NoopLifecyclePublisher),
ReplicaId::mint(),
),
repo,
session,
}
}
#[tokio::test]
async fn previews_hydrate_bot_identity_only_for_accessible_sessions() {
let fx = fixture();
let session = fx.repo.get(fx.session).await.unwrap();
let previews = fx
.service
.preview_sessions(session.owner_user().unwrap(), vec![fx.session, fx.session])
.await
.unwrap();
assert_eq!(previews.len(), 1);
let AgentSessionPreview::Access(data) = &previews[0] else {
panic!("expected access")
};
assert_eq!(data.bot.as_ref().unwrap().name, "Test Agent");
let other =
macro_user_id::user_id::MacroUserIdStr::try_from_email("[email protected]").unwrap();
assert_eq!(
fx.service
.preview_sessions(&other, vec![fx.session])
.await
.unwrap(),
vec![AgentSessionPreview::NoAccess(fx.session)]
);
}
/// A viewer answers for one document-born session.
struct GrantingViewAccess(AgentSessionId);
impl crate::domain::ports::SessionViewAccess for GrantingViewAccess {
fn can_view<'a>(
&'a self,
_viewer: &'a macro_user_id::user_id::MacroUserIdStr<'static>,
session: AgentSessionId,
) -> std::pin::Pin<Box<dyn Future<Output = Result<bool>> + Send + 'a>> {
Box::pin(async move { Ok(session == self.0) })
}
}
#[tokio::test]
async fn previews_resolve_discussion_and_link_access_through_the_view_port() {
for parent in [
messages::domain::models::MessageParent::parse("document", "doc-1").unwrap(),
messages::domain::models::MessageParent::Initiative(Uuid::from_u128(902)),
] {
let fx = fixture();
let mut discussion_session = test_agent_session(AgentSessionId::new());
discussion_session.thread_parent = Some(parent);
let mut channel_session = test_agent_session(AgentSessionId::new());
channel_session.thread_parent = Some(messages::domain::models::MessageParent::Channel(
Uuid::from_u128(9),
));
fx.repo.insert_session(discussion_session.clone());
fx.repo.insert_session(channel_session.clone());
let collaborator =
macro_user_id::user_id::MacroUserIdStr::try_from_email("[email protected]")
.unwrap();
let ids = vec![discussion_session.id, channel_session.id, fx.session];
// Without a view port, only materialized grants count.
let mut previews = fx
.service
.preview_sessions(&collaborator, ids.clone())
.await
.unwrap();
previews.sort_by_key(|preview| preview.id().as_uuid());
assert!(
previews
.iter()
.all(|preview| matches!(preview, AgentSessionPreview::NoAccess(_)))
);
// The view port can resolve discussion inheritance or link sharing.
let service = fx
.service
.clone()
.with_view_access(Arc::new(GrantingViewAccess(discussion_session.id)));
let previews = service.preview_sessions(&collaborator, ids).await.unwrap();
let access: Vec<_> = previews
.iter()
.filter_map(|preview| match preview {
AgentSessionPreview::Access(data) => Some(data.id),
_ => None,
})
.collect();
assert_eq!(access, vec![discussion_session.id]);
let channel_service = fx
.service
.clone()
.with_view_access(Arc::new(GrantingViewAccess(channel_session.id)));
assert!(matches!(
channel_service
.preview_sessions(&collaborator, vec![channel_session.id])
.await
.unwrap().as_slice(),
[AgentSessionPreview::Access(data)] if data.id == channel_session.id
));
}
}
#[tokio::test]
async fn only_the_first_prompt_is_selected_for_automatic_naming() {
let repo = InMemoryAgentSessionRepo::new();
let session = test_session();
repo.insert_session(test_agent_session(session));
let folds = FoldedMessageService::new(repo.clone());
let mut prompt = AgentAction::prompt("composed prompt with private context");
let AgentAction::Prompt(prompt_action) = &mut prompt else {
unreachable!("the test constructed a prompt");
};
prompt_action.set_name_source("fix the flaky tests");
assert_eq!(
initial_prompt_for_rename(&folds, session, &prompt).await,
Some("fix the flaky tests".to_owned())
);
// A control opens a turn of its own, so turn numbering cannot stand in for
// "nobody has spoken yet" - a model picked before the first prompt used to
// leave the session unnamed for life.
repo.extend_log(vec![AgentSessionLog {
agent_session_id: session,
user_id: None,
content: Message::ToRuntime(
AgentAction::set_model("gpt-5.5")
.to_runtime(
&agent_client_protocol::schema::v1::SessionId::new("acp-1"),
RequestId::Number(1),
)
.expect("a set-model frame builds"),
),
logged_at: None,
}]);
assert_eq!(
initial_prompt_for_rename(&folds, session, &prompt).await,
Some("fix the flaky tests".to_owned()),
"a model chosen before the first prompt must not cost the session its name"
);
repo.extend_log(parse_log_as(session, TURN));
assert_eq!(
initial_prompt_for_rename(&folds, session, &prompt).await,
None
);
}
#[derive(Clone, Copy)]
struct FixedNameGenerator;
impl AgentSessionNameGenerator for FixedNameGenerator {
async fn generate_name(
&self,
_session: &AgentSession,
initial_prompt: &str,
) -> std::result::Result<Option<String>, rootcause::Report> {
assert_eq!(initial_prompt, "fix the flaky tests");
Ok(Some("Fix Flaky Tests".to_owned()))
}
}
#[derive(Clone, Default)]
struct RenameRealtime(Arc<Mutex<Vec<AgentSessionRenamed>>>);
impl AgentSessionRealtime for RenameRealtime {
async fn publish(&self, _event: LogAppended) -> std::result::Result<(), rootcause::Report> {
Ok(())
}
async fn publish_renamed(
&self,
event: AgentSessionRenamed,
) -> std::result::Result<(), rootcause::Report> {
self.0
.lock()
.expect("rename store is not poisoned")
.push(event);
Ok(())
}
}
struct PendingTransport;
#[derive(Clone)]
struct PendingSender;
struct PendingReceiver;
struct RecordingTransport {
outbound: mpsc::Sender<ToRuntimeMessage>,
inbound: mpsc::Receiver<ToServerMessage>,
}
#[derive(Clone)]
struct RecordingSender(mpsc::Sender<ToRuntimeMessage>);
impl Transport<ToRuntimeMessage, ToServerMessage> for RecordingTransport {
type Sender = RecordingSender;
type Receiver = mpsc::Receiver<ToServerMessage>;
fn split(self) -> (Self::Sender, Self::Receiver) {
(RecordingSender(self.outbound), self.inbound)
}
}
impl TransportSender<ToRuntimeMessage> for RecordingSender {
async fn send(&self, message: ToRuntimeMessage) -> std::result::Result<(), TransportError> {
self.0
.send(message)
.await
.map_err(|_| TransportError::Client("test receiver closed".to_owned()))
}
}
#[derive(Clone)]
struct BlockingPromptLogs {
repo: InMemoryAgentSessionRepo,
entered: Arc<Notify>,
release: Arc<Notify>,
hang_disconnect: bool,
fail_restore_log: Option<RestoreLogFailure>,
}
#[derive(Clone, Copy)]
enum RestoreLogFailure {
InitializeRequest,
InitializeResponse,
LoadResponse,
}
impl AgentSessionLogWriter for BlockingPromptLogs {
async fn append_with_boundary(
&mut self,
log: AgentSessionLog,
_boundary: Option<crate::domain::model::HistoryBoundary>,
) -> Result<Appended> {
let is_prompt = matches!(
&log.content,
Message::ToRuntime(ToRuntimeMessage::Acp(AcpMessage(
agent_client_protocol::RawJsonRpcMessage::Request(request)
))) if request.method.as_ref() == "session/prompt"
);
if is_prompt {
self.entered.notify_one();
self.release.notified().await;
}
Ok(Appended {
log_id: AgentSessionLogRepo::create(&self.repo, log).await?.id,
signals: Vec::new(),
})
}
}
/// Claim a session's management for a freshly minted replica, as
/// `attach_session` does before activating.
async fn claim_for_test(repo: &InMemoryAgentSessionRepo, session: AgentSessionId) -> SessionClaim {
match repo
.claim(session, ReplicaId::mint())
.await
.expect("claim for test")
{
ClaimOutcome::Claimed(claim) => claim,
ClaimOutcome::ManagedElsewhere(holder) => {
panic!("test session is unexpectedly managed by {holder}")
}
}
}
fn owner_access(session: AgentSessionId) -> EntityAccessReceipt<OwnerAccessLevel> {
EntityAccessReceipt::dangerously_assert_internal_user(
&session.as_uuid().to_string(),
EntityType::AgentSession,
)
}
#[tokio::test]
async fn manual_rename_trims_persists_and_publishes() {
let repo = InMemoryAgentSessionRepo::new();
let session = test_session();
repo.insert_session(test_agent_session(session));
let realtime = RenameRealtime::default();
let service = AgentSessionServiceImpl::new(
repo.clone(),
FoldedMessageService::new(repo.clone()),
realtime.clone(),
NoOpAgentSessionNameGenerator,
Arc::new(NoOpTurnObserver),
Arc::new(NoopLifecyclePublisher),
ReplicaId::mint(),
);
service
.rename_session(&owner_access(session), " Fix Flaky Tests ")
.await
.expect("rename session");
let stored = repo.get(session).await.expect("get session");
assert_eq!(stored.name, "Fix Flaky Tests");
assert_eq!(
realtime
.0
.lock()
.expect("rename store is not poisoned")
.as_slice(),
&[AgentSessionRenamed {
agent_session_id: session,
name: "Fix Flaky Tests".to_owned(),
}]
);
}
#[tokio::test]
async fn archive_is_persisted_published_and_blocks_rename() {
let repo = InMemoryAgentSessionRepo::new();
let session = test_session();
repo.insert_session(test_agent_session(session));
let realtime = RecordingRealtime::default();
let service = AgentSessionServiceImpl::new(
repo.clone(),
FoldedMessageService::new(repo.clone()),
realtime.clone(),
NoOpAgentSessionNameGenerator,
Arc::new(NoOpTurnObserver),
Arc::new(NoopLifecyclePublisher),
ReplicaId::mint(),
);
service
.set_archived(&owner_access(session), true)
.await
.expect("archive session");
assert!(repo.get(session).await.expect("get session").is_archived());
assert_eq!(realtime.updated(), vec![session]);
assert!(matches!(
service
.rename_session(&owner_access(session), "New Name")
.await,
Err(AgentSessionError::Archived(id)) if id == session
));
assert!(matches!(
service
.send_action(
session,
None,
AgentAction::prompt("still there?"),
AgentActionId::mint(),
)
.await,
Err(AgentSessionError::Archived(id)) if id == session
));
assert!(
!repo
.set_name_if_default(session, "Generated Name")
.await
.expect("skip generated rename for archived session")
);
service
.set_archived(&owner_access(session), false)
.await
.expect("unarchive session");
service
.rename_session(&owner_access(session), "New Name")
.await
.expect("rename unarchived session");
}
#[tokio::test]
async fn a_conversations_current_session_is_not_archived() {
let repo = InMemoryAgentSessionRepo::new();
let session = test_session();
repo.insert_session(test_agent_session(session));
repo.answer_conversation(session);
let realtime = RecordingRealtime::default();
let service = AgentSessionServiceImpl::new(
repo.clone(),
FoldedMessageService::new(repo.clone()),
realtime.clone(),
NoOpAgentSessionNameGenerator,
Arc::new(NoOpTurnObserver),
Arc::new(NoopLifecyclePublisher),
ReplicaId::mint(),
);
assert!(matches!(
service.set_archived(&owner_access(session), true).await,
Err(AgentSessionError::AnswersConversation(id)) if id == session
));
assert!(!repo.get(session).await.expect("get session").is_archived());
assert!(realtime.updated().is_empty());
// Unarchiving is never refused.
service
.set_archived(&owner_access(session), false)
.await
.expect("unarchive session");
}
#[tokio::test]
async fn manual_rename_rejects_blank_and_overlong_names() {
let repo = InMemoryAgentSessionRepo::new();
let session = test_session();
repo.insert_session(test_agent_session(session));
let service = AgentSessionServiceImpl::new(
repo.clone(),
FoldedMessageService::new(repo),
RenameRealtime::default(),
NoOpAgentSessionNameGenerator,
Arc::new(NoOpTurnObserver),
Arc::new(NoopLifecyclePublisher),
ReplicaId::mint(),
);
assert!(matches!(
service.rename_session(&owner_access(session), " ").await,
Err(AgentSessionError::InvalidName(_))
));
assert!(matches!(
service
.rename_session(&owner_access(session), DEFAULT_AGENT_SESSION_NAME)
.await,
Err(AgentSessionError::InvalidName(_))
));
assert!(matches!(
service
.rename_session(&owner_access(session), &"a".repeat(101))
.await,
Err(AgentSessionError::InvalidName(_))
));
}
#[tokio::test]
async fn manual_rename_rejects_access_for_another_entity_type() {
let repo = InMemoryAgentSessionRepo::new();
let session = test_session();
repo.insert_session(test_agent_session(session));
let service = AgentSessionServiceImpl::new(
repo.clone(),
FoldedMessageService::new(repo),
RenameRealtime::default(),
NoOpAgentSessionNameGenerator,
Arc::new(NoOpTurnObserver),
Arc::new(NoopLifecyclePublisher),
ReplicaId::mint(),
);
let wrong_access = EntityAccessReceipt::<OwnerAccessLevel>::dangerously_assert_internal_user(
&session.as_uuid().to_string(),
EntityType::Document,
);
assert!(
service
.rename_session(&wrong_access, "New Name")
.await
.is_err()
);
}
#[tokio::test]
async fn background_naming_persists_then_publishes_the_generated_name() {
let repo = InMemoryAgentSessionRepo::new();
let session = test_session();
repo.insert_session(test_agent_session(session));
let realtime = RenameRealtime::default();
let lifecycle = RecordingLifecyclePublisher::new();
spawn_initial_agent_session_rename(
repo.clone(),
realtime.clone(),
Arc::new(lifecycle.clone()),
FixedNameGenerator,
session,
"fix the flaky tests".to_owned(),
);
// The lifecycle event is published last, so its arrival means the
// rename and its realtime push are done too.
lifecycle.wait_for_published(1).await;
let stored = repo.get(session).await.expect("get session");
assert_eq!(stored.name, "Fix Flaky Tests");
assert!(
matches!(
lifecycle.published().as_slice(),
[AgentSessionLifecycleEvent::Renamed(renamed)]
if renamed.identity.session_id == session
&& renamed.identity.session_name == "Fix Flaky Tests"
),
"renamed is published with the new name: {:?}",
lifecycle.published()
);
assert_eq!(
realtime
.0
.lock()
.expect("rename store is not poisoned")
.as_slice(),
&[AgentSessionRenamed {
agent_session_id: session,
name: "Fix Flaky Tests".to_owned(),
}]
);
}
/// A fixed conversation: a vague prompt and a specific reply.
#[derive(Clone)]
struct FixedConversation;
impl FoldedMessageRepo for FixedConversation {
async fn messages(
&self,
_session: AgentSessionId,
) -> std::result::Result<Vec<FoldedMessage>, rootcause::Report> {
let message = |turn, author, text: &str| FoldedMessage {
id: agent_fold::domain::model::TurnId(turn),
author,
request_id: None,
parts: non_empty::NonEmpty::new(vec![MessagePart::Text { text: text.into() }])
.expect("one part"),
stop: None,
pending: false,
posted_at: None,
};
Ok(vec![
message(0, Author::User { user_id: None }, "investigate issue"),
message(
0,
Author::Agent,
"The OAuth callback drops its trailing slash.",
),
])
}
async fn next_turn_id(
&self,
_session: AgentSessionId,
) -> std::result::Result<agent_fold::domain::model::TurnId, rootcause::Report> {
Ok(agent_fold::domain::model::TurnId(1))
}
}
/// Retitles every session it is asked about.
#[derive(Clone)]
struct RetitlingNameGenerator;
impl AgentSessionNameGenerator for RetitlingNameGenerator {
async fn generate_name(
&self,
_session: &AgentSession,
_initial_prompt: &str,
) -> std::result::Result<Option<String>, rootcause::Report> {
Ok(Some("Investigate Issue".to_owned()))
}
async fn retitle(
&self,
_session: &AgentSession,
current: &str,
conversation: &ConversationDigest,
) -> std::result::Result<Option<String>, rootcause::Report> {
assert_eq!(current, "Investigate Issue");
assert!(conversation.has_reply());
Ok(Some("OAuth Callback Redirect".to_owned()))
}
}
#[tokio::test]
async fn retitling_replaces_a_generated_name_and_publishes_it() {
let repo = InMemoryAgentSessionRepo::new();
let session = test_session();
repo.insert_session(test_agent_session(session));
assert!(
repo.set_name_if_default(session, "Investigate Issue")
.await
.unwrap()
);
let realtime = RenameRealtime::default();
let lifecycle = RecordingLifecyclePublisher::new();
spawn_agent_session_retitle(
&TaskTracker::new(),
repo.clone(),
FixedConversation,
realtime.clone(),
Arc::new(lifecycle.clone()),
RetitlingNameGenerator,
session,
);
lifecycle.wait_for_published(1).await;
assert_eq!(
repo.get(session).await.unwrap().name,
"OAuth Callback Redirect"
);
assert_eq!(
realtime.0.lock().expect("rename store is not poisoned")[0].name,
"OAuth Callback Redirect"
);
// A retitled name is still generated, so a later turn may refine it.
assert_eq!(
repo.generated_name(session).await.unwrap().as_deref(),
Some("OAuth Callback Redirect")
);
}
#[tokio::test]
async fn retitling_never_replaces_a_name_a_person_chose() {
let repo = InMemoryAgentSessionRepo::new();
let session = test_session();
repo.insert_session(test_agent_session(session));
repo.set_name_if_default(session, "Investigate Issue")
.await
.unwrap();
repo.set_name(session, "Investigate Issue").await.unwrap();
let realtime = RenameRealtime::default();
let tasks = TaskTracker::new();
spawn_agent_session_retitle(
&tasks,
repo.clone(),
FixedConversation,
realtime.clone(),
Arc::new(RecordingLifecyclePublisher::new()),
RetitlingNameGenerator,
session,
);
tasks.close();
tasks.wait().await;
assert_eq!(repo.get(session).await.unwrap().name, "Investigate Issue");
assert!(
realtime
.0
.lock()
.expect("rename store is not poisoned")
.is_empty()
);
}
#[tokio::test]
async fn retitling_skips_a_session_named_while_it_ran() {
let repo = InMemoryAgentSessionRepo::new();
let session = test_session();
repo.insert_session(test_agent_session(session));
repo.set_name_if_default(session, "Investigate Issue")
.await
.unwrap();
assert!(
!repo
.replace_generated_name(session, "Something Else", "OAuth Callback Redirect")
.await
.unwrap()
);
assert_eq!(repo.get(session).await.unwrap().name, "Investigate Issue");
}
#[tokio::test]
async fn background_naming_does_not_overwrite_a_manual_name() {
let repo = InMemoryAgentSessionRepo::new();
let session = test_session();
let mut stored = test_agent_session(session);
stored.name = "Manual Name".to_owned();
repo.insert_session(stored);
let realtime = RenameRealtime::default();
spawn_initial_agent_session_rename(
repo.clone(),
realtime.clone(),
Arc::new(NoopLifecyclePublisher),
FixedNameGenerator,
session,
"fix the flaky tests".to_owned(),
);
for _ in 0..20 {
tokio::task::yield_now().await;
}
assert_eq!(
repo.get(session).await.expect("get session").name,
"Manual Name"
);
assert!(
realtime
.0
.lock()
.expect("rename store is not poisoned")
.is_empty()
);
}
impl AgentSessionRepo for BlockingPromptLogs {
async fn create(&self, params: CreateAgentSessionParams) -> Result<AgentSession> {
AgentSessionRepo::create(&self.repo, params).await
}
async fn get(&self, id: AgentSessionId) -> Result<AgentSession> {
self.repo.get(id).await
}
async fn find(&self, id: AgentSessionId) -> Result<Option<AgentSession>> {
self.repo.find(id).await
}
async fn preview(
&self,
viewer: &MacroUserIdStr<'static>,
ids: &[AgentSessionId],
) -> Result<Vec<crate::domain::model::SessionPreviewCandidate>> {
self.repo.preview(viewer, ids).await
}
async fn session_bot(&self, id: BotId) -> Result<SessionBot> {
self.repo.session_bot(id).await
}
async fn recent_for_owner(
&self,
owner: &MacroUserIdStr<'_>,
limit: std::num::NonZeroUsize,
) -> Result<Vec<crate::domain::model::AgentSession>> {
self.repo.recent_for_owner(owner, limit).await
}
async fn find_by_egress_token_hash(
&self,
egress_token_hash: &str,
) -> Result<Option<AgentSession>> {
self.repo.find_by_egress_token_hash(egress_token_hash).await
}
async fn find_for_thread(
&self,
thread_id: Option<Uuid>,
bot_id: Option<BotId>,
) -> Result<ThreadSession> {
self.repo.find_for_thread(thread_id, bot_id).await
}
async fn find_all_for_thread(&self, thread_id: Uuid) -> Result<Vec<AgentSession>> {
self.repo.find_all_for_thread(thread_id).await
}
async fn set_acp_session_id(
&self,
id: AgentSessionId,
acp_session_id: SessionId,
) -> Result<()> {
self.repo.set_acp_session_id(id, acp_session_id).await
}
async fn set_egress_token_hash(&self, id: AgentSessionId, hash: &str) -> Result<()> {
self.repo.set_egress_token_hash(id, hash).await
}
async fn set_turn_prompter(
&self,
id: AgentSessionId,
prompter: &crate::domain::model::TurnPrompter,
) -> Result<()> {
self.repo.set_turn_prompter(id, prompter).await
}
async fn add_follower(&self, id: AgentSessionId, user: &MacroUserIdStr<'static>) -> Result<()> {
self.repo.add_follower(id, user).await
}
async fn turn_prompter(
&self,
id: AgentSessionId,
) -> Result<Option<crate::domain::model::TurnPrompter>> {
self.repo.turn_prompter(id).await
}
async fn set_repo_url(&self, id: AgentSessionId, repo_url: Option<String>) -> Result<()> {
self.repo.set_repo_url(id, repo_url).await
}
async fn set_model(&self, id: AgentSessionId, model: &str) -> Result<()> {
self.repo.set_model(id, model).await
}
async fn set_origin(
&self,
id: AgentSessionId,
source: SessionSource,
visibility: SessionVisibility,
) -> Result<()> {
self.repo.set_origin(id, source, visibility).await
}
async fn set_name(&self, id: AgentSessionId, name: &str) -> Result<()> {
self.repo.set_name(id, name).await
}
async fn set_archived(&self, id: AgentSessionId, archived: bool) -> Result<()> {
self.repo.set_archived(id, archived).await
}
async fn is_current_conversation_session(&self, id: AgentSessionId) -> Result<bool> {
self.repo.is_current_conversation_session(id).await
}
async fn set_name_if_default(&self, id: AgentSessionId, name: &str) -> Result<bool> {
self.repo.set_name_if_default(id, name).await
}
async fn generated_name(&self, id: AgentSessionId) -> Result<Option<String>> {
self.repo.generated_name(id).await
}
async fn replace_generated_name(
&self,
id: AgentSessionId,
current: &str,
name: &str,
) -> Result<bool> {
self.repo.replace_generated_name(id, current, name).await
}
async fn set_sandbox_size(&self, id: AgentSessionId, size: SandboxSize) -> Result<()> {
self.repo.set_sandbox_size(id, size).await
}
async fn user_sandbox_size(&self, user_id: &MacroUserIdStr<'static>) -> Result<SandboxSize> {
self.repo.user_sandbox_size(user_id).await
}
async fn set_user_sandbox_size(
&self,
user_id: &MacroUserIdStr<'static>,
size: SandboxSize,
) -> Result<()> {
self.repo.set_user_sandbox_size(user_id, size).await
}
async fn user_coding_preferences(
&self,
user_id: &MacroUserIdStr<'static>,
) -> Result<CodingPreferences> {
self.repo.user_coding_preferences(user_id).await
}
async fn set_user_coding_preferences(
&self,
user_id: &MacroUserIdStr<'static>,
preferences: CodingPreferences,
) -> Result<()> {
self.repo
.set_user_coding_preferences(user_id, preferences)
.await
}
async fn delete(&self, id: AgentSessionId) -> Result<()> {
self.repo.delete(id).await
}
async fn list_queued_actions(
&self,
id: AgentSessionId,
) -> Result<Vec<crate::domain::model::StoredQueuedAction>> {
self.repo.list_queued_actions(id).await
}
async fn replace_queued_actions(
&self,
id: AgentSessionId,
entries: &[crate::domain::model::StoredQueuedAction],
) -> Result<()> {
self.repo.replace_queued_actions(id, entries).await
}
}
/// Pure delegation: the lease semantics under test live in the shared
/// in-memory store, and this wrapper only intercepts log writes.
impl SessionOwnership for BlockingPromptLogs {
async fn claim(&self, session: AgentSessionId, replica: ReplicaId) -> Result<ClaimOutcome> {
self.repo.claim(session, replica).await
}
async fn release(&self, claim: &SessionClaim) -> Result<()> {
self.repo.release(claim).await
}
async fn heartbeat(&self, replica: ReplicaId, address: Option<&ReplicaAddress>) -> Result<()> {
self.repo.heartbeat(replica, address).await
}
async fn lease_view(&self, session: AgentSessionId, replica: ReplicaId) -> Result<LeaseView> {
self.repo.lease_view(session, replica).await
}
async fn begin_draining(&self, replica: ReplicaId) -> Result<()> {
self.repo.begin_draining(replica).await
}
}
impl AgentSessionLogRepo for BlockingPromptLogs {
async fn list_action_history(
&self,
agent_session_id: AgentSessionId,
action: agent_runtime_protocol::domain::action::AgentActionId,
) -> Result<Vec<StoredAgentSessionLog>> {
self.repo
.list_action_history(agent_session_id, action)
.await
}
async fn create_fenced_with_boundary(
&self,
log: AgentSessionLog,
claim: &SessionClaim,
boundary: Option<crate::domain::model::HistoryBoundary>,
) -> Result<StoredAgentSessionLog> {
self.create_projected(log, Some(claim), boundary, None)
.await
}
async fn create_projected(
&self,
log: AgentSessionLog,
claim: Option<&SessionClaim>,
boundary: Option<crate::domain::model::HistoryBoundary>,
turn_state: Option<TurnState>,
) -> Result<StoredAgentSessionLog> {
if claim.is_none()
&& self.hang_disconnect
&& matches!(
&log.content,
Message::ToServer(ToServerMessage::Event {
event: SystemEvent::Disconnected
})
)
{
return std::future::pending().await;
}
let fail = match self.fail_restore_log {
Some(RestoreLogFailure::InitializeRequest) => matches!(&log.content,
Message::ToRuntime(ToRuntimeMessage::Acp(AcpMessage(agent_client_protocol::RawJsonRpcMessage::Request(request))))
if request.method.as_ref() == "initialize"),
Some(RestoreLogFailure::InitializeResponse) => {
boundary.is_none()
&& matches!(
&log.content,
Message::ToServer(ToServerMessage::Acp(AcpMessage(
agent_client_protocol::RawJsonRpcMessage::Response(_)
)))
)
}
Some(RestoreLogFailure::LoadResponse) => boundary.is_some(),
None => false,
};
if fail {
return Err(AgentSessionError::Handshake(
"injected restore log failure".into(),
));
}
self.repo
.create_projected(log, claim, boundary, turn_state)
.await
}
async fn create_fenced(
&self,
log: AgentSessionLog,
claim: &SessionClaim,
) -> Result<StoredAgentSessionLog> {
self.repo.create_fenced(log, claim).await
}
async fn create_batch_fenced(
&self,
entries: Vec<StoredAgentSessionLog>,
claim: &SessionClaim,
) -> Result<Vec<StoredAgentSessionLog>> {
self.repo.create_batch_fenced(entries, claim).await
}
async fn create(&self, log: AgentSessionLog) -> Result<StoredAgentSessionLog> {
if self.hang_disconnect
&& matches!(
&log.content,
Message::ToServer(ToServerMessage::Event {
event: SystemEvent::Disconnected
})
)
{
return std::future::pending().await;
}
AgentSessionLogRepo::create(&self.repo, log).await
}
async fn list_by_session(
&self,
agent_session_id: AgentSessionId,
) -> Result<Vec<StoredAgentSessionLog>> {
AgentSessionLogRepo::list_by_session(&self.repo, agent_session_id).await
}
async fn participants(
&self,
agent_session_id: AgentSessionId,
) -> Result<Vec<MacroUserIdStr<'static>>> {
AgentSessionLogRepo::participants(&self.repo, agent_session_id).await
}
}
impl Transport<ToRuntimeMessage, ToServerMessage> for PendingTransport {
type Sender = PendingSender;
type Receiver = PendingReceiver;
fn split(self) -> (Self::Sender, Self::Receiver) {
(PendingSender, PendingReceiver)
}
}
impl TransportSender<ToRuntimeMessage> for PendingSender {
async fn send(&self, _message: ToRuntimeMessage) -> std::result::Result<(), TransportError> {
Ok(())
}
}
impl TransportReceiver<ToServerMessage> for PendingReceiver {
async fn recv(&mut self) -> std::result::Result<Option<ToServerMessage>, TransportError> {
std::future::pending().await
}
}
async fn open_test_session(
inbound: &mpsc::Sender<ToServerMessage>,
outbound: &mut mpsc::Receiver<ToRuntimeMessage>,
_session: AgentSessionId,
) {
inbound
.send(ToServerMessage::Event {
event: SystemEvent::AcpReady,
})
.await
.unwrap();
let ToRuntimeMessage::Acp(AcpMessage(agent_client_protocol::RawJsonRpcMessage::Request(
initialize,
))) = outbound.recv().await.expect("initialize request")
else {
panic!("expected initialize")
};
inbound
.send(ToServerMessage::Acp(AcpMessage(
agent_client_protocol::RawJsonRpcMessage::response(
initialize.id,
Ok(serde_json::to_value(
agent_client_protocol::schema::v1::InitializeResponse::new(PROTOCOL_VERSION),
)
.unwrap()),
),
)))
.await
.unwrap();
let ToRuntimeMessage::Acp(AcpMessage(agent_client_protocol::RawJsonRpcMessage::Request(open))) =
outbound.recv().await.expect("session/new request")
else {
panic!("expected session/new")
};
inbound
.send(ToServerMessage::Acp(AcpMessage(
agent_client_protocol::RawJsonRpcMessage::response(
open.id,
Ok(serde_json::to_value(
agent_client_protocol::schema::v1::NewSessionResponse::new("acp-1"),
)
.unwrap()),
),
)))
.await
.unwrap();
}
#[tokio::test]
async fn a_stopping_lifecycle_entry_blocks_a_second_attach() {
let fx = fixture();
let (_stopped, marker) = fx.service.begin_stop(fx.session, false);
let result = fx
.service
.attach_session(fx.session, RuntimeAttachment::solo(PendingTransport))
.await;
assert!(matches!(result, Err(AgentSessionError::AlreadyConnected(id)) if id == fx.session));
fx.service.active.remove_if(&fx.session, |_, active| {
Arc::ptr_eq(&active.marker, &marker)
});
}
#[tokio::test]
async fn close_claiming_an_attach_reservation_prevents_actor_start() {
let fx = fixture();
let reservation = fx
.service
.reserve_attach(fx.session)
.await
.expect("attach reserves before reading");
let session = fx.repo.get(fx.session).await.expect("session exists");
let claim = claim_for_test(&fx.repo, fx.session).await;
let (stopped, marker) = fx.service.begin_stop(fx.session, false);
let result = fx
.service
.activate_reserved(
session,
RuntimeAttachment::solo(PendingTransport),
reservation,
claim,
)
.await;
AgentSessionServiceImpl::<
InMemoryAgentSessionRepo,
FoldedMessageService<InMemoryAgentSessionRepo>,
NoOpRealtime,
>::wait_stopped(stopped)
.await;
assert!(matches!(result, Err(AgentSessionError::Disconnected(id)) if id == fx.session));
assert!(
fx.service
.active
.get(&fx.session)
.unwrap()
.commands
.is_none()
);
fx.service.active.remove_if(&fx.session, |_, active| {
Arc::ptr_eq(&active.marker, &marker)
});
}
#[tokio::test]
async fn shutdown_prevents_a_reserved_attach_from_spawning() {
let fx = fixture();
let reservation = fx
.service
.reserve_attach(fx.session)
.await
.expect("attach reserves before reading");
let session = fx.repo.get(fx.session).await.expect("session exists");
let claim = claim_for_test(&fx.repo, fx.session).await;
fx.service.shutdown().await;
let result = fx
.service
.activate_reserved(
session,
RuntimeAttachment::solo(PendingTransport),
reservation,
claim,
)
.await;
assert!(matches!(result, Err(AgentSessionError::Disconnected(id)) if id == fx.session));
assert!(fx.service.tasks.is_closed());
}
#[tokio::test]
async fn close_does_not_remove_a_concurrent_delete_guard() {
let fx = fixture();
let (_stopped, marker) = fx.service.begin_stop(fx.session, true);
fx.service
.close_session(fx.session)
.await
.expect("close observes the stopped actor");
assert!(fx.service.active.contains_key(&fx.session));
fx.service.active.remove_if(&fx.session, |_, active| {
Arc::ptr_eq(&active.marker, &marker)
});
}
/// The cross-replica half of what `AlreadyConnected` guards in-process: a
/// second service instance over the same store - two replicas, in production
/// - cannot attach a session whose managing replica is live. Its claim comes
/// back `ManagedElsewhere` and the attach refuses before touching the actor.
#[tokio::test]
async fn a_second_replica_cannot_attach_a_session_with_a_live_manager() {
let fx = fixture();
fx.service
.attach_session(fx.session, RuntimeAttachment::solo(PendingTransport))
.await
.expect("first replica attaches");
let second_replica = AgentSessionServiceImpl::new(
fx.repo.clone(),
FoldedMessageService::new(fx.repo.clone()),
NoOpRealtime,
NoOpAgentSessionNameGenerator,
Arc::new(NoOpTurnObserver),
Arc::new(NoopLifecyclePublisher),
ReplicaId::mint(),
);
let result = second_replica
.attach_session(fx.session, RuntimeAttachment::solo(PendingTransport))
.await;
assert!(matches!(result, Err(AgentSessionError::ManagedElsewhere(id)) if id == fx.session));
}
/// What a rolling deploy does to routing, from the service's side. The task
/// being replaced keeps heartbeating for its whole drain window, so nothing
/// about liveness stops work reaching it; the drain it publishes is what
/// does. Both halves: the replica leaving reports itself as no place to send
/// work, and the peer stops seeing it as the manager and takes the session
/// over instead of waiting out a heartbeat that is still arriving.
#[tokio::test]
async fn a_draining_replica_stops_managing_its_sessions() {
let fx = fixture();
fx.service
.attach_session(fx.session, RuntimeAttachment::solo(PendingTransport))
.await
.expect("the first replica attaches");
let peer = AgentSessionServiceImpl::new(
fx.repo.clone(),
FoldedMessageService::new(fx.repo.clone()),
NoOpRealtime,
NoOpAgentSessionNameGenerator,
Arc::new(NoOpTurnObserver),
Arc::new(NoopLifecyclePublisher),
ReplicaId::mint(),
);
assert!(matches!(
fx.service.management(fx.session).await.expect("management"),
SessionManagement::Ours
));
assert!(matches!(
peer.management(fx.session).await.expect("management"),
SessionManagement::Peer(manager) if manager.replica == fx.service.replica_id()
));
fx.service
.begin_draining()
.await
.expect("the drain is published");
assert!(
matches!(
fx.service.management(fx.session).await.expect("management"),
SessionManagement::Draining
),
"a replica on its way out sends work nowhere, its own sessions included"
);
assert!(
matches!(
peer.management(fx.session).await.expect("management"),
SessionManagement::Unmanaged
),
"the holder is leaving, so the session is the staying replica's to take"
);
peer.attach_session(fx.session, RuntimeAttachment::solo(PendingTransport))
.await
.expect("the peer takes over from a draining holder");
}
/// A command sent while the handshake never completes cannot hang its caller
/// forever - see [`HANDSHAKE_TIMEOUT`]. Without that bound, this test would
/// simply never finish. The actor it was stuck in cannot linger afterwards
/// either: its `commands` sender is gone from `active`, the same signal
/// `close_session` relies on to mean the actor tore itself down.
#[tokio::test]
async fn a_command_stuck_behind_a_stalled_handshake_times_out_as_disconnected() {
let fx = fixture();
fx.service
.attach_session(fx.session, RuntimeAttachment::solo(PendingTransport))
.await
.expect("attach succeeds");
let result = fx
.service
.send_action(
fx.session,
None,
AgentAction::prompt("hello"),
AgentActionId::mint(),
)
.await;
assert!(
matches!(result, Err(AgentSessionError::Disconnected(id)) if id == fx.session),
"a stalled handshake times out rather than hanging forever, got {result:?}"
);
assert!(
fx.service
.active
.get(&fx.session)
.is_none_or(|active| active.commands.is_none()),
"the stuck actor's connector is released, not left running"
);
}
#[tokio::test]
async fn cancellation_does_not_drop_an_effect_batch_after_machine_mutation() {
let repo = InMemoryAgentSessionRepo::new();
let session = test_session();
repo.insert_session(test_agent_session(session));
let entered = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let logs = BlockingPromptLogs {
repo: repo.clone(),
entered: entered.clone(),
release: release.clone(),
hang_disconnect: false,
fail_restore_log: None,
};
let (outbound_tx, mut outbound_rx) = mpsc::channel(8);
let (inbound_tx, inbound_rx) = mpsc::channel(8);
let (commands, command_rx) = mpsc::channel(8);
let (handshake, _) = watch::channel(HandshakeStatus::Pending);
let actor = SessionActor::new(
session,
None,
"/workspace".to_owned(),
Vec::new(),
PermissionPolicy::AutoAccept,
RecordingTransport {
outbound: outbound_tx,
inbound: inbound_rx,
},
logs,
command_rx,
handshake,
Arc::new(crate::domain::ports::NoOpTurnObserver),
Arc::new(crate::domain::ports::NoOpToolCatalog),
);
let active = Arc::new(ActiveSessions::new());
let cancellation = CancellationToken::new();
let marker = Arc::new(());
let (stopped_tx, _) = watch::channel(false);
let claim = claim_for_test(&repo, session).await;
let task = tokio::spawn(run_session(
actor,
Arc::downgrade(&active),
marker,
stopped_tx,
cancellation.clone(),
repo.clone(),
claim,
Arc::new(crate::domain::ports::NoOpTurnObserver),
));
open_test_session(&inbound_tx, &mut outbound_rx, session).await;
let (completed, result) = oneshot::channel();
commands
.send(SessionMessage::Action(SessionCommand {
user_id: None,
action: AgentAction::prompt("keep dispatching"),
action_id: AgentActionId::mint(),
completed,
span: tracing::info_span!("test.command"),
enqueued_at: tokio::time::Instant::now(),
}))
.await
.unwrap();
entered.notified().await;
cancellation.cancel();
release.notify_one();
let prompt = outbound_rx
.recv()
.await
.expect("prompt is still dispatched");
assert!(matches!(
prompt,
ToRuntimeMessage::Acp(AcpMessage(
agent_client_protocol::RawJsonRpcMessage::Request(request)
)) if request.method.as_ref() == "session/prompt"
));
result.await.unwrap().expect("delivery completes");
task.await.unwrap();
}
#[tokio::test(start_paused = true)]
async fn live_inbound_logs_do_not_reuse_the_expired_handshake_deadline() {
let repo = InMemoryAgentSessionRepo::new();
let session = test_session();
repo.insert_session(test_agent_session(session));
let entered = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let logs = BlockingPromptLogs {
repo: repo.clone(),
entered: entered.clone(),
release: release.clone(),
hang_disconnect: false,
fail_restore_log: None,
};
let (outbound_tx, mut outbound_rx) = mpsc::channel(8);
let (inbound_tx, inbound_rx) = mpsc::channel(8);
let (commands, command_rx) = mpsc::channel(8);
let (handshake, _) = watch::channel(HandshakeStatus::Pending);
let actor = SessionActor::new(
session,
None,
"/workspace".to_owned(),
Vec::new(),
PermissionPolicy::AutoAccept,
RecordingTransport {
outbound: outbound_tx,
inbound: inbound_rx,
},
logs,
command_rx,
handshake,
Arc::new(crate::domain::ports::NoOpTurnObserver),
Arc::new(crate::domain::ports::NoOpToolCatalog),
);
let active = Arc::new(ActiveSessions::new());
let cancellation = CancellationToken::new();
let (stopped_tx, _) = watch::channel(false);
let claim = claim_for_test(&repo, session).await;
let task = tokio::spawn(
run_session(
actor,
Arc::downgrade(&active),
Arc::new(()),
stopped_tx,
cancellation.clone(),
repo.clone(),
claim,
Arc::new(crate::domain::ports::NoOpTurnObserver),
)
.with_current_subscriber(),
);
open_test_session(&inbound_tx, &mut outbound_rx, session).await;
release.notify_one();
let (completed, result) = oneshot::channel();
commands
.send(SessionMessage::Action(SessionCommand {
user_id: None,
action: AgentAction::prompt("keep working"),
action_id: AgentActionId::mint(),
completed,
span: tracing::info_span!("test.command"),
enqueued_at: tokio::time::Instant::now(),
}))
.await
.unwrap();
entered.notified().await;
let _prompt = outbound_rx.recv().await.expect("prompt request");
result.await.unwrap().expect("prompt delivered");
tokio::time::advance(std::time::Duration::from_secs(61)).await;
inbound_tx
.send(ToServerMessage::Acp(AcpMessage(
agent_client_protocol::RawJsonRpcMessage::notification(
"session/update".to_owned(),
serde_json::json!({ "sessionId": "acp-1", "update": {} }),
)
.unwrap(),
)))
.await
.unwrap();
let mut persisted = false;
for _ in 0..20 {
tokio::task::yield_now().await;
persisted = AgentSessionLogRepo::list_by_session(&repo, session)
.await
.unwrap()
.iter()
.any(|stored| {
matches!(
&stored.entry.content,
Message::ToServer(ToServerMessage::Acp(AcpMessage(
agent_client_protocol::RawJsonRpcMessage::Notification(notification)
))) if notification.method.as_ref() == "session/update"
)
});
if persisted {
break;
}
}
assert!(persisted, "live update should use the regular log timeout");
cancellation.cancel();
task.await.unwrap();
}
/// Any protocol frame will do: the service only stores it, turn detection is
/// the fold's answer.
fn any_event(session: AgentSessionId) -> AgentSessionLog {
AgentSessionLog {
agent_session_id: session,
user_id: None,
content: Message::ToServer(ToServerMessage::Event {
event: agent_runtime_protocol::domain::schema::v0::SystemEvent::AcpReady,
}),
logged_at: None,
}
}
// A live session's frames go into `LiveSessionLogWriter`, which the actor
// owns. These pin that path.
/// A `LiveSessionLogWriter` over the given store, as `register_transport`
/// builds one for a connection - with nobody watching its channel.
fn connection(
repo: InMemoryAgentSessionRepo,
) -> LiveSessionLogWriter<InMemoryAgentSessionRepo, NoOpRealtime> {
streaming_connection(repo, NoOpRealtime)
}
/// The same connection, publishing its frames somewhere a test can read them.
fn streaming_connection<Rt>(
repo: InMemoryAgentSessionRepo,
realtime: Rt,
) -> LiveSessionLogWriter<InMemoryAgentSessionRepo, Rt>
where
Rt: AgentSessionRealtime + Send + Sync + 'static,
{
LiveSessionLogWriter::new(repo, realtime)
}
/// Every frame handed to a connection is stored, whether or not it derives
/// anything.
#[tokio::test]
async fn appending_persists_the_event() {
let fx = fixture();
let mut logs = connection(fx.repo.clone());
AgentSessionLogWriter::append(&mut logs, any_event(fx.session))
.await
.expect("append succeeds");
AgentSessionLogWriter::append(&mut logs, any_event(fx.session))
.await
.expect("append succeeds");
let log = AgentSessionLogRepo::list_by_session(&fx.repo, fx.session)
.await
.expect("in-memory repo cannot fail");
assert_eq!(log.len(), 2);
}
#[tokio::test]
async fn marking_disconnected_persists_and_publishes_the_event() {
let repo = InMemoryAgentSessionRepo::new();
let session = test_session();
repo.insert_session(test_agent_session(session));
let realtime = RecordingRealtime::new();
let service = AgentSessionServiceImpl::new(
repo.clone(),
FoldedMessageService::new(repo.clone()),
realtime.clone(),
NoOpAgentSessionNameGenerator,
Arc::new(NoOpTurnObserver),
Arc::new(NoopLifecyclePublisher),
ReplicaId::mint(),
);
service
.mark_disconnected(session)
.await
.expect("disconnect is recorded");
let stored = AgentSessionLogRepo::list_by_session(&repo, session)
.await
.expect("stored log can be read");
assert!(matches!(
&stored[..],
[StoredAgentSessionLog {
entry: AgentSessionLog {
content: Message::ToServer(ToServerMessage::Event {
event: SystemEvent::Disconnected,
}),
..
},
..
}]
));
assert_eq!(realtime.published().len(), 1);
}
/// A frame recorded out of band - a held tool call - reaches the session's
/// viewers straight away, not on some later flush nobody will make.
#[tokio::test]
async fn a_recorded_frame_is_stored_and_published_at_once() {
let repo = InMemoryAgentSessionRepo::new();
let session = test_session();
repo.insert_session(test_agent_session(session));
let realtime = RecordingRealtime::new();
let service = AgentSessionServiceImpl::new(
repo.clone(),
FoldedMessageService::new(repo.clone()),
realtime.clone(),
NoOpAgentSessionNameGenerator,
Arc::new(NoOpTurnObserver),
Arc::new(NoopLifecyclePublisher),
ReplicaId::mint(),
);
let notice = agent_runtime_protocol::domain::tool_approval::ToolApprovalNotice {
approval_id: "a1".to_owned(),
server_slug: "macro".to_owned(),
server_name: "Macro".to_owned(),
tool_name: "WebSearch".to_owned(),
arguments: serde_json::json!({}),
requested_by: None,
status: agent_runtime_protocol::domain::tool_approval::ToolApprovalStatus::Pending,
resolved_by: None,
remembered: false,
};
service
.record_frame(session, notice.to_server_message())
.await
.expect("the frame is recorded");
let stored = AgentSessionLogRepo::list_by_session(&repo, session)
.await
.expect("stored log can be read");
assert_eq!(stored.len(), 1);
assert_eq!(
realtime.published().len(),
1,
"viewers hear it without a flush"
);
}
/// A review's change announcement is stored and reaches viewers at once,
/// and projects nothing: viewers are not told to refetch the session.
#[tokio::test]
async fn an_unprojected_frame_is_stored_and_published_without_a_session_update() {
let repo = InMemoryAgentSessionRepo::new();
let session = test_session();
repo.insert_session(test_agent_session(session));
for entry in parse_log_as(
session,
r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":1,"method":"session/prompt","params":{"sessionId":"s","prompt":[{"type":"text","text":"Draft the email"}]}}}"#,
) {
AgentSessionLogRepo::create(&repo, entry)
.await
.expect("the prompt is stored");
}
let realtime = RecordingRealtime::new();
let service = AgentSessionServiceImpl::new(
repo.clone(),
FoldedMessageService::new(repo.clone()),
realtime.clone(),
NoOpAgentSessionNameGenerator,
Arc::new(NoOpTurnObserver),
Arc::new(NoopLifecyclePublisher),
ReplicaId::mint(),
);
let update = agent_runtime_protocol::domain::review::ReviewUpdatedNotification {
review_id: Uuid::from_u128(0xA),
revision: 4,
};
service
.record_unprojected_frame(session, update.to_server_message())
.await
.expect("the frame is recorded");
let stored = AgentSessionLogRepo::list_by_session(&repo, session)
.await
.expect("stored log can be read");
assert_eq!(stored.len(), 2);
let published = realtime.published();
assert_eq!(published.len(), 1);
assert_eq!(published[0].entries.len(), 1);
assert_eq!(published[0].entries[0].id, stored[1].id);
assert_eq!(
serde_json::to_value(&published[0].entries[0].entry.content).unwrap(),
serde_json::json!({
"direction": "to_server",
"content": {
"type": "acp",
"jsonrpc": "2.0",
"method": "_macro/review_updated",
"params": {"reviewId": "00000000-0000-0000-0000-00000000000a", "revision": 4},
},
})
);
assert!(realtime.updated().is_empty());
}
#[tokio::test(start_paused = true)]
async fn marking_disconnected_is_bounded_when_persistence_hangs() {
let repo = InMemoryAgentSessionRepo::new();
let session = test_session();
repo.insert_session(test_agent_session(session));
let hanging = BlockingPromptLogs {
repo: repo.clone(),
entered: Arc::new(Notify::new()),
release: Arc::new(Notify::new()),
hang_disconnect: true,
fail_restore_log: None,
};
let service = AgentSessionServiceImpl::new(
hanging,
FoldedMessageService::new(repo),
NoOpRealtime,
NoOpAgentSessionNameGenerator,
Arc::new(NoOpTurnObserver),
Arc::new(NoopLifecyclePublisher),
ReplicaId::mint(),
);
let disconnect = tokio::spawn(async move { service.mark_disconnected(session).await });
tokio::task::yield_now().await;
tokio::time::advance(SESSION_PERSIST_TIMEOUT).await;
assert!(matches!(
disconnect.await.unwrap(),
Err(AgentSessionError::LogTimedOut(id)) if id == session
));
}
/// The point of the rework: a connection folds its session once, when it
/// starts, and every frame after that is folded into the state it kept.
///
/// Reading the whole log is what folding from scratch costs, so a read per
/// frame is exactly the quadratic behaviour this replaced.
#[tokio::test]
async fn a_connection_reads_the_log_once_however_many_frames_arrive() {
let repo = InMemoryAgentSessionRepo::new();
repo.insert_session(test_agent_session(test_session()));
let mut logs = connection(repo.clone());
let log = parse_log_as(test_session(), TURN);
let frames = log.len();
assert!(frames > 5, "the fixture is worth counting reads over");
for entry in log {
AgentSessionLogWriter::append(&mut logs, entry)
.await
.expect("append succeeds");
}
assert_eq!(
repo.log_reads(),
1,
"{frames} frames should cost one fold, not one per frame"
);
}
// Streaming: the writer every frame of a connected session passes through
// pushes each one at whoever is watching the channel right now.
/// Every frame a connection writes goes out once, addressed at the session's
/// channel and carrying the frame verbatim - a viewer folds what it is sent
/// with the same code that folds the fetched log, so anything altered on the
/// way out would fold to something else.
#[tokio::test]
async fn a_connections_frames_are_published_to_its_channel() {
let repo = InMemoryAgentSessionRepo::new();
repo.insert_session(test_agent_session(test_session()));
let realtime = RecordingRealtime::new();
let mut logs = streaming_connection(repo.clone(), realtime.clone());
let log = parse_log_as(test_session(), TURN);
for entry in log.clone() {
AgentSessionLogWriter::append(&mut logs, entry)
.await
.expect("append succeeds");
}
AgentSessionLogWriter::flush(&mut logs)
.await
.expect("flush succeeds");
let published = realtime.published();
assert!(
published
.iter()
.all(|event| event.agent_session_id == test_session()),
"every event names the session"
);
let published: Vec<StoredAgentSessionLog> = published
.into_iter()
.flat_map(|event| event.entries)
.collect();
assert_eq!(
published.len(),
log.len(),
"every frame goes out exactly once"
);
let stored = AgentSessionLogRepo::list_by_session(&repo, test_session())
.await
.expect("stored log can be read");
assert_eq!(
published
.iter()
.map(|event| event.created_at)
.collect::<Vec<_>>(),
stored
.iter()
.map(|entry| entry.created_at)
.collect::<Vec<_>>(),
"published timestamps are the timestamps assigned by persistence"
);
// Compared as the JSON they are published as: the client folds these
// bytes with the same code it folds the fetched log with.
let frame = |entry: AgentSessionLog| {
(
entry.user_id.map(|user| user.to_string()),
serde_json::to_value(entry.content).expect("a frame serializes"),
)
};
assert_eq!(
published
.into_iter()
.map(|event| frame(event.entry))
.collect::<Vec<_>>(),
log.into_iter().map(frame).collect::<Vec<_>>(),
"the frames go out as they were logged"
);
}
/// Streaming costs the connection one session lookup, not one per frame.
///
/// Most frames are stream chunks that otherwise cost nothing but the log
/// insert, so the audience lookup must not be per frame.
#[tokio::test]
async fn streaming_costs_one_session_lookup_for_the_whole_connection() {
/// Replay the fixture through a connection publishing to `realtime`, and
/// report what it read and how many frames it took to get there.
async fn replay<Rt>(realtime: Rt) -> (usize, usize)
where
Rt: AgentSessionRealtime + Send + Sync + 'static,
{
let repo = InMemoryAgentSessionRepo::new();
repo.insert_session(test_agent_session(test_session()));
let mut logs = streaming_connection(repo.clone(), realtime);
let log = parse_log_as(test_session(), TURN);
let frames = log.len();
for entry in log {
AgentSessionLogWriter::append(&mut logs, entry)
.await
.expect("append succeeds");
}
(repo.session_reads(), frames)
}
let (streamed, frames) = replay(RecordingRealtime::new()).await;
let (silent, _) = replay(NoOpRealtime).await;
assert!(frames > 5, "the fixture is worth counting reads over");
assert!(
streamed <= silent + 1,
"{frames} streamed frames read the session {streamed} times against \
{silent} unstreamed - that is a lookup per frame, not one per connection"
);
}
/// A publisher that is down costs a viewer some liveness and nothing else:
/// the append succeeds and the log is written.
#[tokio::test]
async fn a_failed_publish_does_not_fail_the_append() {
let repo = InMemoryAgentSessionRepo::new();
repo.insert_session(test_agent_session(test_session()));
let mut logs = streaming_connection(repo.clone(), RecordingRealtime::down());
let log = parse_log_as(test_session(), TURN);
let frames = log.len();
for entry in log {
AgentSessionLogWriter::append(&mut logs, entry)
.await
.expect("a refused publish does not fail the append");
}
let stored = AgentSessionLogRepo::list_by_session(&repo, test_session())
.await
.expect("in-memory repo cannot fail");
assert_eq!(stored.len(), frames, "every frame is still durable");
}
/// `session_log` hands back the log unfolded, in order, with the agent that
/// wrote it.
#[tokio::test]
async fn session_log_returns_the_sessions_frames_in_order() {
let store = InMemoryAgentSessionRepo::new();
store.insert_session(test_agent_session(test_session()));
let recorded = parse_log_as(test_session(), TURN);
store.extend_log(recorded.clone());
let service = AgentSessionServiceImpl::new(
store.clone(),
FoldedMessageService::new(store.clone()),
NoOpRealtime,
NoOpAgentSessionNameGenerator,
Arc::new(NoOpTurnObserver),
Arc::new(NoopLifecyclePublisher),
ReplicaId::mint(),
);
let log = service
.session_log(test_session())
.await
.expect("lookup succeeds");
assert_eq!(
log.entries.len(),
recorded.len(),
"every frame is served, none folded away"
);
assert!(!log.bot.name.is_empty(), "the response names the agent");
assert!(
!log.bot.handle.is_empty(),
"the response includes the agent's handle"
);
// The order is the contract: folding is a left fold from the first frame,
// so a reordered log derives different turn numbering.
let served = fold(log.entries.into_iter().map(|stored| stored.entry));
assert_eq!(
served,
fold(recorded),
"the served log folds to what the stored one does"
);
}
/// A session that never existed is an error: the response has to name the
/// session's agent, and there is none to name.
#[tokio::test]
async fn session_log_of_an_unknown_session_errors() {
let fx = fixture();
let log = fx.service.session_log(AgentSessionId::TEST_A).await;
assert!(log.is_err());
}
/// A config-bearing response moves the fold's model, and the writer projects
/// it onto the session row; an error response projects nothing.
#[tokio::test]
async fn appending_a_config_response_projects_the_model() {
let fx = fixture();
let mut logs = connection(fx.repo.clone());
let frames = parse_log_as(
fx.session,
concat!(
r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"n","method":"session/new","params":{"cwd":"/w","mcpServers":[]}}}"#,
"\n",
r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"n","result":{"sessionId":"s1","configOptions":[{"id":"model","name":"Model","type":"select","currentValue":"sonnet","options":[{"value":"sonnet","name":"Sonnet"},{"value":"opus","name":"Opus"}]}]}}}"#,
"\n",
r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"c","method":"session/set_config_option","params":{"sessionId":"s1","configId":"model","value":"claude-fable-5"}}}"#,
"\n",
r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"c","error":{"code":-32602,"message":"Invalid params: model not found: claude-fable-5"}}}"#,
),
);
for frame in frames {
AgentSessionLogWriter::append(&mut logs, frame)
.await
.expect("append succeeds");
}
let session = AgentSessionRepo::get(&fx.repo, fx.session)
.await
.expect("get session");
assert_eq!(session.model, "sonnet", "the rejected change moved nothing");
}
#[tokio::test]
async fn shared_transport_copies_durable_initialization_before_load() {
use crate::domain::session::Input;
use agent_client_protocol::RawJsonRpcMessage;
use agent_client_protocol::schema::v1::{AgentCapabilities, InitializeResponse};
let repo = InMemoryAgentSessionRepo::new();
let first = AgentSessionId::new();
let second = AgentSessionId::new();
for id in [first, second] {
repo.insert_session(test_agent_session(id));
}
let (handshake, _) = watch::channel(HandshakeStatus::Pending);
let (send, mut received) = mpsc::channel(8);
let (_inbound, inbound) = mpsc::channel(8);
let (_commands, commands) = mpsc::channel(8);
let claim = claim_for_test(&repo, first).await;
let mut actor = SessionActor::new(
first,
Some("first-acp".into()),
"/workspace".into(),
vec![],
PermissionPolicy::Prompt,
RecordingTransport {
outbound: send,
inbound,
},
LiveSessionLogWriter::fenced(repo.clone(), NoOpRealtime, claim),
commands,
handshake.clone(),
Arc::new(crate::domain::ports::NoOpTurnObserver),
Arc::new(crate::domain::ports::NoOpToolCatalog),
);
actor
.dispatch(Input::Inbound(ToServerMessage::Event {
event: SystemEvent::AcpReady,
}))
.await;
let init_request = received.recv().await.unwrap();
let ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Request(init))) = &init_request else {
panic!("initialize request")
};
let init_response = ToServerMessage::Acp(AcpMessage(RawJsonRpcMessage::response(
init.id.clone(),
Ok(serde_json::to_value(
InitializeResponse::new(PROTOCOL_VERSION)
.agent_capabilities(AgentCapabilities::new().load_session(true)),
)
.unwrap()),
)));
actor.dispatch(Input::Inbound(init_response.clone())).await;
let ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Request(load))) =
received.recv().await.unwrap()
else {
panic!("load request")
};
actor
.dispatch(Input::Inbound(ToServerMessage::Acp(AcpMessage(
RawJsonRpcMessage::response(load.id, Ok(serde_json::json!({}))),
))))
.await;
let first_history = AgentSessionLogRepo::list_by_session(&repo, first)
.await
.unwrap();
assert_eq!(first_history.len(), 4);
// A late-bound second session uses the retained actual handshake, with local row IDs.
let (send, mut received) = mpsc::channel(8);
let (_inbound, inbound) = mpsc::channel(8);
let (_commands, commands) = mpsc::channel(8);
let claim = claim_for_test(&repo, second).await;
let mut actor = SessionActor::new(
second,
Some("second-acp".into()),
"/workspace".into(),
vec![],
PermissionPolicy::Prompt,
RecordingTransport {
outbound: send,
inbound,
},
LiveSessionLogWriter::fenced(repo.clone(), NoOpRealtime, claim),
commands,
handshake,
Arc::new(crate::domain::ports::NoOpTurnObserver),
Arc::new(crate::domain::ports::NoOpToolCatalog),
);
let ready = actor.next_input().await;
assert!(matches!(
ready,
ActorInput::Protocol(Input::SharedReady { .. })
));
actor.dispatch_input(ready).await;
let ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Request(load))) =
received.recv().await.unwrap()
else {
panic!("load request")
};
assert_eq!(load.method.as_ref(), "session/load");
actor
.dispatch(Input::Inbound(ToServerMessage::Acp(AcpMessage(
RawJsonRpcMessage::response(load.id, Ok(serde_json::json!({}))),
))))
.await;
let history = AgentSessionLogRepo::list_by_session(&repo, second)
.await
.unwrap();
assert_eq!(history.len(), 4);
assert_ne!(history[0].id, first_history[0].id);
assert!(
history
.iter()
.all(|row| row.entry.agent_session_id == second)
);
assert_eq!(
serde_json::to_value(&history[0].entry.content).unwrap(),
serde_json::to_value(Message::ToRuntime(init_request)).unwrap()
);
assert_eq!(
serde_json::to_value(&history[1].entry.content).unwrap(),
serde_json::to_value(Message::ToServer(init_response)).unwrap()
);
}
#[tokio::test]
async fn shared_initialization_append_failure_stops_before_sending_queued_prompt() {
for failure in [
RestoreLogFailure::InitializeRequest,
RestoreLogFailure::InitializeResponse,
] {
assert_restore_persistence_failure_does_not_send_prompt(failure).await;
}
}
#[tokio::test]
async fn successful_load_response_append_failure_stops_before_sending_queued_prompt() {
assert_restore_persistence_failure_does_not_send_prompt(RestoreLogFailure::LoadResponse).await;
}
async fn assert_restore_persistence_failure_does_not_send_prompt(failure: RestoreLogFailure) {
use crate::domain::model::HistoryBoundary;
use crate::domain::session::actors::Stepped;
use crate::domain::session::{InitializationContext, Input, SessionRestoreSupport};
use agent_client_protocol::{
RawJsonRpcMessage,
schema::v1::{AgentCapabilities, InitializeResponse, RequestId},
};
let repo = InMemoryAgentSessionRepo::new();
let session = AgentSessionId::new();
repo.insert_session(test_agent_session(session));
let claim = claim_for_test(&repo, session).await;
// A prior committed boundary must survive both failure paths.
repo.create_fenced(any_event(session), &claim)
.await
.unwrap();
let previous = repo
.create_fenced(any_event(session), &claim)
.await
.unwrap();
repo.create_fenced_with_boundary(
any_event(session),
&claim,
Some(HistoryBoundary {
initialization_log_id: previous.id,
}),
)
.await
.unwrap();
let logs = BlockingPromptLogs {
repo: repo.clone(),
entered: Arc::new(Notify::new()),
release: Arc::new(Notify::new()),
hang_disconnect: false,
fail_restore_log: Some(failure),
};
let (handshake, _) = watch::channel(HandshakeStatus::Pending);
let (send, mut received) = mpsc::channel(8);
let (_inbound, inbound) = mpsc::channel(8);
let (commands, command_rx) = mpsc::channel(8);
let mut actor = SessionActor::new(
session,
Some("restored-acp".into()),
"/workspace".into(),
vec![],
PermissionPolicy::Prompt,
RecordingTransport {
outbound: send,
inbound,
},
LiveSessionLogWriter::fenced(logs, NoOpRealtime, claim),
command_rx,
handshake.clone(),
Arc::new(crate::domain::ports::NoOpTurnObserver),
Arc::new(crate::domain::ports::NoOpToolCatalog),
);
let (completed, completion) = oneshot::channel();
commands
.send(SessionMessage::Action(SessionCommand {
user_id: None,
action: AgentAction::prompt("must remain unsent"),
action_id: AgentActionId::mint(),
completed,
span: tracing::Span::none(),
enqueued_at: tokio::time::Instant::now(),
}))
.await
.unwrap();
let queued = actor.next_input().await;
assert!(matches!(
queued,
ActorInput::Protocol(Input::Command { .. })
));
assert_eq!(actor.dispatch_input(queued).await, Stepped::Continue);
assert!(received.try_recv().is_err());
let init_id = RequestId::Str("shared-transport-initialization".into());
handshake
.send(HandshakeStatus::ReadyWithContext {
restore: SessionRestoreSupport {
resume: false,
load: true,
},
context: Arc::new(InitializationContext {
request: ToRuntimeMessage::Acp(AcpMessage(
RawJsonRpcMessage::request(
"initialize".to_owned(),
serde_json::json!({"protocolVersion": 1}),
init_id.clone(),
)
.unwrap(),
)),
response: ToServerMessage::Acp(AcpMessage(RawJsonRpcMessage::response(
init_id,
Ok(serde_json::to_value(
InitializeResponse::new(PROTOCOL_VERSION)
.agent_capabilities(AgentCapabilities::new().load_session(true)),
)
.unwrap()),
))),
}),
})
.unwrap();
let ready = actor.next_input().await;
assert!(matches!(
ready,
ActorInput::Protocol(Input::SharedReady { .. })
));
let step = actor.dispatch_input(ready).await;
let mut failed_response_id = None;
if matches!(failure, RestoreLogFailure::LoadResponse) {
assert_eq!(step, Stepped::Continue);
let ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Request(load))) =
received.try_recv().unwrap()
else {
panic!("load request")
};
assert_eq!(load.method.as_ref(), "session/load");
failed_response_id = Some(load.id.clone());
assert!(matches!(
actor
.dispatch(Input::Inbound(ToServerMessage::Acp(AcpMessage(
RawJsonRpcMessage::response(load.id, Ok(serde_json::json!({}))),
))))
.await,
Stepped::Stopped(_)
));
} else {
assert!(
matches!(step, Stepped::Stopped(_)),
"initialization failure stops before load"
);
}
assert!(
received.try_recv().is_err(),
"no queued prompt reached the transport"
);
let result = tokio::time::timeout(std::time::Duration::from_secs(1), completion)
.await
.unwrap()
.unwrap();
assert!(result.is_err(), "queued prompt must not report delivery");
let history = AgentSessionLogRepo::list_by_session(&repo, session)
.await
.unwrap();
assert_eq!(
history[0].id, previous.id,
"prior boundary remains selected"
);
assert!(
history.iter().all(|row| !matches!(&row.entry.content,
Message::ToRuntime(ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Request(request))))
if request.method.as_ref() == "session/prompt")),
"queued prompt was not appended"
);
if let Some(failed_id) = failed_response_id {
assert!(history.iter().all(|row| !matches!(&row.entry.content,
Message::ToServer(ToServerMessage::Acp(AcpMessage(frame))) if frame.response_id() == Some(&failed_id))),
"failed load response append must not be durable");
}
assert!(matches!(
history.last().unwrap().entry.content,
Message::ToServer(ToServerMessage::Event {
event: SystemEvent::Disconnected
})
));
}
/// The actor's GenAI projection, end to end: a prompt delivered through the
/// actor opens an `invoke_agent` span under the command that carried it, and
/// the runtime's answer closes it with what the agent said.
#[tokio::test]
async fn a_prompt_turn_is_traced_as_an_agent_span_under_its_command() {
use genai_telemetry::attr;
use opentelemetry::trace::{TraceContextExt as _, TracerProvider as _};
use opentelemetry_sdk::trace::{InMemorySpanExporter, SdkTracerProvider};
use tracing_opentelemetry::OpenTelemetrySpanExt as _;
use tracing_subscriber::layer::SubscriberExt as _;
let exporter = InMemorySpanExporter::default();
let provider = SdkTracerProvider::builder()
.with_simple_exporter(exporter.clone())
.build();
let layer = tracing_opentelemetry::layer().with_tracer(provider.tracer("test"));
let _guard = tracing::subscriber::set_default(tracing_subscriber::registry().with(layer));
tracing::callsite::rebuild_interest_cache();
let repo = InMemoryAgentSessionRepo::new();
let session = test_session();
repo.insert_session(test_agent_session(session));
let release = Arc::new(Notify::new());
let logs = BlockingPromptLogs {
repo: repo.clone(),
entered: Arc::new(Notify::new()),
release: release.clone(),
hang_disconnect: false,
fail_restore_log: None,
};
let (outbound_tx, mut outbound_rx) = mpsc::channel(8);
let (inbound_tx, inbound_rx) = mpsc::channel(8);
let (commands, command_rx) = mpsc::channel(8);
let (handshake, _) = watch::channel(HandshakeStatus::Pending);
let actor = SessionActor::new(
session,
None,
"/workspace".to_owned(),
Vec::new(),
crate::domain::session::PermissionPolicy::AutoAccept,
RecordingTransport {
outbound: outbound_tx,
inbound: inbound_rx,
},
logs,
command_rx,
handshake,
Arc::new(crate::domain::ports::NoOpTurnObserver),
Arc::new(crate::domain::ports::NoOpToolCatalog),
);
let active = Arc::new(ActiveSessions::new());
let cancellation = CancellationToken::new();
let (stopped_tx, _) = watch::channel(false);
let claim = claim_for_test(&repo, session).await;
let task = tokio::spawn(
run_session(
actor,
Arc::downgrade(&active),
Arc::new(()),
stopped_tx,
cancellation.clone(),
repo.clone(),
claim,
Arc::new(crate::domain::ports::NoOpTurnObserver),
)
.with_current_subscriber(),
);
open_test_session(&inbound_tx, &mut outbound_rx, session).await;
release.notify_one();
let command_span = tracing::info_span!("agent.session.command");
let command_id = command_span.context().span().span_context().span_id();
let action_id = AgentActionId::mint();
let (completed, result) = oneshot::channel();
commands
.send(SessionMessage::Action(SessionCommand {
user_id: None,
action: AgentAction::prompt("what time is it?"),
action_id,
completed,
span: command_span,
enqueued_at: tokio::time::Instant::now(),
}))
.await
.unwrap();
let prompt = outbound_rx.recv().await.expect("prompt is dispatched");
assert!(matches!(
&prompt,
ToRuntimeMessage::Acp(AcpMessage(
agent_client_protocol::RawJsonRpcMessage::Request(request)
)) if request.method.as_ref() == "session/prompt"
));
result.await.unwrap().expect("delivery completes");
let update = agent_client_protocol::RawJsonRpcMessage::notification(
"session/update".to_owned(),
serde_json::json!({
"sessionId": "acp-1",
"update": {
"sessionUpdate": "agent_message_chunk",
"content": { "type": "text", "text": "It is noon." }
}
}),
)
.unwrap();
inbound_tx
.send(ToServerMessage::Acp(AcpMessage(update)))
.await
.unwrap();
inbound_tx
.send(ToServerMessage::Acp(AcpMessage(
agent_client_protocol::RawJsonRpcMessage::response(
action_id.to_request_id(),
Ok(serde_json::json!({ "stopReason": "end_turn" })),
),
)))
.await
.unwrap();
// The transport closing stops the actor, which flushes anything open.
drop(inbound_tx);
task.await.unwrap();
provider.force_flush().expect("flush");
let spans = exporter.get_finished_spans().expect("finished spans");
let agent: Vec<_> = spans
.iter()
.filter(|span| span.name == "invoke_agent")
.collect();
assert_eq!(agent.len(), 1, "one prompt, one agent span: {spans:#?}");
assert_eq!(agent[0].parent_span_id, command_id);
let attribute = |key: &str| {
agent[0]
.attributes
.iter()
.find(|kv| kv.key.as_str() == key)
.map(|kv| kv.value.to_string())
};
assert_eq!(
attribute(attr::CONVERSATION_ID).as_deref(),
Some(session.to_string().as_str())
);
assert_eq!(
attribute(attr::RESPONSE_FINISH_REASONS).as_deref(),
Some(r#"["stop"]"#)
);
let output = attribute(attr::OUTPUT_MESSAGES).expect("output recorded");
assert!(output.contains("It is noon."), "{output}");
let input = attribute(attr::INPUT_MESSAGES).expect("input recorded");
assert!(input.contains("what time is it?"), "{input}");
}
/// A command dequeued before the handshake finished says how long it waited
/// for it; one dequeued on a live session waited for nothing.
#[tokio::test]
async fn a_command_span_records_its_wait_for_the_handshake() {
use opentelemetry::trace::TracerProvider as _;
use opentelemetry_sdk::trace::{InMemorySpanExporter, SdkTracerProvider};
use tracing_subscriber::layer::SubscriberExt as _;
let exporter = InMemorySpanExporter::default();
let provider = SdkTracerProvider::builder()
.with_simple_exporter(exporter.clone())
.build();
let layer = tracing_opentelemetry::layer().with_tracer(provider.tracer("test"));
let _guard = tracing::subscriber::set_default(tracing_subscriber::registry().with(layer));
tracing::callsite::rebuild_interest_cache();
let repo = InMemoryAgentSessionRepo::new();
let session = test_session();
repo.insert_session(test_agent_session(session));
let entered = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let logs = BlockingPromptLogs {
repo: repo.clone(),
entered: entered.clone(),
release: release.clone(),
hang_disconnect: false,
fail_restore_log: None,
};
let (outbound_tx, mut outbound_rx) = mpsc::channel(8);
let (inbound_tx, inbound_rx) = mpsc::channel(8);
let (commands, command_rx) = mpsc::channel(8);
let (handshake, _) = watch::channel(HandshakeStatus::Pending);
let actor = SessionActor::new(
session,
None,
"/workspace".to_owned(),
Vec::new(),
crate::domain::session::PermissionPolicy::AutoAccept,
RecordingTransport {
outbound: outbound_tx,
inbound: inbound_rx,
},
logs,
command_rx,
handshake,
Arc::new(crate::domain::ports::NoOpTurnObserver),
Arc::new(crate::domain::ports::NoOpToolCatalog),
);
let active = Arc::new(ActiveSessions::new());
let (stopped_tx, _) = watch::channel(false);
let claim = claim_for_test(&repo, session).await;
let task = tokio::spawn(
run_session(
actor,
Arc::downgrade(&active),
Arc::new(()),
stopped_tx,
CancellationToken::new(),
repo.clone(),
claim,
Arc::new(crate::domain::ports::NoOpTurnObserver),
)
.with_current_subscriber(),
);
let send_prompt = |name: &'static str| {
let (completed, result) = oneshot::channel();
let command = SessionMessage::Action(SessionCommand {
user_id: None,
action: AgentAction::prompt(name),
action_id: AgentActionId::mint(),
completed,
span: tracing::info_span!(
"agent.session.command",
agent.command.name = name,
agent.command.queue_wait_ms = tracing::field::Empty,
agent.session.runtime_phase_at_dequeue = tracing::field::Empty,
agent.command.handshake_wait_ms = tracing::field::Empty,
),
enqueued_at: tokio::time::Instant::now(),
});
(command, result)
};
// Queued before the runtime is even ready: it waits out the handshake.
let (early, early_result) = send_prompt("early");
commands.send(early).await.unwrap();
open_test_session(&inbound_tx, &mut outbound_rx, session).await;
entered.notified().await;
release.notify_one();
outbound_rx
.recv()
.await
.expect("early prompt is dispatched");
early_result
.await
.unwrap()
.expect("early delivery completes");
let (live, live_result) = send_prompt("live");
commands.send(live).await.unwrap();
entered.notified().await;
release.notify_one();
outbound_rx.recv().await.expect("live prompt is dispatched");
live_result.await.unwrap().expect("live delivery completes");
drop(inbound_tx);
task.await.unwrap();
provider.force_flush().expect("flush");
let spans = exporter.get_finished_spans().expect("finished spans");
let attribute = |name: &str, key: &str| {
let span = spans
.iter()
.find(|span| {
span.name == "agent.session.command"
&& span.attributes.iter().any(|kv| {
kv.key.as_str() == "agent.command.name" && kv.value.as_str() == name
})
})
.unwrap_or_else(|| panic!("no {name} command span: {spans:#?}"));
span.attributes
.iter()
.find(|kv| kv.key.as_str() == key)
.map(|kv| kv.value.clone())
};
assert!(matches!(
attribute("early", "agent.session.runtime_phase_at_dequeue")
.expect("phase recorded")
.as_str()
.as_ref(),
"booting" | "handshaking"
));
assert!(matches!(
attribute("early", "agent.command.handshake_wait_ms"),
Some(opentelemetry::Value::I64(wait)) if wait >= 0
));
assert_eq!(
attribute("live", "agent.session.runtime_phase_at_dequeue")
.expect("phase recorded")
.as_str(),
"live"
);
assert_eq!(
attribute("live", "agent.command.handshake_wait_ms"),
Some(opentelemetry::Value::I64(0))
);
assert!(matches!(
attribute("live", "agent.command.queue_wait_ms"),
Some(opentelemetry::Value::I64(_))
));
}
mod initial_model;
mod owner_binding;
mod turn_projection;
/// The live writer's fold says what each appended frame meant for the turn;
/// history it catches up on says nothing.
mod fold_signals {
use super::*;
use crate::domain::ports::AgentSessionLogWriter as _;
use agent_fold::domain::model::{StopReason as FoldStop, TurnSignal};
use agent_fold::testing::parse_log_as;
use agent_runtime_protocol::domain::schema::v0::SystemEvent;
#[tokio::test]
async fn appending_a_turn_signals_its_end_once_with_its_last_text() {
let repo = InMemoryAgentSessionRepo::new();
let session = test_session();
repo.insert_session(test_agent_session(session));
let mut logs = LiveSessionLogWriter::new(repo.clone(), NoOpRealtime);
let mut signals = Vec::new();
for frame in parse_log_as(session, TURN) {
signals.extend(logs.append(frame).await.expect("append succeeds").signals);
}
// Progress is reported while the turn runs; its end comes once, last.
let (ends, progress): (Vec<_>, Vec<_>) = signals
.iter()
.partition(|signal| !matches!(signal, TurnSignal::Progressed { .. }));
assert!(!progress.is_empty(), "{signals:#?}");
assert!(
matches!(
ends.as_slice(),
[TurnSignal::TurnEnded { stop: FoldStop::EndTurn, last_text: Some(text), .. }]
if !text.is_empty()
),
"{signals:#?}"
);
assert!(
matches!(signals.last(), Some(TurnSignal::TurnEnded { .. })),
"{signals:#?}"
);
}
#[tokio::test]
async fn a_writer_catching_up_on_a_stored_turn_signals_nothing_for_it() {
let repo = InMemoryAgentSessionRepo::new();
let session = test_session();
repo.insert_session(test_agent_session(session));
let mut first = LiveSessionLogWriter::new(repo.clone(), NoOpRealtime);
for frame in parse_log_as(session, TURN) {
first.append(frame).await.expect("append succeeds");
}
// A reconnect: a fresh writer over the same stored log. Its first
// frame is the runtime coming back, not a turn ending.
let mut second = LiveSessionLogWriter::new(repo.clone(), NoOpRealtime);
let appended = second
.append(AgentSessionLog {
agent_session_id: session,
user_id: None,
content: Message::ToServer(ToServerMessage::Event {
event: SystemEvent::AcpReady,
}),
logged_at: None,
})
.await
.expect("append succeeds");
assert!(appended.signals.is_empty(), "{:#?}", appended.signals);
}
}
// Batching: streamed output is stored at once but pushed to viewers in runs
// - one publish per flush - while anything they must see now goes through
// immediately.
/// A streamed ACP notification: the frame kind that is the bulk of every
/// session and the whole of a `session/load` replay.
fn streamed_frame(text: &str) -> AgentSessionLog {
AgentSessionLog {
agent_session_id: test_session(),
user_id: None,
content: Message::ToServer(ToServerMessage::Acp(AcpMessage(
agent_client_protocol::RawJsonRpcMessage::notification(
"session/update".to_owned(),
serde_json::json!({
"sessionId": "acp-1",
"update": {
"sessionUpdate": "agent_thought_chunk",
"content": { "type": "text", "text": text }
}
}),
)
.unwrap(),
))),
logged_at: None,
}
}
/// Streamed frames are durable at once but published only on flush, all
/// together, in log order, as one event.
#[tokio::test]
async fn streamed_frames_are_stored_at_once_and_published_on_flush() {
let repo = InMemoryAgentSessionRepo::new();
repo.insert_session(test_agent_session(test_session()));
let realtime = RecordingRealtime::new();
let mut logs = streaming_connection(repo.clone(), realtime.clone());
let mut appended = Vec::new();
for text in ["one", "two", "three"] {
appended.push(
AgentSessionLogWriter::append(&mut logs, streamed_frame(text))
.await
.expect("append succeeds")
.log_id,
);
}
let stored = AgentSessionLogRepo::list_by_session(&repo, test_session())
.await
.unwrap();
assert_eq!(
stored.iter().map(|row| row.id).collect::<Vec<_>>(),
appended,
"every frame is durable before its append returns"
);
assert!(
realtime.published().is_empty(),
"nothing is published before the flush"
);
assert!(
logs.flush_deadline().is_some(),
"a pending frame gives the actor a deadline to flush by"
);
AgentSessionLogWriter::flush(&mut logs)
.await
.expect("flush succeeds");
let published = realtime.published();
assert_eq!(published.len(), 1, "one flush is one publish");
assert_eq!(
published[0]
.entries
.iter()
.map(|row| row.id)
.collect::<Vec<_>>(),
appended,
"the publish carries the stored frames in log order"
);
assert!(
logs.flush_deadline().is_none(),
"nothing pending needs no wake-up"
);
}
/// A frame headed to the runtime pushes everything pending through with
/// itself, so a viewer never sees a prompt before the output it followed.
#[tokio::test]
async fn frames_headed_to_the_runtime_flush_pending_frames_through() {
let repo = InMemoryAgentSessionRepo::new();
repo.insert_session(test_agent_session(test_session()));
let realtime = RecordingRealtime::new();
let mut logs = streaming_connection(repo.clone(), realtime.clone());
AgentSessionLogWriter::append(&mut logs, streamed_frame("pending"))
.await
.unwrap();
let prompt = parse_log_as(test_session(), TURN)
.into_iter()
.find(|entry| matches!(entry.content, Message::ToRuntime(_)))
.expect("the fixture turn prompts the runtime");
let prompt_id = AgentSessionLogWriter::append(&mut logs, prompt)
.await
.unwrap()
.log_id;
let published = realtime.published();
assert_eq!(published.len(), 1, "flushed through as one publish");
assert_eq!(published[0].entries.len(), 2);
assert_eq!(published[0].entries[1].id, prompt_id);
assert!(logs.flush_deadline().is_none());
}
/// System events move the composer's idea of whether the agent is working,
/// so they go out at once, with whatever was pending ahead of them.
#[tokio::test]
async fn system_events_flush_pending_frames_through() {
let repo = InMemoryAgentSessionRepo::new();
repo.insert_session(test_agent_session(test_session()));
let realtime = RecordingRealtime::new();
let mut logs = streaming_connection(repo.clone(), realtime.clone());
AgentSessionLogWriter::append(&mut logs, streamed_frame("pending"))
.await
.unwrap();
AgentSessionLogWriter::append(
&mut logs,
AgentSessionLog {
agent_session_id: test_session(),
user_id: None,
content: Message::ToServer(ToServerMessage::Event {
event: SystemEvent::AcpReady,
}),
logged_at: None,
},
)
.await
.unwrap();
let published = realtime.published();
assert_eq!(published.len(), 1);
assert_eq!(published[0].entries.len(), 2);
assert!(logs.flush_deadline().is_none());
}
/// Enough pending frames flush themselves, bounding one publish.
#[tokio::test]
async fn a_full_pending_run_flushes_itself() {
let repo = InMemoryAgentSessionRepo::new();
repo.insert_session(test_agent_session(test_session()));
let realtime = RecordingRealtime::new();
let mut logs = streaming_connection(repo.clone(), realtime.clone());
for index in 0..MAX_PENDING_LOG_FRAMES {
AgentSessionLogWriter::append(&mut logs, streamed_frame(&index.to_string()))
.await
.unwrap();
}
let published = realtime.published();
assert_eq!(published.len(), 1);
assert_eq!(published[0].entries.len(), MAX_PENDING_LOG_FRAMES);
assert!(logs.flush_deadline().is_none());
}
// Batched writes: a fenced connection holds streamed notifications back and
// lands them in one insert, while anything the store projects or the
// runtime acts on writes the buffer out first and lands at once.
async fn fenced_connection(
realtime: RecordingRealtime,
) -> (
InMemoryAgentSessionRepo,
LiveSessionLogWriter<InMemoryAgentSessionRepo, RecordingRealtime>,
) {
let repo = InMemoryAgentSessionRepo::new();
repo.insert_session(test_agent_session(test_session()));
let claim = claim_for_test(&repo, test_session()).await;
let logs = LiveSessionLogWriter::fenced(repo.clone(), realtime, claim);
(repo, logs)
}
/// Under a claim, streamed notifications wait for the flush: nothing is
/// stored or published until then, and the flush lands them all at once, in
/// order, under the ids the appends already handed out.
#[tokio::test]
async fn a_fenced_connection_buffers_streamed_frames_until_it_flushes() {
let realtime = RecordingRealtime::new();
let (repo, mut logs) = fenced_connection(realtime.clone()).await;
let mut appended = Vec::new();
for text in ["one", "two", "three"] {
appended.push(
AgentSessionLogWriter::append(&mut logs, streamed_frame(text))
.await
.expect("append succeeds")
.log_id,
);
}
assert_eq!(
AgentSessionLogRepo::list_by_session(&repo, test_session())
.await
.unwrap()
.len(),
1,
"the initial activity projection is durable; subsequent token frames stay buffered"
);
assert!(realtime.published().is_empty());
assert!(logs.flush_deadline().is_some());
AgentSessionLogWriter::flush(&mut logs)
.await
.expect("flush succeeds");
let stored = AgentSessionLogRepo::list_by_session(&repo, test_session())
.await
.unwrap();
assert_eq!(
stored.iter().map(|row| row.id).collect::<Vec<_>>(),
appended,
"the flush stores every frame in append order under the id its append returned"
);
assert!(
stored
.windows(2)
.all(|pair| pair[0].created_at < pair[1].created_at),
"a batch orders strictly by time, as readers expect"
);
let published = realtime.published();
assert_eq!(published.len(), 1, "one flush is one publish");
assert_eq!(
published[0]
.entries
.iter()
.map(|row| row.id)
.collect::<Vec<_>>(),
appended
);
assert!(logs.flush_deadline().is_none());
}
/// A frame headed to the runtime writes the buffer out ahead of itself and
/// is durable before `append` returns, so history never lacks a message the
/// agent received and never reorders around it.
#[tokio::test]
async fn frames_headed_to_the_runtime_write_the_buffer_out_first() {
let realtime = RecordingRealtime::new();
let (repo, mut logs) = fenced_connection(realtime.clone()).await;
let buffered = AgentSessionLogWriter::append(&mut logs, streamed_frame("buffered"))
.await
.unwrap()
.log_id;
let prompt = parse_log_as(test_session(), TURN)
.into_iter()
.find(|entry| matches!(entry.content, Message::ToRuntime(_)))
.expect("the fixture turn prompts the runtime");
let prompt_id = AgentSessionLogWriter::append(&mut logs, prompt)
.await
.unwrap()
.log_id;
let stored = AgentSessionLogRepo::list_by_session(&repo, test_session())
.await
.unwrap();
assert_eq!(
stored.iter().map(|row| row.id).collect::<Vec<_>>(),
vec![buffered, prompt_id],
"both durable, buffered frame first"
);
assert_eq!(realtime.published().len(), 1, "and pushed as one publish");
assert!(logs.flush_deadline().is_none());
}
/// A successful load's boundary selects history at its own row, so the
/// frames buffered before it must already be rows when it lands.
#[tokio::test]
async fn a_load_boundary_lands_after_the_frames_buffered_before_it() {
let realtime = RecordingRealtime::new();
let (repo, mut logs) = fenced_connection(realtime.clone()).await;
let initialize = AgentSessionLog {
agent_session_id: test_session(),
user_id: None,
content: Message::ToRuntime(ToRuntimeMessage::Acp(AcpMessage(
agent_client_protocol::RawJsonRpcMessage::request(
"initialize".to_owned(),
serde_json::json!({}),
agent_client_protocol::schema::v1::RequestId::Str("init".into()),
)
.unwrap(),
))),
logged_at: None,
};
let initialization_log_id = AgentSessionLogWriter::append(&mut logs, initialize)
.await
.unwrap()
.log_id;
let replayed = AgentSessionLogWriter::append(&mut logs, streamed_frame("replayed"))
.await
.unwrap()
.log_id;
let load_response = AgentSessionLog {
agent_session_id: test_session(),
user_id: None,
content: Message::ToServer(ToServerMessage::Acp(AcpMessage(
agent_client_protocol::RawJsonRpcMessage::response(
agent_client_protocol::schema::v1::RequestId::Str("load".into()),
Ok(serde_json::json!({})),
),
))),
logged_at: None,
};
let response_id = AgentSessionLogWriter::append_with_boundary(
&mut logs,
load_response,
Some(crate::domain::model::HistoryBoundary {
initialization_log_id,
}),
)
.await
.unwrap()
.log_id;
let history = AgentSessionLogRepo::list_by_session(&repo, test_session())
.await
.unwrap();
assert_eq!(
history.iter().map(|row| row.id).collect::<Vec<_>>(),
vec![initialization_log_id, replayed, response_id],
"history starts at the initialization and keeps append order"
);
}
/// A full buffer flushes itself, bounding what a crash could lose and what
/// one insert has to write.
#[tokio::test]
async fn a_full_buffer_writes_itself_out() {
let realtime = RecordingRealtime::new();
let (repo, mut logs) = fenced_connection(realtime.clone()).await;
for index in 0..MAX_PENDING_LOG_FRAMES {
AgentSessionLogWriter::append(&mut logs, streamed_frame(&index.to_string()))
.await
.unwrap();
}
let stored = AgentSessionLogRepo::list_by_session(&repo, test_session())
.await
.unwrap();
assert_eq!(stored.len(), MAX_PENDING_LOG_FRAMES);
let published = realtime.published();
assert_eq!(published.len(), 1);
assert_eq!(published[0].entries.len(), MAX_PENDING_LOG_FRAMES);
assert!(logs.flush_deadline().is_none());
}
/// The fold hands out turn ids over the whole log, so it must count frames
/// that are only buffered too, and a flushed turn reads back complete and in
/// order.
#[tokio::test]
async fn a_fenced_turn_flushes_complete_and_in_order() {
let realtime = RecordingRealtime::new();
let (repo, mut logs) = fenced_connection(realtime.clone()).await;
let log = parse_log_as(test_session(), TURN);
for entry in log.clone() {
AgentSessionLogWriter::append(&mut logs, entry)
.await
.unwrap();
}
AgentSessionLogWriter::flush(&mut logs).await.unwrap();
let stored = AgentSessionLogRepo::list_by_session(&repo, test_session())
.await
.unwrap();
assert_eq!(
stored
.into_iter()
.map(|row| serde_json::to_value(row.entry.content).unwrap())
.collect::<Vec<_>>(),
log.into_iter()
.map(|entry| serde_json::to_value(entry.content).unwrap())
.collect::<Vec<_>>(),
);
}