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

@ -12,13 +12,14 @@ use serde_json::Value;
use application::{
AgentBackgroundTaskState, AgentTicketState, AppError, AppExitWorkGuardDetail,
AppExitWorkGuardState, AttachLiveAgentOutput, BackgroundTaskKindLabel,
AppExitWorkGuardState, AttachLiveAgentOutput, BackgroundTaskKindLabel, CellAgentPresentation,
ConversationPreviewStatus, ConversationTurnWorkPreview, ConversationWorkSummary,
CreateProjectInput, CreateProjectOutput, ExecuteSlashCommandOutput, GitGraphOutput,
HealthInput, HealthReport, LayoutKind, ListProjectsOutput, ListSlashCommandsOutput,
LiveRuntimeState, LiveSessionKind, LiveSessionSnapshot, OpenProjectOutput, ProjectWorkState,
RestoreOpenProjectFailure, RestoreOpenProjectsOutput, SlashCommandEffect, StopLiveAgentOutput,
TicketWorkSource, TicketWorkStatus, TurnPage, TurnSource, TurnView,
RestartCellAgentRuntimeOutput, RestoreOpenProjectFailure, RestoreOpenProjectsOutput,
SlashCommandEffect, StopLiveAgentOutput, TicketWorkSource, TicketWorkStatus, TurnPage,
TurnSource, TurnView,
};
use domain::ports::{ReplyProgress, ReplyProgressKind, ReplyProgressSource, ReplyProgressStage};
use domain::{
@ -4611,6 +4612,98 @@ pub struct StopLiveAgentRequestDto {
pub reason: Option<String>,
}
/// Informational presentation supplied by the cell that requests a restart.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CellAgentPresentationDto {
/// Background/headless orchestration surface.
Headless,
/// Native interactive provider terminal.
Tui,
/// IdeA structured/custom CLI chat.
CustomCli,
/// Presentation cannot be determined by the caller.
Unknown,
}
impl From<CellAgentPresentationDto> for CellAgentPresentation {
fn from(value: CellAgentPresentationDto) -> Self {
match value {
CellAgentPresentationDto::Headless => Self::Headless,
CellAgentPresentationDto::Tui => Self::Tui,
CellAgentPresentationDto::CustomCli => Self::CustomCli,
CellAgentPresentationDto::Unknown => Self::Unknown,
}
}
}
impl From<CellAgentPresentation> for CellAgentPresentationDto {
fn from(value: CellAgentPresentation) -> Self {
match value {
CellAgentPresentation::Headless => Self::Headless,
CellAgentPresentation::Tui => Self::Tui,
CellAgentPresentation::CustomCli => Self::CustomCli,
CellAgentPresentation::Unknown => Self::Unknown,
}
}
}
/// Request for an atomic restart of the runtime bound to one agent cell.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RestartCellAgentRuntimeRequestDto {
/// Owning project registry id.
pub project_id: String,
/// Exact hosting layout leaf.
pub node_id: String,
/// Agent expected to be bound to the leaf.
pub agent_id: String,
/// Informational presentation; the backend resolves the real runtime.
#[serde(default = "unknown_cell_agent_presentation")]
pub presentation: CellAgentPresentationDto,
/// Optional named layout id when already known by the caller.
#[serde(default)]
pub layout_id: Option<String>,
}
fn unknown_cell_agent_presentation() -> CellAgentPresentationDto {
CellAgentPresentationDto::Unknown
}
/// Immediate acknowledgement for an accepted cell restart.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RestartCellAgentRuntimeResponseDto {
/// Correlation id used by `agentRestart*` events.
pub restart_id: String,
/// Stable acknowledgement state.
pub status: &'static str,
/// Validated agent id.
pub agent_id: String,
/// Validated node id.
pub node_id: String,
/// Actual live runtime family (`pty` or `structured`).
pub kind: LiveWorkSessionKindDto,
/// Informational presentation echoed to the caller.
pub presentation: CellAgentPresentationDto,
/// Optional layout id echoed to the caller.
pub layout_id: Option<String>,
}
impl From<RestartCellAgentRuntimeOutput> for RestartCellAgentRuntimeResponseDto {
fn from(out: RestartCellAgentRuntimeOutput) -> Self {
Self {
restart_id: out.restart_id,
status: "scheduled",
agent_id: out.agent_id.to_string(),
node_id: out.node_id.to_string(),
kind: out.kind.into(),
presentation: out.presentation.into(),
layout_id: out.layout_id.map(|id| id.to_string()),
}
}
}
/// Response DTO for `stop_live_agent`: the torn-down session's coordinates.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]

View File

@ -139,6 +139,7 @@ pub enum DomainEventDto {
agent_id: String,
restart_id: String,
phase: String,
code: String,
message: String,
},
/// A project was created.
@ -844,11 +845,13 @@ impl From<&DomainEvent> for DomainEventDto {
agent_id,
restart_id,
phase,
code,
message,
} => Self::AgentRestartFailed {
agent_id: agent_id.to_string(),
restart_id: restart_id.clone(),
phase: restart_phase_label(*phase).to_owned(),
code: code.clone(),
message: message.clone(),
},
DomainEvent::ProjectCreated { project_id } => Self::ProjectCreated {
@ -1427,11 +1430,13 @@ mod tests {
agent_id: id,
restart_id: "restart-288".to_owned(),
phase: domain::events::AgentRestartPhase::Launching,
code: "LAUNCH_FAILED".to_owned(),
message: "launch failed".to_owned(),
});
let failed = serde_json::to_value(failed).expect("serialisable");
assert_eq!(failed["type"], "agentRestartFailed");
assert_eq!(failed["phase"], "launching");
assert_eq!(failed["code"], "LAUNCH_FAILED");
assert_eq!(failed["message"], "launch failed");
}

View File

@ -51,21 +51,22 @@ use application::{
ReferenceProfiles, ReleaseManagedTemp, ReloadPlugin, ReloadPluginInput,
RemoveProjectFromRegistry, RenameDevice, RenameLayout, RenameSprint, ReorderSprints,
ResizeTerminal, ResolveAgentCapabilities, ResolveAgentPermissions,
ResolveAgentSystemPermissions, ResolveManagedTemp, ResolveMemoryLinks, RestoreOpenProjects,
RestoreOpenProjectsOutput, RestoreOpenWindows, RetryBackgroundTask, RetryOpenProjectRestore,
ReviewPluginPackage, RevokeAllDevices, RevokeDevice, RotateConversationLog, SaveChatDraft,
SaveEmbedderProfile, SaveModelServer, SaveOpenCodeProviderProfile, SaveOpenProjectRestoreOrder,
SaveProfile, ScheduledProjectTaskService, SessionLimitService, SetActiveLayout,
SetAgentMcpToolAllowed, SetPluginEnabled, SetProjectPluginEnabled, SlashCommandRegistry,
SnapshotOpenWindows, SnapshotRunningAgents, SnapshotRunningAgentsInput, SpawnBackgroundCommand,
StopAgentRuntime, StructuredRoutingMode, StructuredSessions, SuggestedThisSession,
SyncAgentWithTemplate, TerminalSessions, TouchDevice, UnassignSkillFromAgent,
UnassignTicketFromSprint, UninstallPlugin, UnlinkIssues, UpdateAgentContactable,
UpdateAgentContext, UpdateAgentEffort, UpdateAgentMcpToolPermissions, UpdateAgentPermissions,
UpdateAgentSystemPermissions, UpdateIssue, UpdateIssueCarnet, UpdateLiveState, UpdateMemory,
UpdateProjectContext, UpdateProjectMcpToolPermissions, UpdateProjectOrchestrator,
UpdateProjectPermissions, UpdateProjectSettings, UpdateProjectSystemPermissions, UpdateSkill,
UpdateTemplate, UpdateUserSettings, WakeSessionProvider, WriteMemory, WriteToTerminal,
ResolveAgentSystemPermissions, ResolveManagedTemp, ResolveMemoryLinks, RestartCellAgentRuntime,
RestoreOpenProjects, RestoreOpenProjectsOutput, RestoreOpenWindows, RetryBackgroundTask,
RetryOpenProjectRestore, ReviewPluginPackage, RevokeAllDevices, RevokeDevice,
RotateConversationLog, SaveChatDraft, SaveEmbedderProfile, SaveModelServer,
SaveOpenCodeProviderProfile, SaveOpenProjectRestoreOrder, SaveProfile,
ScheduledProjectTaskService, SessionLimitService, SetActiveLayout, SetAgentMcpToolAllowed,
SetPluginEnabled, SetProjectPluginEnabled, SlashCommandRegistry, SnapshotOpenWindows,
SnapshotRunningAgents, SnapshotRunningAgentsInput, SpawnBackgroundCommand, StopAgentRuntime,
StructuredRoutingMode, StructuredSessions, SuggestedThisSession, SyncAgentWithTemplate,
TerminalSessions, TouchDevice, UnassignSkillFromAgent, UnassignTicketFromSprint,
UninstallPlugin, UnlinkIssues, UpdateAgentContactable, UpdateAgentContext, UpdateAgentEffort,
UpdateAgentMcpToolPermissions, UpdateAgentPermissions, UpdateAgentSystemPermissions,
UpdateIssue, UpdateIssueCarnet, UpdateLiveState, UpdateMemory, UpdateProjectContext,
UpdateProjectMcpToolPermissions, UpdateProjectOrchestrator, UpdateProjectPermissions,
UpdateProjectSettings, UpdateProjectSystemPermissions, UpdateSkill, UpdateTemplate,
UpdateUserSettings, WakeSessionProvider, WriteMemory, WriteToTerminal,
AGENT_MEMORY_RECALL_BUDGET,
};
use async_trait::async_trait;
@ -1090,6 +1091,19 @@ struct AppAgentSelfRestarter {
rendezvous: Arc<application::RestartRendezvousCoordinator>,
}
async fn await_cell_restart_stop<F, T>(
agent_id: AgentId,
timeout: std::time::Duration,
stop: F,
) -> Result<T, AppError>
where
F: std::future::Future<Output = Result<T, AppError>>,
{
tokio::time::timeout(timeout, stop)
.await
.map_err(|_| AppError::RestartStopTimeout { agent_id })?
}
fn self_restart_launch_input(
context: ResumeContext,
agent_id: AgentId,
@ -1215,6 +1229,41 @@ mod self_restart_contract_tests {
assert!(!input.fresh_start);
}
#[test]
fn relaunch_preserves_native_tui_routing_and_cell_geometry() {
let project = Project::new(
ProjectId::from_uuid(Uuid::from_u128(317)),
"restart-tui",
domain::project::ProjectPath::new("/tmp/idea-restart-tui").unwrap(),
domain::remote::RemoteRef::local(),
0,
)
.unwrap();
let agent = AgentId::from_uuid(Uuid::from_u128(1));
let node = domain::NodeId::from_uuid(Uuid::from_u128(2));
let input = self_restart_launch_input(
ResumeContext {
project,
rows: 42,
cols: 132,
node_id: Some(node),
conversation_id: Some("conversation-tui".to_owned()),
require_structured: false,
},
agent,
None,
);
assert_eq!(input.node_id, Some(node));
assert_eq!((input.rows, input.cols), (42, 132));
assert_eq!(
input.terminal_interface,
Some(domain::DefaultAgentTerminalInterface::NativeTui)
);
assert!(!input.require_structured);
assert!(!input.fresh_start);
}
#[tokio::test]
async fn human_turn_ignores_old_terminal_and_accepts_replacement() {
let mailbox = Arc::new(InMemoryMailbox::new());
@ -1287,30 +1336,67 @@ mod self_restart_contract_tests {
assert_eq!(input.busy_state(key), domain::input::AgentBusyState::Idle);
assert_eq!(mailbox.pending(&key), 0);
}
#[tokio::test]
async fn cell_restart_stop_timeout_is_typed_and_never_reaches_the_next_step() {
let agent = AgentId::from_uuid(Uuid::from_u128(317));
let reached_after_stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
let result: Result<(), AppError> = await_cell_restart_stop(
agent,
std::time::Duration::from_millis(1),
std::future::pending(),
)
.await;
if result.is_ok() {
reached_after_stop.store(true, std::sync::atomic::Ordering::SeqCst);
}
assert_eq!(result.unwrap_err().code(), "STOP_TIMEOUT");
assert!(!reached_after_stop.load(std::sync::atomic::Ordering::SeqCst));
}
}
impl AgentSelfRestartScheduler for AppAgentSelfRestarter {
fn schedule(
impl AppAgentSelfRestarter {
fn schedule_restart(
&self,
project: &Project,
agent: AgentId,
requested_node: Option<domain::NodeId>,
reason: Option<String>,
) -> Result<AgentRestartScheduled, AppError> {
let key = domain::RuntimeAgentKey::new(project.id, agent);
let snapshots = self.live.live_agent_snapshots_for(project.id, &agent);
if snapshots.is_empty() {
return Err(AppError::Invalid(format!(
"requester agent {agent} is not live"
)));
return if requested_node.is_some() {
Err(AppError::RestartRuntimeNotFound { agent_id: agent })
} else {
Err(AppError::Invalid(format!(
"requester agent {agent} is not live"
)))
};
}
if let Some(node_id) = requested_node {
if snapshots.len() != 1 {
return Err(AppError::ConflictAgentVisibleElsewhere { agent_id: agent });
}
if snapshots[0].node_id != node_id {
return Err(AppError::AgentNotBoundToCell {
agent_id: agent,
node_id,
});
}
}
{
let mut active = self.active.lock().map_err(|_| {
AppError::Internal("agent restart registry lock poisoned".to_owned())
})?;
if !active.insert(key) {
return Err(AppError::Invalid(format!(
"a restart is already scheduled for agent {agent}"
)));
let message = format!("a restart is already scheduled for agent {agent}");
return if requested_node.is_some() {
Err(AppError::Conflict(message))
} else {
Err(AppError::Invalid(message))
};
}
}
@ -1346,29 +1432,36 @@ impl AgentSelfRestartScheduler for AppAgentSelfRestarter {
};
let context = contexts.lock().ok().and_then(|map| map.get(&key).cloned());
let snapshot = snapshots[0];
let context = context.unwrap_or(ResumeContext {
let mut context = context.unwrap_or(ResumeContext {
project: project.clone(),
rows: 24,
cols: 80,
node_id: None,
node_id: Some(snapshot.node_id),
conversation_id: live
.structured
.meta_for_session(&snapshot.session_id)
.and_then(|(_, _, _, conversation)| conversation),
require_structured: snapshot.kind == application::LiveSessionKind::Structured,
});
if let Some(node_id) = requested_node {
context.node_id = Some(node_id);
}
publish_phase(AgentRestartPhase::Stopping);
if !delegated {
input.preempt(key);
}
let stop_result = application::terminal::stop_live_agent_runtime_in_project(
let stop = application::terminal::stop_live_agent_runtime_in_project(
&project,
agent,
live.as_ref(),
close_terminal.as_ref(),
)
.await;
);
let stop_result = if requested_node.is_some() {
await_cell_restart_stop(agent, std::time::Duration::from_secs(10), stop).await
} else {
stop.await
};
publish_phase(AgentRestartPhase::ReleasingInput);
if !delegated {
@ -1382,10 +1475,19 @@ impl AgentSelfRestartScheduler for AppAgentSelfRestarter {
if delegated {
rendezvous.fail(key, &restart_id_task, error.to_string());
}
let code = match (&error, phase) {
(AppError::RestartStopTimeout { .. }, _) => "STOP_TIMEOUT",
(_, AgentRestartPhase::Stopping | AgentRestartPhase::ReleasingInput) => {
"STOP_FAILED"
}
(_, AgentRestartPhase::Launching) => "LAUNCH_FAILED",
(_, AgentRestartPhase::Resuming) => "RESUME_FAILED",
};
events.publish(DomainEvent::AgentRestartFailed {
agent_id: agent,
restart_id: restart_id_task.clone(),
phase,
code: code.to_owned(),
message: error.to_string(),
});
};
@ -1395,7 +1497,7 @@ impl AgentSelfRestartScheduler for AppAgentSelfRestarter {
}
};
match stop_result {
Ok(stopped) if !stopped.is_empty() => {}
Ok(stopped) if !stopped.is_empty() || requested_node.is_some() => {}
Ok(_) => {
fail(
AgentRestartPhase::Stopping,
@ -1541,6 +1643,27 @@ impl AgentSelfRestartScheduler for AppAgentSelfRestarter {
}
}
impl AgentSelfRestartScheduler for AppAgentSelfRestarter {
fn schedule(
&self,
project: &Project,
agent: AgentId,
reason: Option<String>,
) -> Result<AgentRestartScheduled, AppError> {
self.schedule_restart(project, agent, None, reason)
}
fn schedule_cell(
&self,
project: &Project,
agent: AgentId,
node: domain::NodeId,
reason: Option<String>,
) -> Result<AgentRestartScheduled, AppError> {
self.schedule_restart(project, agent, Some(node), reason)
}
}
/// Guard for a direct human turn sent to a structured agent session.
///
/// Direct chat adapters (`agent_send`, web `chat.send`) still drive the provider
@ -2111,6 +2234,8 @@ pub struct BackendCore {
pub attach_live_agent: Arc<AttachLiveAgent>,
/// Tears down an already-running agent's live session by agent id (Lot D).
pub stop_live_agent: Arc<StopAgentRuntime>,
/// Atomically restarts the runtime bound to an exact visible agent cell.
pub restart_cell_agent_runtime: Arc<RestartCellAgentRuntime>,
/// Best-effort inspection of a conversation (last topic + token indicator)
/// for the resume popup (T7). Optional/extensible: backed by a `Vec` of
/// [`domain::ports::SessionInspector`]s; an empty/missing match yields empty
@ -3976,6 +4101,10 @@ impl BackendCore {
active: Arc::new(Mutex::new(HashSet::new())),
rendezvous: Arc::clone(&restart_rendezvous),
}) as Arc<dyn AgentSelfRestartScheduler>;
let restart_cell_agent_runtime = Arc::new(RestartCellAgentRuntime::new(
Arc::clone(&live_sessions),
Arc::clone(&self_restart),
));
// Drain du scheduler (§21.5-b) : à chaque réveil tiré, `TokioScheduler` pousse une
// `ScheduledTask::ResumeAgent` ; on l'exécute via le service (relance + AgentResumed).
// Patron `sweep_stalled` : spawner detache (pas `tokio::spawn` — `build`
@ -4333,6 +4462,7 @@ impl BackendCore {
rotate_conversation_log,
attach_live_agent,
stop_live_agent,
restart_cell_agent_runtime,
inspect_conversation,
project_store,
read_user_settings,