use crate::observability::TrajectoryHandle;
pub(crate) mod surface {
pub use merry_coding::{
CODING_AGENT_DYNAMIC_CONTEXT_LAYOUT, CODING_AGENT_POLICY_PROMPT, CODING_AGENT_PROFILE_ID,
CODING_AGENT_STABLE_PREFIX_LAYOUT, CODING_LOOP_PROCESS_TOOL, CodingAgentProfile,
CodingAgentProfileBuildError, CodingAgentProfileBuilder, CodingAgentProfileHash,
CodingAgentRunPolicy, CodingAgentRunPolicyError, CodingAutoFallback,
CodingFinalReportPolicy, CodingModelRoleConfig, CodingModelRoleConfigError,
CodingPermissionMode, CodingPermissionPolicy, CodingPermissionPolicyError, CodingRuntime,
CodingRuntimeBuildError, CodingRuntimeBuilder, CodingRuntimeInput, CodingSubagentsConfig,
CodingWorkflowCommand, DEFAULT_CODING_AGENT_MAX_MODEL_TURNS,
DEFAULT_CODING_SUBAGENT_MAX_MODEL_TURNS, MAX_ROLE_PROMPT_FILE_BYTES,
MAX_ROOT_PROJECT_RULES_BYTES, MIN_CODING_SUBAGENT_MODEL_TURNS, ProjectRulesLoadError,
ROOT_PROJECT_RULES_FILE, ResolvedSubagentRuntime, SubagentDefaultOverride,
SubagentModelOverride, SubagentResolutionInput, SubagentRoleCatalog, SubagentRoleError,
SubagentRoleOverlay, SubagentRoleSpec, SubagentWorkspaceAccess, WorkspaceToolLimits,
WorktreeError, WorktreeGcReport, WorktreeIsolationManager, cleanup_orphaned_worktrees,
cleanup_orphaned_worktrees_default, coding_agent, default_worktree_base_dir,
load_root_project_rules, load_workspace_prompt_file, resolve_subagent_runtime,
};
}
use merry_core::{
PlanDocument, PlanSessionSnapshot, SessionId, SessionUsage, SubagentId, TodoItem, ToolCallId,
ToolOutput,
};
use merry_llm::GenerationConfig;
pub use merry_runtime::{
AgentLoopConfig, AgentLoopControl, AgentLoopInput, AgentLoopResult, AgentRun, AgentRunMessage,
BackgroundProcessId, BackgroundProcessLookupError, BackgroundProcessOutput,
BackgroundProcessStop, BackgroundProcessSummary, CitationCompactionPolicy,
DEFAULT_CONTEXT_WINDOW_FALLBACK_TOKENS, DEFAULT_FOREGROUND_WAIT_BUDGET_SECS, DurableMemory,
FileSessionStore, InteractiveError, InteractiveProcessExecutionUpdate,
InteractiveRunEventStream, InteractiveRunMessage, InteractiveSettingsUpdate,
InteractiveSubagentSettings, MemoryLayout, RuntimeError, RuntimeModelRole, SessionStoreError,
SessionTranscriptItem, SkillMetadata, SubagentActivityReceiver, SubagentConfig,
SubagentInspectSession, SubagentLimitBehavior, SubagentStatusView, WaitSubagentsOutput,
};
use merry_runtime::{LoadedSession, Runtime, SessionReservation, StepContext, StepInput};
use std::path::{Path, PathBuf};
pub use surface::*;
use thiserror::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodingSessionOpenMode {
New,
Resume,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodingSessionResumeFailure {
AlreadyOpen,
IncompatibleFormat,
}
#[derive(Debug, Error)]
pub enum CodingSessionOpenError {
#[error("session {session_id} already has saved state")]
SessionAlreadyExists {
session_id: SessionId,
},
#[error("could not resume session {session_id}: {message}")]
ResumeUnavailable {
kind: CodingSessionResumeFailure,
session_id: SessionId,
session_dir: PathBuf,
message: String,
},
#[error("session store error: {source}")]
SessionStore {
#[source]
source: SessionStoreError,
},
#[error(transparent)]
Build {
#[from]
source: CodingRuntimeBuildError,
},
}
#[must_use]
pub fn classify_resume_error(error: &RuntimeError) -> Option<CodingSessionResumeFailure> {
match error {
RuntimeError::SessionStore {
source: SessionStoreError::SessionAlreadyReserved { .. },
} => Some(CodingSessionResumeFailure::AlreadyOpen),
RuntimeError::SessionStore {
source:
SessionStoreError::UnsupportedFormatVersion { .. }
| SessionStoreError::InvalidDocument { .. }
| SessionStoreError::Json { .. }
| SessionStoreError::SessionIdMismatch { .. }
| SessionStoreError::Io { .. },
} => Some(CodingSessionResumeFailure::IncompatibleFormat),
_ => None,
}
}
#[must_use]
pub fn attach_durable_memory_at(
input: CodingRuntimeInput,
memory_root: &Path,
) -> CodingRuntimeInput {
let root = input.root().to_path_buf();
match MemoryLayout::at(memory_root, &root).and_then(DurableMemory::open) {
Ok(memory) => input.durable_memory(memory),
Err(error) => {
tracing::warn!(
event = "memory.open_failed",
error = %error,
"durable memory is unavailable; continuing without it"
);
input
}
}
}
#[must_use]
pub fn attach_durable_memory_from_env(input: CodingRuntimeInput) -> CodingRuntimeInput {
let root = input.root().to_path_buf();
match DurableMemory::open_from_env(&root) {
Ok(memory) => input.durable_memory(memory),
Err(error) => {
tracing::warn!(
event = "memory.open_failed",
error = %error,
"durable memory is unavailable; continuing without it"
);
input
}
}
}
pub struct CodingSessionBuilder {
input: CodingRuntimeInput,
permission_policy: CodingPermissionPolicy,
session_store: Option<FileSessionStore>,
loaded_session: Option<LoadedSession>,
}
impl CodingSessionBuilder {
#[must_use]
pub fn new(input: CodingRuntimeInput) -> Self {
Self {
input,
permission_policy: CodingPermissionPolicy::default(),
session_store: None,
loaded_session: None,
}
}
#[must_use]
pub fn permission_policy(mut self, policy: CodingPermissionPolicy) -> Self {
self.permission_policy = policy;
self
}
#[must_use]
pub fn session_store(mut self, store: FileSessionStore) -> Self {
self.session_store = Some(store);
self
}
#[cfg(feature = "mcp")]
#[must_use]
pub fn mcp_tools(mut self, toolset: crate::mcp::McpToolset) -> Self {
let (tools, _warnings) = toolset.into_parts();
self.input = self.input.with_extra_tools(tools);
self
}
#[must_use]
pub fn with_durable_memory_at(mut self, memory_root: &Path) -> Self {
self.input = attach_durable_memory_at(self.input, memory_root);
self
}
#[must_use]
pub fn with_durable_memory_from_env(mut self) -> Self {
self.input = attach_durable_memory_from_env(self.input);
self
}
#[must_use]
pub fn with_workspace_review_notes(mut self, notes: Vec<String>) -> Self {
self.input = self.input.with_workspace_review_notes(notes);
self
}
pub fn build(self) -> Result<CodingSession, CodingRuntimeBuildError> {
let mut reservation = None;
self.build_with_reservation(&mut reservation)
}
fn build_with_reservation(
self,
reservation: &mut Option<SessionReservation>,
) -> Result<CodingSession, CodingRuntimeBuildError> {
let mut builder =
CodingRuntimeBuilder::new(self.input).permission_policy(self.permission_policy);
if let Some(loaded) = self.loaded_session {
builder = builder.with_loaded_session(loaded);
}
if let Some(store) = self.session_store {
builder = builder.session_store(store);
}
let coding_runtime = builder.build_with_reservation(reservation)?;
let loop_config = coding_runtime.loop_config();
let runtime = coding_runtime.into_runtime();
let agent = crate::Agent::from_runtime_parts(
runtime,
loop_config,
GenerationConfig::default(),
None,
);
Ok(CodingSession { agent })
}
pub async fn open(
mut self,
store: FileSessionStore,
mode: CodingSessionOpenMode,
) -> Result<CodingSession, CodingSessionOpenError> {
let session_id = self.input.session_id().clone();
let mut reservation = match store.reserve_session(&session_id).await {
Ok(reservation) => Some(reservation),
Err(SessionStoreError::SessionAlreadyReserved { .. })
if mode == CodingSessionOpenMode::Resume =>
{
return Err(CodingSessionOpenError::ResumeUnavailable {
kind: CodingSessionResumeFailure::AlreadyOpen,
session_dir: store.session_dir(&session_id),
session_id,
message: "session is already open in another process".to_owned(),
});
}
Err(source) => return Err(CodingSessionOpenError::SessionStore { source }),
};
match mode {
CodingSessionOpenMode::New => {
let exists = match store.contains_session(&session_id).await {
Ok(exists) => exists,
Err(source) => {
if let Some(res) = reservation.take() {
store.release_empty_reservation(&session_id, res).await;
}
return Err(CodingSessionOpenError::SessionStore { source });
}
};
if exists {
if let Some(res) = reservation.take() {
store.release_empty_reservation(&session_id, res).await;
}
return Err(CodingSessionOpenError::SessionAlreadyExists { session_id });
}
}
CodingSessionOpenMode::Resume => {
let loaded = match LoadedSession::load(&store, &session_id).await {
Ok(loaded) => loaded,
Err(error) => {
if let Some(res) = reservation.take() {
store.release_empty_reservation(&session_id, res).await;
}
return Err(CodingSessionOpenError::ResumeUnavailable {
kind: classify_resume_error(&error)
.unwrap_or(CodingSessionResumeFailure::IncompatibleFormat),
session_dir: store.session_dir(&session_id),
session_id: session_id.clone(),
message: error.to_string(),
});
}
};
self.loaded_session = Some(loaded);
}
}
self.session_store = Some(store.clone());
match self.build_with_reservation(&mut reservation) {
Ok(session) => Ok(session),
Err(source) => {
if let Some(res) = reservation.take() {
store.release_empty_reservation(&session_id, res).await;
}
Err(CodingSessionOpenError::Build { source })
}
}
}
}
pub struct InteractiveCodingRun {
pub stream: InteractiveRunEventStream,
pub input: AgentLoopInput,
pub control: AgentLoopControl,
pub subagent_activity: SubagentActivityReceiver,
pub skills: Vec<SkillMetadata>,
}
pub struct CodingSession {
agent: crate::Agent,
}
impl CodingSession {
#[must_use]
pub fn builder(input: CodingRuntimeInput) -> CodingSessionBuilder {
CodingSessionBuilder::new(input)
}
#[must_use]
pub fn as_agent(&self) -> &crate::Agent {
&self.agent
}
#[must_use]
pub fn into_agent(self) -> crate::Agent {
self.agent
}
#[must_use]
pub fn session_id(&self) -> &SessionId {
self.agent.session_id()
}
#[must_use]
pub fn handle(&self) -> CodingSessionHandle {
self.agent.session_handle()
}
#[must_use]
pub fn trajectory_handle(&self) -> TrajectoryHandle {
self.agent.trajectory_handle()
}
#[must_use]
pub fn loop_config(&self) -> AgentLoopConfig {
self.agent.loop_config().clone()
}
pub async fn start_interactive(
&self,
generation: GenerationConfig,
) -> Result<InteractiveCodingRun, RuntimeError> {
let handle = self.handle();
let skills = handle.skills().await;
let interactive = self.agent.runtime().start_interactive_agent_run(
StepContext::default().with_generation_config(generation),
self.loop_config(),
)?;
let subagent_activity = handle.subscribe_subagent_activity();
let (stream, input, control) = interactive.split();
Ok(InteractiveCodingRun {
stream,
input,
control,
subagent_activity,
skills,
})
}
pub fn run_stream(
&self,
task: &str,
generation: GenerationConfig,
) -> Result<AgentRun, RuntimeError> {
self.handle()
.run_agent_loop_stream(task, generation, self.loop_config())
}
pub async fn discard_if_empty(&mut self) {
let _ = self.agent.close().await;
}
#[doc(hidden)]
#[must_use]
pub fn into_runtime(self) -> Runtime {
self.agent.into_runtime()
}
}
impl From<CodingSession> for crate::Agent {
fn from(session: CodingSession) -> Self {
session.into_agent()
}
}
#[derive(Clone)]
pub struct CodingSessionHandle {
runtime: Runtime,
}
impl CodingSessionHandle {
#[doc(hidden)]
#[must_use]
pub fn from_runtime(runtime: Runtime) -> Self {
Self { runtime }
}
#[must_use]
pub fn session_id(&self) -> &SessionId {
self.runtime.session_id()
}
#[must_use]
pub fn trajectory_handle(&self) -> TrajectoryHandle {
TrajectoryHandle::from_runtime(self.runtime.clone())
}
pub async fn skills(&self) -> Vec<SkillMetadata> {
self.runtime.skills().await
}
#[must_use]
pub fn subscribe_subagent_activity(&self) -> SubagentActivityReceiver {
self.runtime.subscribe_subagent_activity()
}
pub async fn usage(&self) -> Option<SessionUsage> {
self.runtime.usage().await
}
pub async fn session_transcript(&self) -> Result<Vec<SessionTranscriptItem>, RuntimeError> {
self.runtime.session_transcript().await
}
pub async fn archived_segment_numbers(&self) -> Result<Vec<u32>, RuntimeError> {
self.runtime.archived_segment_numbers().await
}
pub async fn read_archived_segment_transcript(
&self,
segment_number: u32,
) -> Result<Vec<SessionTranscriptItem>, RuntimeError> {
self.runtime
.read_archived_segment_transcript(segment_number)
.await
}
pub async fn read_tool_output(
&self,
call_id: &ToolCallId,
) -> Result<Option<ToolOutput>, RuntimeError> {
self.runtime.read_tool_output(call_id).await
}
pub async fn plan_session_snapshot(&self) -> PlanSessionSnapshot {
self.runtime.plan_session_snapshot().await
}
pub async fn plan_documents(&self) -> Vec<PlanDocument> {
self.runtime.plan_documents().await
}
pub async fn todo_items(&self) -> Vec<TodoItem> {
self.runtime.todo_items().await
}
pub async fn cached_session_topic(&self) -> Option<String> {
self.runtime.cached_session_topic().await
}
pub async fn session_topic(&self) -> Option<String> {
self.runtime.session_topic().await
}
pub async fn subagent_snapshot(&self) -> Option<Vec<SubagentStatusView>> {
self.runtime.subagent_snapshot().await
}
pub async fn inspect_subagent(&self, agent_id: &SubagentId) -> Option<SubagentInspectSession> {
self.runtime.inspect_subagent(agent_id).await
}
pub async fn send_subagent_message(
&self,
agent_id: &SubagentId,
message: String,
) -> Result<(), RuntimeError> {
self.runtime.send_subagent_message(agent_id, message).await
}
pub async fn cancel_subagent(
&self,
agent_id: &SubagentId,
) -> Result<WaitSubagentsOutput, RuntimeError> {
self.runtime.cancel_subagent(agent_id).await
}
#[must_use]
pub fn background_processes(&self) -> Vec<BackgroundProcessSummary> {
self.runtime.background_processes()
}
pub fn read_background_process(
&self,
id: &BackgroundProcessId,
) -> Result<BackgroundProcessOutput, BackgroundProcessLookupError> {
self.runtime.read_background_process(id)
}
pub fn stop_background_process(
&self,
id: &BackgroundProcessId,
) -> Result<BackgroundProcessStop, BackgroundProcessLookupError> {
self.runtime.stop_background_process(id)
}
#[must_use]
pub fn active_permission_grants(&self) -> crate::permissions::ActivePermissionGrants {
self.runtime.active_permission_grants()
}
pub fn revoke_session_grant(
&self,
id: crate::permissions::SessionGrantId,
) -> Result<bool, crate::process::ProcessRunnerError> {
self.runtime.revoke_session_grant(id)
}
pub fn clear_session_grants(&self) -> Result<(), crate::process::ProcessRunnerError> {
self.runtime.clear_session_grants()
}
#[must_use]
pub fn revoke_review_guidance(&self, id: crate::permissions::ReviewGuidanceId) -> bool {
self.runtime.revoke_review_guidance(id)
}
pub fn set_workspace_review_notes(&self, notes: Vec<String>) {
self.runtime.set_workspace_review_notes(notes);
}
pub async fn abandon_pending_tool_calls(&self, reason: &str) -> Result<usize, RuntimeError> {
self.runtime.abandon_pending_tool_calls(reason).await
}
pub async fn save_session_to(&self, store: FileSessionStore) -> Result<(), RuntimeError> {
self.runtime.save_session_to(store).await
}
pub fn run_agent_loop_stream(
&self,
task: &str,
generation: GenerationConfig,
loop_config: AgentLoopConfig,
) -> Result<AgentRun, RuntimeError> {
let input = StepInput::user_text(task)?;
let context = StepContext::default().with_generation_config(generation);
self.runtime
.run_agent_loop_stream(input, context, loop_config)
}
}
#[cfg(test)]
mod tests {
use super::*;
use merry_llm::{
FinishReason, ModelCapabilities, ModelError, ModelEvent, ModelEventStream, ModelName,
ModelOutput, ModelProvider, ModelProviderFuture, ModelRequest, ModelResponse,
ModelStreamContext,
};
use merry_process::{LocalProcessBackend, ProcessBackendMode, ProcessBackendOptions};
use std::sync::{Arc, OnceLock};
struct StaticProvider;
impl ModelProvider for StaticProvider {
fn name(&self) -> &merry_core::ProviderName {
static NAME: OnceLock<merry_core::ProviderName> = OnceLock::new();
NAME.get_or_init(|| merry_core::ProviderName::new("coding-session-test").unwrap())
}
fn capabilities(&self) -> &ModelCapabilities {
static CAPS: OnceLock<ModelCapabilities> = OnceLock::new();
CAPS.get_or_init(|| {
ModelCapabilities::new(true, true, false, true, None, None).unwrap()
})
}
fn stream_model<'a>(
&'a self,
_request: ModelRequest,
_context: ModelStreamContext,
) -> ModelProviderFuture<'a, Result<ModelEventStream, ModelError>> {
Box::pin(async move {
let response =
ModelResponse::new(vec![ModelOutput::text("ok")], FinishReason::Stop, None);
let stream: ModelEventStream = Box::pin(futures_util::stream::iter([
Ok(ModelEvent::Started),
Ok(ModelEvent::Completed { response }),
]));
Ok(stream)
})
}
}
fn test_input(session_id: &str, workspace: &std::path::Path) -> CodingRuntimeInput {
let backend = Arc::new(
LocalProcessBackend::new(
workspace,
ProcessBackendMode::Host,
ProcessBackendOptions::new(),
)
.expect("host backend should build"),
);
CodingRuntimeInput::new(
SessionId::new(session_id).expect("valid session id"),
workspace,
Arc::new(StaticProvider),
ModelName::new("test-model").expect("valid model"),
backend,
)
}
#[tokio::test]
async fn coding_session_open_enforces_lock_and_new_collision_and_resume() {
let temp = tempfile::tempdir().expect("tempdir");
let workspace = temp.path().join("workspace");
std::fs::create_dir_all(&workspace).expect("workspace dir");
let store = FileSessionStore::new(temp.path().join("sessions"));
let session = CodingSession::builder(test_input("webui-session-1", &workspace))
.open(store.clone(), CodingSessionOpenMode::New)
.await
.expect("new coding session should open");
assert_eq!(session.session_id().as_str(), "webui-session-1");
assert_eq!(
session.trajectory_handle().session_id().as_str(),
"webui-session-1"
);
let locked = CodingSession::builder(test_input("webui-session-1", &workspace))
.open(store.clone(), CodingSessionOpenMode::Resume)
.await;
assert!(matches!(
locked,
Err(CodingSessionOpenError::ResumeUnavailable {
kind: CodingSessionResumeFailure::AlreadyOpen,
..
})
));
session
.handle()
.save_session_to(store.clone())
.await
.expect("session should save");
drop(session);
let collision = CodingSession::builder(test_input("webui-session-1", &workspace))
.open(store.clone(), CodingSessionOpenMode::New)
.await;
assert!(matches!(
collision,
Err(CodingSessionOpenError::SessionAlreadyExists { .. })
));
let resumed = CodingSession::builder(test_input("webui-session-1", &workspace))
.open(store.clone(), CodingSessionOpenMode::Resume)
.await
.expect("saved session should resume");
let interactive = resumed
.start_interactive(GenerationConfig::default())
.await
.expect("interactive run should start");
assert!(interactive.skills.is_empty());
}
#[test]
fn classify_resume_error_matches_locked_and_corrupt_store_errors() {
assert_eq!(
classify_resume_error(&RuntimeError::SessionStore {
source: SessionStoreError::UnsupportedFormatVersion { actual: 6 },
}),
Some(CodingSessionResumeFailure::IncompatibleFormat)
);
assert_eq!(
classify_resume_error(&RuntimeError::SessionStore {
source: SessionStoreError::InvalidDocument {
reason: "legacy journal",
},
}),
Some(CodingSessionResumeFailure::IncompatibleFormat)
);
assert_eq!(
classify_resume_error(&RuntimeError::SessionStore {
source: SessionStoreError::SessionAlreadyReserved {
session_id: SessionId::new("busy").expect("valid id"),
},
}),
Some(CodingSessionResumeFailure::AlreadyOpen)
);
}
#[tokio::test]
async fn coding_session_discard_if_empty_removes_untouched_dir() {
let temp = tempfile::tempdir().expect("tempdir");
let workspace = temp.path().join("workspace");
std::fs::create_dir_all(&workspace).expect("workspace dir");
let store = FileSessionStore::new(temp.path().join("sessions"));
let session_id = SessionId::new("untouched-session").expect("valid session id");
let mut session = CodingSession::builder(test_input("untouched-session", &workspace))
.open(store.clone(), CodingSessionOpenMode::New)
.await
.expect("session should open");
assert!(store.session_dir(&session_id).exists());
session.discard_if_empty().await;
assert!(!store.session_dir(&session_id).exists());
}
#[tokio::test]
async fn coding_session_builder_with_durable_memory_at_creates_scoped_memory_without_env() {
let temp = tempfile::tempdir().expect("tempdir");
let workspace = temp.path().join("workspace");
let memory_root = temp.path().join("explicit-memory");
std::fs::create_dir_all(&workspace).expect("workspace dir");
let _session = CodingSession::builder(test_input("memory-root-session", &workspace))
.with_durable_memory_at(&memory_root)
.build()
.expect("session with explicit memory root should build");
assert!(memory_root.join("global").join("MEMORY.md").is_file());
assert!(memory_root.join("workspaces").is_dir());
}
#[tokio::test]
async fn coding_session_delegates_to_unified_agent_facade() {
let temp = tempfile::tempdir().expect("tempdir");
let workspace = temp.path().join("workspace");
std::fs::create_dir_all(&workspace).expect("workspace dir");
let session = CodingSession::builder(test_input("unified-agent-session", &workspace))
.build()
.expect("coding session should build");
assert_eq!(session.session_id(), session.as_agent().session_id());
let result = session
.as_agent()
.run("hello from unified facade")
.await
.expect("agent run should succeed");
assert_eq!(result.final_output(), Some("ok"));
let transcript = session
.handle()
.session_transcript()
.await
.expect("transcript should load");
assert!(
!transcript.is_empty(),
"CodingSession and its underlying Agent must share one runtime session"
);
let agent = session.into_agent();
assert_eq!(
agent.session_handle().session_id().as_str(),
"unified-agent-session"
);
}
#[tokio::test]
async fn coding_session_into_agent_preserves_session_reservation_until_agent_drops() {
let temp = tempfile::tempdir().expect("tempdir");
let workspace = temp.path().join("workspace");
std::fs::create_dir_all(&workspace).expect("workspace dir");
let store = FileSessionStore::new(temp.path().join("sessions"));
let session = CodingSession::builder(test_input("into-agent-lock", &workspace))
.open(store.clone(), CodingSessionOpenMode::New)
.await
.expect("coding session should open");
session
.handle()
.save_session_to(store.clone())
.await
.expect("session should save");
let agent = session.into_agent();
let agent_clone = agent.clone();
let locked = CodingSession::builder(test_input("into-agent-lock", &workspace))
.open(store.clone(), CodingSessionOpenMode::Resume)
.await;
assert!(matches!(
locked,
Err(CodingSessionOpenError::ResumeUnavailable {
kind: CodingSessionResumeFailure::AlreadyOpen,
..
})
));
drop(agent);
let still_locked = CodingSession::builder(test_input("into-agent-lock", &workspace))
.open(store.clone(), CodingSessionOpenMode::Resume)
.await;
assert!(matches!(
still_locked,
Err(CodingSessionOpenError::ResumeUnavailable {
kind: CodingSessionResumeFailure::AlreadyOpen,
..
})
));
drop(agent_clone);
let resumed = CodingSession::builder(test_input("into-agent-lock", &workspace))
.open(store, CodingSessionOpenMode::Resume)
.await
.expect("resume should succeed after Agent drops");
assert_eq!(resumed.session_id().as_str(), "into-agent-lock");
}
#[tokio::test]
async fn coding_session_into_runtime_retains_lock_and_into_agent_close_releases_it() {
let temp = tempfile::tempdir().expect("tempdir");
let workspace = temp.path().join("workspace");
std::fs::create_dir_all(&workspace).expect("workspace dir");
let store = FileSessionStore::new(temp.path().join("sessions"));
let session = CodingSession::builder(test_input("into-runtime-lock", &workspace))
.open(store.clone(), CodingSessionOpenMode::New)
.await
.expect("coding session should open");
session
.handle()
.save_session_to(store.clone())
.await
.expect("session should save");
let runtime = session.into_runtime();
let locked = CodingSession::builder(test_input("into-runtime-lock", &workspace))
.open(store.clone(), CodingSessionOpenMode::Resume)
.await;
assert!(
matches!(
locked,
Err(CodingSessionOpenError::ResumeUnavailable {
kind: CodingSessionResumeFailure::AlreadyOpen,
..
})
),
"into_runtime() must preserve exclusive session reservation"
);
runtime.close().await.expect("runtime close should succeed");
let reopened = CodingSession::builder(test_input("into-runtime-lock", &workspace))
.open(store.clone(), CodingSessionOpenMode::Resume)
.await
.expect("resume should succeed immediately after runtime.close()");
let agent = reopened.into_agent();
let _clone_still_alive = agent.clone();
agent.close().await.expect("agent close should succeed");
let reopened_again = CodingSession::builder(test_input("into-runtime-lock", &workspace))
.open(store, CodingSessionOpenMode::Resume)
.await
.expect("into_agent().close() must release session reservation even with live clones");
assert_eq!(reopened_again.session_id().as_str(), "into-runtime-lock");
}
#[tokio::test]
async fn runtime_builder_with_profile_preserves_explicit_retry_policy() {
use merry_llm::{ModelError, ModelRetryPolicy};
use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(Clone)]
struct AlwaysTransientErrorProvider {
attempts: Arc<AtomicUsize>,
}
impl ModelProvider for AlwaysTransientErrorProvider {
fn name(&self) -> &merry_core::ProviderName {
static NAME: OnceLock<merry_core::ProviderName> = OnceLock::new();
NAME.get_or_init(|| merry_core::ProviderName::new("retry-test").unwrap())
}
fn capabilities(&self) -> &ModelCapabilities {
static CAPS: OnceLock<ModelCapabilities> = OnceLock::new();
CAPS.get_or_init(|| {
ModelCapabilities::new(true, true, false, true, None, None).unwrap()
})
}
fn stream_model<'a>(
&'a self,
_request: ModelRequest,
_context: ModelStreamContext,
) -> ModelProviderFuture<'a, Result<ModelEventStream, ModelError>> {
let attempts = Arc::clone(&self.attempts);
Box::pin(async move {
attempts.fetch_add(1, Ordering::SeqCst);
Err(ModelError::provider(
merry_llm::ProviderErrorKind::Unavailable,
"transient outage",
))
})
}
}
let temp = tempfile::tempdir().expect("tempdir");
let workspace = temp.path().join("workspace");
std::fs::create_dir_all(&workspace).expect("workspace dir");
let attempts = Arc::new(AtomicUsize::new(0));
let provider = Arc::new(AlwaysTransientErrorProvider {
attempts: Arc::clone(&attempts),
});
let single_attempt = ModelRetryPolicy::disabled();
let profile = crate::profiles::coding_agent(&workspace)
.build()
.expect("coding profile");
let agent =
crate::AgentBuilder::new(SessionId::new("retry-order-check").expect("session id"))
.provider(
crate::providers::ConfiguredModelProvider::primary(
provider,
ModelName::new("test-model").expect("valid model"),
)
.with_retry_policy(single_attempt),
)
.profile(profile)
.expect("profile apply")
.build()
.expect("agent build");
let _ = agent.run("hello").await;
assert_eq!(
attempts.load(Ordering::SeqCst),
1,
"profile default retry policy must not clobber explicit provider retry policy"
);
}
}