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:
@ -26,11 +26,12 @@ use application::{
|
||||
ReadAgentContextInput, ReadConversationPageInput, ReadMcpToolPermissionsInput,
|
||||
ReadMemoryIndexInput, ReadProjectContextInput, RecallMemoryInput, RenameDeviceInput,
|
||||
RenameLayoutInput, ResolveAgentPermissionsInput, ResolveAgentSystemPermissionsInput,
|
||||
ResolveMemoryLinksInput, RevokeDeviceInput, RotateConversationLogInput, SaveChatDraftInput,
|
||||
SetActiveLayoutInput, SetAgentMcpToolAllowedInput, SlashCommandEffect,
|
||||
SnapshotRunningAgentsInput, StopLiveAgentInput, SyncAgentWithTemplateInput,
|
||||
UnassignSkillFromAgentInput, UpdateAgentContactableInput, UpdateAgentContextInput,
|
||||
UpdateAgentEffortInput, UpdateAgentMcpToolPermissionsInput, UpdateAgentPermissionsInput,
|
||||
ResolveMemoryLinksInput, RestartCellAgentRuntimeInput, RevokeDeviceInput,
|
||||
RotateConversationLogInput, SaveChatDraftInput, SetActiveLayoutInput,
|
||||
SetAgentMcpToolAllowedInput, SlashCommandEffect, SnapshotRunningAgentsInput,
|
||||
StopLiveAgentInput, SyncAgentWithTemplateInput, UnassignSkillFromAgentInput,
|
||||
UpdateAgentContactableInput, UpdateAgentContextInput, UpdateAgentEffortInput,
|
||||
UpdateAgentMcpToolPermissionsInput, UpdateAgentPermissionsInput,
|
||||
UpdateAgentSystemPermissionsInput, UpdateMemoryInput, UpdateProjectContextInput,
|
||||
UpdateProjectMcpToolPermissionsInput, UpdateProjectOrchestratorInput,
|
||||
UpdateProjectPermissionsInput, UpdateProjectSystemPermissionsInput, UpdateSkillInput,
|
||||
@ -73,6 +74,7 @@ use crate::dto::{
|
||||
RemoveProjectResponseDto, RenameLayoutRequestDto, ReplyChunk, ResizeTerminalRequestDto,
|
||||
ResolveAgentPermissionsRequestDto, ResolveAgentPermissionsResponseDto,
|
||||
ResolveAgentSystemPermissionsRequestDto, ResolvedAgentSystemPermissionsDto,
|
||||
RestartCellAgentRuntimeRequestDto, RestartCellAgentRuntimeResponseDto,
|
||||
RestoreOpenProjectsOutputDto, ResumableAgentListDto, RetryOpenProjectRestoreRequestDto,
|
||||
SaveChatDraftRequestDto, SaveEmbedderProfileRequestDto, SaveModelServerRequestDto,
|
||||
SaveOpenCodeProviderProfileRequestDto, SaveOpenProjectRestoreOrderRequestDto,
|
||||
@ -2268,6 +2270,32 @@ pub async fn stop_live_agent(
|
||||
.map_err(ErrorDto::from)
|
||||
}
|
||||
|
||||
/// Atomically restarts the runtime bound to an exact visible agent cell.
|
||||
///
|
||||
/// The presentation hint is retained for correlation only. Runtime selection,
|
||||
/// stop ordering and relaunch are owned by the backend restart coordinator.
|
||||
#[tauri::command]
|
||||
pub async fn restart_cell_agent_runtime(
|
||||
request: RestartCellAgentRuntimeRequestDto,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<RestartCellAgentRuntimeResponseDto, ErrorDto> {
|
||||
let project = resolve_project(&request.project_id, &state).await?;
|
||||
let output = state
|
||||
.restart_cell_agent_runtime
|
||||
.execute(RestartCellAgentRuntimeInput {
|
||||
project,
|
||||
node_id: parse_node_id(&request.node_id)?,
|
||||
agent_id: parse_agent_id(&request.agent_id)?,
|
||||
presentation: request.presentation.into(),
|
||||
layout_id: request
|
||||
.layout_id
|
||||
.as_deref()
|
||||
.map(parse_layout_id)
|
||||
.transpose()?,
|
||||
})?;
|
||||
Ok(output.into())
|
||||
}
|
||||
|
||||
/// `read_agent_context` — read an agent's Markdown context.
|
||||
///
|
||||
/// # Errors
|
||||
|
||||
@ -351,6 +351,7 @@ pub fn run() {
|
||||
commands::list_live_agents,
|
||||
commands::attach_live_agent,
|
||||
commands::stop_live_agent,
|
||||
commands::restart_cell_agent_runtime,
|
||||
commands::read_agent_context,
|
||||
commands::update_agent_context,
|
||||
commands::delete_agent,
|
||||
|
||||
@ -741,3 +741,53 @@ fn stop_live_agent_response_serialises_camelcase_with_kind() {
|
||||
assert_eq!(v["alreadyStopped"], false);
|
||||
assert!(v.get("session_id").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_cell_agent_request_deserialises_all_presentations() {
|
||||
use app_tauri_lib::dto::{CellAgentPresentationDto, RestartCellAgentRuntimeRequestDto};
|
||||
|
||||
for (wire, expected) in [
|
||||
("headless", CellAgentPresentationDto::Headless),
|
||||
("tui", CellAgentPresentationDto::Tui),
|
||||
("customCli", CellAgentPresentationDto::CustomCli),
|
||||
("unknown", CellAgentPresentationDto::Unknown),
|
||||
] {
|
||||
let raw = json!({
|
||||
"projectId": Uuid::from_u128(1).to_string(),
|
||||
"nodeId": Uuid::from_u128(2).to_string(),
|
||||
"agentId": Uuid::from_u128(3).to_string(),
|
||||
"presentation": wire,
|
||||
"layoutId": Uuid::from_u128(4).to_string()
|
||||
});
|
||||
let dto: RestartCellAgentRuntimeRequestDto = serde_json::from_value(raw).unwrap();
|
||||
assert_eq!(dto.presentation, expected);
|
||||
assert_eq!(dto.layout_id, Some(Uuid::from_u128(4).to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_cell_agent_response_uses_restart_event_correlation_contract() {
|
||||
use app_tauri_lib::dto::RestartCellAgentRuntimeResponseDto;
|
||||
use application::{CellAgentPresentation, LiveSessionKind, RestartCellAgentRuntimeOutput};
|
||||
|
||||
let agent = AgentId::from_uuid(Uuid::from_u128(11));
|
||||
let node = NodeId::from_uuid(Uuid::from_u128(12));
|
||||
let layout = domain::LayoutId::from_uuid(Uuid::from_u128(13));
|
||||
let dto = RestartCellAgentRuntimeResponseDto::from(RestartCellAgentRuntimeOutput {
|
||||
restart_id: "restart-317".to_owned(),
|
||||
agent_id: agent,
|
||||
node_id: node,
|
||||
kind: LiveSessionKind::Structured,
|
||||
presentation: CellAgentPresentation::CustomCli,
|
||||
layout_id: Some(layout),
|
||||
});
|
||||
|
||||
let value = serde_json::to_value(dto).unwrap();
|
||||
assert_eq!(value["restartId"], "restart-317");
|
||||
assert_eq!(value["status"], "scheduled");
|
||||
assert_eq!(value["agentId"], agent.to_string());
|
||||
assert_eq!(value["nodeId"], node.to_string());
|
||||
assert_eq!(value["kind"], "structured");
|
||||
assert_eq!(value["presentation"], "customCli");
|
||||
assert_eq!(value["layoutId"], layout.to_string());
|
||||
}
|
||||
|
||||
@ -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",
|
||||
|
||||
@ -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,
|
||||
};
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -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
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@ -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")]
|
||||
|
||||
@ -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");
|
||||
}
|
||||
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -82,6 +82,8 @@ pub enum DomainEvent {
|
||||
restart_id: String,
|
||||
/// Phase that failed.
|
||||
phase: AgentRestartPhase,
|
||||
/// Stable machine-readable failure code.
|
||||
code: String,
|
||||
/// Human-readable failure safe to expose in the UI.
|
||||
message: String,
|
||||
},
|
||||
|
||||
@ -100,6 +100,7 @@ use backend::dto::{
|
||||
RemoveOpenProjectRestoreEntryRequestDto, RemoveProjectRequestDto, RemoveProjectResponseDto,
|
||||
RenameLayoutRequestDto, ResolveAgentPermissionsRequestDto, ResolveAgentPermissionsResponseDto,
|
||||
ResolveAgentSystemPermissionsRequestDto, ResolvedAgentSystemPermissionsDto,
|
||||
RestartCellAgentRuntimeRequestDto, RestartCellAgentRuntimeResponseDto,
|
||||
RestoreOpenProjectsOutputDto, ResumableAgentListDto, RetryOpenProjectRestoreRequestDto,
|
||||
SaveEmbedderProfileRequestDto, SaveOpenCodeProviderProfileRequestDto,
|
||||
SaveOpenProjectRestoreOrderRequestDto, SaveProfileRequestDto, SetActiveLayoutRequestDto,
|
||||
@ -3442,6 +3443,9 @@ async fn invoke(
|
||||
"list_resumable_agents" => invoke_list_resumable_agents(&request.args, &state.app).await,
|
||||
"attach_live_agent" => invoke_attach_live_agent(&request.args, &state.app).await,
|
||||
"stop_live_agent" => invoke_stop_live_agent(&request.args, &state.app).await,
|
||||
"restart_cell_agent_runtime" => {
|
||||
invoke_restart_cell_agent_runtime(&request.args, &state.app).await
|
||||
}
|
||||
"create_agent" => invoke_create_agent(&request.args, &state.app).await,
|
||||
"change_agent_profile" => invoke_change_agent_profile(&request.args, &state.app).await,
|
||||
"read_agent_context" => invoke_read_agent_context(&request.args, &state.app).await,
|
||||
@ -4128,6 +4132,31 @@ async fn invoke_stop_live_agent(args: &Value, state: &BackendCore) -> Result<Val
|
||||
serde_json::to_value(output).map_err(serialization_error)
|
||||
}
|
||||
|
||||
async fn invoke_restart_cell_agent_runtime(
|
||||
args: &Value,
|
||||
state: &BackendCore,
|
||||
) -> Result<Value, ErrorDto> {
|
||||
let request =
|
||||
required_request::<RestartCellAgentRuntimeRequestDto>("restart_cell_agent_runtime", args)?;
|
||||
let project = resolve_project_readonly(&request.project_id, state).await?;
|
||||
let output = state
|
||||
.restart_cell_agent_runtime
|
||||
.execute(application::RestartCellAgentRuntimeInput {
|
||||
project,
|
||||
node_id: parse_node_id(&request.node_id)?,
|
||||
agent_id: parse_agent_id(&request.agent_id)?,
|
||||
presentation: request.presentation.into(),
|
||||
layout_id: request
|
||||
.layout_id
|
||||
.as_deref()
|
||||
.map(parse_layout_id)
|
||||
.transpose()?,
|
||||
})
|
||||
.map(RestartCellAgentRuntimeResponseDto::from)
|
||||
.map_err(ErrorDto::from)?;
|
||||
serde_json::to_value(output).map_err(serialization_error)
|
||||
}
|
||||
|
||||
async fn invoke_create_agent(args: &Value, state: &BackendCore) -> Result<Value, ErrorDto> {
|
||||
let request = required_request::<CreateAgentRequestDto>("create_agent", args)?;
|
||||
let project = resolve_project_readonly(&request.project_id, state).await?;
|
||||
@ -10748,6 +10777,7 @@ mod tests {
|
||||
"list_resumable_agents",
|
||||
"attach_live_agent",
|
||||
"stop_live_agent",
|
||||
"restart_cell_agent_runtime",
|
||||
"create_agent",
|
||||
"change_agent_profile",
|
||||
"read_agent_context",
|
||||
|
||||
Reference in New Issue
Block a user