feat: add main features
Agents for developpement added + frontend add + backend added. Git viewer created + agent and template creator + layout and project creator
This commit is contained in:
681
crates/application/tests/agent_lifecycle.rs
Normal file
681
crates/application/tests/agent_lifecycle.rs
Normal file
@ -0,0 +1,681 @@
|
||||
//! L6 tests for the agent lifecycle use cases (`CreateAgentFromScratch`,
|
||||
//! `ListAgents`, `ReadAgentContext`, `UpdateAgentContext`, `DeleteAgent`,
|
||||
//! `LaunchAgent`).
|
||||
//!
|
||||
//! Every port is faked in-memory so the use cases run without real I/O:
|
||||
//! - [`FakeContexts`] — an [`AgentContextStore`] holding the manifest + a
|
||||
//! `md_path → content` map,
|
||||
//! - [`FakeProfiles`] — a [`ProfileStore`] returning a fixed profile list,
|
||||
//! - [`FakeRuntime`] — an [`AgentRuntime`] whose `prepare_invocation` records the
|
||||
//! call into a shared **trace** and returns a configurable injection plan,
|
||||
//! - [`FakeFs`] — a [`FileSystem`] recording writes into the same trace,
|
||||
//! - [`FakePty`] — a [`PtyPort`] recording `spawn` into the trace,
|
||||
//! - [`SpyBus`], [`SeqIds`] — event recorder and deterministic id generator.
|
||||
//!
|
||||
//! The shared trace lets us assert the **call ordering** contract of
|
||||
//! `LaunchAgent`: `prepare_invocation` → injection (fs write) → `pty.spawn`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use domain::agent::{Agent, AgentManifest, AgentOrigin, ManifestEntry};
|
||||
use domain::events::DomainEvent;
|
||||
use domain::ids::{AgentId, ProfileId, ProjectId};
|
||||
use domain::markdown::MarkdownDoc;
|
||||
use domain::ports::{
|
||||
AgentContextStore, AgentRuntime, ContextInjectionPlan, DirEntry, EventBus, EventStream,
|
||||
ExitStatus, FileSystem, FsError, IdGenerator, OutputStream, PreparedContext, ProfileStore,
|
||||
PtyError, PtyHandle, PtyPort, RemotePath, RuntimeError, SpawnSpec, StoreError,
|
||||
};
|
||||
use domain::profile::{AgentProfile, ContextInjection};
|
||||
use domain::project::{Project, ProjectPath};
|
||||
use domain::remote::RemoteRef;
|
||||
use domain::{PtySize, SessionId};
|
||||
use uuid::Uuid;
|
||||
|
||||
use application::{
|
||||
CreateAgentFromScratch, CreateAgentInput, DeleteAgent, DeleteAgentInput, LaunchAgent,
|
||||
LaunchAgentInput, ListAgents, ListAgentsInput, ReadAgentContext, ReadAgentContextInput,
|
||||
TerminalSessions, UpdateAgentContext, UpdateAgentContextInput,
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared trace (ordering)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type Trace = Arc<Mutex<Vec<String>>>;
|
||||
|
||||
/// A recorded list of `(target, bytes)` writes, keyed by whatever addresses the
|
||||
/// target (a path for the fs, a [`SessionId`] for the pty).
|
||||
type WriteLog<K> = Arc<Mutex<Vec<(K, Vec<u8>)>>>;
|
||||
|
||||
fn trace() -> Trace {
|
||||
Arc::new(Mutex::new(Vec::new()))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// FakeContexts (AgentContextStore)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Default)]
|
||||
struct ContextsInner {
|
||||
manifest: AgentManifest,
|
||||
contents: HashMap<String, String>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct FakeContexts(Arc<Mutex<ContextsInner>>);
|
||||
|
||||
impl FakeContexts {
|
||||
fn new() -> Self {
|
||||
Self(Arc::new(Mutex::new(ContextsInner {
|
||||
manifest: AgentManifest {
|
||||
version: 1,
|
||||
entries: Vec::new(),
|
||||
},
|
||||
contents: HashMap::new(),
|
||||
})))
|
||||
}
|
||||
fn with_agent(agent: &Agent, content: &str) -> Self {
|
||||
let me = Self::new();
|
||||
{
|
||||
let mut inner = me.0.lock().unwrap();
|
||||
inner.manifest.entries.push(ManifestEntry::from_agent(agent));
|
||||
inner
|
||||
.contents
|
||||
.insert(agent.context_path.clone(), content.to_owned());
|
||||
}
|
||||
me
|
||||
}
|
||||
fn manifest(&self) -> AgentManifest {
|
||||
self.0.lock().unwrap().manifest.clone()
|
||||
}
|
||||
fn content(&self, md_path: &str) -> Option<String> {
|
||||
self.0.lock().unwrap().contents.get(md_path).cloned()
|
||||
}
|
||||
fn md_path_of(&self, agent: &AgentId) -> Option<String> {
|
||||
self.0
|
||||
.lock()
|
||||
.unwrap()
|
||||
.manifest
|
||||
.entries
|
||||
.iter()
|
||||
.find(|e| &e.agent_id == agent)
|
||||
.map(|e| e.md_path.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl AgentContextStore for FakeContexts {
|
||||
async fn read_context(
|
||||
&self,
|
||||
_project: &Project,
|
||||
agent: &AgentId,
|
||||
) -> Result<MarkdownDoc, StoreError> {
|
||||
let md_path = self.md_path_of(agent).ok_or(StoreError::NotFound)?;
|
||||
self.content(&md_path)
|
||||
.map(MarkdownDoc::new)
|
||||
.ok_or(StoreError::NotFound)
|
||||
}
|
||||
async fn write_context(
|
||||
&self,
|
||||
_project: &Project,
|
||||
agent: &AgentId,
|
||||
md: &MarkdownDoc,
|
||||
) -> Result<(), StoreError> {
|
||||
let md_path = self.md_path_of(agent).ok_or(StoreError::NotFound)?;
|
||||
self.0
|
||||
.lock()
|
||||
.unwrap()
|
||||
.contents
|
||||
.insert(md_path, md.as_str().to_owned());
|
||||
Ok(())
|
||||
}
|
||||
async fn load_manifest(&self, _project: &Project) -> Result<AgentManifest, StoreError> {
|
||||
Ok(self.manifest())
|
||||
}
|
||||
async fn save_manifest(
|
||||
&self,
|
||||
_project: &Project,
|
||||
manifest: &AgentManifest,
|
||||
) -> Result<(), StoreError> {
|
||||
self.0.lock().unwrap().manifest = manifest.clone();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// FakeProfiles (ProfileStore)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Clone)]
|
||||
struct FakeProfiles(Arc<Vec<AgentProfile>>);
|
||||
|
||||
impl FakeProfiles {
|
||||
fn new(profiles: Vec<AgentProfile>) -> Self {
|
||||
Self(Arc::new(profiles))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ProfileStore for FakeProfiles {
|
||||
async fn list(&self) -> Result<Vec<AgentProfile>, StoreError> {
|
||||
Ok((*self.0).clone())
|
||||
}
|
||||
async fn save(&self, _profile: &AgentProfile) -> Result<(), StoreError> {
|
||||
Ok(())
|
||||
}
|
||||
async fn delete(&self, _id: ProfileId) -> Result<(), StoreError> {
|
||||
Ok(())
|
||||
}
|
||||
async fn is_configured(&self) -> Result<bool, StoreError> {
|
||||
Ok(true)
|
||||
}
|
||||
async fn mark_configured(&self) -> Result<(), StoreError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// FakeRuntime (AgentRuntime) — records prepare + returns a configured plan
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
struct FakeRuntime {
|
||||
trace: Trace,
|
||||
plan: Option<ContextInjectionPlan>,
|
||||
}
|
||||
|
||||
impl FakeRuntime {
|
||||
fn new(trace: Trace, plan: Option<ContextInjectionPlan>) -> Self {
|
||||
Self { trace, plan }
|
||||
}
|
||||
}
|
||||
|
||||
impl AgentRuntime for FakeRuntime {
|
||||
fn detect(&self, _profile: &AgentProfile) -> Result<bool, RuntimeError> {
|
||||
Ok(true)
|
||||
}
|
||||
fn prepare_invocation(
|
||||
&self,
|
||||
profile: &AgentProfile,
|
||||
_ctx: &PreparedContext,
|
||||
cwd: &ProjectPath,
|
||||
) -> Result<SpawnSpec, RuntimeError> {
|
||||
self.trace.lock().unwrap().push("prepare".to_owned());
|
||||
Ok(SpawnSpec {
|
||||
command: profile.command.clone(),
|
||||
args: profile.args.clone(),
|
||||
cwd: cwd.clone(),
|
||||
env: Vec::new(),
|
||||
context_plan: self.plan.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// FakeFs (FileSystem) — records writes into the trace
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Clone)]
|
||||
struct FakeFs {
|
||||
trace: Trace,
|
||||
writes: WriteLog<String>,
|
||||
}
|
||||
|
||||
impl FakeFs {
|
||||
fn new(trace: Trace) -> Self {
|
||||
Self {
|
||||
trace,
|
||||
writes: Arc::new(Mutex::new(Vec::new())),
|
||||
}
|
||||
}
|
||||
fn writes(&self) -> Vec<(String, Vec<u8>)> {
|
||||
self.writes.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl FileSystem for FakeFs {
|
||||
async fn read(&self, path: &RemotePath) -> Result<Vec<u8>, FsError> {
|
||||
Err(FsError::NotFound(path.as_str().to_owned()))
|
||||
}
|
||||
async fn write(&self, path: &RemotePath, data: &[u8]) -> Result<(), FsError> {
|
||||
self.trace.lock().unwrap().push("fs.write".to_owned());
|
||||
self.writes
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push((path.as_str().to_owned(), data.to_vec()));
|
||||
Ok(())
|
||||
}
|
||||
async fn exists(&self, _path: &RemotePath) -> Result<bool, FsError> {
|
||||
Ok(false)
|
||||
}
|
||||
async fn create_dir_all(&self, _path: &RemotePath) -> Result<(), FsError> {
|
||||
Ok(())
|
||||
}
|
||||
async fn list(&self, _path: &RemotePath) -> Result<Vec<DirEntry>, FsError> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
async fn symlink(&self, _src: &RemotePath, _dst: &RemotePath) -> Result<(), FsError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// FakePty (PtyPort) — records spawn into the trace
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Clone)]
|
||||
struct FakePty {
|
||||
trace: Trace,
|
||||
next_id: SessionId,
|
||||
spawns: Arc<Mutex<Vec<SpawnSpec>>>,
|
||||
writes: WriteLog<SessionId>,
|
||||
}
|
||||
|
||||
impl FakePty {
|
||||
fn new(trace: Trace, next_id: SessionId) -> Self {
|
||||
Self {
|
||||
trace,
|
||||
next_id,
|
||||
spawns: Arc::new(Mutex::new(Vec::new())),
|
||||
writes: Arc::new(Mutex::new(Vec::new())),
|
||||
}
|
||||
}
|
||||
fn spawns(&self) -> Vec<SpawnSpec> {
|
||||
self.spawns.lock().unwrap().clone()
|
||||
}
|
||||
fn writes(&self) -> Vec<(SessionId, Vec<u8>)> {
|
||||
self.writes.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl PtyPort for FakePty {
|
||||
async fn spawn(&self, spec: SpawnSpec, _size: PtySize) -> Result<PtyHandle, PtyError> {
|
||||
self.trace.lock().unwrap().push("spawn".to_owned());
|
||||
self.spawns.lock().unwrap().push(spec);
|
||||
Ok(PtyHandle {
|
||||
session_id: self.next_id,
|
||||
})
|
||||
}
|
||||
fn write(&self, handle: &PtyHandle, data: &[u8]) -> Result<(), PtyError> {
|
||||
self.writes
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push((handle.session_id, data.to_vec()));
|
||||
Ok(())
|
||||
}
|
||||
fn resize(&self, _handle: &PtyHandle, _size: PtySize) -> Result<(), PtyError> {
|
||||
Ok(())
|
||||
}
|
||||
fn subscribe_output(&self, _handle: &PtyHandle) -> Result<OutputStream, PtyError> {
|
||||
Ok(Box::new(std::iter::empty()))
|
||||
}
|
||||
async fn kill(&self, _handle: &PtyHandle) -> Result<ExitStatus, PtyError> {
|
||||
Ok(ExitStatus { code: Some(0) })
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SpyBus + SeqIds
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
struct SpyBus(Arc<Mutex<Vec<DomainEvent>>>);
|
||||
impl SpyBus {
|
||||
fn events(&self) -> Vec<DomainEvent> {
|
||||
self.0.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
impl EventBus for SpyBus {
|
||||
fn publish(&self, event: DomainEvent) {
|
||||
self.0.lock().unwrap().push(event);
|
||||
}
|
||||
fn subscribe(&self) -> EventStream {
|
||||
Box::new(std::iter::empty())
|
||||
}
|
||||
}
|
||||
|
||||
struct SeqIds(Mutex<u128>);
|
||||
impl SeqIds {
|
||||
fn new() -> Self {
|
||||
Self(Mutex::new(1))
|
||||
}
|
||||
}
|
||||
impl IdGenerator for SeqIds {
|
||||
fn new_uuid(&self) -> Uuid {
|
||||
let mut n = self.0.lock().unwrap();
|
||||
let id = Uuid::from_u128(*n);
|
||||
*n += 1;
|
||||
id
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Builders
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn pid(n: u128) -> ProfileId {
|
||||
ProfileId::from_uuid(Uuid::from_u128(n))
|
||||
}
|
||||
fn aid(n: u128) -> AgentId {
|
||||
AgentId::from_uuid(Uuid::from_u128(n))
|
||||
}
|
||||
fn sid(n: u128) -> SessionId {
|
||||
SessionId::from_uuid(Uuid::from_u128(n))
|
||||
}
|
||||
|
||||
fn project() -> Project {
|
||||
Project::new(
|
||||
ProjectId::from_uuid(Uuid::from_u128(1000)),
|
||||
"demo",
|
||||
ProjectPath::new("/home/me/proj").unwrap(),
|
||||
RemoteRef::local(),
|
||||
1_700_000_000_000,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn profile(id: ProfileId, injection: ContextInjection) -> AgentProfile {
|
||||
AgentProfile::new(
|
||||
id,
|
||||
"Claude Code",
|
||||
"claude",
|
||||
Vec::new(),
|
||||
injection,
|
||||
Some("claude --version".to_owned()),
|
||||
"{projectRoot}",
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn scratch_agent(id: AgentId, name: &str, md: &str, profile_id: ProfileId) -> Agent {
|
||||
Agent::new(id, name, md, profile_id, AgentOrigin::Scratch, false).unwrap()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CreateAgentFromScratch
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_persists_manifest_entry_and_initial_context() {
|
||||
let contexts = FakeContexts::new();
|
||||
let bus = SpyBus::default();
|
||||
let create = CreateAgentFromScratch::new(
|
||||
Arc::new(contexts.clone()),
|
||||
Arc::new(SeqIds::new()),
|
||||
Arc::new(bus.clone()),
|
||||
);
|
||||
|
||||
let out = create
|
||||
.execute(CreateAgentInput {
|
||||
project: project(),
|
||||
name: "Backend Dev".to_owned(),
|
||||
profile_id: pid(9),
|
||||
initial_content: Some("# Backend".to_owned()),
|
||||
})
|
||||
.await
|
||||
.expect("create succeeds");
|
||||
|
||||
// md_path is slugified from the name.
|
||||
assert_eq!(out.agent.context_path, "agents/backend-dev.md");
|
||||
assert_eq!(out.agent.profile_id, pid(9));
|
||||
assert!(matches!(out.agent.origin, AgentOrigin::Scratch));
|
||||
assert!(!out.agent.synchronized);
|
||||
|
||||
// Manifest has exactly one entry for this agent; context stored under md_path.
|
||||
let manifest = contexts.manifest();
|
||||
assert_eq!(manifest.entries.len(), 1);
|
||||
assert_eq!(manifest.entries[0].agent_id, out.agent.id);
|
||||
assert_eq!(
|
||||
contexts.content("agents/backend-dev.md").as_deref(),
|
||||
Some("# Backend")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_disambiguates_md_path_on_name_collision() {
|
||||
// Seed a project that already has `agents/backend.md`.
|
||||
let existing = scratch_agent(aid(50), "Backend", "agents/backend.md", pid(9));
|
||||
let contexts = FakeContexts::with_agent(&existing, "old");
|
||||
let create = CreateAgentFromScratch::new(
|
||||
Arc::new(contexts.clone()),
|
||||
Arc::new(SeqIds::new()),
|
||||
Arc::new(SpyBus::default()),
|
||||
);
|
||||
|
||||
let out = create
|
||||
.execute(CreateAgentInput {
|
||||
project: project(),
|
||||
name: "Backend".to_owned(),
|
||||
profile_id: pid(9),
|
||||
initial_content: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(out.agent.context_path, "agents/backend-2.md");
|
||||
assert_eq!(contexts.manifest().entries.len(), 2);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ListAgents / Read / Update / Delete
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_reconstructs_agents_from_manifest() {
|
||||
let a = scratch_agent(aid(1), "Backend", "agents/backend.md", pid(9));
|
||||
let contexts = FakeContexts::with_agent(&a, "ctx");
|
||||
let list = ListAgents::new(Arc::new(contexts));
|
||||
|
||||
let out = list
|
||||
.execute(ListAgentsInput { project: project() })
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(out.agents, vec![a]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_then_update_context_roundtrips() {
|
||||
let a = scratch_agent(aid(1), "Backend", "agents/backend.md", pid(9));
|
||||
let contexts = FakeContexts::with_agent(&a, "original");
|
||||
let read = ReadAgentContext::new(Arc::new(contexts.clone()));
|
||||
let update = UpdateAgentContext::new(Arc::new(contexts.clone()));
|
||||
|
||||
let before = read
|
||||
.execute(ReadAgentContextInput {
|
||||
project: project(),
|
||||
agent_id: a.id,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(before.content.as_str(), "original");
|
||||
|
||||
update
|
||||
.execute(UpdateAgentContextInput {
|
||||
project: project(),
|
||||
agent_id: a.id,
|
||||
content: "edited".to_owned(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(contexts.content("agents/backend.md").as_deref(), Some("edited"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_removes_entry_then_unknown_is_not_found() {
|
||||
let a = scratch_agent(aid(1), "Backend", "agents/backend.md", pid(9));
|
||||
let contexts = FakeContexts::with_agent(&a, "ctx");
|
||||
let delete = DeleteAgent::new(Arc::new(contexts.clone()), Arc::new(SpyBus::default()));
|
||||
|
||||
delete
|
||||
.execute(DeleteAgentInput {
|
||||
project: project(),
|
||||
agent_id: a.id,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(contexts.manifest().entries.is_empty());
|
||||
|
||||
// Second delete: the agent is gone → NotFound.
|
||||
let err = delete
|
||||
.execute(DeleteAgentInput {
|
||||
project: project(),
|
||||
agent_id: a.id,
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "NOT_FOUND", "got {err:?}");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// LaunchAgent
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Everything a launch test needs to drive `LaunchAgent` and assert over the
|
||||
/// fakes: the use case, the seeded agent, the recording fs/pty, the event spy,
|
||||
/// the session registry and the shared ordering trace.
|
||||
type LaunchFixture = (
|
||||
LaunchAgent,
|
||||
Agent,
|
||||
FakeFs,
|
||||
FakePty,
|
||||
SpyBus,
|
||||
Arc<TerminalSessions>,
|
||||
Trace,
|
||||
);
|
||||
|
||||
/// Wires a LaunchAgent over fakes for a given injection strategy/plan.
|
||||
fn launch_fixture(injection: ContextInjection, plan: Option<ContextInjectionPlan>) -> LaunchFixture {
|
||||
let agent = scratch_agent(aid(1), "Backend", "agents/backend.md", pid(9));
|
||||
let contexts = FakeContexts::with_agent(&agent, "# ctx body");
|
||||
let profiles = FakeProfiles::new(vec![profile(pid(9), injection)]);
|
||||
let tr = trace();
|
||||
let runtime = FakeRuntime::new(Arc::clone(&tr), plan);
|
||||
let fs = FakeFs::new(Arc::clone(&tr));
|
||||
let pty = FakePty::new(Arc::clone(&tr), sid(777));
|
||||
let sessions = Arc::new(TerminalSessions::new());
|
||||
let bus = SpyBus::default();
|
||||
let launch = LaunchAgent::new(
|
||||
Arc::new(contexts),
|
||||
Arc::new(profiles),
|
||||
Arc::new(runtime),
|
||||
Arc::new(fs.clone()),
|
||||
Arc::new(pty.clone()),
|
||||
Arc::clone(&sessions),
|
||||
Arc::new(bus.clone()),
|
||||
);
|
||||
(launch, agent, fs, pty, bus, sessions, tr)
|
||||
}
|
||||
|
||||
fn launch_input(agent_id: AgentId) -> LaunchAgentInput {
|
||||
LaunchAgentInput {
|
||||
project: project(),
|
||||
agent_id,
|
||||
rows: 24,
|
||||
cols: 80,
|
||||
node_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn launch_orders_prepare_then_injection_then_spawn() {
|
||||
// conventionFile strategy → an fs.write must happen between prepare and spawn.
|
||||
let (launch, agent, fs, pty, bus, sessions, tr) = launch_fixture(
|
||||
ContextInjection::convention_file("CLAUDE.md").unwrap(),
|
||||
Some(ContextInjectionPlan::File {
|
||||
target: "CLAUDE.md".to_owned(),
|
||||
}),
|
||||
);
|
||||
|
||||
let out = launch.execute(launch_input(agent.id)).await.expect("launch");
|
||||
|
||||
// Ordering contract.
|
||||
assert_eq!(
|
||||
*tr.lock().unwrap(),
|
||||
vec!["prepare".to_owned(), "fs.write".to_owned(), "spawn".to_owned()],
|
||||
"prepare → injection → spawn"
|
||||
);
|
||||
|
||||
// The conventionFile was written to <cwd>/CLAUDE.md with the context body.
|
||||
let writes = fs.writes();
|
||||
assert_eq!(writes.len(), 1);
|
||||
assert_eq!(writes[0].0, "/home/me/proj/CLAUDE.md");
|
||||
assert_eq!(writes[0].1, b"# ctx body");
|
||||
|
||||
// Spawn happened at the resolved cwd with the profile command.
|
||||
let spawns = pty.spawns();
|
||||
assert_eq!(spawns.len(), 1);
|
||||
assert_eq!(spawns[0].command, "claude");
|
||||
assert_eq!(spawns[0].cwd.as_str(), "/home/me/proj");
|
||||
|
||||
// The session adopts the PTY id, is Running, and is registered as an agent.
|
||||
assert_eq!(out.session.id, sid(777));
|
||||
assert!(matches!(
|
||||
out.session.kind,
|
||||
domain::SessionKind::Agent { agent_id } if agent_id == agent.id
|
||||
));
|
||||
assert!(sessions.session(&sid(777)).is_some());
|
||||
|
||||
// AgentLaunched announced.
|
||||
assert_eq!(
|
||||
bus.events(),
|
||||
vec![DomainEvent::AgentLaunched {
|
||||
agent_id: agent.id,
|
||||
session_id: sid(777),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn launch_stdin_strategy_pipes_context_after_spawn() {
|
||||
let (launch, agent, fs, pty, _bus, _sessions, tr) =
|
||||
launch_fixture(ContextInjection::stdin(), Some(ContextInjectionPlan::Stdin));
|
||||
|
||||
launch.execute(launch_input(agent.id)).await.unwrap();
|
||||
|
||||
// No file written for stdin; content is piped to the PTY post-spawn.
|
||||
assert!(fs.writes().is_empty(), "stdin must not write a file");
|
||||
assert_eq!(*tr.lock().unwrap(), vec!["prepare".to_owned(), "spawn".to_owned()]);
|
||||
let writes = pty.writes();
|
||||
assert_eq!(writes.len(), 1);
|
||||
assert_eq!(writes[0].0, sid(777));
|
||||
assert_eq!(writes[0].1, b"# ctx body");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn launch_unknown_agent_is_not_found() {
|
||||
let (launch, _agent, _fs, pty, _bus, _sessions, _tr) = launch_fixture(
|
||||
ContextInjection::stdin(),
|
||||
Some(ContextInjectionPlan::Stdin),
|
||||
);
|
||||
let err = launch.execute(launch_input(aid(404))).await.unwrap_err();
|
||||
assert_eq!(err.code(), "NOT_FOUND", "got {err:?}");
|
||||
assert!(pty.spawns().is_empty(), "no spawn for unknown agent");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn launch_unknown_profile_is_not_found() {
|
||||
// The agent references pid(9) but the store only knows pid(1).
|
||||
let agent = scratch_agent(aid(1), "Backend", "agents/backend.md", pid(9));
|
||||
let contexts = FakeContexts::with_agent(&agent, "ctx");
|
||||
let profiles = FakeProfiles::new(vec![profile(pid(1), ContextInjection::stdin())]);
|
||||
let tr = trace();
|
||||
let pty = FakePty::new(Arc::clone(&tr), sid(777));
|
||||
let launch = LaunchAgent::new(
|
||||
Arc::new(contexts),
|
||||
Arc::new(profiles),
|
||||
Arc::new(FakeRuntime::new(Arc::clone(&tr), Some(ContextInjectionPlan::Stdin))),
|
||||
Arc::new(FakeFs::new(Arc::clone(&tr))),
|
||||
Arc::new(pty.clone()),
|
||||
Arc::new(TerminalSessions::new()),
|
||||
Arc::new(SpyBus::default()),
|
||||
);
|
||||
|
||||
let err = launch.execute(launch_input(agent.id)).await.unwrap_err();
|
||||
assert_eq!(err.code(), "NOT_FOUND", "got {err:?}");
|
||||
assert!(pty.spawns().is_empty(), "no spawn when profile unresolved");
|
||||
}
|
||||
57
crates/application/tests/error_codes.rs
Normal file
57
crates/application/tests/error_codes.rs
Normal file
@ -0,0 +1,57 @@
|
||||
//! L1 tests pinning the stable [`AppError::code`] strings the IPC `ErrorDto`
|
||||
//! relies on, and the per-port `From` mappings.
|
||||
|
||||
use application::AppError;
|
||||
use domain::ports::{FsError, GitError, ProcessError, PtyError, RemoteError, StoreError};
|
||||
|
||||
#[test]
|
||||
fn codes_are_stable() {
|
||||
assert_eq!(AppError::NotFound("x".into()).code(), "NOT_FOUND");
|
||||
assert_eq!(AppError::Invalid("x".into()).code(), "INVALID");
|
||||
assert_eq!(AppError::FileSystem("x".into()).code(), "FILESYSTEM");
|
||||
assert_eq!(AppError::Store("x".into()).code(), "STORE");
|
||||
assert_eq!(AppError::Process("x".into()).code(), "PROCESS");
|
||||
assert_eq!(AppError::Git("x".into()).code(), "GIT");
|
||||
assert_eq!(AppError::Remote("x".into()).code(), "REMOTE");
|
||||
assert_eq!(AppError::Internal("x".into()).code(), "INTERNAL");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fs_not_found_maps_to_not_found_other_to_filesystem() {
|
||||
assert_eq!(
|
||||
AppError::from(FsError::NotFound("/tmp/x".into())).code(),
|
||||
"NOT_FOUND"
|
||||
);
|
||||
assert_eq!(
|
||||
AppError::from(FsError::PermissionDenied("/tmp/x".into())).code(),
|
||||
"FILESYSTEM"
|
||||
);
|
||||
assert_eq!(AppError::from(FsError::Io("boom".into())).code(), "FILESYSTEM");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_not_found_maps_to_not_found_other_to_store() {
|
||||
assert_eq!(AppError::from(StoreError::NotFound).code(), "NOT_FOUND");
|
||||
assert_eq!(
|
||||
AppError::from(StoreError::Serialization("bad".into())).code(),
|
||||
"STORE"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_pty_runtime_map_to_process() {
|
||||
assert_eq!(AppError::from(PtyError::NotFound).code(), "PROCESS");
|
||||
assert_eq!(
|
||||
AppError::from(ProcessError::Spawn("x".into())).code(),
|
||||
"PROCESS"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_and_remote_map_through() {
|
||||
assert_eq!(AppError::from(GitError::NotFound).code(), "GIT");
|
||||
assert_eq!(
|
||||
AppError::from(RemoteError::Auth("nope".into())).code(),
|
||||
"REMOTE"
|
||||
);
|
||||
}
|
||||
240
crates/application/tests/git_usecases.rs
Normal file
240
crates/application/tests/git_usecases.rs
Normal file
@ -0,0 +1,240 @@
|
||||
//! L8 tests for the Git use cases with a faked [`GitPort`] (no real repo):
|
||||
//! pass-through to the port, event emission on state changes, and input
|
||||
//! validation (empty message, non-absolute root).
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use domain::events::DomainEvent;
|
||||
use domain::ports::{
|
||||
EventBus, EventStream, GitCommitInfo, GitError, GitFileStatus, GitPort, GraphCommit,
|
||||
};
|
||||
use domain::{ProjectId, ProjectPath};
|
||||
use uuid::Uuid;
|
||||
|
||||
use application::{
|
||||
GitBranches, GitBranchesInput, GitCheckout, GitCheckoutInput, GitCommit, GitCommitInput,
|
||||
GitStage, GitStagePathInput, GitStatus, GitStatusInput,
|
||||
};
|
||||
|
||||
/// A recording [`GitPort`] with canned return values.
|
||||
#[derive(Default)]
|
||||
struct FakeGitInner {
|
||||
calls: Vec<String>,
|
||||
status: Vec<GitFileStatus>,
|
||||
branches: Vec<String>,
|
||||
current: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
struct FakeGit(Arc<Mutex<FakeGitInner>>);
|
||||
impl FakeGit {
|
||||
fn calls(&self) -> Vec<String> {
|
||||
self.0.lock().unwrap().calls.clone()
|
||||
}
|
||||
fn set_status(&self, s: Vec<GitFileStatus>) {
|
||||
self.0.lock().unwrap().status = s;
|
||||
}
|
||||
fn set_branches(&self, b: Vec<String>, current: Option<String>) {
|
||||
let mut i = self.0.lock().unwrap();
|
||||
i.branches = b;
|
||||
i.current = current;
|
||||
}
|
||||
fn record(&self, c: &str) {
|
||||
self.0.lock().unwrap().calls.push(c.to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl GitPort for FakeGit {
|
||||
async fn init(&self, _r: &ProjectPath) -> Result<(), GitError> {
|
||||
self.record("init");
|
||||
Ok(())
|
||||
}
|
||||
async fn status(&self, _r: &ProjectPath) -> Result<Vec<GitFileStatus>, GitError> {
|
||||
self.record("status");
|
||||
Ok(self.0.lock().unwrap().status.clone())
|
||||
}
|
||||
async fn stage(&self, _r: &ProjectPath, path: &str) -> Result<(), GitError> {
|
||||
self.record(&format!("stage:{path}"));
|
||||
Ok(())
|
||||
}
|
||||
async fn unstage(&self, _r: &ProjectPath, path: &str) -> Result<(), GitError> {
|
||||
self.record(&format!("unstage:{path}"));
|
||||
Ok(())
|
||||
}
|
||||
async fn commit(&self, _r: &ProjectPath, message: &str) -> Result<GitCommitInfo, GitError> {
|
||||
self.record(&format!("commit:{message}"));
|
||||
Ok(GitCommitInfo {
|
||||
hash: "abc123".to_owned(),
|
||||
summary: message.to_owned(),
|
||||
})
|
||||
}
|
||||
async fn branches(&self, _r: &ProjectPath) -> Result<Vec<String>, GitError> {
|
||||
self.record("branches");
|
||||
Ok(self.0.lock().unwrap().branches.clone())
|
||||
}
|
||||
async fn current_branch(&self, _r: &ProjectPath) -> Result<Option<String>, GitError> {
|
||||
self.record("current_branch");
|
||||
Ok(self.0.lock().unwrap().current.clone())
|
||||
}
|
||||
async fn checkout(&self, _r: &ProjectPath, branch: &str) -> Result<(), GitError> {
|
||||
self.record(&format!("checkout:{branch}"));
|
||||
Ok(())
|
||||
}
|
||||
async fn log(
|
||||
&self,
|
||||
_r: &ProjectPath,
|
||||
_limit: usize,
|
||||
) -> Result<Vec<GitCommitInfo>, GitError> {
|
||||
self.record("log");
|
||||
Ok(Vec::new())
|
||||
}
|
||||
async fn log_graph(
|
||||
&self,
|
||||
_r: &ProjectPath,
|
||||
_limit: usize,
|
||||
) -> Result<Vec<GraphCommit>, GitError> {
|
||||
self.record("log_graph");
|
||||
Ok(Vec::new())
|
||||
}
|
||||
async fn pull(&self, _r: &ProjectPath) -> Result<(), GitError> {
|
||||
Ok(())
|
||||
}
|
||||
async fn push(&self, _r: &ProjectPath) -> Result<(), GitError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
struct SpyBus(Arc<Mutex<Vec<DomainEvent>>>);
|
||||
impl SpyBus {
|
||||
fn events(&self) -> Vec<DomainEvent> {
|
||||
self.0.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
impl EventBus for SpyBus {
|
||||
fn publish(&self, event: DomainEvent) {
|
||||
self.0.lock().unwrap().push(event);
|
||||
}
|
||||
fn subscribe(&self) -> EventStream {
|
||||
Box::new(std::iter::empty())
|
||||
}
|
||||
}
|
||||
|
||||
fn pid() -> ProjectId {
|
||||
ProjectId::from_uuid(Uuid::from_u128(1))
|
||||
}
|
||||
const ROOT: &str = "/home/me/repo";
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_passes_through_to_port() {
|
||||
let git = FakeGit::default();
|
||||
git.set_status(vec![GitFileStatus {
|
||||
path: "a.txt".to_owned(),
|
||||
staged: true,
|
||||
}]);
|
||||
let out = GitStatus::new(Arc::new(git.clone()))
|
||||
.execute(GitStatusInput { root: ROOT.to_owned() })
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(out.entries.len(), 1);
|
||||
assert_eq!(out.entries[0].path, "a.txt");
|
||||
assert_eq!(git.calls(), vec!["status"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_rejects_non_absolute_root() {
|
||||
let git = FakeGit::default();
|
||||
let err = GitStatus::new(Arc::new(git.clone()))
|
||||
.execute(GitStatusInput {
|
||||
root: "relative/path".to_owned(),
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "INVALID", "got {err:?}");
|
||||
assert!(git.calls().is_empty(), "no port call on invalid root");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stage_calls_port_with_path() {
|
||||
let git = FakeGit::default();
|
||||
GitStage::new(Arc::new(git.clone()))
|
||||
.execute(GitStagePathInput {
|
||||
root: ROOT.to_owned(),
|
||||
path: "src/x.rs".to_owned(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(git.calls(), vec!["stage:src/x.rs"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn commit_returns_commit_and_publishes_event() {
|
||||
let git = FakeGit::default();
|
||||
let bus = SpyBus::default();
|
||||
let out = GitCommit::new(Arc::new(git.clone()), Arc::new(bus.clone()))
|
||||
.execute(GitCommitInput {
|
||||
project_id: pid(),
|
||||
root: ROOT.to_owned(),
|
||||
message: "feat: x".to_owned(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(out.commit.hash, "abc123");
|
||||
assert_eq!(out.commit.summary, "feat: x");
|
||||
assert_eq!(git.calls(), vec!["commit:feat: x"]);
|
||||
assert_eq!(
|
||||
bus.events(),
|
||||
vec![DomainEvent::GitStateChanged { project_id: pid() }]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn commit_rejects_empty_message_without_touching_port() {
|
||||
let git = FakeGit::default();
|
||||
let bus = SpyBus::default();
|
||||
let err = GitCommit::new(Arc::new(git.clone()), Arc::new(bus.clone()))
|
||||
.execute(GitCommitInput {
|
||||
project_id: pid(),
|
||||
root: ROOT.to_owned(),
|
||||
message: " ".to_owned(),
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "INVALID", "got {err:?}");
|
||||
assert!(git.calls().is_empty(), "no commit attempted");
|
||||
assert!(bus.events().is_empty(), "no event on rejected commit");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn checkout_publishes_event() {
|
||||
let git = FakeGit::default();
|
||||
let bus = SpyBus::default();
|
||||
GitCheckout::new(Arc::new(git.clone()), Arc::new(bus.clone()))
|
||||
.execute(GitCheckoutInput {
|
||||
project_id: pid(),
|
||||
root: ROOT.to_owned(),
|
||||
branch: "dev".to_owned(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(git.calls(), vec!["checkout:dev"]);
|
||||
assert_eq!(
|
||||
bus.events(),
|
||||
vec![DomainEvent::GitStateChanged { project_id: pid() }]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn branches_returns_list_and_current() {
|
||||
let git = FakeGit::default();
|
||||
git.set_branches(vec!["main".to_owned(), "dev".to_owned()], Some("main".to_owned()));
|
||||
let out = GitBranches::new(Arc::new(git.clone()))
|
||||
.execute(GitBranchesInput { root: ROOT.to_owned() })
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(out.branches, vec!["main", "dev"]);
|
||||
assert_eq!(out.current.as_deref(), Some("main"));
|
||||
assert_eq!(git.calls(), vec!["branches", "current_branch"]);
|
||||
}
|
||||
96
crates/application/tests/health.rs
Normal file
96
crates/application/tests/health.rs
Normal file
@ -0,0 +1,96 @@
|
||||
//! L1 tests for [`HealthUseCase`] driven entirely through **mocked/fake ports**
|
||||
//! (`FixedClock`, `SeqIdGenerator`, a spy `EventBus`), exercising DI without any
|
||||
//! real I/O (README "Domaine/application testés sans I/O").
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use application::{HealthInput, HealthUseCase};
|
||||
use domain::events::DomainEvent;
|
||||
use domain::ports::{Clock, EventBus, EventStream, IdGenerator};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// A clock that always returns the same configured instant.
|
||||
struct FixedClock(i64);
|
||||
impl Clock for FixedClock {
|
||||
fn now_millis(&self) -> i64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// An id generator yielding a deterministic, predefined UUID.
|
||||
struct SeqIdGenerator(Uuid);
|
||||
impl IdGenerator for SeqIdGenerator {
|
||||
fn new_uuid(&self) -> Uuid {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// A spy event bus capturing every published event for assertions.
|
||||
#[derive(Default)]
|
||||
struct SpyEventBus {
|
||||
published: Mutex<Vec<DomainEvent>>,
|
||||
}
|
||||
impl EventBus for SpyEventBus {
|
||||
fn publish(&self, event: DomainEvent) {
|
||||
self.published.lock().unwrap().push(event);
|
||||
}
|
||||
fn subscribe(&self) -> EventStream {
|
||||
Box::new(std::iter::empty())
|
||||
}
|
||||
}
|
||||
|
||||
fn fixed_uuid() -> Uuid {
|
||||
Uuid::parse_str("11111111-2222-3333-4444-555555555555").unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn health_report_reflects_injected_ports_and_input() {
|
||||
let clock = Arc::new(FixedClock(1_700_000_000_123));
|
||||
let ids = Arc::new(SeqIdGenerator(fixed_uuid()));
|
||||
let bus = Arc::new(SpyEventBus::default());
|
||||
|
||||
let uc = HealthUseCase::new(clock, ids, Arc::clone(&bus) as Arc<dyn EventBus>);
|
||||
|
||||
let report = uc
|
||||
.execute(HealthInput {
|
||||
note: Some("ping".to_owned()),
|
||||
})
|
||||
.expect("health never errs");
|
||||
|
||||
assert!(report.alive);
|
||||
assert_eq!(report.time_millis, 1_700_000_000_123);
|
||||
assert_eq!(report.correlation_id, fixed_uuid().to_string());
|
||||
assert_eq!(report.note.as_deref(), Some("ping"));
|
||||
assert_eq!(report.version, env!("CARGO_PKG_VERSION"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn health_publishes_exactly_one_domain_event() {
|
||||
let clock = Arc::new(FixedClock(0));
|
||||
let ids = Arc::new(SeqIdGenerator(fixed_uuid()));
|
||||
let bus = Arc::new(SpyEventBus::default());
|
||||
|
||||
let uc = HealthUseCase::new(clock, ids, Arc::clone(&bus) as Arc<dyn EventBus>);
|
||||
uc.execute(HealthInput::default()).unwrap();
|
||||
|
||||
let published = bus.published.lock().unwrap();
|
||||
assert_eq!(published.len(), 1, "exactly one smoke event is published");
|
||||
match &published[0] {
|
||||
DomainEvent::ProjectCreated { project_id } => {
|
||||
// The smoke event reuses the correlation id as the (fake) project id.
|
||||
assert_eq!(project_id.as_uuid(), fixed_uuid());
|
||||
}
|
||||
other => panic!("expected ProjectCreated smoke event, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn health_note_defaults_to_none() {
|
||||
let uc = HealthUseCase::new(
|
||||
Arc::new(FixedClock(42)),
|
||||
Arc::new(SeqIdGenerator(fixed_uuid())),
|
||||
Arc::new(SpyEventBus::default()),
|
||||
);
|
||||
let report = uc.execute(HealthInput::default()).unwrap();
|
||||
assert_eq!(report.note, None);
|
||||
}
|
||||
814
crates/application/tests/layout_usecases.rs
Normal file
814
crates/application/tests/layout_usecases.rs
Normal file
@ -0,0 +1,814 @@
|
||||
//! L4 + #4 tests for the layout use cases (`LoadLayout`, `MutateLayout`) and the
|
||||
//! named-layout management (`ListLayouts`, `CreateLayout`, `RenameLayout`,
|
||||
//! `DeleteLayout`, `SetActiveLayout`).
|
||||
//!
|
||||
//! Every port is faked in-memory so the use cases run without any real I/O.
|
||||
//! Layouts now persist to `.ideai/layouts.json` (a collection); a legacy
|
||||
//! `.ideai/layout.json` is migrated transparently.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use domain::events::DomainEvent;
|
||||
use domain::layout::Workspace;
|
||||
use domain::ports::{
|
||||
DirEntry, EventBus, EventStream, FileSystem, FsError, IdGenerator, ProjectStore, RemotePath,
|
||||
StoreError,
|
||||
};
|
||||
use domain::{
|
||||
AgentId, Direction, LayoutId, LayoutNode, LayoutTree, LeafCell, NodeId, Project, ProjectId,
|
||||
ProjectPath, RemoteRef, SessionId,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
use application::{
|
||||
CreateLayout, CreateLayoutInput, DeleteLayout, DeleteLayoutInput, LayoutKind, LayoutOperation,
|
||||
ListLayouts, ListLayoutsInput, LoadLayout, LoadLayoutInput, MutateLayout, MutateLayoutInput,
|
||||
RenameLayout, RenameLayoutInput, SetActiveLayout, SetActiveLayoutInput,
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fakes
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Default)]
|
||||
struct FakeFsInner {
|
||||
files: HashMap<String, Vec<u8>>,
|
||||
dirs: HashSet<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
struct FakeFs(Arc<Mutex<FakeFsInner>>);
|
||||
|
||||
impl FakeFs {
|
||||
fn read_file(&self, path: &str) -> Option<Vec<u8>> {
|
||||
self.0.lock().unwrap().files.get(path).cloned()
|
||||
}
|
||||
fn has_dir(&self, path: &str) -> bool {
|
||||
self.0.lock().unwrap().dirs.contains(path)
|
||||
}
|
||||
fn put(&self, path: &str, data: &[u8]) {
|
||||
self.0
|
||||
.lock()
|
||||
.unwrap()
|
||||
.files
|
||||
.insert(path.to_owned(), data.to_vec());
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl FileSystem for FakeFs {
|
||||
async fn read(&self, path: &RemotePath) -> Result<Vec<u8>, FsError> {
|
||||
self.0
|
||||
.lock()
|
||||
.unwrap()
|
||||
.files
|
||||
.get(path.as_str())
|
||||
.cloned()
|
||||
.ok_or_else(|| FsError::NotFound(path.as_str().to_owned()))
|
||||
}
|
||||
async fn write(&self, path: &RemotePath, data: &[u8]) -> Result<(), FsError> {
|
||||
self.0
|
||||
.lock()
|
||||
.unwrap()
|
||||
.files
|
||||
.insert(path.as_str().to_owned(), data.to_vec());
|
||||
Ok(())
|
||||
}
|
||||
async fn exists(&self, path: &RemotePath) -> Result<bool, FsError> {
|
||||
let inner = self.0.lock().unwrap();
|
||||
Ok(inner.files.contains_key(path.as_str()) || inner.dirs.contains(path.as_str()))
|
||||
}
|
||||
async fn create_dir_all(&self, path: &RemotePath) -> Result<(), FsError> {
|
||||
self.0.lock().unwrap().dirs.insert(path.as_str().to_owned());
|
||||
Ok(())
|
||||
}
|
||||
async fn list(&self, _path: &RemotePath) -> Result<Vec<DirEntry>, FsError> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
async fn symlink(&self, _src: &RemotePath, _dst: &RemotePath) -> Result<(), FsError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct FakeStoreInner {
|
||||
projects: Vec<Project>,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
struct FakeStore(Arc<Mutex<FakeStoreInner>>);
|
||||
|
||||
#[async_trait]
|
||||
impl ProjectStore for FakeStore {
|
||||
async fn list_projects(&self) -> Result<Vec<Project>, StoreError> {
|
||||
Ok(self.0.lock().unwrap().projects.clone())
|
||||
}
|
||||
async fn load_project(&self, id: ProjectId) -> Result<Project, StoreError> {
|
||||
self.0
|
||||
.lock()
|
||||
.unwrap()
|
||||
.projects
|
||||
.iter()
|
||||
.find(|p| p.id == id)
|
||||
.cloned()
|
||||
.ok_or(StoreError::NotFound)
|
||||
}
|
||||
async fn save_project(&self, project: &Project) -> Result<(), StoreError> {
|
||||
self.0.lock().unwrap().projects.push(project.clone());
|
||||
Ok(())
|
||||
}
|
||||
async fn save_workspace(&self, _w: &Workspace) -> Result<(), StoreError> {
|
||||
Ok(())
|
||||
}
|
||||
async fn load_workspace(&self) -> Result<Workspace, StoreError> {
|
||||
Ok(Workspace::default())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
struct SpyBus(Arc<Mutex<Vec<DomainEvent>>>);
|
||||
impl SpyBus {
|
||||
fn events(&self) -> Vec<DomainEvent> {
|
||||
self.0.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
impl EventBus for SpyBus {
|
||||
fn publish(&self, event: DomainEvent) {
|
||||
self.0.lock().unwrap().push(event);
|
||||
}
|
||||
fn subscribe(&self) -> EventStream {
|
||||
Box::new(std::iter::empty())
|
||||
}
|
||||
}
|
||||
|
||||
struct SeqIds(Mutex<u128>);
|
||||
impl SeqIds {
|
||||
fn new(start: u128) -> Self {
|
||||
Self(Mutex::new(start))
|
||||
}
|
||||
}
|
||||
impl IdGenerator for SeqIds {
|
||||
fn new_uuid(&self) -> Uuid {
|
||||
let mut n = self.0.lock().unwrap();
|
||||
let id = Uuid::from_u128(*n);
|
||||
*n += 1;
|
||||
id
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const ROOT: &str = "/home/me/proj";
|
||||
const LAYOUTS_PATH: &str = "/home/me/proj/.ideai/layouts.json";
|
||||
const LEGACY_PATH: &str = "/home/me/proj/.ideai/layout.json";
|
||||
|
||||
fn pid(n: u128) -> ProjectId {
|
||||
ProjectId::from_uuid(Uuid::from_u128(n))
|
||||
}
|
||||
fn nid(n: u128) -> NodeId {
|
||||
NodeId::from_uuid(Uuid::from_u128(n))
|
||||
}
|
||||
fn sid(n: u128) -> SessionId {
|
||||
SessionId::from_uuid(Uuid::from_u128(n))
|
||||
}
|
||||
fn lid(n: u128) -> LayoutId {
|
||||
LayoutId::from_uuid(Uuid::from_u128(n))
|
||||
}
|
||||
|
||||
async fn register_project(store: &FakeStore, id: ProjectId) -> ProjectId {
|
||||
let project =
|
||||
Project::new(id, "Demo", ProjectPath::new(ROOT).unwrap(), RemoteRef::Local, 0).unwrap();
|
||||
store.save_project(&project).await.unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
fn single_leaf(node_id: NodeId) -> LayoutTree {
|
||||
LayoutTree::single(LeafCell {
|
||||
id: node_id,
|
||||
session: None,
|
||||
agent: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Seeds a valid `layouts.json` with a single active layout holding `tree`.
|
||||
fn seed_layouts(fs: &FakeFs, id: LayoutId, tree: &LayoutTree) {
|
||||
let doc = serde_json::json!({
|
||||
"version": 1,
|
||||
"activeId": id.to_string(),
|
||||
"layouts": [ { "id": id.to_string(), "name": "Default", "tree": tree } ],
|
||||
});
|
||||
fs.put(LAYOUTS_PATH, &serde_json::to_vec(&doc).unwrap());
|
||||
}
|
||||
|
||||
fn doc_json(fs: &FakeFs) -> serde_json::Value {
|
||||
serde_json::from_slice(&fs.read_file(LAYOUTS_PATH).expect("layouts.json written")).unwrap()
|
||||
}
|
||||
|
||||
/// The JSON of the active layout's tree.
|
||||
fn active_tree_json(fs: &FakeFs) -> serde_json::Value {
|
||||
let doc = doc_json(fs);
|
||||
let active = doc["activeId"].clone();
|
||||
doc["layouts"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|l| l["id"] == active)
|
||||
.expect("active layout present")["tree"]
|
||||
.clone()
|
||||
}
|
||||
|
||||
fn read_active_tree(fs: &FakeFs) -> LayoutTree {
|
||||
serde_json::from_value(active_tree_json(fs)).expect("active tree parseable")
|
||||
}
|
||||
|
||||
fn root_leaf_id(tree: &LayoutTree) -> NodeId {
|
||||
match &tree.root {
|
||||
LayoutNode::Leaf(l) => l.id,
|
||||
_ => panic!("expected a single-leaf root"),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// LoadLayout
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn load_returns_persisted_active_layout() {
|
||||
let store = FakeStore::default();
|
||||
let fs = FakeFs::default();
|
||||
let id = register_project(&store, pid(1)).await;
|
||||
seed_layouts(&fs, lid(1), &single_leaf(nid(42)));
|
||||
|
||||
let load = LoadLayout::new(Arc::new(store), Arc::new(fs));
|
||||
let out = load
|
||||
.execute(LoadLayoutInput {
|
||||
project_id: id,
|
||||
layout_id: None,
|
||||
})
|
||||
.await
|
||||
.expect("load succeeds");
|
||||
|
||||
assert_eq!(out.layout_id, lid(1));
|
||||
assert_eq!(root_leaf_id(&out.layout), nid(42));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn load_migrates_a_legacy_layout_json() {
|
||||
let store = FakeStore::default();
|
||||
let fs = FakeFs::default();
|
||||
let id = register_project(&store, pid(2)).await;
|
||||
// Only the legacy single-layout file exists.
|
||||
fs.put(LEGACY_PATH, &serde_json::to_vec(&single_leaf(nid(7))).unwrap());
|
||||
|
||||
let load = LoadLayout::new(Arc::new(store), Arc::new(fs.clone()));
|
||||
let out = load
|
||||
.execute(LoadLayoutInput {
|
||||
project_id: id,
|
||||
layout_id: None,
|
||||
})
|
||||
.await
|
||||
.expect("legacy layout migrates");
|
||||
|
||||
assert_eq!(root_leaf_id(&out.layout), nid(7), "legacy tree preserved");
|
||||
// A layouts.json was written with that tree as the active layout.
|
||||
assert_eq!(root_leaf_id(&read_active_tree(&fs)), nid(7));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn load_defaults_to_single_empty_leaf_when_absent() {
|
||||
let store = FakeStore::default();
|
||||
let fs = FakeFs::default();
|
||||
let id = register_project(&store, pid(3)).await;
|
||||
|
||||
let load = LoadLayout::new(Arc::new(store), Arc::new(fs.clone()));
|
||||
let out = load
|
||||
.execute(LoadLayoutInput {
|
||||
project_id: id,
|
||||
layout_id: None,
|
||||
})
|
||||
.await
|
||||
.expect("absent layout does not fail");
|
||||
|
||||
match &out.layout.root {
|
||||
LayoutNode::Leaf(l) => assert!(l.session.is_none()),
|
||||
_ => panic!("expected a single default leaf"),
|
||||
}
|
||||
// Default was written through; two loads are deterministic.
|
||||
assert_eq!(root_leaf_id(&read_active_tree(&fs)), root_leaf_id(&out.layout));
|
||||
assert!(fs.has_dir("/home/me/proj/.ideai"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn load_tolerates_corrupt_json_with_default() {
|
||||
let store = FakeStore::default();
|
||||
let fs = FakeFs::default();
|
||||
let id = register_project(&store, pid(4)).await;
|
||||
fs.put(LAYOUTS_PATH, b"{ not json ]");
|
||||
|
||||
let load = LoadLayout::new(Arc::new(store), Arc::new(fs));
|
||||
let out = load
|
||||
.execute(LoadLayoutInput {
|
||||
project_id: id,
|
||||
layout_id: None,
|
||||
})
|
||||
.await
|
||||
.expect("corrupt JSON falls back to default");
|
||||
|
||||
assert!(matches!(out.layout.root, LayoutNode::Leaf(_)));
|
||||
assert!(out.layout.validate().is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn load_unknown_layout_id_is_not_found() {
|
||||
let store = FakeStore::default();
|
||||
let fs = FakeFs::default();
|
||||
let id = register_project(&store, pid(5)).await;
|
||||
seed_layouts(&fs, lid(1), &single_leaf(nid(1)));
|
||||
|
||||
let load = LoadLayout::new(Arc::new(store), Arc::new(fs));
|
||||
let err = load
|
||||
.execute(LoadLayoutInput {
|
||||
project_id: id,
|
||||
layout_id: Some(lid(999)),
|
||||
})
|
||||
.await
|
||||
.expect_err("unknown layout id rejected");
|
||||
assert_eq!(err.code(), "NOT_FOUND", "got {err:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn load_unknown_project_is_not_found() {
|
||||
let store = FakeStore::default();
|
||||
let fs = FakeFs::default();
|
||||
let load = LoadLayout::new(Arc::new(store), Arc::new(fs));
|
||||
let err = load
|
||||
.execute(LoadLayoutInput {
|
||||
project_id: pid(999),
|
||||
layout_id: None,
|
||||
})
|
||||
.await
|
||||
.expect_err("unknown project rejected");
|
||||
assert_eq!(err.code(), "NOT_FOUND", "got {err:?}");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MutateLayout
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
struct MutEnv {
|
||||
fs: FakeFs,
|
||||
bus: SpyBus,
|
||||
mutate: MutateLayout,
|
||||
project_id: ProjectId,
|
||||
}
|
||||
|
||||
async fn mut_env(project_id: ProjectId) -> MutEnv {
|
||||
let store = FakeStore::default();
|
||||
let fs = FakeFs::default();
|
||||
let bus = SpyBus::default();
|
||||
register_project(&store, project_id).await;
|
||||
seed_layouts(&fs, lid(1), &single_leaf(nid(1)));
|
||||
|
||||
let mutate = MutateLayout::new(
|
||||
Arc::new(store.clone()),
|
||||
Arc::new(fs.clone()),
|
||||
Arc::new(bus.clone()),
|
||||
);
|
||||
MutEnv {
|
||||
fs,
|
||||
bus,
|
||||
mutate,
|
||||
project_id,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mutate_split_persists_camelcase_layout_and_announces() {
|
||||
let env = mut_env(pid(10)).await;
|
||||
let out = env
|
||||
.mutate
|
||||
.execute(MutateLayoutInput {
|
||||
project_id: env.project_id,
|
||||
layout_id: None,
|
||||
operation: LayoutOperation::Split {
|
||||
target: nid(1),
|
||||
direction: Direction::Row,
|
||||
new_leaf: nid(2),
|
||||
container: nid(9),
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("split succeeds");
|
||||
|
||||
match &out.layout.root {
|
||||
LayoutNode::Split(s) => assert_eq!(s.children.len(), 2),
|
||||
_ => panic!("expected a split root"),
|
||||
}
|
||||
|
||||
assert!(env.fs.has_dir("/home/me/proj/.ideai"));
|
||||
let tree = active_tree_json(&env.fs);
|
||||
assert_eq!(tree["root"]["type"], "split", "tagged on `type`");
|
||||
assert_eq!(tree["root"]["node"]["direction"], "row");
|
||||
assert_eq!(tree["root"]["node"]["children"].as_array().unwrap().len(), 2);
|
||||
|
||||
assert_eq!(
|
||||
env.bus.events(),
|
||||
vec![DomainEvent::LayoutChanged {
|
||||
project_id: env.project_id
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mutate_resize_writes_new_weights() {
|
||||
let env = mut_env(pid(11)).await;
|
||||
env.mutate
|
||||
.execute(MutateLayoutInput {
|
||||
project_id: env.project_id,
|
||||
layout_id: None,
|
||||
operation: LayoutOperation::Split {
|
||||
target: nid(1),
|
||||
direction: Direction::Row,
|
||||
new_leaf: nid(2),
|
||||
container: nid(9),
|
||||
},
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
env.mutate
|
||||
.execute(MutateLayoutInput {
|
||||
project_id: env.project_id,
|
||||
layout_id: None,
|
||||
operation: LayoutOperation::Resize {
|
||||
container: nid(9),
|
||||
weights: vec![3.0, 1.0],
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("resize succeeds");
|
||||
|
||||
let tree = active_tree_json(&env.fs);
|
||||
let children = tree["root"]["node"]["children"].as_array().unwrap();
|
||||
assert_eq!(children[0]["weight"], 3.0);
|
||||
assert_eq!(children[1]["weight"], 1.0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mutate_set_session_attaches_and_clears() {
|
||||
let env = mut_env(pid(12)).await;
|
||||
env.mutate
|
||||
.execute(MutateLayoutInput {
|
||||
project_id: env.project_id,
|
||||
layout_id: None,
|
||||
operation: LayoutOperation::SetSession {
|
||||
target: nid(1),
|
||||
session: Some(sid(77)),
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("attach");
|
||||
assert_eq!(
|
||||
active_tree_json(&env.fs)["root"]["node"]["session"],
|
||||
sid(77).to_string()
|
||||
);
|
||||
|
||||
let out = env
|
||||
.mutate
|
||||
.execute(MutateLayoutInput {
|
||||
project_id: env.project_id,
|
||||
layout_id: None,
|
||||
operation: LayoutOperation::SetSession {
|
||||
target: nid(1),
|
||||
session: None,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("detach");
|
||||
match &out.layout.root {
|
||||
LayoutNode::Leaf(l) => assert!(l.session.is_none()),
|
||||
_ => panic!("expected leaf root"),
|
||||
}
|
||||
assert!(active_tree_json(&env.fs)["root"]["node"]
|
||||
.get("session")
|
||||
.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mutate_invalid_op_errors_and_does_not_persist() {
|
||||
let env = mut_env(pid(14)).await;
|
||||
// Force the layouts.json to exist first (a clean load) so we have a baseline.
|
||||
let before = doc_json(&env.fs);
|
||||
|
||||
let err = env
|
||||
.mutate
|
||||
.execute(MutateLayoutInput {
|
||||
project_id: env.project_id,
|
||||
layout_id: None,
|
||||
operation: LayoutOperation::SetSession {
|
||||
target: nid(404),
|
||||
session: Some(sid(1)),
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect_err("set_session on unknown node fails");
|
||||
assert_eq!(err.code(), "NOT_FOUND", "got {err:?}");
|
||||
|
||||
assert_eq!(before, doc_json(&env.fs), "failed op must not overwrite");
|
||||
assert!(env.bus.events().is_empty(), "no event on failed mutation");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn load_then_set_session_on_returned_id_succeeds() {
|
||||
let store = FakeStore::default();
|
||||
let fs = FakeFs::default();
|
||||
let bus = SpyBus::default();
|
||||
let id = register_project(&store, pid(22)).await;
|
||||
|
||||
let load = LoadLayout::new(Arc::new(store.clone()), Arc::new(fs.clone()));
|
||||
let mutate = MutateLayout::new(
|
||||
Arc::new(store.clone()),
|
||||
Arc::new(fs.clone()),
|
||||
Arc::new(bus.clone()),
|
||||
);
|
||||
|
||||
let loaded = load
|
||||
.execute(LoadLayoutInput {
|
||||
project_id: id,
|
||||
layout_id: None,
|
||||
})
|
||||
.await
|
||||
.expect("load");
|
||||
let leaf = root_leaf_id(&loaded.layout);
|
||||
|
||||
mutate
|
||||
.execute(MutateLayoutInput {
|
||||
project_id: id,
|
||||
layout_id: None,
|
||||
operation: LayoutOperation::SetSession {
|
||||
target: leaf,
|
||||
session: Some(sid(7)),
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("set_session on the just-loaded leaf id must succeed");
|
||||
|
||||
match &read_active_tree(&fs).root {
|
||||
LayoutNode::Leaf(l) => assert_eq!(l.session, Some(sid(7))),
|
||||
_ => panic!("expected persisted leaf root"),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SetCellAgent (#3 — per-cell agent)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn aid(n: u128) -> AgentId {
|
||||
AgentId::from_uuid(Uuid::from_u128(n))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mutate_set_cell_agent_persists_agent_on_leaf() {
|
||||
let env = mut_env(pid(50)).await;
|
||||
// Attach an agent to the single root leaf (nid(1)).
|
||||
env.mutate
|
||||
.execute(MutateLayoutInput {
|
||||
project_id: env.project_id,
|
||||
layout_id: None,
|
||||
operation: LayoutOperation::SetCellAgent {
|
||||
target: nid(1),
|
||||
agent: Some(aid(0xAA)),
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("set_cell_agent attaches");
|
||||
|
||||
// Verify persisted JSON has the agent field.
|
||||
let tree_json = active_tree_json(&env.fs);
|
||||
assert_eq!(
|
||||
tree_json["root"]["node"]["agent"],
|
||||
aid(0xAA).to_string(),
|
||||
"agent must be persisted on the leaf"
|
||||
);
|
||||
|
||||
// Now clear it.
|
||||
let out = env
|
||||
.mutate
|
||||
.execute(MutateLayoutInput {
|
||||
project_id: env.project_id,
|
||||
layout_id: None,
|
||||
operation: LayoutOperation::SetCellAgent {
|
||||
target: nid(1),
|
||||
agent: None,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("set_cell_agent clears");
|
||||
|
||||
match &out.layout.root {
|
||||
LayoutNode::Leaf(l) => assert_eq!(l.agent, None, "agent must be cleared"),
|
||||
_ => panic!("expected leaf root"),
|
||||
}
|
||||
assert!(
|
||||
active_tree_json(&env.fs)["root"]["node"]
|
||||
.get("agent")
|
||||
.is_none(),
|
||||
"cleared agent must not be serialised"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mutate_set_cell_agent_missing_leaf_is_not_found() {
|
||||
let env = mut_env(pid(51)).await;
|
||||
let err = env
|
||||
.mutate
|
||||
.execute(MutateLayoutInput {
|
||||
project_id: env.project_id,
|
||||
layout_id: None,
|
||||
operation: LayoutOperation::SetCellAgent {
|
||||
target: nid(404),
|
||||
agent: Some(aid(1)),
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect_err("unknown node rejected");
|
||||
assert_eq!(err.code(), "NOT_FOUND", "got {err:?}");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Named-layout management (#4)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Builds a project + fs + bus with a seeded single "Default" layout (id 1).
|
||||
async fn mgmt_env(project_id: ProjectId) -> (FakeStore, FakeFs, SpyBus) {
|
||||
let store = FakeStore::default();
|
||||
let fs = FakeFs::default();
|
||||
let bus = SpyBus::default();
|
||||
register_project(&store, project_id).await;
|
||||
seed_layouts(&fs, lid(1), &single_leaf(nid(1)));
|
||||
(store, fs, bus)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_layout_appends_and_activates_it() {
|
||||
let (store, fs, bus) = mgmt_env(pid(30)).await;
|
||||
let create = CreateLayout::new(
|
||||
Arc::new(store.clone()),
|
||||
Arc::new(fs.clone()),
|
||||
Arc::new(SeqIds::new(0xABC)),
|
||||
Arc::new(bus.clone()),
|
||||
);
|
||||
let out = create
|
||||
.execute(CreateLayoutInput {
|
||||
project_id: pid(30),
|
||||
name: "Backend".to_owned(),
|
||||
kind: LayoutKind::Terminal,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let list = ListLayouts::new(Arc::new(store), Arc::new(fs))
|
||||
.execute(ListLayoutsInput { project_id: pid(30) })
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(list.layouts.len(), 2, "Default + Backend");
|
||||
assert_eq!(list.active_id, out.layout_id, "new layout is active");
|
||||
assert!(list.layouts.iter().any(|l| l.name == "Backend"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_layout_rejects_empty_name() {
|
||||
let (store, fs, bus) = mgmt_env(pid(31)).await;
|
||||
let err = CreateLayout::new(
|
||||
Arc::new(store),
|
||||
Arc::new(fs),
|
||||
Arc::new(SeqIds::new(1)),
|
||||
Arc::new(bus),
|
||||
)
|
||||
.execute(CreateLayoutInput {
|
||||
project_id: pid(31),
|
||||
name: " ".to_owned(),
|
||||
kind: LayoutKind::Terminal,
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "INVALID", "got {err:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rename_layout_changes_the_name() {
|
||||
let (store, fs, bus) = mgmt_env(pid(32)).await;
|
||||
RenameLayout::new(
|
||||
Arc::new(store.clone()),
|
||||
Arc::new(fs.clone()),
|
||||
Arc::new(bus),
|
||||
)
|
||||
.execute(RenameLayoutInput {
|
||||
project_id: pid(32),
|
||||
layout_id: lid(1),
|
||||
name: "Main".to_owned(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let list = ListLayouts::new(Arc::new(store), Arc::new(fs))
|
||||
.execute(ListLayoutsInput { project_id: pid(32) })
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(list.layouts[0].name, "Main");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_layout_rejects_the_last_one() {
|
||||
let (store, fs, bus) = mgmt_env(pid(33)).await;
|
||||
let err = DeleteLayout::new(Arc::new(store), Arc::new(fs), Arc::new(bus))
|
||||
.execute(DeleteLayoutInput {
|
||||
project_id: pid(33),
|
||||
layout_id: lid(1),
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "INVALID", "cannot delete the last layout");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_active_layout_reassigns_active() {
|
||||
let (store, fs, bus) = mgmt_env(pid(34)).await;
|
||||
// Add a second layout (becomes active), then delete it → active falls back.
|
||||
let created = CreateLayout::new(
|
||||
Arc::new(store.clone()),
|
||||
Arc::new(fs.clone()),
|
||||
Arc::new(SeqIds::new(0xD)),
|
||||
Arc::new(bus.clone()),
|
||||
)
|
||||
.execute(CreateLayoutInput {
|
||||
project_id: pid(34),
|
||||
name: "Second".to_owned(),
|
||||
kind: LayoutKind::Terminal,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let out = DeleteLayout::new(
|
||||
Arc::new(store.clone()),
|
||||
Arc::new(fs.clone()),
|
||||
Arc::new(bus),
|
||||
)
|
||||
.execute(DeleteLayoutInput {
|
||||
project_id: pid(34),
|
||||
layout_id: created.layout_id,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(out.active_id, lid(1), "active fell back to the Default layout");
|
||||
|
||||
let list = ListLayouts::new(Arc::new(store), Arc::new(fs))
|
||||
.execute(ListLayoutsInput { project_id: pid(34) })
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(list.layouts.len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn set_active_layout_switches_and_load_follows() {
|
||||
let (store, fs, bus) = mgmt_env(pid(35)).await;
|
||||
let created = CreateLayout::new(
|
||||
Arc::new(store.clone()),
|
||||
Arc::new(fs.clone()),
|
||||
Arc::new(SeqIds::new(0xE)),
|
||||
Arc::new(bus.clone()),
|
||||
)
|
||||
.execute(CreateLayoutInput {
|
||||
project_id: pid(35),
|
||||
name: "Second".to_owned(),
|
||||
kind: LayoutKind::Terminal,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Switch back to the Default layout.
|
||||
SetActiveLayout::new(
|
||||
Arc::new(store.clone()),
|
||||
Arc::new(fs.clone()),
|
||||
Arc::new(bus),
|
||||
)
|
||||
.execute(SetActiveLayoutInput {
|
||||
project_id: pid(35),
|
||||
layout_id: lid(1),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let loaded = LoadLayout::new(Arc::new(store), Arc::new(fs))
|
||||
.execute(LoadLayoutInput {
|
||||
project_id: pid(35),
|
||||
layout_id: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(loaded.layout_id, lid(1));
|
||||
assert_ne!(loaded.layout_id, created.layout_id);
|
||||
}
|
||||
320
crates/application/tests/profile_usecases.rs
Normal file
320
crates/application/tests/profile_usecases.rs
Normal file
@ -0,0 +1,320 @@
|
||||
//! L5 tests for the profile/first-run use cases and the reference catalogue.
|
||||
//!
|
||||
//! Ports are faked in-memory so the use cases run without any I/O:
|
||||
//! - [`FakeProfileStore`] — an in-memory [`ProfileStore`] tracking a `configured`
|
||||
//! flag (mirrors `profiles.json` existence),
|
||||
//! - [`StubRuntime`] — an [`AgentRuntime`] whose `detect` is driven by a map from
|
||||
//! command → result (including an error case to prove graceful degradation).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use domain::ids::ProfileId;
|
||||
use domain::ports::{
|
||||
AgentRuntime, PreparedContext, ProfileStore, RuntimeError, SpawnSpec, StoreError,
|
||||
};
|
||||
use domain::profile::{AgentProfile, ContextInjection};
|
||||
use domain::project::ProjectPath;
|
||||
|
||||
use application::{
|
||||
reference_profile_id, reference_profiles, ConfigureProfiles, ConfigureProfilesInput,
|
||||
DeleteProfile, DeleteProfileInput, DetectProfiles, DetectProfilesInput, FirstRunState,
|
||||
ListProfiles, ReferenceProfiles, SaveProfile, SaveProfileInput,
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fakes
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Default)]
|
||||
struct FakeStoreInner {
|
||||
profiles: Vec<AgentProfile>,
|
||||
configured: bool,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
struct FakeProfileStore(Arc<Mutex<FakeStoreInner>>);
|
||||
|
||||
#[async_trait]
|
||||
impl ProfileStore for FakeProfileStore {
|
||||
async fn list(&self) -> Result<Vec<AgentProfile>, StoreError> {
|
||||
Ok(self.0.lock().unwrap().profiles.clone())
|
||||
}
|
||||
|
||||
async fn save(&self, profile: &AgentProfile) -> Result<(), StoreError> {
|
||||
let mut inner = self.0.lock().unwrap();
|
||||
inner.configured = true;
|
||||
if let Some(slot) = inner.profiles.iter_mut().find(|p| p.id == profile.id) {
|
||||
*slot = profile.clone();
|
||||
} else {
|
||||
inner.profiles.push(profile.clone());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn delete(&self, id: ProfileId) -> Result<(), StoreError> {
|
||||
let mut inner = self.0.lock().unwrap();
|
||||
let before = inner.profiles.len();
|
||||
inner.profiles.retain(|p| p.id != id);
|
||||
if inner.profiles.len() == before {
|
||||
return Err(StoreError::NotFound);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn is_configured(&self) -> Result<bool, StoreError> {
|
||||
Ok(self.0.lock().unwrap().configured)
|
||||
}
|
||||
|
||||
async fn mark_configured(&self) -> Result<(), StoreError> {
|
||||
self.0.lock().unwrap().configured = true;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Detection outcomes keyed by command. Missing keys ⇒ `false`.
|
||||
#[derive(Clone)]
|
||||
enum DetectResult {
|
||||
Available,
|
||||
Missing,
|
||||
Error,
|
||||
}
|
||||
|
||||
struct StubRuntime {
|
||||
by_command: HashMap<String, DetectResult>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl AgentRuntime for StubRuntime {
|
||||
fn detect(&self, profile: &AgentProfile) -> Result<bool, RuntimeError> {
|
||||
match self.by_command.get(&profile.command) {
|
||||
Some(DetectResult::Available) => Ok(true),
|
||||
Some(DetectResult::Missing) | None => Ok(false),
|
||||
Some(DetectResult::Error) => {
|
||||
Err(RuntimeError::Detection("boom".to_owned()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_invocation(
|
||||
&self,
|
||||
_profile: &AgentProfile,
|
||||
_ctx: &PreparedContext,
|
||||
_cwd: &ProjectPath,
|
||||
) -> Result<SpawnSpec, RuntimeError> {
|
||||
unreachable!("not used in these tests")
|
||||
}
|
||||
}
|
||||
|
||||
fn profile(id: u128, name: &str, command: &str) -> AgentProfile {
|
||||
AgentProfile::new(
|
||||
ProfileId::from_uuid(uuid::Uuid::from_u128(id)),
|
||||
name,
|
||||
command,
|
||||
Vec::new(),
|
||||
ContextInjection::stdin(),
|
||||
Some(format!("{command} --version")),
|
||||
"{projectRoot}",
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// DetectProfiles
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn detect_maps_candidates_to_availability_in_order() {
|
||||
let mut map = HashMap::new();
|
||||
map.insert("claude".to_owned(), DetectResult::Available);
|
||||
map.insert("codex".to_owned(), DetectResult::Missing);
|
||||
let runtime: Arc<dyn AgentRuntime> = Arc::new(StubRuntime { by_command: map });
|
||||
|
||||
let detect = DetectProfiles::new(runtime);
|
||||
let out = detect
|
||||
.execute(DetectProfilesInput {
|
||||
candidates: vec![profile(1, "Claude", "claude"), profile(2, "Codex", "codex")],
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(out.results.len(), 2);
|
||||
assert_eq!(out.results[0].profile.command, "claude");
|
||||
assert!(out.results[0].available);
|
||||
assert_eq!(out.results[1].profile.command, "codex");
|
||||
assert!(!out.results[1].available);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn detect_error_degrades_to_unavailable_not_hard_failure() {
|
||||
let mut map = HashMap::new();
|
||||
map.insert("aider".to_owned(), DetectResult::Error);
|
||||
let runtime: Arc<dyn AgentRuntime> = Arc::new(StubRuntime { by_command: map });
|
||||
|
||||
let detect = DetectProfiles::new(runtime);
|
||||
let out = detect
|
||||
.execute(DetectProfilesInput {
|
||||
candidates: vec![profile(1, "Aider", "aider")],
|
||||
})
|
||||
.await
|
||||
.expect("detection error must not fail the use case");
|
||||
|
||||
assert!(!out.results[0].available, "errored detection ⇒ available:false");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ConfigureProfiles
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn configure_persists_chosen_profiles_and_closes_first_run() {
|
||||
let store = FakeProfileStore::default();
|
||||
let configure = ConfigureProfiles::new(Arc::new(store.clone()));
|
||||
|
||||
let out = configure
|
||||
.execute(ConfigureProfilesInput {
|
||||
profiles: vec![profile(1, "Claude", "claude"), profile(2, "Codex", "codex")],
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(out.profiles.len(), 2);
|
||||
assert!(store.is_configured().await.unwrap());
|
||||
assert_eq!(store.list().await.unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn configure_empty_list_still_marks_configured() {
|
||||
let store = FakeProfileStore::default();
|
||||
let configure = ConfigureProfiles::new(Arc::new(store.clone()));
|
||||
|
||||
configure
|
||||
.execute(ConfigureProfilesInput { profiles: vec![] })
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(
|
||||
store.is_configured().await.unwrap(),
|
||||
"empty configure closes the first run"
|
||||
);
|
||||
assert!(store.list().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// FirstRunState
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn first_run_true_when_not_configured_with_reference_catalogue() {
|
||||
let store = FakeProfileStore::default();
|
||||
let uc = FirstRunState::new(Arc::new(store));
|
||||
|
||||
let out = uc.execute().await.unwrap();
|
||||
assert!(out.is_first_run);
|
||||
assert_eq!(out.reference_profiles.len(), 4, "catalogue seeded");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn first_run_false_after_configuration() {
|
||||
let store = FakeProfileStore::default();
|
||||
store.mark_configured().await.unwrap();
|
||||
let uc = FirstRunState::new(Arc::new(store));
|
||||
|
||||
let out = uc.execute().await.unwrap();
|
||||
assert!(!out.is_first_run);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ListProfiles / SaveProfile / DeleteProfile
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn save_then_list_then_delete() {
|
||||
let store = FakeProfileStore::default();
|
||||
let save = SaveProfile::new(Arc::new(store.clone()));
|
||||
let list = ListProfiles::new(Arc::new(store.clone()));
|
||||
let delete = DeleteProfile::new(Arc::new(store.clone()));
|
||||
|
||||
let p = profile(1, "Claude", "claude");
|
||||
let saved = save
|
||||
.execute(SaveProfileInput { profile: p.clone() })
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(saved.profile, p);
|
||||
|
||||
assert_eq!(list.execute().await.unwrap().profiles, vec![p.clone()]);
|
||||
|
||||
delete.execute(DeleteProfileInput { id: p.id }).await.unwrap();
|
||||
assert!(list.execute().await.unwrap().profiles.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_unknown_is_not_found_error() {
|
||||
let store = FakeProfileStore::default();
|
||||
let delete = DeleteProfile::new(Arc::new(store));
|
||||
let err = delete
|
||||
.execute(DeleteProfileInput {
|
||||
id: ProfileId::from_uuid(uuid::Uuid::from_u128(123)),
|
||||
})
|
||||
.await
|
||||
.expect_err("deleting unknown id errors");
|
||||
assert_eq!(err.code(), "NOT_FOUND", "got {err:?}");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ReferenceProfiles / catalogue
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn reference_profiles_use_case_returns_four() {
|
||||
let out = ReferenceProfiles::new().execute().await.unwrap();
|
||||
assert_eq!(out.profiles.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalogue_has_expected_commands_and_injection() {
|
||||
let profiles = reference_profiles();
|
||||
let by_command: HashMap<&str, &AgentProfile> =
|
||||
profiles.iter().map(|p| (p.command.as_str(), p)).collect();
|
||||
|
||||
let claude = by_command["claude"];
|
||||
assert_eq!(
|
||||
claude.context_injection,
|
||||
ContextInjection::ConventionFile {
|
||||
target: "CLAUDE.md".to_owned()
|
||||
}
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
by_command["codex"].context_injection,
|
||||
ContextInjection::ConventionFile {
|
||||
target: "AGENTS.md".to_owned()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
by_command["gemini"].context_injection,
|
||||
ContextInjection::ConventionFile {
|
||||
target: "GEMINI.md".to_owned()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
by_command["aider"].context_injection,
|
||||
ContextInjection::Flag {
|
||||
flag: "--message-file {path}".to_owned()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalogue_ids_are_stable_across_calls() {
|
||||
let first = reference_profiles();
|
||||
let second = reference_profiles();
|
||||
let ids_a: Vec<_> = first.iter().map(|p| p.id).collect();
|
||||
let ids_b: Vec<_> = second.iter().map(|p| p.id).collect();
|
||||
assert_eq!(ids_a, ids_b, "reference ids are deterministic");
|
||||
|
||||
// And match the slug-derived id helper.
|
||||
assert_eq!(first[0].id, reference_profile_id("claude"));
|
||||
}
|
||||
565
crates/application/tests/project_usecases.rs
Normal file
565
crates/application/tests/project_usecases.rs
Normal file
@ -0,0 +1,565 @@
|
||||
//! L2 tests for the project life-cycle use cases (`CreateProject`,
|
||||
//! `OpenProject`, `ListProjects`, `CloseProject`/`CloseTab`).
|
||||
//!
|
||||
//! Every port is faked in-memory so the use cases are exercised without any I/O:
|
||||
//! - [`FakeFs`] — a `Mutex<HashMap<String, Vec<u8>>>` filesystem that records
|
||||
//! directories and file contents,
|
||||
//! - [`FakeStore`] — an in-memory `ProjectStore` (registry + workspace),
|
||||
//! - [`SpyBus`] — records published [`DomainEvent`]s,
|
||||
//! - [`SeqIds`] / [`FixedClock`] — deterministic id/time.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use domain::events::DomainEvent;
|
||||
use domain::layout::Workspace;
|
||||
use domain::ports::{
|
||||
Clock, DirEntry, EventBus, EventStream, FileSystem, FsError, IdGenerator, ProjectStore,
|
||||
RemotePath, StoreError,
|
||||
};
|
||||
use domain::{Project, ProjectId, ProjectPath, RemoteRef};
|
||||
|
||||
use application::{
|
||||
CloseProject, CloseProjectInput, CloseTab, CloseTabInput, CreateProject, CreateProjectInput,
|
||||
ListProjects, OpenProject, OpenProjectInput,
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fakes
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Default)]
|
||||
struct FakeFsInner {
|
||||
files: HashMap<String, Vec<u8>>,
|
||||
dirs: HashSet<String>,
|
||||
}
|
||||
|
||||
/// An in-memory [`FileSystem`] recording writes and created directories.
|
||||
#[derive(Default, Clone)]
|
||||
struct FakeFs(Arc<Mutex<FakeFsInner>>);
|
||||
|
||||
impl FakeFs {
|
||||
fn read_file(&self, path: &str) -> Option<Vec<u8>> {
|
||||
self.0.lock().unwrap().files.get(path).cloned()
|
||||
}
|
||||
fn has_dir(&self, path: &str) -> bool {
|
||||
self.0.lock().unwrap().dirs.contains(path)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl FileSystem for FakeFs {
|
||||
async fn read(&self, path: &RemotePath) -> Result<Vec<u8>, FsError> {
|
||||
self.0
|
||||
.lock()
|
||||
.unwrap()
|
||||
.files
|
||||
.get(path.as_str())
|
||||
.cloned()
|
||||
.ok_or_else(|| FsError::NotFound(path.as_str().to_owned()))
|
||||
}
|
||||
|
||||
async fn write(&self, path: &RemotePath, data: &[u8]) -> Result<(), FsError> {
|
||||
self.0
|
||||
.lock()
|
||||
.unwrap()
|
||||
.files
|
||||
.insert(path.as_str().to_owned(), data.to_vec());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn exists(&self, path: &RemotePath) -> Result<bool, FsError> {
|
||||
let inner = self.0.lock().unwrap();
|
||||
Ok(inner.files.contains_key(path.as_str()) || inner.dirs.contains(path.as_str()))
|
||||
}
|
||||
|
||||
async fn create_dir_all(&self, path: &RemotePath) -> Result<(), FsError> {
|
||||
self.0
|
||||
.lock()
|
||||
.unwrap()
|
||||
.dirs
|
||||
.insert(path.as_str().to_owned());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn list(&self, _path: &RemotePath) -> Result<Vec<DirEntry>, FsError> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
async fn symlink(&self, _src: &RemotePath, _dst: &RemotePath) -> Result<(), FsError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct FakeStoreInner {
|
||||
projects: Vec<Project>,
|
||||
workspace: Option<Workspace>,
|
||||
}
|
||||
|
||||
/// An in-memory [`ProjectStore`].
|
||||
#[derive(Default, Clone)]
|
||||
struct FakeStore(Arc<Mutex<FakeStoreInner>>);
|
||||
|
||||
impl FakeStore {
|
||||
fn saved_workspace(&self) -> Option<Workspace> {
|
||||
self.0.lock().unwrap().workspace.clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ProjectStore for FakeStore {
|
||||
async fn list_projects(&self) -> Result<Vec<Project>, StoreError> {
|
||||
Ok(self.0.lock().unwrap().projects.clone())
|
||||
}
|
||||
|
||||
async fn load_project(&self, id: ProjectId) -> Result<Project, StoreError> {
|
||||
self.0
|
||||
.lock()
|
||||
.unwrap()
|
||||
.projects
|
||||
.iter()
|
||||
.find(|p| p.id == id)
|
||||
.cloned()
|
||||
.ok_or(StoreError::NotFound)
|
||||
}
|
||||
|
||||
async fn save_project(&self, project: &Project) -> Result<(), StoreError> {
|
||||
let mut inner = self.0.lock().unwrap();
|
||||
if let Some(slot) = inner.projects.iter_mut().find(|p| p.id == project.id) {
|
||||
*slot = project.clone();
|
||||
} else {
|
||||
inner.projects.push(project.clone());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn save_workspace(&self, workspace: &Workspace) -> Result<(), StoreError> {
|
||||
self.0.lock().unwrap().workspace = Some(workspace.clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn load_workspace(&self) -> Result<Workspace, StoreError> {
|
||||
Ok(self.0.lock().unwrap().workspace.clone().unwrap_or_default())
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`ProjectStore`] whose registry read always fails — used to assert the
|
||||
/// `Store` error code propagates.
|
||||
#[derive(Default, Clone)]
|
||||
struct BrokenStore;
|
||||
|
||||
#[async_trait]
|
||||
impl ProjectStore for BrokenStore {
|
||||
async fn list_projects(&self) -> Result<Vec<Project>, StoreError> {
|
||||
Err(StoreError::Io("boom".into()))
|
||||
}
|
||||
async fn load_project(&self, _id: ProjectId) -> Result<Project, StoreError> {
|
||||
Err(StoreError::Io("boom".into()))
|
||||
}
|
||||
async fn save_project(&self, _project: &Project) -> Result<(), StoreError> {
|
||||
Err(StoreError::Io("boom".into()))
|
||||
}
|
||||
async fn save_workspace(&self, _w: &Workspace) -> Result<(), StoreError> {
|
||||
Err(StoreError::Io("boom".into()))
|
||||
}
|
||||
async fn load_workspace(&self) -> Result<Workspace, StoreError> {
|
||||
Err(StoreError::Io("boom".into()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Records published events.
|
||||
#[derive(Default, Clone)]
|
||||
struct SpyBus(Arc<Mutex<Vec<DomainEvent>>>);
|
||||
|
||||
impl SpyBus {
|
||||
fn events(&self) -> Vec<DomainEvent> {
|
||||
self.0.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl EventBus for SpyBus {
|
||||
fn publish(&self, event: DomainEvent) {
|
||||
self.0.lock().unwrap().push(event);
|
||||
}
|
||||
fn subscribe(&self) -> EventStream {
|
||||
Box::new(std::iter::empty())
|
||||
}
|
||||
}
|
||||
|
||||
/// Deterministic ids: nil-based UUIDs derived from a counter.
|
||||
struct SeqIds(Mutex<u128>);
|
||||
impl SeqIds {
|
||||
fn new() -> Self {
|
||||
Self(Mutex::new(1))
|
||||
}
|
||||
}
|
||||
impl IdGenerator for SeqIds {
|
||||
fn new_uuid(&self) -> uuid::Uuid {
|
||||
let mut n = self.0.lock().unwrap();
|
||||
let v = *n;
|
||||
*n += 1;
|
||||
uuid::Uuid::from_u128(v)
|
||||
}
|
||||
}
|
||||
|
||||
struct FixedClock(i64);
|
||||
impl Clock for FixedClock {
|
||||
fn now_millis(&self) -> i64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Wiring helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
struct Env {
|
||||
store: FakeStore,
|
||||
fs: FakeFs,
|
||||
bus: SpyBus,
|
||||
create: CreateProject,
|
||||
open: OpenProject,
|
||||
}
|
||||
|
||||
fn env() -> Env {
|
||||
let store = FakeStore::default();
|
||||
let fs = FakeFs::default();
|
||||
let bus = SpyBus::default();
|
||||
let ids: Arc<dyn IdGenerator> = Arc::new(SeqIds::new());
|
||||
let clock: Arc<dyn Clock> = Arc::new(FixedClock(1_700_000_000_000));
|
||||
|
||||
let create = CreateProject::new(
|
||||
Arc::new(store.clone()),
|
||||
Arc::new(fs.clone()),
|
||||
ids,
|
||||
clock,
|
||||
Arc::new(bus.clone()),
|
||||
);
|
||||
let open = OpenProject::new(Arc::new(store.clone()), Arc::new(fs.clone()));
|
||||
|
||||
Env {
|
||||
store,
|
||||
fs,
|
||||
bus,
|
||||
create,
|
||||
open,
|
||||
}
|
||||
}
|
||||
|
||||
fn input(name: &str, root: &str) -> CreateProjectInput {
|
||||
CreateProjectInput {
|
||||
name: name.to_owned(),
|
||||
root: root.to_owned(),
|
||||
remote: None,
|
||||
default_profile_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CreateProject
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_inits_ideai_dir_and_writes_camelcase_project_json() {
|
||||
let env = env();
|
||||
let out = env
|
||||
.create
|
||||
.execute(input("Demo", "/home/me/proj"))
|
||||
.await
|
||||
.expect("creation succeeds");
|
||||
|
||||
// .ideai/ created.
|
||||
assert!(env.fs.has_dir("/home/me/proj/.ideai"), "dir created");
|
||||
|
||||
// project.json written with camelCase fields and no `root`.
|
||||
let bytes = env
|
||||
.fs
|
||||
.read_file("/home/me/proj/.ideai/project.json")
|
||||
.expect("project.json written");
|
||||
let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
|
||||
|
||||
assert_eq!(json["version"], 1);
|
||||
assert_eq!(json["name"], "Demo");
|
||||
assert_eq!(json["id"], out.project.id.to_string());
|
||||
assert_eq!(json["createdAt"], 1_700_000_000_000i64);
|
||||
assert_eq!(json["remote"]["kind"], "local");
|
||||
assert!(json.get("root").is_none(), "root must NOT be stored");
|
||||
// default_profile_id omitted when None (skip_serializing_if).
|
||||
assert!(json.get("defaultProfileId").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_registers_project_in_store() {
|
||||
let env = env();
|
||||
let out = env.create.execute(input("Demo", "/p")).await.unwrap();
|
||||
|
||||
let stored = env.store.list_projects().await.unwrap();
|
||||
assert_eq!(stored.len(), 1);
|
||||
assert_eq!(stored[0].id, out.project.id);
|
||||
assert_eq!(stored[0].name, "Demo");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_publishes_project_created_event() {
|
||||
let env = env();
|
||||
let out = env.create.execute(input("Demo", "/p")).await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
env.bus.events(),
|
||||
vec![DomainEvent::ProjectCreated {
|
||||
project_id: out.project.id
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_rejects_duplicate_remote_root() {
|
||||
let env = env();
|
||||
env.create.execute(input("A", "/same")).await.unwrap();
|
||||
|
||||
let err = env
|
||||
.create
|
||||
.execute(input("B", "/same"))
|
||||
.await
|
||||
.expect_err("duplicate (remote, root) rejected");
|
||||
|
||||
assert_eq!(err.code(), "INVALID", "got {err:?}");
|
||||
// Only the first project remains registered.
|
||||
assert_eq!(env.store.list_projects().await.unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_allows_same_root_on_different_remote() {
|
||||
let env = env();
|
||||
env.create.execute(input("Local", "/shared")).await.unwrap();
|
||||
|
||||
let remote_input = CreateProjectInput {
|
||||
remote: Some(RemoteRef::Wsl {
|
||||
distro: "Ubuntu".to_owned(),
|
||||
}),
|
||||
..input("Wsl", "/shared")
|
||||
};
|
||||
env.create
|
||||
.execute(remote_input)
|
||||
.await
|
||||
.expect("same root, different remote is allowed");
|
||||
|
||||
assert_eq!(env.store.list_projects().await.unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_rejects_non_absolute_root() {
|
||||
let env = env();
|
||||
let err = env
|
||||
.create
|
||||
.execute(input("X", "relative/path"))
|
||||
.await
|
||||
.expect_err("non-absolute root rejected");
|
||||
assert_eq!(err.code(), "INVALID", "got {err:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_rejects_empty_name() {
|
||||
let env = env();
|
||||
let err = env
|
||||
.create
|
||||
.execute(input("", "/abs"))
|
||||
.await
|
||||
.expect_err("empty name rejected");
|
||||
assert_eq!(err.code(), "INVALID", "got {err:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_propagates_store_error_code() {
|
||||
let ids: Arc<dyn IdGenerator> = Arc::new(SeqIds::new());
|
||||
let clock: Arc<dyn Clock> = Arc::new(FixedClock(0));
|
||||
let create = CreateProject::new(
|
||||
Arc::new(BrokenStore),
|
||||
Arc::new(FakeFs::default()),
|
||||
ids,
|
||||
clock,
|
||||
Arc::new(SpyBus::default()),
|
||||
);
|
||||
let err = create
|
||||
.execute(input("X", "/abs"))
|
||||
.await
|
||||
.expect_err("store failure surfaces");
|
||||
assert_eq!(err.code(), "STORE", "got {err:?}");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// OpenProject — tolerant reads
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn open_loads_project_and_meta() {
|
||||
let env = env();
|
||||
let created = env.create.execute(input("Demo", "/o/proj")).await.unwrap();
|
||||
|
||||
let out = env
|
||||
.open
|
||||
.execute(OpenProjectInput {
|
||||
project_id: created.project.id,
|
||||
})
|
||||
.await
|
||||
.expect("open succeeds");
|
||||
|
||||
assert_eq!(out.project.id, created.project.id);
|
||||
assert_eq!(out.project.root, created.project.root);
|
||||
let meta = out.meta.expect("meta present (project.json was written)");
|
||||
assert_eq!(meta.id, created.project.id);
|
||||
assert_eq!(meta.name, "Demo");
|
||||
// No agents.json was written → manifest tolerantly None.
|
||||
assert!(out.manifest.is_none(), "agents.json absent → None");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn open_unknown_project_is_not_found() {
|
||||
let env = env();
|
||||
let err = env
|
||||
.open
|
||||
.execute(OpenProjectInput {
|
||||
project_id: ProjectId::from_uuid(uuid::Uuid::from_u128(999)),
|
||||
})
|
||||
.await
|
||||
.expect_err("unknown id");
|
||||
assert_eq!(err.code(), "NOT_FOUND", "got {err:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn open_tolerates_missing_meta_file() {
|
||||
// Register a project in the store WITHOUT writing any .ideai/ files.
|
||||
let store = FakeStore::default();
|
||||
let fs = FakeFs::default();
|
||||
let id = ProjectId::from_uuid(uuid::Uuid::from_u128(7));
|
||||
let project = Project::new(
|
||||
id,
|
||||
"Orphan",
|
||||
ProjectPath::new("/no/ideai").unwrap(),
|
||||
RemoteRef::Local,
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
store.save_project(&project).await.unwrap();
|
||||
|
||||
let open = OpenProject::new(Arc::new(store), Arc::new(fs));
|
||||
let out = open
|
||||
.execute(OpenProjectInput { project_id: id })
|
||||
.await
|
||||
.expect("open does not fail on missing meta");
|
||||
assert!(out.meta.is_none(), "missing project.json → None");
|
||||
assert!(out.manifest.is_none(), "missing agents.json → None");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn open_tolerates_corrupt_json() {
|
||||
let store = FakeStore::default();
|
||||
let fs = FakeFs::default();
|
||||
let id = ProjectId::from_uuid(uuid::Uuid::from_u128(8));
|
||||
let project = Project::new(
|
||||
id,
|
||||
"Corrupt",
|
||||
ProjectPath::new("/c/proj").unwrap(),
|
||||
RemoteRef::Local,
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
store.save_project(&project).await.unwrap();
|
||||
// Write garbage at both .ideai/ paths.
|
||||
fs.write(
|
||||
&RemotePath::new("/c/proj/.ideai/project.json"),
|
||||
b"{ not json ]",
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
fs.write(
|
||||
&RemotePath::new("/c/proj/.ideai/agents.json"),
|
||||
b"<<<broken>>>",
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let open = OpenProject::new(Arc::new(store), Arc::new(fs));
|
||||
let out = open
|
||||
.execute(OpenProjectInput { project_id: id })
|
||||
.await
|
||||
.expect("corrupt JSON does not fail the open");
|
||||
assert!(out.meta.is_none(), "corrupt project.json → None");
|
||||
assert!(out.manifest.is_none(), "corrupt agents.json → None");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ListProjects
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_projects_returns_registered() {
|
||||
let env = env();
|
||||
env.create.execute(input("A", "/a")).await.unwrap();
|
||||
env.create.execute(input("B", "/b")).await.unwrap();
|
||||
|
||||
let list = ListProjects::new(Arc::new(env.store.clone()));
|
||||
let out = list.execute().await.unwrap();
|
||||
let names: Vec<&str> = out.projects.iter().map(|p| p.name.as_str()).collect();
|
||||
assert_eq!(out.projects.len(), 2);
|
||||
assert!(names.contains(&"A") && names.contains(&"B"));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CloseProject / CloseTab
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn close_persists_workspace() {
|
||||
let store = FakeStore::default();
|
||||
let close = CloseProject::new(Arc::new(store.clone()));
|
||||
let id = ProjectId::from_uuid(uuid::Uuid::from_u128(3));
|
||||
|
||||
let out = close
|
||||
.execute(CloseProjectInput {
|
||||
project_id: id,
|
||||
workspace: Some(Workspace::default()),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(out.project_id, id);
|
||||
assert!(store.saved_workspace().is_some(), "workspace persisted");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn close_without_workspace_skips_persistence() {
|
||||
let store = FakeStore::default();
|
||||
let close = CloseProject::new(Arc::new(store.clone()));
|
||||
let id = ProjectId::from_uuid(uuid::Uuid::from_u128(4));
|
||||
|
||||
close
|
||||
.execute(CloseProjectInput {
|
||||
project_id: id,
|
||||
workspace: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(store.saved_workspace().is_none(), "no persistence when None");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn close_tab_delegates_to_persistence() {
|
||||
let store = FakeStore::default();
|
||||
let close_tab = CloseTab::new(Arc::new(store.clone()));
|
||||
let id = ProjectId::from_uuid(uuid::Uuid::from_u128(5));
|
||||
|
||||
let out = close_tab
|
||||
.execute(CloseTabInput {
|
||||
project_id: id,
|
||||
workspace: Some(Workspace::default()),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(out.project_id, id);
|
||||
assert!(store.saved_workspace().is_some(), "tab close persists too");
|
||||
}
|
||||
158
crates/application/tests/remote_usecases.rs
Normal file
158
crates/application/tests/remote_usecases.rs
Normal file
@ -0,0 +1,158 @@
|
||||
//! L9 tests for [`ConnectRemote`] with a mock [`RemoteHost`]. The same use case
|
||||
//! must behave identically whatever the host kind (Liskov), so we drive it with a
|
||||
//! fake host parameterised by kind + root reachability.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use domain::events::DomainEvent;
|
||||
use domain::ports::{
|
||||
DirEntry, EventBus, EventStream, FileSystem, FsError, ProcessSpawner, PtyPort, RemoteError,
|
||||
RemoteHost, RemotePath,
|
||||
};
|
||||
use domain::{ProjectId, RemoteKind};
|
||||
use uuid::Uuid;
|
||||
|
||||
use application::{ConnectRemote, ConnectRemoteInput};
|
||||
|
||||
// --- Fake filesystem (only `exists` matters here) -------------------------
|
||||
|
||||
struct FakeFs {
|
||||
existing_root: Option<String>,
|
||||
}
|
||||
#[async_trait]
|
||||
impl FileSystem for FakeFs {
|
||||
async fn read(&self, p: &RemotePath) -> Result<Vec<u8>, FsError> {
|
||||
Err(FsError::NotFound(p.as_str().to_owned()))
|
||||
}
|
||||
async fn write(&self, _p: &RemotePath, _d: &[u8]) -> Result<(), FsError> {
|
||||
Ok(())
|
||||
}
|
||||
async fn exists(&self, p: &RemotePath) -> Result<bool, FsError> {
|
||||
Ok(self.existing_root.as_deref() == Some(p.as_str()))
|
||||
}
|
||||
async fn create_dir_all(&self, _p: &RemotePath) -> Result<(), FsError> {
|
||||
Ok(())
|
||||
}
|
||||
async fn list(&self, _p: &RemotePath) -> Result<Vec<DirEntry>, FsError> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
async fn symlink(&self, _s: &RemotePath, _d: &RemotePath) -> Result<(), FsError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// --- Fake remote host -----------------------------------------------------
|
||||
|
||||
struct FakeHost {
|
||||
kind: RemoteKind,
|
||||
connect_ok: bool,
|
||||
fs: Arc<dyn FileSystem>,
|
||||
}
|
||||
impl FakeHost {
|
||||
fn make(kind: RemoteKind, connect_ok: bool, existing_root: Option<&str>) -> Arc<dyn RemoteHost> {
|
||||
Arc::new(Self {
|
||||
kind,
|
||||
connect_ok,
|
||||
fs: Arc::new(FakeFs {
|
||||
existing_root: existing_root.map(ToOwned::to_owned),
|
||||
}),
|
||||
})
|
||||
}
|
||||
}
|
||||
#[async_trait]
|
||||
impl RemoteHost for FakeHost {
|
||||
fn kind(&self) -> RemoteKind {
|
||||
self.kind
|
||||
}
|
||||
async fn connect(&self) -> Result<(), RemoteError> {
|
||||
if self.connect_ok {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(RemoteError::Connection("refused".to_owned()))
|
||||
}
|
||||
}
|
||||
fn file_system(&self) -> Arc<dyn FileSystem> {
|
||||
Arc::clone(&self.fs)
|
||||
}
|
||||
fn process_spawner(&self) -> Arc<dyn ProcessSpawner> {
|
||||
unreachable!("ConnectRemote does not use the spawner")
|
||||
}
|
||||
fn pty(&self) -> Arc<dyn PtyPort> {
|
||||
unreachable!("ConnectRemote does not use the pty")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
struct SpyBus(Arc<Mutex<Vec<DomainEvent>>>);
|
||||
impl SpyBus {
|
||||
fn events(&self) -> Vec<DomainEvent> {
|
||||
self.0.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
impl EventBus for SpyBus {
|
||||
fn publish(&self, e: DomainEvent) {
|
||||
self.0.lock().unwrap().push(e);
|
||||
}
|
||||
fn subscribe(&self) -> EventStream {
|
||||
Box::new(std::iter::empty())
|
||||
}
|
||||
}
|
||||
|
||||
fn pid() -> ProjectId {
|
||||
ProjectId::from_uuid(Uuid::from_u128(1))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn connect_succeeds_and_emits_event_for_any_host_kind() {
|
||||
// Liskov: identical behaviour for Local, Ssh and Wsl hosts.
|
||||
for kind in [RemoteKind::Local, RemoteKind::Ssh, RemoteKind::Wsl] {
|
||||
let host = FakeHost::make(kind, true, Some("/srv/app"));
|
||||
let bus = SpyBus::default();
|
||||
let out = ConnectRemote::new(Arc::new(bus.clone()))
|
||||
.execute(ConnectRemoteInput {
|
||||
host,
|
||||
project_id: pid(),
|
||||
root: "/srv/app".to_owned(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(out.kind, kind);
|
||||
assert_eq!(
|
||||
bus.events(),
|
||||
vec![DomainEvent::RemoteConnected { project_id: pid() }]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn connect_propagates_connection_failure() {
|
||||
let host = FakeHost::make(RemoteKind::Ssh, false, Some("/srv/app"));
|
||||
let bus = SpyBus::default();
|
||||
let err = ConnectRemote::new(Arc::new(bus.clone()))
|
||||
.execute(ConnectRemoteInput {
|
||||
host,
|
||||
project_id: pid(),
|
||||
root: "/srv/app".to_owned(),
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "REMOTE", "got {err:?}");
|
||||
assert!(bus.events().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn connect_fails_when_root_unreachable() {
|
||||
let host = FakeHost::make(RemoteKind::Local, true, Some("/other"));
|
||||
let bus = SpyBus::default();
|
||||
let err = ConnectRemote::new(Arc::new(bus.clone()))
|
||||
.execute(ConnectRemoteInput {
|
||||
host,
|
||||
project_id: pid(),
|
||||
root: "/srv/app".to_owned(),
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "NOT_FOUND", "got {err:?}");
|
||||
assert!(bus.events().is_empty(), "no event when root is missing");
|
||||
}
|
||||
421
crates/application/tests/template_usecases.rs
Normal file
421
crates/application/tests/template_usecases.rs
Normal file
@ -0,0 +1,421 @@
|
||||
//! L7 tests for the template & synchronisation use cases, with in-memory port
|
||||
//! fakes (no real store/FS): `CreateTemplate`, `UpdateTemplate`,
|
||||
//! `CreateAgentFromTemplate`, `DetectAgentDrift`, `SyncAgentWithTemplate`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use domain::events::DomainEvent;
|
||||
use domain::ids::{AgentId, ProfileId, ProjectId, TemplateId};
|
||||
use domain::markdown::MarkdownDoc;
|
||||
use domain::ports::{
|
||||
AgentContextStore, EventBus, EventStream, IdGenerator, StoreError, TemplateStore,
|
||||
};
|
||||
use domain::template::{AgentTemplate, TemplateVersion};
|
||||
use domain::{AgentManifest, ManifestEntry, Project, ProjectPath, RemoteRef};
|
||||
use uuid::Uuid;
|
||||
|
||||
use application::{
|
||||
CreateAgentFromTemplate, CreateAgentFromTemplateInput, CreateTemplate, CreateTemplateInput,
|
||||
DetectAgentDrift, DetectAgentDriftInput, SyncAgentWithTemplate, SyncAgentWithTemplateInput,
|
||||
UpdateTemplate, UpdateTemplateInput,
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fakes
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct FakeTemplates(Arc<Mutex<Vec<AgentTemplate>>>);
|
||||
impl FakeTemplates {
|
||||
fn with(templates: Vec<AgentTemplate>) -> Self {
|
||||
Self(Arc::new(Mutex::new(templates)))
|
||||
}
|
||||
fn get_sync(&self, id: TemplateId) -> Option<AgentTemplate> {
|
||||
self.0.lock().unwrap().iter().find(|t| t.id == id).cloned()
|
||||
}
|
||||
}
|
||||
#[async_trait]
|
||||
impl TemplateStore for FakeTemplates {
|
||||
async fn list(&self) -> Result<Vec<AgentTemplate>, StoreError> {
|
||||
Ok(self.0.lock().unwrap().clone())
|
||||
}
|
||||
async fn get(&self, id: TemplateId) -> Result<AgentTemplate, StoreError> {
|
||||
self.get_sync(id).ok_or(StoreError::NotFound)
|
||||
}
|
||||
async fn save(&self, template: &AgentTemplate) -> Result<(), StoreError> {
|
||||
let mut v = self.0.lock().unwrap();
|
||||
if let Some(slot) = v.iter_mut().find(|t| t.id == template.id) {
|
||||
*slot = template.clone();
|
||||
} else {
|
||||
v.push(template.clone());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
async fn delete(&self, id: TemplateId) -> Result<(), StoreError> {
|
||||
let mut v = self.0.lock().unwrap();
|
||||
let before = v.len();
|
||||
v.retain(|t| t.id != id);
|
||||
if v.len() == before {
|
||||
return Err(StoreError::NotFound);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct FakeContexts(Arc<Mutex<(AgentManifest, HashMap<String, String>)>>);
|
||||
impl FakeContexts {
|
||||
fn new(entries: Vec<ManifestEntry>) -> Self {
|
||||
Self(Arc::new(Mutex::new((
|
||||
AgentManifest { version: 1, entries },
|
||||
HashMap::new(),
|
||||
))))
|
||||
}
|
||||
fn manifest(&self) -> AgentManifest {
|
||||
self.0.lock().unwrap().0.clone()
|
||||
}
|
||||
fn content(&self, md_path: &str) -> Option<String> {
|
||||
self.0.lock().unwrap().1.get(md_path).cloned()
|
||||
}
|
||||
fn md_path_of(&self, agent: &AgentId) -> Option<String> {
|
||||
self.0
|
||||
.lock()
|
||||
.unwrap()
|
||||
.0
|
||||
.entries
|
||||
.iter()
|
||||
.find(|e| &e.agent_id == agent)
|
||||
.map(|e| e.md_path.clone())
|
||||
}
|
||||
}
|
||||
#[async_trait]
|
||||
impl AgentContextStore for FakeContexts {
|
||||
async fn read_context(
|
||||
&self,
|
||||
_p: &Project,
|
||||
agent: &AgentId,
|
||||
) -> Result<MarkdownDoc, StoreError> {
|
||||
let md = self.md_path_of(agent).ok_or(StoreError::NotFound)?;
|
||||
self.content(&md).map(MarkdownDoc::new).ok_or(StoreError::NotFound)
|
||||
}
|
||||
async fn write_context(
|
||||
&self,
|
||||
_p: &Project,
|
||||
agent: &AgentId,
|
||||
md: &MarkdownDoc,
|
||||
) -> Result<(), StoreError> {
|
||||
let path = self.md_path_of(agent).ok_or(StoreError::NotFound)?;
|
||||
self.0.lock().unwrap().1.insert(path, md.as_str().to_owned());
|
||||
Ok(())
|
||||
}
|
||||
async fn load_manifest(&self, _p: &Project) -> Result<AgentManifest, StoreError> {
|
||||
Ok(self.manifest())
|
||||
}
|
||||
async fn save_manifest(&self, _p: &Project, m: &AgentManifest) -> Result<(), StoreError> {
|
||||
self.0.lock().unwrap().0 = m.clone();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
struct SpyBus(Arc<Mutex<Vec<DomainEvent>>>);
|
||||
impl SpyBus {
|
||||
fn events(&self) -> Vec<DomainEvent> {
|
||||
self.0.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
impl EventBus for SpyBus {
|
||||
fn publish(&self, event: DomainEvent) {
|
||||
self.0.lock().unwrap().push(event);
|
||||
}
|
||||
fn subscribe(&self) -> EventStream {
|
||||
Box::new(std::iter::empty())
|
||||
}
|
||||
}
|
||||
|
||||
struct SeqIds(Mutex<u128>);
|
||||
impl SeqIds {
|
||||
fn new() -> Self {
|
||||
Self(Mutex::new(1))
|
||||
}
|
||||
}
|
||||
impl IdGenerator for SeqIds {
|
||||
fn new_uuid(&self) -> Uuid {
|
||||
let mut n = self.0.lock().unwrap();
|
||||
let id = Uuid::from_u128(*n);
|
||||
*n += 1;
|
||||
id
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Builders
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn pid(n: u128) -> ProfileId {
|
||||
ProfileId::from_uuid(Uuid::from_u128(n))
|
||||
}
|
||||
fn tid(n: u128) -> TemplateId {
|
||||
TemplateId::from_uuid(Uuid::from_u128(n))
|
||||
}
|
||||
fn aid(n: u128) -> AgentId {
|
||||
AgentId::from_uuid(Uuid::from_u128(n))
|
||||
}
|
||||
fn v(n: u64) -> TemplateVersion {
|
||||
TemplateVersion(n)
|
||||
}
|
||||
fn project() -> Project {
|
||||
Project::new(
|
||||
ProjectId::from_uuid(Uuid::from_u128(1000)),
|
||||
"demo",
|
||||
ProjectPath::new("/home/me/demo").unwrap(),
|
||||
RemoteRef::local(),
|
||||
1_700_000_000_000,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
fn template(id: TemplateId, name: &str, content: &str, version: u64) -> AgentTemplate {
|
||||
let mut t = AgentTemplate::new(id, name, MarkdownDoc::new(content), pid(1)).unwrap();
|
||||
// Bump to the requested version by re-applying content updates.
|
||||
while t.version.get() < version {
|
||||
t = t.with_updated_content(MarkdownDoc::new(content));
|
||||
}
|
||||
t
|
||||
}
|
||||
/// A synchronized, template-backed manifest entry synced at `synced`.
|
||||
fn synced_entry(agent: AgentId, md: &str, template: TemplateId, synced: u64) -> ManifestEntry {
|
||||
ManifestEntry::new(agent, "A", md, pid(1), Some(template), true, Some(v(synced))).unwrap()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CreateTemplate / UpdateTemplate
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_template_starts_at_initial_version() {
|
||||
let store = FakeTemplates::default();
|
||||
let out = CreateTemplate::new(Arc::new(store.clone()), Arc::new(SeqIds::new()))
|
||||
.execute(CreateTemplateInput {
|
||||
name: "Backend".to_owned(),
|
||||
content: "# ctx".to_owned(),
|
||||
default_profile_id: pid(7),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(out.template.version, TemplateVersion::INITIAL);
|
||||
assert_eq!(out.template.default_profile_id, pid(7));
|
||||
assert_eq!(store.list().await.unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn update_template_bumps_version_and_publishes_event() {
|
||||
let store = FakeTemplates::with(vec![template(tid(1), "T", "v1", 1)]);
|
||||
let bus = SpyBus::default();
|
||||
let out = UpdateTemplate::new(Arc::new(store.clone()), Arc::new(bus.clone()))
|
||||
.execute(UpdateTemplateInput {
|
||||
template_id: tid(1),
|
||||
content: "v2".to_owned(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(out.template.version.get(), 2);
|
||||
assert_eq!(store.get_sync(tid(1)).unwrap().content_md.as_str(), "v2");
|
||||
assert_eq!(
|
||||
bus.events(),
|
||||
vec![DomainEvent::TemplateUpdated {
|
||||
template_id: tid(1),
|
||||
version: v(2),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn update_unknown_template_is_not_found() {
|
||||
let err = UpdateTemplate::new(Arc::new(FakeTemplates::default()), Arc::new(SpyBus::default()))
|
||||
.execute(UpdateTemplateInput {
|
||||
template_id: tid(404),
|
||||
content: "x".to_owned(),
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "NOT_FOUND", "got {err:?}");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CreateAgentFromTemplate
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_agent_from_template_links_origin_and_seeds_context() {
|
||||
let store = FakeTemplates::with(vec![template(tid(1), "Backend", "# body", 4)]);
|
||||
let contexts = FakeContexts::new(vec![]);
|
||||
let out = CreateAgentFromTemplate::new(
|
||||
Arc::new(store),
|
||||
Arc::new(contexts.clone()),
|
||||
Arc::new(SeqIds::new()),
|
||||
Arc::new(SpyBus::default()),
|
||||
)
|
||||
.execute(CreateAgentFromTemplateInput {
|
||||
project: project(),
|
||||
template_id: tid(1),
|
||||
name: None,
|
||||
synchronized: true,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Name defaults to the template name; profile = template default.
|
||||
assert_eq!(out.agent.name, "Backend");
|
||||
assert_eq!(out.agent.profile_id, pid(1));
|
||||
assert!(out.agent.synchronized);
|
||||
assert_eq!(
|
||||
out.agent.origin,
|
||||
domain::AgentOrigin::FromTemplate {
|
||||
template_id: tid(1),
|
||||
synced_template_version: v(4),
|
||||
}
|
||||
);
|
||||
// Context seeded with the template content under the agent's md path.
|
||||
assert_eq!(contexts.content(&out.agent.context_path).as_deref(), Some("# body"));
|
||||
assert_eq!(contexts.manifest().entries.len(), 1);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// DetectAgentDrift
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn detect_drift_flags_only_synchronized_agents_behind() {
|
||||
// Template at v3.
|
||||
let store = FakeTemplates::with(vec![template(tid(1), "T", "v3", 3)]);
|
||||
// a1: synchronized, synced at v1 → drift (1→3).
|
||||
// a2: synchronized, synced at v3 → up to date, no drift.
|
||||
// a3: from template but NOT synchronized → ignored.
|
||||
// a4: scratch (no template) → ignored.
|
||||
let a3 = ManifestEntry::new(aid(3), "A3", "agents/a3.md", pid(1), Some(tid(1)), false, Some(v(1)))
|
||||
.unwrap();
|
||||
let a4 = ManifestEntry::new(aid(4), "A4", "agents/a4.md", pid(1), None, false, None).unwrap();
|
||||
let contexts = FakeContexts::new(vec![
|
||||
synced_entry(aid(1), "agents/a1.md", tid(1), 1),
|
||||
synced_entry(aid(2), "agents/a2.md", tid(1), 3),
|
||||
a3,
|
||||
a4,
|
||||
]);
|
||||
let bus = SpyBus::default();
|
||||
|
||||
let out = DetectAgentDrift::new(
|
||||
Arc::new(store),
|
||||
Arc::new(contexts),
|
||||
Arc::new(bus.clone()),
|
||||
)
|
||||
.execute(DetectAgentDriftInput { project: project() })
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(out.drifts.len(), 1, "only a1 drifts");
|
||||
assert_eq!(out.drifts[0].agent_id, aid(1));
|
||||
assert_eq!(out.drifts[0].from, v(1));
|
||||
assert_eq!(out.drifts[0].to, v(3));
|
||||
assert_eq!(
|
||||
bus.events(),
|
||||
vec![DomainEvent::AgentDriftDetected {
|
||||
agent_id: aid(1),
|
||||
from: v(1),
|
||||
to: v(3),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn detect_drift_ignores_deleted_template() {
|
||||
// No templates in the store, but an agent references tid(1): not an error.
|
||||
let store = FakeTemplates::default();
|
||||
let contexts = FakeContexts::new(vec![synced_entry(aid(1), "agents/a1.md", tid(1), 1)]);
|
||||
let out = DetectAgentDrift::new(
|
||||
Arc::new(store),
|
||||
Arc::new(contexts),
|
||||
Arc::new(SpyBus::default()),
|
||||
)
|
||||
.execute(DetectAgentDriftInput { project: project() })
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(out.drifts.is_empty());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SyncAgentWithTemplate
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn sync_applies_to_synchronized_and_updates_version_and_context() {
|
||||
let store = FakeTemplates::with(vec![template(tid(1), "T", "newest body", 3)]);
|
||||
let contexts = FakeContexts::new(vec![synced_entry(aid(1), "agents/a1.md", tid(1), 1)]);
|
||||
// Seed an old context so we can see the replacement.
|
||||
contexts
|
||||
.write_context(&project(), &aid(1), &MarkdownDoc::new("old"))
|
||||
.await
|
||||
.unwrap();
|
||||
let bus = SpyBus::default();
|
||||
|
||||
let out = SyncAgentWithTemplate::new(
|
||||
Arc::new(store),
|
||||
Arc::new(contexts.clone()),
|
||||
Arc::new(bus.clone()),
|
||||
)
|
||||
.execute(SyncAgentWithTemplateInput {
|
||||
project: project(),
|
||||
agent_id: aid(1),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(out.synced);
|
||||
assert_eq!(out.version, Some(v(3)));
|
||||
// Context replaced by the template content.
|
||||
assert_eq!(contexts.content("agents/a1.md").as_deref(), Some("newest body"));
|
||||
// Manifest synced version advanced to 3.
|
||||
let entry = &contexts.manifest().entries[0];
|
||||
assert_eq!(entry.synced_template_version, Some(v(3)));
|
||||
assert_eq!(
|
||||
bus.events(),
|
||||
vec![DomainEvent::AgentSynced {
|
||||
agent_id: aid(1),
|
||||
to: v(3),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sync_ignores_non_synchronized_agent() {
|
||||
let store = FakeTemplates::with(vec![template(tid(1), "T", "body", 3)]);
|
||||
// Non-synchronized agent from a template.
|
||||
let entry =
|
||||
ManifestEntry::new(aid(1), "A", "agents/a1.md", pid(1), Some(tid(1)), false, Some(v(1)))
|
||||
.unwrap();
|
||||
let contexts = FakeContexts::new(vec![entry]);
|
||||
contexts
|
||||
.write_context(&project(), &aid(1), &MarkdownDoc::new("keep me"))
|
||||
.await
|
||||
.unwrap();
|
||||
let bus = SpyBus::default();
|
||||
|
||||
let out = SyncAgentWithTemplate::new(
|
||||
Arc::new(store),
|
||||
Arc::new(contexts.clone()),
|
||||
Arc::new(bus.clone()),
|
||||
)
|
||||
.execute(SyncAgentWithTemplateInput {
|
||||
project: project(),
|
||||
agent_id: aid(1),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(!out.synced, "non-synchronized agent is left untouched");
|
||||
assert_eq!(out.version, None);
|
||||
assert_eq!(contexts.content("agents/a1.md").as_deref(), Some("keep me"));
|
||||
assert!(bus.events().is_empty(), "no sync event for an ignored agent");
|
||||
}
|
||||
535
crates/application/tests/terminal_usecases.rs
Normal file
535
crates/application/tests/terminal_usecases.rs
Normal file
@ -0,0 +1,535 @@
|
||||
//! L3 tests for the terminal use cases (`OpenTerminal`, `WriteToTerminal`,
|
||||
//! `ResizeTerminal`, `CloseTerminal`) and the [`TerminalSessions`] registry.
|
||||
//!
|
||||
//! Every port is faked in-memory so the use cases run without any real PTY:
|
||||
//! - [`FakePty`] — a recording [`PtyPort`] that mints a deterministic
|
||||
//! [`SessionId`] on `spawn` and records every `write`/`resize`/`kill`,
|
||||
//! - [`SpyBus`] — records published [`DomainEvent`]s.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use domain::events::DomainEvent;
|
||||
use domain::ports::{
|
||||
EventBus, EventStream, ExitStatus, OutputStream, PtyError, PtyHandle, PtyPort, SpawnSpec,
|
||||
};
|
||||
use domain::{PtySize, SessionId};
|
||||
|
||||
use application::{
|
||||
CloseTerminal, CloseTerminalInput, OpenTerminal, OpenTerminalInput, ResizeTerminal,
|
||||
ResizeTerminalInput, TerminalSessions, WriteToTerminal, WriteToTerminalInput,
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fakes
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// One recorded PTY call.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
enum Call {
|
||||
Spawn { spec: SpawnSpec, size: PtySize },
|
||||
Write { id: SessionId, data: Vec<u8> },
|
||||
Resize { id: SessionId, size: PtySize },
|
||||
Kill { id: SessionId },
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct FakePtyInner {
|
||||
calls: Vec<Call>,
|
||||
/// SessionId the next `spawn` will mint (defaults to random).
|
||||
next_id: Option<SessionId>,
|
||||
/// Exit code the next `kill` will report.
|
||||
kill_code: Option<i32>,
|
||||
/// When set, `write`/`resize` fail to exercise error propagation.
|
||||
fail_io: bool,
|
||||
}
|
||||
|
||||
/// A recording [`PtyPort`]: no real OS PTY, just bookkeeping.
|
||||
#[derive(Default, Clone)]
|
||||
struct FakePty(Arc<Mutex<FakePtyInner>>);
|
||||
|
||||
impl FakePty {
|
||||
fn with_next_id(id: SessionId) -> Self {
|
||||
let pty = Self::default();
|
||||
pty.0.lock().unwrap().next_id = Some(id);
|
||||
pty
|
||||
}
|
||||
fn calls(&self) -> Vec<Call> {
|
||||
self.0.lock().unwrap().calls.clone()
|
||||
}
|
||||
fn set_kill_code(&self, code: Option<i32>) {
|
||||
self.0.lock().unwrap().kill_code = code;
|
||||
}
|
||||
fn set_fail_io(&self, fail: bool) {
|
||||
self.0.lock().unwrap().fail_io = fail;
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl PtyPort for FakePty {
|
||||
async fn spawn(&self, spec: SpawnSpec, size: PtySize) -> Result<PtyHandle, PtyError> {
|
||||
let mut inner = self.0.lock().unwrap();
|
||||
inner.calls.push(Call::Spawn { spec, size });
|
||||
let session_id = inner.next_id.unwrap_or_else(SessionId::new_random);
|
||||
Ok(PtyHandle { session_id })
|
||||
}
|
||||
|
||||
fn write(&self, handle: &PtyHandle, data: &[u8]) -> Result<(), PtyError> {
|
||||
let mut inner = self.0.lock().unwrap();
|
||||
if inner.fail_io {
|
||||
return Err(PtyError::Io("boom".to_owned()));
|
||||
}
|
||||
inner.calls.push(Call::Write {
|
||||
id: handle.session_id,
|
||||
data: data.to_vec(),
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn resize(&self, handle: &PtyHandle, size: PtySize) -> Result<(), PtyError> {
|
||||
let mut inner = self.0.lock().unwrap();
|
||||
if inner.fail_io {
|
||||
return Err(PtyError::Io("boom".to_owned()));
|
||||
}
|
||||
inner.calls.push(Call::Resize {
|
||||
id: handle.session_id,
|
||||
size,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn subscribe_output(&self, _handle: &PtyHandle) -> Result<OutputStream, PtyError> {
|
||||
Ok(Box::new(std::iter::empty()))
|
||||
}
|
||||
|
||||
async fn kill(&self, handle: &PtyHandle) -> Result<ExitStatus, PtyError> {
|
||||
let mut inner = self.0.lock().unwrap();
|
||||
inner.calls.push(Call::Kill {
|
||||
id: handle.session_id,
|
||||
});
|
||||
Ok(ExitStatus {
|
||||
code: inner.kill_code,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Records published events.
|
||||
#[derive(Default, Clone)]
|
||||
struct SpyBus(Arc<Mutex<Vec<DomainEvent>>>);
|
||||
|
||||
impl SpyBus {
|
||||
fn events(&self) -> Vec<DomainEvent> {
|
||||
self.0.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl EventBus for SpyBus {
|
||||
fn publish(&self, event: DomainEvent) {
|
||||
self.0.lock().unwrap().push(event);
|
||||
}
|
||||
fn subscribe(&self) -> EventStream {
|
||||
Box::new(std::iter::empty())
|
||||
}
|
||||
}
|
||||
|
||||
fn sid(n: u128) -> SessionId {
|
||||
SessionId::from_uuid(uuid::Uuid::from_u128(n))
|
||||
}
|
||||
|
||||
fn open_input(cwd: &str) -> OpenTerminalInput {
|
||||
OpenTerminalInput {
|
||||
cwd: cwd.to_owned(),
|
||||
rows: 24,
|
||||
cols: 80,
|
||||
command: None,
|
||||
args: Vec::new(),
|
||||
node_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// OpenTerminal
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn open_spawns_with_resolved_spec_and_size() {
|
||||
let pty = FakePty::with_next_id(sid(42));
|
||||
let sessions = Arc::new(TerminalSessions::new());
|
||||
let bus = SpyBus::default();
|
||||
let open = OpenTerminal::new(
|
||||
Arc::new(pty.clone()),
|
||||
Arc::clone(&sessions),
|
||||
Arc::new(bus.clone()),
|
||||
);
|
||||
|
||||
let input = OpenTerminalInput {
|
||||
command: Some("/bin/zsh".to_owned()),
|
||||
args: vec!["-l".to_owned()],
|
||||
..open_input("/home/me/proj")
|
||||
};
|
||||
let out = open.execute(input).await.expect("open succeeds");
|
||||
|
||||
// The session adopts the PTY-minted id.
|
||||
assert_eq!(out.session.id, sid(42));
|
||||
|
||||
let calls = pty.calls();
|
||||
assert_eq!(calls.len(), 1, "exactly one spawn");
|
||||
match &calls[0] {
|
||||
Call::Spawn { spec, size } => {
|
||||
assert_eq!(spec.command, "/bin/zsh");
|
||||
assert_eq!(spec.args, vec!["-l".to_owned()]);
|
||||
assert_eq!(spec.cwd.as_str(), "/home/me/proj");
|
||||
assert_eq!(*size, PtySize::new(24, 80).unwrap());
|
||||
}
|
||||
other => panic!("expected spawn, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn open_defaults_command_when_none() {
|
||||
let pty = FakePty::default();
|
||||
let open = OpenTerminal::new(
|
||||
Arc::new(pty.clone()),
|
||||
Arc::new(TerminalSessions::new()),
|
||||
Arc::new(SpyBus::default()),
|
||||
);
|
||||
open.execute(open_input("/p")).await.unwrap();
|
||||
|
||||
match &pty.calls()[0] {
|
||||
Call::Spawn { spec, .. } => assert!(
|
||||
!spec.command.is_empty(),
|
||||
"a default shell command is filled in"
|
||||
),
|
||||
other => panic!("expected spawn, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn open_registers_session_in_registry() {
|
||||
let pty = FakePty::with_next_id(sid(7));
|
||||
let sessions = Arc::new(TerminalSessions::new());
|
||||
let open = OpenTerminal::new(
|
||||
Arc::new(pty),
|
||||
Arc::clone(&sessions),
|
||||
Arc::new(SpyBus::default()),
|
||||
);
|
||||
|
||||
assert!(sessions.is_empty());
|
||||
open.execute(open_input("/p")).await.unwrap();
|
||||
|
||||
assert_eq!(sessions.len(), 1);
|
||||
assert!(sessions.handle(&sid(7)).is_some(), "handle registered");
|
||||
assert!(sessions.session(&sid(7)).is_some(), "snapshot registered");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn open_publishes_pty_output_open_event() {
|
||||
let pty = FakePty::with_next_id(sid(9));
|
||||
let bus = SpyBus::default();
|
||||
let open = OpenTerminal::new(
|
||||
Arc::new(pty),
|
||||
Arc::new(TerminalSessions::new()),
|
||||
Arc::new(bus.clone()),
|
||||
);
|
||||
open.execute(open_input("/p")).await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
bus.events(),
|
||||
vec![DomainEvent::PtyOutput {
|
||||
session_id: sid(9),
|
||||
bytes: Vec::new(),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn open_rejects_non_absolute_cwd() {
|
||||
let open = OpenTerminal::new(
|
||||
Arc::new(FakePty::default()),
|
||||
Arc::new(TerminalSessions::new()),
|
||||
Arc::new(SpyBus::default()),
|
||||
);
|
||||
let err = open
|
||||
.execute(open_input("relative/path"))
|
||||
.await
|
||||
.expect_err("non-absolute cwd rejected");
|
||||
assert_eq!(err.code(), "INVALID", "got {err:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn open_rejects_zero_sized_terminal() {
|
||||
let pty = FakePty::default();
|
||||
let open = OpenTerminal::new(
|
||||
Arc::new(pty.clone()),
|
||||
Arc::new(TerminalSessions::new()),
|
||||
Arc::new(SpyBus::default()),
|
||||
);
|
||||
let err = open
|
||||
.execute(OpenTerminalInput {
|
||||
rows: 0,
|
||||
..open_input("/p")
|
||||
})
|
||||
.await
|
||||
.expect_err("zero-sized terminal rejected");
|
||||
assert_eq!(err.code(), "INVALID", "got {err:?}");
|
||||
assert!(pty.calls().is_empty(), "must not spawn on invalid size");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// WriteToTerminal
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn write_routes_bytes_to_the_right_session() {
|
||||
let pty = FakePty::with_next_id(sid(1));
|
||||
let sessions = Arc::new(TerminalSessions::new());
|
||||
let open = OpenTerminal::new(
|
||||
Arc::new(pty.clone()),
|
||||
Arc::clone(&sessions),
|
||||
Arc::new(SpyBus::default()),
|
||||
);
|
||||
open.execute(open_input("/p")).await.unwrap();
|
||||
|
||||
let write = WriteToTerminal::new(Arc::new(pty.clone()), Arc::clone(&sessions));
|
||||
write
|
||||
.execute(WriteToTerminalInput {
|
||||
session_id: sid(1),
|
||||
data: b"ls\n".to_vec(),
|
||||
})
|
||||
.expect("write succeeds");
|
||||
|
||||
let writes: Vec<_> = pty
|
||||
.calls()
|
||||
.into_iter()
|
||||
.filter(|c| matches!(c, Call::Write { .. }))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
writes,
|
||||
vec![Call::Write {
|
||||
id: sid(1),
|
||||
data: b"ls\n".to_vec(),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn write_to_unknown_session_is_not_found() {
|
||||
let pty = FakePty::default();
|
||||
let write = WriteToTerminal::new(Arc::new(pty.clone()), Arc::new(TerminalSessions::new()));
|
||||
let err = write
|
||||
.execute(WriteToTerminalInput {
|
||||
session_id: sid(404),
|
||||
data: b"x".to_vec(),
|
||||
})
|
||||
.expect_err("unknown session rejected");
|
||||
assert_eq!(err.code(), "NOT_FOUND", "got {err:?}");
|
||||
assert!(pty.calls().is_empty(), "no PTY call for unknown session");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn write_propagates_pty_io_error() {
|
||||
let pty = FakePty::with_next_id(sid(2));
|
||||
let sessions = Arc::new(TerminalSessions::new());
|
||||
OpenTerminal::new(
|
||||
Arc::new(pty.clone()),
|
||||
Arc::clone(&sessions),
|
||||
Arc::new(SpyBus::default()),
|
||||
)
|
||||
.execute(open_input("/p"))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
pty.set_fail_io(true);
|
||||
let write = WriteToTerminal::new(Arc::new(pty.clone()), Arc::clone(&sessions));
|
||||
let err = write
|
||||
.execute(WriteToTerminalInput {
|
||||
session_id: sid(2),
|
||||
data: b"x".to_vec(),
|
||||
})
|
||||
.expect_err("io failure surfaces");
|
||||
assert_eq!(err.code(), "PROCESS", "got {err:?}");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ResizeTerminal
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn resize_calls_pty_with_new_size() {
|
||||
let pty = FakePty::with_next_id(sid(3));
|
||||
let sessions = Arc::new(TerminalSessions::new());
|
||||
OpenTerminal::new(
|
||||
Arc::new(pty.clone()),
|
||||
Arc::clone(&sessions),
|
||||
Arc::new(SpyBus::default()),
|
||||
)
|
||||
.execute(open_input("/p"))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let resize = ResizeTerminal::new(Arc::new(pty.clone()), Arc::clone(&sessions));
|
||||
resize
|
||||
.execute(ResizeTerminalInput {
|
||||
session_id: sid(3),
|
||||
rows: 40,
|
||||
cols: 120,
|
||||
})
|
||||
.expect("resize succeeds");
|
||||
|
||||
let resizes: Vec<_> = pty
|
||||
.calls()
|
||||
.into_iter()
|
||||
.filter(|c| matches!(c, Call::Resize { .. }))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
resizes,
|
||||
vec![Call::Resize {
|
||||
id: sid(3),
|
||||
size: PtySize::new(40, 120).unwrap(),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resize_unknown_session_is_not_found() {
|
||||
let resize = ResizeTerminal::new(
|
||||
Arc::new(FakePty::default()),
|
||||
Arc::new(TerminalSessions::new()),
|
||||
);
|
||||
let err = resize
|
||||
.execute(ResizeTerminalInput {
|
||||
session_id: sid(404),
|
||||
rows: 40,
|
||||
cols: 120,
|
||||
})
|
||||
.expect_err("unknown session rejected");
|
||||
assert_eq!(err.code(), "NOT_FOUND", "got {err:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resize_rejects_zero_size() {
|
||||
let resize = ResizeTerminal::new(
|
||||
Arc::new(FakePty::default()),
|
||||
Arc::new(TerminalSessions::new()),
|
||||
);
|
||||
let err = resize
|
||||
.execute(ResizeTerminalInput {
|
||||
session_id: sid(1),
|
||||
rows: 0,
|
||||
cols: 80,
|
||||
})
|
||||
.expect_err("zero size rejected");
|
||||
assert_eq!(err.code(), "INVALID", "got {err:?}");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CloseTerminal
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn close_kills_pty_removes_session_and_returns_code() {
|
||||
let pty = FakePty::with_next_id(sid(5));
|
||||
pty.set_kill_code(Some(0));
|
||||
let sessions = Arc::new(TerminalSessions::new());
|
||||
OpenTerminal::new(
|
||||
Arc::new(pty.clone()),
|
||||
Arc::clone(&sessions),
|
||||
Arc::new(SpyBus::default()),
|
||||
)
|
||||
.execute(open_input("/p"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(sessions.len(), 1);
|
||||
|
||||
let close = CloseTerminal::new(Arc::new(pty.clone()), Arc::clone(&sessions));
|
||||
let out = close
|
||||
.execute(CloseTerminalInput {
|
||||
session_id: sid(5),
|
||||
})
|
||||
.await
|
||||
.expect("close succeeds");
|
||||
|
||||
assert_eq!(out.code, Some(0));
|
||||
assert!(sessions.is_empty(), "session removed from registry");
|
||||
assert!(
|
||||
pty.calls().iter().any(|c| matches!(c, Call::Kill { id } if *id == sid(5))),
|
||||
"kill called for the session"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn close_surfaces_signal_exit_as_none_code() {
|
||||
let pty = FakePty::with_next_id(sid(6));
|
||||
pty.set_kill_code(None);
|
||||
let sessions = Arc::new(TerminalSessions::new());
|
||||
OpenTerminal::new(
|
||||
Arc::new(pty.clone()),
|
||||
Arc::clone(&sessions),
|
||||
Arc::new(SpyBus::default()),
|
||||
)
|
||||
.execute(open_input("/p"))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let close = CloseTerminal::new(Arc::new(pty.clone()), Arc::clone(&sessions));
|
||||
let out = close
|
||||
.execute(CloseTerminalInput {
|
||||
session_id: sid(6),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(out.code, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn close_unknown_session_is_not_found() {
|
||||
let pty = FakePty::default();
|
||||
let close = CloseTerminal::new(Arc::new(pty.clone()), Arc::new(TerminalSessions::new()));
|
||||
let err = close
|
||||
.execute(CloseTerminalInput {
|
||||
session_id: sid(404),
|
||||
})
|
||||
.await
|
||||
.expect_err("unknown session rejected");
|
||||
assert_eq!(err.code(), "NOT_FOUND", "got {err:?}");
|
||||
assert!(pty.calls().is_empty(), "no kill for unknown session");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TerminalSessions registry (unit-level)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn registry_insert_handle_session_remove_len() {
|
||||
use domain::{NodeId, ProjectPath, SessionKind, TerminalSession};
|
||||
|
||||
let registry = TerminalSessions::new();
|
||||
assert!(registry.is_empty());
|
||||
assert_eq!(registry.len(), 0);
|
||||
|
||||
let id = sid(100);
|
||||
let handle = PtyHandle { session_id: id };
|
||||
let session = TerminalSession::starting(
|
||||
id,
|
||||
NodeId::new_random(),
|
||||
ProjectPath::new("/p").unwrap(),
|
||||
SessionKind::Plain,
|
||||
PtySize::new(24, 80).unwrap(),
|
||||
);
|
||||
registry.insert(handle.clone(), session);
|
||||
|
||||
assert_eq!(registry.len(), 1);
|
||||
assert!(!registry.is_empty());
|
||||
assert_eq!(registry.handle(&id), Some(handle.clone()));
|
||||
assert!(registry.session(&id).is_some());
|
||||
assert_eq!(registry.session(&id).unwrap().id, id);
|
||||
|
||||
// Unknown id resolves to None.
|
||||
assert!(registry.handle(&sid(999)).is_none());
|
||||
assert!(registry.session(&sid(999)).is_none());
|
||||
|
||||
// Remove returns the handle and empties the registry.
|
||||
assert_eq!(registry.remove(&id), Some(handle));
|
||||
assert!(registry.is_empty());
|
||||
assert!(registry.remove(&id).is_none(), "second remove is a no-op");
|
||||
}
|
||||
111
crates/application/tests/window_usecases.rs
Normal file
111
crates/application/tests/window_usecases.rs
Normal file
@ -0,0 +1,111 @@
|
||||
//! L10 tests for [`MoveTabToNewWindow`] with a fake [`ProjectStore`]: the tab is
|
||||
//! detached and the workspace is persisted (load returns the new state).
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use domain::ids::{ProjectId, TabId, WindowId};
|
||||
use domain::layout::{LayoutNode, LayoutTree, LeafCell, Tab, Window, Workspace};
|
||||
use domain::ports::{IdGenerator, ProjectStore, StoreError};
|
||||
use domain::project::Project;
|
||||
use domain::NodeId;
|
||||
use uuid::Uuid;
|
||||
|
||||
use application::{MoveTabToNewWindow, MoveTabToNewWindowInput};
|
||||
|
||||
/// A `ProjectStore` fake that only implements the workspace persistence the use
|
||||
/// case needs (the project methods are never called here).
|
||||
#[derive(Clone)]
|
||||
struct FakeStore(Arc<Mutex<Workspace>>);
|
||||
#[async_trait]
|
||||
impl ProjectStore for FakeStore {
|
||||
async fn list_projects(&self) -> Result<Vec<Project>, StoreError> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn load_project(&self, _id: ProjectId) -> Result<Project, StoreError> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn save_project(&self, _p: &Project) -> Result<(), StoreError> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn save_workspace(&self, ws: &Workspace) -> Result<(), StoreError> {
|
||||
*self.0.lock().unwrap() = ws.clone();
|
||||
Ok(())
|
||||
}
|
||||
async fn load_workspace(&self) -> Result<Workspace, StoreError> {
|
||||
Ok(self.0.lock().unwrap().clone())
|
||||
}
|
||||
}
|
||||
|
||||
struct SeqIds(Mutex<u128>);
|
||||
impl IdGenerator for SeqIds {
|
||||
fn new_uuid(&self) -> Uuid {
|
||||
let mut n = self.0.lock().unwrap();
|
||||
let id = Uuid::from_u128(*n);
|
||||
*n += 1;
|
||||
id
|
||||
}
|
||||
}
|
||||
|
||||
fn tid(n: u128) -> TabId {
|
||||
TabId::from_uuid(Uuid::from_u128(n))
|
||||
}
|
||||
fn wid(n: u128) -> WindowId {
|
||||
WindowId::from_uuid(Uuid::from_u128(n))
|
||||
}
|
||||
fn tab(n: u128) -> Tab {
|
||||
Tab {
|
||||
id: tid(n),
|
||||
project_id: ProjectId::from_uuid(Uuid::from_u128(1000 + n)),
|
||||
layout: LayoutTree::new(LayoutNode::Leaf(LeafCell {
|
||||
id: NodeId::from_uuid(Uuid::from_u128(900 + n)),
|
||||
session: None,
|
||||
agent: None,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
fn seeded() -> FakeStore {
|
||||
let ws = Workspace {
|
||||
windows: vec![Window::new(wid(1), vec![tab(1), tab(2)], tid(1)).unwrap()],
|
||||
};
|
||||
FakeStore(Arc::new(Mutex::new(ws)))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn detaches_tab_and_persists_workspace() {
|
||||
let store = seeded();
|
||||
// The id generator's first uuid (from_u128(7)) becomes the new window id.
|
||||
let ids = Arc::new(SeqIds(Mutex::new(7)));
|
||||
let uc = MoveTabToNewWindow::new(Arc::new(store.clone()), ids);
|
||||
|
||||
let out = uc
|
||||
.execute(MoveTabToNewWindowInput { tab_id: tid(1) })
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(out.new_window_id, WindowId::from_uuid(Uuid::from_u128(7)));
|
||||
assert_eq!(out.workspace.windows.len(), 2);
|
||||
|
||||
// Persisted: reloading the store yields the detached layout.
|
||||
let reloaded = store.load_workspace().await.unwrap();
|
||||
assert_eq!(reloaded, out.workspace);
|
||||
let detached = reloaded
|
||||
.windows
|
||||
.iter()
|
||||
.find(|w| w.id == out.new_window_id)
|
||||
.unwrap();
|
||||
assert_eq!(detached.tabs.len(), 1);
|
||||
assert_eq!(detached.tabs[0].id, tid(1));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unknown_tab_is_not_found() {
|
||||
let store = seeded();
|
||||
let uc = MoveTabToNewWindow::new(Arc::new(store), Arc::new(SeqIds(Mutex::new(7))));
|
||||
let err = uc
|
||||
.execute(MoveTabToNewWindowInput { tab_id: tid(404) })
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "NOT_FOUND", "got {err:?}");
|
||||
}
|
||||
Reference in New Issue
Block a user