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:
@ -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,
|
||||
|
||||
Reference in New Issue
Block a user