feat(backend,application,frontend,domain,web-server,app-tauri): bouton Redémarrer l'agent dans la barre supérieure des cellules — #317 (QA verte)

La cellule expose un bouton Redémarrer l'agent valable pour les trois
modes de présentation (headless, TUI native, CLI custom), sans jamais
prendre la présentation pour vérité runtime.

- Application: use case RestartCellAgentRuntime validant le binding
  exact cellule/runtime via les snapshots live (RestartRuntimeNotFound,
  ConflictAgentVisibleElsewhere, AgentNotBoundToCell) puis déléguant au
  scheduler self-restart existant (schedule_cell); CellAgentPresentation
  purement informationnelle.
- Backend/app-tauri/web-server: commande restart_cell_agent sur contrat
  DTO identique Tauri/HTTP, stop borné par timeout typé
  (RestartStopTimeout), relance préservant routage TUI natif, géométrie
  de cellule (node/rows/cols) et conversation; évenements domaine
  enrichis.
- Frontend: bouton dans la barre de cellule avec confirmation,
  overlay d'état Redémarrage…/échec (libellés par code d'erreur, Fermer/
  Réessayer), gardes d'identité de cellule et de restarts externes,
  gateway/mock/http adapters et ports alignés.
- Tests: dto_agents, workstate_actions, contrats web-server,
  LayoutGrid.cellControlsLayering, adapters agent/mock/http.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-09-11 15:00:43 +02:00
parent 46449bdf46
commit 7fb9d8bb86
26 changed files with 1404 additions and 58 deletions

View File

@ -73,6 +73,36 @@ pub enum AppError {
node_id: NodeId,
},
/// No live runtime can be restarted for the requested agent.
#[error("runtime not found for agent {agent_id}")]
RestartRuntimeNotFound {
/// Agent whose runtime was requested.
agent_id: AgentId,
},
/// The requested cell does not host the requested live agent runtime.
#[error("agent {agent_id} is not bound to cell {node_id}")]
AgentNotBoundToCell {
/// Agent supplied by the caller.
agent_id: AgentId,
/// Cell supplied by the caller.
node_id: NodeId,
},
/// More than one live runtime/cell currently represents the same agent.
#[error("agent {agent_id} is visible in more than one live cell")]
ConflictAgentVisibleElsewhere {
/// Ambiguous agent.
agent_id: AgentId,
},
/// Runtime teardown did not reach its terminal boundary in time.
#[error("timed out while stopping agent {agent_id} for restart")]
RestartStopTimeout {
/// Agent whose old runtime could not be stopped conclusively.
agent_id: AgentId,
},
/// The delegation target finished its structured/headless turn without producing
/// a [`ReplyEvent::Final`](domain::ports::ReplyEvent::Final), so the rendezvous
/// could not capture an inline answer. Surfaced promptly instead of blocking the
@ -120,6 +150,10 @@ impl AppError {
Self::Git(_) => "GIT",
Self::Remote(_) => "REMOTE",
Self::AgentAlreadyRunning { .. } => "AGENT_ALREADY_RUNNING",
Self::RestartRuntimeNotFound { .. } => "RUNTIME_NOT_FOUND",
Self::AgentNotBoundToCell { .. } => "AGENT_NOT_BOUND_TO_CELL",
Self::ConflictAgentVisibleElsewhere { .. } => "CONFLICT_AGENT_VISIBLE_ELSEWHERE",
Self::RestartStopTimeout { .. } => "STOP_TIMEOUT",
Self::TargetReturnedNoReply(_) => "TARGET_RETURNED_NO_REPLY",
Self::TargetCeilingActive(_) => "RENDEZVOUS_CEILING_ACTIVE",
Self::Internal(_) => "INTERNAL",

View File

@ -280,11 +280,13 @@ pub use window::{
pub use workstate::{
AgentBackgroundTaskState, AgentTicketState, AgentWorkState, AppExitWorkGuardDetail,
AppExitWorkGuardState, AttachLiveAgent, AttachLiveAgentInput, AttachLiveAgentOutput,
BackgroundTaskKindLabel, ConversationLogProvider, ConversationPreviewStatus,
ConversationTurnWorkPreview, ConversationWorkSummary, GetAppExitWorkGuardState,
GetAppExitWorkGuardStateInput, GetLiveStateLean, GetProjectWorkState, GetProjectWorkStateInput,
LeanLiveEntry, LeanLiveState, LiveWorkSession, ProjectWorkState, ReconcileLiveState,
ReconcileLiveStateInput, StopAgentExecutionCascade, StopAgentRuntime, StopLiveAgent,
StopLiveAgentInput, StopLiveAgentOutput, TicketWorkSource, TicketWorkStatus, UpdateLiveState,
UpdateLiveStateInput, LIVE_STATE_MAX_ENTRIES, LIVE_STATE_TTL_MS,
BackgroundTaskKindLabel, CellAgentPresentation, ConversationLogProvider,
ConversationPreviewStatus, ConversationTurnWorkPreview, ConversationWorkSummary,
GetAppExitWorkGuardState, GetAppExitWorkGuardStateInput, GetLiveStateLean, GetProjectWorkState,
GetProjectWorkStateInput, LeanLiveEntry, LeanLiveState, LiveWorkSession, ProjectWorkState,
ReconcileLiveState, ReconcileLiveStateInput, RestartCellAgentRuntime,
RestartCellAgentRuntimeInput, RestartCellAgentRuntimeOutput, StopAgentExecutionCascade,
StopAgentRuntime, StopLiveAgent, StopLiveAgentInput, StopLiveAgentOutput, TicketWorkSource,
TicketWorkStatus, UpdateLiveState, UpdateLiveStateInput, LIVE_STATE_MAX_ENTRIES,
LIVE_STATE_TTL_MS,
};

View File

@ -32,7 +32,7 @@ use domain::ports::{
use domain::project::ProjectPath;
use domain::{
AgentId, AgentProfile, BackgroundTask, BackgroundTaskKind, BackgroundTaskRendezvousLink,
BackgroundTaskResult, BackgroundTaskState, BackgroundTaskWakePolicy, DomainEvent,
BackgroundTaskResult, BackgroundTaskState, BackgroundTaskWakePolicy, DomainEvent, NodeId,
OrchestratorCommand, OrchestratorVisibility, ProfileId, Project, RendezvousId, RuntimeAgentKey,
TaskId,
};
@ -83,6 +83,20 @@ pub trait AgentSelfRestartScheduler: Send + Sync {
agent: AgentId,
reason: Option<String>,
) -> Result<AgentRestartScheduled, AppError>;
/// Schedules the same restart while pinning it to a caller-validated cell.
/// Implementations must revalidate the binding atomically with their
/// concurrency guard before accepting the request.
fn schedule_cell(
&self,
project: &Project,
agent: AgentId,
node: NodeId,
reason: Option<String>,
) -> Result<AgentRestartScheduled, AppError> {
let _ = node;
self.schedule(project, agent, reason)
}
}
/// Internal continuation prompt used when a self-restart is handed back to the

View File

@ -12,10 +12,10 @@ use std::sync::Arc;
use async_trait::async_trait;
use domain::input::InputMediator;
use domain::live_state::WorkStatus;
use domain::{AgentId, NodeId, Project, RuntimeAgentKey, SessionId};
use domain::{AgentId, LayoutId, NodeId, Project, RuntimeAgentKey, SessionId};
use crate::error::AppError;
use crate::orchestrator::{LiveStateProvider, OrchestratorService};
use crate::orchestrator::{AgentSelfRestartScheduler, LiveStateProvider, OrchestratorService};
use crate::terminal::{
stop_live_agent_runtime_in_project, CloseTerminal, LiveSessionKind, LiveSessions,
};
@ -122,6 +122,113 @@ pub struct StopLiveAgentOutput {
pub already_stopped: bool,
}
/// Caller-side indication of how the hosting cell presents the agent.
///
/// This value is never trusted to select the runtime: the live registries and
/// the launch context remain authoritative.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CellAgentPresentation {
/// Agent driven without an interactive human surface.
Headless,
/// Native provider terminal/TUI.
Tui,
/// IdeA structured/custom CLI chat.
CustomCli,
/// Older caller that cannot identify its presentation.
Unknown,
}
/// Input for [`RestartCellAgentRuntime::execute`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RestartCellAgentRuntimeInput {
/// Owning project resolved by the driving adapter.
pub project: Project,
/// Exact leaf whose runtime is being restarted.
pub node_id: NodeId,
/// Agent expected to be bound to `node_id`.
pub agent_id: AgentId,
/// Informational UI presentation; never used as runtime truth.
pub presentation: CellAgentPresentation,
/// Optional layout identity supplied by clients that already have it.
pub layout_id: Option<LayoutId>,
}
/// Immediate acknowledgement for an accepted atomic cell restart.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RestartCellAgentRuntimeOutput {
/// Restart correlation id used by the existing restart event stream.
pub restart_id: String,
/// Validated agent identity.
pub agent_id: AgentId,
/// Validated hosting node.
pub node_id: NodeId,
/// Actual runtime family resolved from the live registry.
pub kind: LiveSessionKind,
/// Informational presentation echoed for caller correlation.
pub presentation: CellAgentPresentation,
/// Optional layout identity echoed for caller correlation.
pub layout_id: Option<LayoutId>,
}
/// Atomically validates a cell/runtime binding and schedules its replacement
/// through IdeA's existing restart coordinator.
pub struct RestartCellAgentRuntime {
live: Arc<LiveSessions>,
scheduler: Arc<dyn AgentSelfRestartScheduler>,
}
impl RestartCellAgentRuntime {
/// Builds the use case over the authoritative runtime registry and restart seam.
#[must_use]
pub fn new(live: Arc<LiveSessions>, scheduler: Arc<dyn AgentSelfRestartScheduler>) -> Self {
Self { live, scheduler }
}
/// Validates the exact live binding before the scheduler repeats that check
/// under its per-agent concurrency guard and accepts the detached restart.
pub fn execute(
&self,
input: RestartCellAgentRuntimeInput,
) -> Result<RestartCellAgentRuntimeOutput, AppError> {
let snapshots = self
.live
.live_agent_snapshots_for(input.project.id, &input.agent_id);
let snapshot = match snapshots.as_slice() {
[] => {
return Err(AppError::RestartRuntimeNotFound {
agent_id: input.agent_id,
});
}
[snapshot] => *snapshot,
_ => {
return Err(AppError::ConflictAgentVisibleElsewhere {
agent_id: input.agent_id,
});
}
};
if snapshot.node_id != input.node_id {
return Err(AppError::AgentNotBoundToCell {
agent_id: input.agent_id,
node_id: input.node_id,
});
}
let scheduled = self.scheduler.schedule_cell(
&input.project,
input.agent_id,
input.node_id,
Some("redémarrage demandé depuis la cellule".to_owned()),
)?;
Ok(RestartCellAgentRuntimeOutput {
restart_id: scheduled.restart_id,
agent_id: input.agent_id,
node_id: input.node_id,
kind: snapshot.kind,
presentation: input.presentation,
layout_id: input.layout_id,
})
}
}
/// Best-effort stopper for execution resources owned by one live agent turn.
///
/// Implementations must be idempotent: a missing, already-finished or already-stopped

View File

@ -10,8 +10,10 @@ mod live;
mod reconcile;
pub use actions::{
AttachLiveAgent, AttachLiveAgentInput, AttachLiveAgentOutput, StopAgentExecutionCascade,
StopAgentRuntime, StopLiveAgent, StopLiveAgentInput, StopLiveAgentOutput,
AttachLiveAgent, AttachLiveAgentInput, AttachLiveAgentOutput, CellAgentPresentation,
RestartCellAgentRuntime, RestartCellAgentRuntimeInput, RestartCellAgentRuntimeOutput,
StopAgentExecutionCascade, StopAgentRuntime, StopLiveAgent, StopLiveAgentInput,
StopLiveAgentOutput,
};
pub use live::{
GetLiveStateLean, LeanLiveEntry, LeanLiveState, UpdateLiveState, UpdateLiveStateInput,

View File

@ -11,9 +11,10 @@ use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use application::{
AttachLiveAgent, AttachLiveAgentInput, CloseTerminal, LiveRuntimeState, LiveSessionKind,
LiveSessions, StopAgentExecutionCascade, StopLiveAgent, StopLiveAgentInput, StructuredSessions,
TerminalSessions,
AgentRestartScheduled, AgentSelfRestartScheduler, AppError, AttachLiveAgent,
AttachLiveAgentInput, CellAgentPresentation, CloseTerminal, LiveRuntimeState, LiveSessionKind,
LiveSessions, RestartCellAgentRuntime, RestartCellAgentRuntimeInput, StopAgentExecutionCascade,
StopLiveAgent, StopLiveAgentInput, StructuredSessions, TerminalSessions,
};
use domain::ports::{
AgentSession, AgentSessionError, ExitStatus, OutputStream, PtyError, PtyHandle, PtyPort,
@ -21,7 +22,7 @@ use domain::ports::{
};
use domain::Project;
use domain::{
AgentId, NodeId, ProjectId, ProjectPath, PtySize, RemoteRef, SessionId, SessionKind,
AgentId, LayoutId, NodeId, ProjectId, ProjectPath, PtySize, RemoteRef, SessionId, SessionKind,
TerminalSession,
};
use uuid::Uuid;
@ -131,6 +132,35 @@ struct FakeCascade {
calls: Mutex<Vec<(ProjectId, AgentId)>>,
}
#[derive(Default)]
struct FakeRestartScheduler {
calls: Mutex<Vec<(ProjectId, AgentId, NodeId)>>,
}
impl AgentSelfRestartScheduler for FakeRestartScheduler {
fn schedule(
&self,
_project: &Project,
_agent: AgentId,
_reason: Option<String>,
) -> Result<AgentRestartScheduled, AppError> {
unreachable!("cell restart must use the cell-aware scheduler seam")
}
fn schedule_cell(
&self,
project: &Project,
agent: AgentId,
node: NodeId,
_reason: Option<String>,
) -> Result<AgentRestartScheduled, AppError> {
self.calls.lock().unwrap().push((project.id, agent, node));
Ok(AgentRestartScheduled {
restart_id: "restart-cell-test".to_owned(),
})
}
}
#[async_trait]
impl StopAgentExecutionCascade for FakeCascade {
async fn stop_agent_execution_children(&self, project: &Project, agent_id: AgentId) {
@ -148,6 +178,8 @@ struct Fixture {
pty: Arc<TerminalSessions>,
structured: Arc<StructuredSessions>,
pty_port: Arc<FakePty>,
restart: RestartCellAgentRuntime,
restart_scheduler: Arc<FakeRestartScheduler>,
}
fn fixture() -> Fixture {
@ -159,12 +191,32 @@ fn fixture() -> Fixture {
Arc::clone(&pty_port) as Arc<dyn PtyPort>,
Arc::clone(&pty),
));
let restart_scheduler = Arc::new(FakeRestartScheduler::default());
Fixture {
attach: AttachLiveAgent::new(Arc::clone(&live)),
stop: StopLiveAgent::new(Arc::clone(&live), close),
pty,
structured,
pty_port,
restart: RestartCellAgentRuntime::new(
Arc::clone(&live),
Arc::clone(&restart_scheduler) as Arc<dyn AgentSelfRestartScheduler>,
),
restart_scheduler,
}
}
fn restart_input(
agent_id: AgentId,
node_id: NodeId,
presentation: CellAgentPresentation,
) -> RestartCellAgentRuntimeInput {
RestartCellAgentRuntimeInput {
project: project(),
node_id,
agent_id,
presentation,
layout_id: Some(LayoutId::from_uuid(Uuid::from_u128(500))),
}
}
@ -315,6 +367,106 @@ fn attach_same_node_is_idempotent() {
assert_eq!(f.pty.len(), 1, "no extra session created");
}
// ---------------------------------------------------------------------------
// RestartCellAgentRuntime
// ---------------------------------------------------------------------------
#[test]
fn restart_cell_accepts_tui_and_preserves_exact_binding() {
let f = fixture();
let agent = aid(10);
let node = nid(100);
insert_pty(&f.pty, sid(1), agent, node);
let out = f
.restart
.execute(restart_input(agent, node, CellAgentPresentation::Tui))
.unwrap();
assert_eq!(out.restart_id, "restart-cell-test");
assert_eq!(out.agent_id, agent);
assert_eq!(out.node_id, node);
assert_eq!(out.kind, LiveSessionKind::Pty);
assert_eq!(out.presentation, CellAgentPresentation::Tui);
assert_eq!(
*f.restart_scheduler.calls.lock().unwrap(),
vec![(project().id, agent, node)]
);
}
#[test]
fn restart_cell_accepts_structured_custom_cli_and_headless_hints() {
for presentation in [
CellAgentPresentation::CustomCli,
CellAgentPresentation::Headless,
] {
let f = fixture();
let agent = aid(10);
let node = nid(100);
insert_structured(&f.structured, sid(2), agent, node);
let out = f
.restart
.execute(restart_input(agent, node, presentation))
.unwrap();
assert_eq!(out.kind, LiveSessionKind::Structured);
assert_eq!(out.presentation, presentation);
assert_eq!(f.restart_scheduler.calls.lock().unwrap().len(), 1);
}
}
#[test]
fn restart_cell_rejects_stale_agent_or_node_without_scheduling() {
let f = fixture();
let agent = aid(10);
insert_pty(&f.pty, sid(1), agent, nid(100));
let error = f
.restart
.execute(restart_input(
agent,
nid(999),
CellAgentPresentation::Unknown,
))
.unwrap_err();
assert_eq!(error.code(), "AGENT_NOT_BOUND_TO_CELL");
assert!(f.restart_scheduler.calls.lock().unwrap().is_empty());
}
#[test]
fn restart_cell_rejects_missing_runtime_without_scheduling() {
let f = fixture();
let error = f
.restart
.execute(restart_input(
aid(999),
nid(100),
CellAgentPresentation::Unknown,
))
.unwrap_err();
assert_eq!(error.code(), "RUNTIME_NOT_FOUND");
assert!(f.restart_scheduler.calls.lock().unwrap().is_empty());
}
#[test]
fn restart_cell_rejects_agent_visible_in_multiple_live_cells() {
let f = fixture();
let agent = aid(10);
insert_pty(&f.pty, sid(1), agent, nid(100));
insert_structured(&f.structured, sid(2), agent, nid(200));
let error = f
.restart
.execute(restart_input(agent, nid(100), CellAgentPresentation::Tui))
.unwrap_err();
assert_eq!(error.code(), "CONFLICT_AGENT_VISIBLE_ELSEWHERE");
assert!(f.restart_scheduler.calls.lock().unwrap().is_empty());
}
// ---------------------------------------------------------------------------
// StopLiveAgent
// ---------------------------------------------------------------------------