feat(backend,frontend): lot utilisateur #310 #311 #312 #313 — horodatage conversation, stop agent robuste, préférence terminal par défaut, paramètres projet (QA verte)
- #310: horodatage de tous les messages et événements de conversation visibles — composant partagé EntryTimestamp, timestamps propagés dans le transcript chat, les annonces inter-agent et le viewer de conversation, normalisation côté domain/adapters (conversation_log, paginate). - #311: stop d'agent robuste pour PTY non monté, sessions headless et CLI custom — lifecycle/orchestrator durcis, ponts chat app-tauri/web-server alignés, arrêt fiable sans session orpheline. - #312: préférence globale d'interface terminal par défaut — nouveau store settings (domain/application/infrastructure + tests), DTO et commandes backend, adapter frontend userSettings, panneau TerminalSettings dans les paramètres globaux. - #313: Paramètres du projet — contexte de projet éditable et couleur de thème par projet (ProjectSettingsPanel + projectTheme), teinte des onglets projet, persistance via DTO projet. QA verte (GO QA sur feature/batch-310-311-312-313-chat-stop-prefs-theme) — vérifications Git: git diff --cached --check OK; staging borné à crates/ et frontend/ (74 fichiers, +2105/-531), commit unique de lot conforme à la convention des lots (précédents batch-151/158/159, batch-210/211/212) car les fichiers partagés (dto.rs, commands.rs, CustomAgentChatView) entrelacent les 4 tickets. fichiers .ideai/* (agents/test.md, chat-drafts.json, system-permissions.json, tickets/counter.json, tickets/index.json, tickets/308-313/), attachments/ et scripts/ hors périmètre et préservés en worktree ; aucun push. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@ -19,6 +19,7 @@ use domain::ports::{
|
||||
FileSystem, FsError, IdGenerator, LocalPath, MemoryQuery, MemoryRecall, PermissionStore,
|
||||
PreparedContext, ProfileStore, ProjectStore, PtyPort, RemotePath, SecretStore, SessionPlan,
|
||||
SkillStore, SpawnSpec, StructuredProviderLaunchPolicy, SystemPermissionStore,
|
||||
UserSettingsStore,
|
||||
};
|
||||
use domain::profile::{
|
||||
resolve_effort, EffortSelection, McpConfigStrategy, OpenCodeProviderConfig, StructuredAdapter,
|
||||
@ -27,12 +28,12 @@ use domain::profile::{
|
||||
use domain::sandbox::{compile_sandbox_plan, PathAccess, PathGrant, SandboxContext, SandboxPlan};
|
||||
use domain::{
|
||||
bound_handoff_summary, Agent, AgentId, AgentManifest, AgentOrigin, AgentProfile,
|
||||
ContextInjection, ConversationId, ConversationParty, DomainEvent, EffectivePermissions,
|
||||
Handoff, HandoffStore, ManagedTempKind, ManifestEntry, MarkdownDoc, MemoryIndexEntry,
|
||||
MemoryType, NetworkPolicy, NodeId, OrchestrationCapabilitySnapshot, PermissionProjector,
|
||||
PluginMcpServerSpec, ProfileId, Project, ProjectPath, ProjectedFile, ProjectionContext,
|
||||
ProjectorKey, ProviderSessionStore, PtySize, SessionId, SessionKind, SessionStatus, SkillKind,
|
||||
TerminalSession, HANDOFF_SUMMARY_MAX_CHARS,
|
||||
ContextInjection, ConversationId, ConversationParty, DefaultAgentTerminalInterface,
|
||||
DomainEvent, EffectivePermissions, Handoff, HandoffStore, ManagedTempKind, ManifestEntry,
|
||||
MarkdownDoc, MemoryIndexEntry, MemoryType, NetworkPolicy, NodeId,
|
||||
OrchestrationCapabilitySnapshot, PermissionProjector, PluginMcpServerSpec, ProfileId, Project,
|
||||
ProjectPath, ProjectedFile, ProjectionContext, ProjectorKey, ProviderSessionStore, PtySize,
|
||||
SessionId, SessionKind, SessionStatus, SkillKind, TerminalSession, HANDOFF_SUMMARY_MAX_CHARS,
|
||||
};
|
||||
|
||||
use domain::live_state::WorkStatus;
|
||||
@ -1123,6 +1124,7 @@ impl ChangeAgentProfile {
|
||||
mcp_runtime: None,
|
||||
allow_structured_alongside_pty: false,
|
||||
require_structured: false,
|
||||
terminal_interface: None,
|
||||
fresh_start: false,
|
||||
managed_temp_exposure: ManagedTempExposureRequest::default(),
|
||||
})
|
||||
@ -1310,6 +1312,8 @@ pub struct LaunchAgentInput {
|
||||
///
|
||||
/// Historical callers leave this `false`, preserving the PTY launch contract.
|
||||
pub require_structured: bool,
|
||||
/// Explicit human terminal interface. `None` lets the global preference apply.
|
||||
pub terminal_interface: Option<DefaultAgentTerminalInterface>,
|
||||
/// Cold restart request: ignore the cell's previous conversation id and create
|
||||
/// a new provider/CLI conversation for this activation.
|
||||
pub fresh_start: bool,
|
||||
@ -1803,6 +1807,8 @@ pub struct LaunchAgent {
|
||||
/// Optional for legacy tests/callers; runtime composition wires the shared
|
||||
/// project-plugin resolver used by the capability assignment use cases.
|
||||
plugin_mcp: Option<Arc<ProjectPluginResolver>>,
|
||||
/// Machine-local preference source, wired only on the human launcher.
|
||||
user_settings: Option<Arc<dyn UserSettingsStore>>,
|
||||
/// Explicit intent for structured profiles when structured ports are absent.
|
||||
structured_routing_mode: StructuredRoutingMode,
|
||||
}
|
||||
@ -1855,6 +1861,7 @@ impl LaunchAgent {
|
||||
managed_temp_allocator: None,
|
||||
managed_temp_releaser: None,
|
||||
plugin_mcp: None,
|
||||
user_settings: None,
|
||||
structured_routing_mode: StructuredRoutingMode::HumanPtyFallback,
|
||||
}
|
||||
}
|
||||
@ -1866,6 +1873,13 @@ impl LaunchAgent {
|
||||
self
|
||||
}
|
||||
|
||||
/// Wires machine-local preferences for human-facing launches.
|
||||
#[must_use]
|
||||
pub fn with_user_settings(mut self, settings: Arc<dyn UserSettingsStore>) -> Self {
|
||||
self.user_settings = Some(settings);
|
||||
self
|
||||
}
|
||||
|
||||
/// Replaces the default native-skill resolver with the shared effective
|
||||
/// resolver used by runtime context injection and `idea_skill_read`.
|
||||
#[must_use]
|
||||
@ -2279,7 +2293,16 @@ impl LaunchAgent {
|
||||
input.agent_id, profile.id
|
||||
)));
|
||||
}
|
||||
let preferred_interface = match input.terminal_interface {
|
||||
some @ Some(_) => some,
|
||||
None => match &self.user_settings {
|
||||
Some(settings) => settings.load().await?.default_agent_terminal_interface,
|
||||
None => None,
|
||||
},
|
||||
};
|
||||
let wants_structured = input.require_structured
|
||||
|| preferred_interface == Some(DefaultAgentTerminalInterface::IdeaCli)
|
||||
&& profile.structured_adapter.is_some()
|
||||
|| matches!(
|
||||
self.structured_routing_mode,
|
||||
StructuredRoutingMode::RequireStructured
|
||||
|
||||
@ -56,7 +56,7 @@ pub struct TurnView {
|
||||
/// Identifiant stable du tour (sert aussi d'ancre de pagination).
|
||||
pub id: TurnId,
|
||||
/// Horodatage (epoch millisecondes).
|
||||
pub at_ms: u64,
|
||||
pub at_ms: Option<u64>,
|
||||
/// Nature du tour (invite, réponse, activité outillée).
|
||||
pub role: TurnRole,
|
||||
/// Origine (humain ou agent délégant).
|
||||
|
||||
@ -35,6 +35,7 @@ pub mod plugin;
|
||||
pub mod project;
|
||||
pub mod project_plugin;
|
||||
pub mod remote;
|
||||
pub mod settings;
|
||||
pub mod skill;
|
||||
pub mod slash_command;
|
||||
pub mod sprints;
|
||||
@ -219,6 +220,9 @@ pub use project_plugin::{
|
||||
ProjectPluginSettingsView, SetProjectPluginEnabled,
|
||||
};
|
||||
pub use remote::{ConnectRemote, ConnectRemoteInput, ConnectRemoteOutput};
|
||||
pub use settings::{
|
||||
ReadProjectSettings, ReadUserSettings, UpdateProjectSettings, UpdateUserSettings,
|
||||
};
|
||||
pub use skill::{
|
||||
AgentCapability, AssignSkillToAgent, AssignSkillToAgentInput, AssignedSkillResolver,
|
||||
CreateSkill, CreateSkillInput, CreateSkillOutput, DeleteSkill, DeleteSkillInput, ListSkills,
|
||||
@ -275,7 +279,7 @@ pub use workstate::{
|
||||
ConversationTurnWorkPreview, ConversationWorkSummary, GetAppExitWorkGuardState,
|
||||
GetAppExitWorkGuardStateInput, GetLiveStateLean, GetProjectWorkState, GetProjectWorkStateInput,
|
||||
LeanLiveEntry, LeanLiveState, LiveWorkSession, ProjectWorkState, ReconcileLiveState,
|
||||
ReconcileLiveStateInput, StopAgentExecutionCascade, StopLiveAgent, StopLiveAgentInput,
|
||||
StopLiveAgentOutput, TicketWorkSource, TicketWorkStatus, UpdateLiveState, UpdateLiveStateInput,
|
||||
LIVE_STATE_MAX_ENTRIES, LIVE_STATE_TTL_MS,
|
||||
ReconcileLiveStateInput, StopAgentExecutionCascade, StopAgentRuntime, StopLiveAgent,
|
||||
StopLiveAgentInput, StopLiveAgentOutput, TicketWorkSource, TicketWorkStatus, UpdateLiveState,
|
||||
UpdateLiveStateInput, LIVE_STATE_MAX_ENTRIES, LIVE_STATE_TTL_MS,
|
||||
};
|
||||
|
||||
@ -2744,6 +2744,7 @@ impl OrchestratorService {
|
||||
mcp_runtime: None,
|
||||
allow_structured_alongside_pty: false,
|
||||
require_structured: false,
|
||||
terminal_interface: None,
|
||||
fresh_start: false,
|
||||
managed_temp_exposure: ManagedTempExposureRequest::default(),
|
||||
})
|
||||
@ -3638,6 +3639,7 @@ impl OrchestratorService {
|
||||
.and_then(|p| p.runtime_for(project, agent_id)),
|
||||
allow_structured_alongside_pty: false,
|
||||
require_structured: false,
|
||||
terminal_interface: None,
|
||||
fresh_start: false,
|
||||
managed_temp_exposure: ManagedTempExposureRequest::default(),
|
||||
})
|
||||
@ -3722,6 +3724,7 @@ impl OrchestratorService {
|
||||
.and_then(|p| p.runtime_for(project, agent_id)),
|
||||
allow_structured_alongside_pty: true,
|
||||
require_structured: true,
|
||||
terminal_interface: None,
|
||||
fresh_start: false,
|
||||
managed_temp_exposure: ManagedTempExposureRequest::default(),
|
||||
})
|
||||
|
||||
72
crates/application/src/settings.rs
Normal file
72
crates/application/src/settings.rs
Normal file
@ -0,0 +1,72 @@
|
||||
//! Read/update use cases for global and project settings.
|
||||
|
||||
use crate::AppError;
|
||||
use domain::{IdeaUserSettings, Project, ProjectSettings, ProjectSettingsStore, UserSettingsStore};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Reads global machine-local user settings.
|
||||
pub struct ReadUserSettings {
|
||||
store: Arc<dyn UserSettingsStore>,
|
||||
}
|
||||
impl ReadUserSettings {
|
||||
/// Builds the use case.
|
||||
#[must_use]
|
||||
pub fn new(store: Arc<dyn UserSettingsStore>) -> Self {
|
||||
Self { store }
|
||||
}
|
||||
/// Loads the current settings without writing defaults.
|
||||
pub async fn execute(&self) -> Result<IdeaUserSettings, AppError> {
|
||||
self.store.load().await.map_err(Into::into)
|
||||
}
|
||||
}
|
||||
/// Replaces global machine-local user settings.
|
||||
pub struct UpdateUserSettings {
|
||||
store: Arc<dyn UserSettingsStore>,
|
||||
}
|
||||
impl UpdateUserSettings {
|
||||
/// Builds the use case.
|
||||
#[must_use]
|
||||
pub fn new(store: Arc<dyn UserSettingsStore>) -> Self {
|
||||
Self { store }
|
||||
}
|
||||
/// Persists and returns the accepted document.
|
||||
pub async fn execute(&self, settings: IdeaUserSettings) -> Result<IdeaUserSettings, AppError> {
|
||||
self.store.save(&settings).await?;
|
||||
Ok(settings)
|
||||
}
|
||||
}
|
||||
/// Reads the settings owned by one project.
|
||||
pub struct ReadProjectSettings {
|
||||
store: Arc<dyn ProjectSettingsStore>,
|
||||
}
|
||||
impl ReadProjectSettings {
|
||||
/// Builds the use case.
|
||||
#[must_use]
|
||||
pub fn new(store: Arc<dyn ProjectSettingsStore>) -> Self {
|
||||
Self { store }
|
||||
}
|
||||
/// Loads settings for `project` without creating a missing file.
|
||||
pub async fn execute(&self, project: &Project) -> Result<ProjectSettings, AppError> {
|
||||
self.store.load(&project.root).await.map_err(Into::into)
|
||||
}
|
||||
}
|
||||
/// Replaces the settings owned by one project.
|
||||
pub struct UpdateProjectSettings {
|
||||
store: Arc<dyn ProjectSettingsStore>,
|
||||
}
|
||||
impl UpdateProjectSettings {
|
||||
/// Builds the use case.
|
||||
#[must_use]
|
||||
pub fn new(store: Arc<dyn ProjectSettingsStore>) -> Self {
|
||||
Self { store }
|
||||
}
|
||||
/// Persists and returns the accepted project settings.
|
||||
pub async fn execute(
|
||||
&self,
|
||||
project: &Project,
|
||||
settings: ProjectSettings,
|
||||
) -> Result<ProjectSettings, AppError> {
|
||||
self.store.save(&project.root, &settings).await?;
|
||||
Ok(settings)
|
||||
}
|
||||
}
|
||||
@ -290,42 +290,57 @@ pub async fn stop_live_agent_runtime_in_project(
|
||||
close: &CloseTerminal,
|
||||
) -> Result<Vec<StoppedAgentRuntime>, AppError> {
|
||||
let mut stopped = Vec::new();
|
||||
let mut first_error = None;
|
||||
let snapshots = live.live_agent_snapshots_for(project.id, &agent_id);
|
||||
|
||||
for snapshot in snapshots {
|
||||
live.mark_runtime_state(snapshot, LiveRuntimeState::Stopping);
|
||||
match snapshot.kind {
|
||||
let removed = match snapshot.kind {
|
||||
LiveSessionKind::Structured => {
|
||||
if let Some(removed) = live.structured.remove_runtime(&snapshot.session_id) {
|
||||
removed
|
||||
.session
|
||||
.shutdown()
|
||||
.await
|
||||
.map_err(|e| AppError::Process(e.to_string()))?;
|
||||
close
|
||||
if let Err(error) = removed.session.shutdown().await {
|
||||
first_error.get_or_insert_with(|| AppError::Process(error.to_string()));
|
||||
}
|
||||
if let Err(error) = close
|
||||
.release_managed_temp_handle(removed.managed_temp_handle)
|
||||
.await?;
|
||||
.await
|
||||
{
|
||||
first_error.get_or_insert(error);
|
||||
}
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
LiveSessionKind::Pty => {
|
||||
close
|
||||
if let Err(error) = close
|
||||
.execute(CloseTerminalInput {
|
||||
session_id: snapshot.session_id,
|
||||
})
|
||||
.await?;
|
||||
.await
|
||||
{
|
||||
first_error.get_or_insert(error);
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
||||
};
|
||||
if removed {
|
||||
live.mark_runtime_state(snapshot, LiveRuntimeState::Stopped);
|
||||
stopped.push(StoppedAgentRuntime {
|
||||
agent_id: snapshot.agent_id,
|
||||
session_id: snapshot.session_id,
|
||||
node_id: snapshot.node_id,
|
||||
kind: snapshot.kind,
|
||||
state: LiveRuntimeState::Stopped,
|
||||
});
|
||||
}
|
||||
live.mark_runtime_state(snapshot, LiveRuntimeState::Stopped);
|
||||
stopped.push(StoppedAgentRuntime {
|
||||
agent_id: snapshot.agent_id,
|
||||
session_id: snapshot.session_id,
|
||||
node_id: snapshot.node_id,
|
||||
kind: snapshot.kind,
|
||||
state: LiveRuntimeState::Stopped,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(stopped)
|
||||
match first_error {
|
||||
Some(error) => Err(error),
|
||||
None => Ok(stopped),
|
||||
}
|
||||
}
|
||||
|
||||
/// The platform default interactive shell.
|
||||
|
||||
@ -11,13 +11,13 @@ 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 crate::error::AppError;
|
||||
use crate::orchestrator::OrchestratorService;
|
||||
use crate::orchestrator::{LiveStateProvider, OrchestratorService};
|
||||
use crate::terminal::{
|
||||
stop_live_agent_runtime_in_project, CloseTerminal, LiveRuntimeState, LiveSessionKind,
|
||||
LiveSessions,
|
||||
stop_live_agent_runtime_in_project, CloseTerminal, LiveSessionKind, LiveSessions,
|
||||
};
|
||||
|
||||
/// Input for [`AttachLiveAgent::execute`].
|
||||
@ -100,35 +100,33 @@ impl AttachLiveAgent {
|
||||
}
|
||||
}
|
||||
|
||||
/// Input for [`StopLiveAgent::execute`].
|
||||
/// Input for [`StopAgentRuntime::execute`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct StopLiveAgentInput {
|
||||
/// The owning project (boundary/symmetry; the registries are global by agent).
|
||||
pub project: Project,
|
||||
/// The agent whose live session is stopped.
|
||||
pub agent_id: AgentId,
|
||||
/// Optional human-readable stop reason.
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
/// Output of [`StopLiveAgent::execute`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct StopLiveAgentOutput {
|
||||
/// The stopped agent.
|
||||
pub agent_id: AgentId,
|
||||
/// The id of the session that was torn down.
|
||||
pub session_id: SessionId,
|
||||
/// Last known layout node hosting the runtime view.
|
||||
pub node_id: NodeId,
|
||||
/// Runtime family that owned the session.
|
||||
pub kind: LiveSessionKind,
|
||||
/// Runtime lifecycle projection after the stop request.
|
||||
pub runtime_state: LiveRuntimeState,
|
||||
pub stopped: Vec<crate::terminal::StoppedAgentRuntime>,
|
||||
/// Whether no live runtime remained to stop.
|
||||
pub already_stopped: bool,
|
||||
}
|
||||
|
||||
/// Best-effort stopper for execution resources owned by one live agent turn.
|
||||
///
|
||||
/// Implementations must be idempotent: a missing, already-finished or already-stopped
|
||||
/// child resource is a successful no-op. Failures are deliberately not propagated by
|
||||
/// [`StopLiveAgent`], because the product contract is "stop the agent; cascade related
|
||||
/// [`StopAgentRuntime`], because the product contract is "stop the agent; cascade related
|
||||
/// work best-effort".
|
||||
#[async_trait]
|
||||
pub trait StopAgentExecutionCascade: Send + Sync {
|
||||
@ -143,16 +141,17 @@ pub trait StopAgentExecutionCascade: Send + Sync {
|
||||
/// provider conversation/context survives the stop. A PTY session has no finer
|
||||
/// turn boundary, so it is torn down through the existing [`CloseTerminal`]
|
||||
/// primitive (registry removal + process kill).
|
||||
pub struct StopLiveAgent {
|
||||
pub struct StopAgentRuntime {
|
||||
live: Arc<LiveSessions>,
|
||||
close: Arc<CloseTerminal>,
|
||||
input: Option<Arc<dyn InputMediator>>,
|
||||
waits: Option<Arc<OrchestratorService>>,
|
||||
cascade: Option<Arc<dyn StopAgentExecutionCascade>>,
|
||||
restart_rendezvous: Option<Arc<crate::RestartRendezvousCoordinator>>,
|
||||
live_state: Option<Arc<dyn LiveStateProvider>>,
|
||||
}
|
||||
|
||||
impl StopLiveAgent {
|
||||
impl StopAgentRuntime {
|
||||
/// Builds the use case from the live-session registry and the close primitive.
|
||||
#[must_use]
|
||||
pub fn new(live: Arc<LiveSessions>, close: Arc<CloseTerminal>) -> Self {
|
||||
@ -163,9 +162,17 @@ impl StopLiveAgent {
|
||||
waits: None,
|
||||
cascade: None,
|
||||
restart_rendezvous: None,
|
||||
live_state: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Wires the project-scoped live-state projection updated after a stop.
|
||||
#[must_use]
|
||||
pub fn with_live_state(mut self, live_state: Arc<dyn LiveStateProvider>) -> Self {
|
||||
self.live_state = Some(live_state);
|
||||
self
|
||||
}
|
||||
|
||||
/// Wires cancellation helpers used for user-driven stop cascades.
|
||||
///
|
||||
/// Stopping A while A waits on B should stop B too. The orchestrator service is
|
||||
@ -216,14 +223,32 @@ impl StopLiveAgent {
|
||||
if let Some(mediator) = &self.input {
|
||||
mediator.preempt(RuntimeAgentKey::new(input.project.id, input.agent_id));
|
||||
}
|
||||
if let Some(out) = self
|
||||
.cancel_structured_turn_in_project(&input.project, input.agent_id)
|
||||
.await?
|
||||
{
|
||||
return Ok(out);
|
||||
let stopped = stop_live_agent_runtime_in_project(
|
||||
&input.project,
|
||||
input.agent_id,
|
||||
&self.live,
|
||||
&self.close,
|
||||
)
|
||||
.await?;
|
||||
if let Some(provider) = &self.live_state {
|
||||
if let Some(update) = provider.live_state_for(&input.project.root) {
|
||||
let _ = update
|
||||
.execute(crate::UpdateLiveStateInput {
|
||||
agent_id: input.agent_id,
|
||||
ticket: None,
|
||||
intent: input.reason.unwrap_or_else(|| "arrêté".to_owned()),
|
||||
status: WorkStatus::Idle,
|
||||
progress: None,
|
||||
last_delegation: None,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
self.stop_one_in_project(&input.project, input.agent_id)
|
||||
.await
|
||||
Ok(StopLiveAgentOutput {
|
||||
agent_id: input.agent_id,
|
||||
already_stopped: stopped.is_empty(),
|
||||
stopped,
|
||||
})
|
||||
}
|
||||
|
||||
async fn stop_dependencies(
|
||||
@ -246,87 +271,11 @@ impl StopLiveAgent {
|
||||
if let Some(mediator) = &self.input {
|
||||
mediator.preempt(RuntimeAgentKey::new(project.id, dep));
|
||||
}
|
||||
if self
|
||||
.cancel_structured_turn_in_project(project, dep)
|
||||
.await?
|
||||
.is_none()
|
||||
{
|
||||
let _ = self.stop_one_in_project(project, dep).await;
|
||||
}
|
||||
let _ = stop_live_agent_runtime_in_project(project, dep, &self.live, &self.close).await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn cancel_structured_turn_in_project(
|
||||
&self,
|
||||
project: &Project,
|
||||
agent_id: AgentId,
|
||||
) -> Result<Option<StopLiveAgentOutput>, AppError> {
|
||||
let Some(snapshot) = self
|
||||
.live
|
||||
.live_agent_snapshots_for(project.id, &agent_id)
|
||||
.into_iter()
|
||||
.find(|snapshot| snapshot.kind == LiveSessionKind::Structured)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(session) = self
|
||||
.live
|
||||
.structured
|
||||
.session_for_agent_in_project(project.id, &agent_id)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.live
|
||||
.mark_runtime_state(snapshot, LiveRuntimeState::Stopping);
|
||||
session
|
||||
.cancel_current_turn()
|
||||
.await
|
||||
.map_err(|err| AppError::Process(err.to_string()))?;
|
||||
self.live
|
||||
.mark_runtime_state(snapshot, LiveRuntimeState::Stopped);
|
||||
Ok(Some(StopLiveAgentOutput {
|
||||
agent_id: snapshot.agent_id,
|
||||
session_id: snapshot.session_id,
|
||||
node_id: snapshot.node_id,
|
||||
kind: snapshot.kind,
|
||||
runtime_state: LiveRuntimeState::Stopped,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn stop_one_in_project(
|
||||
&self,
|
||||
project: &Project,
|
||||
agent_id: AgentId,
|
||||
) -> Result<StopLiveAgentOutput, AppError> {
|
||||
stop_live_agent_runtime_in_project(project, agent_id, &self.live, &self.close)
|
||||
.await?
|
||||
.into_iter()
|
||||
.next()
|
||||
.map(|stopped| StopLiveAgentOutput {
|
||||
agent_id: stopped.agent_id,
|
||||
session_id: stopped.session_id,
|
||||
node_id: stopped.node_id,
|
||||
kind: stopped.kind,
|
||||
runtime_state: stopped.state,
|
||||
})
|
||||
.or_else(|| {
|
||||
self.live
|
||||
.runtime_status_for(project.id, &agent_id)
|
||||
.filter(|status| {
|
||||
matches!(
|
||||
status.state,
|
||||
LiveRuntimeState::Stopping | LiveRuntimeState::Stopped
|
||||
)
|
||||
})
|
||||
.map(|status| StopLiveAgentOutput {
|
||||
agent_id: status.agent_id,
|
||||
session_id: status.session_id,
|
||||
node_id: status.node_id,
|
||||
kind: status.kind,
|
||||
runtime_state: status.state,
|
||||
})
|
||||
})
|
||||
.ok_or_else(|| AppError::NotFound(format!("running session for agent {agent_id}")))
|
||||
}
|
||||
}
|
||||
|
||||
/// Compatibility name kept for existing driving adapters.
|
||||
pub type StopLiveAgent = StopAgentRuntime;
|
||||
|
||||
@ -11,7 +11,7 @@ mod reconcile;
|
||||
|
||||
pub use actions::{
|
||||
AttachLiveAgent, AttachLiveAgentInput, AttachLiveAgentOutput, StopAgentExecutionCascade,
|
||||
StopLiveAgent, StopLiveAgentInput, StopLiveAgentOutput,
|
||||
StopAgentRuntime, StopLiveAgent, StopLiveAgentInput, StopLiveAgentOutput,
|
||||
};
|
||||
pub use live::{
|
||||
GetLiveStateLean, LeanLiveEntry, LeanLiveState, UpdateLiveState, UpdateLiveStateInput,
|
||||
@ -172,7 +172,7 @@ pub struct ConversationTurnWorkPreview {
|
||||
/// Origin of the turn (human operator or a delegating agent).
|
||||
pub source: TicketWorkSource,
|
||||
/// Timestamp (epoch milliseconds) of the turn.
|
||||
pub at_ms: u64,
|
||||
pub at_ms: Option<u64>,
|
||||
/// Bounded, whitespace-normalised excerpt of the turn text.
|
||||
pub text_preview: String,
|
||||
/// Character length of the **original** (un-truncated) turn text.
|
||||
|
||||
@ -1501,6 +1501,7 @@ fn launch_input_with_project(agent_id: AgentId, project: Project) -> LaunchAgent
|
||||
mcp_runtime: None,
|
||||
allow_structured_alongside_pty: false,
|
||||
require_structured: false,
|
||||
terminal_interface: None,
|
||||
fresh_start: false,
|
||||
managed_temp_exposure: ManagedTempExposureRequest::default(),
|
||||
}
|
||||
|
||||
@ -4585,8 +4585,8 @@ async fn p6b_user_ask_records_prompt_then_response_pair() {
|
||||
"response is sourced from the target (architect)"
|
||||
);
|
||||
// Clock stamp came from the injected Clock.
|
||||
assert_eq!(prompt.at_ms, 123);
|
||||
assert_eq!(response.at_ms, 123);
|
||||
assert_eq!(prompt.at_ms, Some(123));
|
||||
assert_eq!(response.at_ms, Some(123));
|
||||
}
|
||||
|
||||
/// Round-trip with an **agent** requester (A) resolves the `A↔B` conversation and the
|
||||
|
||||
@ -40,13 +40,16 @@ use domain::ports::{
|
||||
ContextInjectionPlan, DirEntry, EventBus, EventStream, ExitStatus, FileSystem, FsError,
|
||||
IdGenerator, MemoryError, MemoryQuery, MemoryRecall, OutputStream, PreparedContext,
|
||||
ProfileStore, ProjectStore, PtyError, PtyHandle, PtyPort, RemotePath, ReplyEvent, ReplyStream,
|
||||
RuntimeError, SessionPlan, SkillStore, SpawnSpec, StoreError,
|
||||
RuntimeError, SessionPlan, SkillStore, SpawnSpec, StoreError, UserSettingsStore,
|
||||
};
|
||||
use domain::profile::{AgentProfile, ContextInjection, StructuredAdapter};
|
||||
use domain::project::{Project, ProjectPath};
|
||||
use domain::remote::RemoteRef;
|
||||
use domain::skill::{Skill, SkillScope};
|
||||
use domain::{MemoryIndexEntry, NodeId, PtySize, SessionId, SessionKind, SkillId};
|
||||
use domain::{
|
||||
DefaultAgentTerminalInterface, IdeaUserSettings, MemoryIndexEntry, NodeId, PtySize, SessionId,
|
||||
SessionKind, SkillId,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
use application::{
|
||||
@ -772,6 +775,7 @@ fn launch_input(agent_id: AgentId) -> LaunchAgentInput {
|
||||
mcp_runtime: None,
|
||||
allow_structured_alongside_pty: false,
|
||||
require_structured: false,
|
||||
terminal_interface: None,
|
||||
fresh_start: false,
|
||||
managed_temp_exposure: ManagedTempExposureRequest::default(),
|
||||
}
|
||||
@ -858,10 +862,103 @@ fn launch_fixture_with_mode(
|
||||
}
|
||||
}
|
||||
|
||||
struct FixedUserSettings(IdeaUserSettings);
|
||||
|
||||
#[async_trait]
|
||||
impl UserSettingsStore for FixedUserSettings {
|
||||
async fn load(&self) -> Result<IdeaUserSettings, StoreError> {
|
||||
Ok(self.0.clone())
|
||||
}
|
||||
async fn save(&self, _settings: &IdeaUserSettings) -> Result<(), StoreError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct MutableUserSettings(Arc<Mutex<IdeaUserSettings>>);
|
||||
|
||||
#[async_trait]
|
||||
impl UserSettingsStore for MutableUserSettings {
|
||||
async fn load(&self) -> Result<IdeaUserSettings, StoreError> {
|
||||
Ok(self.0.lock().unwrap().clone())
|
||||
}
|
||||
async fn save(&self, settings: &IdeaUserSettings) -> Result<(), StoreError> {
|
||||
*self.0.lock().unwrap() = settings.clone();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn launch_fixture_with_preference(interface: DefaultAgentTerminalInterface) -> LaunchFixture {
|
||||
let mut fixture = launch_fixture_with_mode(
|
||||
structured_profile(pid(9)),
|
||||
FakeFactory::new(500, Some("engine-conv")),
|
||||
StructuredRoutingMode::HumanPtyFallback,
|
||||
);
|
||||
let launch = Arc::try_unwrap(fixture.launch)
|
||||
.ok()
|
||||
.expect("fixture owns its launcher")
|
||||
.with_user_settings(Arc::new(FixedUserSettings(IdeaUserSettings {
|
||||
default_agent_terminal_interface: Some(interface),
|
||||
})));
|
||||
fixture.launch = Arc::new(launch);
|
||||
fixture
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// 1. Routage LaunchAgent : chemin structuré
|
||||
// ===========================================================================
|
||||
|
||||
#[tokio::test]
|
||||
async fn global_idea_cli_preference_applies_to_a_new_human_launch() {
|
||||
let f = launch_fixture_with_preference(DefaultAgentTerminalInterface::IdeaCli);
|
||||
let out = f.launch.execute(launch_input(f.agent.id)).await.unwrap();
|
||||
assert!(out.structured.is_some());
|
||||
assert_eq!(f.factory.start_count(), 1);
|
||||
assert_eq!(f.pty.spawn_count(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_native_tui_overrides_the_global_idea_cli_preference() {
|
||||
let f = launch_fixture_with_preference(DefaultAgentTerminalInterface::IdeaCli);
|
||||
let mut input = launch_input(f.agent.id);
|
||||
input.terminal_interface = Some(DefaultAgentTerminalInterface::NativeTui);
|
||||
let out = f.launch.execute(input).await.unwrap();
|
||||
assert!(out.structured.is_none());
|
||||
assert_eq!(f.factory.start_count(), 0);
|
||||
assert_eq!(f.pty.spawn_count(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn changing_global_preference_does_not_replace_an_existing_terminal() {
|
||||
let mut fixture = launch_fixture_with_mode(
|
||||
structured_profile(pid(9)),
|
||||
FakeFactory::new(500, Some("engine-conv")),
|
||||
StructuredRoutingMode::HumanPtyFallback,
|
||||
);
|
||||
let settings = MutableUserSettings(Arc::new(Mutex::new(IdeaUserSettings::default())));
|
||||
let launch = Arc::try_unwrap(fixture.launch)
|
||||
.ok()
|
||||
.unwrap()
|
||||
.with_user_settings(Arc::new(settings.clone()));
|
||||
fixture.launch = Arc::new(launch);
|
||||
|
||||
let mut input = launch_input(fixture.agent.id);
|
||||
input.node_id = Some(nid(3));
|
||||
let first = fixture.launch.execute(input.clone()).await.unwrap();
|
||||
assert!(first.structured.is_none());
|
||||
settings
|
||||
.save(&IdeaUserSettings {
|
||||
default_agent_terminal_interface: Some(DefaultAgentTerminalInterface::IdeaCli),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let second = fixture.launch.execute(input).await.unwrap();
|
||||
assert_eq!(second.session.id, first.session.id);
|
||||
assert_eq!(fixture.pty.spawn_count(), 1);
|
||||
assert_eq!(fixture.factory.start_count(), 0);
|
||||
}
|
||||
|
||||
/// Profil structuré + factory câblée ⇒ `factory.start` appelé une fois, session
|
||||
/// enregistrée dans `StructuredSessions`, AUCUN `pty.spawn`, `AgentLaunched` publié,
|
||||
/// `output.structured = Some(descriptor)` avec les bons champs.
|
||||
|
||||
@ -330,15 +330,17 @@ async fn stop_pty_kills_and_removes_session() {
|
||||
.execute(StopLiveAgentInput {
|
||||
project: project(),
|
||||
agent_id: a,
|
||||
reason: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(out.agent_id, a);
|
||||
assert_eq!(out.session_id, sid(1));
|
||||
assert_eq!(out.node_id, nid(100));
|
||||
assert_eq!(out.kind, LiveSessionKind::Pty);
|
||||
assert_eq!(out.runtime_state, LiveRuntimeState::Stopped);
|
||||
assert!(!out.already_stopped);
|
||||
assert_eq!(out.stopped[0].session_id, sid(1));
|
||||
assert_eq!(out.stopped[0].node_id, nid(100));
|
||||
assert_eq!(out.stopped[0].kind, LiveSessionKind::Pty);
|
||||
assert_eq!(out.stopped[0].state, LiveRuntimeState::Stopped);
|
||||
// Delegated to the close primitive: process killed and registry emptied.
|
||||
assert_eq!(f.pty_port.kills(), vec![sid(1)]);
|
||||
assert!(f.pty.is_empty(), "live session removed from the registry");
|
||||
@ -346,7 +348,7 @@ async fn stop_pty_kills_and_removes_session() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_structured_cancels_turn_and_keeps_session() {
|
||||
async fn stop_structured_shuts_down_and_removes_session() {
|
||||
let f = fixture();
|
||||
let a = aid(10);
|
||||
let (shutdown_called, cancel_called) = insert_structured(&f.structured, sid(2), a, nid(100));
|
||||
@ -356,26 +358,24 @@ async fn stop_structured_cancels_turn_and_keeps_session() {
|
||||
.execute(StopLiveAgentInput {
|
||||
project: project(),
|
||||
agent_id: a,
|
||||
reason: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(out.session_id, sid(2));
|
||||
assert_eq!(out.kind, LiveSessionKind::Structured);
|
||||
assert_eq!(out.runtime_state, LiveRuntimeState::Stopped);
|
||||
assert_eq!(out.stopped[0].session_id, sid(2));
|
||||
assert_eq!(out.stopped[0].kind, LiveSessionKind::Structured);
|
||||
assert_eq!(out.stopped[0].state, LiveRuntimeState::Stopped);
|
||||
assert!(!cancel_called.load(Ordering::SeqCst));
|
||||
assert!(
|
||||
cancel_called.load(Ordering::SeqCst),
|
||||
"session.cancel_current_turn() was called"
|
||||
shutdown_called.load(Ordering::SeqCst),
|
||||
"session.shutdown() must be called"
|
||||
);
|
||||
assert!(
|
||||
!shutdown_called.load(Ordering::SeqCst),
|
||||
"session.shutdown() must not be called"
|
||||
);
|
||||
assert!(!f.structured.is_empty(), "live session is preserved");
|
||||
assert!(f.structured.is_empty(), "live session is removed");
|
||||
assert_eq!(
|
||||
f.structured
|
||||
.session_id_for_agent_in_project(project().id, &a),
|
||||
Some(sid(2))
|
||||
None
|
||||
);
|
||||
// No PTY was touched.
|
||||
assert!(f.pty_port.kills().is_empty());
|
||||
@ -395,21 +395,46 @@ async fn stop_structured_runs_execution_cascade_best_effort() {
|
||||
.execute(StopLiveAgentInput {
|
||||
project: project(),
|
||||
agent_id: a,
|
||||
reason: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(out.session_id, sid(2));
|
||||
assert_eq!(out.stopped[0].session_id, sid(2));
|
||||
assert_eq!(*cascade.calls.lock().unwrap(), vec![(project().id, a)]);
|
||||
assert!(
|
||||
cancel_called.load(Ordering::SeqCst),
|
||||
"session.cancel_current_turn() was called"
|
||||
!cancel_called.load(Ordering::SeqCst),
|
||||
"session.cancel_current_turn() is not the runtime stop primitive"
|
||||
);
|
||||
assert!(
|
||||
!shutdown_called.load(Ordering::SeqCst),
|
||||
"session.shutdown() must not be called"
|
||||
shutdown_called.load(Ordering::SeqCst),
|
||||
"session.shutdown() must be called"
|
||||
);
|
||||
assert!(!f.structured.is_empty(), "live session is preserved");
|
||||
assert!(f.structured.is_empty(), "live session is removed");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_removes_every_runtime_for_the_agent_across_registries() {
|
||||
let f = fixture();
|
||||
let agent = aid(10);
|
||||
insert_pty(&f.pty, sid(1), agent, nid(100));
|
||||
let (shutdown_called, _) = insert_structured(&f.structured, sid(2), agent, nid(200));
|
||||
|
||||
let out = f
|
||||
.stop
|
||||
.execute(StopLiveAgentInput {
|
||||
project: project(),
|
||||
agent_id: agent,
|
||||
reason: Some("user requested".to_owned()),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(out.stopped.len(), 2);
|
||||
assert!(f.pty.is_empty());
|
||||
assert!(f.structured.is_empty());
|
||||
assert_eq!(f.pty_port.kills(), vec![sid(1)]);
|
||||
assert!(shutdown_called.load(Ordering::SeqCst));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@ -423,6 +448,7 @@ async fn stop_pty_is_idempotent_after_success() {
|
||||
.execute(StopLiveAgentInput {
|
||||
project: project(),
|
||||
agent_id: a,
|
||||
reason: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@ -431,31 +457,31 @@ async fn stop_pty_is_idempotent_after_success() {
|
||||
.execute(StopLiveAgentInput {
|
||||
project: project(),
|
||||
agent_id: a,
|
||||
reason: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(first, second);
|
||||
assert_eq!(second.runtime_state, LiveRuntimeState::Stopped);
|
||||
assert!(!first.already_stopped);
|
||||
assert!(second.already_stopped);
|
||||
assert!(second.stopped.is_empty());
|
||||
assert_eq!(f.pty_port.kills(), vec![sid(1)], "kill is not repeated");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_unknown_agent_is_not_found() {
|
||||
async fn stop_unknown_agent_is_idempotent_success() {
|
||||
let f = fixture();
|
||||
|
||||
let err = f
|
||||
let out = f
|
||||
.stop
|
||||
.execute(StopLiveAgentInput {
|
||||
project: project(),
|
||||
agent_id: aid(999),
|
||||
reason: None,
|
||||
})
|
||||
.await
|
||||
.expect_err("absent agent ⇒ NOT_FOUND");
|
||||
|
||||
assert!(
|
||||
matches!(err, application::AppError::NotFound(_)),
|
||||
"got {err:?}"
|
||||
);
|
||||
.expect("absent agent is an idempotent success");
|
||||
assert!(out.already_stopped);
|
||||
assert!(out.stopped.is_empty());
|
||||
assert!(f.pty_port.kills().is_empty(), "nothing killed");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user