Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 47 additions & 8 deletions src/crates/assembly/core/src/agentic/coordination/coordinator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9736,6 +9736,35 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet
turn_id: Option<&str>,
history: Option<Option<usize>>,
) -> OpenBitFunResult<(Vec<DialogTurnData>, Option<usize>)> {
// A temporary child owns canonical turn data in memory throughout its
// lifetime. Live updates and history replay must select from that same source.
if let Some((mut turns, next)) =
self.session_manager
.with_transient_session_turns(session_id, |turns| {
if let Some(before) = history {
let ceiling = before.unwrap_or(usize::MAX);
let end = turns.partition_point(|turn| turn.turn_index < ceiling);
let Some((turn, older)) = turns[..end].split_last() else {
return (Vec::new(), None);
};
(
vec![turn.clone()],
(!older.is_empty()).then_some(turn.turn_index),
)
} else if let Some(id) = turn_id {
let found = turns.iter().rev().find(|turn| turn.turn_id == id);
(found.cloned().into_iter().collect(), None)
} else {
(turns.to_vec(), None)
}
})
{
self.session_manager
.validate_session_storage_path_binding(session_id, storage)?;
self.project_relay_turns(session_id, turn_id, &mut turns)
.await?;
return Ok((turns, next));
}
#[cfg(feature = "external-sources")]
self.session_manager
.persistence_manager()
Expand Down Expand Up @@ -9862,12 +9891,6 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet
read_mode,
turns.len()
);
if turn_id.is_some() && turns.is_empty() {
return Err(OpenBitFunError::NotFound(format!(
"Session turn unavailable: {}",
turn_id.unwrap_or_default()
)));
}
if execution_absent {
for turn in &mut turns {
if turn.status != TurnStatus::InProgress {
Expand Down Expand Up @@ -9911,6 +9934,22 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet
}
}
}
self.project_relay_turns(session_id, turn_id, &mut turns)
.await?;
Ok((turns, next))
}

async fn project_relay_turns(
&self,
session_id: &str,
turn_id: Option<&str>,
turns: &mut [DialogTurnData],
) -> OpenBitFunResult<()> {
if let Some(id) = turn_id.filter(|_| turns.is_empty()) {
return Err(OpenBitFunError::NotFound(format!(
"Session turn unavailable: {id}"
)));
}
let context = if turns
.iter()
.any(|turn| turn.status == TurnStatus::InProgress)
Expand All @@ -9921,7 +9960,7 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet
} else {
Vec::new()
};
for turn in &mut turns {
for turn in turns {
if turn.status == TurnStatus::InProgress {
let messages: Vec<_> = context
.iter()
Expand All @@ -9935,7 +9974,7 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet
SessionManager::append_generation_rounds(turn, &id, &messages, timestamp);
}
}
Ok((turns, next))
Ok(())
}

/// Export a transcript while retaining the same Session history boundary
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,36 @@ use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

async fn complete_observed_turn(
coordinator: &ConversationCoordinator,
manager: &SessionManager,
session_id: &str,
turn_id: &str,
message: Message,
) {
ConversationCoordinator::persist_completed_dialog_turn(
coordinator.event_queue.as_ref(),
manager,
None,
session_id,
turn_id,
&ExecutionResult {
final_message: message.clone(),
total_rounds: 1,
success: true,
new_messages: vec![message],
finish_reason: FinishReason::Complete,
total_tools: 0,
duration_ms: 1,
partial_recovery_reason: None,
effective_finish_reason: "complete".to_string(),
has_final_response: true,
},
None,
)
.await;
}

#[tokio::test]
async fn load_relay_session_turns_reads_history_after_the_session_is_unloaded() {
let workspace = tempfile::tempdir().expect("workspace");
Expand Down Expand Up @@ -45,25 +75,12 @@ async fn load_relay_session_turns_reads_history_after_the_session_is_unloaded()
let message = Message::assistant("observer history".to_string())
.with_turn_id(turn_id.clone())
.with_round_id("round-observer".to_string());
ConversationCoordinator::persist_completed_dialog_turn(
coordinator.event_queue.as_ref(),
session_manager.as_ref(),
None,
complete_observed_turn(
&coordinator,
&session_manager,
&session.session_id,
&turn_id,
&ExecutionResult {
final_message: message.clone(),
total_rounds: 1,
success: true,
new_messages: vec![message],
finish_reason: FinishReason::Complete,
total_tools: 0,
duration_ms: 1,
partial_recovery_reason: None,
effective_finish_reason: "complete".to_string(),
has_final_response: true,
},
None,
message,
)
.await;

Expand Down Expand Up @@ -154,25 +171,12 @@ async fn relay_observer_fixture(
let message = Message::assistant("observer history".to_string())
.with_turn_id(turn_id.clone())
.with_round_id("round-observer".to_string());
ConversationCoordinator::persist_completed_dialog_turn(
coordinator.event_queue.as_ref(),
session_manager.as_ref(),
None,
complete_observed_turn(
&coordinator,
&session_manager,
&session.session_id,
&turn_id,
&ExecutionResult {
final_message: message.clone(),
total_rounds: 1,
success: true,
new_messages: vec![message],
finish_reason: FinishReason::Complete,
total_tools: 0,
duration_ms: 1,
partial_recovery_reason: None,
effective_finish_reason: "complete".to_string(),
has_final_response: true,
},
None,
message,
)
.await;
(
Expand All @@ -185,6 +189,108 @@ async fn relay_observer_fixture(
)
}

#[tokio::test]
async fn load_relay_session_turns_streams_and_replays_a_temporary_btw_child() {
let (workspace, coordinator, manager, parent, storage, parent_turn) =
relay_observer_fixture("btw-host").await;
let child_id = format!("btw-{parent}");
coordinator
.ensure_btw_session(
&parent,
&child_id,
None,
"side-question",
Some(&parent_turn),
Some(0),
)
.await
.unwrap();

let history = |before| coordinator.load_relay_history_turn(&storage, &child_id, before);
assert!(history(None).await.unwrap().0.is_empty());
for (id, question, reply) in [
("side-1", "first question", "first answer"),
("side-2", "follow-up", "second answer"),
] {
manager
.start_dialog_turn(
&child_id,
"Standard".into(),
question.into(),
Some(id.into()),
None,
None,
)
.await
.unwrap();
let message = Message::assistant(reply.to_string())
.with_turn_id(id.to_string())
.with_round_id(format!("round-{id}"));
manager
.add_message(&child_id, message.clone())
.await
.unwrap();
{
let _executing = manager.acquire_session_mutation(&child_id).await.unwrap();
let live = tokio::time::timeout(
Duration::from_secs(1),
coordinator.load_relay_session_turns(&storage, &child_id, Some(id)),
)
.await
.unwrap()
.unwrap();
assert_eq!(live.len(), 1);
assert_eq!(live[0].user_message.content, question);
assert_eq!(live[0].status, TurnStatus::InProgress);
assert_eq!(live[0].model_rounds[0].text_items[0].content, reply);
}
complete_observed_turn(&coordinator, &manager, &child_id, id, message).await;
}

let (latest, before) = history(None).await.unwrap();
assert_eq!(latest.len(), 1);
assert_eq!(latest[0].turn_id, "side-2");
assert_eq!(latest[0].status, TurnStatus::Completed);
assert_eq!(
latest[0].model_rounds[0].text_items[0].content,
"second answer"
);
assert_eq!(before, Some(1));
let (first, before) = history(before).await.unwrap();
assert_eq!(first.len(), 1);
assert_eq!(first[0].turn_id, "side-1");
assert_eq!(before, None);
assert!(history(Some(0)).await.unwrap().0.is_empty());
let all = coordinator
.load_relay_session_turns(&storage, &child_id, None)
.await
.unwrap();
assert_eq!(
all.iter()
.map(|turn| turn.turn_id.as_str())
.collect::<Vec<_>>(),
["side-1", "side-2"]
);
assert!(matches!(
coordinator
.load_relay_session_turns(&storage, &child_id, Some(&parent_turn))
.await,
Err(OpenBitFunError::NotFound(_))
));
assert!(matches!(
coordinator
.load_relay_history_turn(&workspace.path().join("other"), &child_id, None)
.await,
Err(OpenBitFunError::Validation(_))
));
assert!(manager
.persistence_manager()
.load_visible_session_turns(&storage, &child_id)
.await
.unwrap()
.is_empty());
}

#[tokio::test]
async fn load_relay_session_turns_projects_history_while_a_turn_holds_the_mutation_lease() {
let (_workspace, coordinator, session_manager, session_id, storage, turn_id) =
Expand Down
16 changes: 16 additions & 0 deletions src/crates/assembly/core/src/agentic/session/session_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8399,6 +8399,22 @@ impl SessionManager {
}
}

/// Read the current temporary history without cloning unrelated turns or
/// holding its map guard across an await. None denotes a disk-backed read.
pub(crate) fn with_transient_session_turns<T>(
&self,
session_id: &str,
read: impl FnOnce(&[DialogTurnData]) -> T,
) -> Option<T> {
let session = self.sessions.get(session_id)?;
if self.config.enable_persistence && self.should_persist_session(&session) {
return None;
}
drop(session);
let history = self.transient_turns.get(session_id);
Some(read(history.as_deref().map_or(&[], |h| h.turns.as_slice())))
}

async fn save_runtime_dialog_turn(
&self,
workspace_path: &Path,
Expand Down
Loading