fix(runtime): stop/restart d'agent visible robuste — kill réel, état stopped, relance froide (#196, QA verte)

Solidifie le cycle stop/restart d'un agent visible en cellule:

- terminal/registry: kill effectif de la TUI native et de la CLI custom, arrêt idempotent du live runtime (PTY + structuré), distinction nette « agent stoppé » vs « pas de session ».

- workstate + lifecycle: projection d'un état runtime explicite « stopped » (AgentRuntimeState: running/stopping/stopped/failedStart), réconcilié avec le live state; traitement des courses « agent not found ».

- relance froide via freshStart: repart de zéro sans réattacher une session morte et recharge la configuration courante de l'agent (y compris changement de modèle).

- contrat projeté côté adapters frontend (ports/domain/normalization/mock) pour la consommation UI future (#197/#198), sans surface UI ici.

Tests QA verts: workstate_actions, orchestrator_service stop_agent, agent_lifecycle (reopen/fresh_start), workstate stopped runtime state, vitest adapter stop_live_agent.
This commit is contained in:
2026-08-12 14:56:02 +02:00
parent 4e93fa2f20
commit bad7b4c2f3
23 changed files with 440 additions and 46 deletions

View File

@ -29,8 +29,8 @@ mod registry;
mod usecases;
pub use registry::{
LiveAgentRegistry, LiveSessionKind, LiveSessionSnapshot, LiveSessions, StructuredSessions,
TerminalSessions,
LiveAgentRegistry, LiveRuntimeState, LiveRuntimeStatus, LiveSessionKind, LiveSessionSnapshot,
LiveSessions, StructuredSessions, TerminalSessions,
};
pub use usecases::{
stop_live_agent_runtime_in_project, CloseTerminal, CloseTerminalInput, CloseTerminalOutput,

View File

@ -24,6 +24,19 @@ pub enum LiveSessionKind {
Structured,
}
/// Explicit lifecycle state of an agent runtime in a visible cell.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LiveRuntimeState {
/// The runtime has a live session in one of the registries.
Running,
/// A stop request is currently tearing the runtime down.
Stopping,
/// The runtime was torn down and no live session remains.
Stopped,
/// The last launch attempt failed before a live session was registered.
FailedStart,
}
/// Read-only coordinates of one live agent session.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LiveSessionSnapshot {
@ -39,6 +52,51 @@ pub struct LiveSessionSnapshot {
pub kind: LiveSessionKind,
}
/// Last-known lifecycle projection for one agent runtime.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LiveRuntimeStatus {
/// The project owning the runtime.
pub project_id: ProjectId,
/// The agent owning the runtime.
pub agent_id: AgentId,
/// Last known layout node hosting the runtime view.
pub node_id: NodeId,
/// Last known session id.
pub session_id: SessionId,
/// Runtime family that owns or owned the session.
pub kind: LiveSessionKind,
/// Current lifecycle state.
pub state: LiveRuntimeState,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct LiveAgentKey {
project_id: ProjectId,
agent_id: AgentId,
}
impl LiveAgentKey {
fn new(project_id: ProjectId, agent_id: AgentId) -> Self {
Self {
project_id,
agent_id,
}
}
}
impl From<LiveSessionSnapshot> for LiveRuntimeStatus {
fn from(snapshot: LiveSessionSnapshot) -> Self {
Self {
project_id: snapshot.project_id,
agent_id: snapshot.agent_id,
node_id: snapshot.node_id,
session_id: snapshot.session_id,
kind: snapshot.kind,
state: LiveRuntimeState::Running,
}
}
}
/// A registered, live terminal: its PTY handle plus the domain snapshot.
#[derive(Debug)]
struct Entry {
@ -849,13 +907,18 @@ pub struct LiveSessions {
pub pty: Arc<TerminalSessions>,
/// Registre des sessions IA structurées.
pub structured: Arc<StructuredSessions>,
runtime: Mutex<HashMap<LiveAgentKey, LiveRuntimeStatus>>,
}
impl LiveSessions {
/// Construit l'agrégateur à partir des deux registres partagés.
#[must_use]
pub fn new(pty: Arc<TerminalSessions>, structured: Arc<StructuredSessions>) -> Self {
Self { pty, structured }
Self {
pty,
structured,
runtime: Mutex::new(HashMap::new()),
}
}
/// L'[`SessionId`] de la session vivante d'un agent, PTY **ou** structurée.
@ -899,6 +962,62 @@ impl LiveSessions {
all.extend(self.structured.live_agent_snapshots());
all
}
/// All live runtime snapshots for one `(project, agent)` canonical key.
#[must_use]
pub fn live_agent_snapshots_for(
&self,
project_id: ProjectId,
agent_id: &AgentId,
) -> Vec<LiveSessionSnapshot> {
self.live_agent_snapshots()
.into_iter()
.filter(|snapshot| snapshot.project_id == project_id && &snapshot.agent_id == agent_id)
.collect()
}
/// Current runtime projection for one canonical `(project, agent)` key.
#[must_use]
pub fn runtime_status_for(
&self,
project_id: ProjectId,
agent_id: &AgentId,
) -> Option<LiveRuntimeStatus> {
self.live_agent_snapshots_for(project_id, agent_id)
.into_iter()
.next()
.map(LiveRuntimeStatus::from)
.or_else(|| {
self.runtime
.lock()
.ok()
.and_then(|m| m.get(&LiveAgentKey::new(project_id, *agent_id)).copied())
})
}
/// Records a non-running runtime state for the last known session coordinates.
pub fn mark_runtime_state(&self, snapshot: LiveSessionSnapshot, state: LiveRuntimeState) {
if let Ok(mut map) = self.runtime.lock() {
map.insert(
LiveAgentKey::new(snapshot.project_id, snapshot.agent_id),
LiveRuntimeStatus {
project_id: snapshot.project_id,
agent_id: snapshot.agent_id,
node_id: snapshot.node_id,
session_id: snapshot.session_id,
kind: snapshot.kind,
state,
},
);
}
}
/// Drops stale stopped/failed state when a caller needs a clean runtime boundary.
pub fn clear_runtime_state(&self, project_id: ProjectId, agent_id: &AgentId) {
if let Ok(mut map) = self.runtime.lock() {
map.remove(&LiveAgentKey::new(project_id, *agent_id));
}
}
}
impl LiveAgentRegistry for LiveSessions {

View File

@ -10,7 +10,7 @@ use domain::{
use crate::error::AppError;
use super::registry::{LiveSessionKind, LiveSessions, TerminalSessions};
use super::registry::{LiveRuntimeState, LiveSessionKind, LiveSessions, TerminalSessions};
/// Input for [`OpenTerminal::execute`].
#[derive(Debug, Clone, PartialEq, Eq)]
@ -223,9 +223,10 @@ impl CloseTerminal {
) -> Result<CloseTerminalOutput, AppError> {
let handle = self
.sessions
.remove(&input.session_id)
.handle(&input.session_id)
.ok_or_else(|| AppError::NotFound(format!("terminal session {}", input.session_id)))?;
let status = self.pty.kill(&handle).await?;
self.sessions.remove(&input.session_id);
Ok(CloseTerminalOutput { code: status.code })
}
}
@ -237,8 +238,12 @@ pub struct StoppedAgentRuntime {
pub agent_id: AgentId,
/// Live session id removed from its registry.
pub session_id: SessionId,
/// Last known layout node hosting the runtime view.
pub node_id: NodeId,
/// Runtime registry that owned the session.
pub kind: LiveSessionKind,
/// Lifecycle state reached by this stop operation.
pub state: LiveRuntimeState,
}
/// Stops one agent's live runtime across both registries.
@ -253,30 +258,34 @@ pub async fn stop_live_agent_runtime_in_project(
close: &CloseTerminal,
) -> Result<Vec<StoppedAgentRuntime>, AppError> {
let mut stopped = Vec::new();
let snapshots = live.live_agent_snapshots_for(project.id, &agent_id);
if let Some(session_id) = live
.structured
.session_id_for_agent_in_project(project.id, &agent_id)
{
if let Some(session) = live.structured.remove(&session_id) {
session
.shutdown()
.await
.map_err(|e| AppError::Process(e.to_string()))?;
for snapshot in snapshots {
live.mark_runtime_state(snapshot, LiveRuntimeState::Stopping);
match snapshot.kind {
LiveSessionKind::Structured => {
if let Some(session) = live.structured.remove(&snapshot.session_id) {
session
.shutdown()
.await
.map_err(|e| AppError::Process(e.to_string()))?;
}
}
LiveSessionKind::Pty => {
close
.execute(CloseTerminalInput {
session_id: snapshot.session_id,
})
.await?;
}
}
live.mark_runtime_state(snapshot, LiveRuntimeState::Stopped);
stopped.push(StoppedAgentRuntime {
agent_id,
session_id,
kind: LiveSessionKind::Structured,
});
}
if let Some(session_id) = live.pty.session_for_agent_in_project(project.id, &agent_id) {
close.execute(CloseTerminalInput { session_id }).await?;
stopped.push(StoppedAgentRuntime {
agent_id,
session_id,
kind: LiveSessionKind::Pty,
agent_id: snapshot.agent_id,
session_id: snapshot.session_id,
node_id: snapshot.node_id,
kind: snapshot.kind,
state: LiveRuntimeState::Stopped,
});
}