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:
@ -344,6 +344,7 @@ fn progress_entity_key(progress: &ReplyProgressDto) -> Option<String> {
|
||||
fn reply_chunk_bytes(chunk: &ReplyChunk) -> usize {
|
||||
match chunk {
|
||||
ReplyChunk::UserPrompt {
|
||||
at_ms: _,
|
||||
text,
|
||||
attachments,
|
||||
attachment_refs,
|
||||
@ -360,8 +361,8 @@ fn reply_chunk_bytes(chunk: &ReplyChunk) -> usize {
|
||||
})
|
||||
.sum::<usize>()
|
||||
}
|
||||
ReplyChunk::TextDelta { text } => text.len(),
|
||||
ReplyChunk::ToolActivity { label } => label.len(),
|
||||
ReplyChunk::TextDelta { text, .. } => text.len(),
|
||||
ReplyChunk::ToolActivity { label, .. } => label.len(),
|
||||
ReplyChunk::Progress { progress } => {
|
||||
progress.label.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.tool_name.as_ref().map_or(0, String::len)
|
||||
}
|
||||
ReplyChunk::Final { content } => content.len(),
|
||||
ReplyChunk::Error { message } => message.len(),
|
||||
ReplyChunk::Final { content, .. } => content.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.
|
||||
#[must_use]
|
||||
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 {
|
||||
ReplyEvent::Progress { progress } => Some(ReplyChunk::Progress {
|
||||
progress: progress.into(),
|
||||
}),
|
||||
ReplyEvent::TextDelta { text } => Some(ReplyChunk::TextDelta { text }),
|
||||
ReplyEvent::Progress { progress } => {
|
||||
let mut progress: ReplyProgressDto = progress.into();
|
||||
progress.occurred_at_ms = at_ms;
|
||||
Some(ReplyChunk::Progress { progress })
|
||||
}
|
||||
ReplyEvent::TextDelta { text } => Some(ReplyChunk::TextDelta { text, at_ms }),
|
||||
ReplyEvent::ToolActivity { label } => Some(ReplyChunk::Progress {
|
||||
progress: ReplyProgress::new(
|
||||
ReplyProgressSource::ProviderNative,
|
||||
ReplyProgressKind::Tool,
|
||||
ReplyProgressStage::Info,
|
||||
label.clone(),
|
||||
)
|
||||
.with_tool_name(label)
|
||||
.into(),
|
||||
progress: {
|
||||
let mut progress: ReplyProgressDto = ReplyProgress::new(
|
||||
ReplyProgressSource::ProviderNative,
|
||||
ReplyProgressKind::Tool,
|
||||
ReplyProgressStage::Info,
|
||||
label.clone(),
|
||||
)
|
||||
.with_tool_name(label)
|
||||
.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 } => {
|
||||
if content.trim().is_empty() {
|
||||
Some(ReplyChunk::Error {
|
||||
message: "Réponse vide du modèle.".to_owned(),
|
||||
at_ms,
|
||||
})
|
||||
} else {
|
||||
Some(ReplyChunk::Final { content })
|
||||
Some(ReplyChunk::Final { content, at_ms })
|
||||
}
|
||||
}
|
||||
ReplyEvent::Announcement { text } => Some(ReplyChunk::Progress {
|
||||
progress: ReplyProgress::new(
|
||||
ReplyProgressSource::ProviderNative,
|
||||
ReplyProgressKind::Message,
|
||||
ReplyProgressStage::Delta,
|
||||
"message intermédiaire",
|
||||
)
|
||||
.with_text(text)
|
||||
.into(),
|
||||
progress: {
|
||||
let mut progress: ReplyProgressDto = ReplyProgress::new(
|
||||
ReplyProgressSource::ProviderNative,
|
||||
ReplyProgressKind::Message,
|
||||
ReplyProgressStage::Delta,
|
||||
"message intermédiaire",
|
||||
)
|
||||
.with_text(text)
|
||||
.into();
|
||||
progress.occurred_at_ms = at_ms;
|
||||
progress
|
||||
},
|
||||
}),
|
||||
ReplyEvent::Heartbeat => None,
|
||||
ReplyEvent::RateLimited { .. } => None,
|
||||
@ -432,5 +450,20 @@ pub fn chunk_from_event(event: ReplyEvent) -> Option<ReplyChunk> {
|
||||
pub fn unfinished_turn_chunk() -> ReplyChunk {
|
||||
ReplyChunk::Error {
|
||||
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
|
||||
}
|
||||
|
||||
@ -66,7 +66,7 @@ use crate::dto::{
|
||||
MemoryIndexDto, MemoryLinksDto, MemoryListDto, ModelServerConfigDto, ModelServerConfigListDto,
|
||||
OpenCodeProviderListDto, OpenProjectRestoreStateDto, OpenTerminalRequestDto,
|
||||
PreviewModelServerCommandDto, ProfileDto, ProfileListDto, ProfileModelCatalogDto, ProjectDto,
|
||||
ProjectListDto, ProjectMcpToolPermissionsDto, ProjectPermissionsDto,
|
||||
ProjectListDto, ProjectMcpToolPermissionsDto, ProjectPermissionsDto, ProjectSettingsDto,
|
||||
ProjectSystemPermissionsDto, ProjectWorkStateDto, ReadAgentContextResponseDto,
|
||||
ReadChatDraftResponseDto, ReadConversationPageRequestDto, ReattachChatDto, ReattachResultDto,
|
||||
RecallMemoryRequestDto, RemoveOpenProjectRestoreEntryRequestDto, RemoveProjectRequestDto,
|
||||
@ -86,8 +86,8 @@ use crate::dto::{
|
||||
UpdateAgentSystemPermissionsRequestDto, UpdateMemoryRequestDto, UpdateProjectContextRequestDto,
|
||||
UpdateProjectMcpToolPermissionsRequestDto, UpdateProjectOrchestratorRequestDto,
|
||||
UpdateProjectOrchestratorResponseDto, UpdateProjectPermissionsRequestDto,
|
||||
UpdateProjectSystemPermissionsRequestDto, UpdateSkillRequestDto, UpdateTemplateRequestDto,
|
||||
WriteTerminalRequestDto,
|
||||
UpdateProjectSettingsRequestDto, UpdateProjectSystemPermissionsRequestDto,
|
||||
UpdateSkillRequestDto, UpdateTemplateRequestDto, UserSettingsDto, WriteTerminalRequestDto,
|
||||
};
|
||||
use crate::embedded_server::{
|
||||
EmbeddedServerStatusDto, ServerExposurePreviewDto, ServerExposureSettingsDto,
|
||||
@ -815,6 +815,66 @@ pub async fn update_project_context(
|
||||
.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`.
|
||||
///
|
||||
/// # Errors
|
||||
@ -2198,7 +2258,11 @@ pub async fn stop_live_agent(
|
||||
}
|
||||
state
|
||||
.stop_live_agent
|
||||
.execute(StopLiveAgentInput { project, agent_id })
|
||||
.execute(StopLiveAgentInput {
|
||||
project,
|
||||
agent_id,
|
||||
reason: request.reason,
|
||||
})
|
||||
.await
|
||||
.map(StopLiveAgentResponseDto::from)
|
||||
.map_err(ErrorDto::from)
|
||||
@ -2372,6 +2436,10 @@ pub async fn launch_agent(
|
||||
mcp_runtime,
|
||||
allow_structured_alongside_pty: false,
|
||||
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,
|
||||
managed_temp_exposure: application::ManagedTempExposureRequest::default(),
|
||||
})
|
||||
@ -2781,6 +2849,7 @@ pub async fn agent_send(
|
||||
let _ = state.chat_bridge.send_output(
|
||||
&sid,
|
||||
ReplyChunk::UserPrompt {
|
||||
at_ms: u64::try_from(state.clock.now_millis()).ok(),
|
||||
text: prompt.clone(),
|
||||
attachments: attachment_labels,
|
||||
attachment_refs,
|
||||
@ -2793,6 +2862,7 @@ pub async fn agent_send(
|
||||
// still running.
|
||||
let (tap_tx, tap_rx) = std::sync::mpsc::channel();
|
||||
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_turn_guard = turn_guard.as_ref().map(|guard| guard.liveness_handle());
|
||||
let tap_pump = std::thread::spawn(move || {
|
||||
@ -2803,7 +2873,9 @@ pub async fn agent_send(
|
||||
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;
|
||||
};
|
||||
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
|
||||
// own* generation so a concurrent re-attach is never torn down.
|
||||
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
|
||||
// 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
|
||||
@ -2879,7 +2952,10 @@ pub async fn agent_send(
|
||||
let _ = bridge.send_output_settled(
|
||||
&sid,
|
||||
&mut settler,
|
||||
ReplyChunk::Error { message },
|
||||
ReplyChunk::Error {
|
||||
message,
|
||||
at_ms: u64::try_from(clock.now_millis()).ok(),
|
||||
},
|
||||
);
|
||||
break 'logical_turn;
|
||||
}
|
||||
@ -2920,7 +2996,9 @@ pub async fn agent_send(
|
||||
}
|
||||
// Heartbeats carry no chat content (readiness/heartbeat lot 1) ⇒ no wire
|
||||
// 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;
|
||||
};
|
||||
if matches!(chunk, ReplyChunk::Final { .. } | ReplyChunk::Error { .. }) {
|
||||
@ -2946,7 +3024,10 @@ pub async fn agent_send(
|
||||
let _ = bridge.send_output_settled(
|
||||
&sid,
|
||||
&mut settler,
|
||||
ReplyChunk::Error { message },
|
||||
ReplyChunk::Error {
|
||||
message,
|
||||
at_ms: u64::try_from(clock.now_millis()).ok(),
|
||||
},
|
||||
);
|
||||
}
|
||||
backend::StructuredHumanTurnTransition::Cancelled => {
|
||||
@ -2971,6 +3052,7 @@ pub async fn agent_send(
|
||||
ReplyChunk::Error {
|
||||
message: "Le redémarrage n'a pas fourni de session de remplacement."
|
||||
.to_owned(),
|
||||
at_ms: u64::try_from(clock.now_millis()).ok(),
|
||||
},
|
||||
);
|
||||
break;
|
||||
@ -2991,6 +3073,7 @@ pub async fn agent_send(
|
||||
&mut settler,
|
||||
ReplyChunk::Error {
|
||||
message: error.to_string(),
|
||||
at_ms: u64::try_from(clock.now_millis()).ok(),
|
||||
},
|
||||
);
|
||||
break;
|
||||
@ -2998,7 +3081,10 @@ pub async fn agent_send(
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
if let Some(guard) = &turn_guard {
|
||||
@ -3421,7 +3507,11 @@ pub async fn cancel_agent_chat(
|
||||
}
|
||||
state
|
||||
.stop_live_agent
|
||||
.execute(StopLiveAgentInput { project, agent_id })
|
||||
.execute(StopLiveAgentInput {
|
||||
project,
|
||||
agent_id,
|
||||
reason: Some("fermeture de la session chat".to_owned()),
|
||||
})
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(ErrorDto::from)
|
||||
|
||||
@ -263,6 +263,10 @@ pub fn run() {
|
||||
commands::list_projects,
|
||||
commands::read_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::update_project_permissions,
|
||||
commands::update_agent_permissions,
|
||||
|
||||
@ -48,17 +48,22 @@ fn sid() -> SessionId {
|
||||
}
|
||||
|
||||
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 {
|
||||
ReplyChunk::Final {
|
||||
at_ms: None,
|
||||
content: s.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn error_chunk(s: &str) -> ReplyChunk {
|
||||
ReplyChunk::Error {
|
||||
at_ms: None,
|
||||
message: s.to_owned(),
|
||||
}
|
||||
}
|
||||
@ -70,6 +75,7 @@ fn progress_chunk(
|
||||
) -> ReplyChunk {
|
||||
ReplyChunk::Progress {
|
||||
progress: ReplyProgressDto {
|
||||
occurred_at_ms: None,
|
||||
progress_id: None,
|
||||
source: ReplyProgressSourceDto::ProviderNative,
|
||||
kind,
|
||||
@ -91,6 +97,7 @@ fn progress_chunk_with_id(
|
||||
) -> ReplyChunk {
|
||||
ReplyChunk::Progress {
|
||||
progress: ReplyProgressDto {
|
||||
occurred_at_ms: None,
|
||||
progress_id: Some(progress_id.to_owned()),
|
||||
source: ReplyProgressSourceDto::ProviderNative,
|
||||
kind,
|
||||
@ -107,6 +114,7 @@ fn progress_chunk_with_id(
|
||||
fn chunk_bytes(chunk: &ReplyChunk) -> usize {
|
||||
match chunk {
|
||||
ReplyChunk::UserPrompt {
|
||||
at_ms: _,
|
||||
text,
|
||||
attachments,
|
||||
attachment_refs,
|
||||
@ -123,13 +131,13 @@ fn chunk_bytes(chunk: &ReplyChunk) -> usize {
|
||||
})
|
||||
.sum::<usize>()
|
||||
}
|
||||
ReplyChunk::TextDelta { text } => text.len(),
|
||||
ReplyChunk::ToolActivity { label } => label.len(),
|
||||
ReplyChunk::TextDelta { text, .. } => text.len(),
|
||||
ReplyChunk::ToolActivity { label, .. } => label.len(),
|
||||
ReplyChunk::Progress { progress } => {
|
||||
progress.label.len() + progress.text.as_ref().map_or(0, String::len)
|
||||
}
|
||||
ReplyChunk::Final { content } => content.len(),
|
||||
ReplyChunk::Error { message } => message.len(),
|
||||
ReplyChunk::Final { content, .. } => content.len(),
|
||||
ReplyChunk::Error { message, .. } => message.len(),
|
||||
}
|
||||
}
|
||||
|
||||
@ -137,11 +145,32 @@ fn chunk_bytes(chunk: &ReplyChunk) -> usize {
|
||||
// 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]
|
||||
fn chunk_from_event_maps_text_delta() {
|
||||
assert_eq!(
|
||||
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()
|
||||
}),
|
||||
Some(ReplyChunk::Final {
|
||||
at_ms: None,
|
||||
content: "done".into()
|
||||
})
|
||||
);
|
||||
@ -236,7 +266,10 @@ fn pump_turn(bridge: &ChatBridge, session: &SessionId, gen: u64, events: Vec<Rep
|
||||
for event in events {
|
||||
// Mirror the real pump: heartbeats map to no chunk and are skipped.
|
||||
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;
|
||||
}
|
||||
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).
|
||||
let finals = got
|
||||
.iter()
|
||||
.filter(|c| matches!(c, ReplyChunk::Final { .. }))
|
||||
.filter(|c| matches!(c, ReplyChunk::Final { at_ms: None, .. }))
|
||||
.count();
|
||||
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]
|
||||
@ -490,6 +526,7 @@ fn scrollback_accumulates_every_routed_chunk_in_order() {
|
||||
.map(|chunk| match chunk {
|
||||
ReplyChunk::Progress { progress } => {
|
||||
ReplyChunk::ToolActivity {
|
||||
at_ms: None,
|
||||
label: progress.label,
|
||||
}
|
||||
}
|
||||
@ -499,6 +536,7 @@ fn scrollback_accumulates_every_routed_chunk_in_order() {
|
||||
vec![
|
||||
delta("x"),
|
||||
ReplyChunk::ToolActivity {
|
||||
at_ms: None,
|
||||
label: "runs".into()
|
||||
},
|
||||
final_chunk("x"),
|
||||
@ -756,15 +794,15 @@ fn scrollback_drops_oldest_whole_chunks_when_byte_cap_is_exceeded() {
|
||||
assert_eq!(scrollback.len(), 4);
|
||||
assert!(matches!(
|
||||
scrollback.first(),
|
||||
Some(ReplyChunk::TextDelta { text }) if text.starts_with("02:")
|
||||
Some(ReplyChunk::TextDelta { text, .. }) if text.starts_with("02:")
|
||||
));
|
||||
assert!(matches!(
|
||||
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!(
|
||||
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(
|
||||
&session,
|
||||
ReplyChunk::ToolActivity {
|
||||
at_ms: None,
|
||||
label: "tool".into(),
|
||||
},
|
||||
);
|
||||
@ -793,6 +832,7 @@ fn truncated_scrollback_replays_valid_unmodified_chunks_in_order() {
|
||||
&scrollback[(MAX_CHAT_SCROLLBACK_CHUNKS - 2)..],
|
||||
&[
|
||||
ReplyChunk::ToolActivity {
|
||||
at_ms: None,
|
||||
label: "tool".into()
|
||||
},
|
||||
final_chunk("done")
|
||||
|
||||
@ -444,7 +444,7 @@ fn project_work_state_dto_serialises_conversations_camelcase() {
|
||||
source: TicketWorkSource::Agent {
|
||||
agent_id: requester,
|
||||
},
|
||||
at_ms: 1_700,
|
||||
at_ms: Some(1_700),
|
||||
text_preview: "Analyse le module".to_owned(),
|
||||
text_len: 17,
|
||||
}],
|
||||
@ -715,6 +715,7 @@ fn stop_live_agent_request_deserialises_camelcase() {
|
||||
#[test]
|
||||
fn stop_live_agent_response_serialises_camelcase_with_kind() {
|
||||
use app_tauri_lib::dto::StopLiveAgentResponseDto;
|
||||
use application::terminal::StoppedAgentRuntime;
|
||||
use application::{LiveSessionKind, StopLiveAgentOutput};
|
||||
|
||||
let agent = AgentId::from_uuid(Uuid::from_u128(11));
|
||||
@ -722,17 +723,21 @@ fn stop_live_agent_response_serialises_camelcase_with_kind() {
|
||||
let session = SessionId::from_uuid(Uuid::from_u128(13));
|
||||
let dto = StopLiveAgentResponseDto::from(StopLiveAgentOutput {
|
||||
agent_id: agent,
|
||||
node_id: node,
|
||||
session_id: session,
|
||||
kind: LiveSessionKind::Structured,
|
||||
runtime_state: LiveRuntimeState::Stopped,
|
||||
stopped: vec![StoppedAgentRuntime {
|
||||
agent_id: agent,
|
||||
node_id: node,
|
||||
session_id: session,
|
||||
kind: LiveSessionKind::Structured,
|
||||
state: LiveRuntimeState::Stopped,
|
||||
}],
|
||||
already_stopped: false,
|
||||
});
|
||||
|
||||
let v = serde_json::to_value(&dto).unwrap();
|
||||
assert_eq!(v["agentId"], agent.to_string());
|
||||
assert_eq!(v["sessionId"], session.to_string());
|
||||
assert_eq!(v["kind"], "structured");
|
||||
assert_eq!(v["runtimeState"], "stopped");
|
||||
assert!(v.get("nodeId").is_none());
|
||||
assert_eq!(v["stopped"][0]["sessionId"], session.to_string());
|
||||
assert_eq!(v["stopped"][0]["kind"], "structured");
|
||||
assert_eq!(v["stopped"][0]["runtimeState"], "stopped");
|
||||
assert_eq!(v["alreadyStopped"], false);
|
||||
assert!(v.get("session_id").is_none());
|
||||
}
|
||||
|
||||
@ -26,17 +26,22 @@ use uuid::Uuid;
|
||||
#[test]
|
||||
fn reply_chunk_user_prompt_serialises_exact_camel_case() {
|
||||
let v = serde_json::to_value(ReplyChunk::UserPrompt {
|
||||
at_ms: None,
|
||||
text: "run tests".into(),
|
||||
attachments: Vec::new(),
|
||||
attachment_refs: Vec::new(),
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(v, json!({ "kind": "userPrompt", "text": "run tests" }));
|
||||
assert_eq!(
|
||||
v,
|
||||
json!({ "kind": "userPrompt", "text": "run tests", "atMs": null })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reply_chunk_user_prompt_serialises_attachment_labels() {
|
||||
let v = serde_json::to_value(ReplyChunk::UserPrompt {
|
||||
at_ms: None,
|
||||
text: "describe this".into(),
|
||||
attachments: vec!["clipboard.png".into()],
|
||||
attachment_refs: vec![ChatPromptAttachmentDto {
|
||||
@ -52,6 +57,7 @@ fn reply_chunk_user_prompt_serialises_attachment_labels() {
|
||||
v,
|
||||
json!({
|
||||
"kind": "userPrompt",
|
||||
"atMs": null,
|
||||
"text": "describe this",
|
||||
"attachments": ["clipboard.png"],
|
||||
"attachmentRefs": [{
|
||||
@ -68,25 +74,50 @@ fn reply_chunk_user_prompt_serialises_attachment_labels() {
|
||||
#[test]
|
||||
fn reply_chunk_text_delta_serialises_exact_camel_case() {
|
||||
let v = serde_json::to_value(ReplyChunk::TextDelta {
|
||||
at_ms: None,
|
||||
text: "hello".into(),
|
||||
})
|
||||
.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]
|
||||
fn reply_chunk_tool_activity_serialises_exact_camel_case() {
|
||||
let v = serde_json::to_value(ReplyChunk::ToolActivity {
|
||||
at_ms: None,
|
||||
label: "reads file".into(),
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(v, json!({ "kind": "toolActivity", "label": "reads file" }));
|
||||
assert_eq!(
|
||||
v,
|
||||
json!({ "kind": "toolActivity", "label": "reads file", "atMs": null })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reply_chunk_progress_serialises_exact_camel_case() {
|
||||
let v = serde_json::to_value(ReplyChunk::Progress {
|
||||
progress: ReplyProgressDto {
|
||||
occurred_at_ms: None,
|
||||
progress_id: Some("codex:item:tool0".into()),
|
||||
source: ReplyProgressSourceDto::IdeaLocal,
|
||||
kind: ReplyProgressKindDto::Mcp,
|
||||
@ -105,6 +136,7 @@ fn reply_chunk_progress_serialises_exact_camel_case() {
|
||||
"kind": "progress",
|
||||
"progress": {
|
||||
"source": "ideaLocal",
|
||||
"occurredAtMs": null,
|
||||
"kind": "mcp",
|
||||
"progressId": "codex:item:tool0",
|
||||
"stage": "started",
|
||||
@ -119,21 +151,26 @@ fn reply_chunk_progress_serialises_exact_camel_case() {
|
||||
#[test]
|
||||
fn reply_chunk_final_serialises_exact_camel_case() {
|
||||
let v = serde_json::to_value(ReplyChunk::Final {
|
||||
at_ms: None,
|
||||
content: "done".into(),
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(v, json!({ "kind": "final", "content": "done" }));
|
||||
assert_eq!(
|
||||
v,
|
||||
json!({ "kind": "final", "content": "done", "atMs": null })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reply_chunk_error_serialises_exact_camel_case() {
|
||||
let v = serde_json::to_value(ReplyChunk::Error {
|
||||
at_ms: None,
|
||||
message: "Réponse vide du modèle.".into(),
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
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() {
|
||||
for chunk in [
|
||||
ReplyChunk::UserPrompt {
|
||||
at_ms: None,
|
||||
text: "u".into(),
|
||||
attachments: vec!["clipboard.png".into()],
|
||||
attachment_refs: vec![ChatPromptAttachmentDto {
|
||||
@ -152,12 +190,17 @@ fn reply_chunk_round_trips_through_json_for_every_variant() {
|
||||
.into(),
|
||||
}],
|
||||
},
|
||||
ReplyChunk::TextDelta { text: "x".into() },
|
||||
ReplyChunk::TextDelta {
|
||||
at_ms: None,
|
||||
text: "x".into(),
|
||||
},
|
||||
ReplyChunk::ToolActivity {
|
||||
at_ms: None,
|
||||
label: "runs".into(),
|
||||
},
|
||||
ReplyChunk::Progress {
|
||||
progress: ReplyProgressDto {
|
||||
occurred_at_ms: None,
|
||||
progress_id: None,
|
||||
source: ReplyProgressSourceDto::ProviderNative,
|
||||
kind: ReplyProgressKindDto::Turn,
|
||||
@ -170,9 +213,11 @@ fn reply_chunk_round_trips_through_json_for_every_variant() {
|
||||
},
|
||||
},
|
||||
ReplyChunk::Final {
|
||||
at_ms: None,
|
||||
content: "y".into(),
|
||||
},
|
||||
ReplyChunk::Error {
|
||||
at_ms: None,
|
||||
message: "empty".into(),
|
||||
},
|
||||
] {
|
||||
@ -190,6 +235,7 @@ fn reply_chunk_deserialises_from_camel_case_wire_payload() {
|
||||
assert_eq!(
|
||||
back,
|
||||
ReplyChunk::UserPrompt {
|
||||
at_ms: None,
|
||||
text: "hi".into(),
|
||||
attachments: 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()),
|
||||
scrollback: vec![
|
||||
ReplyChunk::UserPrompt {
|
||||
at_ms: None,
|
||||
text: "Hi".into(),
|
||||
attachments: Vec::new(),
|
||||
attachment_refs: Vec::new(),
|
||||
},
|
||||
ReplyChunk::TextDelta { text: "Hi".into() },
|
||||
ReplyChunk::TextDelta {
|
||||
at_ms: None,
|
||||
text: "Hi".into(),
|
||||
},
|
||||
ReplyChunk::Final {
|
||||
at_ms: None,
|
||||
content: "Hi".into(),
|
||||
},
|
||||
],
|
||||
@ -383,9 +434,9 @@ fn reattach_chat_dto_serialises_camel_case_with_typed_scrollback() {
|
||||
"sessionId": "sess-1",
|
||||
"conversationId": "conv-1",
|
||||
"scrollback": [
|
||||
{ "kind": "userPrompt", "text": "Hi" },
|
||||
{ "kind": "textDelta", "text": "Hi" },
|
||||
{ "kind": "final", "content": "Hi" },
|
||||
{ "kind": "userPrompt", "text": "Hi", "atMs": null },
|
||||
{ "kind": "textDelta", "text": "Hi", "atMs": null },
|
||||
{ "kind": "final", "content": "Hi", "atMs": null },
|
||||
],
|
||||
})
|
||||
);
|
||||
|
||||
@ -19,6 +19,7 @@ use domain::ports::{
|
||||
FileSystem, FsError, IdGenerator, LocalPath, MemoryQuery, MemoryRecall, PermissionStore,
|
||||
PreparedContext, ProfileStore, ProjectStore, PtyPort, RemotePath, SecretStore, SessionPlan,
|
||||
SkillStore, SpawnSpec, StructuredProviderLaunchPolicy, SystemPermissionStore,
|
||||
UserSettingsStore,
|
||||
};
|
||||
use domain::profile::{
|
||||
resolve_effort, EffortSelection, McpConfigStrategy, OpenCodeProviderConfig, StructuredAdapter,
|
||||
@ -27,12 +28,12 @@ use domain::profile::{
|
||||
use domain::sandbox::{compile_sandbox_plan, PathAccess, PathGrant, SandboxContext, SandboxPlan};
|
||||
use domain::{
|
||||
bound_handoff_summary, Agent, AgentId, AgentManifest, AgentOrigin, AgentProfile,
|
||||
ContextInjection, ConversationId, ConversationParty, DomainEvent, EffectivePermissions,
|
||||
Handoff, HandoffStore, ManagedTempKind, ManifestEntry, MarkdownDoc, MemoryIndexEntry,
|
||||
MemoryType, NetworkPolicy, NodeId, OrchestrationCapabilitySnapshot, PermissionProjector,
|
||||
PluginMcpServerSpec, ProfileId, Project, ProjectPath, ProjectedFile, ProjectionContext,
|
||||
ProjectorKey, ProviderSessionStore, PtySize, SessionId, SessionKind, SessionStatus, SkillKind,
|
||||
TerminalSession, HANDOFF_SUMMARY_MAX_CHARS,
|
||||
ContextInjection, ConversationId, ConversationParty, DefaultAgentTerminalInterface,
|
||||
DomainEvent, EffectivePermissions, Handoff, HandoffStore, ManagedTempKind, ManifestEntry,
|
||||
MarkdownDoc, MemoryIndexEntry, MemoryType, NetworkPolicy, NodeId,
|
||||
OrchestrationCapabilitySnapshot, PermissionProjector, PluginMcpServerSpec, ProfileId, Project,
|
||||
ProjectPath, ProjectedFile, ProjectionContext, ProjectorKey, ProviderSessionStore, PtySize,
|
||||
SessionId, SessionKind, SessionStatus, SkillKind, TerminalSession, HANDOFF_SUMMARY_MAX_CHARS,
|
||||
};
|
||||
|
||||
use domain::live_state::WorkStatus;
|
||||
@ -1123,6 +1124,7 @@ impl ChangeAgentProfile {
|
||||
mcp_runtime: None,
|
||||
allow_structured_alongside_pty: false,
|
||||
require_structured: false,
|
||||
terminal_interface: None,
|
||||
fresh_start: false,
|
||||
managed_temp_exposure: ManagedTempExposureRequest::default(),
|
||||
})
|
||||
@ -1310,6 +1312,8 @@ pub struct LaunchAgentInput {
|
||||
///
|
||||
/// Historical callers leave this `false`, preserving the PTY launch contract.
|
||||
pub require_structured: bool,
|
||||
/// Explicit human terminal interface. `None` lets the global preference apply.
|
||||
pub terminal_interface: Option<DefaultAgentTerminalInterface>,
|
||||
/// Cold restart request: ignore the cell's previous conversation id and create
|
||||
/// a new provider/CLI conversation for this activation.
|
||||
pub fresh_start: bool,
|
||||
@ -1803,6 +1807,8 @@ pub struct LaunchAgent {
|
||||
/// Optional for legacy tests/callers; runtime composition wires the shared
|
||||
/// project-plugin resolver used by the capability assignment use cases.
|
||||
plugin_mcp: Option<Arc<ProjectPluginResolver>>,
|
||||
/// Machine-local preference source, wired only on the human launcher.
|
||||
user_settings: Option<Arc<dyn UserSettingsStore>>,
|
||||
/// Explicit intent for structured profiles when structured ports are absent.
|
||||
structured_routing_mode: StructuredRoutingMode,
|
||||
}
|
||||
@ -1855,6 +1861,7 @@ impl LaunchAgent {
|
||||
managed_temp_allocator: None,
|
||||
managed_temp_releaser: None,
|
||||
plugin_mcp: None,
|
||||
user_settings: None,
|
||||
structured_routing_mode: StructuredRoutingMode::HumanPtyFallback,
|
||||
}
|
||||
}
|
||||
@ -1866,6 +1873,13 @@ impl LaunchAgent {
|
||||
self
|
||||
}
|
||||
|
||||
/// Wires machine-local preferences for human-facing launches.
|
||||
#[must_use]
|
||||
pub fn with_user_settings(mut self, settings: Arc<dyn UserSettingsStore>) -> Self {
|
||||
self.user_settings = Some(settings);
|
||||
self
|
||||
}
|
||||
|
||||
/// Replaces the default native-skill resolver with the shared effective
|
||||
/// resolver used by runtime context injection and `idea_skill_read`.
|
||||
#[must_use]
|
||||
@ -2279,7 +2293,16 @@ impl LaunchAgent {
|
||||
input.agent_id, profile.id
|
||||
)));
|
||||
}
|
||||
let preferred_interface = match input.terminal_interface {
|
||||
some @ Some(_) => some,
|
||||
None => match &self.user_settings {
|
||||
Some(settings) => settings.load().await?.default_agent_terminal_interface,
|
||||
None => None,
|
||||
},
|
||||
};
|
||||
let wants_structured = input.require_structured
|
||||
|| preferred_interface == Some(DefaultAgentTerminalInterface::IdeaCli)
|
||||
&& profile.structured_adapter.is_some()
|
||||
|| matches!(
|
||||
self.structured_routing_mode,
|
||||
StructuredRoutingMode::RequireStructured
|
||||
|
||||
@ -56,7 +56,7 @@ pub struct TurnView {
|
||||
/// Identifiant stable du tour (sert aussi d'ancre de pagination).
|
||||
pub id: TurnId,
|
||||
/// Horodatage (epoch millisecondes).
|
||||
pub at_ms: u64,
|
||||
pub at_ms: Option<u64>,
|
||||
/// Nature du tour (invite, réponse, activité outillée).
|
||||
pub role: TurnRole,
|
||||
/// Origine (humain ou agent délégant).
|
||||
|
||||
@ -35,6 +35,7 @@ pub mod plugin;
|
||||
pub mod project;
|
||||
pub mod project_plugin;
|
||||
pub mod remote;
|
||||
pub mod settings;
|
||||
pub mod skill;
|
||||
pub mod slash_command;
|
||||
pub mod sprints;
|
||||
@ -219,6 +220,9 @@ pub use project_plugin::{
|
||||
ProjectPluginSettingsView, SetProjectPluginEnabled,
|
||||
};
|
||||
pub use remote::{ConnectRemote, ConnectRemoteInput, ConnectRemoteOutput};
|
||||
pub use settings::{
|
||||
ReadProjectSettings, ReadUserSettings, UpdateProjectSettings, UpdateUserSettings,
|
||||
};
|
||||
pub use skill::{
|
||||
AgentCapability, AssignSkillToAgent, AssignSkillToAgentInput, AssignedSkillResolver,
|
||||
CreateSkill, CreateSkillInput, CreateSkillOutput, DeleteSkill, DeleteSkillInput, ListSkills,
|
||||
@ -275,7 +279,7 @@ pub use workstate::{
|
||||
ConversationTurnWorkPreview, ConversationWorkSummary, GetAppExitWorkGuardState,
|
||||
GetAppExitWorkGuardStateInput, GetLiveStateLean, GetProjectWorkState, GetProjectWorkStateInput,
|
||||
LeanLiveEntry, LeanLiveState, LiveWorkSession, ProjectWorkState, ReconcileLiveState,
|
||||
ReconcileLiveStateInput, StopAgentExecutionCascade, StopLiveAgent, StopLiveAgentInput,
|
||||
StopLiveAgentOutput, TicketWorkSource, TicketWorkStatus, UpdateLiveState, UpdateLiveStateInput,
|
||||
LIVE_STATE_MAX_ENTRIES, LIVE_STATE_TTL_MS,
|
||||
ReconcileLiveStateInput, StopAgentExecutionCascade, StopAgentRuntime, StopLiveAgent,
|
||||
StopLiveAgentInput, StopLiveAgentOutput, TicketWorkSource, TicketWorkStatus, UpdateLiveState,
|
||||
UpdateLiveStateInput, LIVE_STATE_MAX_ENTRIES, LIVE_STATE_TTL_MS,
|
||||
};
|
||||
|
||||
@ -2744,6 +2744,7 @@ impl OrchestratorService {
|
||||
mcp_runtime: None,
|
||||
allow_structured_alongside_pty: false,
|
||||
require_structured: false,
|
||||
terminal_interface: None,
|
||||
fresh_start: false,
|
||||
managed_temp_exposure: ManagedTempExposureRequest::default(),
|
||||
})
|
||||
@ -3638,6 +3639,7 @@ impl OrchestratorService {
|
||||
.and_then(|p| p.runtime_for(project, agent_id)),
|
||||
allow_structured_alongside_pty: false,
|
||||
require_structured: false,
|
||||
terminal_interface: None,
|
||||
fresh_start: false,
|
||||
managed_temp_exposure: ManagedTempExposureRequest::default(),
|
||||
})
|
||||
@ -3722,6 +3724,7 @@ impl OrchestratorService {
|
||||
.and_then(|p| p.runtime_for(project, agent_id)),
|
||||
allow_structured_alongside_pty: true,
|
||||
require_structured: true,
|
||||
terminal_interface: None,
|
||||
fresh_start: false,
|
||||
managed_temp_exposure: ManagedTempExposureRequest::default(),
|
||||
})
|
||||
|
||||
72
crates/application/src/settings.rs
Normal file
72
crates/application/src/settings.rs
Normal file
@ -0,0 +1,72 @@
|
||||
//! Read/update use cases for global and project settings.
|
||||
|
||||
use crate::AppError;
|
||||
use domain::{IdeaUserSettings, Project, ProjectSettings, ProjectSettingsStore, UserSettingsStore};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Reads global machine-local user settings.
|
||||
pub struct ReadUserSettings {
|
||||
store: Arc<dyn UserSettingsStore>,
|
||||
}
|
||||
impl ReadUserSettings {
|
||||
/// Builds the use case.
|
||||
#[must_use]
|
||||
pub fn new(store: Arc<dyn UserSettingsStore>) -> Self {
|
||||
Self { store }
|
||||
}
|
||||
/// Loads the current settings without writing defaults.
|
||||
pub async fn execute(&self) -> Result<IdeaUserSettings, AppError> {
|
||||
self.store.load().await.map_err(Into::into)
|
||||
}
|
||||
}
|
||||
/// Replaces global machine-local user settings.
|
||||
pub struct UpdateUserSettings {
|
||||
store: Arc<dyn UserSettingsStore>,
|
||||
}
|
||||
impl UpdateUserSettings {
|
||||
/// Builds the use case.
|
||||
#[must_use]
|
||||
pub fn new(store: Arc<dyn UserSettingsStore>) -> Self {
|
||||
Self { store }
|
||||
}
|
||||
/// Persists and returns the accepted document.
|
||||
pub async fn execute(&self, settings: IdeaUserSettings) -> Result<IdeaUserSettings, AppError> {
|
||||
self.store.save(&settings).await?;
|
||||
Ok(settings)
|
||||
}
|
||||
}
|
||||
/// Reads the settings owned by one project.
|
||||
pub struct ReadProjectSettings {
|
||||
store: Arc<dyn ProjectSettingsStore>,
|
||||
}
|
||||
impl ReadProjectSettings {
|
||||
/// Builds the use case.
|
||||
#[must_use]
|
||||
pub fn new(store: Arc<dyn ProjectSettingsStore>) -> Self {
|
||||
Self { store }
|
||||
}
|
||||
/// Loads settings for `project` without creating a missing file.
|
||||
pub async fn execute(&self, project: &Project) -> Result<ProjectSettings, AppError> {
|
||||
self.store.load(&project.root).await.map_err(Into::into)
|
||||
}
|
||||
}
|
||||
/// Replaces the settings owned by one project.
|
||||
pub struct UpdateProjectSettings {
|
||||
store: Arc<dyn ProjectSettingsStore>,
|
||||
}
|
||||
impl UpdateProjectSettings {
|
||||
/// Builds the use case.
|
||||
#[must_use]
|
||||
pub fn new(store: Arc<dyn ProjectSettingsStore>) -> Self {
|
||||
Self { store }
|
||||
}
|
||||
/// Persists and returns the accepted project settings.
|
||||
pub async fn execute(
|
||||
&self,
|
||||
project: &Project,
|
||||
settings: ProjectSettings,
|
||||
) -> Result<ProjectSettings, AppError> {
|
||||
self.store.save(&project.root, &settings).await?;
|
||||
Ok(settings)
|
||||
}
|
||||
}
|
||||
@ -290,42 +290,57 @@ pub async fn stop_live_agent_runtime_in_project(
|
||||
close: &CloseTerminal,
|
||||
) -> Result<Vec<StoppedAgentRuntime>, AppError> {
|
||||
let mut stopped = Vec::new();
|
||||
let mut first_error = None;
|
||||
let snapshots = live.live_agent_snapshots_for(project.id, &agent_id);
|
||||
|
||||
for snapshot in snapshots {
|
||||
live.mark_runtime_state(snapshot, LiveRuntimeState::Stopping);
|
||||
match snapshot.kind {
|
||||
let removed = match snapshot.kind {
|
||||
LiveSessionKind::Structured => {
|
||||
if let Some(removed) = live.structured.remove_runtime(&snapshot.session_id) {
|
||||
removed
|
||||
.session
|
||||
.shutdown()
|
||||
.await
|
||||
.map_err(|e| AppError::Process(e.to_string()))?;
|
||||
close
|
||||
if let Err(error) = removed.session.shutdown().await {
|
||||
first_error.get_or_insert_with(|| AppError::Process(error.to_string()));
|
||||
}
|
||||
if let Err(error) = close
|
||||
.release_managed_temp_handle(removed.managed_temp_handle)
|
||||
.await?;
|
||||
.await
|
||||
{
|
||||
first_error.get_or_insert(error);
|
||||
}
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
LiveSessionKind::Pty => {
|
||||
close
|
||||
if let Err(error) = close
|
||||
.execute(CloseTerminalInput {
|
||||
session_id: snapshot.session_id,
|
||||
})
|
||||
.await?;
|
||||
.await
|
||||
{
|
||||
first_error.get_or_insert(error);
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
||||
};
|
||||
if removed {
|
||||
live.mark_runtime_state(snapshot, LiveRuntimeState::Stopped);
|
||||
stopped.push(StoppedAgentRuntime {
|
||||
agent_id: snapshot.agent_id,
|
||||
session_id: snapshot.session_id,
|
||||
node_id: snapshot.node_id,
|
||||
kind: snapshot.kind,
|
||||
state: LiveRuntimeState::Stopped,
|
||||
});
|
||||
}
|
||||
live.mark_runtime_state(snapshot, LiveRuntimeState::Stopped);
|
||||
stopped.push(StoppedAgentRuntime {
|
||||
agent_id: snapshot.agent_id,
|
||||
session_id: snapshot.session_id,
|
||||
node_id: snapshot.node_id,
|
||||
kind: snapshot.kind,
|
||||
state: LiveRuntimeState::Stopped,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(stopped)
|
||||
match first_error {
|
||||
Some(error) => Err(error),
|
||||
None => Ok(stopped),
|
||||
}
|
||||
}
|
||||
|
||||
/// The platform default interactive shell.
|
||||
|
||||
@ -11,13 +11,13 @@ use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use domain::input::InputMediator;
|
||||
use domain::live_state::WorkStatus;
|
||||
use domain::{AgentId, NodeId, Project, RuntimeAgentKey, SessionId};
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::orchestrator::OrchestratorService;
|
||||
use crate::orchestrator::{LiveStateProvider, OrchestratorService};
|
||||
use crate::terminal::{
|
||||
stop_live_agent_runtime_in_project, CloseTerminal, LiveRuntimeState, LiveSessionKind,
|
||||
LiveSessions,
|
||||
stop_live_agent_runtime_in_project, CloseTerminal, LiveSessionKind, LiveSessions,
|
||||
};
|
||||
|
||||
/// Input for [`AttachLiveAgent::execute`].
|
||||
@ -100,35 +100,33 @@ impl AttachLiveAgent {
|
||||
}
|
||||
}
|
||||
|
||||
/// Input for [`StopLiveAgent::execute`].
|
||||
/// Input for [`StopAgentRuntime::execute`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct StopLiveAgentInput {
|
||||
/// The owning project (boundary/symmetry; the registries are global by agent).
|
||||
pub project: Project,
|
||||
/// The agent whose live session is stopped.
|
||||
pub agent_id: AgentId,
|
||||
/// Optional human-readable stop reason.
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
/// Output of [`StopLiveAgent::execute`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct StopLiveAgentOutput {
|
||||
/// The stopped agent.
|
||||
pub agent_id: AgentId,
|
||||
/// The id of the session that was torn down.
|
||||
pub session_id: SessionId,
|
||||
/// Last known layout node hosting the runtime view.
|
||||
pub node_id: NodeId,
|
||||
/// Runtime family that owned the session.
|
||||
pub kind: LiveSessionKind,
|
||||
/// Runtime lifecycle projection after the stop request.
|
||||
pub runtime_state: LiveRuntimeState,
|
||||
pub stopped: Vec<crate::terminal::StoppedAgentRuntime>,
|
||||
/// Whether no live runtime remained to stop.
|
||||
pub already_stopped: bool,
|
||||
}
|
||||
|
||||
/// Best-effort stopper for execution resources owned by one live agent turn.
|
||||
///
|
||||
/// Implementations must be idempotent: a missing, already-finished or already-stopped
|
||||
/// child resource is a successful no-op. Failures are deliberately not propagated by
|
||||
/// [`StopLiveAgent`], because the product contract is "stop the agent; cascade related
|
||||
/// [`StopAgentRuntime`], because the product contract is "stop the agent; cascade related
|
||||
/// work best-effort".
|
||||
#[async_trait]
|
||||
pub trait StopAgentExecutionCascade: Send + Sync {
|
||||
@ -143,16 +141,17 @@ pub trait StopAgentExecutionCascade: Send + Sync {
|
||||
/// provider conversation/context survives the stop. A PTY session has no finer
|
||||
/// turn boundary, so it is torn down through the existing [`CloseTerminal`]
|
||||
/// primitive (registry removal + process kill).
|
||||
pub struct StopLiveAgent {
|
||||
pub struct StopAgentRuntime {
|
||||
live: Arc<LiveSessions>,
|
||||
close: Arc<CloseTerminal>,
|
||||
input: Option<Arc<dyn InputMediator>>,
|
||||
waits: Option<Arc<OrchestratorService>>,
|
||||
cascade: Option<Arc<dyn StopAgentExecutionCascade>>,
|
||||
restart_rendezvous: Option<Arc<crate::RestartRendezvousCoordinator>>,
|
||||
live_state: Option<Arc<dyn LiveStateProvider>>,
|
||||
}
|
||||
|
||||
impl StopLiveAgent {
|
||||
impl StopAgentRuntime {
|
||||
/// Builds the use case from the live-session registry and the close primitive.
|
||||
#[must_use]
|
||||
pub fn new(live: Arc<LiveSessions>, close: Arc<CloseTerminal>) -> Self {
|
||||
@ -163,9 +162,17 @@ impl StopLiveAgent {
|
||||
waits: None,
|
||||
cascade: None,
|
||||
restart_rendezvous: None,
|
||||
live_state: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Wires the project-scoped live-state projection updated after a stop.
|
||||
#[must_use]
|
||||
pub fn with_live_state(mut self, live_state: Arc<dyn LiveStateProvider>) -> Self {
|
||||
self.live_state = Some(live_state);
|
||||
self
|
||||
}
|
||||
|
||||
/// Wires cancellation helpers used for user-driven stop cascades.
|
||||
///
|
||||
/// Stopping A while A waits on B should stop B too. The orchestrator service is
|
||||
@ -216,14 +223,32 @@ impl StopLiveAgent {
|
||||
if let Some(mediator) = &self.input {
|
||||
mediator.preempt(RuntimeAgentKey::new(input.project.id, input.agent_id));
|
||||
}
|
||||
if let Some(out) = self
|
||||
.cancel_structured_turn_in_project(&input.project, input.agent_id)
|
||||
.await?
|
||||
{
|
||||
return Ok(out);
|
||||
let stopped = stop_live_agent_runtime_in_project(
|
||||
&input.project,
|
||||
input.agent_id,
|
||||
&self.live,
|
||||
&self.close,
|
||||
)
|
||||
.await?;
|
||||
if let Some(provider) = &self.live_state {
|
||||
if let Some(update) = provider.live_state_for(&input.project.root) {
|
||||
let _ = update
|
||||
.execute(crate::UpdateLiveStateInput {
|
||||
agent_id: input.agent_id,
|
||||
ticket: None,
|
||||
intent: input.reason.unwrap_or_else(|| "arrêté".to_owned()),
|
||||
status: WorkStatus::Idle,
|
||||
progress: None,
|
||||
last_delegation: None,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
self.stop_one_in_project(&input.project, input.agent_id)
|
||||
.await
|
||||
Ok(StopLiveAgentOutput {
|
||||
agent_id: input.agent_id,
|
||||
already_stopped: stopped.is_empty(),
|
||||
stopped,
|
||||
})
|
||||
}
|
||||
|
||||
async fn stop_dependencies(
|
||||
@ -246,87 +271,11 @@ impl StopLiveAgent {
|
||||
if let Some(mediator) = &self.input {
|
||||
mediator.preempt(RuntimeAgentKey::new(project.id, dep));
|
||||
}
|
||||
if self
|
||||
.cancel_structured_turn_in_project(project, dep)
|
||||
.await?
|
||||
.is_none()
|
||||
{
|
||||
let _ = self.stop_one_in_project(project, dep).await;
|
||||
}
|
||||
let _ = stop_live_agent_runtime_in_project(project, dep, &self.live, &self.close).await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn cancel_structured_turn_in_project(
|
||||
&self,
|
||||
project: &Project,
|
||||
agent_id: AgentId,
|
||||
) -> Result<Option<StopLiveAgentOutput>, AppError> {
|
||||
let Some(snapshot) = self
|
||||
.live
|
||||
.live_agent_snapshots_for(project.id, &agent_id)
|
||||
.into_iter()
|
||||
.find(|snapshot| snapshot.kind == LiveSessionKind::Structured)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(session) = self
|
||||
.live
|
||||
.structured
|
||||
.session_for_agent_in_project(project.id, &agent_id)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.live
|
||||
.mark_runtime_state(snapshot, LiveRuntimeState::Stopping);
|
||||
session
|
||||
.cancel_current_turn()
|
||||
.await
|
||||
.map_err(|err| AppError::Process(err.to_string()))?;
|
||||
self.live
|
||||
.mark_runtime_state(snapshot, LiveRuntimeState::Stopped);
|
||||
Ok(Some(StopLiveAgentOutput {
|
||||
agent_id: snapshot.agent_id,
|
||||
session_id: snapshot.session_id,
|
||||
node_id: snapshot.node_id,
|
||||
kind: snapshot.kind,
|
||||
runtime_state: LiveRuntimeState::Stopped,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn stop_one_in_project(
|
||||
&self,
|
||||
project: &Project,
|
||||
agent_id: AgentId,
|
||||
) -> Result<StopLiveAgentOutput, AppError> {
|
||||
stop_live_agent_runtime_in_project(project, agent_id, &self.live, &self.close)
|
||||
.await?
|
||||
.into_iter()
|
||||
.next()
|
||||
.map(|stopped| StopLiveAgentOutput {
|
||||
agent_id: stopped.agent_id,
|
||||
session_id: stopped.session_id,
|
||||
node_id: stopped.node_id,
|
||||
kind: stopped.kind,
|
||||
runtime_state: stopped.state,
|
||||
})
|
||||
.or_else(|| {
|
||||
self.live
|
||||
.runtime_status_for(project.id, &agent_id)
|
||||
.filter(|status| {
|
||||
matches!(
|
||||
status.state,
|
||||
LiveRuntimeState::Stopping | LiveRuntimeState::Stopped
|
||||
)
|
||||
})
|
||||
.map(|status| StopLiveAgentOutput {
|
||||
agent_id: status.agent_id,
|
||||
session_id: status.session_id,
|
||||
node_id: status.node_id,
|
||||
kind: status.kind,
|
||||
runtime_state: status.state,
|
||||
})
|
||||
})
|
||||
.ok_or_else(|| AppError::NotFound(format!("running session for agent {agent_id}")))
|
||||
}
|
||||
}
|
||||
|
||||
/// Compatibility name kept for existing driving adapters.
|
||||
pub type StopLiveAgent = StopAgentRuntime;
|
||||
|
||||
@ -11,7 +11,7 @@ mod reconcile;
|
||||
|
||||
pub use actions::{
|
||||
AttachLiveAgent, AttachLiveAgentInput, AttachLiveAgentOutput, StopAgentExecutionCascade,
|
||||
StopLiveAgent, StopLiveAgentInput, StopLiveAgentOutput,
|
||||
StopAgentRuntime, StopLiveAgent, StopLiveAgentInput, StopLiveAgentOutput,
|
||||
};
|
||||
pub use live::{
|
||||
GetLiveStateLean, LeanLiveEntry, LeanLiveState, UpdateLiveState, UpdateLiveStateInput,
|
||||
@ -172,7 +172,7 @@ pub struct ConversationTurnWorkPreview {
|
||||
/// Origin of the turn (human operator or a delegating agent).
|
||||
pub source: TicketWorkSource,
|
||||
/// Timestamp (epoch milliseconds) of the turn.
|
||||
pub at_ms: u64,
|
||||
pub at_ms: Option<u64>,
|
||||
/// Bounded, whitespace-normalised excerpt of the turn text.
|
||||
pub text_preview: String,
|
||||
/// Character length of the **original** (un-truncated) turn text.
|
||||
|
||||
@ -1501,6 +1501,7 @@ fn launch_input_with_project(agent_id: AgentId, project: Project) -> LaunchAgent
|
||||
mcp_runtime: None,
|
||||
allow_structured_alongside_pty: false,
|
||||
require_structured: false,
|
||||
terminal_interface: None,
|
||||
fresh_start: false,
|
||||
managed_temp_exposure: ManagedTempExposureRequest::default(),
|
||||
}
|
||||
|
||||
@ -4585,8 +4585,8 @@ async fn p6b_user_ask_records_prompt_then_response_pair() {
|
||||
"response is sourced from the target (architect)"
|
||||
);
|
||||
// Clock stamp came from the injected Clock.
|
||||
assert_eq!(prompt.at_ms, 123);
|
||||
assert_eq!(response.at_ms, 123);
|
||||
assert_eq!(prompt.at_ms, Some(123));
|
||||
assert_eq!(response.at_ms, Some(123));
|
||||
}
|
||||
|
||||
/// Round-trip with an **agent** requester (A) resolves the `A↔B` conversation and the
|
||||
|
||||
@ -40,13 +40,16 @@ use domain::ports::{
|
||||
ContextInjectionPlan, DirEntry, EventBus, EventStream, ExitStatus, FileSystem, FsError,
|
||||
IdGenerator, MemoryError, MemoryQuery, MemoryRecall, OutputStream, PreparedContext,
|
||||
ProfileStore, ProjectStore, PtyError, PtyHandle, PtyPort, RemotePath, ReplyEvent, ReplyStream,
|
||||
RuntimeError, SessionPlan, SkillStore, SpawnSpec, StoreError,
|
||||
RuntimeError, SessionPlan, SkillStore, SpawnSpec, StoreError, UserSettingsStore,
|
||||
};
|
||||
use domain::profile::{AgentProfile, ContextInjection, StructuredAdapter};
|
||||
use domain::project::{Project, ProjectPath};
|
||||
use domain::remote::RemoteRef;
|
||||
use domain::skill::{Skill, SkillScope};
|
||||
use domain::{MemoryIndexEntry, NodeId, PtySize, SessionId, SessionKind, SkillId};
|
||||
use domain::{
|
||||
DefaultAgentTerminalInterface, IdeaUserSettings, MemoryIndexEntry, NodeId, PtySize, SessionId,
|
||||
SessionKind, SkillId,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
use application::{
|
||||
@ -772,6 +775,7 @@ fn launch_input(agent_id: AgentId) -> LaunchAgentInput {
|
||||
mcp_runtime: None,
|
||||
allow_structured_alongside_pty: false,
|
||||
require_structured: false,
|
||||
terminal_interface: None,
|
||||
fresh_start: false,
|
||||
managed_temp_exposure: ManagedTempExposureRequest::default(),
|
||||
}
|
||||
@ -858,10 +862,103 @@ fn launch_fixture_with_mode(
|
||||
}
|
||||
}
|
||||
|
||||
struct FixedUserSettings(IdeaUserSettings);
|
||||
|
||||
#[async_trait]
|
||||
impl UserSettingsStore for FixedUserSettings {
|
||||
async fn load(&self) -> Result<IdeaUserSettings, StoreError> {
|
||||
Ok(self.0.clone())
|
||||
}
|
||||
async fn save(&self, _settings: &IdeaUserSettings) -> Result<(), StoreError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct MutableUserSettings(Arc<Mutex<IdeaUserSettings>>);
|
||||
|
||||
#[async_trait]
|
||||
impl UserSettingsStore for MutableUserSettings {
|
||||
async fn load(&self) -> Result<IdeaUserSettings, StoreError> {
|
||||
Ok(self.0.lock().unwrap().clone())
|
||||
}
|
||||
async fn save(&self, settings: &IdeaUserSettings) -> Result<(), StoreError> {
|
||||
*self.0.lock().unwrap() = settings.clone();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn launch_fixture_with_preference(interface: DefaultAgentTerminalInterface) -> LaunchFixture {
|
||||
let mut fixture = launch_fixture_with_mode(
|
||||
structured_profile(pid(9)),
|
||||
FakeFactory::new(500, Some("engine-conv")),
|
||||
StructuredRoutingMode::HumanPtyFallback,
|
||||
);
|
||||
let launch = Arc::try_unwrap(fixture.launch)
|
||||
.ok()
|
||||
.expect("fixture owns its launcher")
|
||||
.with_user_settings(Arc::new(FixedUserSettings(IdeaUserSettings {
|
||||
default_agent_terminal_interface: Some(interface),
|
||||
})));
|
||||
fixture.launch = Arc::new(launch);
|
||||
fixture
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// 1. Routage LaunchAgent : chemin structuré
|
||||
// ===========================================================================
|
||||
|
||||
#[tokio::test]
|
||||
async fn global_idea_cli_preference_applies_to_a_new_human_launch() {
|
||||
let f = launch_fixture_with_preference(DefaultAgentTerminalInterface::IdeaCli);
|
||||
let out = f.launch.execute(launch_input(f.agent.id)).await.unwrap();
|
||||
assert!(out.structured.is_some());
|
||||
assert_eq!(f.factory.start_count(), 1);
|
||||
assert_eq!(f.pty.spawn_count(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_native_tui_overrides_the_global_idea_cli_preference() {
|
||||
let f = launch_fixture_with_preference(DefaultAgentTerminalInterface::IdeaCli);
|
||||
let mut input = launch_input(f.agent.id);
|
||||
input.terminal_interface = Some(DefaultAgentTerminalInterface::NativeTui);
|
||||
let out = f.launch.execute(input).await.unwrap();
|
||||
assert!(out.structured.is_none());
|
||||
assert_eq!(f.factory.start_count(), 0);
|
||||
assert_eq!(f.pty.spawn_count(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn changing_global_preference_does_not_replace_an_existing_terminal() {
|
||||
let mut fixture = launch_fixture_with_mode(
|
||||
structured_profile(pid(9)),
|
||||
FakeFactory::new(500, Some("engine-conv")),
|
||||
StructuredRoutingMode::HumanPtyFallback,
|
||||
);
|
||||
let settings = MutableUserSettings(Arc::new(Mutex::new(IdeaUserSettings::default())));
|
||||
let launch = Arc::try_unwrap(fixture.launch)
|
||||
.ok()
|
||||
.unwrap()
|
||||
.with_user_settings(Arc::new(settings.clone()));
|
||||
fixture.launch = Arc::new(launch);
|
||||
|
||||
let mut input = launch_input(fixture.agent.id);
|
||||
input.node_id = Some(nid(3));
|
||||
let first = fixture.launch.execute(input.clone()).await.unwrap();
|
||||
assert!(first.structured.is_none());
|
||||
settings
|
||||
.save(&IdeaUserSettings {
|
||||
default_agent_terminal_interface: Some(DefaultAgentTerminalInterface::IdeaCli),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let second = fixture.launch.execute(input).await.unwrap();
|
||||
assert_eq!(second.session.id, first.session.id);
|
||||
assert_eq!(fixture.pty.spawn_count(), 1);
|
||||
assert_eq!(fixture.factory.start_count(), 0);
|
||||
}
|
||||
|
||||
/// Profil structuré + factory câblée ⇒ `factory.start` appelé une fois, session
|
||||
/// enregistrée dans `StructuredSessions`, AUCUN `pty.spawn`, `AgentLaunched` publié,
|
||||
/// `output.structured = Some(descriptor)` avec les bons champs.
|
||||
|
||||
@ -330,15 +330,17 @@ async fn stop_pty_kills_and_removes_session() {
|
||||
.execute(StopLiveAgentInput {
|
||||
project: project(),
|
||||
agent_id: a,
|
||||
reason: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(out.agent_id, a);
|
||||
assert_eq!(out.session_id, sid(1));
|
||||
assert_eq!(out.node_id, nid(100));
|
||||
assert_eq!(out.kind, LiveSessionKind::Pty);
|
||||
assert_eq!(out.runtime_state, LiveRuntimeState::Stopped);
|
||||
assert!(!out.already_stopped);
|
||||
assert_eq!(out.stopped[0].session_id, sid(1));
|
||||
assert_eq!(out.stopped[0].node_id, nid(100));
|
||||
assert_eq!(out.stopped[0].kind, LiveSessionKind::Pty);
|
||||
assert_eq!(out.stopped[0].state, LiveRuntimeState::Stopped);
|
||||
// Delegated to the close primitive: process killed and registry emptied.
|
||||
assert_eq!(f.pty_port.kills(), vec![sid(1)]);
|
||||
assert!(f.pty.is_empty(), "live session removed from the registry");
|
||||
@ -346,7 +348,7 @@ async fn stop_pty_kills_and_removes_session() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_structured_cancels_turn_and_keeps_session() {
|
||||
async fn stop_structured_shuts_down_and_removes_session() {
|
||||
let f = fixture();
|
||||
let a = aid(10);
|
||||
let (shutdown_called, cancel_called) = insert_structured(&f.structured, sid(2), a, nid(100));
|
||||
@ -356,26 +358,24 @@ async fn stop_structured_cancels_turn_and_keeps_session() {
|
||||
.execute(StopLiveAgentInput {
|
||||
project: project(),
|
||||
agent_id: a,
|
||||
reason: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(out.session_id, sid(2));
|
||||
assert_eq!(out.kind, LiveSessionKind::Structured);
|
||||
assert_eq!(out.runtime_state, LiveRuntimeState::Stopped);
|
||||
assert_eq!(out.stopped[0].session_id, sid(2));
|
||||
assert_eq!(out.stopped[0].kind, LiveSessionKind::Structured);
|
||||
assert_eq!(out.stopped[0].state, LiveRuntimeState::Stopped);
|
||||
assert!(!cancel_called.load(Ordering::SeqCst));
|
||||
assert!(
|
||||
cancel_called.load(Ordering::SeqCst),
|
||||
"session.cancel_current_turn() was called"
|
||||
shutdown_called.load(Ordering::SeqCst),
|
||||
"session.shutdown() must be called"
|
||||
);
|
||||
assert!(
|
||||
!shutdown_called.load(Ordering::SeqCst),
|
||||
"session.shutdown() must not be called"
|
||||
);
|
||||
assert!(!f.structured.is_empty(), "live session is preserved");
|
||||
assert!(f.structured.is_empty(), "live session is removed");
|
||||
assert_eq!(
|
||||
f.structured
|
||||
.session_id_for_agent_in_project(project().id, &a),
|
||||
Some(sid(2))
|
||||
None
|
||||
);
|
||||
// No PTY was touched.
|
||||
assert!(f.pty_port.kills().is_empty());
|
||||
@ -395,21 +395,46 @@ async fn stop_structured_runs_execution_cascade_best_effort() {
|
||||
.execute(StopLiveAgentInput {
|
||||
project: project(),
|
||||
agent_id: a,
|
||||
reason: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(out.session_id, sid(2));
|
||||
assert_eq!(out.stopped[0].session_id, sid(2));
|
||||
assert_eq!(*cascade.calls.lock().unwrap(), vec![(project().id, a)]);
|
||||
assert!(
|
||||
cancel_called.load(Ordering::SeqCst),
|
||||
"session.cancel_current_turn() was called"
|
||||
!cancel_called.load(Ordering::SeqCst),
|
||||
"session.cancel_current_turn() is not the runtime stop primitive"
|
||||
);
|
||||
assert!(
|
||||
!shutdown_called.load(Ordering::SeqCst),
|
||||
"session.shutdown() must not be called"
|
||||
shutdown_called.load(Ordering::SeqCst),
|
||||
"session.shutdown() must be called"
|
||||
);
|
||||
assert!(!f.structured.is_empty(), "live session is preserved");
|
||||
assert!(f.structured.is_empty(), "live session is removed");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_removes_every_runtime_for_the_agent_across_registries() {
|
||||
let f = fixture();
|
||||
let agent = aid(10);
|
||||
insert_pty(&f.pty, sid(1), agent, nid(100));
|
||||
let (shutdown_called, _) = insert_structured(&f.structured, sid(2), agent, nid(200));
|
||||
|
||||
let out = f
|
||||
.stop
|
||||
.execute(StopLiveAgentInput {
|
||||
project: project(),
|
||||
agent_id: agent,
|
||||
reason: Some("user requested".to_owned()),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(out.stopped.len(), 2);
|
||||
assert!(f.pty.is_empty());
|
||||
assert!(f.structured.is_empty());
|
||||
assert_eq!(f.pty_port.kills(), vec![sid(1)]);
|
||||
assert!(shutdown_called.load(Ordering::SeqCst));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@ -423,6 +448,7 @@ async fn stop_pty_is_idempotent_after_success() {
|
||||
.execute(StopLiveAgentInput {
|
||||
project: project(),
|
||||
agent_id: a,
|
||||
reason: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@ -431,31 +457,31 @@ async fn stop_pty_is_idempotent_after_success() {
|
||||
.execute(StopLiveAgentInput {
|
||||
project: project(),
|
||||
agent_id: a,
|
||||
reason: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(first, second);
|
||||
assert_eq!(second.runtime_state, LiveRuntimeState::Stopped);
|
||||
assert!(!first.already_stopped);
|
||||
assert!(second.already_stopped);
|
||||
assert!(second.stopped.is_empty());
|
||||
assert_eq!(f.pty_port.kills(), vec![sid(1)], "kill is not repeated");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_unknown_agent_is_not_found() {
|
||||
async fn stop_unknown_agent_is_idempotent_success() {
|
||||
let f = fixture();
|
||||
|
||||
let err = f
|
||||
let out = f
|
||||
.stop
|
||||
.execute(StopLiveAgentInput {
|
||||
project: project(),
|
||||
agent_id: aid(999),
|
||||
reason: None,
|
||||
})
|
||||
.await
|
||||
.expect_err("absent agent ⇒ NOT_FOUND");
|
||||
|
||||
assert!(
|
||||
matches!(err, application::AppError::NotFound(_)),
|
||||
"got {err:?}"
|
||||
);
|
||||
.expect("absent agent is an idempotent success");
|
||||
assert!(out.already_stopped);
|
||||
assert!(out.stopped.is_empty());
|
||||
assert!(f.pty_port.kills().is_empty(), "nothing killed");
|
||||
}
|
||||
|
||||
@ -3252,6 +3252,59 @@ pub struct UpdateProjectContextRequestDto {
|
||||
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`.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@ -3747,6 +3800,9 @@ impl From<ReplyProgressStage> for ReplyProgressStageDto {
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
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.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub progress_id: Option<String>,
|
||||
@ -3775,6 +3831,7 @@ pub struct ReplyProgressDto {
|
||||
impl From<ReplyProgress> for ReplyProgressDto {
|
||||
fn from(value: ReplyProgress) -> Self {
|
||||
Self {
|
||||
occurred_at_ms: None,
|
||||
progress_id: value.progress_id,
|
||||
source: value.source.into(),
|
||||
kind: value.kind.into(),
|
||||
@ -3804,6 +3861,9 @@ pub enum ReplyChunk {
|
||||
/// The user's submitted prompt, retained in live scrollback for reattach.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
UserPrompt {
|
||||
/// Time at which the backend accepted this prompt.
|
||||
#[serde(default)]
|
||||
at_ms: Option<u64>,
|
||||
/// Submitted prompt text.
|
||||
text: String,
|
||||
/// Display labels for attachments submitted with the prompt.
|
||||
@ -3816,12 +3876,18 @@ pub enum ReplyChunk {
|
||||
/// An assistant text fragment (incremental chat rendering).
|
||||
#[serde(rename_all = "camelCase")]
|
||||
TextDelta {
|
||||
/// Time at which the backend accepted this fragment.
|
||||
#[serde(default)]
|
||||
at_ms: Option<u64>,
|
||||
/// The text fragment.
|
||||
text: String,
|
||||
},
|
||||
/// A human-readable tool-activity badge (best-effort observability).
|
||||
#[serde(rename_all = "camelCase")]
|
||||
ToolActivity {
|
||||
/// Time at which the backend accepted this activity.
|
||||
#[serde(default)]
|
||||
at_ms: Option<u64>,
|
||||
/// The human-readable activity label.
|
||||
label: String,
|
||||
},
|
||||
@ -3834,12 +3900,18 @@ pub enum ReplyChunk {
|
||||
/// The deterministic end-of-turn chunk carrying the aggregated final content.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
Final {
|
||||
/// Time at which the backend accepted the terminal response.
|
||||
#[serde(default)]
|
||||
at_ms: Option<u64>,
|
||||
/// The aggregated final content of the turn.
|
||||
content: String,
|
||||
},
|
||||
/// A visible terminal fallback when the model stream produced no usable answer.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
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.
|
||||
message: String,
|
||||
},
|
||||
@ -4210,7 +4282,7 @@ pub struct ConversationTurnWorkPreviewDto {
|
||||
/// Origin of the turn (human operator or a delegating agent).
|
||||
pub source: TicketWorkSourceDto,
|
||||
/// Timestamp (epoch milliseconds) of the turn.
|
||||
pub at_ms: u64,
|
||||
pub at_ms: Option<u64>,
|
||||
/// Bounded excerpt of the turn text.
|
||||
pub text_preview: String,
|
||||
/// Character length of the original (un-truncated) turn text.
|
||||
@ -4469,6 +4541,9 @@ pub struct StopLiveAgentRequestDto {
|
||||
pub project_id: String,
|
||||
/// Id of the running agent to stop.
|
||||
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.
|
||||
@ -4477,11 +4552,23 @@ pub struct StopLiveAgentRequestDto {
|
||||
pub struct StopLiveAgentResponseDto {
|
||||
/// The stopped agent's id.
|
||||
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,
|
||||
/// Runtime family that owned the session (`pty`/`structured`).
|
||||
/// Last hosting layout node id.
|
||||
pub node_id: String,
|
||||
/// Runtime family.
|
||||
pub kind: LiveWorkSessionKindDto,
|
||||
/// Runtime lifecycle projection after the stop request.
|
||||
/// Terminal lifecycle state.
|
||||
pub runtime_state: LiveRuntimeStateDto,
|
||||
}
|
||||
|
||||
@ -4489,9 +4576,17 @@ impl From<StopLiveAgentOutput> for StopLiveAgentResponseDto {
|
||||
fn from(out: StopLiveAgentOutput) -> Self {
|
||||
Self {
|
||||
agent_id: out.agent_id.to_string(),
|
||||
session_id: out.session_id.to_string(),
|
||||
kind: out.kind.into(),
|
||||
runtime_state: out.runtime_state.into(),
|
||||
stopped: out
|
||||
.stopped
|
||||
.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).
|
||||
pub id: String,
|
||||
/// Timestamp (epoch milliseconds).
|
||||
pub at_ms: u64,
|
||||
pub at_ms: Option<u64>,
|
||||
/// Turn nature (prompt, response, tool activity).
|
||||
pub role: TurnRole,
|
||||
/// Origin (human or delegating agent).
|
||||
|
||||
@ -44,27 +44,28 @@ use application::{
|
||||
PluginToolchainDiagnostics, PluginWorkspaceAccess, ProjectPluginResolver, ProposeContext,
|
||||
PurgeManagedTemp, QueryProjectStructure, ReadAgentContext, ReadChatDraft, ReadContext,
|
||||
ReadConversationPage, ReadIssue, ReadIssueAttachment, ReadIssueCarnet, ReadMcpToolPermissions,
|
||||
ReadMemory, ReadMemoryIndex, ReadOpenProjectRestoreState, ReadProjectContext, ReadSkill,
|
||||
ReadTemplate, RecallMemory, ReconcileLayouts, ReconcileLiveState, ReconcileLiveStateInput,
|
||||
ReconcilePluginMcpServers, RecordProjectClosedForRestore, RecordProjectOpenedForRestore,
|
||||
RecordTurn, RecordTurnProvider, ReferenceProfiles, ReleaseManagedTemp, ReloadPlugin,
|
||||
ReloadPluginInput, RemoveProjectFromRegistry, RenameDevice, RenameLayout, RenameSprint,
|
||||
ReorderSprints, ResizeTerminal, ResolveAgentCapabilities, ResolveAgentPermissions,
|
||||
ReadMemory, ReadMemoryIndex, ReadOpenProjectRestoreState, ReadProjectContext,
|
||||
ReadProjectSettings, ReadSkill, ReadTemplate, ReadUserSettings, RecallMemory, ReconcileLayouts,
|
||||
ReconcileLiveState, ReconcileLiveStateInput, ReconcilePluginMcpServers,
|
||||
RecordProjectClosedForRestore, RecordProjectOpenedForRestore, RecordTurn, RecordTurnProvider,
|
||||
ReferenceProfiles, ReleaseManagedTemp, ReloadPlugin, ReloadPluginInput,
|
||||
RemoveProjectFromRegistry, RenameDevice, RenameLayout, RenameSprint, ReorderSprints,
|
||||
ResizeTerminal, ResolveAgentCapabilities, ResolveAgentPermissions,
|
||||
ResolveAgentSystemPermissions, ResolveManagedTemp, ResolveMemoryLinks, RestoreOpenProjects,
|
||||
RestoreOpenProjectsOutput, RestoreOpenWindows, RetryBackgroundTask, RetryOpenProjectRestore,
|
||||
ReviewPluginPackage, RevokeAllDevices, RevokeDevice, RotateConversationLog, SaveChatDraft,
|
||||
SaveEmbedderProfile, SaveModelServer, SaveOpenCodeProviderProfile, SaveOpenProjectRestoreOrder,
|
||||
SaveProfile, SessionLimitService, SetActiveLayout, SetAgentMcpToolAllowed, SetPluginEnabled,
|
||||
SetProjectPluginEnabled, SlashCommandRegistry, SnapshotOpenWindows, SnapshotRunningAgents,
|
||||
SnapshotRunningAgentsInput, SpawnBackgroundCommand, StopLiveAgent, StructuredRoutingMode,
|
||||
SnapshotRunningAgentsInput, SpawnBackgroundCommand, StopAgentRuntime, StructuredRoutingMode,
|
||||
StructuredSessions, SuggestedThisSession, SyncAgentWithTemplate, TerminalSessions, TouchDevice,
|
||||
UnassignSkillFromAgent, UnassignTicketFromSprint, UninstallPlugin, UnlinkIssues,
|
||||
UpdateAgentContactable, UpdateAgentContext, UpdateAgentEffort, UpdateAgentMcpToolPermissions,
|
||||
UpdateAgentPermissions, UpdateAgentSystemPermissions, UpdateIssue, UpdateIssueCarnet,
|
||||
UpdateLiveState, UpdateMemory, UpdateProjectContext, UpdateProjectMcpToolPermissions,
|
||||
UpdateProjectOrchestrator, UpdateProjectPermissions, UpdateProjectSystemPermissions,
|
||||
UpdateSkill, UpdateTemplate, WakeSessionProvider, WriteMemory, WriteToTerminal,
|
||||
AGENT_MEMORY_RECALL_BUDGET,
|
||||
UpdateProjectOrchestrator, UpdateProjectPermissions, UpdateProjectSettings,
|
||||
UpdateProjectSystemPermissions, UpdateSkill, UpdateTemplate, UpdateUserSettings,
|
||||
WakeSessionProvider, WriteMemory, WriteToTerminal, AGENT_MEMORY_RECALL_BUDGET,
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use domain::events::AgentRestartPhase;
|
||||
@ -77,10 +78,10 @@ use domain::ports::{
|
||||
McpToolPermissionStore, MemoryRecall, MemoryStore, ModelArtifactDownloader,
|
||||
OpenProjectRestoreStore, PermissionStore, PluginManifestValidator, PluginMcpSupervisor,
|
||||
PluginPackageStore, PluginRegistryStore, PluginStorageStore, ProcessSpawner, ProfileStore,
|
||||
ProjectPluginSettingsStore, ProjectStore, PtyHandle, PtyPort, RuntimePermissionProbe,
|
||||
ScheduledTask, Scheduler, SecretStore, SkillStore, SprintStore,
|
||||
ProjectPluginSettingsStore, ProjectSettingsStore, ProjectStore, PtyHandle, PtyPort,
|
||||
RuntimePermissionProbe, ScheduledTask, Scheduler, SecretStore, SkillStore, SprintStore,
|
||||
StructuredSessionEnvironmentPreparer, SystemPermissionStore, TemplateStore, ToolInvoker,
|
||||
WakeError, WakeReason, WindowStateStore,
|
||||
UserSettingsStore, WakeError, WakeReason, WindowStateStore,
|
||||
};
|
||||
use domain::profile::{
|
||||
AgentProfile, ContextInjection, McpConfigStrategy, McpTransport, StructuredAdapter,
|
||||
@ -105,19 +106,19 @@ use infrastructure::{
|
||||
FsHandoffStore, FsIssueNumberAllocator, FsIssueStore, FsLiveStateStore, FsManagedTempStore,
|
||||
FsMcpToolPermissionStore, FsMemoryStore, FsModelServerRegistry, FsOpenProjectRestoreStore,
|
||||
FsOrchestratorWatcher, FsPermissionStore, FsPluginPackageStore, FsPluginRegistryStore,
|
||||
FsPluginStorageStore, FsProfileStore, FsProjectPluginSettingsStore, FsProjectStore,
|
||||
FsProviderSessionStore, FsSecretStore, FsSkillStore, FsSprintStore, FsSystemPermissionStore,
|
||||
FsTemplateStore, FsWindowStateStore, Git2Repository, HeuristicHandoffSummarizer,
|
||||
HfModelArtifactDownloader, HttpOpenAiCompatibleProbe, HttpProviderModelCatalogue,
|
||||
IdeaiContextStore, InMemoryConversationRegistry, InMemoryMailbox, InMemoryPairAttemptLimiter,
|
||||
LlamaCppRuntime, LocalEnvironmentReader, LocalFileSystem, LocalManagedProcess,
|
||||
LocalProcessSpawner, ManagedTempToolProvider, McpServer, MediatedInbox, NaiveMemoryRecall,
|
||||
OrchestratorWatchHandle, PortablePtyAdapter, ProcessCliVersionReader,
|
||||
ReadOnlyRuntimePermissionProbe, RwFileGuard, StructuredSessionFactory, SystemClock,
|
||||
SystemMillisClock, TemplateToolProvider, TicketAssistantEnvironmentPreparer,
|
||||
TicketToolProvider, TokioBroadcastEventBus, TokioScheduler, ToolPolicyRegistry, UuidGenerator,
|
||||
VectorMemoryRecall, DEFAULT_OLLAMA_BASE_URL, ONNX_CACHE_SUBDIR, RECOMMENDED_ONNX_MODELS,
|
||||
VECTOR_HTTP_ENABLED, VECTOR_ONNX_ENABLED,
|
||||
FsPluginStorageStore, FsProfileStore, FsProjectPluginSettingsStore, FsProjectSettingsStore,
|
||||
FsProjectStore, FsProviderSessionStore, FsSecretStore, FsSkillStore, FsSprintStore,
|
||||
FsSystemPermissionStore, FsTemplateStore, FsUserSettingsStore, FsWindowStateStore,
|
||||
Git2Repository, HeuristicHandoffSummarizer, HfModelArtifactDownloader,
|
||||
HttpOpenAiCompatibleProbe, HttpProviderModelCatalogue, IdeaiContextStore,
|
||||
InMemoryConversationRegistry, InMemoryMailbox, InMemoryPairAttemptLimiter, LlamaCppRuntime,
|
||||
LocalEnvironmentReader, LocalFileSystem, LocalManagedProcess, LocalProcessSpawner,
|
||||
ManagedTempToolProvider, McpServer, MediatedInbox, NaiveMemoryRecall, OrchestratorWatchHandle,
|
||||
PortablePtyAdapter, ProcessCliVersionReader, ReadOnlyRuntimePermissionProbe, RwFileGuard,
|
||||
StructuredSessionFactory, SystemClock, SystemMillisClock, TemplateToolProvider,
|
||||
TicketAssistantEnvironmentPreparer, TicketToolProvider, TokioBroadcastEventBus, TokioScheduler,
|
||||
ToolPolicyRegistry, UuidGenerator, VectorMemoryRecall, DEFAULT_OLLAMA_BASE_URL,
|
||||
ONNX_CACHE_SUBDIR, RECOMMENDED_ONNX_MODELS, VECTOR_HTTP_ENABLED, VECTOR_ONNX_ENABLED,
|
||||
};
|
||||
|
||||
pub mod dto;
|
||||
@ -992,6 +993,7 @@ impl WakeSessionProvider for AppWakeSessionProvider {
|
||||
mcp_runtime: None,
|
||||
allow_structured_alongside_pty: true,
|
||||
require_structured: false,
|
||||
terminal_interface: None,
|
||||
fresh_start: false,
|
||||
managed_temp_exposure: application::ManagedTempExposureRequest::default(),
|
||||
})
|
||||
@ -1102,6 +1104,11 @@ fn self_restart_launch_input(
|
||||
mcp_runtime,
|
||||
allow_structured_alongside_pty: false,
|
||||
require_structured: context.require_structured,
|
||||
terminal_interface: Some(if context.require_structured {
|
||||
domain::DefaultAgentTerminalInterface::IdeaCli
|
||||
} else {
|
||||
domain::DefaultAgentTerminalInterface::NativeTui
|
||||
}),
|
||||
fresh_start: false,
|
||||
managed_temp_exposure: application::ManagedTempExposureRequest::default(),
|
||||
}
|
||||
@ -1124,6 +1131,11 @@ fn automatic_resume_launch_input(
|
||||
mcp_runtime,
|
||||
allow_structured_alongside_pty: false,
|
||||
require_structured: context.require_structured,
|
||||
terminal_interface: Some(if context.require_structured {
|
||||
domain::DefaultAgentTerminalInterface::IdeaCli
|
||||
} else {
|
||||
domain::DefaultAgentTerminalInterface::NativeTui
|
||||
}),
|
||||
fresh_start: false,
|
||||
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
|
||||
/// cases.
|
||||
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.
|
||||
pub health: Arc<HealthUseCase>,
|
||||
/// 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).
|
||||
pub attach_live_agent: Arc<AttachLiveAgent>,
|
||||
/// Tears down an already-running agent's live session by agent id (Lot D).
|
||||
pub stop_live_agent: Arc<StopLiveAgent>,
|
||||
pub stop_live_agent: Arc<StopAgentRuntime>,
|
||||
/// Best-effort inspection of a conversation (last topic + token indicator)
|
||||
/// for the resume popup (T7). Optional/extensible: backed by a `Vec` of
|
||||
/// [`domain::ports::SessionInspector`]s; an empty/missing match yields empty
|
||||
@ -2103,6 +2117,14 @@ pub struct BackendCore {
|
||||
pub inspect_conversation: Arc<InspectConversation>,
|
||||
/// Project registry — used by agent commands to resolve a `Project` from an id.
|
||||
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.
|
||||
pub get_project_permissions: Arc<GetProjectPermissions>,
|
||||
/// Update project-level default permissions.
|
||||
@ -2455,6 +2477,26 @@ impl BackendCore {
|
||||
// Port-typed handles for injection.
|
||||
let fs_port = Arc::clone(&fs) as Arc<dyn FileSystem>;
|
||||
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 =
|
||||
Arc::clone(&open_project_restore_store) as Arc<dyn OpenProjectRestoreStore>;
|
||||
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_plugin_mcp_resolver(Arc::clone(&project_plugin_resolver))
|
||||
.with_structured_routing_mode(StructuredRoutingMode::HumanPtyFallback)
|
||||
.with_user_settings(Arc::clone(&user_settings_store_port))
|
||||
.with_permission_store(Arc::clone(&permission_store_port))
|
||||
.with_system_permission_store(Arc::clone(&system_permission_store_port))
|
||||
// Reprise conversationnelle (lot P7) : à chaque (re)lancement, si la cellule
|
||||
@ -4100,14 +4143,17 @@ impl BackendCore {
|
||||
)) as Arc<dyn ToolInvoker>);
|
||||
|
||||
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(
|
||||
Arc::clone(&input_mediator),
|
||||
Arc::clone(&orchestrator_service),
|
||||
)
|
||||
.with_execution_cascade(Arc::clone(&orchestrator_service)
|
||||
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) ---
|
||||
@ -4131,6 +4177,7 @@ impl BackendCore {
|
||||
));
|
||||
|
||||
Self {
|
||||
clock: Arc::clone(&clock) as Arc<dyn Clock>,
|
||||
health,
|
||||
list_slash_commands,
|
||||
execute_slash_command,
|
||||
@ -4257,6 +4304,10 @@ impl BackendCore {
|
||||
stop_live_agent,
|
||||
inspect_conversation,
|
||||
project_store,
|
||||
read_user_settings,
|
||||
update_user_settings,
|
||||
read_project_settings,
|
||||
update_project_settings,
|
||||
get_project_permissions,
|
||||
update_project_permissions,
|
||||
update_agent_permissions,
|
||||
|
||||
@ -91,8 +91,10 @@ pub struct ConversationTurn {
|
||||
pub id: TurnId,
|
||||
/// La conversation (paire) à laquelle ce tour appartient.
|
||||
pub conversation: ConversationId,
|
||||
/// Horodatage (epoch millisecondes) du tour.
|
||||
pub at_ms: u64,
|
||||
/// Horodatage (epoch millisecondes) du tour. Absent uniquement pour les
|
||||
/// 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).
|
||||
pub source: InputSource,
|
||||
/// La nature du tour (invite, réponse, activité outillée).
|
||||
@ -115,7 +117,7 @@ impl ConversationTurn {
|
||||
Self {
|
||||
id,
|
||||
conversation,
|
||||
at_ms,
|
||||
at_ms: Some(at_ms),
|
||||
source,
|
||||
role,
|
||||
text: text.into(),
|
||||
|
||||
@ -67,6 +67,7 @@ pub mod readiness;
|
||||
pub mod remote;
|
||||
pub mod sandbox;
|
||||
pub mod session_limit;
|
||||
pub mod settings;
|
||||
pub mod skill;
|
||||
pub mod slash_command;
|
||||
pub mod sprint;
|
||||
@ -258,6 +259,8 @@ pub use sandbox::{
|
||||
SandboxKind, SandboxPlan, SandboxStatus,
|
||||
};
|
||||
|
||||
pub use settings::{DefaultAgentTerminalInterface, IdeaUserSettings, ProjectSettings, ThemeColor};
|
||||
|
||||
pub use orchestrator::{
|
||||
OrchestratorCommand, OrchestratorError, OrchestratorRequest, OrchestratorVisibility,
|
||||
};
|
||||
@ -277,9 +280,10 @@ pub use ports::{
|
||||
PluginManifestError, PluginManifestValidator, PluginMcpError, PluginMcpSupervisor,
|
||||
PluginPackageStore, PluginRegistryError, PluginRegistryStore, PluginStorageError,
|
||||
PluginStorageStore, PluginStoreError, PreparedContext, ProcessError, ProcessSpawner,
|
||||
ProfileStore, ProjectPluginSettingsStore, ProjectStore, ProviderModelCatalogue, PtyError,
|
||||
PtyHandle, PtyPort, RemoteError, RemoteHost, RemotePath, RuntimeError, RuntimePermissionProbe,
|
||||
ScheduledTask, Scheduler, SpawnSpec, SprintStore, SprintStoreError, StoreError,
|
||||
StructuredSessionEnvironment, StructuredSessionEnvironmentPreparer, SystemPermissionStore,
|
||||
TemplateStore, WindowStateStore,
|
||||
ProfileStore, ProjectPluginSettingsStore, ProjectSettingsStore, ProjectStore,
|
||||
ProviderModelCatalogue, PtyError, PtyHandle, PtyPort, RemoteError, RemoteHost, RemotePath,
|
||||
RuntimeError, RuntimePermissionProbe, ScheduledTask, Scheduler, SpawnSpec, SprintStore,
|
||||
SprintStoreError, StoreError, StructuredSessionEnvironment,
|
||||
StructuredSessionEnvironmentPreparer, SystemPermissionStore, TemplateStore, UserSettingsStore,
|
||||
WindowStateStore,
|
||||
};
|
||||
|
||||
@ -539,6 +539,31 @@ pub trait ProjectPluginSettingsStore: Send + Sync {
|
||||
) -> 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.
|
||||
pub trait PluginManifestValidator: Send + Sync {
|
||||
/// Validates raw manifest bytes.
|
||||
|
||||
69
crates/domain/src/settings.rs
Normal file
69
crates/domain/src/settings.rs
Normal 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>,
|
||||
}
|
||||
@ -120,8 +120,9 @@ pub use store::{
|
||||
AdaptiveMemoryRecall, BackgroundTaskReconcileReport, EmbedderEnvProbe, FsBackgroundTaskStore,
|
||||
FsDeviceSessionStore, FsEmbedderProfileStore, FsEmbedderPromptStore, FsLiveStateStore,
|
||||
FsMcpToolPermissionStore, FsMemoryStore, FsOpenProjectRestoreStore, FsPermissionStore,
|
||||
FsProfileStore, FsProjectStore, FsSecretStore, FsSkillStore, FsSystemPermissionStore,
|
||||
FsTemplateStore, FsWindowStateStore, HashEmbedder, IdeaiContextStore, NaiveMemoryRecall,
|
||||
OnnxModelInfo, StubEmbedder, VectorMemoryRecall, DEFAULT_OLLAMA_BASE_URL, ONNX_CACHE_SUBDIR,
|
||||
RECOMMENDED_ONNX_MODELS, VECTOR_HTTP_ENABLED, VECTOR_ONNX_ENABLED,
|
||||
FsProfileStore, FsProjectSettingsStore, FsProjectStore, FsSecretStore, FsSkillStore,
|
||||
FsSystemPermissionStore, FsTemplateStore, FsUserSettingsStore, FsWindowStateStore,
|
||||
HashEmbedder, IdeaiContextStore, NaiveMemoryRecall, OnnxModelInfo, StubEmbedder,
|
||||
VectorMemoryRecall, DEFAULT_OLLAMA_BASE_URL, ONNX_CACHE_SUBDIR, RECOMMENDED_ONNX_MODELS,
|
||||
VECTOR_HTTP_ENABLED, VECTOR_ONNX_ENABLED,
|
||||
};
|
||||
|
||||
@ -17,6 +17,7 @@ mod profile;
|
||||
mod project;
|
||||
mod project_plugin;
|
||||
mod secrets;
|
||||
mod settings;
|
||||
mod skill;
|
||||
mod system_permission;
|
||||
mod template;
|
||||
@ -44,6 +45,7 @@ pub use profile::{FsEmbedderProfileStore, FsProfileStore};
|
||||
pub use project::FsProjectStore;
|
||||
pub use project_plugin::FsProjectPluginSettingsStore;
|
||||
pub use secrets::FsSecretStore;
|
||||
pub use settings::{FsProjectSettingsStore, FsUserSettingsStore};
|
||||
pub use skill::FsSkillStore;
|
||||
pub use system_permission::FsSystemPermissionStore;
|
||||
pub use template::FsTemplateStore;
|
||||
|
||||
104
crates/infrastructure/src/store/settings.rs
Normal file
104
crates/infrastructure/src/store/settings.rs
Normal 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()))
|
||||
}
|
||||
}
|
||||
@ -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
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
74
crates/infrastructure/tests/settings.rs
Normal file
74
crates/infrastructure/tests/settings.rs
Normal 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}");
|
||||
}
|
||||
}
|
||||
@ -93,7 +93,7 @@ use backend::dto::{
|
||||
MemoryDto, MemoryIndexDto, MemoryLinksDto, MemoryListDto, OpenCodeProviderListDto,
|
||||
OpenProjectRestoreStateDto, OpenTerminalRequestDto, ProfileDto, ProfileListDto,
|
||||
ProfileModelCatalogDto, ProjectDto, ProjectListDto, ProjectMcpToolPermissionsDto,
|
||||
ProjectPermissionsDto, ProjectSystemPermissionsDto, ProjectWorkStateDto,
|
||||
ProjectPermissionsDto, ProjectSettingsDto, ProjectSystemPermissionsDto, ProjectWorkStateDto,
|
||||
ReadAgentContextResponseDto, ReadConversationPageRequestDto, RecallMemoryRequestDto,
|
||||
RemoveOpenProjectRestoreEntryRequestDto, RemoveProjectRequestDto, RemoveProjectResponseDto,
|
||||
RenameLayoutRequestDto, ResolveAgentPermissionsRequestDto, ResolveAgentPermissionsResponseDto,
|
||||
@ -116,7 +116,8 @@ use backend::dto::{
|
||||
UpdateAgentMcpToolPermissionsRequestDto, UpdateAgentPermissionsRequestDto,
|
||||
UpdateAgentSystemPermissionsRequestDto, UpdateMemoryRequestDto, UpdateProjectContextRequestDto,
|
||||
UpdateProjectMcpToolPermissionsRequestDto, UpdateProjectPermissionsRequestDto,
|
||||
UpdateProjectSystemPermissionsRequestDto, UpdateSkillRequestDto, UpdateTemplateRequestDto,
|
||||
UpdateProjectSettingsRequestDto, UpdateProjectSystemPermissionsRequestDto,
|
||||
UpdateSkillRequestDto, UpdateTemplateRequestDto, UserSettingsDto,
|
||||
};
|
||||
use backend::events::DomainEventDto;
|
||||
type PtyChunk = Vec<u8>;
|
||||
@ -1647,6 +1648,10 @@ async fn execute_launch_agent_for_ws(
|
||||
mcp_runtime,
|
||||
allow_structured_alongside_pty: false,
|
||||
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,
|
||||
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_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_pump = std::thread::spawn(move || {
|
||||
for event in tap_rx {
|
||||
@ -1930,7 +1936,7 @@ async fn ws_send_chat(
|
||||
if matches!(event, ReplyEvent::Final { .. } | ReplyEvent::Error { .. }) {
|
||||
continue;
|
||||
}
|
||||
let chunk = reply_event_chunk(event);
|
||||
let chunk = reply_event_chunk(event, u64::try_from(tap_clock.now_millis()).ok());
|
||||
if tap_out
|
||||
.blocking_send(ServerFrame::chat_output(None, sid, chunk))
|
||||
.is_err()
|
||||
@ -1978,7 +1984,10 @@ async fn ws_send_chat(
|
||||
break;
|
||||
}
|
||||
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(
|
||||
(!sent_ack).then_some(frame.id.as_str()),
|
||||
sid,
|
||||
@ -2002,7 +2011,7 @@ async fn ws_send_chat(
|
||||
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 {
|
||||
tx.send(ServerFrame::chat_output(Some(&frame.id), sid, chunk))
|
||||
.await
|
||||
@ -2030,7 +2039,10 @@ async fn ws_send_chat(
|
||||
resume_prompt = Some(prompt);
|
||||
}
|
||||
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(
|
||||
(!sent_ack).then_some(frame.id.as_str()),
|
||||
sid,
|
||||
@ -2076,7 +2088,7 @@ async fn ws_send_chat(
|
||||
tx.send(ServerFrame::chat_output(
|
||||
Some(&frame.id),
|
||||
sid,
|
||||
json!({ "kind": "final", "content": "" }),
|
||||
json!({ "kind": "final", "content": "", "atMs": u64::try_from(state.app.clock.now_millis()).ok() }),
|
||||
))
|
||||
.await
|
||||
.map_err(|_| ErrorDto {
|
||||
@ -2112,16 +2124,20 @@ fn ws_detach_chat(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reply_event_chunk(event: ReplyEvent) -> Value {
|
||||
fn reply_event_chunk(event: ReplyEvent, occurred_at_ms: Option<u64>) -> Value {
|
||||
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 } => {
|
||||
json!({ "kind": "toolActivity", "label": label })
|
||||
json!({ "kind": "toolActivity", "label": label, "atMs": occurred_at_ms })
|
||||
}
|
||||
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!({
|
||||
"kind": "progress",
|
||||
"progress": {
|
||||
@ -2129,6 +2145,7 @@ fn reply_event_chunk(event: ReplyEvent) -> Value {
|
||||
"kind": "other",
|
||||
"stage": "info",
|
||||
"label": "heartbeat"
|
||||
,"occurredAtMs": occurred_at_ms
|
||||
}
|
||||
}),
|
||||
ReplyEvent::RateLimited { resets_at_ms } => json!({
|
||||
@ -2138,15 +2155,20 @@ fn reply_event_chunk(event: ReplyEvent) -> Value {
|
||||
"kind": "turn",
|
||||
"stage": "info",
|
||||
"label": "rate_limited",
|
||||
"occurredAtMs": resets_at_ms
|
||||
"occurredAtMs": occurred_at_ms,
|
||||
"resetsAtMs": resets_at_ms
|
||||
}
|
||||
}),
|
||||
ReplyEvent::Error { message } => json!({ "kind": "error", "message": message }),
|
||||
ReplyEvent::Final { content } => json!({ "kind": "final", "content": content }),
|
||||
ReplyEvent::Error { message } => {
|
||||
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!({
|
||||
"progressId": progress.progress_id,
|
||||
"source": reply_progress_source(progress.source),
|
||||
@ -2157,6 +2179,7 @@ fn reply_progress_value(progress: ReplyProgress) -> Value {
|
||||
"provider": progress.provider,
|
||||
"nativeEvent": progress.native_event,
|
||||
"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,
|
||||
"read_project_context" => invoke_read_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,
|
||||
"reference_profiles" => invoke_reference_profiles(&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)
|
||||
}
|
||||
|
||||
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> {
|
||||
let output = state
|
||||
.first_run_state
|
||||
@ -3991,6 +4080,7 @@ async fn invoke_stop_live_agent(args: &Value, state: &BackendCore) -> Result<Val
|
||||
.execute(StopLiveAgentInput {
|
||||
project,
|
||||
agent_id: parse_agent_id(&request.agent_id)?,
|
||||
reason: request.reason,
|
||||
})
|
||||
.await
|
||||
.map(StopLiveAgentResponseDto::from)
|
||||
@ -8021,22 +8111,19 @@ mod tests {
|
||||
assert_eq!(ack.kind, "chat.output");
|
||||
assert_eq!(ack.reply_to.as_deref(), Some("chat-send"));
|
||||
assert_eq!(ack.payload["sessionId"], session_id.to_string());
|
||||
assert_eq!(
|
||||
ack.payload["chunk"],
|
||||
json!({ "kind": "textDelta", "text": "Hello " })
|
||||
);
|
||||
assert_eq!(ack.payload["chunk"]["kind"], "textDelta");
|
||||
assert_eq!(ack.payload["chunk"]["text"], "Hello ");
|
||||
assert!(ack.payload["chunk"]["atMs"].is_number());
|
||||
assert_eq!(tool.kind, "chat.output");
|
||||
assert!(tool.reply_to.is_none());
|
||||
assert_eq!(
|
||||
tool.payload["chunk"],
|
||||
json!({ "kind": "toolActivity", "label": "read_file" })
|
||||
);
|
||||
assert_eq!(tool.payload["chunk"]["kind"], "toolActivity");
|
||||
assert_eq!(tool.payload["chunk"]["label"], "read_file");
|
||||
assert!(tool.payload["chunk"]["atMs"].is_number());
|
||||
assert_eq!(final_chunk.kind, "chat.output");
|
||||
assert!(final_chunk.reply_to.is_none());
|
||||
assert_eq!(
|
||||
final_chunk.payload["chunk"],
|
||||
json!({ "kind": "final", "content": "Hello back" })
|
||||
);
|
||||
assert_eq!(final_chunk.payload["chunk"]["kind"], "final");
|
||||
assert_eq!(final_chunk.payload["chunk"]["content"], "Hello back");
|
||||
assert!(final_chunk.payload["chunk"]["atMs"].is_number());
|
||||
assert_eq!(
|
||||
session.prompts.lock().unwrap().as_slice(),
|
||||
&["Salut".to_owned()]
|
||||
@ -8087,10 +8174,9 @@ mod tests {
|
||||
|
||||
assert_eq!(final_chunk.kind, "chat.output");
|
||||
assert_eq!(final_chunk.reply_to.as_deref(), Some("chat-send-busy"));
|
||||
assert_eq!(
|
||||
final_chunk.payload["chunk"],
|
||||
json!({ "kind": "final", "content": "released" })
|
||||
);
|
||||
assert_eq!(final_chunk.payload["chunk"]["kind"], "final");
|
||||
assert_eq!(final_chunk.payload["chunk"]["content"], "released");
|
||||
assert!(final_chunk.payload["chunk"]["atMs"].is_number());
|
||||
assert!(
|
||||
!state.app.turn_watch_input.busy_state(runtime_key).is_busy(),
|
||||
"direct structured human turn should be idle after final"
|
||||
@ -8161,10 +8247,9 @@ mod tests {
|
||||
"idea_ask_agent"
|
||||
);
|
||||
assert_eq!(final_chunk.reply_to.as_deref(), Some("chat-send-progress"));
|
||||
assert_eq!(
|
||||
final_chunk.payload["chunk"],
|
||||
json!({ "kind": "final", "content": "done" })
|
||||
);
|
||||
assert_eq!(final_chunk.payload["chunk"]["kind"], "final");
|
||||
assert_eq!(final_chunk.payload["chunk"]["content"], "done");
|
||||
assert!(final_chunk.payload["chunk"]["atMs"].is_number());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@ -10262,6 +10347,49 @@ mod tests {
|
||||
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]
|
||||
async fn ticket_and_sprint_commands_require_authenticated_invoke() {
|
||||
let state = state();
|
||||
|
||||
Reference in New Issue
Block a user