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:
2026-09-10 21:26:16 +02:00
parent fc45594d9a
commit 402a60f213
74 changed files with 2105 additions and 531 deletions

View File

@ -344,6 +344,7 @@ fn progress_entity_key(progress: &ReplyProgressDto) -> Option<String> {
fn reply_chunk_bytes(chunk: &ReplyChunk) -> usize { fn reply_chunk_bytes(chunk: &ReplyChunk) -> usize {
match chunk { match chunk {
ReplyChunk::UserPrompt { ReplyChunk::UserPrompt {
at_ms: _,
text, text,
attachments, attachments,
attachment_refs, attachment_refs,
@ -360,8 +361,8 @@ fn reply_chunk_bytes(chunk: &ReplyChunk) -> usize {
}) })
.sum::<usize>() .sum::<usize>()
} }
ReplyChunk::TextDelta { text } => text.len(), ReplyChunk::TextDelta { text, .. } => text.len(),
ReplyChunk::ToolActivity { label } => label.len(), ReplyChunk::ToolActivity { label, .. } => label.len(),
ReplyChunk::Progress { progress } => { ReplyChunk::Progress { progress } => {
progress.label.len() progress.label.len()
+ progress.text.as_ref().map_or(0, String::len) + progress.text.as_ref().map_or(0, String::len)
@ -369,8 +370,8 @@ fn reply_chunk_bytes(chunk: &ReplyChunk) -> usize {
+ progress.native_event.as_ref().map_or(0, String::len) + progress.native_event.as_ref().map_or(0, String::len)
+ progress.tool_name.as_ref().map_or(0, String::len) + progress.tool_name.as_ref().map_or(0, String::len)
} }
ReplyChunk::Final { content } => content.len(), ReplyChunk::Final { content, .. } => content.len(),
ReplyChunk::Error { message } => message.len(), ReplyChunk::Error { message, .. } => message.len(),
} }
} }
@ -386,40 +387,57 @@ fn reply_chunk_bytes(chunk: &ReplyChunk) -> usize {
/// too. Every content-bearing event still maps to exactly one chunk. /// too. Every content-bearing event still maps to exactly one chunk.
#[must_use] #[must_use]
pub fn chunk_from_event(event: ReplyEvent) -> Option<ReplyChunk> { pub fn chunk_from_event(event: ReplyEvent) -> Option<ReplyChunk> {
chunk_from_event_at(event, None)
}
/// Maps a domain reply event while preserving the backend acceptance time.
#[must_use]
pub fn chunk_from_event_at(event: ReplyEvent, at_ms: Option<u64>) -> Option<ReplyChunk> {
match event { match event {
ReplyEvent::Progress { progress } => Some(ReplyChunk::Progress { ReplyEvent::Progress { progress } => {
progress: progress.into(), let mut progress: ReplyProgressDto = progress.into();
}), progress.occurred_at_ms = at_ms;
ReplyEvent::TextDelta { text } => Some(ReplyChunk::TextDelta { text }), Some(ReplyChunk::Progress { progress })
}
ReplyEvent::TextDelta { text } => Some(ReplyChunk::TextDelta { text, at_ms }),
ReplyEvent::ToolActivity { label } => Some(ReplyChunk::Progress { ReplyEvent::ToolActivity { label } => Some(ReplyChunk::Progress {
progress: ReplyProgress::new( progress: {
let mut progress: ReplyProgressDto = ReplyProgress::new(
ReplyProgressSource::ProviderNative, ReplyProgressSource::ProviderNative,
ReplyProgressKind::Tool, ReplyProgressKind::Tool,
ReplyProgressStage::Info, ReplyProgressStage::Info,
label.clone(), label.clone(),
) )
.with_tool_name(label) .with_tool_name(label)
.into(), .into();
progress.occurred_at_ms = at_ms;
progress
},
}), }),
ReplyEvent::Error { message } => Some(ReplyChunk::Error { message }), ReplyEvent::Error { message } => Some(ReplyChunk::Error { message, at_ms }),
ReplyEvent::Final { content } => { ReplyEvent::Final { content } => {
if content.trim().is_empty() { if content.trim().is_empty() {
Some(ReplyChunk::Error { Some(ReplyChunk::Error {
message: "Réponse vide du modèle.".to_owned(), message: "Réponse vide du modèle.".to_owned(),
at_ms,
}) })
} else { } else {
Some(ReplyChunk::Final { content }) Some(ReplyChunk::Final { content, at_ms })
} }
} }
ReplyEvent::Announcement { text } => Some(ReplyChunk::Progress { ReplyEvent::Announcement { text } => Some(ReplyChunk::Progress {
progress: ReplyProgress::new( progress: {
let mut progress: ReplyProgressDto = ReplyProgress::new(
ReplyProgressSource::ProviderNative, ReplyProgressSource::ProviderNative,
ReplyProgressKind::Message, ReplyProgressKind::Message,
ReplyProgressStage::Delta, ReplyProgressStage::Delta,
"message intermédiaire", "message intermédiaire",
) )
.with_text(text) .with_text(text)
.into(), .into();
progress.occurred_at_ms = at_ms;
progress
},
}), }),
ReplyEvent::Heartbeat => None, ReplyEvent::Heartbeat => None,
ReplyEvent::RateLimited { .. } => None, ReplyEvent::RateLimited { .. } => None,
@ -432,5 +450,20 @@ pub fn chunk_from_event(event: ReplyEvent) -> Option<ReplyChunk> {
pub fn unfinished_turn_chunk() -> ReplyChunk { pub fn unfinished_turn_chunk() -> ReplyChunk {
ReplyChunk::Error { ReplyChunk::Error {
message: MODEL_RESPONSE_NOT_FINALIZED_MESSAGE.to_owned(), message: MODEL_RESPONSE_NOT_FINALIZED_MESSAGE.to_owned(),
at_ms: None,
} }
} }
/// Assigns an acceptance timestamp to a transport-created chunk.
#[must_use]
pub fn with_chunk_timestamp(mut chunk: ReplyChunk, at_ms: Option<u64>) -> ReplyChunk {
match &mut chunk {
ReplyChunk::UserPrompt { at_ms: value, .. }
| ReplyChunk::TextDelta { at_ms: value, .. }
| ReplyChunk::ToolActivity { at_ms: value, .. }
| ReplyChunk::Final { at_ms: value, .. }
| ReplyChunk::Error { at_ms: value, .. } => *value = at_ms,
ReplyChunk::Progress { progress } => progress.occurred_at_ms = at_ms,
}
chunk
}

View File

@ -66,7 +66,7 @@ use crate::dto::{
MemoryIndexDto, MemoryLinksDto, MemoryListDto, ModelServerConfigDto, ModelServerConfigListDto, MemoryIndexDto, MemoryLinksDto, MemoryListDto, ModelServerConfigDto, ModelServerConfigListDto,
OpenCodeProviderListDto, OpenProjectRestoreStateDto, OpenTerminalRequestDto, OpenCodeProviderListDto, OpenProjectRestoreStateDto, OpenTerminalRequestDto,
PreviewModelServerCommandDto, ProfileDto, ProfileListDto, ProfileModelCatalogDto, ProjectDto, PreviewModelServerCommandDto, ProfileDto, ProfileListDto, ProfileModelCatalogDto, ProjectDto,
ProjectListDto, ProjectMcpToolPermissionsDto, ProjectPermissionsDto, ProjectListDto, ProjectMcpToolPermissionsDto, ProjectPermissionsDto, ProjectSettingsDto,
ProjectSystemPermissionsDto, ProjectWorkStateDto, ReadAgentContextResponseDto, ProjectSystemPermissionsDto, ProjectWorkStateDto, ReadAgentContextResponseDto,
ReadChatDraftResponseDto, ReadConversationPageRequestDto, ReattachChatDto, ReattachResultDto, ReadChatDraftResponseDto, ReadConversationPageRequestDto, ReattachChatDto, ReattachResultDto,
RecallMemoryRequestDto, RemoveOpenProjectRestoreEntryRequestDto, RemoveProjectRequestDto, RecallMemoryRequestDto, RemoveOpenProjectRestoreEntryRequestDto, RemoveProjectRequestDto,
@ -86,8 +86,8 @@ use crate::dto::{
UpdateAgentSystemPermissionsRequestDto, UpdateMemoryRequestDto, UpdateProjectContextRequestDto, UpdateAgentSystemPermissionsRequestDto, UpdateMemoryRequestDto, UpdateProjectContextRequestDto,
UpdateProjectMcpToolPermissionsRequestDto, UpdateProjectOrchestratorRequestDto, UpdateProjectMcpToolPermissionsRequestDto, UpdateProjectOrchestratorRequestDto,
UpdateProjectOrchestratorResponseDto, UpdateProjectPermissionsRequestDto, UpdateProjectOrchestratorResponseDto, UpdateProjectPermissionsRequestDto,
UpdateProjectSystemPermissionsRequestDto, UpdateSkillRequestDto, UpdateTemplateRequestDto, UpdateProjectSettingsRequestDto, UpdateProjectSystemPermissionsRequestDto,
WriteTerminalRequestDto, UpdateSkillRequestDto, UpdateTemplateRequestDto, UserSettingsDto, WriteTerminalRequestDto,
}; };
use crate::embedded_server::{ use crate::embedded_server::{
EmbeddedServerStatusDto, ServerExposurePreviewDto, ServerExposureSettingsDto, EmbeddedServerStatusDto, ServerExposurePreviewDto, ServerExposureSettingsDto,
@ -815,6 +815,66 @@ pub async fn update_project_context(
.map_err(ErrorDto::from) .map_err(ErrorDto::from)
} }
/// Reads global machine-local IdeA preferences.
#[tauri::command]
pub async fn read_user_settings(state: State<'_, AppState>) -> Result<UserSettingsDto, ErrorDto> {
state
.read_user_settings
.execute()
.await
.map(Into::into)
.map_err(Into::into)
}
/// Replaces global machine-local IdeA preferences.
#[tauri::command]
pub async fn update_user_settings(
request: UserSettingsDto,
state: State<'_, AppState>,
) -> Result<UserSettingsDto, ErrorDto> {
state
.update_user_settings
.execute(request.into())
.await
.map(Into::into)
.map_err(Into::into)
}
/// Reads project-owned settings without creating a legacy-missing file.
#[tauri::command]
pub async fn read_project_settings(
project_id: String,
state: State<'_, AppState>,
) -> Result<ProjectSettingsDto, ErrorDto> {
let project = resolve_project(&project_id, &state).await?;
state
.read_project_settings
.execute(&project)
.await
.map(Into::into)
.map_err(Into::into)
}
/// Validates and replaces project-owned settings.
#[tauri::command]
pub async fn update_project_settings(
request: UpdateProjectSettingsRequestDto,
state: State<'_, AppState>,
) -> Result<ProjectSettingsDto, ErrorDto> {
let project = resolve_project(&request.project_id, &state).await?;
let theme_color = request
.theme_color
.map(domain::ThemeColor::new)
.transpose()
.map_err(|message| ErrorDto::from(AppError::Invalid(message)))?;
state
.update_project_settings
.execute(&project, domain::ProjectSettings { theme_color })
.await
.map(Into::into)
.map_err(Into::into)
}
/// `get_project_permissions` — read `.ideai/permissions.json`. /// `get_project_permissions` — read `.ideai/permissions.json`.
/// ///
/// # Errors /// # Errors
@ -2198,7 +2258,11 @@ pub async fn stop_live_agent(
} }
state state
.stop_live_agent .stop_live_agent
.execute(StopLiveAgentInput { project, agent_id }) .execute(StopLiveAgentInput {
project,
agent_id,
reason: request.reason,
})
.await .await
.map(StopLiveAgentResponseDto::from) .map(StopLiveAgentResponseDto::from)
.map_err(ErrorDto::from) .map_err(ErrorDto::from)
@ -2372,6 +2436,10 @@ pub async fn launch_agent(
mcp_runtime, mcp_runtime,
allow_structured_alongside_pty: false, allow_structured_alongside_pty: false,
require_structured: request.cell_kind == Some(CellKind::Chat), require_structured: request.cell_kind == Some(CellKind::Chat),
terminal_interface: request.cell_kind.map(|kind| match kind {
CellKind::Pty => domain::DefaultAgentTerminalInterface::NativeTui,
CellKind::Chat => domain::DefaultAgentTerminalInterface::IdeaCli,
}),
fresh_start: request.fresh_start, fresh_start: request.fresh_start,
managed_temp_exposure: application::ManagedTempExposureRequest::default(), managed_temp_exposure: application::ManagedTempExposureRequest::default(),
}) })
@ -2781,6 +2849,7 @@ pub async fn agent_send(
let _ = state.chat_bridge.send_output( let _ = state.chat_bridge.send_output(
&sid, &sid,
ReplyChunk::UserPrompt { ReplyChunk::UserPrompt {
at_ms: u64::try_from(state.clock.now_millis()).ok(),
text: prompt.clone(), text: prompt.clone(),
attachments: attachment_labels, attachments: attachment_labels,
attachment_refs, attachment_refs,
@ -2793,6 +2862,7 @@ pub async fn agent_send(
// still running. // still running.
let (tap_tx, tap_rx) = std::sync::mpsc::channel(); let (tap_tx, tap_rx) = std::sync::mpsc::channel();
let tap_bridge = std::sync::Arc::clone(&state.chat_bridge); let tap_bridge = std::sync::Arc::clone(&state.chat_bridge);
let tap_clock = std::sync::Arc::clone(&state.clock);
let tap_sid = sid; let tap_sid = sid;
let tap_turn_guard = turn_guard.as_ref().map(|guard| guard.liveness_handle()); let tap_turn_guard = turn_guard.as_ref().map(|guard| guard.liveness_handle());
let tap_pump = std::thread::spawn(move || { let tap_pump = std::thread::spawn(move || {
@ -2803,7 +2873,9 @@ pub async fn agent_send(
guard.mark_alive(); guard.mark_alive();
} }
} }
let Some(chunk) = crate::chat::chunk_from_event(event) else { let Some(chunk) =
crate::chat::chunk_from_event_at(event, u64::try_from(tap_clock.now_millis()).ok())
else {
continue; continue;
}; };
if matches!(chunk, ReplyChunk::Final { .. } | ReplyChunk::Error { .. }) { if matches!(chunk, ReplyChunk::Final { .. } | ReplyChunk::Error { .. }) {
@ -2842,6 +2914,7 @@ pub async fn agent_send(
// `Final` event (or stream end / superseded channel), then detaches *only its // `Final` event (or stream end / superseded channel), then detaches *only its
// own* generation so a concurrent re-attach is never torn down. // own* generation so a concurrent re-attach is never torn down.
let bridge = std::sync::Arc::clone(&state.chat_bridge); let bridge = std::sync::Arc::clone(&state.chat_bridge);
let clock = std::sync::Arc::clone(&state.clock);
// Level-1 session-limit tap (§21, niveau 1 — structuré). Resolve the agent, host // Level-1 session-limit tap (§21, niveau 1 — structuré). Resolve the agent, host
// cell and engine conversation once from the live registry; a `RateLimited` turn // cell and engine conversation once from the live registry; a `RateLimited` turn
// event then feeds the service (détecter→planifier). Without a conversation id the // event then feeds the service (détecter→planifier). Without a conversation id the
@ -2879,7 +2952,10 @@ pub async fn agent_send(
let _ = bridge.send_output_settled( let _ = bridge.send_output_settled(
&sid, &sid,
&mut settler, &mut settler,
ReplyChunk::Error { message }, ReplyChunk::Error {
message,
at_ms: u64::try_from(clock.now_millis()).ok(),
},
); );
break 'logical_turn; break 'logical_turn;
} }
@ -2920,7 +2996,9 @@ pub async fn agent_send(
} }
// Heartbeats carry no chat content (readiness/heartbeat lot 1) ⇒ no wire // Heartbeats carry no chat content (readiness/heartbeat lot 1) ⇒ no wire
// chunk; skip them while still draining so the turn runs to its `Final`. // chunk; skip them while still draining so the turn runs to its `Final`.
let Some(chunk) = crate::chat::chunk_from_event(event) else { let Some(chunk) =
crate::chat::chunk_from_event_at(event, u64::try_from(clock.now_millis()).ok())
else {
continue; continue;
}; };
if matches!(chunk, ReplyChunk::Final { .. } | ReplyChunk::Error { .. }) { if matches!(chunk, ReplyChunk::Final { .. } | ReplyChunk::Error { .. }) {
@ -2946,7 +3024,10 @@ pub async fn agent_send(
let _ = bridge.send_output_settled( let _ = bridge.send_output_settled(
&sid, &sid,
&mut settler, &mut settler,
ReplyChunk::Error { message }, ReplyChunk::Error {
message,
at_ms: u64::try_from(clock.now_millis()).ok(),
},
); );
} }
backend::StructuredHumanTurnTransition::Cancelled => { backend::StructuredHumanTurnTransition::Cancelled => {
@ -2971,6 +3052,7 @@ pub async fn agent_send(
ReplyChunk::Error { ReplyChunk::Error {
message: "Le redémarrage n'a pas fourni de session de remplacement." message: "Le redémarrage n'a pas fourni de session de remplacement."
.to_owned(), .to_owned(),
at_ms: u64::try_from(clock.now_millis()).ok(),
}, },
); );
break; break;
@ -2991,6 +3073,7 @@ pub async fn agent_send(
&mut settler, &mut settler,
ReplyChunk::Error { ReplyChunk::Error {
message: error.to_string(), message: error.to_string(),
at_ms: u64::try_from(clock.now_millis()).ok(),
}, },
); );
break; break;
@ -2998,7 +3081,10 @@ pub async fn agent_send(
} }
} }
if !terminal_visible { if !terminal_visible {
let chunk = crate::chat::unfinished_turn_chunk(); let chunk = crate::chat::with_chunk_timestamp(
crate::chat::unfinished_turn_chunk(),
u64::try_from(clock.now_millis()).ok(),
);
let _ = bridge.send_output_settled(&sid, &mut settler, chunk); let _ = bridge.send_output_settled(&sid, &mut settler, chunk);
} }
if let Some(guard) = &turn_guard { if let Some(guard) = &turn_guard {
@ -3421,7 +3507,11 @@ pub async fn cancel_agent_chat(
} }
state state
.stop_live_agent .stop_live_agent
.execute(StopLiveAgentInput { project, agent_id }) .execute(StopLiveAgentInput {
project,
agent_id,
reason: Some("fermeture de la session chat".to_owned()),
})
.await .await
.map(|_| ()) .map(|_| ())
.map_err(ErrorDto::from) .map_err(ErrorDto::from)

View File

@ -263,6 +263,10 @@ pub fn run() {
commands::list_projects, commands::list_projects,
commands::read_project_context, commands::read_project_context,
commands::update_project_context, commands::update_project_context,
commands::read_user_settings,
commands::update_user_settings,
commands::read_project_settings,
commands::update_project_settings,
commands::get_project_permissions, commands::get_project_permissions,
commands::update_project_permissions, commands::update_project_permissions,
commands::update_agent_permissions, commands::update_agent_permissions,

View File

@ -48,17 +48,22 @@ fn sid() -> SessionId {
} }
fn delta(s: &str) -> ReplyChunk { fn delta(s: &str) -> ReplyChunk {
ReplyChunk::TextDelta { text: s.to_owned() } ReplyChunk::TextDelta {
at_ms: None,
text: s.to_owned(),
}
} }
fn final_chunk(s: &str) -> ReplyChunk { fn final_chunk(s: &str) -> ReplyChunk {
ReplyChunk::Final { ReplyChunk::Final {
at_ms: None,
content: s.to_owned(), content: s.to_owned(),
} }
} }
fn error_chunk(s: &str) -> ReplyChunk { fn error_chunk(s: &str) -> ReplyChunk {
ReplyChunk::Error { ReplyChunk::Error {
at_ms: None,
message: s.to_owned(), message: s.to_owned(),
} }
} }
@ -70,6 +75,7 @@ fn progress_chunk(
) -> ReplyChunk { ) -> ReplyChunk {
ReplyChunk::Progress { ReplyChunk::Progress {
progress: ReplyProgressDto { progress: ReplyProgressDto {
occurred_at_ms: None,
progress_id: None, progress_id: None,
source: ReplyProgressSourceDto::ProviderNative, source: ReplyProgressSourceDto::ProviderNative,
kind, kind,
@ -91,6 +97,7 @@ fn progress_chunk_with_id(
) -> ReplyChunk { ) -> ReplyChunk {
ReplyChunk::Progress { ReplyChunk::Progress {
progress: ReplyProgressDto { progress: ReplyProgressDto {
occurred_at_ms: None,
progress_id: Some(progress_id.to_owned()), progress_id: Some(progress_id.to_owned()),
source: ReplyProgressSourceDto::ProviderNative, source: ReplyProgressSourceDto::ProviderNative,
kind, kind,
@ -107,6 +114,7 @@ fn progress_chunk_with_id(
fn chunk_bytes(chunk: &ReplyChunk) -> usize { fn chunk_bytes(chunk: &ReplyChunk) -> usize {
match chunk { match chunk {
ReplyChunk::UserPrompt { ReplyChunk::UserPrompt {
at_ms: _,
text, text,
attachments, attachments,
attachment_refs, attachment_refs,
@ -123,13 +131,13 @@ fn chunk_bytes(chunk: &ReplyChunk) -> usize {
}) })
.sum::<usize>() .sum::<usize>()
} }
ReplyChunk::TextDelta { text } => text.len(), ReplyChunk::TextDelta { text, .. } => text.len(),
ReplyChunk::ToolActivity { label } => label.len(), ReplyChunk::ToolActivity { label, .. } => label.len(),
ReplyChunk::Progress { progress } => { ReplyChunk::Progress { progress } => {
progress.label.len() + progress.text.as_ref().map_or(0, String::len) progress.label.len() + progress.text.as_ref().map_or(0, String::len)
} }
ReplyChunk::Final { content } => content.len(), ReplyChunk::Final { content, .. } => content.len(),
ReplyChunk::Error { message } => message.len(), ReplyChunk::Error { message, .. } => message.len(),
} }
} }
@ -137,11 +145,32 @@ fn chunk_bytes(chunk: &ReplyChunk) -> usize {
// chunk_from_event — exhaustive mapping (zone 6) // chunk_from_event — exhaustive mapping (zone 6)
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
#[test]
fn accepted_reply_events_keep_the_backend_timestamp() {
let chunk = app_tauri_lib::chat::chunk_from_event_at(
ReplyEvent::Final {
content: "done".to_owned(),
},
Some(42_424),
)
.unwrap();
assert_eq!(
chunk,
ReplyChunk::Final {
at_ms: Some(42_424),
content: "done".to_owned()
}
);
}
#[test] #[test]
fn chunk_from_event_maps_text_delta() { fn chunk_from_event_maps_text_delta() {
assert_eq!( assert_eq!(
chunk_from_event(ReplyEvent::TextDelta { text: "hi".into() }), chunk_from_event(ReplyEvent::TextDelta { text: "hi".into() }),
Some(ReplyChunk::TextDelta { text: "hi".into() }) Some(ReplyChunk::TextDelta {
at_ms: None,
text: "hi".into()
})
); );
} }
@ -202,6 +231,7 @@ fn chunk_from_event_maps_final() {
content: "done".into() content: "done".into()
}), }),
Some(ReplyChunk::Final { Some(ReplyChunk::Final {
at_ms: None,
content: "done".into() content: "done".into()
}) })
); );
@ -236,7 +266,10 @@ fn pump_turn(bridge: &ChatBridge, session: &SessionId, gen: u64, events: Vec<Rep
for event in events { for event in events {
// Mirror the real pump: heartbeats map to no chunk and are skipped. // Mirror the real pump: heartbeats map to no chunk and are skipped.
if let Some(chunk) = chunk_from_event(event) { if let Some(chunk) = chunk_from_event(event) {
if matches!(chunk, ReplyChunk::Final { .. } | ReplyChunk::Error { .. }) { if matches!(
chunk,
ReplyChunk::Final { at_ms: None, .. } | ReplyChunk::Error { at_ms: None, .. }
) {
terminal_visible = true; terminal_visible = true;
} }
let _ = bridge.send_output(session, chunk); let _ = bridge.send_output(session, chunk);
@ -277,10 +310,13 @@ fn pump_delivers_deltas_then_exactly_one_final_in_order() {
// Exactly one Final, and it is last (deterministic terminal chunk). // Exactly one Final, and it is last (deterministic terminal chunk).
let finals = got let finals = got
.iter() .iter()
.filter(|c| matches!(c, ReplyChunk::Final { .. })) .filter(|c| matches!(c, ReplyChunk::Final { at_ms: None, .. }))
.count(); .count();
assert_eq!(finals, 1, "exactly one Final per turn"); assert_eq!(finals, 1, "exactly one Final per turn");
assert!(matches!(got.last(), Some(ReplyChunk::Final { .. }))); assert!(matches!(
got.last(),
Some(ReplyChunk::Final { at_ms: None, .. })
));
} }
#[test] #[test]
@ -490,6 +526,7 @@ fn scrollback_accumulates_every_routed_chunk_in_order() {
.map(|chunk| match chunk { .map(|chunk| match chunk {
ReplyChunk::Progress { progress } => { ReplyChunk::Progress { progress } => {
ReplyChunk::ToolActivity { ReplyChunk::ToolActivity {
at_ms: None,
label: progress.label, label: progress.label,
} }
} }
@ -499,6 +536,7 @@ fn scrollback_accumulates_every_routed_chunk_in_order() {
vec![ vec![
delta("x"), delta("x"),
ReplyChunk::ToolActivity { ReplyChunk::ToolActivity {
at_ms: None,
label: "runs".into() label: "runs".into()
}, },
final_chunk("x"), final_chunk("x"),
@ -756,15 +794,15 @@ fn scrollback_drops_oldest_whole_chunks_when_byte_cap_is_exceeded() {
assert_eq!(scrollback.len(), 4); assert_eq!(scrollback.len(), 4);
assert!(matches!( assert!(matches!(
scrollback.first(), scrollback.first(),
Some(ReplyChunk::TextDelta { text }) if text.starts_with("02:") Some(ReplyChunk::TextDelta { text, .. }) if text.starts_with("02:")
)); ));
assert!(matches!( assert!(matches!(
scrollback.last(), scrollback.last(),
Some(ReplyChunk::TextDelta { text }) if text.starts_with("05:") Some(ReplyChunk::TextDelta { text, .. }) if text.starts_with("05:")
)); ));
assert!(scrollback.iter().all(|chunk| matches!( assert!(scrollback.iter().all(|chunk| matches!(
chunk, chunk,
ReplyChunk::TextDelta { text } if text.len() == chunk_size ReplyChunk::TextDelta { text, .. } if text.len() == chunk_size
))); )));
} }
@ -781,6 +819,7 @@ fn truncated_scrollback_replays_valid_unmodified_chunks_in_order() {
bridge.send_output( bridge.send_output(
&session, &session,
ReplyChunk::ToolActivity { ReplyChunk::ToolActivity {
at_ms: None,
label: "tool".into(), label: "tool".into(),
}, },
); );
@ -793,6 +832,7 @@ fn truncated_scrollback_replays_valid_unmodified_chunks_in_order() {
&scrollback[(MAX_CHAT_SCROLLBACK_CHUNKS - 2)..], &scrollback[(MAX_CHAT_SCROLLBACK_CHUNKS - 2)..],
&[ &[
ReplyChunk::ToolActivity { ReplyChunk::ToolActivity {
at_ms: None,
label: "tool".into() label: "tool".into()
}, },
final_chunk("done") final_chunk("done")

View File

@ -444,7 +444,7 @@ fn project_work_state_dto_serialises_conversations_camelcase() {
source: TicketWorkSource::Agent { source: TicketWorkSource::Agent {
agent_id: requester, agent_id: requester,
}, },
at_ms: 1_700, at_ms: Some(1_700),
text_preview: "Analyse le module".to_owned(), text_preview: "Analyse le module".to_owned(),
text_len: 17, text_len: 17,
}], }],
@ -715,24 +715,29 @@ fn stop_live_agent_request_deserialises_camelcase() {
#[test] #[test]
fn stop_live_agent_response_serialises_camelcase_with_kind() { fn stop_live_agent_response_serialises_camelcase_with_kind() {
use app_tauri_lib::dto::StopLiveAgentResponseDto; use app_tauri_lib::dto::StopLiveAgentResponseDto;
use application::terminal::StoppedAgentRuntime;
use application::{LiveSessionKind, StopLiveAgentOutput}; use application::{LiveSessionKind, StopLiveAgentOutput};
let agent = AgentId::from_uuid(Uuid::from_u128(11)); let agent = AgentId::from_uuid(Uuid::from_u128(11));
let node = NodeId::from_uuid(Uuid::from_u128(12)); let node = NodeId::from_uuid(Uuid::from_u128(12));
let session = SessionId::from_uuid(Uuid::from_u128(13)); let session = SessionId::from_uuid(Uuid::from_u128(13));
let dto = StopLiveAgentResponseDto::from(StopLiveAgentOutput { let dto = StopLiveAgentResponseDto::from(StopLiveAgentOutput {
agent_id: agent,
stopped: vec![StoppedAgentRuntime {
agent_id: agent, agent_id: agent,
node_id: node, node_id: node,
session_id: session, session_id: session,
kind: LiveSessionKind::Structured, kind: LiveSessionKind::Structured,
runtime_state: LiveRuntimeState::Stopped, state: LiveRuntimeState::Stopped,
}],
already_stopped: false,
}); });
let v = serde_json::to_value(&dto).unwrap(); let v = serde_json::to_value(&dto).unwrap();
assert_eq!(v["agentId"], agent.to_string()); assert_eq!(v["agentId"], agent.to_string());
assert_eq!(v["sessionId"], session.to_string()); assert_eq!(v["stopped"][0]["sessionId"], session.to_string());
assert_eq!(v["kind"], "structured"); assert_eq!(v["stopped"][0]["kind"], "structured");
assert_eq!(v["runtimeState"], "stopped"); assert_eq!(v["stopped"][0]["runtimeState"], "stopped");
assert!(v.get("nodeId").is_none()); assert_eq!(v["alreadyStopped"], false);
assert!(v.get("session_id").is_none()); assert!(v.get("session_id").is_none());
} }

View File

@ -26,17 +26,22 @@ use uuid::Uuid;
#[test] #[test]
fn reply_chunk_user_prompt_serialises_exact_camel_case() { fn reply_chunk_user_prompt_serialises_exact_camel_case() {
let v = serde_json::to_value(ReplyChunk::UserPrompt { let v = serde_json::to_value(ReplyChunk::UserPrompt {
at_ms: None,
text: "run tests".into(), text: "run tests".into(),
attachments: Vec::new(), attachments: Vec::new(),
attachment_refs: Vec::new(), attachment_refs: Vec::new(),
}) })
.unwrap(); .unwrap();
assert_eq!(v, json!({ "kind": "userPrompt", "text": "run tests" })); assert_eq!(
v,
json!({ "kind": "userPrompt", "text": "run tests", "atMs": null })
);
} }
#[test] #[test]
fn reply_chunk_user_prompt_serialises_attachment_labels() { fn reply_chunk_user_prompt_serialises_attachment_labels() {
let v = serde_json::to_value(ReplyChunk::UserPrompt { let v = serde_json::to_value(ReplyChunk::UserPrompt {
at_ms: None,
text: "describe this".into(), text: "describe this".into(),
attachments: vec!["clipboard.png".into()], attachments: vec!["clipboard.png".into()],
attachment_refs: vec![ChatPromptAttachmentDto { attachment_refs: vec![ChatPromptAttachmentDto {
@ -52,6 +57,7 @@ fn reply_chunk_user_prompt_serialises_attachment_labels() {
v, v,
json!({ json!({
"kind": "userPrompt", "kind": "userPrompt",
"atMs": null,
"text": "describe this", "text": "describe this",
"attachments": ["clipboard.png"], "attachments": ["clipboard.png"],
"attachmentRefs": [{ "attachmentRefs": [{
@ -68,25 +74,50 @@ fn reply_chunk_user_prompt_serialises_attachment_labels() {
#[test] #[test]
fn reply_chunk_text_delta_serialises_exact_camel_case() { fn reply_chunk_text_delta_serialises_exact_camel_case() {
let v = serde_json::to_value(ReplyChunk::TextDelta { let v = serde_json::to_value(ReplyChunk::TextDelta {
at_ms: None,
text: "hello".into(), text: "hello".into(),
}) })
.unwrap(); .unwrap();
assert_eq!(v, json!({ "kind": "textDelta", "text": "hello" })); assert_eq!(
v,
json!({ "kind": "textDelta", "text": "hello", "atMs": null })
);
}
#[test]
fn legacy_reply_chunk_without_timestamp_deserialises_as_none() {
let chunk: ReplyChunk = serde_json::from_value(json!({
"kind": "final",
"content": "legacy"
}))
.unwrap();
assert_eq!(
chunk,
ReplyChunk::Final {
at_ms: None,
content: "legacy".into()
}
);
} }
#[test] #[test]
fn reply_chunk_tool_activity_serialises_exact_camel_case() { fn reply_chunk_tool_activity_serialises_exact_camel_case() {
let v = serde_json::to_value(ReplyChunk::ToolActivity { let v = serde_json::to_value(ReplyChunk::ToolActivity {
at_ms: None,
label: "reads file".into(), label: "reads file".into(),
}) })
.unwrap(); .unwrap();
assert_eq!(v, json!({ "kind": "toolActivity", "label": "reads file" })); assert_eq!(
v,
json!({ "kind": "toolActivity", "label": "reads file", "atMs": null })
);
} }
#[test] #[test]
fn reply_chunk_progress_serialises_exact_camel_case() { fn reply_chunk_progress_serialises_exact_camel_case() {
let v = serde_json::to_value(ReplyChunk::Progress { let v = serde_json::to_value(ReplyChunk::Progress {
progress: ReplyProgressDto { progress: ReplyProgressDto {
occurred_at_ms: None,
progress_id: Some("codex:item:tool0".into()), progress_id: Some("codex:item:tool0".into()),
source: ReplyProgressSourceDto::IdeaLocal, source: ReplyProgressSourceDto::IdeaLocal,
kind: ReplyProgressKindDto::Mcp, kind: ReplyProgressKindDto::Mcp,
@ -105,6 +136,7 @@ fn reply_chunk_progress_serialises_exact_camel_case() {
"kind": "progress", "kind": "progress",
"progress": { "progress": {
"source": "ideaLocal", "source": "ideaLocal",
"occurredAtMs": null,
"kind": "mcp", "kind": "mcp",
"progressId": "codex:item:tool0", "progressId": "codex:item:tool0",
"stage": "started", "stage": "started",
@ -119,21 +151,26 @@ fn reply_chunk_progress_serialises_exact_camel_case() {
#[test] #[test]
fn reply_chunk_final_serialises_exact_camel_case() { fn reply_chunk_final_serialises_exact_camel_case() {
let v = serde_json::to_value(ReplyChunk::Final { let v = serde_json::to_value(ReplyChunk::Final {
at_ms: None,
content: "done".into(), content: "done".into(),
}) })
.unwrap(); .unwrap();
assert_eq!(v, json!({ "kind": "final", "content": "done" })); assert_eq!(
v,
json!({ "kind": "final", "content": "done", "atMs": null })
);
} }
#[test] #[test]
fn reply_chunk_error_serialises_exact_camel_case() { fn reply_chunk_error_serialises_exact_camel_case() {
let v = serde_json::to_value(ReplyChunk::Error { let v = serde_json::to_value(ReplyChunk::Error {
at_ms: None,
message: "Réponse vide du modèle.".into(), message: "Réponse vide du modèle.".into(),
}) })
.unwrap(); .unwrap();
assert_eq!( assert_eq!(
v, v,
json!({ "kind": "error", "message": "Réponse vide du modèle." }) json!({ "kind": "error", "message": "Réponse vide du modèle.", "atMs": null })
); );
} }
@ -141,6 +178,7 @@ fn reply_chunk_error_serialises_exact_camel_case() {
fn reply_chunk_round_trips_through_json_for_every_variant() { fn reply_chunk_round_trips_through_json_for_every_variant() {
for chunk in [ for chunk in [
ReplyChunk::UserPrompt { ReplyChunk::UserPrompt {
at_ms: None,
text: "u".into(), text: "u".into(),
attachments: vec!["clipboard.png".into()], attachments: vec!["clipboard.png".into()],
attachment_refs: vec![ChatPromptAttachmentDto { attachment_refs: vec![ChatPromptAttachmentDto {
@ -152,12 +190,17 @@ fn reply_chunk_round_trips_through_json_for_every_variant() {
.into(), .into(),
}], }],
}, },
ReplyChunk::TextDelta { text: "x".into() }, ReplyChunk::TextDelta {
at_ms: None,
text: "x".into(),
},
ReplyChunk::ToolActivity { ReplyChunk::ToolActivity {
at_ms: None,
label: "runs".into(), label: "runs".into(),
}, },
ReplyChunk::Progress { ReplyChunk::Progress {
progress: ReplyProgressDto { progress: ReplyProgressDto {
occurred_at_ms: None,
progress_id: None, progress_id: None,
source: ReplyProgressSourceDto::ProviderNative, source: ReplyProgressSourceDto::ProviderNative,
kind: ReplyProgressKindDto::Turn, kind: ReplyProgressKindDto::Turn,
@ -170,9 +213,11 @@ fn reply_chunk_round_trips_through_json_for_every_variant() {
}, },
}, },
ReplyChunk::Final { ReplyChunk::Final {
at_ms: None,
content: "y".into(), content: "y".into(),
}, },
ReplyChunk::Error { ReplyChunk::Error {
at_ms: None,
message: "empty".into(), message: "empty".into(),
}, },
] { ] {
@ -190,6 +235,7 @@ fn reply_chunk_deserialises_from_camel_case_wire_payload() {
assert_eq!( assert_eq!(
back, back,
ReplyChunk::UserPrompt { ReplyChunk::UserPrompt {
at_ms: None,
text: "hi".into(), text: "hi".into(),
attachments: Vec::new(), attachments: Vec::new(),
attachment_refs: Vec::new() attachment_refs: Vec::new()
@ -366,12 +412,17 @@ fn reattach_chat_dto_serialises_camel_case_with_typed_scrollback() {
conversation_id: Some("conv-1".into()), conversation_id: Some("conv-1".into()),
scrollback: vec![ scrollback: vec![
ReplyChunk::UserPrompt { ReplyChunk::UserPrompt {
at_ms: None,
text: "Hi".into(), text: "Hi".into(),
attachments: Vec::new(), attachments: Vec::new(),
attachment_refs: Vec::new(), attachment_refs: Vec::new(),
}, },
ReplyChunk::TextDelta { text: "Hi".into() }, ReplyChunk::TextDelta {
at_ms: None,
text: "Hi".into(),
},
ReplyChunk::Final { ReplyChunk::Final {
at_ms: None,
content: "Hi".into(), content: "Hi".into(),
}, },
], ],
@ -383,9 +434,9 @@ fn reattach_chat_dto_serialises_camel_case_with_typed_scrollback() {
"sessionId": "sess-1", "sessionId": "sess-1",
"conversationId": "conv-1", "conversationId": "conv-1",
"scrollback": [ "scrollback": [
{ "kind": "userPrompt", "text": "Hi" }, { "kind": "userPrompt", "text": "Hi", "atMs": null },
{ "kind": "textDelta", "text": "Hi" }, { "kind": "textDelta", "text": "Hi", "atMs": null },
{ "kind": "final", "content": "Hi" }, { "kind": "final", "content": "Hi", "atMs": null },
], ],
}) })
); );

View File

@ -19,6 +19,7 @@ use domain::ports::{
FileSystem, FsError, IdGenerator, LocalPath, MemoryQuery, MemoryRecall, PermissionStore, FileSystem, FsError, IdGenerator, LocalPath, MemoryQuery, MemoryRecall, PermissionStore,
PreparedContext, ProfileStore, ProjectStore, PtyPort, RemotePath, SecretStore, SessionPlan, PreparedContext, ProfileStore, ProjectStore, PtyPort, RemotePath, SecretStore, SessionPlan,
SkillStore, SpawnSpec, StructuredProviderLaunchPolicy, SystemPermissionStore, SkillStore, SpawnSpec, StructuredProviderLaunchPolicy, SystemPermissionStore,
UserSettingsStore,
}; };
use domain::profile::{ use domain::profile::{
resolve_effort, EffortSelection, McpConfigStrategy, OpenCodeProviderConfig, StructuredAdapter, 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::sandbox::{compile_sandbox_plan, PathAccess, PathGrant, SandboxContext, SandboxPlan};
use domain::{ use domain::{
bound_handoff_summary, Agent, AgentId, AgentManifest, AgentOrigin, AgentProfile, bound_handoff_summary, Agent, AgentId, AgentManifest, AgentOrigin, AgentProfile,
ContextInjection, ConversationId, ConversationParty, DomainEvent, EffectivePermissions, ContextInjection, ConversationId, ConversationParty, DefaultAgentTerminalInterface,
Handoff, HandoffStore, ManagedTempKind, ManifestEntry, MarkdownDoc, MemoryIndexEntry, DomainEvent, EffectivePermissions, Handoff, HandoffStore, ManagedTempKind, ManifestEntry,
MemoryType, NetworkPolicy, NodeId, OrchestrationCapabilitySnapshot, PermissionProjector, MarkdownDoc, MemoryIndexEntry, MemoryType, NetworkPolicy, NodeId,
PluginMcpServerSpec, ProfileId, Project, ProjectPath, ProjectedFile, ProjectionContext, OrchestrationCapabilitySnapshot, PermissionProjector, PluginMcpServerSpec, ProfileId, Project,
ProjectorKey, ProviderSessionStore, PtySize, SessionId, SessionKind, SessionStatus, SkillKind, ProjectPath, ProjectedFile, ProjectionContext, ProjectorKey, ProviderSessionStore, PtySize,
TerminalSession, HANDOFF_SUMMARY_MAX_CHARS, SessionId, SessionKind, SessionStatus, SkillKind, TerminalSession, HANDOFF_SUMMARY_MAX_CHARS,
}; };
use domain::live_state::WorkStatus; use domain::live_state::WorkStatus;
@ -1123,6 +1124,7 @@ impl ChangeAgentProfile {
mcp_runtime: None, mcp_runtime: None,
allow_structured_alongside_pty: false, allow_structured_alongside_pty: false,
require_structured: false, require_structured: false,
terminal_interface: None,
fresh_start: false, fresh_start: false,
managed_temp_exposure: ManagedTempExposureRequest::default(), managed_temp_exposure: ManagedTempExposureRequest::default(),
}) })
@ -1310,6 +1312,8 @@ pub struct LaunchAgentInput {
/// ///
/// Historical callers leave this `false`, preserving the PTY launch contract. /// Historical callers leave this `false`, preserving the PTY launch contract.
pub require_structured: bool, 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 /// Cold restart request: ignore the cell's previous conversation id and create
/// a new provider/CLI conversation for this activation. /// a new provider/CLI conversation for this activation.
pub fresh_start: bool, pub fresh_start: bool,
@ -1803,6 +1807,8 @@ pub struct LaunchAgent {
/// Optional for legacy tests/callers; runtime composition wires the shared /// Optional for legacy tests/callers; runtime composition wires the shared
/// project-plugin resolver used by the capability assignment use cases. /// project-plugin resolver used by the capability assignment use cases.
plugin_mcp: Option<Arc<ProjectPluginResolver>>, 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. /// Explicit intent for structured profiles when structured ports are absent.
structured_routing_mode: StructuredRoutingMode, structured_routing_mode: StructuredRoutingMode,
} }
@ -1855,6 +1861,7 @@ impl LaunchAgent {
managed_temp_allocator: None, managed_temp_allocator: None,
managed_temp_releaser: None, managed_temp_releaser: None,
plugin_mcp: None, plugin_mcp: None,
user_settings: None,
structured_routing_mode: StructuredRoutingMode::HumanPtyFallback, structured_routing_mode: StructuredRoutingMode::HumanPtyFallback,
} }
} }
@ -1866,6 +1873,13 @@ impl LaunchAgent {
self 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 /// Replaces the default native-skill resolver with the shared effective
/// resolver used by runtime context injection and `idea_skill_read`. /// resolver used by runtime context injection and `idea_skill_read`.
#[must_use] #[must_use]
@ -2279,7 +2293,16 @@ impl LaunchAgent {
input.agent_id, profile.id 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 let wants_structured = input.require_structured
|| preferred_interface == Some(DefaultAgentTerminalInterface::IdeaCli)
&& profile.structured_adapter.is_some()
|| matches!( || matches!(
self.structured_routing_mode, self.structured_routing_mode,
StructuredRoutingMode::RequireStructured StructuredRoutingMode::RequireStructured

View File

@ -56,7 +56,7 @@ pub struct TurnView {
/// Identifiant stable du tour (sert aussi d'ancre de pagination). /// Identifiant stable du tour (sert aussi d'ancre de pagination).
pub id: TurnId, pub id: TurnId,
/// Horodatage (epoch millisecondes). /// Horodatage (epoch millisecondes).
pub at_ms: u64, pub at_ms: Option<u64>,
/// Nature du tour (invite, réponse, activité outillée). /// Nature du tour (invite, réponse, activité outillée).
pub role: TurnRole, pub role: TurnRole,
/// Origine (humain ou agent délégant). /// Origine (humain ou agent délégant).

View File

@ -35,6 +35,7 @@ pub mod plugin;
pub mod project; pub mod project;
pub mod project_plugin; pub mod project_plugin;
pub mod remote; pub mod remote;
pub mod settings;
pub mod skill; pub mod skill;
pub mod slash_command; pub mod slash_command;
pub mod sprints; pub mod sprints;
@ -219,6 +220,9 @@ pub use project_plugin::{
ProjectPluginSettingsView, SetProjectPluginEnabled, ProjectPluginSettingsView, SetProjectPluginEnabled,
}; };
pub use remote::{ConnectRemote, ConnectRemoteInput, ConnectRemoteOutput}; pub use remote::{ConnectRemote, ConnectRemoteInput, ConnectRemoteOutput};
pub use settings::{
ReadProjectSettings, ReadUserSettings, UpdateProjectSettings, UpdateUserSettings,
};
pub use skill::{ pub use skill::{
AgentCapability, AssignSkillToAgent, AssignSkillToAgentInput, AssignedSkillResolver, AgentCapability, AssignSkillToAgent, AssignSkillToAgentInput, AssignedSkillResolver,
CreateSkill, CreateSkillInput, CreateSkillOutput, DeleteSkill, DeleteSkillInput, ListSkills, CreateSkill, CreateSkillInput, CreateSkillOutput, DeleteSkill, DeleteSkillInput, ListSkills,
@ -275,7 +279,7 @@ pub use workstate::{
ConversationTurnWorkPreview, ConversationWorkSummary, GetAppExitWorkGuardState, ConversationTurnWorkPreview, ConversationWorkSummary, GetAppExitWorkGuardState,
GetAppExitWorkGuardStateInput, GetLiveStateLean, GetProjectWorkState, GetProjectWorkStateInput, GetAppExitWorkGuardStateInput, GetLiveStateLean, GetProjectWorkState, GetProjectWorkStateInput,
LeanLiveEntry, LeanLiveState, LiveWorkSession, ProjectWorkState, ReconcileLiveState, LeanLiveEntry, LeanLiveState, LiveWorkSession, ProjectWorkState, ReconcileLiveState,
ReconcileLiveStateInput, StopAgentExecutionCascade, StopLiveAgent, StopLiveAgentInput, ReconcileLiveStateInput, StopAgentExecutionCascade, StopAgentRuntime, StopLiveAgent,
StopLiveAgentOutput, TicketWorkSource, TicketWorkStatus, UpdateLiveState, UpdateLiveStateInput, StopLiveAgentInput, StopLiveAgentOutput, TicketWorkSource, TicketWorkStatus, UpdateLiveState,
LIVE_STATE_MAX_ENTRIES, LIVE_STATE_TTL_MS, UpdateLiveStateInput, LIVE_STATE_MAX_ENTRIES, LIVE_STATE_TTL_MS,
}; };

View File

@ -2744,6 +2744,7 @@ impl OrchestratorService {
mcp_runtime: None, mcp_runtime: None,
allow_structured_alongside_pty: false, allow_structured_alongside_pty: false,
require_structured: false, require_structured: false,
terminal_interface: None,
fresh_start: false, fresh_start: false,
managed_temp_exposure: ManagedTempExposureRequest::default(), managed_temp_exposure: ManagedTempExposureRequest::default(),
}) })
@ -3638,6 +3639,7 @@ impl OrchestratorService {
.and_then(|p| p.runtime_for(project, agent_id)), .and_then(|p| p.runtime_for(project, agent_id)),
allow_structured_alongside_pty: false, allow_structured_alongside_pty: false,
require_structured: false, require_structured: false,
terminal_interface: None,
fresh_start: false, fresh_start: false,
managed_temp_exposure: ManagedTempExposureRequest::default(), managed_temp_exposure: ManagedTempExposureRequest::default(),
}) })
@ -3722,6 +3724,7 @@ impl OrchestratorService {
.and_then(|p| p.runtime_for(project, agent_id)), .and_then(|p| p.runtime_for(project, agent_id)),
allow_structured_alongside_pty: true, allow_structured_alongside_pty: true,
require_structured: true, require_structured: true,
terminal_interface: None,
fresh_start: false, fresh_start: false,
managed_temp_exposure: ManagedTempExposureRequest::default(), managed_temp_exposure: ManagedTempExposureRequest::default(),
}) })

View 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)
}
}

View File

@ -290,31 +290,43 @@ pub async fn stop_live_agent_runtime_in_project(
close: &CloseTerminal, close: &CloseTerminal,
) -> Result<Vec<StoppedAgentRuntime>, AppError> { ) -> Result<Vec<StoppedAgentRuntime>, AppError> {
let mut stopped = Vec::new(); let mut stopped = Vec::new();
let mut first_error = None;
let snapshots = live.live_agent_snapshots_for(project.id, &agent_id); let snapshots = live.live_agent_snapshots_for(project.id, &agent_id);
for snapshot in snapshots { for snapshot in snapshots {
live.mark_runtime_state(snapshot, LiveRuntimeState::Stopping); live.mark_runtime_state(snapshot, LiveRuntimeState::Stopping);
match snapshot.kind { let removed = match snapshot.kind {
LiveSessionKind::Structured => { LiveSessionKind::Structured => {
if let Some(removed) = live.structured.remove_runtime(&snapshot.session_id) { if let Some(removed) = live.structured.remove_runtime(&snapshot.session_id) {
removed if let Err(error) = removed.session.shutdown().await {
.session first_error.get_or_insert_with(|| AppError::Process(error.to_string()));
.shutdown() }
.await if let Err(error) = close
.map_err(|e| AppError::Process(e.to_string()))?;
close
.release_managed_temp_handle(removed.managed_temp_handle) .release_managed_temp_handle(removed.managed_temp_handle)
.await?; .await
{
first_error.get_or_insert(error);
}
true
} else {
false
} }
} }
LiveSessionKind::Pty => { LiveSessionKind::Pty => {
close if let Err(error) = close
.execute(CloseTerminalInput { .execute(CloseTerminalInput {
session_id: snapshot.session_id, 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); live.mark_runtime_state(snapshot, LiveRuntimeState::Stopped);
stopped.push(StoppedAgentRuntime { stopped.push(StoppedAgentRuntime {
agent_id: snapshot.agent_id, agent_id: snapshot.agent_id,
@ -324,8 +336,11 @@ pub async fn stop_live_agent_runtime_in_project(
state: LiveRuntimeState::Stopped, state: LiveRuntimeState::Stopped,
}); });
} }
}
Ok(stopped) match first_error {
Some(error) => Err(error),
None => Ok(stopped),
}
} }
/// The platform default interactive shell. /// The platform default interactive shell.

View File

@ -11,13 +11,13 @@ use std::sync::Arc;
use async_trait::async_trait; use async_trait::async_trait;
use domain::input::InputMediator; use domain::input::InputMediator;
use domain::live_state::WorkStatus;
use domain::{AgentId, NodeId, Project, RuntimeAgentKey, SessionId}; use domain::{AgentId, NodeId, Project, RuntimeAgentKey, SessionId};
use crate::error::AppError; use crate::error::AppError;
use crate::orchestrator::OrchestratorService; use crate::orchestrator::{LiveStateProvider, OrchestratorService};
use crate::terminal::{ use crate::terminal::{
stop_live_agent_runtime_in_project, CloseTerminal, LiveRuntimeState, LiveSessionKind, stop_live_agent_runtime_in_project, CloseTerminal, LiveSessionKind, LiveSessions,
LiveSessions,
}; };
/// Input for [`AttachLiveAgent::execute`]. /// Input for [`AttachLiveAgent::execute`].
@ -100,35 +100,33 @@ impl AttachLiveAgent {
} }
} }
/// Input for [`StopLiveAgent::execute`]. /// Input for [`StopAgentRuntime::execute`].
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct StopLiveAgentInput { pub struct StopLiveAgentInput {
/// The owning project (boundary/symmetry; the registries are global by agent). /// The owning project (boundary/symmetry; the registries are global by agent).
pub project: Project, pub project: Project,
/// The agent whose live session is stopped. /// The agent whose live session is stopped.
pub agent_id: AgentId, pub agent_id: AgentId,
/// Optional human-readable stop reason.
pub reason: Option<String>,
} }
/// Output of [`StopLiveAgent::execute`]. /// Output of [`StopLiveAgent::execute`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct StopLiveAgentOutput { pub struct StopLiveAgentOutput {
/// The stopped agent. /// The stopped agent.
pub agent_id: AgentId, pub agent_id: AgentId,
/// The id of the session that was torn down. /// The id of the session that was torn down.
pub session_id: SessionId, pub stopped: Vec<crate::terminal::StoppedAgentRuntime>,
/// Last known layout node hosting the runtime view. /// Whether no live runtime remained to stop.
pub node_id: NodeId, pub already_stopped: bool,
/// Runtime family that owned the session.
pub kind: LiveSessionKind,
/// Runtime lifecycle projection after the stop request.
pub runtime_state: LiveRuntimeState,
} }
/// Best-effort stopper for execution resources owned by one live agent turn. /// Best-effort stopper for execution resources owned by one live agent turn.
/// ///
/// Implementations must be idempotent: a missing, already-finished or already-stopped /// Implementations must be idempotent: a missing, already-finished or already-stopped
/// child resource is a successful no-op. Failures are deliberately not propagated by /// 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". /// work best-effort".
#[async_trait] #[async_trait]
pub trait StopAgentExecutionCascade: Send + Sync { 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 /// provider conversation/context survives the stop. A PTY session has no finer
/// turn boundary, so it is torn down through the existing [`CloseTerminal`] /// turn boundary, so it is torn down through the existing [`CloseTerminal`]
/// primitive (registry removal + process kill). /// primitive (registry removal + process kill).
pub struct StopLiveAgent { pub struct StopAgentRuntime {
live: Arc<LiveSessions>, live: Arc<LiveSessions>,
close: Arc<CloseTerminal>, close: Arc<CloseTerminal>,
input: Option<Arc<dyn InputMediator>>, input: Option<Arc<dyn InputMediator>>,
waits: Option<Arc<OrchestratorService>>, waits: Option<Arc<OrchestratorService>>,
cascade: Option<Arc<dyn StopAgentExecutionCascade>>, cascade: Option<Arc<dyn StopAgentExecutionCascade>>,
restart_rendezvous: Option<Arc<crate::RestartRendezvousCoordinator>>, 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. /// Builds the use case from the live-session registry and the close primitive.
#[must_use] #[must_use]
pub fn new(live: Arc<LiveSessions>, close: Arc<CloseTerminal>) -> Self { pub fn new(live: Arc<LiveSessions>, close: Arc<CloseTerminal>) -> Self {
@ -163,9 +162,17 @@ impl StopLiveAgent {
waits: None, waits: None,
cascade: None, cascade: None,
restart_rendezvous: 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. /// Wires cancellation helpers used for user-driven stop cascades.
/// ///
/// Stopping A while A waits on B should stop B too. The orchestrator service is /// 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 { if let Some(mediator) = &self.input {
mediator.preempt(RuntimeAgentKey::new(input.project.id, input.agent_id)); mediator.preempt(RuntimeAgentKey::new(input.project.id, input.agent_id));
} }
if let Some(out) = self let stopped = stop_live_agent_runtime_in_project(
.cancel_structured_turn_in_project(&input.project, input.agent_id) &input.project,
.await? input.agent_id,
{ &self.live,
return Ok(out); &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( async fn stop_dependencies(
@ -246,87 +271,11 @@ impl StopLiveAgent {
if let Some(mediator) = &self.input { if let Some(mediator) = &self.input {
mediator.preempt(RuntimeAgentKey::new(project.id, dep)); mediator.preempt(RuntimeAgentKey::new(project.id, dep));
} }
if self let _ = stop_live_agent_runtime_in_project(project, dep, &self.live, &self.close).await;
.cancel_structured_turn_in_project(project, dep)
.await?
.is_none()
{
let _ = self.stop_one_in_project(project, dep).await;
}
} }
Ok(()) 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( /// Compatibility name kept for existing driving adapters.
&self, pub type StopLiveAgent = StopAgentRuntime;
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}")))
}
}

View File

@ -11,7 +11,7 @@ mod reconcile;
pub use actions::{ pub use actions::{
AttachLiveAgent, AttachLiveAgentInput, AttachLiveAgentOutput, StopAgentExecutionCascade, AttachLiveAgent, AttachLiveAgentInput, AttachLiveAgentOutput, StopAgentExecutionCascade,
StopLiveAgent, StopLiveAgentInput, StopLiveAgentOutput, StopAgentRuntime, StopLiveAgent, StopLiveAgentInput, StopLiveAgentOutput,
}; };
pub use live::{ pub use live::{
GetLiveStateLean, LeanLiveEntry, LeanLiveState, UpdateLiveState, UpdateLiveStateInput, GetLiveStateLean, LeanLiveEntry, LeanLiveState, UpdateLiveState, UpdateLiveStateInput,
@ -172,7 +172,7 @@ pub struct ConversationTurnWorkPreview {
/// Origin of the turn (human operator or a delegating agent). /// Origin of the turn (human operator or a delegating agent).
pub source: TicketWorkSource, pub source: TicketWorkSource,
/// Timestamp (epoch milliseconds) of the turn. /// Timestamp (epoch milliseconds) of the turn.
pub at_ms: u64, pub at_ms: Option<u64>,
/// Bounded, whitespace-normalised excerpt of the turn text. /// Bounded, whitespace-normalised excerpt of the turn text.
pub text_preview: String, pub text_preview: String,
/// Character length of the **original** (un-truncated) turn text. /// Character length of the **original** (un-truncated) turn text.

View File

@ -1501,6 +1501,7 @@ fn launch_input_with_project(agent_id: AgentId, project: Project) -> LaunchAgent
mcp_runtime: None, mcp_runtime: None,
allow_structured_alongside_pty: false, allow_structured_alongside_pty: false,
require_structured: false, require_structured: false,
terminal_interface: None,
fresh_start: false, fresh_start: false,
managed_temp_exposure: ManagedTempExposureRequest::default(), managed_temp_exposure: ManagedTempExposureRequest::default(),
} }

View File

@ -4585,8 +4585,8 @@ async fn p6b_user_ask_records_prompt_then_response_pair() {
"response is sourced from the target (architect)" "response is sourced from the target (architect)"
); );
// Clock stamp came from the injected Clock. // Clock stamp came from the injected Clock.
assert_eq!(prompt.at_ms, 123); assert_eq!(prompt.at_ms, Some(123));
assert_eq!(response.at_ms, 123); assert_eq!(response.at_ms, Some(123));
} }
/// Round-trip with an **agent** requester (A) resolves the `A↔B` conversation and the /// Round-trip with an **agent** requester (A) resolves the `A↔B` conversation and the

View File

@ -40,13 +40,16 @@ use domain::ports::{
ContextInjectionPlan, DirEntry, EventBus, EventStream, ExitStatus, FileSystem, FsError, ContextInjectionPlan, DirEntry, EventBus, EventStream, ExitStatus, FileSystem, FsError,
IdGenerator, MemoryError, MemoryQuery, MemoryRecall, OutputStream, PreparedContext, IdGenerator, MemoryError, MemoryQuery, MemoryRecall, OutputStream, PreparedContext,
ProfileStore, ProjectStore, PtyError, PtyHandle, PtyPort, RemotePath, ReplyEvent, ReplyStream, 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::profile::{AgentProfile, ContextInjection, StructuredAdapter};
use domain::project::{Project, ProjectPath}; use domain::project::{Project, ProjectPath};
use domain::remote::RemoteRef; use domain::remote::RemoteRef;
use domain::skill::{Skill, SkillScope}; 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 uuid::Uuid;
use application::{ use application::{
@ -772,6 +775,7 @@ fn launch_input(agent_id: AgentId) -> LaunchAgentInput {
mcp_runtime: None, mcp_runtime: None,
allow_structured_alongside_pty: false, allow_structured_alongside_pty: false,
require_structured: false, require_structured: false,
terminal_interface: None,
fresh_start: false, fresh_start: false,
managed_temp_exposure: ManagedTempExposureRequest::default(), 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é // 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 /// Profil structuré + factory câblée ⇒ `factory.start` appelé une fois, session
/// enregistrée dans `StructuredSessions`, AUCUN `pty.spawn`, `AgentLaunched` publié, /// enregistrée dans `StructuredSessions`, AUCUN `pty.spawn`, `AgentLaunched` publié,
/// `output.structured = Some(descriptor)` avec les bons champs. /// `output.structured = Some(descriptor)` avec les bons champs.

View File

@ -330,15 +330,17 @@ async fn stop_pty_kills_and_removes_session() {
.execute(StopLiveAgentInput { .execute(StopLiveAgentInput {
project: project(), project: project(),
agent_id: a, agent_id: a,
reason: None,
}) })
.await .await
.unwrap(); .unwrap();
assert_eq!(out.agent_id, a); assert_eq!(out.agent_id, a);
assert_eq!(out.session_id, sid(1)); assert!(!out.already_stopped);
assert_eq!(out.node_id, nid(100)); assert_eq!(out.stopped[0].session_id, sid(1));
assert_eq!(out.kind, LiveSessionKind::Pty); assert_eq!(out.stopped[0].node_id, nid(100));
assert_eq!(out.runtime_state, LiveRuntimeState::Stopped); 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. // Delegated to the close primitive: process killed and registry emptied.
assert_eq!(f.pty_port.kills(), vec![sid(1)]); assert_eq!(f.pty_port.kills(), vec![sid(1)]);
assert!(f.pty.is_empty(), "live session removed from the registry"); 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] #[tokio::test]
async fn stop_structured_cancels_turn_and_keeps_session() { async fn stop_structured_shuts_down_and_removes_session() {
let f = fixture(); let f = fixture();
let a = aid(10); let a = aid(10);
let (shutdown_called, cancel_called) = insert_structured(&f.structured, sid(2), a, nid(100)); 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 { .execute(StopLiveAgentInput {
project: project(), project: project(),
agent_id: a, agent_id: a,
reason: None,
}) })
.await .await
.unwrap(); .unwrap();
assert_eq!(out.session_id, sid(2)); assert_eq!(out.stopped[0].session_id, sid(2));
assert_eq!(out.kind, LiveSessionKind::Structured); assert_eq!(out.stopped[0].kind, LiveSessionKind::Structured);
assert_eq!(out.runtime_state, LiveRuntimeState::Stopped); assert_eq!(out.stopped[0].state, LiveRuntimeState::Stopped);
assert!(!cancel_called.load(Ordering::SeqCst));
assert!( assert!(
cancel_called.load(Ordering::SeqCst), shutdown_called.load(Ordering::SeqCst),
"session.cancel_current_turn() was called" "session.shutdown() must be called"
); );
assert!( assert!(f.structured.is_empty(), "live session is removed");
!shutdown_called.load(Ordering::SeqCst),
"session.shutdown() must not be called"
);
assert!(!f.structured.is_empty(), "live session is preserved");
assert_eq!( assert_eq!(
f.structured f.structured
.session_id_for_agent_in_project(project().id, &a), .session_id_for_agent_in_project(project().id, &a),
Some(sid(2)) None
); );
// No PTY was touched. // No PTY was touched.
assert!(f.pty_port.kills().is_empty()); assert!(f.pty_port.kills().is_empty());
@ -395,21 +395,46 @@ async fn stop_structured_runs_execution_cascade_best_effort() {
.execute(StopLiveAgentInput { .execute(StopLiveAgentInput {
project: project(), project: project(),
agent_id: a, agent_id: a,
reason: None,
}) })
.await .await
.unwrap(); .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_eq!(*cascade.calls.lock().unwrap(), vec![(project().id, a)]);
assert!( assert!(
cancel_called.load(Ordering::SeqCst), !cancel_called.load(Ordering::SeqCst),
"session.cancel_current_turn() was called" "session.cancel_current_turn() is not the runtime stop primitive"
); );
assert!( assert!(
!shutdown_called.load(Ordering::SeqCst), shutdown_called.load(Ordering::SeqCst),
"session.shutdown() must not be called" "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] #[tokio::test]
@ -423,6 +448,7 @@ async fn stop_pty_is_idempotent_after_success() {
.execute(StopLiveAgentInput { .execute(StopLiveAgentInput {
project: project(), project: project(),
agent_id: a, agent_id: a,
reason: None,
}) })
.await .await
.unwrap(); .unwrap();
@ -431,31 +457,31 @@ async fn stop_pty_is_idempotent_after_success() {
.execute(StopLiveAgentInput { .execute(StopLiveAgentInput {
project: project(), project: project(),
agent_id: a, agent_id: a,
reason: None,
}) })
.await .await
.unwrap(); .unwrap();
assert_eq!(first, second); assert!(!first.already_stopped);
assert_eq!(second.runtime_state, LiveRuntimeState::Stopped); assert!(second.already_stopped);
assert!(second.stopped.is_empty());
assert_eq!(f.pty_port.kills(), vec![sid(1)], "kill is not repeated"); assert_eq!(f.pty_port.kills(), vec![sid(1)], "kill is not repeated");
} }
#[tokio::test] #[tokio::test]
async fn stop_unknown_agent_is_not_found() { async fn stop_unknown_agent_is_idempotent_success() {
let f = fixture(); let f = fixture();
let err = f let out = f
.stop .stop
.execute(StopLiveAgentInput { .execute(StopLiveAgentInput {
project: project(), project: project(),
agent_id: aid(999), agent_id: aid(999),
reason: None,
}) })
.await .await
.expect_err("absent agent ⇒ NOT_FOUND"); .expect("absent agent is an idempotent success");
assert!(out.already_stopped);
assert!( assert!(out.stopped.is_empty());
matches!(err, application::AppError::NotFound(_)),
"got {err:?}"
);
assert!(f.pty_port.kills().is_empty(), "nothing killed"); assert!(f.pty_port.kills().is_empty(), "nothing killed");
} }

View File

@ -3252,6 +3252,59 @@ pub struct UpdateProjectContextRequestDto {
pub content: String, pub content: String,
} }
/// Global machine-local user settings wire contract.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserSettingsDto {
/// Default interface for newly opened agent terminals.
#[serde(default)]
pub default_agent_terminal_interface: Option<domain::DefaultAgentTerminalInterface>,
}
impl From<domain::IdeaUserSettings> for UserSettingsDto {
fn from(value: domain::IdeaUserSettings) -> Self {
Self {
default_agent_terminal_interface: value.default_agent_terminal_interface,
}
}
}
impl From<UserSettingsDto> for domain::IdeaUserSettings {
fn from(value: UserSettingsDto) -> Self {
Self {
default_agent_terminal_interface: value.default_agent_terminal_interface,
}
}
}
/// Project-owned settings wire contract.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProjectSettingsDto {
/// Optional validated project theme colour.
#[serde(default)]
pub theme_color: Option<String>,
}
impl From<domain::ProjectSettings> for ProjectSettingsDto {
fn from(value: domain::ProjectSettings) -> Self {
Self {
theme_color: value.theme_color.map(|color| color.as_str().to_owned()),
}
}
}
/// Project settings update request.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateProjectSettingsRequestDto {
/// Project registry id.
pub project_id: String,
/// New colour, or null to restore the product default.
#[serde(default)]
pub theme_color: Option<String>,
}
/// Request DTO for `launch_agent`. /// Request DTO for `launch_agent`.
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
@ -3747,6 +3800,9 @@ impl From<ReplyProgressStage> for ReplyProgressStageDto {
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct ReplyProgressDto { pub struct ReplyProgressDto {
/// Time at which the backend accepted this visible event.
#[serde(default)]
pub occurred_at_ms: Option<u64>,
/// Optional stable progress entity id for frontend upsert. /// Optional stable progress entity id for frontend upsert.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub progress_id: Option<String>, pub progress_id: Option<String>,
@ -3775,6 +3831,7 @@ pub struct ReplyProgressDto {
impl From<ReplyProgress> for ReplyProgressDto { impl From<ReplyProgress> for ReplyProgressDto {
fn from(value: ReplyProgress) -> Self { fn from(value: ReplyProgress) -> Self {
Self { Self {
occurred_at_ms: None,
progress_id: value.progress_id, progress_id: value.progress_id,
source: value.source.into(), source: value.source.into(),
kind: value.kind.into(), kind: value.kind.into(),
@ -3804,6 +3861,9 @@ pub enum ReplyChunk {
/// The user's submitted prompt, retained in live scrollback for reattach. /// The user's submitted prompt, retained in live scrollback for reattach.
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
UserPrompt { UserPrompt {
/// Time at which the backend accepted this prompt.
#[serde(default)]
at_ms: Option<u64>,
/// Submitted prompt text. /// Submitted prompt text.
text: String, text: String,
/// Display labels for attachments submitted with the prompt. /// Display labels for attachments submitted with the prompt.
@ -3816,12 +3876,18 @@ pub enum ReplyChunk {
/// An assistant text fragment (incremental chat rendering). /// An assistant text fragment (incremental chat rendering).
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
TextDelta { TextDelta {
/// Time at which the backend accepted this fragment.
#[serde(default)]
at_ms: Option<u64>,
/// The text fragment. /// The text fragment.
text: String, text: String,
}, },
/// A human-readable tool-activity badge (best-effort observability). /// A human-readable tool-activity badge (best-effort observability).
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
ToolActivity { ToolActivity {
/// Time at which the backend accepted this activity.
#[serde(default)]
at_ms: Option<u64>,
/// The human-readable activity label. /// The human-readable activity label.
label: String, label: String,
}, },
@ -3834,12 +3900,18 @@ pub enum ReplyChunk {
/// The deterministic end-of-turn chunk carrying the aggregated final content. /// The deterministic end-of-turn chunk carrying the aggregated final content.
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
Final { Final {
/// Time at which the backend accepted the terminal response.
#[serde(default)]
at_ms: Option<u64>,
/// The aggregated final content of the turn. /// The aggregated final content of the turn.
content: String, content: String,
}, },
/// A visible terminal fallback when the model stream produced no usable answer. /// A visible terminal fallback when the model stream produced no usable answer.
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
Error { Error {
/// Time at which the backend accepted the terminal error.
#[serde(default)]
at_ms: Option<u64>,
/// Human-readable explanation to render in the chat cell. /// Human-readable explanation to render in the chat cell.
message: String, message: String,
}, },
@ -4210,7 +4282,7 @@ pub struct ConversationTurnWorkPreviewDto {
/// Origin of the turn (human operator or a delegating agent). /// Origin of the turn (human operator or a delegating agent).
pub source: TicketWorkSourceDto, pub source: TicketWorkSourceDto,
/// Timestamp (epoch milliseconds) of the turn. /// Timestamp (epoch milliseconds) of the turn.
pub at_ms: u64, pub at_ms: Option<u64>,
/// Bounded excerpt of the turn text. /// Bounded excerpt of the turn text.
pub text_preview: String, pub text_preview: String,
/// Character length of the original (un-truncated) turn text. /// Character length of the original (un-truncated) turn text.
@ -4469,6 +4541,9 @@ pub struct StopLiveAgentRequestDto {
pub project_id: String, pub project_id: String,
/// Id of the running agent to stop. /// Id of the running agent to stop.
pub agent_id: String, pub agent_id: String,
/// Optional human-readable reason for the stop.
#[serde(default)]
pub reason: Option<String>,
} }
/// Response DTO for `stop_live_agent`: the torn-down session's coordinates. /// Response DTO for `stop_live_agent`: the torn-down session's coordinates.
@ -4477,11 +4552,23 @@ pub struct StopLiveAgentRequestDto {
pub struct StopLiveAgentResponseDto { pub struct StopLiveAgentResponseDto {
/// The stopped agent's id. /// The stopped agent's id.
pub agent_id: String, pub agent_id: String,
/// The id of the session that was torn down. /// Every runtime actually torn down by this request.
pub stopped: Vec<StoppedAgentRuntimeDto>,
/// True when the operation was an idempotent no-op.
pub already_stopped: bool,
}
/// One stopped runtime in an agent-level stop response.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StoppedAgentRuntimeDto {
/// Removed runtime session id.
pub session_id: String, pub session_id: String,
/// Runtime family that owned the session (`pty`/`structured`). /// Last hosting layout node id.
pub node_id: String,
/// Runtime family.
pub kind: LiveWorkSessionKindDto, pub kind: LiveWorkSessionKindDto,
/// Runtime lifecycle projection after the stop request. /// Terminal lifecycle state.
pub runtime_state: LiveRuntimeStateDto, pub runtime_state: LiveRuntimeStateDto,
} }
@ -4489,9 +4576,17 @@ impl From<StopLiveAgentOutput> for StopLiveAgentResponseDto {
fn from(out: StopLiveAgentOutput) -> Self { fn from(out: StopLiveAgentOutput) -> Self {
Self { Self {
agent_id: out.agent_id.to_string(), agent_id: out.agent_id.to_string(),
session_id: out.session_id.to_string(), stopped: out
kind: out.kind.into(), .stopped
runtime_state: out.runtime_state.into(), .into_iter()
.map(|item| StoppedAgentRuntimeDto {
session_id: item.session_id.to_string(),
node_id: item.node_id.to_string(),
kind: item.kind.into(),
runtime_state: item.state.into(),
})
.collect(),
already_stopped: out.already_stopped,
} }
} }
} }
@ -5552,7 +5647,7 @@ pub struct TurnViewDto {
/// Stable turn id (also the pagination anchor). /// Stable turn id (also the pagination anchor).
pub id: String, pub id: String,
/// Timestamp (epoch milliseconds). /// Timestamp (epoch milliseconds).
pub at_ms: u64, pub at_ms: Option<u64>,
/// Turn nature (prompt, response, tool activity). /// Turn nature (prompt, response, tool activity).
pub role: TurnRole, pub role: TurnRole,
/// Origin (human or delegating agent). /// Origin (human or delegating agent).

View File

@ -44,27 +44,28 @@ use application::{
PluginToolchainDiagnostics, PluginWorkspaceAccess, ProjectPluginResolver, ProposeContext, PluginToolchainDiagnostics, PluginWorkspaceAccess, ProjectPluginResolver, ProposeContext,
PurgeManagedTemp, QueryProjectStructure, ReadAgentContext, ReadChatDraft, ReadContext, PurgeManagedTemp, QueryProjectStructure, ReadAgentContext, ReadChatDraft, ReadContext,
ReadConversationPage, ReadIssue, ReadIssueAttachment, ReadIssueCarnet, ReadMcpToolPermissions, ReadConversationPage, ReadIssue, ReadIssueAttachment, ReadIssueCarnet, ReadMcpToolPermissions,
ReadMemory, ReadMemoryIndex, ReadOpenProjectRestoreState, ReadProjectContext, ReadSkill, ReadMemory, ReadMemoryIndex, ReadOpenProjectRestoreState, ReadProjectContext,
ReadTemplate, RecallMemory, ReconcileLayouts, ReconcileLiveState, ReconcileLiveStateInput, ReadProjectSettings, ReadSkill, ReadTemplate, ReadUserSettings, RecallMemory, ReconcileLayouts,
ReconcilePluginMcpServers, RecordProjectClosedForRestore, RecordProjectOpenedForRestore, ReconcileLiveState, ReconcileLiveStateInput, ReconcilePluginMcpServers,
RecordTurn, RecordTurnProvider, ReferenceProfiles, ReleaseManagedTemp, ReloadPlugin, RecordProjectClosedForRestore, RecordProjectOpenedForRestore, RecordTurn, RecordTurnProvider,
ReloadPluginInput, RemoveProjectFromRegistry, RenameDevice, RenameLayout, RenameSprint, ReferenceProfiles, ReleaseManagedTemp, ReloadPlugin, ReloadPluginInput,
ReorderSprints, ResizeTerminal, ResolveAgentCapabilities, ResolveAgentPermissions, RemoveProjectFromRegistry, RenameDevice, RenameLayout, RenameSprint, ReorderSprints,
ResizeTerminal, ResolveAgentCapabilities, ResolveAgentPermissions,
ResolveAgentSystemPermissions, ResolveManagedTemp, ResolveMemoryLinks, RestoreOpenProjects, ResolveAgentSystemPermissions, ResolveManagedTemp, ResolveMemoryLinks, RestoreOpenProjects,
RestoreOpenProjectsOutput, RestoreOpenWindows, RetryBackgroundTask, RetryOpenProjectRestore, RestoreOpenProjectsOutput, RestoreOpenWindows, RetryBackgroundTask, RetryOpenProjectRestore,
ReviewPluginPackage, RevokeAllDevices, RevokeDevice, RotateConversationLog, SaveChatDraft, ReviewPluginPackage, RevokeAllDevices, RevokeDevice, RotateConversationLog, SaveChatDraft,
SaveEmbedderProfile, SaveModelServer, SaveOpenCodeProviderProfile, SaveOpenProjectRestoreOrder, SaveEmbedderProfile, SaveModelServer, SaveOpenCodeProviderProfile, SaveOpenProjectRestoreOrder,
SaveProfile, SessionLimitService, SetActiveLayout, SetAgentMcpToolAllowed, SetPluginEnabled, SaveProfile, SessionLimitService, SetActiveLayout, SetAgentMcpToolAllowed, SetPluginEnabled,
SetProjectPluginEnabled, SlashCommandRegistry, SnapshotOpenWindows, SnapshotRunningAgents, SetProjectPluginEnabled, SlashCommandRegistry, SnapshotOpenWindows, SnapshotRunningAgents,
SnapshotRunningAgentsInput, SpawnBackgroundCommand, StopLiveAgent, StructuredRoutingMode, SnapshotRunningAgentsInput, SpawnBackgroundCommand, StopAgentRuntime, StructuredRoutingMode,
StructuredSessions, SuggestedThisSession, SyncAgentWithTemplate, TerminalSessions, TouchDevice, StructuredSessions, SuggestedThisSession, SyncAgentWithTemplate, TerminalSessions, TouchDevice,
UnassignSkillFromAgent, UnassignTicketFromSprint, UninstallPlugin, UnlinkIssues, UnassignSkillFromAgent, UnassignTicketFromSprint, UninstallPlugin, UnlinkIssues,
UpdateAgentContactable, UpdateAgentContext, UpdateAgentEffort, UpdateAgentMcpToolPermissions, UpdateAgentContactable, UpdateAgentContext, UpdateAgentEffort, UpdateAgentMcpToolPermissions,
UpdateAgentPermissions, UpdateAgentSystemPermissions, UpdateIssue, UpdateIssueCarnet, UpdateAgentPermissions, UpdateAgentSystemPermissions, UpdateIssue, UpdateIssueCarnet,
UpdateLiveState, UpdateMemory, UpdateProjectContext, UpdateProjectMcpToolPermissions, UpdateLiveState, UpdateMemory, UpdateProjectContext, UpdateProjectMcpToolPermissions,
UpdateProjectOrchestrator, UpdateProjectPermissions, UpdateProjectSystemPermissions, UpdateProjectOrchestrator, UpdateProjectPermissions, UpdateProjectSettings,
UpdateSkill, UpdateTemplate, WakeSessionProvider, WriteMemory, WriteToTerminal, UpdateProjectSystemPermissions, UpdateSkill, UpdateTemplate, UpdateUserSettings,
AGENT_MEMORY_RECALL_BUDGET, WakeSessionProvider, WriteMemory, WriteToTerminal, AGENT_MEMORY_RECALL_BUDGET,
}; };
use async_trait::async_trait; use async_trait::async_trait;
use domain::events::AgentRestartPhase; use domain::events::AgentRestartPhase;
@ -77,10 +78,10 @@ use domain::ports::{
McpToolPermissionStore, MemoryRecall, MemoryStore, ModelArtifactDownloader, McpToolPermissionStore, MemoryRecall, MemoryStore, ModelArtifactDownloader,
OpenProjectRestoreStore, PermissionStore, PluginManifestValidator, PluginMcpSupervisor, OpenProjectRestoreStore, PermissionStore, PluginManifestValidator, PluginMcpSupervisor,
PluginPackageStore, PluginRegistryStore, PluginStorageStore, ProcessSpawner, ProfileStore, PluginPackageStore, PluginRegistryStore, PluginStorageStore, ProcessSpawner, ProfileStore,
ProjectPluginSettingsStore, ProjectStore, PtyHandle, PtyPort, RuntimePermissionProbe, ProjectPluginSettingsStore, ProjectSettingsStore, ProjectStore, PtyHandle, PtyPort,
ScheduledTask, Scheduler, SecretStore, SkillStore, SprintStore, RuntimePermissionProbe, ScheduledTask, Scheduler, SecretStore, SkillStore, SprintStore,
StructuredSessionEnvironmentPreparer, SystemPermissionStore, TemplateStore, ToolInvoker, StructuredSessionEnvironmentPreparer, SystemPermissionStore, TemplateStore, ToolInvoker,
WakeError, WakeReason, WindowStateStore, UserSettingsStore, WakeError, WakeReason, WindowStateStore,
}; };
use domain::profile::{ use domain::profile::{
AgentProfile, ContextInjection, McpConfigStrategy, McpTransport, StructuredAdapter, AgentProfile, ContextInjection, McpConfigStrategy, McpTransport, StructuredAdapter,
@ -105,19 +106,19 @@ use infrastructure::{
FsHandoffStore, FsIssueNumberAllocator, FsIssueStore, FsLiveStateStore, FsManagedTempStore, FsHandoffStore, FsIssueNumberAllocator, FsIssueStore, FsLiveStateStore, FsManagedTempStore,
FsMcpToolPermissionStore, FsMemoryStore, FsModelServerRegistry, FsOpenProjectRestoreStore, FsMcpToolPermissionStore, FsMemoryStore, FsModelServerRegistry, FsOpenProjectRestoreStore,
FsOrchestratorWatcher, FsPermissionStore, FsPluginPackageStore, FsPluginRegistryStore, FsOrchestratorWatcher, FsPermissionStore, FsPluginPackageStore, FsPluginRegistryStore,
FsPluginStorageStore, FsProfileStore, FsProjectPluginSettingsStore, FsProjectStore, FsPluginStorageStore, FsProfileStore, FsProjectPluginSettingsStore, FsProjectSettingsStore,
FsProviderSessionStore, FsSecretStore, FsSkillStore, FsSprintStore, FsSystemPermissionStore, FsProjectStore, FsProviderSessionStore, FsSecretStore, FsSkillStore, FsSprintStore,
FsTemplateStore, FsWindowStateStore, Git2Repository, HeuristicHandoffSummarizer, FsSystemPermissionStore, FsTemplateStore, FsUserSettingsStore, FsWindowStateStore,
HfModelArtifactDownloader, HttpOpenAiCompatibleProbe, HttpProviderModelCatalogue, Git2Repository, HeuristicHandoffSummarizer, HfModelArtifactDownloader,
IdeaiContextStore, InMemoryConversationRegistry, InMemoryMailbox, InMemoryPairAttemptLimiter, HttpOpenAiCompatibleProbe, HttpProviderModelCatalogue, IdeaiContextStore,
LlamaCppRuntime, LocalEnvironmentReader, LocalFileSystem, LocalManagedProcess, InMemoryConversationRegistry, InMemoryMailbox, InMemoryPairAttemptLimiter, LlamaCppRuntime,
LocalProcessSpawner, ManagedTempToolProvider, McpServer, MediatedInbox, NaiveMemoryRecall, LocalEnvironmentReader, LocalFileSystem, LocalManagedProcess, LocalProcessSpawner,
OrchestratorWatchHandle, PortablePtyAdapter, ProcessCliVersionReader, ManagedTempToolProvider, McpServer, MediatedInbox, NaiveMemoryRecall, OrchestratorWatchHandle,
ReadOnlyRuntimePermissionProbe, RwFileGuard, StructuredSessionFactory, SystemClock, PortablePtyAdapter, ProcessCliVersionReader, ReadOnlyRuntimePermissionProbe, RwFileGuard,
SystemMillisClock, TemplateToolProvider, TicketAssistantEnvironmentPreparer, StructuredSessionFactory, SystemClock, SystemMillisClock, TemplateToolProvider,
TicketToolProvider, TokioBroadcastEventBus, TokioScheduler, ToolPolicyRegistry, UuidGenerator, TicketAssistantEnvironmentPreparer, TicketToolProvider, TokioBroadcastEventBus, TokioScheduler,
VectorMemoryRecall, DEFAULT_OLLAMA_BASE_URL, ONNX_CACHE_SUBDIR, RECOMMENDED_ONNX_MODELS, ToolPolicyRegistry, UuidGenerator, VectorMemoryRecall, DEFAULT_OLLAMA_BASE_URL,
VECTOR_HTTP_ENABLED, VECTOR_ONNX_ENABLED, ONNX_CACHE_SUBDIR, RECOMMENDED_ONNX_MODELS, VECTOR_HTTP_ENABLED, VECTOR_ONNX_ENABLED,
}; };
pub mod dto; pub mod dto;
@ -992,6 +993,7 @@ impl WakeSessionProvider for AppWakeSessionProvider {
mcp_runtime: None, mcp_runtime: None,
allow_structured_alongside_pty: true, allow_structured_alongside_pty: true,
require_structured: false, require_structured: false,
terminal_interface: None,
fresh_start: false, fresh_start: false,
managed_temp_exposure: application::ManagedTempExposureRequest::default(), managed_temp_exposure: application::ManagedTempExposureRequest::default(),
}) })
@ -1102,6 +1104,11 @@ fn self_restart_launch_input(
mcp_runtime, mcp_runtime,
allow_structured_alongside_pty: false, allow_structured_alongside_pty: false,
require_structured: context.require_structured, require_structured: context.require_structured,
terminal_interface: Some(if context.require_structured {
domain::DefaultAgentTerminalInterface::IdeaCli
} else {
domain::DefaultAgentTerminalInterface::NativeTui
}),
fresh_start: false, fresh_start: false,
managed_temp_exposure: application::ManagedTempExposureRequest::default(), managed_temp_exposure: application::ManagedTempExposureRequest::default(),
} }
@ -1124,6 +1131,11 @@ fn automatic_resume_launch_input(
mcp_runtime, mcp_runtime,
allow_structured_alongside_pty: false, allow_structured_alongside_pty: false,
require_structured: context.require_structured, require_structured: context.require_structured,
terminal_interface: Some(if context.require_structured {
domain::DefaultAgentTerminalInterface::IdeaCli
} else {
domain::DefaultAgentTerminalInterface::NativeTui
}),
fresh_start: false, fresh_start: false,
managed_temp_exposure: application::ManagedTempExposureRequest::default(), managed_temp_exposure: application::ManagedTempExposureRequest::default(),
} }
@ -1835,6 +1847,8 @@ pub struct RemoveProjectResult {
/// types — downstream code only sees the `Arc<dyn Port>` held inside the use /// types — downstream code only sees the `Arc<dyn Port>` held inside the use
/// cases. /// cases.
pub struct BackendCore { pub struct BackendCore {
/// Shared business clock used to stamp transport events at acceptance.
pub clock: Arc<dyn Clock>,
/// Trivial health use case validating the end-to-end wiring. /// Trivial health use case validating the end-to-end wiring.
pub health: Arc<HealthUseCase>, pub health: Arc<HealthUseCase>,
/// List/filter the unified slash-command registry. /// List/filter the unified slash-command registry.
@ -2095,7 +2109,7 @@ pub struct BackendCore {
/// Rebinds an already-running agent's live session to a visible cell (Lot D). /// Rebinds an already-running agent's live session to a visible cell (Lot D).
pub attach_live_agent: Arc<AttachLiveAgent>, pub attach_live_agent: Arc<AttachLiveAgent>,
/// Tears down an already-running agent's live session by agent id (Lot D). /// Tears down an already-running agent's live session by agent id (Lot D).
pub stop_live_agent: Arc<StopLiveAgent>, pub stop_live_agent: Arc<StopAgentRuntime>,
/// Best-effort inspection of a conversation (last topic + token indicator) /// Best-effort inspection of a conversation (last topic + token indicator)
/// for the resume popup (T7). Optional/extensible: backed by a `Vec` of /// for the resume popup (T7). Optional/extensible: backed by a `Vec` of
/// [`domain::ports::SessionInspector`]s; an empty/missing match yields empty /// [`domain::ports::SessionInspector`]s; an empty/missing match yields empty
@ -2103,6 +2117,14 @@ pub struct BackendCore {
pub inspect_conversation: Arc<InspectConversation>, pub inspect_conversation: Arc<InspectConversation>,
/// Project registry — used by agent commands to resolve a `Project` from an id. /// Project registry — used by agent commands to resolve a `Project` from an id.
pub project_store: Arc<dyn ProjectStore>, pub project_store: Arc<dyn ProjectStore>,
/// Reads global machine-local preferences.
pub read_user_settings: Arc<ReadUserSettings>,
/// Updates global machine-local preferences.
pub update_user_settings: Arc<UpdateUserSettings>,
/// Reads settings owned by the active project.
pub read_project_settings: Arc<ReadProjectSettings>,
/// Updates settings owned by the active project.
pub update_project_settings: Arc<UpdateProjectSettings>,
/// Read the project permission document. /// Read the project permission document.
pub get_project_permissions: Arc<GetProjectPermissions>, pub get_project_permissions: Arc<GetProjectPermissions>,
/// Update project-level default permissions. /// Update project-level default permissions.
@ -2455,6 +2477,26 @@ impl BackendCore {
// Port-typed handles for injection. // Port-typed handles for injection.
let fs_port = Arc::clone(&fs) as Arc<dyn FileSystem>; let fs_port = Arc::clone(&fs) as Arc<dyn FileSystem>;
let store_port = Arc::clone(&store) as Arc<dyn ProjectStore>; let store_port = Arc::clone(&store) as Arc<dyn ProjectStore>;
let user_settings_store = Arc::new(FsUserSettingsStore::new(
Arc::clone(&fs_port),
app_data_dir.to_string_lossy().into_owned(),
));
let user_settings_store_port =
Arc::clone(&user_settings_store) as Arc<dyn UserSettingsStore>;
let project_settings_store = Arc::new(FsProjectSettingsStore::new(Arc::clone(&fs_port)));
let project_settings_store_port =
Arc::clone(&project_settings_store) as Arc<dyn ProjectSettingsStore>;
let read_user_settings =
Arc::new(ReadUserSettings::new(Arc::clone(&user_settings_store_port)));
let update_user_settings = Arc::new(UpdateUserSettings::new(Arc::clone(
&user_settings_store_port,
)));
let read_project_settings = Arc::new(ReadProjectSettings::new(Arc::clone(
&project_settings_store_port,
)));
let update_project_settings = Arc::new(UpdateProjectSettings::new(Arc::clone(
&project_settings_store_port,
)));
let open_project_restore_store_port = let open_project_restore_store_port =
Arc::clone(&open_project_restore_store) as Arc<dyn OpenProjectRestoreStore>; Arc::clone(&open_project_restore_store) as Arc<dyn OpenProjectRestoreStore>;
let window_state_port = Arc::clone(&window_state_store) as Arc<dyn WindowStateStore>; let window_state_port = Arc::clone(&window_state_store) as Arc<dyn WindowStateStore>;
@ -3207,6 +3249,7 @@ impl BackendCore {
.with_assigned_skill_resolver(Arc::clone(&assigned_skill_resolver)) .with_assigned_skill_resolver(Arc::clone(&assigned_skill_resolver))
.with_plugin_mcp_resolver(Arc::clone(&project_plugin_resolver)) .with_plugin_mcp_resolver(Arc::clone(&project_plugin_resolver))
.with_structured_routing_mode(StructuredRoutingMode::HumanPtyFallback) .with_structured_routing_mode(StructuredRoutingMode::HumanPtyFallback)
.with_user_settings(Arc::clone(&user_settings_store_port))
.with_permission_store(Arc::clone(&permission_store_port)) .with_permission_store(Arc::clone(&permission_store_port))
.with_system_permission_store(Arc::clone(&system_permission_store_port)) .with_system_permission_store(Arc::clone(&system_permission_store_port))
// Reprise conversationnelle (lot P7) : à chaque (re)lancement, si la cellule // Reprise conversationnelle (lot P7) : à chaque (re)lancement, si la cellule
@ -4100,14 +4143,17 @@ impl BackendCore {
)) as Arc<dyn ToolInvoker>); )) as Arc<dyn ToolInvoker>);
let stop_live_agent = Arc::new( let stop_live_agent = Arc::new(
StopLiveAgent::new(Arc::clone(&live_sessions), Arc::clone(&close_terminal)) StopAgentRuntime::new(Arc::clone(&live_sessions), Arc::clone(&close_terminal))
.with_cascade( .with_cascade(
Arc::clone(&input_mediator), Arc::clone(&input_mediator),
Arc::clone(&orchestrator_service), Arc::clone(&orchestrator_service),
) )
.with_execution_cascade(Arc::clone(&orchestrator_service) .with_execution_cascade(Arc::clone(&orchestrator_service)
as Arc<dyn application::StopAgentExecutionCascade>) as Arc<dyn application::StopAgentExecutionCascade>)
.with_restart_rendezvous(Arc::clone(&restart_rendezvous)), .with_restart_rendezvous(Arc::clone(&restart_rendezvous))
.with_live_state(Arc::new(AppLiveStateProvider {
clock: Arc::clone(&clock) as Arc<dyn Clock>,
}) as Arc<dyn LiveStateProvider>),
); );
// --- Windows (L10) --- // --- Windows (L10) ---
@ -4131,6 +4177,7 @@ impl BackendCore {
)); ));
Self { Self {
clock: Arc::clone(&clock) as Arc<dyn Clock>,
health, health,
list_slash_commands, list_slash_commands,
execute_slash_command, execute_slash_command,
@ -4257,6 +4304,10 @@ impl BackendCore {
stop_live_agent, stop_live_agent,
inspect_conversation, inspect_conversation,
project_store, project_store,
read_user_settings,
update_user_settings,
read_project_settings,
update_project_settings,
get_project_permissions, get_project_permissions,
update_project_permissions, update_project_permissions,
update_agent_permissions, update_agent_permissions,

View File

@ -91,8 +91,10 @@ pub struct ConversationTurn {
pub id: TurnId, pub id: TurnId,
/// La conversation (paire) à laquelle ce tour appartient. /// La conversation (paire) à laquelle ce tour appartient.
pub conversation: ConversationId, pub conversation: ConversationId,
/// Horodatage (epoch millisecondes) du tour. /// Horodatage (epoch millisecondes) du tour. Absent uniquement pour les
pub at_ms: u64, /// lignes legacy écrites avant que l'horodatage ne devienne universel.
#[serde(default)]
pub at_ms: Option<u64>,
/// L'origine de l'entrée (Humain ou Agent délégant). /// L'origine de l'entrée (Humain ou Agent délégant).
pub source: InputSource, pub source: InputSource,
/// La nature du tour (invite, réponse, activité outillée). /// La nature du tour (invite, réponse, activité outillée).
@ -115,7 +117,7 @@ impl ConversationTurn {
Self { Self {
id, id,
conversation, conversation,
at_ms, at_ms: Some(at_ms),
source, source,
role, role,
text: text.into(), text: text.into(),

View File

@ -67,6 +67,7 @@ pub mod readiness;
pub mod remote; pub mod remote;
pub mod sandbox; pub mod sandbox;
pub mod session_limit; pub mod session_limit;
pub mod settings;
pub mod skill; pub mod skill;
pub mod slash_command; pub mod slash_command;
pub mod sprint; pub mod sprint;
@ -258,6 +259,8 @@ pub use sandbox::{
SandboxKind, SandboxPlan, SandboxStatus, SandboxKind, SandboxPlan, SandboxStatus,
}; };
pub use settings::{DefaultAgentTerminalInterface, IdeaUserSettings, ProjectSettings, ThemeColor};
pub use orchestrator::{ pub use orchestrator::{
OrchestratorCommand, OrchestratorError, OrchestratorRequest, OrchestratorVisibility, OrchestratorCommand, OrchestratorError, OrchestratorRequest, OrchestratorVisibility,
}; };
@ -277,9 +280,10 @@ pub use ports::{
PluginManifestError, PluginManifestValidator, PluginMcpError, PluginMcpSupervisor, PluginManifestError, PluginManifestValidator, PluginMcpError, PluginMcpSupervisor,
PluginPackageStore, PluginRegistryError, PluginRegistryStore, PluginStorageError, PluginPackageStore, PluginRegistryError, PluginRegistryStore, PluginStorageError,
PluginStorageStore, PluginStoreError, PreparedContext, ProcessError, ProcessSpawner, PluginStorageStore, PluginStoreError, PreparedContext, ProcessError, ProcessSpawner,
ProfileStore, ProjectPluginSettingsStore, ProjectStore, ProviderModelCatalogue, PtyError, ProfileStore, ProjectPluginSettingsStore, ProjectSettingsStore, ProjectStore,
PtyHandle, PtyPort, RemoteError, RemoteHost, RemotePath, RuntimeError, RuntimePermissionProbe, ProviderModelCatalogue, PtyError, PtyHandle, PtyPort, RemoteError, RemoteHost, RemotePath,
ScheduledTask, Scheduler, SpawnSpec, SprintStore, SprintStoreError, StoreError, RuntimeError, RuntimePermissionProbe, ScheduledTask, Scheduler, SpawnSpec, SprintStore,
StructuredSessionEnvironment, StructuredSessionEnvironmentPreparer, SystemPermissionStore, SprintStoreError, StoreError, StructuredSessionEnvironment,
TemplateStore, WindowStateStore, StructuredSessionEnvironmentPreparer, SystemPermissionStore, TemplateStore, UserSettingsStore,
WindowStateStore,
}; };

View File

@ -539,6 +539,31 @@ pub trait ProjectPluginSettingsStore: Send + Sync {
) -> Result<(), StoreError>; ) -> Result<(), StoreError>;
} }
/// Persistence for global, machine-local user settings.
#[async_trait]
pub trait UserSettingsStore: Send + Sync {
/// Loads settings, returning an empty document when missing.
async fn load(&self) -> Result<crate::IdeaUserSettings, StoreError>;
/// Persists the complete document.
async fn save(&self, settings: &crate::IdeaUserSettings) -> Result<(), StoreError>;
}
/// Persistence for settings owned by one project.
#[async_trait]
pub trait ProjectSettingsStore: Send + Sync {
/// Loads settings, returning an empty document when missing.
async fn load(
&self,
project_root: &crate::ProjectPath,
) -> Result<crate::ProjectSettings, StoreError>;
/// Persists the complete document.
async fn save(
&self,
project_root: &crate::ProjectPath,
settings: &crate::ProjectSettings,
) -> Result<(), StoreError>;
}
/// Manifest parser and validator. /// Manifest parser and validator.
pub trait PluginManifestValidator: Send + Sync { pub trait PluginManifestValidator: Send + Sync {
/// Validates raw manifest bytes. /// Validates raw manifest bytes.

View File

@ -0,0 +1,69 @@
//! Machine-local user preferences and project-owned presentation settings.
use serde::{Deserialize, Serialize};
/// Preferred interface when a new human-facing agent terminal is opened.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum DefaultAgentTerminalInterface {
/// Provider's native interactive terminal UI.
NativeTui,
/// IdeA's structured/custom CLI chat surface.
IdeaCli,
}
/// Global, machine-local IdeA preferences.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IdeaUserSettings {
/// Default for newly launched human-facing agent terminals.
#[serde(default)]
pub default_agent_terminal_interface: Option<DefaultAgentTerminalInterface>,
}
/// Strict project theme colour (`#RRGGBB`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct ThemeColor(String);
impl ThemeColor {
/// Validates and builds a project theme colour.
pub fn new(value: impl Into<String>) -> Result<Self, String> {
let value = value.into();
let valid = value.len() == 7
&& value.starts_with('#')
&& value.as_bytes()[1..].iter().all(u8::is_ascii_hexdigit);
valid
.then_some(Self(value))
.ok_or_else(|| "themeColor must match #RRGGBB".to_owned())
}
/// Returns the validated wire representation.
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl TryFrom<String> for ThemeColor {
type Error = String;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl From<ThemeColor> for String {
fn from(value: ThemeColor) -> Self {
value.0
}
}
/// Settings owned by one project and stored below its `.ideai` directory.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProjectSettings {
/// Optional visual theme colour; absence keeps the product fallback.
#[serde(default)]
pub theme_color: Option<ThemeColor>,
}

View File

@ -120,8 +120,9 @@ pub use store::{
AdaptiveMemoryRecall, BackgroundTaskReconcileReport, EmbedderEnvProbe, FsBackgroundTaskStore, AdaptiveMemoryRecall, BackgroundTaskReconcileReport, EmbedderEnvProbe, FsBackgroundTaskStore,
FsDeviceSessionStore, FsEmbedderProfileStore, FsEmbedderPromptStore, FsLiveStateStore, FsDeviceSessionStore, FsEmbedderProfileStore, FsEmbedderPromptStore, FsLiveStateStore,
FsMcpToolPermissionStore, FsMemoryStore, FsOpenProjectRestoreStore, FsPermissionStore, FsMcpToolPermissionStore, FsMemoryStore, FsOpenProjectRestoreStore, FsPermissionStore,
FsProfileStore, FsProjectStore, FsSecretStore, FsSkillStore, FsSystemPermissionStore, FsProfileStore, FsProjectSettingsStore, FsProjectStore, FsSecretStore, FsSkillStore,
FsTemplateStore, FsWindowStateStore, HashEmbedder, IdeaiContextStore, NaiveMemoryRecall, FsSystemPermissionStore, FsTemplateStore, FsUserSettingsStore, FsWindowStateStore,
OnnxModelInfo, StubEmbedder, VectorMemoryRecall, DEFAULT_OLLAMA_BASE_URL, ONNX_CACHE_SUBDIR, HashEmbedder, IdeaiContextStore, NaiveMemoryRecall, OnnxModelInfo, StubEmbedder,
RECOMMENDED_ONNX_MODELS, VECTOR_HTTP_ENABLED, VECTOR_ONNX_ENABLED, VectorMemoryRecall, DEFAULT_OLLAMA_BASE_URL, ONNX_CACHE_SUBDIR, RECOMMENDED_ONNX_MODELS,
VECTOR_HTTP_ENABLED, VECTOR_ONNX_ENABLED,
}; };

View File

@ -17,6 +17,7 @@ mod profile;
mod project; mod project;
mod project_plugin; mod project_plugin;
mod secrets; mod secrets;
mod settings;
mod skill; mod skill;
mod system_permission; mod system_permission;
mod template; mod template;
@ -44,6 +45,7 @@ pub use profile::{FsEmbedderProfileStore, FsProfileStore};
pub use project::FsProjectStore; pub use project::FsProjectStore;
pub use project_plugin::FsProjectPluginSettingsStore; pub use project_plugin::FsProjectPluginSettingsStore;
pub use secrets::FsSecretStore; pub use secrets::FsSecretStore;
pub use settings::{FsProjectSettingsStore, FsUserSettingsStore};
pub use skill::FsSkillStore; pub use skill::FsSkillStore;
pub use system_permission::FsSystemPermissionStore; pub use system_permission::FsSystemPermissionStore;
pub use template::FsTemplateStore; pub use template::FsTemplateStore;

View File

@ -0,0 +1,104 @@
//! JSON persistence for global user settings and project-owned settings.
use async_trait::async_trait;
use domain::{
FileSystem, FsError, IdeaUserSettings, ProjectPath, ProjectSettings, ProjectSettingsStore,
RemotePath, StoreError, UserSettingsStore,
};
use std::sync::Arc;
#[derive(Clone)]
/// File-backed global user-settings adapter.
pub struct FsUserSettingsStore {
fs: Arc<dyn FileSystem>,
app_data_dir: String,
}
impl FsUserSettingsStore {
/// Builds an adapter rooted in the machine-local application data directory.
#[must_use]
pub fn new(fs: Arc<dyn FileSystem>, app_data_dir: impl Into<String>) -> Self {
Self {
fs,
app_data_dir: app_data_dir.into(),
}
}
fn path(&self) -> RemotePath {
RemotePath::new(format!(
"{}/settings.json",
self.app_data_dir.trim_end_matches(['/', '\\'])
))
}
}
#[async_trait]
impl UserSettingsStore for FsUserSettingsStore {
async fn load(&self) -> Result<IdeaUserSettings, StoreError> {
match self.fs.read(&self.path()).await {
Ok(bytes) => {
serde_json::from_slice(&bytes).map_err(|e| StoreError::Serialization(e.to_string()))
}
Err(FsError::NotFound(_)) => Ok(IdeaUserSettings::default()),
Err(error) => Err(StoreError::Io(error.to_string())),
}
}
async fn save(&self, settings: &IdeaUserSettings) -> Result<(), StoreError> {
self.fs
.create_dir_all(&RemotePath::new(self.app_data_dir.clone()))
.await
.map_err(|e| StoreError::Io(e.to_string()))?;
let mut bytes = serde_json::to_vec_pretty(settings)
.map_err(|e| StoreError::Serialization(e.to_string()))?;
bytes.push(b'\n');
self.fs
.write(&self.path(), &bytes)
.await
.map_err(|e| StoreError::Io(e.to_string()))
}
}
#[derive(Clone)]
/// File-backed project-settings adapter.
pub struct FsProjectSettingsStore {
fs: Arc<dyn FileSystem>,
}
impl FsProjectSettingsStore {
/// Builds an adapter over the location-neutral filesystem port.
#[must_use]
pub fn new(fs: Arc<dyn FileSystem>) -> Self {
Self { fs }
}
fn path(root: &ProjectPath) -> RemotePath {
RemotePath::new(format!(
"{}/.ideai/project-settings.json",
root.as_str().trim_end_matches(['/', '\\'])
))
}
}
#[async_trait]
impl ProjectSettingsStore for FsProjectSettingsStore {
async fn load(&self, root: &ProjectPath) -> Result<ProjectSettings, StoreError> {
match self.fs.read(&Self::path(root)).await {
Ok(bytes) => {
serde_json::from_slice(&bytes).map_err(|e| StoreError::Serialization(e.to_string()))
}
Err(FsError::NotFound(_)) => Ok(ProjectSettings::default()),
Err(error) => Err(StoreError::Io(error.to_string())),
}
}
async fn save(&self, root: &ProjectPath, settings: &ProjectSettings) -> Result<(), StoreError> {
let dir = RemotePath::new(format!(
"{}/.ideai",
root.as_str().trim_end_matches(['/', '\\'])
));
self.fs
.create_dir_all(&dir)
.await
.map_err(|e| StoreError::Io(e.to_string()))?;
let mut bytes = serde_json::to_vec_pretty(settings)
.map_err(|e| StoreError::Serialization(e.to_string()))?;
bytes.push(b'\n');
self.fs
.write(&Self::path(root), &bytes)
.await
.map_err(|e| StoreError::Io(e.to_string()))
}
}

View File

@ -133,6 +133,26 @@ async fn append_writes_one_valid_json_line_per_turn() {
} }
} }
#[tokio::test]
async fn legacy_line_without_timestamp_remains_readable_without_backfill() {
let tmp = TempDir::new();
let c = conv_id(91);
std::fs::create_dir_all(tmp.conversation_dir(c)).unwrap();
let raw = format!(
"{{\"id\":\"{}\",\"conversation\":\"{}\",\"source\":{{\"kind\":\"human\"}},\"role\":\"prompt\",\"text\":\"legacy\"}}\n",
turn_id(1), c
);
std::fs::write(tmp.log_path(c), &raw).unwrap();
let turns = FsConversationLog::new(&tmp.project_path())
.read(c, None)
.await
.unwrap();
assert_eq!(turns.len(), 1);
assert_eq!(turns[0].at_ms, None);
assert_eq!(std::fs::read_to_string(tmp.log_path(c)).unwrap(), raw);
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// survives a "restart" — a fresh instance on the same root relits everything // survives a "restart" — a fresh instance on the same root relits everything
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------

View File

@ -0,0 +1,74 @@
use std::path::PathBuf;
use std::sync::Arc;
use domain::{
DefaultAgentTerminalInterface, FileSystem, IdeaUserSettings, ProjectPath, ProjectSettings,
ProjectSettingsStore, ThemeColor, UserSettingsStore,
};
use infrastructure::{FsProjectSettingsStore, FsUserSettingsStore, LocalFileSystem};
use uuid::Uuid;
struct TempDir(PathBuf);
impl TempDir {
fn new() -> Self {
let path = std::env::temp_dir().join(format!("idea-settings-{}", Uuid::new_v4()));
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
fn root(&self) -> ProjectPath {
ProjectPath::new(self.0.to_string_lossy().into_owned()).unwrap()
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn fs() -> Arc<dyn FileSystem> {
Arc::new(LocalFileSystem::new())
}
#[tokio::test]
async fn global_user_preference_persists_outside_project() {
let tmp = TempDir::new();
let store = FsUserSettingsStore::new(fs(), tmp.0.to_string_lossy());
assert_eq!(store.load().await.unwrap(), IdeaUserSettings::default());
let settings = IdeaUserSettings {
default_agent_terminal_interface: Some(DefaultAgentTerminalInterface::IdeaCli),
};
store.save(&settings).await.unwrap();
assert_eq!(
FsUserSettingsStore::new(fs(), tmp.0.to_string_lossy())
.load()
.await
.unwrap(),
settings
);
assert!(tmp.0.join("settings.json").is_file());
assert!(!tmp.0.join(".ideai").exists());
}
#[tokio::test]
async fn project_settings_missing_then_valid_round_trip() {
let tmp = TempDir::new();
let store = FsProjectSettingsStore::new(fs());
assert_eq!(
store.load(&tmp.root()).await.unwrap(),
ProjectSettings::default()
);
assert!(!tmp.0.join(".ideai/project-settings.json").exists());
let settings = ProjectSettings {
theme_color: Some(ThemeColor::new("#12AbEF").unwrap()),
};
store.save(&tmp.root(), &settings).await.unwrap();
assert_eq!(store.load(&tmp.root()).await.unwrap(), settings);
assert!(!tmp.0.join(".ideai/CONTEXT.md").exists());
}
#[test]
fn theme_color_validation_is_strict() {
assert!(ThemeColor::new("#112233").is_ok());
for invalid in ["112233", "#123", "#GG0000", "#11223344", "# 12233"] {
assert!(ThemeColor::new(invalid).is_err(), "accepted {invalid}");
}
}

View File

@ -93,7 +93,7 @@ use backend::dto::{
MemoryDto, MemoryIndexDto, MemoryLinksDto, MemoryListDto, OpenCodeProviderListDto, MemoryDto, MemoryIndexDto, MemoryLinksDto, MemoryListDto, OpenCodeProviderListDto,
OpenProjectRestoreStateDto, OpenTerminalRequestDto, ProfileDto, ProfileListDto, OpenProjectRestoreStateDto, OpenTerminalRequestDto, ProfileDto, ProfileListDto,
ProfileModelCatalogDto, ProjectDto, ProjectListDto, ProjectMcpToolPermissionsDto, ProfileModelCatalogDto, ProjectDto, ProjectListDto, ProjectMcpToolPermissionsDto,
ProjectPermissionsDto, ProjectSystemPermissionsDto, ProjectWorkStateDto, ProjectPermissionsDto, ProjectSettingsDto, ProjectSystemPermissionsDto, ProjectWorkStateDto,
ReadAgentContextResponseDto, ReadConversationPageRequestDto, RecallMemoryRequestDto, ReadAgentContextResponseDto, ReadConversationPageRequestDto, RecallMemoryRequestDto,
RemoveOpenProjectRestoreEntryRequestDto, RemoveProjectRequestDto, RemoveProjectResponseDto, RemoveOpenProjectRestoreEntryRequestDto, RemoveProjectRequestDto, RemoveProjectResponseDto,
RenameLayoutRequestDto, ResolveAgentPermissionsRequestDto, ResolveAgentPermissionsResponseDto, RenameLayoutRequestDto, ResolveAgentPermissionsRequestDto, ResolveAgentPermissionsResponseDto,
@ -116,7 +116,8 @@ use backend::dto::{
UpdateAgentMcpToolPermissionsRequestDto, UpdateAgentPermissionsRequestDto, UpdateAgentMcpToolPermissionsRequestDto, UpdateAgentPermissionsRequestDto,
UpdateAgentSystemPermissionsRequestDto, UpdateMemoryRequestDto, UpdateProjectContextRequestDto, UpdateAgentSystemPermissionsRequestDto, UpdateMemoryRequestDto, UpdateProjectContextRequestDto,
UpdateProjectMcpToolPermissionsRequestDto, UpdateProjectPermissionsRequestDto, UpdateProjectMcpToolPermissionsRequestDto, UpdateProjectPermissionsRequestDto,
UpdateProjectSystemPermissionsRequestDto, UpdateSkillRequestDto, UpdateTemplateRequestDto, UpdateProjectSettingsRequestDto, UpdateProjectSystemPermissionsRequestDto,
UpdateSkillRequestDto, UpdateTemplateRequestDto, UserSettingsDto,
}; };
use backend::events::DomainEventDto; use backend::events::DomainEventDto;
type PtyChunk = Vec<u8>; type PtyChunk = Vec<u8>;
@ -1647,6 +1648,10 @@ async fn execute_launch_agent_for_ws(
mcp_runtime, mcp_runtime,
allow_structured_alongside_pty: false, allow_structured_alongside_pty: false,
require_structured: request.cell_kind == Some(backend::dto::CellKind::Chat), require_structured: request.cell_kind == Some(backend::dto::CellKind::Chat),
terminal_interface: request.cell_kind.map(|kind| match kind {
backend::dto::CellKind::Pty => domain::DefaultAgentTerminalInterface::NativeTui,
backend::dto::CellKind::Chat => domain::DefaultAgentTerminalInterface::IdeaCli,
}),
fresh_start: request.fresh_start, fresh_start: request.fresh_start,
managed_temp_exposure: application::ManagedTempExposureRequest::default(), managed_temp_exposure: application::ManagedTempExposureRequest::default(),
}) })
@ -1919,6 +1924,7 @@ async fn ws_send_chat(
let (tap_tx, tap_rx) = std::sync::mpsc::channel(); let (tap_tx, tap_rx) = std::sync::mpsc::channel();
let tap_out = tx.clone(); let tap_out = tx.clone();
let tap_clock = Arc::clone(&state.app.clock);
let tap_turn_guard = turn_guard.as_ref().map(|guard| guard.liveness_handle()); let tap_turn_guard = turn_guard.as_ref().map(|guard| guard.liveness_handle());
let tap_pump = std::thread::spawn(move || { let tap_pump = std::thread::spawn(move || {
for event in tap_rx { for event in tap_rx {
@ -1930,7 +1936,7 @@ async fn ws_send_chat(
if matches!(event, ReplyEvent::Final { .. } | ReplyEvent::Error { .. }) { if matches!(event, ReplyEvent::Final { .. } | ReplyEvent::Error { .. }) {
continue; continue;
} }
let chunk = reply_event_chunk(event); let chunk = reply_event_chunk(event, u64::try_from(tap_clock.now_millis()).ok());
if tap_out if tap_out
.blocking_send(ServerFrame::chat_output(None, sid, chunk)) .blocking_send(ServerFrame::chat_output(None, sid, chunk))
.is_err() .is_err()
@ -1978,7 +1984,10 @@ async fn ws_send_chat(
break; break;
} }
backend::StructuredHumanTurnTransition::Failed(message) => { backend::StructuredHumanTurnTransition::Failed(message) => {
let chunk = reply_event_chunk(ReplyEvent::Error { message }); let chunk = reply_event_chunk(
ReplyEvent::Error { message },
u64::try_from(state.app.clock.now_millis()).ok(),
);
tx.send(ServerFrame::chat_output( tx.send(ServerFrame::chat_output(
(!sent_ack).then_some(frame.id.as_str()), (!sent_ack).then_some(frame.id.as_str()),
sid, sid,
@ -2002,7 +2011,7 @@ async fn ws_send_chat(
guard.mark_alive(); guard.mark_alive();
} }
} }
let chunk = reply_event_chunk(event); let chunk = reply_event_chunk(event, u64::try_from(state.app.clock.now_millis()).ok());
if !sent_ack { if !sent_ack {
tx.send(ServerFrame::chat_output(Some(&frame.id), sid, chunk)) tx.send(ServerFrame::chat_output(Some(&frame.id), sid, chunk))
.await .await
@ -2030,7 +2039,10 @@ async fn ws_send_chat(
resume_prompt = Some(prompt); resume_prompt = Some(prompt);
} }
backend::StructuredHumanTurnTransition::Failed(message) => { backend::StructuredHumanTurnTransition::Failed(message) => {
let chunk = reply_event_chunk(ReplyEvent::Error { message }); let chunk = reply_event_chunk(
ReplyEvent::Error { message },
u64::try_from(state.app.clock.now_millis()).ok(),
);
tx.send(ServerFrame::chat_output( tx.send(ServerFrame::chat_output(
(!sent_ack).then_some(frame.id.as_str()), (!sent_ack).then_some(frame.id.as_str()),
sid, sid,
@ -2076,7 +2088,7 @@ async fn ws_send_chat(
tx.send(ServerFrame::chat_output( tx.send(ServerFrame::chat_output(
Some(&frame.id), Some(&frame.id),
sid, sid,
json!({ "kind": "final", "content": "" }), json!({ "kind": "final", "content": "", "atMs": u64::try_from(state.app.clock.now_millis()).ok() }),
)) ))
.await .await
.map_err(|_| ErrorDto { .map_err(|_| ErrorDto {
@ -2112,16 +2124,20 @@ fn ws_detach_chat(
Ok(()) Ok(())
} }
fn reply_event_chunk(event: ReplyEvent) -> Value { fn reply_event_chunk(event: ReplyEvent, occurred_at_ms: Option<u64>) -> Value {
match event { match event {
ReplyEvent::TextDelta { text } => json!({ "kind": "textDelta", "text": text }), ReplyEvent::TextDelta { text } => {
json!({ "kind": "textDelta", "text": text, "atMs": occurred_at_ms })
}
ReplyEvent::ToolActivity { label } => { ReplyEvent::ToolActivity { label } => {
json!({ "kind": "toolActivity", "label": label }) json!({ "kind": "toolActivity", "label": label, "atMs": occurred_at_ms })
} }
ReplyEvent::Progress { progress } => { ReplyEvent::Progress { progress } => {
json!({ "kind": "progress", "progress": reply_progress_value(progress) }) json!({ "kind": "progress", "progress": reply_progress_value(progress, occurred_at_ms) })
}
ReplyEvent::Announcement { text } => {
json!({ "kind": "textDelta", "text": text, "atMs": occurred_at_ms })
} }
ReplyEvent::Announcement { text } => json!({ "kind": "textDelta", "text": text }),
ReplyEvent::Heartbeat => json!({ ReplyEvent::Heartbeat => json!({
"kind": "progress", "kind": "progress",
"progress": { "progress": {
@ -2129,6 +2145,7 @@ fn reply_event_chunk(event: ReplyEvent) -> Value {
"kind": "other", "kind": "other",
"stage": "info", "stage": "info",
"label": "heartbeat" "label": "heartbeat"
,"occurredAtMs": occurred_at_ms
} }
}), }),
ReplyEvent::RateLimited { resets_at_ms } => json!({ ReplyEvent::RateLimited { resets_at_ms } => json!({
@ -2138,15 +2155,20 @@ fn reply_event_chunk(event: ReplyEvent) -> Value {
"kind": "turn", "kind": "turn",
"stage": "info", "stage": "info",
"label": "rate_limited", "label": "rate_limited",
"occurredAtMs": resets_at_ms "occurredAtMs": occurred_at_ms,
"resetsAtMs": resets_at_ms
} }
}), }),
ReplyEvent::Error { message } => json!({ "kind": "error", "message": message }), ReplyEvent::Error { message } => {
ReplyEvent::Final { content } => json!({ "kind": "final", "content": content }), json!({ "kind": "error", "message": message, "atMs": occurred_at_ms })
}
ReplyEvent::Final { content } => {
json!({ "kind": "final", "content": content, "atMs": occurred_at_ms })
}
} }
} }
fn reply_progress_value(progress: ReplyProgress) -> Value { fn reply_progress_value(progress: ReplyProgress, occurred_at_ms: Option<u64>) -> Value {
json!({ json!({
"progressId": progress.progress_id, "progressId": progress.progress_id,
"source": reply_progress_source(progress.source), "source": reply_progress_source(progress.source),
@ -2157,6 +2179,7 @@ fn reply_progress_value(progress: ReplyProgress) -> Value {
"provider": progress.provider, "provider": progress.provider,
"nativeEvent": progress.native_event, "nativeEvent": progress.native_event,
"toolName": progress.tool_name, "toolName": progress.tool_name,
"occurredAtMs": occurred_at_ms,
}) })
} }
@ -3370,6 +3393,12 @@ async fn invoke(
"set_active_layout" => invoke_set_active_layout(&request.args, &state.app).await, "set_active_layout" => invoke_set_active_layout(&request.args, &state.app).await,
"read_project_context" => invoke_read_project_context(&request.args, &state.app).await, "read_project_context" => invoke_read_project_context(&request.args, &state.app).await,
"update_project_context" => invoke_update_project_context(&request.args, &state.app).await, "update_project_context" => invoke_update_project_context(&request.args, &state.app).await,
"read_user_settings" => invoke_read_user_settings(&state.app).await,
"update_user_settings" => invoke_update_user_settings(&request.args, &state.app).await,
"read_project_settings" => invoke_read_project_settings(&request.args, &state.app).await,
"update_project_settings" => {
invoke_update_project_settings(&request.args, &state.app).await
}
"first_run_state" => invoke_first_run_state(&state.app).await, "first_run_state" => invoke_first_run_state(&state.app).await,
"reference_profiles" => invoke_reference_profiles(&state.app).await, "reference_profiles" => invoke_reference_profiles(&state.app).await,
"detect_profiles" => invoke_detect_profiles(&request.args, &state.app).await, "detect_profiles" => invoke_detect_profiles(&request.args, &state.app).await,
@ -3803,6 +3832,66 @@ async fn invoke_update_project_context(
Ok(Value::Null) Ok(Value::Null)
} }
async fn invoke_read_user_settings(state: &BackendCore) -> Result<Value, ErrorDto> {
let output: UserSettingsDto = state
.read_user_settings
.execute()
.await
.map_err(ErrorDto::from)?
.into();
serde_json::to_value(output).map_err(serialization_error)
}
async fn invoke_update_user_settings(args: &Value, state: &BackendCore) -> Result<Value, ErrorDto> {
let request = required_request::<UserSettingsDto>("update_user_settings", args)?;
let output: UserSettingsDto = state
.update_user_settings
.execute(request.into())
.await
.map_err(ErrorDto::from)?
.into();
serde_json::to_value(output).map_err(serialization_error)
}
async fn invoke_read_project_settings(
args: &Value,
state: &BackendCore,
) -> Result<Value, ErrorDto> {
let project = resolve_project_readonly(
string_arg(args, "projectId", "read_project_settings")?,
state,
)
.await?;
let output: ProjectSettingsDto = state
.read_project_settings
.execute(&project)
.await
.map_err(ErrorDto::from)?
.into();
serde_json::to_value(output).map_err(serialization_error)
}
async fn invoke_update_project_settings(
args: &Value,
state: &BackendCore,
) -> Result<Value, ErrorDto> {
let request =
required_request::<UpdateProjectSettingsRequestDto>("update_project_settings", args)?;
let project = resolve_project_readonly(&request.project_id, state).await?;
let theme_color = request
.theme_color
.map(domain::ThemeColor::new)
.transpose()
.map_err(|message| ErrorDto::from(AppError::Invalid(message)))?;
let output: ProjectSettingsDto = state
.update_project_settings
.execute(&project, domain::ProjectSettings { theme_color })
.await
.map_err(ErrorDto::from)?
.into();
serde_json::to_value(output).map_err(serialization_error)
}
async fn invoke_first_run_state(state: &BackendCore) -> Result<Value, ErrorDto> { async fn invoke_first_run_state(state: &BackendCore) -> Result<Value, ErrorDto> {
let output = state let output = state
.first_run_state .first_run_state
@ -3991,6 +4080,7 @@ async fn invoke_stop_live_agent(args: &Value, state: &BackendCore) -> Result<Val
.execute(StopLiveAgentInput { .execute(StopLiveAgentInput {
project, project,
agent_id: parse_agent_id(&request.agent_id)?, agent_id: parse_agent_id(&request.agent_id)?,
reason: request.reason,
}) })
.await .await
.map(StopLiveAgentResponseDto::from) .map(StopLiveAgentResponseDto::from)
@ -8021,22 +8111,19 @@ mod tests {
assert_eq!(ack.kind, "chat.output"); assert_eq!(ack.kind, "chat.output");
assert_eq!(ack.reply_to.as_deref(), Some("chat-send")); assert_eq!(ack.reply_to.as_deref(), Some("chat-send"));
assert_eq!(ack.payload["sessionId"], session_id.to_string()); assert_eq!(ack.payload["sessionId"], session_id.to_string());
assert_eq!( assert_eq!(ack.payload["chunk"]["kind"], "textDelta");
ack.payload["chunk"], assert_eq!(ack.payload["chunk"]["text"], "Hello ");
json!({ "kind": "textDelta", "text": "Hello " }) assert!(ack.payload["chunk"]["atMs"].is_number());
);
assert_eq!(tool.kind, "chat.output"); assert_eq!(tool.kind, "chat.output");
assert!(tool.reply_to.is_none()); assert!(tool.reply_to.is_none());
assert_eq!( assert_eq!(tool.payload["chunk"]["kind"], "toolActivity");
tool.payload["chunk"], assert_eq!(tool.payload["chunk"]["label"], "read_file");
json!({ "kind": "toolActivity", "label": "read_file" }) assert!(tool.payload["chunk"]["atMs"].is_number());
);
assert_eq!(final_chunk.kind, "chat.output"); assert_eq!(final_chunk.kind, "chat.output");
assert!(final_chunk.reply_to.is_none()); assert!(final_chunk.reply_to.is_none());
assert_eq!( assert_eq!(final_chunk.payload["chunk"]["kind"], "final");
final_chunk.payload["chunk"], assert_eq!(final_chunk.payload["chunk"]["content"], "Hello back");
json!({ "kind": "final", "content": "Hello back" }) assert!(final_chunk.payload["chunk"]["atMs"].is_number());
);
assert_eq!( assert_eq!(
session.prompts.lock().unwrap().as_slice(), session.prompts.lock().unwrap().as_slice(),
&["Salut".to_owned()] &["Salut".to_owned()]
@ -8087,10 +8174,9 @@ mod tests {
assert_eq!(final_chunk.kind, "chat.output"); assert_eq!(final_chunk.kind, "chat.output");
assert_eq!(final_chunk.reply_to.as_deref(), Some("chat-send-busy")); assert_eq!(final_chunk.reply_to.as_deref(), Some("chat-send-busy"));
assert_eq!( assert_eq!(final_chunk.payload["chunk"]["kind"], "final");
final_chunk.payload["chunk"], assert_eq!(final_chunk.payload["chunk"]["content"], "released");
json!({ "kind": "final", "content": "released" }) assert!(final_chunk.payload["chunk"]["atMs"].is_number());
);
assert!( assert!(
!state.app.turn_watch_input.busy_state(runtime_key).is_busy(), !state.app.turn_watch_input.busy_state(runtime_key).is_busy(),
"direct structured human turn should be idle after final" "direct structured human turn should be idle after final"
@ -8161,10 +8247,9 @@ mod tests {
"idea_ask_agent" "idea_ask_agent"
); );
assert_eq!(final_chunk.reply_to.as_deref(), Some("chat-send-progress")); assert_eq!(final_chunk.reply_to.as_deref(), Some("chat-send-progress"));
assert_eq!( assert_eq!(final_chunk.payload["chunk"]["kind"], "final");
final_chunk.payload["chunk"], assert_eq!(final_chunk.payload["chunk"]["content"], "done");
json!({ "kind": "final", "content": "done" }) assert!(final_chunk.payload["chunk"]["atMs"].is_number());
);
} }
#[tokio::test] #[tokio::test]
@ -10262,6 +10347,49 @@ mod tests {
assert_eq!(tasks[0]["state"], "queued"); assert_eq!(tasks[0]["state"], "queued");
} }
#[tokio::test]
async fn authorized_settings_invoke_round_trips_user_and_project_contracts() {
let state = state();
let project_id = create_project_for_test(&state, "Settings Round Trip").await;
let cookie = pair_and_cookie(Arc::clone(&state)).await;
let (status, initial_user) =
invoke_request_for_test(Arc::clone(&state), &cookie, "read_user_settings", json!({}))
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(initial_user["defaultAgentTerminalInterface"], Value::Null);
let (status, saved_user) = invoke_request_for_test(
Arc::clone(&state),
&cookie,
"update_user_settings",
json!({ "request": { "defaultAgentTerminalInterface": "ideaCli" } }),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(saved_user["defaultAgentTerminalInterface"], "ideaCli");
let (status, initial_project) = invoke_request_for_test(
Arc::clone(&state),
&cookie,
"read_project_settings",
json!({ "projectId": project_id }),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(initial_project["themeColor"], Value::Null);
let (status, saved_project) = invoke_request_for_test(
Arc::clone(&state),
&cookie,
"update_project_settings",
json!({ "request": { "projectId": project_id, "themeColor": "#AA3366" } }),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(saved_project["themeColor"], "#AA3366");
}
#[tokio::test] #[tokio::test]
async fn ticket_and_sprint_commands_require_authenticated_invoke() { async fn ticket_and_sprint_commands_require_authenticated_invoke() {
let state = state(); let state = state();

View File

@ -82,14 +82,19 @@ describe("TauriAgentGateway invoke payloads", () => {
it("stop_live_agent wraps project and agent in the request DTO", async () => { it("stop_live_agent wraps project and agent in the request DTO", async () => {
invoke.mockResolvedValueOnce({ invoke.mockResolvedValueOnce({
agentId: "agent-2", agentId: "agent-2",
stopped: [{
sessionId: "session-4", sessionId: "session-4",
nodeId: "node-3",
kind: "pty", kind: "pty",
runtimeState: "stopped",
}],
alreadyStopped: false,
}); });
const out = await new TauriAgentGateway().stopLiveAgent("proj-1", "agent-2"); const out = await new TauriAgentGateway().stopLiveAgent("proj-1", "agent-2");
expect(invoke).toHaveBeenCalledWith("stop_live_agent", { expect(invoke).toHaveBeenCalledWith("stop_live_agent", {
request: { projectId: "proj-1", agentId: "agent-2" }, request: { projectId: "proj-1", agentId: "agent-2" },
}); });
expect(out.sessionId).toBe("session-4"); expect(out.stopped[0]?.sessionId).toBe("session-4");
}); });
it("change_agent_profile wraps all five fields in the request DTO (camelCase)", async () => { it("change_agent_profile wraps all five fields in the request DTO (camelCase)", async () => {

View File

@ -98,9 +98,9 @@ export class TauriAgentGateway implements AgentGateway {
}); });
} }
stopLiveAgent(projectId: string, agentId: string): Promise<StoppedLiveAgent> { stopLiveAgent(projectId: string, agentId: string, reason?: string): Promise<StoppedLiveAgent> {
return invoke<StoppedLiveAgent>("stop_live_agent", { return invoke<StoppedLiveAgent>("stop_live_agent", {
request: { projectId, agentId }, request: { projectId, agentId, ...(reason ? { reason } : {}) },
}); });
} }

View File

@ -47,7 +47,7 @@ function normalizeTurn(value: unknown, index: number): TurnView {
const text = stringValue(turn.text); const text = stringValue(turn.text);
return { return {
id: stringValue(turn.id, `turn-${index}`), id: stringValue(turn.id, `turn-${index}`),
atMs: numberValue(turn.atMs, index), atMs: typeof turn.atMs === "number" && Number.isFinite(turn.atMs) ? turn.atMs : null,
role: normalizeRole(turn.role), role: normalizeRole(turn.role),
source: normalizeSource(turn.source), source: normalizeSource(turn.source),
text, text,

View File

@ -14,7 +14,7 @@
* error or an inert stub, never a Tauri call. * error or an inert stub, never a Tauri call.
*/ */
import type { Gateways } from "@/ports"; import type { Gateways, UserSettings, UserSettingsGateway } from "@/ports";
import { LocalStorageUiPreferencesGateway } from "../uiPreferences"; import { LocalStorageUiPreferencesGateway } from "../uiPreferences";
import { HttpInvoker } from "./httpInvoker"; import { HttpInvoker } from "./httpInvoker";
import { WsLiveClient } from "./wsLiveClient"; import { WsLiveClient } from "./wsLiveClient";
@ -146,6 +146,7 @@ export function createHttpWsGateways(config: HttpWsGatewaysConfig = {}): Gateway
focusedProject: new WebFocusedProjectGateway(), focusedProject: new WebFocusedProjectGateway(),
// Frontend-owned UI prefs are transport-neutral (localStorage) — reuse as-is. // Frontend-owned UI prefs are transport-neutral (localStorage) — reuse as-is.
uiPreferences: new LocalStorageUiPreferencesGateway(), uiPreferences: new LocalStorageUiPreferencesGateway(),
userSettings: new HttpUserSettingsGateway(http),
plugin: new WebPluginGateway(), plugin: new WebPluginGateway(),
pluginWorkspace: new WebPluginWorkspaceGateway(), pluginWorkspace: new WebPluginWorkspaceGateway(),
pluginTask: new WebPluginTaskGateway(), pluginTask: new WebPluginTaskGateway(),
@ -156,6 +157,18 @@ export function createHttpWsGateways(config: HttpWsGatewaysConfig = {}): Gateway
}; };
} }
class HttpUserSettingsGateway implements UserSettingsGateway {
constructor(private readonly http: HttpInvoker) {}
readUserSettings(): Promise<UserSettings> {
return this.http.invoke<UserSettings>("read_user_settings");
}
updateUserSettings(settings: UserSettings): Promise<UserSettings> {
return this.http.invoke<UserSettings>("update_user_settings", { request: settings });
}
}
export { HttpInvoker } from "./httpInvoker"; export { HttpInvoker } from "./httpInvoker";
export { WsLiveClient } from "./wsLiveClient"; export { WsLiveClient } from "./wsLiveClient";
export { WebSession, getWebSession, setWebSessionForTests } from "./webSession"; export { WebSession, getWebSession, setWebSessionForTests } from "./webSession";

View File

@ -73,6 +73,7 @@ import type {
PermissionGateway, PermissionGateway,
ProfileGateway, ProfileGateway,
ProjectGateway, ProjectGateway,
ProjectSettings,
SaveOpenCodeProviderProfileInput, SaveOpenCodeProviderProfileInput,
SkillGateway, SkillGateway,
TemplateGateway, TemplateGateway,
@ -134,6 +135,14 @@ export class HttpProjectGateway implements ProjectGateway {
async updateProjectContext(projectId: string, content: string): Promise<void> { async updateProjectContext(projectId: string, content: string): Promise<void> {
await this.http.invoke("update_project_context", { request: { projectId, content } }); await this.http.invoke("update_project_context", { request: { projectId, content } });
} }
readProjectSettings(projectId: string): Promise<ProjectSettings> {
return this.http.invoke<ProjectSettings>("read_project_settings", { projectId });
}
updateProjectSettings(projectId: string, settings: ProjectSettings): Promise<ProjectSettings> {
return this.http.invoke<ProjectSettings>("update_project_settings", {
request: { projectId, themeColor: settings.themeColor },
});
}
listProjectFiles(projectId: string, path: string): Promise<ProjectFileListing> { listProjectFiles(projectId: string, path: string): Promise<ProjectFileListing> {
return this.http.request<ProjectFileListing>( return this.http.request<ProjectFileListing>(
"GET", "GET",

View File

@ -216,8 +216,10 @@ export class HttpAgentGateway implements AgentGateway {
attachLiveAgent(projectId: string, agentId: string, nodeId: string): Promise<LiveAgent> { attachLiveAgent(projectId: string, agentId: string, nodeId: string): Promise<LiveAgent> {
return this.http.invoke<LiveAgent>("attach_live_agent", { request: { projectId, agentId, nodeId } }); return this.http.invoke<LiveAgent>("attach_live_agent", { request: { projectId, agentId, nodeId } });
} }
stopLiveAgent(projectId: string, agentId: string): Promise<StoppedLiveAgent> { stopLiveAgent(projectId: string, agentId: string, reason?: string): Promise<StoppedLiveAgent> {
return this.http.invoke<StoppedLiveAgent>("stop_live_agent", { request: { projectId, agentId } }); return this.http.invoke<StoppedLiveAgent>("stop_live_agent", {
request: { projectId, agentId, ...(reason ? { reason } : {}) },
});
} }
createAgent(projectId: string, input: CreateAgentInput): Promise<Agent> { createAgent(projectId: string, input: CreateAgentInput): Promise<Agent> {
return this.http.invoke<Agent>("create_agent", { return this.http.invoke<Agent>("create_agent", {

View File

@ -34,6 +34,7 @@ import { TauriTicketGateway } from "./ticket";
import { TauriWindowGateway } from "./window"; import { TauriWindowGateway } from "./window";
import { TauriFocusedProjectGateway } from "./focusedProject"; import { TauriFocusedProjectGateway } from "./focusedProject";
import { LocalStorageUiPreferencesGateway } from "./uiPreferences"; import { LocalStorageUiPreferencesGateway } from "./uiPreferences";
import { TauriUserSettingsGateway } from "./userSettings";
import { TauriPluginGateway } from "./plugin"; import { TauriPluginGateway } from "./plugin";
import { TauriPluginWorkspaceGateway } from "./pluginWorkspace"; import { TauriPluginWorkspaceGateway } from "./pluginWorkspace";
import { TauriPluginTaskGateway } from "./pluginTask"; import { TauriPluginTaskGateway } from "./pluginTask";
@ -82,6 +83,7 @@ export function createTauriGateways(): Gateways {
window: new TauriWindowGateway(), window: new TauriWindowGateway(),
focusedProject: new TauriFocusedProjectGateway(), focusedProject: new TauriFocusedProjectGateway(),
uiPreferences: new LocalStorageUiPreferencesGateway(), uiPreferences: new LocalStorageUiPreferencesGateway(),
userSettings: new TauriUserSettingsGateway(),
plugin: new TauriPluginGateway(), plugin: new TauriPluginGateway(),
pluginWorkspace: new TauriPluginWorkspaceGateway(), pluginWorkspace: new TauriPluginWorkspaceGateway(),
pluginTask: new TauriPluginTaskGateway(), pluginTask: new TauriPluginTaskGateway(),
@ -115,6 +117,7 @@ export {
TauriWindowGateway, TauriWindowGateway,
TauriFocusedProjectGateway, TauriFocusedProjectGateway,
LocalStorageUiPreferencesGateway, LocalStorageUiPreferencesGateway,
TauriUserSettingsGateway,
TauriPluginGateway, TauriPluginGateway,
TauriPluginStorageGateway, TauriPluginStorageGateway,
}; };

View File

@ -136,6 +136,7 @@ import type {
OpenTerminalOptions, OpenTerminalOptions,
ProfileGateway, ProfileGateway,
ProjectGateway, ProjectGateway,
ProjectSettings,
PermissionGateway, PermissionGateway,
PluginConfigDocumentReadInput, PluginConfigDocumentReadInput,
PluginConfigDocumentUpdateInput, PluginConfigDocumentUpdateInput,
@ -178,6 +179,8 @@ import type {
CreateTicketInput, CreateTicketInput,
UpdateTicketInput, UpdateTicketInput,
UiPreferencesGateway, UiPreferencesGateway,
UserSettings,
UserSettingsGateway,
ViewWindowClosed, ViewWindowClosed,
ViewWindowSnapshot, ViewWindowSnapshot,
WindowGateway, WindowGateway,
@ -414,7 +417,6 @@ export class MockAgentGateway implements AgentGateway {
/** Runtime kind per live agent (`agentId → kind`). */ /** Runtime kind per live agent (`agentId → kind`). */
private liveKindByAgent = new Map<string, "pty" | "structured">(); private liveKindByAgent = new Map<string, "pty" | "structured">();
/** Last stopped runtime per agent for idempotent stop. */ /** Last stopped runtime per agent for idempotent stop. */
private stoppedByAgent = new Map<string, StoppedLiveAgent>();
/** Retained structured reply chunks per live chat session. */ /** Retained structured reply chunks per live chat session. */
private chatScrollback = new Map<string, ReplyChunk[]>(); private chatScrollback = new Map<string, ReplyChunk[]>();
/** Persisted custom chat drafts keyed by project/layout/node. */ /** Persisted custom chat drafts keyed by project/layout/node. */
@ -539,14 +541,9 @@ export class MockAgentGateway implements AgentGateway {
} }
const sessionId = this.liveSessionByAgent.get(agentId); const sessionId = this.liveSessionByAgent.get(agentId);
if (!sessionId) { if (!sessionId) {
const stopped = this.stoppedByAgent.get(agentId); return { agentId, stopped: [], alreadyStopped: true };
if (stopped) return stopped;
const err: GatewayError = {
code: "NOT_FOUND",
message: `agent ${agentId} has no live session`,
};
throw err;
} }
const nodeId = this.liveByAgent.get(agentId) ?? "mock-node";
const session = this.sessions.get(sessionId); const session = this.sessions.get(sessionId);
if (session) session.closed = true; if (session) session.closed = true;
this.sessions.delete(sessionId); this.sessions.delete(sessionId);
@ -557,11 +554,14 @@ export class MockAgentGateway implements AgentGateway {
this.liveKindByAgent.delete(agentId); this.liveKindByAgent.delete(agentId);
const stopped: StoppedLiveAgent = { const stopped: StoppedLiveAgent = {
agentId, agentId,
stopped: [{
sessionId, sessionId,
nodeId,
kind, kind,
runtimeState: "stopped", runtimeState: "stopped",
}],
alreadyStopped: false,
}; };
this.stoppedByAgent.set(agentId, stopped);
return stopped; return stopped;
} }
@ -842,7 +842,6 @@ export class MockAgentGateway implements AgentGateway {
this.liveByAgent.set(agentId, options.nodeId); this.liveByAgent.set(agentId, options.nodeId);
this.liveSessionByAgent.set(agentId, sessionId); this.liveSessionByAgent.set(agentId, sessionId);
this.liveKindByAgent.set(agentId, "pty"); this.liveKindByAgent.set(agentId, "pty");
this.stoppedByAgent.delete(agentId);
} }
const clearLive = () => { const clearLive = () => {
if (this.liveByAgent.get(agentId) === options.nodeId) { if (this.liveByAgent.get(agentId) === options.nodeId) {
@ -910,7 +909,6 @@ export class MockAgentGateway implements AgentGateway {
this.liveByAgent.set(agentId, options.nodeId); this.liveByAgent.set(agentId, options.nodeId);
this.liveSessionByAgent.set(agentId, sessionId); this.liveSessionByAgent.set(agentId, sessionId);
this.liveKindByAgent.set(agentId, "structured"); this.liveKindByAgent.set(agentId, "structured");
this.stoppedByAgent.delete(agentId);
} }
return { return {
sessionId, sessionId,
@ -1251,6 +1249,7 @@ export class MockTerminalGateway implements TerminalGateway {
export class MockProjectGateway implements ProjectGateway { export class MockProjectGateway implements ProjectGateway {
private projects: Project[] = []; private projects: Project[] = [];
private contexts = new Map<string, string>(); private contexts = new Map<string, string>();
private settings = new Map<string, ProjectSettings>();
private restoreProjectIds: string[] = []; private restoreProjectIds: string[] = [];
private restoreFailures = new Map<string, OpenProjectRestoreFailure>(); private restoreFailures = new Map<string, OpenProjectRestoreFailure>();
@ -1426,6 +1425,28 @@ export class MockProjectGateway implements ProjectGateway {
this.contexts.set(projectId, content); this.contexts.set(projectId, content);
} }
async readProjectSettings(projectId: string): Promise<ProjectSettings> {
if (!this.projects.some((project) => project.id === projectId)) {
throw { code: "NOT_FOUND", message: `project ${projectId} not found` };
}
return this.settings.get(projectId) ?? { themeColor: null };
}
async updateProjectSettings(
projectId: string,
settings: ProjectSettings,
): Promise<ProjectSettings> {
if (!this.projects.some((project) => project.id === projectId)) {
throw { code: "NOT_FOUND", message: `project ${projectId} not found` };
}
if (settings.themeColor !== null && !/^#[0-9A-Fa-f]{6}$/.test(settings.themeColor)) {
throw { code: "INVALID", message: "themeColor must use #RRGGBB" };
}
const stored = { themeColor: settings.themeColor?.toUpperCase() ?? null };
this.settings.set(projectId, stored);
return stored;
}
async listProjectFiles(_projectId: string, path: string): Promise<ProjectFileListing> { async listProjectFiles(_projectId: string, path: string): Promise<ProjectFileListing> {
return { path, entries: [] }; return { path, entries: [] };
} }
@ -4838,6 +4859,7 @@ export function createMockGateways(): Gateways {
window: new MockWindowGateway(), window: new MockWindowGateway(),
focusedProject: new MockFocusedProjectGateway(), focusedProject: new MockFocusedProjectGateway(),
uiPreferences: new MockUiPreferencesGateway(), uiPreferences: new MockUiPreferencesGateway(),
userSettings: new MockUserSettingsGateway(),
plugin: new MockPluginGateway(), plugin: new MockPluginGateway(),
pluginWorkspace: new MockPluginWorkspaceGateway(), pluginWorkspace: new MockPluginWorkspaceGateway(),
pluginTask: new MockPluginTaskGateway(), pluginTask: new MockPluginTaskGateway(),
@ -4848,5 +4870,18 @@ export function createMockGateways(): Gateways {
}; };
} }
export class MockUserSettingsGateway implements UserSettingsGateway {
private settings: UserSettings = { defaultAgentTerminalInterface: null };
async readUserSettings(): Promise<UserSettings> {
return { ...this.settings };
}
async updateUserSettings(settings: UserSettings): Promise<UserSettings> {
this.settings = { ...settings };
return { ...this.settings };
}
}
// Re-export GatewayError so tests can reference the thrown shape. // Re-export GatewayError so tests can reference the thrown shape.
export type { GatewayError }; export type { GatewayError };

View File

@ -42,6 +42,7 @@ describe("createMockGateways", () => {
"terminal", "terminal",
"ticket", "ticket",
"uiPreferences", "uiPreferences",
"userSettings",
"window", "window",
"workState", "workState",
]); ]);

View File

@ -15,7 +15,7 @@ import type {
RemoveProjectOutput, RemoveProjectOutput,
RestoreOpenProjectsOutput, RestoreOpenProjectsOutput,
} from "@/domain"; } from "@/domain";
import type { ProjectGateway } from "@/ports"; import type { ProjectGateway, ProjectSettings } from "@/ports";
export class TauriProjectGateway implements ProjectGateway { export class TauriProjectGateway implements ProjectGateway {
listProjects(): Promise<Project[]> { listProjects(): Promise<Project[]> {
@ -78,6 +78,19 @@ export class TauriProjectGateway implements ProjectGateway {
}); });
} }
readProjectSettings(projectId: string): Promise<ProjectSettings> {
return invoke<ProjectSettings>("read_project_settings", { projectId });
}
updateProjectSettings(
projectId: string,
settings: ProjectSettings,
): Promise<ProjectSettings> {
return invoke<ProjectSettings>("update_project_settings", {
request: { projectId, themeColor: settings.themeColor },
});
}
async listProjectFiles(): Promise<ProjectFileListing> { async listProjectFiles(): Promise<ProjectFileListing> {
throw new Error("Project files browsing is available in the web workspace only."); throw new Error("Project files browsing is available in the web workspace only.");
} }

View File

@ -0,0 +1,13 @@
import { invoke } from "@tauri-apps/api/core";
import type { UserSettings, UserSettingsGateway } from "@/ports";
export class TauriUserSettingsGateway implements UserSettingsGateway {
readUserSettings(): Promise<UserSettings> {
return invoke<UserSettings>("read_user_settings");
}
updateUserSettings(settings: UserSettings): Promise<UserSettings> {
return invoke<UserSettings>("update_user_settings", { request: settings });
}
}

View File

@ -220,7 +220,7 @@ function normalizeSummaryStatus(value: unknown): ConversationPreviewStatus {
return "missing"; return "missing";
} }
function normalizeTurn(value: unknown, index: number): ConversationTurnWorkPreview { function normalizeTurn(value: unknown): ConversationTurnWorkPreview {
const turn = isRecord(value) ? value : {}; const turn = isRecord(value) ? value : {};
const textPreview = stringValue(turn.textPreview); const textPreview = stringValue(turn.textPreview);
const role = const role =
@ -230,7 +230,7 @@ function normalizeTurn(value: unknown, index: number): ConversationTurnWorkPrevi
return { return {
role, role,
source: normalizeSource(turn.source), source: normalizeSource(turn.source),
atMs: numberValue(turn.atMs, index), atMs: nullableNumber(turn.atMs),
textPreview, textPreview,
textLen: numberValue(turn.textLen, textPreview.length), textLen: numberValue(turn.textLen, textPreview.length),
}; };

View File

@ -558,7 +558,7 @@ export type DomainEvent =
target: string; target: string;
ticketId: string; ticketId: string;
text: string; text: string;
atMs: number; atMs: number | null;
} }
| { type: "ptyOutput"; sessionId: string; bytes: number[] }; | { type: "ptyOutput"; sessionId: string; bytes: number[] };
@ -751,7 +751,7 @@ export type ConversationPreviewStatus =
export interface ConversationTurnWorkPreview { export interface ConversationTurnWorkPreview {
role: "prompt" | "response" | "toolActivity"; role: "prompt" | "response" | "toolActivity";
source: TicketWorkSource; source: TicketWorkSource;
atMs: number; atMs: number | null;
textPreview: string; textPreview: string;
textLen: number; textLen: number;
} }
@ -800,7 +800,7 @@ export type TurnSource = { kind: "human" } | { kind: "agent"; agentId: string };
/** One turn of the human transcript — full text, never truncated. */ /** One turn of the human transcript — full text, never truncated. */
export interface TurnView { export interface TurnView {
id: string; id: string;
atMs: number; atMs: number | null;
role: TurnRole; role: TurnRole;
source: TurnSource; source: TurnSource;
text: string; text: string;
@ -1792,7 +1792,7 @@ export type ReplyProgressStage = "started" | "delta" | "completed" | "info";
export interface ReplyProgress { export interface ReplyProgress {
progressId?: string; progressId?: string;
occurredAtMs?: number; occurredAtMs?: number | null;
source: ReplyProgressSource; source: ReplyProgressSource;
kind: ReplyProgressKind; kind: ReplyProgressKind;
stage: ReplyProgressStage; stage: ReplyProgressStage;
@ -1817,12 +1817,13 @@ export type ReplyChunk =
text: string; text: string;
attachments?: string[]; attachments?: string[];
attachmentRefs?: ChatPromptAttachment[]; attachmentRefs?: ChatPromptAttachment[];
atMs?: number | null;
} }
| { kind: "textDelta"; text: string } | { kind: "textDelta"; text: string; atMs?: number | null }
| { kind: "toolActivity"; label: string } | { kind: "toolActivity"; label: string; atMs?: number | null }
| { kind: "progress"; progress: ReplyProgress } | { kind: "progress"; progress: ReplyProgress }
| { kind: "final"; content: string } | { kind: "final"; content: string; atMs?: number | null }
| { kind: "error"; message: string }; | { kind: "error"; message: string; atMs?: number | null };
export type SlashCommandAvailability = export type SlashCommandAvailability =
| { status: "available" } | { status: "available" }

View File

@ -847,9 +847,9 @@ describe("CustomAgentChatView", () => {
})), })),
sendAgentChat: vi.fn(async (_sessionId: string, _prompt: string, onChunk) => { sendAgentChat: vi.fn(async (_sessionId: string, _prompt: string, onChunk) => {
nowMs = firstDeltaReceivedAtMs; nowMs = firstDeltaReceivedAtMs;
onChunk({ kind: "textDelta", text: "Streaming reply" }); onChunk({ kind: "textDelta", text: "Streaming reply", atMs: firstDeltaReceivedAtMs });
nowMs = finalChunkReceivedAtMs; nowMs = finalChunkReceivedAtMs;
onChunk({ kind: "final", content: "Completed reply" }); onChunk({ kind: "final", content: "Completed reply", atMs: finalChunkReceivedAtMs });
}), }),
cancelAgentChat: vi.fn(async () => {}), cancelAgentChat: vi.fn(async () => {}),
closeAgentChat: vi.fn(async () => {}), closeAgentChat: vi.fn(async () => {}),
@ -898,16 +898,16 @@ describe("CustomAgentChatView", () => {
expect(userBubble).toBeTruthy(); expect(userBubble).toBeTruthy();
expect(agentBubble).toBeTruthy(); expect(agentBubble).toBeTruthy();
expect(finalBubble).toBeTruthy(); expect(finalBubble).toBeTruthy();
expect(within(userBubble!).getByText(expectedChatTime(userReceivedAtMs))).toBeTruthy(); expect(within(userBubble!).getByLabelText("Heure indisponible")).toBeTruthy();
expect( expect(
within(agentBubble!).getByText(expectedChatTime(firstDeltaReceivedAtMs)), within(agentBubble!).getByText(expectedChatTime(firstDeltaReceivedAtMs)),
).toBeTruthy(); ).toBeTruthy();
expect( expect(
within(finalBubble!).getByText(expectedChatTime(firstDeltaReceivedAtMs)), within(finalBubble!).getByText(expectedChatTime(finalChunkReceivedAtMs)),
).toBeTruthy(); ).toBeTruthy();
expect(screen.getByText("Streaming reply")).toBeTruthy(); expect(screen.getByText("Streaming reply")).toBeTruthy();
expect(screen.getByText("Completed reply")).toBeTruthy(); expect(screen.getByText("Completed reply")).toBeTruthy();
expect(screen.queryByText(expectedChatTime(finalChunkReceivedAtMs))).toBeNull(); expect(screen.getByText(expectedChatTime(finalChunkReceivedAtMs))).toBeTruthy();
} finally { } finally {
nowSpy.mockRestore(); nowSpy.mockRestore();
} }
@ -927,9 +927,9 @@ describe("CustomAgentChatView", () => {
})), })),
sendAgentChat: vi.fn(async (_sessionId: string, _prompt: string, onChunk) => { sendAgentChat: vi.fn(async (_sessionId: string, _prompt: string, onChunk) => {
nowMs = firstDeltaReceivedAtMs; nowMs = firstDeltaReceivedAtMs;
onChunk({ kind: "textDelta", text: "Streaming reply" }); onChunk({ kind: "textDelta", text: "Streaming reply", atMs: firstDeltaReceivedAtMs });
nowMs = errorReceivedAtMs; nowMs = errorReceivedAtMs;
onChunk({ kind: "error", message: "Broken reply" }); onChunk({ kind: "error", message: "Broken reply", atMs: errorReceivedAtMs });
}), }),
cancelAgentChat: vi.fn(async () => {}), cancelAgentChat: vi.fn(async () => {}),
closeAgentChat: vi.fn(async () => {}), closeAgentChat: vi.fn(async () => {}),
@ -981,9 +981,9 @@ describe("CustomAgentChatView", () => {
within(agentBubble!).getByText(expectedChatTime(firstDeltaReceivedAtMs)), within(agentBubble!).getByText(expectedChatTime(firstDeltaReceivedAtMs)),
).toBeTruthy(); ).toBeTruthy();
expect( expect(
within(errorBubble!).getByText(expectedChatTime(firstDeltaReceivedAtMs)), within(errorBubble!).getByText(expectedChatTime(errorReceivedAtMs)),
).toBeTruthy(); ).toBeTruthy();
expect(screen.queryByText(expectedChatTime(errorReceivedAtMs))).toBeNull(); expect(screen.getByText(expectedChatTime(errorReceivedAtMs))).toBeTruthy();
} finally { } finally {
nowSpy.mockRestore(); nowSpy.mockRestore();
} }
@ -1036,12 +1036,8 @@ describe("CustomAgentChatView", () => {
expect(agentBubble).toBeTruthy(); expect(agentBubble).toBeTruthy();
expect(finalBubble).toBeTruthy(); expect(finalBubble).toBeTruthy();
expect( expect(within(agentBubble!).getByLabelText("Heure indisponible")).toBeTruthy();
within(agentBubble!).getByText(expectedChatTime(replayReceivedAtMs)), expect(within(finalBubble!).getByLabelText("Heure indisponible")).toBeTruthy();
).toBeTruthy();
expect(
within(finalBubble!).getByText(expectedChatTime(replayReceivedAtMs)),
).toBeTruthy();
expect(within(agentBubble!).queryByText(indexOneTime)).toBeNull(); expect(within(agentBubble!).queryByText(indexOneTime)).toBeNull();
expect(within(finalBubble!).queryByText(indexOneTime)).toBeNull(); expect(within(finalBubble!).queryByText(indexOneTime)).toBeNull();
} finally { } finally {

View File

@ -42,7 +42,7 @@ import {
markProjectCliInteractionStarted, markProjectCliInteractionStarted,
markProjectCliInteractionStopped, markProjectCliInteractionStopped,
} from "@/features/projects/projectCliInteractionActivity"; } from "@/features/projects/projectCliInteractionActivity";
import { Button, Spinner, cn } from "@/shared"; import { Button, EntryTimestamp, Spinner, cn, normalizeTimestamp } from "@/shared";
import type { ChatAttachmentInput, ChatDraftScope } from "@/ports"; import type { ChatAttachmentInput, ChatDraftScope } from "@/ports";
export interface CustomAgentChatViewProps { export interface CustomAgentChatViewProps {
@ -66,14 +66,14 @@ export interface CustomAgentChatViewProps {
} }
type ChatTurn = type ChatTurn =
| { role: "user"; text: string; attachments?: string[]; receivedAtMs?: number } | { role: "user"; text: string; attachments?: string[]; receivedAtMs?: number | null }
| { role: "agent"; text: string; pending?: boolean; receivedAtMs?: number } | { role: "agent"; text: string; pending?: boolean; receivedAtMs?: number | null }
| { role: "tool"; label: string; receivedAtMs?: number } | { role: "tool"; label: string; receivedAtMs?: number | null }
| { role: "progress"; progress: ReplyProgress; settled?: boolean; progressKey?: string } | { role: "progress"; progress: ReplyProgress; settled?: boolean; progressKey?: string }
| { role: "final"; text: string; receivedAtMs?: number } | { role: "final"; text: string; receivedAtMs?: number | null }
| { role: "error"; text: string; receivedAtMs?: number } | { role: "error"; text: string; receivedAtMs?: number | null }
| { role: "restart"; key: string; text: string; message?: string; failed?: boolean } | { role: "restart"; key: string; text: string; message?: string; failed?: boolean; receivedAtMs?: number | null }
| { role: "unknown"; text: string; receivedAtMs?: number }; | { role: "unknown"; text: string; receivedAtMs?: number | null };
interface CachedChatView { interface CachedChatView {
turns: ChatTurn[]; turns: ChatTurn[];
@ -89,14 +89,6 @@ const EMPTY_MODEL_RESPONSE_MESSAGE = "Le modèle n'a renvoyé aucune réponse.";
const COMPOSER_RESIZE_STEP = 12; const COMPOSER_RESIZE_STEP = 12;
const FALLBACK_COMPOSER_HEIGHT = 64; const FALLBACK_COMPOSER_HEIGHT = 64;
const COMPOSER_HISTORY_LIMIT = 100; const COMPOSER_HISTORY_LIMIT = 100;
const MIN_REASONABLE_CHAT_TIMESTAMP_MS = Date.UTC(2020, 0, 1);
const MAX_REASONABLE_CHAT_TIMESTAMP_MS = Date.UTC(2100, 0, 1);
const MIN_REASONABLE_CHAT_TIMESTAMP_SECONDS = Math.floor(
MIN_REASONABLE_CHAT_TIMESTAMP_MS / 1000,
);
const MAX_REASONABLE_CHAT_TIMESTAMP_SECONDS = Math.floor(
MAX_REASONABLE_CHAT_TIMESTAMP_MS / 1000,
);
export function __clearCustomAgentChatViewCacheForTests() { export function __clearCustomAgentChatViewCacheForTests() {
chatSessionViewCache.clear(); chatSessionViewCache.clear();
@ -214,7 +206,7 @@ function isReplyRecord(chunk: unknown): chunk is Record<string, unknown> {
function appendAgentDelta( function appendAgentDelta(
turns: ChatTurn[], turns: ChatTurn[],
text: string, text: string,
receivedAtMs: number, receivedAtMs: number | null | undefined,
): ChatTurn[] { ): ChatTurn[] {
const next = [...turns]; const next = [...turns];
const last = next[next.length - 1]; const last = next[next.length - 1];
@ -241,7 +233,7 @@ function appendUserPrompt(
turns: ChatTurn[], turns: ChatTurn[],
text: string, text: string,
attachments: string[] = [], attachments: string[] = [],
receivedAtMs = Date.now(), receivedAtMs?: number | null,
): { turns: ChatTurn[]; appended: boolean } { ): { turns: ChatTurn[]; appended: boolean } {
for (let index = turns.length - 1; index >= 0; index -= 1) { for (let index = turns.length - 1; index >= 0; index -= 1) {
const turn = turns[index]; const turn = turns[index];
@ -251,6 +243,11 @@ function appendUserPrompt(
turn.text === text && turn.text === text &&
JSON.stringify(turn.attachments ?? []) === JSON.stringify(attachments) JSON.stringify(turn.attachments ?? []) === JSON.stringify(attachments)
) { ) {
if (turn.receivedAtMs == null && receivedAtMs != null) {
const next = [...turns];
next[index] = { ...turn, receivedAtMs };
return { turns: next, appended: false };
}
return { turns, appended: false }; return { turns, appended: false };
} }
break; break;
@ -805,29 +802,21 @@ function formatSlashCommandHelp(commands: SlashCommand[]): string {
.join("\n"); .join("\n");
} }
function lastAgentReceivedAtMs(turns: ChatTurn[]): number | undefined {
for (let index = turns.length - 1; index >= 0; index -= 1) {
const turn = turns[index];
if (turn.role === "agent") return turn.receivedAtMs;
if (turn.role === "user" || turn.role === "final" || turn.role === "error") {
return undefined;
}
}
return undefined;
}
function foldChunk( function foldChunk(
state: ChatViewState, state: ChatViewState,
raw: unknown, raw: unknown,
receivedAtMs = Date.now(), receivedAtMs?: number | null,
): ChatViewState { ): ChatViewState {
const { turns } = state; const { turns } = state;
if (!isReplyRecord(raw)) { if (!isReplyRecord(raw)) {
return { return {
...state, ...state,
turns: [...turns, { role: "unknown", text: unknownChunkLabel(raw), receivedAtMs }], turns: [...turns, { role: "unknown", text: unknownChunkLabel(raw) }],
}; };
} }
const emittedAtMs =
receivedAtMs ??
normalizeTimestamp(typeof raw.atMs === "number" ? raw.atMs : null);
const last = turns[turns.length - 1]; const last = turns[turns.length - 1];
if ( if (
(last?.role === "final" || last?.role === "error") && (last?.role === "final" || last?.role === "error") &&
@ -843,14 +832,14 @@ function foldChunk(
case "textDelta": case "textDelta":
return { return {
...state, ...state,
turns: appendAgentDelta(turns, String(raw.text ?? ""), receivedAtMs), turns: appendAgentDelta(turns, String(raw.text ?? ""), emittedAtMs),
}; };
case "toolActivity": case "toolActivity":
return { return {
...state, ...state,
turns: [ turns: [
...turns, ...turns,
{ role: "tool", label: String(raw.label ?? "Activité"), receivedAtMs }, { role: "tool", label: String(raw.label ?? "Activité"), receivedAtMs: emittedAtMs },
], ],
}; };
case "progress": { case "progress": {
@ -860,7 +849,7 @@ function foldChunk(
...state, ...state,
turns: [ turns: [
...turns, ...turns,
{ role: "unknown", text: unknownChunkLabel(raw), receivedAtMs }, { role: "unknown", text: unknownChunkLabel(raw), receivedAtMs: emittedAtMs },
], ],
}; };
} }
@ -875,7 +864,7 @@ function foldChunk(
next.push({ next.push({
role: "final", role: "final",
text: content, text: content,
receivedAtMs: lastAgentReceivedAtMs(next) ?? receivedAtMs, receivedAtMs: emittedAtMs,
}); });
return { ...completedState, turns: next }; return { ...completedState, turns: next };
} }
@ -887,7 +876,7 @@ function foldChunk(
next.push({ next.push({
role: "error", role: "error",
text: String(raw.message ?? "Erreur agent"), text: String(raw.message ?? "Erreur agent"),
receivedAtMs: lastAgentReceivedAtMs(next) ?? receivedAtMs, receivedAtMs: emittedAtMs,
}); });
return { ...completedState, turns: next }; return { ...completedState, turns: next };
} }
@ -897,7 +886,7 @@ function foldChunk(
turns, turns,
String(raw.text ?? raw.prompt ?? ""), String(raw.text ?? raw.prompt ?? ""),
attachmentLabels(raw.attachments), attachmentLabels(raw.attachments),
receivedAtMs, emittedAtMs,
); );
return { return {
...state, ...state,
@ -910,7 +899,7 @@ function foldChunk(
default: default:
return { return {
...state, ...state,
turns: [...turns, { role: "unknown", text: unknownChunkLabel(raw), receivedAtMs }], turns: [...turns, { role: "unknown", text: unknownChunkLabel(raw), receivedAtMs: emittedAtMs }],
}; };
} }
} }
@ -1998,7 +1987,7 @@ export function CustomAgentChatView({
{ {
role: "tool", role: "tool",
label: `Profil changé vers ${selected.name}.`, label: `Profil changé vers ${selected.name}.`,
receivedAtMs: Date.now(), receivedAtMs: null,
}, },
], ],
progressIndex: new Map(), progressIndex: new Map(),
@ -2040,7 +2029,7 @@ export function CustomAgentChatView({
const helpText = formatSlashCommandHelp(result.effect.commands); const helpText = formatSlashCommandHelp(result.effect.commands);
updateChatViewState((prev) => ({ updateChatViewState((prev) => ({
...prev, ...prev,
turns: [...prev.turns, { role: "agent", text: helpText, receivedAtMs: Date.now() }], turns: [...prev.turns, { role: "agent", text: helpText, receivedAtMs: null }],
})); }));
return; return;
} }
@ -2065,7 +2054,7 @@ export function CustomAgentChatView({
{ {
role: "tool", role: "tool",
label: `Commande plugin ${result.command.name} exécutée.`, label: `Commande plugin ${result.command.name} exécutée.`,
receivedAtMs: Date.now(), receivedAtMs: null,
}, },
], ],
})); }));
@ -2076,7 +2065,7 @@ export function CustomAgentChatView({
setError({ message, openFailure: false }); setError({ message, openFailure: false });
updateChatViewState((prev) => ({ updateChatViewState((prev) => ({
...prev, ...prev,
turns: [...prev.turns, { role: "error", text: message, receivedAtMs: Date.now() }], turns: [...prev.turns, { role: "error", text: message, receivedAtMs: null }],
})); }));
} }
} }
@ -2195,7 +2184,6 @@ export function CustomAgentChatView({
void clearPersistedDraft(); void clearPersistedDraft();
setBusy(true); setBusy(true);
setError(null); setError(null);
const sentAtMs = Date.now();
updateChatViewState((prev) => ({ updateChatViewState((prev) => ({
...prev, ...prev,
turns: [ turns: [
@ -2203,7 +2191,7 @@ export function CustomAgentChatView({
{ {
role: "user", role: "user",
text: displayText, text: displayText,
receivedAtMs: sentAtMs, receivedAtMs: null,
...(attachmentLabels.length > 0 ? { attachments: attachmentLabels } : {}), ...(attachmentLabels.length > 0 ? { attachments: attachmentLabels } : {}),
}, },
], ],
@ -2242,7 +2230,7 @@ export function CustomAgentChatView({
...prev, ...prev,
turns: [ turns: [
...prev.turns, ...prev.turns,
{ role: "error", text: describe(recoveryError), receivedAtMs: Date.now() }, { role: "error", text: describe(recoveryError), receivedAtMs: null },
], ],
})); }));
return; return;
@ -2253,7 +2241,7 @@ export function CustomAgentChatView({
setError({ message: describe(e), openFailure: false }); setError({ message: describe(e), openFailure: false });
updateChatViewState((prev) => ({ updateChatViewState((prev) => ({
...prev, ...prev,
turns: [...prev.turns, { role: "error", text: describe(e), receivedAtMs: Date.now() }], turns: [...prev.turns, { role: "error", text: describe(e), receivedAtMs: null }],
})); }));
} }
} }
@ -2280,7 +2268,7 @@ export function CustomAgentChatView({
{ {
role: "tool", role: "tool",
label: "Request stopped.", label: "Request stopped.",
receivedAtMs: Date.now(), receivedAtMs: null,
}, },
], ],
}; };
@ -2299,7 +2287,7 @@ export function CustomAgentChatView({
...completed, ...completed,
turns: [ turns: [
...completed.turns, ...completed.turns,
{ role: "tool", label: "Request already stopped.", receivedAtMs: Date.now() }, { role: "tool", label: "Request already stopped.", receivedAtMs: null },
], ],
}; };
}); });
@ -2313,7 +2301,7 @@ export function CustomAgentChatView({
{ {
role: "error", role: "error",
text: `Arrêt de la demande échoué: ${describe(e)}`, text: `Arrêt de la demande échoué: ${describe(e)}`,
receivedAtMs: Date.now(), receivedAtMs: null,
}, },
], ],
})); }));
@ -2729,7 +2717,10 @@ function ChatBubble({
turn.failed ? "text-danger" : "text-muted", turn.failed ? "text-danger" : "text-muted",
)} )}
> >
<div className="flex items-baseline gap-2">
<span className="whitespace-pre-wrap text-center">{turn.text}</span> <span className="whitespace-pre-wrap text-center">{turn.text}</span>
<EntryTimestamp atMs={turn.receivedAtMs} />
</div>
{turn.message && <span className="max-w-[86%] text-center">{turn.message}</span>} {turn.message && <span className="max-w-[86%] text-center">{turn.message}</span>}
</div> </div>
); );
@ -2737,8 +2728,9 @@ function ChatBubble({
if (turn.role === "tool") { if (turn.role === "tool") {
return ( return (
<div className="flex min-w-0 justify-center"> <div className="flex min-w-0 justify-center">
<span className="max-w-[80%] truncate rounded-md border border-border bg-raised px-2 py-1 text-xs text-muted"> <span className="flex max-w-[80%] items-baseline gap-2 truncate rounded-md border border-border bg-raised px-2 py-1 text-xs text-muted">
{turn.label} <span className="truncate">{turn.label}</span>
<EntryTimestamp atMs={turn.receivedAtMs} />
</span> </span>
</div> </div>
); );
@ -2824,67 +2816,21 @@ function ChatBubble({
); );
} }
function normalizeChatReceivedAtMs(receivedAtMs: number | undefined): number | undefined {
if (!Number.isFinite(receivedAtMs) || receivedAtMs === undefined || receivedAtMs <= 0) {
return undefined;
}
if (
receivedAtMs >= MIN_REASONABLE_CHAT_TIMESTAMP_SECONDS &&
receivedAtMs < MAX_REASONABLE_CHAT_TIMESTAMP_SECONDS
) {
return receivedAtMs * 1000;
}
if (
receivedAtMs < MIN_REASONABLE_CHAT_TIMESTAMP_MS ||
receivedAtMs >= MAX_REASONABLE_CHAT_TIMESTAMP_MS
) {
return undefined;
}
return receivedAtMs;
}
function formatChatReceivedTime(receivedAtMs: number | undefined): string {
const normalizedAtMs = normalizeChatReceivedAtMs(receivedAtMs);
if (!normalizedAtMs) return "";
try {
const parts = new Intl.DateTimeFormat(undefined, {
hour: "2-digit",
minute: "2-digit",
hourCycle: "h23",
}).formatToParts(new Date(normalizedAtMs));
const hour = parts.find((part) => part.type === "hour")?.value;
const minute = parts.find((part) => part.type === "minute")?.value;
return hour && minute ? `${hour}:${minute}` : "";
} catch {
return "";
}
}
function ChatMessageMeta({ function ChatMessageMeta({
label, label,
receivedAtMs, receivedAtMs,
labelClassName, labelClassName,
}: { }: {
label: string; label: string;
receivedAtMs: number | undefined; receivedAtMs: number | null | undefined;
labelClassName?: string; labelClassName?: string;
}) { }) {
const time = formatChatReceivedTime(receivedAtMs);
const normalizedAtMs = normalizeChatReceivedAtMs(receivedAtMs);
const dateTime = time && normalizedAtMs ? new Date(normalizedAtMs).toISOString() : undefined;
return ( return (
<div className="mb-1 flex min-w-0 flex-col gap-0.5 text-xs sm:flex-row sm:items-baseline sm:justify-between sm:gap-3"> <div className="mb-1 flex min-w-0 flex-col gap-0.5 text-xs sm:flex-row sm:items-baseline sm:justify-between sm:gap-3">
<span className={cn("min-w-0 truncate font-medium text-muted", labelClassName)}> <span className={cn("min-w-0 truncate font-medium text-muted", labelClassName)}>
{label} {label}
</span> </span>
{time && ( <EntryTimestamp atMs={receivedAtMs} />
<time
dateTime={dateTime}
className="shrink-0 text-faint"
>
{time}
</time>
)}
</div> </div>
); );
} }
@ -3105,6 +3051,7 @@ function TurnMarker({ progress }: { progress: ReplyProgress }) {
{stage} {stage}
</span> </span>
<span className="truncate">{label}</span> <span className="truncate">{label}</span>
<EntryTimestamp atMs={progress.occurredAtMs} />
<span className="h-px w-8 shrink-0 bg-border" aria-hidden /> <span className="h-px w-8 shrink-0 bg-border" aria-hidden />
</div> </div>
</div> </div>
@ -3150,6 +3097,7 @@ function ToolProgressCard({
<span className="min-w-0 truncate text-muted">{compactToolName(progress)}</span> <span className="min-w-0 truncate text-muted">{compactToolName(progress)}</span>
)} )}
<span className="shrink-0 text-muted">· {stage}</span> <span className="shrink-0 text-muted">· {stage}</span>
<EntryTimestamp atMs={progress.occurredAtMs} />
</div> </div>
{delegation?.excerpt && !detail && ( {delegation?.excerpt && !detail && (
<p className="mt-1 text-center text-[11px] text-content" style={fourLineClamp}> <p className="mt-1 text-center text-[11px] text-content" style={fourLineClamp}>
@ -3224,6 +3172,7 @@ function ProgressBubble({
<span className="shrink-0 font-semibold">{title}</span> <span className="shrink-0 font-semibold">{title}</span>
<span className="min-w-0 truncate text-muted">{progress.label}</span> <span className="min-w-0 truncate text-muted">{progress.label}</span>
<span className="shrink-0 text-muted">· {stage}</span> <span className="shrink-0 text-muted">· {stage}</span>
<EntryTimestamp atMs={progress.occurredAtMs} />
</div> </div>
<div className="mt-0.5 flex min-w-0 flex-wrap justify-end gap-x-2 gap-y-0.5 text-[11px] text-muted"> <div className="mt-0.5 flex min-w-0 flex-wrap justify-end gap-x-2 gap-y-0.5 text-[11px] text-muted">
<span>{source}</span> <span>{source}</span>

View File

@ -450,7 +450,8 @@ describe("AgentsPanel (with MockAgentGateway)", () => {
it("stopping an agent unmounts the terminal view", async () => { it("stopping an agent unmounts the terminal view", async () => {
const agent = new MockAgentGateway(); const agent = new MockAgentGateway();
await agent.createAgent(PROJECT_ID, { name: "Echo", profileId: "p1" }); const created = await agent.createAgent(PROJECT_ID, { name: "Echo", profileId: "p1" });
const stop = vi.spyOn(agent, "stopLiveAgent");
renderPanel(agent); renderPanel(agent);
await waitForIdle(); await waitForIdle();
@ -466,6 +467,31 @@ describe("AgentsPanel (with MockAgentGateway)", () => {
await waitFor(() => { await waitFor(() => {
expect(screen.queryByTestId("terminal-view")).toBeNull(); expect(screen.queryByTestId("terminal-view")).toBeNull();
}); });
expect(stop).toHaveBeenCalledWith(
PROJECT_ID,
created.id,
"Arrêt demandé depuis Agents",
);
});
it("stops a live agent even when its TerminalView was never mounted", async () => {
const agent = new MockAgentGateway();
const created = await agent.createAgent(PROJECT_ID, { name: "Headless", profileId: "p1" });
await agent.launchAgent(
PROJECT_ID,
created.id,
{ cwd: "/repo", rows: 24, cols: 80, nodeId: "background-node" },
() => {},
);
const stop = vi.spyOn(agent, "stopLiveAgent");
renderPanel(agent);
await screen.findByRole("button", { name: "stop Headless" });
expect(screen.queryByTestId("terminal-view")).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "stop Headless" }));
await waitFor(() => expect(stop).toHaveBeenCalled());
await expect(agent.listLiveAgents(PROJECT_ID)).resolves.toEqual([]);
}); });
it("selecting a template calls createAgentFromTemplate instead of createAgent", async () => { it("selecting a template calls createAgentFromTemplate instead of createAgent", async () => {

View File

@ -171,7 +171,7 @@ function describe(e: unknown): string {
} }
export function useAgents(projectId: string): AgentsViewModel { export function useAgents(projectId: string): AgentsViewModel {
const { agent, profile, system, terminal, input } = useGateways(); const { agent, profile, system, input } = useGateways();
const [agents, setAgents] = useState<Agent[]>([]); const [agents, setAgents] = useState<Agent[]>([]);
const [selectedAgentId, setSelectedAgentId] = useState<string | null>(null); const [selectedAgentId, setSelectedAgentId] = useState<string | null>(null);
@ -515,15 +515,12 @@ export function useAgents(projectId: string): AgentsViewModel {
const stopAgent = useCallback( const stopAgent = useCallback(
async (agentId?: string) => { async (agentId?: string) => {
const targetAgentId = agentId ?? runningAgentId; const targetAgentId = agentId ?? runningAgentId;
const live = targetAgentId if (!targetAgentId) return;
? liveAgents.find((candidate) => candidate.agentId === targetAgentId)
: null;
setRunningAgentId((current) => setRunningAgentId((current) =>
current === targetAgentId || !targetAgentId ? null : current, current === targetAgentId || !targetAgentId ? null : current,
); );
if (live?.sessionId) {
try { try {
await terminal?.closeTerminal(live.sessionId); await agent.stopLiveAgent(projectId, targetAgentId, "Arrêt demandé depuis Agents");
setLiveAgents((current) => setLiveAgents((current) =>
current.filter((candidate) => candidate.agentId !== targetAgentId), current.filter((candidate) => candidate.agentId !== targetAgentId),
); );
@ -531,9 +528,8 @@ export function useAgents(projectId: string): AgentsViewModel {
setError(describe(e)); setError(describe(e));
await refreshLiveAgents(); await refreshLiveAgents();
} }
}
}, },
[liveAgents, refreshLiveAgents, runningAgentId, terminal], [agent, projectId, refreshLiveAgents, runningAgentId],
); );
const cancelResume = useCallback( const cancelResume = useCallback(

View File

@ -1,6 +1,6 @@
import { useEffect, useRef } from "react"; import { useEffect, useRef } from "react";
import { Spinner } from "@/shared"; import { EntryTimestamp, Spinner } from "@/shared";
import { useAgentRestart, useTargetAnnouncements } from "./AnnouncementsProvider"; import { useAgentRestart, useTargetAnnouncements } from "./AnnouncementsProvider";
export interface AgentRestartOverlayProps { export interface AgentRestartOverlayProps {
@ -69,7 +69,8 @@ export function AgentRestartOverlay({ agentId }: AgentRestartOverlayProps) {
</div> </div>
) : ( ) : (
announcements.map((announcement) => ( announcements.map((announcement) => (
<div key={announcement.seq} className="text-sm text-content/90"> <div key={announcement.seq} className="flex items-baseline gap-2 text-sm text-content/90">
<EntryTimestamp atMs={announcement.atMs} className="text-xs" />
<span className="whitespace-pre-wrap break-words">{announcement.text}</span> <span className="whitespace-pre-wrap break-words">{announcement.text}</span>
</div> </div>
)) ))

View File

@ -12,6 +12,7 @@
*/ */
import { useRequesterAnnouncements } from "./AnnouncementsProvider"; import { useRequesterAnnouncements } from "./AnnouncementsProvider";
import { EntryTimestamp } from "@/shared";
export interface AnnouncementsPreviewProps { export interface AnnouncementsPreviewProps {
/** The requesting agent this preview belongs to (the announcement `requester`). */ /** The requesting agent this preview belongs to (the announcement `requester`). */
@ -60,10 +61,11 @@ export function AnnouncementsPreview({
{recent.map((a) => ( {recent.map((a) => (
<li <li
key={a.seq} key={a.seq}
className="truncate text-xs text-muted" className="flex min-w-0 items-baseline gap-1.5 text-xs text-muted"
title={a.text} title={a.text}
> >
{a.text} <EntryTimestamp atMs={a.atMs} />
<span className="truncate">{a.text}</span>
</li> </li>
))} ))}
</ul> </ul>

View File

@ -15,7 +15,7 @@
import { useEffect, useRef } from "react"; import { useEffect, useRef } from "react";
import { Spinner } from "@/shared"; import { EntryTimestamp, Spinner } from "@/shared";
import { import {
useHydrateAgentBusy, useHydrateAgentBusy,
useTargetAnnouncements, useTargetAnnouncements,
@ -32,15 +32,6 @@ export interface TargetAnnouncementsOverlayProps {
fallbackText?: string; fallbackText?: string;
} }
function formatTime(atMs: number): string {
if (!Number.isFinite(atMs) || atMs <= 0) return "";
try {
return new Date(atMs).toLocaleTimeString();
} catch {
return "";
}
}
export function TargetAnnouncementsOverlay({ export function TargetAnnouncementsOverlay({
projectId, projectId,
agentId, agentId,
@ -88,13 +79,12 @@ export function TargetAnnouncementsOverlay({
</div> </div>
) : ( ) : (
announcements.map((a) => { announcements.map((a) => {
const time = formatTime(a.atMs);
return ( return (
<div <div
key={a.seq} key={a.seq}
className="flex items-baseline gap-2 text-sm text-muted" className="flex items-baseline gap-2 text-sm text-muted"
> >
{time && <span className="shrink-0 text-xs text-faint">{time}</span>} <EntryTimestamp atMs={a.atMs} className="text-xs" />
<span className="whitespace-pre-wrap break-words text-content/90"> <span className="whitespace-pre-wrap break-words text-content/90">
{a.text} {a.text}
</span> </span>

View File

@ -34,7 +34,7 @@ export interface Announcement {
/** Human-readable réflexion/annonce text. */ /** Human-readable réflexion/annonce text. */
text: string; text: string;
/** Wall-clock timestamp (epoch-ms) as emitted by the backend. */ /** Wall-clock timestamp (epoch-ms) as emitted by the backend. */
atMs: number; atMs: number | null;
/** /**
* Monotonic local sequence assigned on ingest. Provides a stable React key and * Monotonic local sequence assigned on ingest. Provides a stable React key and
* a total order even when two announcements share the same `atMs`. * a total order even when two announcements share the same `atMs`.
@ -110,6 +110,7 @@ export function purgeAllForTarget(
/** Orders two announcements oldest → newest (by `atMs`, tie-broken by `seq`). */ /** Orders two announcements oldest → newest (by `atMs`, tie-broken by `seq`). */
function byTime(a: Announcement, b: Announcement): number { function byTime(a: Announcement, b: Announcement): number {
if (a.atMs === null || b.atMs === null) return a.seq - b.seq;
return a.atMs - b.atMs || a.seq - b.seq; return a.atMs - b.atMs || a.seq - b.seq;
} }

View File

@ -18,7 +18,7 @@ import type {
TurnSource, TurnSource,
TurnView, TurnView,
} from "@/domain"; } from "@/domain";
import { Button, Spinner, cn } from "@/shared"; import { Button, EntryTimestamp, Spinner, cn } from "@/shared";
import { useProjectWorkState } from "@/features/workstate"; import { useProjectWorkState } from "@/features/workstate";
import { useConversationThread } from "./useConversationThread"; import { useConversationThread } from "./useConversationThread";
@ -38,15 +38,6 @@ function partyKey(source: TurnSource): string {
return source.kind === "human" ? "human" : `agent:${source.agentId}`; return source.kind === "human" ? "human" : `agent:${source.agentId}`;
} }
function formatTime(atMs: number): string {
if (!Number.isFinite(atMs) || atMs <= 0) return "";
try {
return new Date(atMs).toLocaleString();
} catch {
return "";
}
}
function roleLabel(role: TurnView["role"]): string { function roleLabel(role: TurnView["role"]): string {
switch (role) { switch (role) {
case "prompt": case "prompt":
@ -185,6 +176,7 @@ function ToolTurn({ turn, sideClass }: { turn: TurnView; sideClass: string }) {
<span aria-hidden>{open ? "▾" : "▸"}</span> <span aria-hidden>{open ? "▾" : "▸"}</span>
Tool activity Tool activity
<span className="text-faint">· {turn.textLen} chars</span> <span className="text-faint">· {turn.textLen} chars</span>
<EntryTimestamp atMs={turn.atMs} />
</button> </button>
{open && ( {open && (
<pre className="mt-1.5 whitespace-pre-wrap break-words font-mono text-[11px] text-muted"> <pre className="mt-1.5 whitespace-pre-wrap break-words font-mono text-[11px] text-muted">
@ -353,7 +345,6 @@ export function ConversationViewer({
); );
} }
const party = parties.meta.get(partyKey(turn.source)); const party = parties.meta.get(partyKey(turn.source));
const time = formatTime(turn.atMs);
return ( return (
<div key={turn.id} className={cn("flex flex-col", sideClass)}> <div key={turn.id} className={cn("flex flex-col", sideClass)}>
<div <div
@ -369,7 +360,7 @@ export function ConversationViewer({
{party?.label ?? "?"} {party?.label ?? "?"}
</span> </span>
<span>· {roleLabel(turn.role)}</span> <span>· {roleLabel(turn.role)}</span>
{time && <span className="text-faint">· {time}</span>} <EntryTimestamp atMs={turn.atMs} />
</div> </div>
<p className="whitespace-pre-wrap break-words">{turn.text}</p> <p className="whitespace-pre-wrap break-words">{turn.text}</p>
</div> </div>

View File

@ -843,10 +843,8 @@ function LeafView({
} }
if (cellMode === "custom" && agentGateway?.closeAgentChat) { if (cellMode === "custom" && agentGateway?.closeAgentChat) {
await agentGateway.closeAgentChat(session); await agentGateway.closeAgentChat(session);
} else if (agentId && agentGateway?.stopLiveAgent) { } else if (agentId && agentGateway) {
await agentGateway.stopLiveAgent(projectId, agentId).catch(async () => { await agentGateway.stopLiveAgent(projectId, agentId, "Changement d'interface terminal");
await terminal?.closeTerminal(session);
});
} else { } else {
await terminal?.closeTerminal(session); await terminal?.closeTerminal(session);
} }
@ -1115,7 +1113,7 @@ function LeafView({
height: "100%", height: "100%",
minHeight: 0, minHeight: 0,
minWidth: 0, minWidth: 0,
border: "1px solid #2a2a2a", border: "1px solid var(--color-border-strong, #3b4757)",
boxSizing: "border-box", boxSizing: "border-box",
overflow: "hidden", overflow: "hidden",
}} }}

View File

@ -0,0 +1,39 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { createMockGateways } from "@/adapters/mock";
import { DIProvider } from "@/app/di";
import { ProjectSettingsPanel, PROJECT_THEME_CHANGED_EVENT } from "./ProjectSettingsPanel";
import { accessibleProjectAccent, validThemeColor } from "./projectTheme";
describe("ProjectSettingsPanel", () => {
it("persists a project colour, emits the scoped refresh, and resets to fallback", async () => {
const gateways = createMockGateways();
const project = await gateways.project.createProject("Alpha", "/alpha");
const update = vi.spyOn(gateways.project, "updateProjectSettings");
const changed = vi.fn();
window.addEventListener(PROJECT_THEME_CHANGED_EVENT, changed);
render(
<DIProvider gateways={gateways}>
<ProjectSettingsPanel projectId={project.id} />
</DIProvider>,
);
const picker = (await screen.findByLabelText("Couleur du projet")) as HTMLInputElement;
await waitFor(() => expect(picker.disabled).toBe(false));
fireEvent.change(picker, { target: { value: "#aa3366" } });
await waitFor(() => expect(update).toHaveBeenCalledWith(project.id, { themeColor: "#AA3366" }));
expect(changed).toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Rétablir la couleur par défaut" }));
await waitFor(() => expect(update).toHaveBeenLastCalledWith(project.id, { themeColor: null }));
expect(screen.getByText("Contexte du projet")).toBeTruthy();
window.removeEventListener(PROJECT_THEME_CHANGED_EVENT, changed);
});
it("keeps strict colours and raises dark accents to readable contrast", () => {
expect(validThemeColor("#12abEF")).toBe("#12ABEF");
expect(validThemeColor("red")).toBeNull();
expect(accessibleProjectAccent("#000000")).not.toBe("#000000");
});
});

View File

@ -0,0 +1,91 @@
import { useEffect, useState } from "react";
import { useGateways } from "@/app/di";
import { Button, Panel, Spinner } from "@/shared";
import { ProjectContextPanel } from "./ProjectContextPanel";
import { DEFAULT_PROJECT_COLOR, validThemeColor } from "./projectTheme";
export const PROJECT_THEME_CHANGED_EVENT = "idea:project-theme-changed";
export function ProjectSettingsPanel({ projectId }: { projectId: string }) {
const { project } = useGateways();
const [themeColor, setThemeColor] = useState<string | null>(null);
const [busy, setBusy] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
setBusy(true);
project
.readProjectSettings(projectId)
.then((settings) => {
if (!cancelled) {
setThemeColor(validThemeColor(settings.themeColor));
setError(null);
}
})
.catch(() => {
if (!cancelled) setError("Impossible de charger les paramètres du projet.");
})
.finally(() => {
if (!cancelled) setBusy(false);
});
return () => {
cancelled = true;
};
}, [project, projectId]);
async function save(next: string | null) {
setBusy(true);
setError(null);
try {
const saved = await project.updateProjectSettings(projectId, { themeColor: next });
const normalized = validThemeColor(saved.themeColor);
setThemeColor(normalized);
window.dispatchEvent(
new CustomEvent(PROJECT_THEME_CHANGED_EVENT, {
detail: { projectId, themeColor: normalized },
}),
);
} catch {
setError("Impossible d’enregistrer la couleur du projet.");
} finally {
setBusy(false);
}
}
return (
<div className="flex flex-col gap-4">
<Panel title="Apparence" className="flex flex-col gap-4 p-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<label className="flex items-center gap-3 text-sm font-medium text-content">
Couleur du projet
<input
aria-label="Couleur du projet"
type="color"
value={themeColor ?? DEFAULT_PROJECT_COLOR}
disabled={busy}
onChange={(event) => void save(event.target.value.toUpperCase())}
className="h-9 w-12 cursor-pointer rounded border border-border bg-raised p-1 disabled:cursor-not-allowed"
/>
</label>
<Button size="sm" variant="ghost" disabled={busy || themeColor === null} onClick={() => void save(null)}>
Rétablir la couleur par défaut
</Button>
</div>
{busy && <Spinner size={14} />}
{error && <p role="alert" className="text-sm text-danger">{error}</p>}
</Panel>
<section aria-labelledby="project-context-settings-title">
<h2
id="project-context-settings-title"
className="mb-2 text-sm font-semibold text-content"
>
Contexte du projet
</h2>
<ProjectContextPanel projectId={projectId} />
</section>
</div>
);
}

View File

@ -13,6 +13,7 @@
import type { TabItem } from "@/shared"; import type { TabItem } from "@/shared";
import { Button, Tabs, cn } from "@/shared"; import { Button, Tabs, cn } from "@/shared";
import type { ProjectActivityStatus } from "./projectActivity"; import type { ProjectActivityStatus } from "./projectActivity";
import { accessibleProjectAccent } from "./projectTheme";
export interface ProjectTabsProps { export interface ProjectTabsProps {
items: TabItem[]; items: TabItem[];
@ -25,6 +26,7 @@ export interface ProjectTabsProps {
onOpenProjectsPanel: () => void; onOpenProjectsPanel: () => void;
/** Per-project custom CLI activity, keyed by project id. Missing = none. */ /** Per-project custom CLI activity, keyed by project id. Missing = none. */
activityByProjectId?: Record<string, ProjectActivityStatus>; activityByProjectId?: Record<string, ProjectActivityStatus>;
themeColorByProjectId?: Record<string, string | null>;
className?: string; className?: string;
} }
@ -36,10 +38,15 @@ export function ProjectTabs({
projectsPanelOpen, projectsPanelOpen,
onOpenProjectsPanel, onOpenProjectsPanel,
activityByProjectId = {}, activityByProjectId = {},
themeColorByProjectId = {},
className, className,
}: ProjectTabsProps) { }: ProjectTabsProps) {
const tabs = items.map((item) => ({ const tabs = items.map((item) => ({
...item, ...item,
themeColor: themeColorByProjectId[item.id] ?? null,
themeAccent: themeColorByProjectId[item.id]
? accessibleProjectAccent(themeColorByProjectId[item.id]!)
: null,
leading: ( leading: (
<ProjectActivityDot <ProjectActivityDot
status={activityByProjectId[item.id] ?? "none"} status={activityByProjectId[item.id] ?? "none"}

View File

@ -81,6 +81,8 @@ import { useProjectActivity } from "./useProjectActivity";
import { ProjectTabs } from "./ProjectTabs"; import { ProjectTabs } from "./ProjectTabs";
import { ProjectActionsMenu } from "./ProjectActionsMenu"; import { ProjectActionsMenu } from "./ProjectActionsMenu";
import { RemoveProjectDialog } from "./RemoveProjectDialog"; import { RemoveProjectDialog } from "./RemoveProjectDialog";
import { PROJECT_THEME_CHANGED_EVENT } from "./ProjectSettingsPanel";
import { projectThemeStyle, validThemeColor } from "./projectTheme";
import { ViewPanelBody, type ViewPanelId } from "./ViewPanelBody"; import { ViewPanelBody, type ViewPanelId } from "./ViewPanelBody";
import { import {
PANEL_TITLE, PANEL_TITLE,
@ -99,6 +101,7 @@ import {
const PANEL_SIZE: Record<PanelId, FloatingWindowSize> = { const PANEL_SIZE: Record<PanelId, FloatingWindowSize> = {
projects: "md", projects: "md",
context: "lg", context: "lg",
projectSettings: "lg",
work: "lg", work: "lg",
tickets: "lg", tickets: "lg",
agents: "lg", agents: "lg",
@ -235,6 +238,7 @@ export function ProjectsView() {
system, system,
window: windowGateway, window: windowGateway,
focusedProject, focusedProject,
project,
git, git,
agent, agent,
} = useGateways(); } = useGateways();
@ -273,8 +277,15 @@ export function ProjectsView() {
const [removalPending, setRemovalPending] = useState(false); const [removalPending, setRemovalPending] = useState(false);
const [removalError, setRemovalError] = useState<string | null>(null); const [removalError, setRemovalError] = useState<string | null>(null);
const [removalNotice, setRemovalNotice] = useState<Project | null>(null); const [removalNotice, setRemovalNotice] = useState<Project | null>(null);
const [projectThemeColors, setProjectThemeColors] = useState<
Record<string, string | null>
>({});
const active = vm.openTabs.find((t) => t.id === vm.activeTabId) ?? null; const active = vm.openTabs.find((t) => t.id === vm.activeTabId) ?? null;
const openProjectThemeKey = vm.openTabs.map((tab) => tab.id).join("\u0000");
const activeThemeStyle = projectThemeStyle(
active ? projectThemeColors[active.id] : null,
);
const activeViewerConversation = const activeViewerConversation =
viewerConversation?.projectId === active?.id ? viewerConversation : null; viewerConversation?.projectId === active?.id ? viewerConversation : null;
const showRestoreNotification = const showRestoreNotification =
@ -301,6 +312,40 @@ export function ProjectsView() {
useEffect(() => { useEffect(() => {
if (vm.restoreFailures.length === 0) setRestoreDetailsOpen(false); if (vm.restoreFailures.length === 0) setRestoreDetailsOpen(false);
}, [vm.restoreFailures.length]); }, [vm.restoreFailures.length]);
useEffect(() => {
let cancelled = false;
void Promise.all(
vm.openTabs.map(async (tab) => {
try {
const settings = await project.readProjectSettings(tab.id);
return [tab.id, validThemeColor(settings.themeColor)] as const;
} catch {
return [tab.id, null] as const;
}
}),
).then((entries) => {
if (!cancelled) setProjectThemeColors(Object.fromEntries(entries));
});
return () => {
cancelled = true;
};
}, [project, openProjectThemeKey]);
useEffect(() => {
const update = (event: Event) => {
const detail = (
event as CustomEvent<{ projectId: string; themeColor: string | null }>
).detail;
if (!detail?.projectId) return;
setProjectThemeColors((current) => ({
...current,
[detail.projectId]: validThemeColor(detail.themeColor),
}));
};
window.addEventListener(PROJECT_THEME_CHANGED_EVENT, update);
return () => window.removeEventListener(PROJECT_THEME_CHANGED_EVENT, update);
}, []);
const projectNameById = useMemo(() => { const projectNameById = useMemo(() => {
const names = new Map<string, string>(); const names = new Map<string, string>();
for (const project of vm.projects) names.set(project.id, project.name); for (const project of vm.projects) names.set(project.id, project.name);
@ -601,6 +646,7 @@ export function ProjectsView() {
// placement is marked in the submenu (and the parent entry shows ● when the // placement is marked in the submenu (and the parent entry shows ● when the
// panel is open somewhere). Order per UX: content panels first, Projects last. // panel is open somewhere). Order per UX: content panels first, Projects last.
const panelOrder: PanelId[] = [ const panelOrder: PanelId[] = [
"projectSettings",
"context", "context",
"work", "work",
"tickets", "tickets",
@ -659,6 +705,11 @@ export function ProjectsView() {
const nativePanelItems: MenuBarItem[] = panelOrder.map((panel) => ({ const nativePanelItems: MenuBarItem[] = panelOrder.map((panel) => ({
id: panel, id: panel,
label: PANEL_TITLE[panel], label: PANEL_TITLE[panel],
disabled: panel === "projectSettings" && !active,
title:
panel === "projectSettings" && !active
? "Ouvrez ou sélectionnez un projet pour accéder à ses paramètres."
: undefined,
active: placementOf(placements, panel) !== "closed", active: placementOf(placements, panel) !== "closed",
onSelect: () => {}, onSelect: () => {},
submenu: placementSubmenu(panel), submenu: placementSubmenu(panel),
@ -954,6 +1005,7 @@ export function ProjectsView() {
{/* ── Project tab bar (#26): tabs = open projects, "+" opens Projects ── */} {/* ── Project tab bar (#26): tabs = open projects, "+" opens Projects ── */}
<ProjectTabs <ProjectTabs
items={vm.openTabs.map((t) => ({ id: t.id, label: t.name }))} items={vm.openTabs.map((t) => ({ id: t.id, label: t.name }))}
themeColorByProjectId={projectThemeColors}
activeTabId={vm.activeTabId} activeTabId={vm.activeTabId}
onSelect={(id) => vm.activateTab(id)} onSelect={(id) => vm.activateTab(id)}
onClose={(id) => void vm.closeTab(id)} onClose={(id) => void vm.closeTab(id)}
@ -965,6 +1017,11 @@ export function ProjectsView() {
}} }}
/> />
<div
data-testid="active-project-theme-scope"
className="flex min-h-0 flex-1 flex-col overflow-hidden bg-canvas"
style={activeThemeStyle}
>
{/* ── Menu bar (replaces the former left sidebar) ── */} {/* ── Menu bar (replaces the former left sidebar) ── */}
<PluginMenuRenderBoundary <PluginMenuRenderBoundary
resetKey={pluginMenuResetKey} resetKey={pluginMenuResetKey}
@ -1205,5 +1262,6 @@ export function ProjectsView() {
</div> </div>
)} )}
</div> </div>
</div>
); );
} }

View File

@ -21,6 +21,7 @@ import { ProjectWorkStatePanel } from "@/features/workstate";
import { TicketsView } from "@/features/tickets"; import { TicketsView } from "@/features/tickets";
import { GitPanel } from "@/features/git"; import { GitPanel } from "@/features/git";
import { ProjectContextPanel } from "./ProjectContextPanel"; import { ProjectContextPanel } from "./ProjectContextPanel";
import { ProjectSettingsPanel } from "./ProjectSettingsPanel";
import type { PanelId } from "./viewPlacement"; import type { PanelId } from "./viewPlacement";
/** Panels that render a project-scoped view (everything except "projects"). */ /** Panels that render a project-scoped view (everything except "projects"). */
@ -45,6 +46,8 @@ export function ViewPanelBody({
switch (panel) { switch (panel) {
case "context": case "context":
return <ProjectContextPanel projectId={projectId} />; return <ProjectContextPanel projectId={projectId} />;
case "projectSettings":
return <ProjectSettingsPanel projectId={projectId} />;
case "work": case "work":
return ( return (
<ProjectWorkStatePanel <ProjectWorkStatePanel

View File

@ -0,0 +1,59 @@
import type { CSSProperties } from "react";
export const DEFAULT_PROJECT_COLOR = "#4C8DFF";
export function validThemeColor(value: string | null | undefined): string | null {
return value && /^#[0-9A-Fa-f]{6}$/.test(value) ? value.toUpperCase() : null;
}
function rgb(hex: string): [number, number, number] {
return [1, 3, 5].map((index) => Number.parseInt(hex.slice(index, index + 2), 16)) as [
number,
number,
number,
];
}
function luminance(hex: string): number {
const channels = rgb(hex).map((channel) => {
const value = channel / 255;
return value <= 0.03928 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
});
return channels[0] * 0.2126 + channels[1] * 0.7152 + channels[2] * 0.0722;
}
function contrast(a: string, b: string): number {
const [light, dark] = [luminance(a), luminance(b)].sort((x, y) => y - x);
return (light + 0.05) / (dark + 0.05);
}
/** Lightens very dark user colours until accent text remains WCAG-AA on canvas. */
export function accessibleProjectAccent(raw: string): string {
const color = validThemeColor(raw) ?? DEFAULT_PROJECT_COLOR;
const [r, g, b] = rgb(color);
for (let amount = 0; amount <= 1; amount += 0.02) {
const next = `#${[r, g, b]
.map((channel) => Math.round(channel + (255 - channel) * amount).toString(16).padStart(2, "0"))
.join("")}`;
if (contrast(next, "#0E1116") >= 4.5) return next.toUpperCase();
}
return "#FFFFFF";
}
export function projectThemeStyle(themeColor: string | null | undefined): CSSProperties {
const raw = validThemeColor(themeColor);
if (!raw) return {};
const accent = accessibleProjectAccent(raw);
return {
"--project-theme-color": raw,
"--color-primary": accent,
"--color-primary-hover": `color-mix(in srgb, ${accent} 86%, white)`,
"--color-on-primary": contrast(accent, "#0E1116") >= 4.5 ? "#0E1116" : "#FFFFFF",
"--color-canvas": `color-mix(in srgb, #0e1116 96%, ${raw})`,
"--color-surface": `color-mix(in srgb, #161b22 95%, ${raw})`,
"--color-raised": `color-mix(in srgb, #1c2430 94%, ${raw})`,
"--color-overlay": `color-mix(in srgb, #222c3a 94%, ${raw})`,
"--color-border": `color-mix(in srgb, #2b3440 88%, ${accent})`,
"--color-border-strong": accent,
} as CSSProperties;
}

View File

@ -610,6 +610,33 @@ describe("ProjectsView (with MockProjectGateway)", () => {
}); });
}); });
it("opens project settings from Panneaux and reuses the context editor", async () => {
const project = new MockProjectGateway();
await project.createProject("alpha", "/p/a");
renderView(project);
await screen.findByText("/p/a");
fireEvent.click(screen.getByRole("button", { name: "Open" }));
await screen.findByRole("tab", { name: "alpha" });
openPanel("Paramètres du projet");
expect(await screen.findByText("Apparence")).toBeTruthy();
expect(screen.getByLabelText("Couleur du projet")).toBeTruthy();
expect(screen.getByText("Contexte du projet")).toBeTruthy();
expect(screen.getByLabelText("project context")).toBeTruthy();
});
it("disables project settings while no project is active", async () => {
renderView(new MockProjectGateway());
await waitForIdle();
fireEvent.click(screen.getByRole("button", { name: "Panneaux" }));
const item = screen.getByRole("button", { name: "Paramètres du projet" });
expect(item.hasAttribute("disabled")).toBe(true);
expect(item.getAttribute("title")).toBe(
"Ouvrez ou sélectionnez un projet pour accéder à ses paramètres.",
);
});
it("Browse… button calls pickFolder and fills the root field with the returned path", async () => { it("Browse… button calls pickFolder and fills the root field with the returned path", async () => {
const system = new MockSystemGateway(); const system = new MockSystemGateway();
renderView(new MockProjectGateway(), system); renderView(new MockProjectGateway(), system);

View File

@ -23,6 +23,7 @@ import type { ViewWindowSnapshot } from "@/ports";
export type PanelId = export type PanelId =
| "projects" | "projects"
| "context" | "context"
| "projectSettings"
| "work" | "work"
| "tickets" | "tickets"
| "agents" | "agents"
@ -50,6 +51,7 @@ export type ViewPlacements = Partial<Record<PanelId, ViewPlacement>>;
export const PANEL_TITLE: Record<PanelId, string> = { export const PANEL_TITLE: Record<PanelId, string> = {
projects: "Projects", projects: "Projects",
context: "Project context", context: "Project context",
projectSettings: "Paramètres du projet",
work: "Work state", work: "Work state",
tickets: "Tickets", tickets: "Tickets",
agents: "Agents", agents: "Agents",

View File

@ -26,13 +26,15 @@ import { ProfilesSettings } from "@/features/first-run";
import { DevicesScreen } from "@/features/devices"; import { DevicesScreen } from "@/features/devices";
import { PluginsPanel } from "@/features/plugins"; import { PluginsPanel } from "@/features/plugins";
import { DeploymentSettings } from "./DeploymentSettings"; import { DeploymentSettings } from "./DeploymentSettings";
import { TerminalSettings } from "./TerminalSettings";
/** The Settings sections, in menu/nav order. */ /** The Settings sections, in menu/nav order. */
export type SettingsSection = "aiProfiles" | "deployment" | "devices" | "plugins"; export type SettingsSection = "aiProfiles" | "terminal" | "deployment" | "devices" | "plugins";
/** Human labels, shared by the nav column and the `Settings` menu (ticket #78 — French). */ /** Human labels, shared by the nav column and the `Settings` menu (ticket #78 — French). */
export const SETTINGS_SECTION_LABEL: Record<SettingsSection, string> = { export const SETTINGS_SECTION_LABEL: Record<SettingsSection, string> = {
aiProfiles: "Profils IA", aiProfiles: "Profils IA",
terminal: "Terminal",
deployment: "Déploiement", deployment: "Déploiement",
devices: "Appareils", devices: "Appareils",
plugins: "Plugins", plugins: "Plugins",
@ -41,6 +43,7 @@ export const SETTINGS_SECTION_LABEL: Record<SettingsSection, string> = {
/** Section order — the single source of truth for both nav and menu. */ /** Section order — the single source of truth for both nav and menu. */
export const SETTINGS_SECTIONS: SettingsSection[] = [ export const SETTINGS_SECTIONS: SettingsSection[] = [
"aiProfiles", "aiProfiles",
"terminal",
"deployment", "deployment",
"devices", "devices",
"plugins", "plugins",
@ -98,6 +101,8 @@ export function SettingsView({
<div className="w-full max-w-2xl"> <div className="w-full max-w-2xl">
{section === "aiProfiles" ? ( {section === "aiProfiles" ? (
<ProfilesSettings /> <ProfilesSettings />
) : section === "terminal" ? (
<TerminalSettings />
) : section === "deployment" ? ( ) : section === "deployment" ? (
<DeploymentSettings /> <DeploymentSettings />
) : section === "plugins" ? ( ) : section === "plugins" ? (

View File

@ -0,0 +1,30 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { DIProvider } from "@/app/di";
import { createMockGateways } from "@/adapters/mock";
import { TerminalSettings } from "./TerminalSettings";
describe("TerminalSettings", () => {
it("loads and persists the exclusive global default without touching sessions", async () => {
const gateways = createMockGateways();
const update = vi.spyOn(gateways.userSettings, "updateUserSettings");
const close = vi.spyOn(gateways.terminal, "closeTerminal");
render(
<DIProvider gateways={gateways}>
<TerminalSettings />
</DIProvider>,
);
const native = (await screen.findByLabelText("TUI native")) as HTMLInputElement;
const cli = screen.getByLabelText("CLI IdeA") as HTMLInputElement;
await waitFor(() => expect(native.checked).toBe(true));
fireEvent.click(cli);
await waitFor(() =>
expect(update).toHaveBeenCalledWith({ defaultAgentTerminalInterface: "ideaCli" }),
);
expect(cli.checked).toBe(true);
expect(close).not.toHaveBeenCalled();
expect(screen.getByText("Utilisée à l'ouverture d'un nouveau terminal. Les terminaux déjà ouverts ne sont pas modifiés.")).toBeTruthy();
});
});

View File

@ -0,0 +1,86 @@
import { useEffect, useState } from "react";
import type { DefaultAgentTerminalInterface } from "@/ports";
import { Panel, Spinner } from "@/shared";
import { useGateways } from "@/app/di";
const choices: Array<{ value: DefaultAgentTerminalInterface; label: string }> = [
{ value: "nativeTui", label: "TUI native" },
{ value: "ideaCli", label: "CLI IdeA" },
];
export function TerminalSettings() {
const { userSettings } = useGateways();
const [value, setValue] = useState<DefaultAgentTerminalInterface>("nativeTui");
const [busy, setBusy] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
setBusy(true);
userSettings
.readUserSettings()
.then((settings) => {
if (!cancelled) {
setValue(settings.defaultAgentTerminalInterface ?? "nativeTui");
setError(null);
}
})
.catch(() => {
if (!cancelled) setError("Impossible de charger la préférence de terminal.");
})
.finally(() => {
if (!cancelled) setBusy(false);
});
return () => {
cancelled = true;
};
}, [userSettings]);
async function select(next: DefaultAgentTerminalInterface) {
const previous = value;
setValue(next);
setBusy(true);
setError(null);
try {
const saved = await userSettings.updateUserSettings({
defaultAgentTerminalInterface: next,
});
setValue(saved.defaultAgentTerminalInterface ?? "nativeTui");
} catch {
setValue(previous);
setError("Impossible d’enregistrer la préférence de terminal.");
} finally {
setBusy(false);
}
}
return (
<Panel title="Terminal" className="flex flex-col gap-4 p-4">
<fieldset disabled={busy} className="flex flex-col gap-3">
<legend className="text-sm font-semibold text-content">
Interface de terminal par défaut
</legend>
<div className="flex flex-col gap-2">
{choices.map((choice) => (
<label key={choice.value} className="flex items-center gap-2 text-sm text-content">
<input
type="radio"
name="default-agent-terminal-interface"
value={choice.value}
checked={value === choice.value}
onChange={() => void select(choice.value)}
/>
{choice.label}
</label>
))}
</div>
<p className="text-xs text-muted">
Utilisée à l'ouverture d'un nouveau terminal. Les terminaux déjà ouverts ne sont pas modifiés.
</p>
</fieldset>
{busy && <Spinner size={14} />}
{error && <p role="alert" className="text-sm text-danger">{error}</p>}
</Panel>
);
}

View File

@ -7,5 +7,6 @@ export {
type SettingsSection, type SettingsSection,
} from "./SettingsView"; } from "./SettingsView";
export { DeploymentSettings } from "./DeploymentSettings"; export { DeploymentSettings } from "./DeploymentSettings";
export { TerminalSettings } from "./TerminalSettings";
export { useDeployment } from "./useDeployment"; export { useDeployment } from "./useDeployment";
export type { DeploymentVm } from "./useDeployment"; export type { DeploymentVm } from "./useDeployment";

View File

@ -19,7 +19,7 @@ import { useGateways } from "@/app/di";
import { leaves } from "@/features/layout/layout"; import { leaves } from "@/features/layout/layout";
import { useLayout } from "@/features/layout/useLayout"; import { useLayout } from "@/features/layout/useLayout";
import type { LayoutViewModel } from "@/features/layout/useLayout"; import type { LayoutViewModel } from "@/features/layout/useLayout";
import { Button, Panel, Spinner, cn } from "@/shared"; import { Button, EntryTimestamp, Panel, Spinner, cn } from "@/shared";
import { useProjectWorkState } from "./useProjectWorkState"; import { useProjectWorkState } from "./useProjectWorkState";
export interface ProjectWorkStatePanelProps { export interface ProjectWorkStatePanelProps {
@ -307,7 +307,10 @@ function ConversationSummaryLine({
<ul className="space-y-0.5"> <ul className="space-y-0.5">
{(summary.recentTurns ?? []).map((turn) => ( {(summary.recentTurns ?? []).map((turn) => (
<li key={`${turn.atMs}-${turn.role}-${turn.textPreview}`}> <li key={`${turn.atMs}-${turn.role}-${turn.textPreview}`}>
<span className="font-medium text-content">{turn.role}:</span>{" "} <span className="inline-flex items-baseline gap-1">
<span className="font-medium text-content">{turn.role}:</span>
<EntryTimestamp atMs={turn.atMs} />
</span>{" "}
{turn.textPreview} {turn.textPreview}
</li> </li>
))} ))}
@ -659,7 +662,7 @@ function AgentRow({
} }
async function stop(): Promise<void> { async function stop(): Promise<void> {
if (!agent.live || !agentGateway?.stopLiveAgent) return; if (!agent.live || !agentGateway) return;
const warning = currentTurn const warning = currentTurn
? " The current turn will be interrupted." ? " The current turn will be interrupted."
: ""; : "";
@ -667,10 +670,15 @@ function AgentRow({
setActionBusy(true); setActionBusy(true);
setMessage(null); setMessage(null);
try { try {
const stopped = await agentGateway.stopLiveAgent(projectId, agent.agentId); const stopped = await agentGateway.stopLiveAgent(
projectId,
agent.agentId,
"Arrêt demandé depuis Travail",
);
if (visibleNodeIds.has(agent.live.nodeId)) { if (visibleNodeIds.has(agent.live.nodeId)) {
const leaf = visibleLeaves.find((candidate) => candidate.id === agent.live?.nodeId); const leaf = visibleLeaves.find((candidate) => candidate.id === agent.live?.nodeId);
if (!leaf?.session || leaf.session === stopped.sessionId) { const stoppedSessionIds = new Set(stopped.stopped.map((runtime) => runtime.sessionId));
if (!leaf?.session || stoppedSessionIds.has(leaf.session) || stopped.alreadyStopped) {
await layout.setSession(agent.live.nodeId, null); await layout.setSession(agent.live.nodeId, null);
} }
} }
@ -763,7 +771,7 @@ function AgentRow({
size="sm" size="sm"
variant="danger" variant="danger"
loading={actionBusy} loading={actionBusy}
disabled={!agentGateway?.stopLiveAgent} disabled={!agentGateway}
onClick={() => void stop()} onClick={() => void stop()}
> >
Stop Stop

View File

@ -1006,7 +1006,13 @@ describe("ProjectWorkStatePanel", () => {
"Stop Runner? The current turn will be interrupted.", "Stop Runner? The current turn will be interrupted.",
), ),
); );
await waitFor(() => expect(stopSpy).toHaveBeenCalledWith(PROJECT_ID, created.id)); await waitFor(() =>
expect(stopSpy).toHaveBeenCalledWith(
PROJECT_ID,
created.id,
"Arrêt demandé depuis Travail",
),
);
await waitFor(() => expect(refreshSpy).toHaveBeenCalled()); await waitFor(() => expect(refreshSpy).toHaveBeenCalled());
await waitFor(async () => { await waitFor(async () => {
const leaf = leaves(await layout.loadLayout(PROJECT_ID))[0]; const leaf = leaves(await layout.loadLayout(PROJECT_ID))[0];

View File

@ -71,6 +71,8 @@ function gateways(overrides: {
readOpenProjectRestoreState: vi.fn(async () => ({ version: 1, entries: [], updatedAt: 0 })), readOpenProjectRestoreState: vi.fn(async () => ({ version: 1, entries: [], updatedAt: 0 })),
readProjectContext: vi.fn(async () => "project context"), readProjectContext: vi.fn(async () => "project context"),
updateProjectContext: vi.fn(), updateProjectContext: vi.fn(),
readProjectSettings: vi.fn(async () => ({ themeColor: null })),
updateProjectSettings: vi.fn(async (_projectId, settings) => settings),
listProjectFiles: vi.fn(async (_projectId, path) => ({ path, entries: [] })), listProjectFiles: vi.fn(async (_projectId, path) => ({ path, entries: [] })),
downloadProjectFile: vi.fn(), downloadProjectFile: vi.fn(),
downloadProjectDirectory: vi.fn(), downloadProjectDirectory: vi.fn(),

View File

@ -257,7 +257,7 @@ export interface AgentGateway {
* Stops an already-live agent session without going through terminal teardown * Stops an already-live agent session without going through terminal teardown
* commands from the Work panel. The backend owns the live-agent lifecycle. * commands from the Work panel. The backend owns the live-agent lifecycle.
*/ */
stopLiveAgent?(projectId: string, agentId: string): Promise<StoppedLiveAgent>; stopLiveAgent(projectId: string, agentId: string, reason?: string): Promise<StoppedLiveAgent>;
/** Creates a new agent from scratch; returns the created agent. */ /** Creates a new agent from scratch; returns the created agent. */
createAgent(projectId: string, input: CreateAgentInput): Promise<Agent>; createAgent(projectId: string, input: CreateAgentInput): Promise<Agent>;
/** /**
@ -435,9 +435,30 @@ export interface LiveAgent {
/** Result returned when the backend stops a live agent. */ /** Result returned when the backend stops a live agent. */
export interface StoppedLiveAgent { export interface StoppedLiveAgent {
agentId: string; agentId: string;
stopped: StoppedAgentRuntime[];
alreadyStopped: boolean;
}
export interface StoppedAgentRuntime {
sessionId: string; sessionId: string;
nodeId: string;
kind: "pty" | "structured"; kind: "pty" | "structured";
runtimeState?: AgentRuntimeState; runtimeState: AgentRuntimeState;
}
export type DefaultAgentTerminalInterface = "nativeTui" | "ideaCli";
export interface UserSettings {
defaultAgentTerminalInterface: DefaultAgentTerminalInterface | null;
}
export interface UserSettingsGateway {
readUserSettings(): Promise<UserSettings>;
updateUserSettings(settings: UserSettings): Promise<UserSettings>;
}
export interface ProjectSettings {
themeColor: string | null;
} }
export type AgentRuntimeState = export type AgentRuntimeState =
@ -596,6 +617,10 @@ export interface ProjectGateway {
readProjectContext(projectId: string): Promise<string>; readProjectContext(projectId: string): Promise<string>;
/** Overwrites the shared project context stored at `.ideai/CONTEXT.md`. */ /** Overwrites the shared project context stored at `.ideai/CONTEXT.md`. */
updateProjectContext(projectId: string, content: string): Promise<void>; updateProjectContext(projectId: string, content: string): Promise<void>;
/** Reads project-owned settings. */
readProjectSettings(projectId: string): Promise<ProjectSettings>;
/** Replaces project-owned settings. */
updateProjectSettings(projectId: string, settings: ProjectSettings): Promise<ProjectSettings>;
/** Lists one project-relative directory for the web project files surface. */ /** Lists one project-relative directory for the web project files surface. */
listProjectFiles(projectId: string, path: string): Promise<ProjectFileListing>; listProjectFiles(projectId: string, path: string): Promise<ProjectFileListing>;
/** Downloads one project-relative file. */ /** Downloads one project-relative file. */
@ -1784,6 +1809,7 @@ export interface Gateways {
window: WindowGateway; window: WindowGateway;
focusedProject: FocusedProjectGateway; focusedProject: FocusedProjectGateway;
uiPreferences: UiPreferencesGateway; uiPreferences: UiPreferencesGateway;
userSettings: UserSettingsGateway;
plugin: PluginGateway; plugin: PluginGateway;
pluginWorkspace: PluginWorkspaceGateway; pluginWorkspace: PluginWorkspaceGateway;
pluginTask: PluginTaskGateway; pluginTask: PluginTaskGateway;

View File

@ -32,6 +32,13 @@ export type { ToolbarProps } from "./ui/Toolbar";
export { Spinner } from "./ui/Spinner"; export { Spinner } from "./ui/Spinner";
export type { SpinnerProps } from "./ui/Spinner"; export type { SpinnerProps } from "./ui/Spinner";
export {
EntryTimestamp,
formatFullLocalTime,
formatShortLocalTime,
normalizeTimestamp,
} from "./ui/EntryTimestamp";
export { zIndex } from "./ui/zIndex"; export { zIndex } from "./ui/zIndex";
export type { ZIndexLevel } from "./ui/zIndex"; export type { ZIndexLevel } from "./ui/zIndex";

View File

@ -0,0 +1,19 @@
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { EntryTimestamp, formatShortLocalTime } from "./EntryTimestamp";
describe("EntryTimestamp", () => {
it("shows a stable local HH:mm and exposes the full zoned date", () => {
const atMs = Date.UTC(2026, 8, 10, 12, 37);
render(<EntryTimestamp atMs={atMs} />);
const timestamp = screen.getByText(formatShortLocalTime(atMs)!);
expect(timestamp.getAttribute("title")).toBeTruthy();
expect(timestamp.getAttribute("tabindex")).toBe("0");
});
it("does not invent a timestamp for legacy entries", () => {
render(<EntryTimestamp atMs={null} />);
expect(screen.getByLabelText("Heure indisponible").textContent).toBe("—");
});
});

View File

@ -0,0 +1,52 @@
import { cn } from "../lib/cn";
export function normalizeTimestamp(atMs: number | null | undefined): number | null {
return typeof atMs === "number" && Number.isFinite(atMs) && atMs > 0 && !Number.isNaN(new Date(atMs).getTime())
? atMs
: null;
}
export function formatShortLocalTime(atMs: number | null | undefined): string | null {
const value = normalizeTimestamp(atMs);
if (value === null) return null;
const parts = new Intl.DateTimeFormat(undefined, {
hour: "2-digit",
minute: "2-digit",
hourCycle: "h23",
}).formatToParts(new Date(value));
const hour = parts.find((part) => part.type === "hour")?.value;
const minute = parts.find((part) => part.type === "minute")?.value;
return hour && minute ? `${hour}:${minute}` : null;
}
export function formatFullLocalTime(atMs: number | null | undefined): string {
const value = normalizeTimestamp(atMs);
if (value === null) return "Heure indisponible";
return new Intl.DateTimeFormat(undefined, {
dateStyle: "full",
timeStyle: "long",
}).format(new Date(value));
}
export function EntryTimestamp({
atMs,
className,
}: {
atMs: number | null | undefined;
className?: string;
}) {
const value = normalizeTimestamp(atMs);
const short = formatShortLocalTime(value);
const full = formatFullLocalTime(value);
return (
<time
dateTime={value === null ? undefined : new Date(value).toISOString()}
title={full}
aria-label={full}
tabIndex={0}
className={cn("shrink-0 text-faint", className)}
>
{short ?? "—"}
</time>
);
}

View File

@ -21,6 +21,7 @@ export interface MenuBarItem {
label: string; label: string;
onSelect: () => void; onSelect: () => void;
disabled?: boolean; disabled?: boolean;
title?: string;
/** Renders a selected/active marker (e.g. the currently-open panel). */ /** Renders a selected/active marker (e.g. the currently-open panel). */
active?: boolean; active?: boolean;
/** /**
@ -124,6 +125,7 @@ export function MenuBar({ menus, className }: MenuBarProps) {
<button <button
type="button" type="button"
disabled={item.disabled} disabled={item.disabled}
title={item.title}
aria-haspopup={hasSub ? "menu" : undefined} aria-haspopup={hasSub ? "menu" : undefined}
aria-expanded={hasSub ? subOpen : undefined} aria-expanded={hasSub ? subOpen : undefined}
onClick={() => { onClick={() => {

View File

@ -16,6 +16,9 @@ export interface TabItem {
label: string; label: string;
/** Optional leading visual, such as a status indicator. */ /** Optional leading visual, such as a status indicator. */
leading?: ReactNode; leading?: ReactNode;
/** Optional project colour used only for this tab's subtle neutral tint. */
themeColor?: string | null;
themeAccent?: string | null;
} }
export interface TabsProps { export interface TabsProps {
@ -42,6 +45,14 @@ export function Tabs({ items, value, onSelect, onClose, className }: TabsProps)
return ( return (
<div <div
key={tab.id} key={tab.id}
style={
tab.themeColor
? {
backgroundColor: `color-mix(in srgb, var(--color-raised) ${active ? 90 : 96}%, ${tab.themeColor})`,
...(active ? { borderColor: tab.themeAccent ?? tab.themeColor } : {}),
}
: undefined
}
className={cn( className={cn(
"group flex items-center gap-1 rounded-md border px-1 transition-colors", "group flex items-center gap-1 rounded-md border px-1 transition-colors",
active active