feat(terminals): reprise de conversation par cellule + fix ordre d'écriture
Permet de recharger la conversation CLI précédente de chaque cellule à la
réouverture du projet, de façon universelle (indépendant du modèle/CLI).
- profil AgentRuntime: bloc déclaratif optionnel `session { assignFlag, resumeFlag }`
- LeafCell: `conversationId` (persistant, distinct du SessionId PTY) + `agentWasRunning`
- runtime: SessionPlan (None/Assign/Resume) + composition pure des args
- LaunchAgent: décide Assign vs Resume, génère l'UUID, remonte l'id assigné
(persistance par l'appelant via setCellConversation — découplage SRP)
- close: SnapshotRunningAgents fige `agentWasRunning` avant le kill-all
(statut clot/en cours universel, sans parsing CLI)
- SessionInspector: port optionnel best-effort + adapter ClaudeTranscriptInspector
- popup de reprise par cellule (statut + sujet/tokens si dispo), intercalée
avant le Resume auto, jamais sur le chemin reattach
fix(terminals): sérialise les écritures PTY (file FIFO par handle) — corrige
les caractères mélangés/accents dus au réordonnancement des invoke Tauri concurrents
fix(layout): l'opération `move` préservait mal les champs du leaf (perdait `agent`)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@ -11,9 +11,10 @@ use application::{
|
||||
AppError, CloseProjectInput, CreateAgentInput, CreateLayoutInput, DeleteAgentInput,
|
||||
DeleteLayoutInput, DeleteTemplateInput, DetectAgentDriftInput, GitBranchesInput,
|
||||
GitCheckoutInput, GitCommitInput, GitGraphInput, GitInitInput, GitLogInput, GitStagePathInput,
|
||||
GitStatusInput, LaunchAgentInput, ListAgentsInput, ListLayoutsInput, LoadLayoutInput,
|
||||
GitStatusInput, InspectConversationInput, LaunchAgentInput, ListAgentsInput, ListLayoutsInput, LoadLayoutInput,
|
||||
MutateLayoutInput, OpenProjectInput, ReadAgentContextInput, RenameLayoutInput,
|
||||
SetActiveLayoutInput, SyncAgentWithTemplateInput, UpdateAgentContextInput,
|
||||
SetActiveLayoutInput, SnapshotRunningAgentsInput, SyncAgentWithTemplateInput,
|
||||
UpdateAgentContextInput,
|
||||
AssignSkillToAgentInput, CreateSkillInput, DeleteSkillInput, ListSkillsInput,
|
||||
UnassignSkillFromAgentInput, UpdateSkillInput,
|
||||
};
|
||||
@ -28,6 +29,7 @@ use crate::dto::{
|
||||
DetectProfilesRequestDto, DetectProfilesResponseDto, ErrorDto, FirstRunStateDto,
|
||||
GitBranchesDto, GitCheckoutRequestDto, GitCommitDto, GitCommitListDto, GitCommitRequestDto,
|
||||
GitStageRequestDto, GitStatusListDto, GraphCommitListDto, HealthRequestDto, HealthResponseDto,
|
||||
ConversationDetailsDto, InspectConversationRequestDto,
|
||||
LaunchAgentRequestDto, LayoutDto, LayoutOperationDto, ListLayoutsDto, OpenTerminalRequestDto,
|
||||
ProfileDto, ProfileListDto, ProjectDto, ProjectListDto, ReadAgentContextResponseDto,
|
||||
ReattachResultDto, RenameLayoutRequestDto, ResizeTerminalRequestDto, SaveProfileRequestDto,
|
||||
@ -110,6 +112,13 @@ pub async fn close_project(
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), ErrorDto> {
|
||||
let id = parse_project_id(&project_id)?;
|
||||
// T5: freeze `agent_was_running` on every agent leaf BEFORE any PTY release,
|
||||
// reading the live registry as it stands now. Best-effort: a snapshot failure
|
||||
// must not block the close.
|
||||
let _ = state
|
||||
.snapshot_running_agents
|
||||
.execute(SnapshotRunningAgentsInput { project_id: id })
|
||||
.await;
|
||||
// Stop tailing this project's `.ideai/requests/` tree (§14.3).
|
||||
state.stop_orchestrator_watch(&id);
|
||||
state
|
||||
@ -740,6 +749,35 @@ pub async fn delete_agent(
|
||||
.map_err(ErrorDto::from)
|
||||
}
|
||||
|
||||
/// `inspect_conversation` — best-effort enriched details (last topic + token
|
||||
/// indicator) for a resume popup (T7).
|
||||
///
|
||||
/// Best-effort by contract: a missing/unsupported inspector or a missing
|
||||
/// transcript yields **empty details** (absent `lastTopic`/`tokenCount`), never
|
||||
/// an error. Only a genuine store failure (resolving the agent/profile) errors.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns an [`ErrorDto`] (`INVALID` for a malformed id, `NOT_FOUND` if the
|
||||
/// project, agent or profile is unknown, `STORE` on a manifest/profile failure).
|
||||
#[tauri::command]
|
||||
pub async fn inspect_conversation(
|
||||
request: InspectConversationRequestDto,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<ConversationDetailsDto, ErrorDto> {
|
||||
let project = resolve_project(&request.project_id, &state).await?;
|
||||
let agent_id = parse_agent_id(&request.agent_id)?;
|
||||
state
|
||||
.inspect_conversation
|
||||
.execute(InspectConversationInput {
|
||||
project,
|
||||
agent_id,
|
||||
conversation_id: request.conversation_id,
|
||||
})
|
||||
.await
|
||||
.map(ConversationDetailsDto::from)
|
||||
.map_err(ErrorDto::from)
|
||||
}
|
||||
|
||||
/// `launch_agent` — spawn an agent's CLI in a PTY and wire its byte stream to
|
||||
/// the frontend via a [`Channel`].
|
||||
///
|
||||
@ -770,6 +808,10 @@ pub async fn launch_agent(
|
||||
rows: request.rows,
|
||||
cols: request.cols,
|
||||
node_id: None,
|
||||
// Resume id is a property of the hosting cell; the frontend passes the
|
||||
// leaf's current conversation id here. `None` until the launch_agent
|
||||
// command is made layout-aware (T4 wiring follow-up).
|
||||
conversation_id: request.conversation_id.clone(),
|
||||
})
|
||||
.await
|
||||
.map_err(ErrorDto::from)?;
|
||||
|
||||
@ -231,6 +231,12 @@ pub struct TerminalSessionDto {
|
||||
pub rows: u16,
|
||||
/// Current cols.
|
||||
pub cols: u16,
|
||||
/// Conversation id **assigned** by this launch, when the agent's profile
|
||||
/// supports session assignment and the hosting cell had none yet (T4b). The
|
||||
/// front persists it on the leaf (`setCellConversation`) so the next open
|
||||
/// resumes. `None` for a plain terminal, a resume, or a degraded launch.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub assigned_conversation_id: Option<String>,
|
||||
}
|
||||
|
||||
impl From<OpenTerminalOutput> for TerminalSessionDto {
|
||||
@ -241,6 +247,7 @@ impl From<OpenTerminalOutput> for TerminalSessionDto {
|
||||
cwd: s.cwd.as_str().to_owned(),
|
||||
rows: s.pty_size.rows,
|
||||
cols: s.pty_size.cols,
|
||||
assigned_conversation_id: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -436,6 +443,15 @@ pub enum LayoutOperationDto {
|
||||
#[serde(default)]
|
||||
agent: Option<String>,
|
||||
},
|
||||
/// Record/clear the persistent CLI conversation id on a leaf (T4b).
|
||||
#[serde(rename_all = "camelCase")]
|
||||
SetCellConversation {
|
||||
/// Hosting leaf.
|
||||
target: String,
|
||||
/// Conversation id, or `null` to clear.
|
||||
#[serde(default)]
|
||||
conversation_id: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
impl LayoutOperationDto {
|
||||
@ -479,6 +495,13 @@ impl LayoutOperationDto {
|
||||
target: parse_node_id(&target)?,
|
||||
agent: agent.as_deref().map(parse_agent_id).transpose()?,
|
||||
},
|
||||
Self::SetCellConversation {
|
||||
target,
|
||||
conversation_id,
|
||||
} => LayoutOperation::SetCellConversation {
|
||||
target: parse_node_id(&target)?,
|
||||
conversation_id,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -832,7 +855,8 @@ pub fn parse_profile_id(raw: &str) -> Result<ProfileId, ErrorDto> {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
use application::{
|
||||
CreateAgentOutput, LaunchAgentOutput, ListAgentsOutput, ReadAgentContextOutput,
|
||||
CreateAgentOutput, InspectConversationOutput, LaunchAgentOutput, ListAgentsOutput,
|
||||
ReadAgentContextOutput,
|
||||
};
|
||||
use domain::Agent;
|
||||
|
||||
@ -915,16 +939,60 @@ pub struct LaunchAgentRequestDto {
|
||||
pub rows: u16,
|
||||
/// Initial terminal width in columns.
|
||||
pub cols: u16,
|
||||
/// Persistent CLI conversation id currently recorded on the hosting cell, if
|
||||
/// any. `Some` ⇒ the launch resumes it; absent/`None` ⇒ a fresh cell (the
|
||||
/// launch may assign a new id when the profile supports it).
|
||||
#[serde(default)]
|
||||
pub conversation_id: Option<String>,
|
||||
}
|
||||
|
||||
impl From<LaunchAgentOutput> for TerminalSessionDto {
|
||||
fn from(out: LaunchAgentOutput) -> Self {
|
||||
let assigned_conversation_id = out.assigned_conversation_id;
|
||||
let s = out.session;
|
||||
Self {
|
||||
session_id: s.id.to_string(),
|
||||
cwd: s.cwd.as_str().to_owned(),
|
||||
rows: s.pty_size.rows,
|
||||
cols: s.pty_size.cols,
|
||||
assigned_conversation_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Request DTO for `inspect_conversation` (T7).
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InspectConversationRequestDto {
|
||||
/// Id of the owning project.
|
||||
pub project_id: String,
|
||||
/// Id of the agent whose conversation is inspected.
|
||||
pub agent_id: String,
|
||||
/// The conversation id recorded on the hosting cell.
|
||||
pub conversation_id: String,
|
||||
}
|
||||
|
||||
/// Response DTO for `inspect_conversation` (T7): the best-effort enriched
|
||||
/// details for a resume popup. Both fields are optional and **omitted from the
|
||||
/// wire when `None`** (`skip_serializing_if`), so the TypeScript side sees an
|
||||
/// absent key — not `null` — for a degraded inspection.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ConversationDetailsDto {
|
||||
/// A short, best-effort label for the conversation (last user message,
|
||||
/// truncated). Absent when it could not be extracted.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub last_topic: Option<String>,
|
||||
/// A best-effort cumulative token count. Absent when no usage info exists.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub token_count: Option<u64>,
|
||||
}
|
||||
|
||||
impl From<InspectConversationOutput> for ConversationDetailsDto {
|
||||
fn from(out: InspectConversationOutput) -> Self {
|
||||
Self {
|
||||
last_topic: out.details.last_topic,
|
||||
token_count: out.details.token_count,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -59,8 +59,22 @@ pub fn run() {
|
||||
if let tauri::WindowEvent::CloseRequested { .. } = event {
|
||||
if let Some(state) = handle.try_state::<AppState>() {
|
||||
let pty = std::sync::Arc::clone(&state.pty_port);
|
||||
// ORDER IS CRITICAL: freeze `agent_was_running` on every
|
||||
// agent leaf of every open project FIRST, reading the live
|
||||
// PTY registry as it stands now; only THEN kill the PTYs.
|
||||
// If we killed first, the registry would be empty and every
|
||||
// agent would be persisted as "closed".
|
||||
let snapshot = std::sync::Arc::clone(&state.snapshot_running_agents);
|
||||
let open_projects = state.open_project_ids();
|
||||
let handles = state.terminal_sessions.handles();
|
||||
tauri::async_runtime::block_on(async move {
|
||||
for project_id in open_projects {
|
||||
let _ = snapshot
|
||||
.execute(application::SnapshotRunningAgentsInput {
|
||||
project_id,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
for h in handles {
|
||||
let _ = pty.kill(&h).await;
|
||||
}
|
||||
@ -103,6 +117,7 @@ pub fn run() {
|
||||
commands::update_agent_context,
|
||||
commands::delete_agent,
|
||||
commands::launch_agent,
|
||||
commands::inspect_conversation,
|
||||
commands::create_template,
|
||||
commands::update_template,
|
||||
commands::list_templates,
|
||||
|
||||
@ -14,10 +14,10 @@ use application::{
|
||||
CreateAgentFromTemplate, CreateLayout, CreateProject, CreateTemplate, DeleteAgent,
|
||||
DeleteLayout, DeleteProfile, DeleteTemplate, DetectAgentDrift, DetectProfiles, FirstRunState,
|
||||
GitBranches, GitCheckout, GitCommit, GitGraph, GitInit, GitLog, GitStage, GitStatus, GitUnstage,
|
||||
HealthUseCase, LaunchAgent, ListAgents, ListLayouts, ListProfiles, ListProjects, ListSkills,
|
||||
ListTemplates, LoadLayout, MoveTabToNewWindow, MutateLayout, OpenProject, OpenTerminal,
|
||||
OrchestratorService, ReadAgentContext, ReferenceProfiles, RenameLayout, ResizeTerminal,
|
||||
SaveProfile, SetActiveLayout,
|
||||
HealthUseCase, InspectConversation, LaunchAgent, ListAgents, ListLayouts, ListProfiles, ListProjects, ListSkills,
|
||||
ListTemplates, LiveAgentRegistry, LoadLayout, MoveTabToNewWindow, MutateLayout, OpenProject,
|
||||
OpenTerminal, OrchestratorService, ReadAgentContext, ReferenceProfiles, RenameLayout,
|
||||
ResizeTerminal, SaveProfile, SetActiveLayout, SnapshotRunningAgents,
|
||||
AssignSkillToAgent, CreateSkill, DeleteSkill, UnassignSkillFromAgent, UpdateSkill,
|
||||
SyncAgentWithTemplate, TerminalSessions, UpdateAgentContext, UpdateTemplate, WriteToTerminal,
|
||||
};
|
||||
@ -28,9 +28,10 @@ use domain::ports::{
|
||||
use domain::{DomainEvent, Project, ProjectId};
|
||||
|
||||
use infrastructure::{
|
||||
CliAgentRuntime, FsOrchestratorWatcher, FsProfileStore, FsProjectStore, FsSkillStore,
|
||||
FsTemplateStore, Git2Repository, IdeaiContextStore, LocalFileSystem, LocalProcessSpawner,
|
||||
OrchestratorWatchHandle, PortablePtyAdapter, SystemClock, TokioBroadcastEventBus, UuidGenerator,
|
||||
ClaudeTranscriptInspector, CliAgentRuntime, FsOrchestratorWatcher, FsProfileStore,
|
||||
FsProjectStore, FsSkillStore, FsTemplateStore, Git2Repository, IdeaiContextStore,
|
||||
LocalFileSystem, LocalProcessSpawner, OrchestratorWatchHandle, PortablePtyAdapter, SystemClock,
|
||||
TokioBroadcastEventBus, UuidGenerator,
|
||||
};
|
||||
|
||||
use crate::pty::PtyBridge;
|
||||
@ -76,6 +77,8 @@ pub struct AppState {
|
||||
pub delete_layout: Arc<DeleteLayout>,
|
||||
/// Set the active named layout (#4).
|
||||
pub set_active_layout: Arc<SetActiveLayout>,
|
||||
/// Freeze `agent_was_running` on every agent leaf before a PTY kill (T5).
|
||||
pub snapshot_running_agents: Arc<SnapshotRunningAgents>,
|
||||
/// Detect which candidate profiles' CLIs are installed (first-run).
|
||||
pub detect_profiles: Arc<DetectProfiles>,
|
||||
/// List configured profiles.
|
||||
@ -112,6 +115,11 @@ pub struct AppState {
|
||||
pub delete_agent: Arc<DeleteAgent>,
|
||||
/// Launch an agent (spawn PTY, apply injection strategy).
|
||||
pub launch_agent: Arc<LaunchAgent>,
|
||||
/// 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
|
||||
/// details, never an error.
|
||||
pub inspect_conversation: Arc<InspectConversation>,
|
||||
/// Project registry — used by agent commands to resolve a `Project` from an id.
|
||||
pub project_store: Arc<dyn ProjectStore>,
|
||||
// --- Windows (L10) ---
|
||||
@ -282,6 +290,14 @@ impl AppState {
|
||||
Arc::clone(&fs_port),
|
||||
Arc::clone(&events_port),
|
||||
));
|
||||
// Close-time snapshot of running agents (T5). Shares the SAME live-session
|
||||
// registry as the terminal/agent use cases, so its liveness check reflects
|
||||
// the very PTYs the shutdown hook is about to kill — it must run *before*.
|
||||
let snapshot_running_agents = Arc::new(SnapshotRunningAgents::new(
|
||||
Arc::clone(&store_port),
|
||||
Arc::clone(&fs_port),
|
||||
Arc::clone(&terminal_sessions) as Arc<dyn LiveAgentRegistry>,
|
||||
));
|
||||
|
||||
// --- Profiles & AI runtime (L5) ---
|
||||
// One generic, profile-driven runtime adapter (Open/Closed): it holds the
|
||||
@ -347,6 +363,27 @@ impl AppState {
|
||||
Arc::clone(&skill_store_port),
|
||||
Arc::clone(&terminal_sessions),
|
||||
Arc::clone(&events_port),
|
||||
Arc::clone(&ids) as Arc<dyn IdGenerator>,
|
||||
));
|
||||
|
||||
// --- Conversation inspection (T7) ---
|
||||
// Best-effort, optional, extensible: a `Vec` of SessionInspectors routed
|
||||
// by profile. Adding an inspectable CLI = pushing one more adapter here.
|
||||
// The Claude inspector reads `<home>/.claude/projects/<cwd>/<id>.jsonl`;
|
||||
// `$HOME` is resolved from the environment (empty string if unset — the
|
||||
// inspector then simply finds nothing and yields empty details).
|
||||
let home_dir = std::env::var("HOME")
|
||||
.or_else(|_| std::env::var("USERPROFILE"))
|
||||
.unwrap_or_default();
|
||||
let inspectors: Vec<Arc<dyn domain::ports::SessionInspector>> =
|
||||
vec![Arc::new(ClaudeTranscriptInspector::new(
|
||||
Arc::clone(&fs_port),
|
||||
home_dir,
|
||||
))];
|
||||
let inspect_conversation = Arc::new(InspectConversation::new(
|
||||
Arc::clone(&contexts_port),
|
||||
Arc::clone(&profile_store_port),
|
||||
inspectors,
|
||||
));
|
||||
|
||||
let project_store = Arc::clone(&store_port);
|
||||
@ -461,6 +498,7 @@ impl AppState {
|
||||
rename_layout,
|
||||
delete_layout,
|
||||
set_active_layout,
|
||||
snapshot_running_agents,
|
||||
detect_profiles,
|
||||
list_profiles,
|
||||
save_profile,
|
||||
@ -478,6 +516,7 @@ impl AppState {
|
||||
update_agent_context,
|
||||
delete_agent,
|
||||
launch_agent,
|
||||
inspect_conversation,
|
||||
project_store,
|
||||
create_template,
|
||||
update_template,
|
||||
@ -535,6 +574,20 @@ impl AppState {
|
||||
watchers.insert(project.id, handle);
|
||||
}
|
||||
|
||||
/// Returns the ids of every currently-open project.
|
||||
///
|
||||
/// Derived from the orchestrator watcher registry, which holds exactly one
|
||||
/// entry per open project (started on open/create, dropped on close). Used by
|
||||
/// the shutdown hook to snapshot running agents across all open projects
|
||||
/// before the global PTY kill.
|
||||
#[must_use]
|
||||
pub fn open_project_ids(&self) -> Vec<ProjectId> {
|
||||
self.orchestrator_watchers
|
||||
.lock()
|
||||
.map(|w| w.keys().copied().collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Stops and removes the orchestrator watcher for `project_id`, if any.
|
||||
/// Called from `close_project` so a closed project stops consuming requests.
|
||||
pub fn stop_orchestrator_watch(&self, project_id: &ProjectId) {
|
||||
|
||||
@ -223,6 +223,8 @@ fn layout_dto_serialises_camelcase_tagged_tree() {
|
||||
id: nid(1),
|
||||
session: None,
|
||||
agent: None,
|
||||
conversation_id: None,
|
||||
agent_was_running: false,
|
||||
});
|
||||
let dto = LayoutDto::from(LoadLayoutOutput {
|
||||
layout_id: domain::LayoutId::new_random(),
|
||||
@ -322,8 +324,10 @@ fn layout_dto_round_trips_a_split_tree_shape() {
|
||||
id: nid(1),
|
||||
session: None,
|
||||
agent: None,
|
||||
conversation_id: None,
|
||||
agent_was_running: false,
|
||||
})
|
||||
.split(nid(1), Direction::Column, LeafCell { id: nid(2), session: None, agent: None }, nid(9))
|
||||
.split(nid(1), Direction::Column, LeafCell { id: nid(2), session: None, agent: None, conversation_id: None, agent_was_running: false }, nid(9))
|
||||
.unwrap();
|
||||
let dto = LayoutDto::from(LoadLayoutOutput {
|
||||
layout_id: domain::LayoutId::new_random(),
|
||||
|
||||
@ -3,10 +3,14 @@
|
||||
//! and `From<LaunchAgentOutput>` for [`TerminalSessionDto`].
|
||||
|
||||
use app_tauri_lib::dto::{
|
||||
parse_agent_id, AgentDto, AgentListDto, CreateAgentRequestDto, LaunchAgentRequestDto,
|
||||
TerminalSessionDto, UpdateAgentContextRequestDto,
|
||||
parse_agent_id, AgentDto, AgentListDto, ConversationDetailsDto, CreateAgentRequestDto,
|
||||
InspectConversationRequestDto, LaunchAgentRequestDto, TerminalSessionDto,
|
||||
UpdateAgentContextRequestDto,
|
||||
};
|
||||
use application::{CreateAgentOutput, LaunchAgentOutput, ListAgentsOutput};
|
||||
use application::{
|
||||
CreateAgentOutput, InspectConversationOutput, LaunchAgentOutput, ListAgentsOutput,
|
||||
};
|
||||
use domain::ports::ConversationDetails;
|
||||
use domain::ids::{AgentId, NodeId, ProfileId, SessionId};
|
||||
use domain::terminal::{PtySize, SessionKind, SessionStatus, TerminalSession};
|
||||
use domain::{Agent, AgentOrigin, ProjectPath};
|
||||
@ -126,6 +130,72 @@ fn launch_agent_request_deserialises_camelcase() {
|
||||
assert_eq!(dto.cols, 80);
|
||||
assert_eq!(dto.project_id, project_id);
|
||||
assert_eq!(dto.agent_id, agent_id);
|
||||
// Omitting the resume id defaults to None (a fresh cell).
|
||||
assert_eq!(dto.conversation_id, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launch_agent_request_carries_conversation_id_for_resume() {
|
||||
let raw = json!({
|
||||
"projectId": Uuid::from_u128(1).to_string(),
|
||||
"agentId": Uuid::from_u128(2).to_string(),
|
||||
"rows": 24,
|
||||
"cols": 80,
|
||||
"conversationId": "resume-me"
|
||||
});
|
||||
let dto: LaunchAgentRequestDto = serde_json::from_value(raw).unwrap();
|
||||
// The leaf's persisted id reaches the backend so the launch resumes (T4b).
|
||||
assert_eq!(dto.conversation_id.as_deref(), Some("resume-me"));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// InspectConversation DTOs (T7)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn inspect_conversation_request_deserialises_camelcase() {
|
||||
let raw = json!({
|
||||
"projectId": Uuid::from_u128(1).to_string(),
|
||||
"agentId": Uuid::from_u128(2).to_string(),
|
||||
"conversationId": "conv-7"
|
||||
});
|
||||
let dto: InspectConversationRequestDto = serde_json::from_value(raw).unwrap();
|
||||
assert_eq!(dto.project_id, Uuid::from_u128(1).to_string());
|
||||
assert_eq!(dto.agent_id, Uuid::from_u128(2).to_string());
|
||||
assert_eq!(dto.conversation_id, "conv-7");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conversation_details_dto_serialises_camelcase_when_present() {
|
||||
let out = InspectConversationOutput {
|
||||
details: ConversationDetails {
|
||||
last_topic: Some("refactor parser".to_owned()),
|
||||
token_count: Some(1234),
|
||||
},
|
||||
};
|
||||
let dto = ConversationDetailsDto::from(out);
|
||||
let v = serde_json::to_value(&dto).unwrap();
|
||||
assert_eq!(v["lastTopic"], "refactor parser");
|
||||
assert_eq!(v["tokenCount"], 1234);
|
||||
// No snake_case leak.
|
||||
assert!(v.get("last_topic").is_none());
|
||||
assert!(v.get("token_count").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conversation_details_dto_omits_fields_when_none() {
|
||||
let out = InspectConversationOutput {
|
||||
details: ConversationDetails {
|
||||
last_topic: None,
|
||||
token_count: None,
|
||||
},
|
||||
};
|
||||
let dto = ConversationDetailsDto::from(out);
|
||||
let v = serde_json::to_value(&dto).unwrap();
|
||||
// Both optional fields are omitted from the wire (absent, not null).
|
||||
assert!(v.get("lastTopic").is_none(), "absent topic ⇒ field omitted");
|
||||
assert!(v.get("tokenCount").is_none(), "absent tokens ⇒ field omitted");
|
||||
assert_eq!(v, json!({}), "fully degraded ⇒ empty object");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@ -168,7 +238,10 @@ fn launch_agent_output_maps_to_terminal_session_dto() {
|
||||
);
|
||||
session.status = SessionStatus::Running;
|
||||
|
||||
let out = LaunchAgentOutput { session };
|
||||
let out = LaunchAgentOutput {
|
||||
session,
|
||||
assigned_conversation_id: None,
|
||||
};
|
||||
let dto = TerminalSessionDto::from(out);
|
||||
|
||||
assert_eq!(dto.session_id, session_id.to_string());
|
||||
@ -176,9 +249,51 @@ fn launch_agent_output_maps_to_terminal_session_dto() {
|
||||
assert_eq!(dto.rows, 24);
|
||||
assert_eq!(dto.cols, 80);
|
||||
|
||||
// Nothing assigned ⇒ no conversation id surfaced.
|
||||
assert_eq!(dto.assigned_conversation_id, None);
|
||||
|
||||
// Also verify camelCase serialisation.
|
||||
let v = serde_json::to_value(&dto).unwrap();
|
||||
assert_eq!(v["sessionId"], session_id.to_string());
|
||||
assert_eq!(v["cwd"], "/tmp/project");
|
||||
assert!(v.get("session_id").is_none(), "no snake_case leak");
|
||||
// Absent assignment must be omitted from the wire payload entirely.
|
||||
assert!(
|
||||
v.get("assignedConversationId").is_none(),
|
||||
"no assignment ⇒ field omitted"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launch_agent_output_propagates_assigned_conversation_id() {
|
||||
let session_id = SessionId::from_uuid(Uuid::from_u128(70));
|
||||
let node_id = NodeId::from_uuid(Uuid::from_u128(80));
|
||||
let agent_id = AgentId::from_uuid(Uuid::from_u128(90));
|
||||
let cwd = ProjectPath::new("/tmp/project".to_owned()).expect("valid path");
|
||||
let size = PtySize::new(24, 80).unwrap();
|
||||
|
||||
let mut session = TerminalSession::starting(
|
||||
session_id,
|
||||
node_id,
|
||||
cwd,
|
||||
SessionKind::Agent { agent_id },
|
||||
size,
|
||||
);
|
||||
session.status = SessionStatus::Running;
|
||||
|
||||
let out = LaunchAgentOutput {
|
||||
session,
|
||||
assigned_conversation_id: Some("conv-xyz".to_owned()),
|
||||
};
|
||||
let dto = TerminalSessionDto::from(out);
|
||||
|
||||
// The id minted by the launch is carried through to the DTO …
|
||||
assert_eq!(dto.assigned_conversation_id.as_deref(), Some("conv-xyz"));
|
||||
// … and serialised in camelCase for the front to persist on the leaf.
|
||||
let v = serde_json::to_value(&dto).unwrap();
|
||||
assert_eq!(v["assignedConversationId"], "conv-xyz");
|
||||
assert!(
|
||||
v.get("assigned_conversation_id").is_none(),
|
||||
"no snake_case leak"
|
||||
);
|
||||
}
|
||||
|
||||
@ -245,3 +245,66 @@ fn set_cell_agent_op_deserialises_with_absent_agent_defaults_to_none() {
|
||||
_ => panic!("expected SetCellAgent with None agent"),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// setCellConversation operation deserialisation (T4b)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn set_cell_conversation_op_deserialises_with_id() {
|
||||
let target = nid(1);
|
||||
let raw = json!({
|
||||
"type": "setCellConversation",
|
||||
"target": target.to_string(),
|
||||
"conversationId": "conv-42"
|
||||
});
|
||||
let dto: LayoutOperationDto = serde_json::from_value(raw).unwrap();
|
||||
let op = dto.into_operation().unwrap();
|
||||
match op {
|
||||
application::LayoutOperation::SetCellConversation {
|
||||
target: t,
|
||||
conversation_id: Some(id),
|
||||
} => {
|
||||
assert_eq!(t, target);
|
||||
assert_eq!(id, "conv-42");
|
||||
}
|
||||
_ => panic!("expected SetCellConversation with id"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_cell_conversation_op_deserialises_with_null_id() {
|
||||
let target = nid(2);
|
||||
let raw = json!({
|
||||
"type": "setCellConversation",
|
||||
"target": target.to_string(),
|
||||
"conversationId": null
|
||||
});
|
||||
let dto: LayoutOperationDto = serde_json::from_value(raw).unwrap();
|
||||
let op = dto.into_operation().unwrap();
|
||||
match op {
|
||||
application::LayoutOperation::SetCellConversation {
|
||||
target: t,
|
||||
conversation_id: None,
|
||||
} => assert_eq!(t, target),
|
||||
_ => panic!("expected SetCellConversation with None id"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_cell_conversation_op_deserialises_with_absent_id_defaults_to_none() {
|
||||
let target = nid(3);
|
||||
let raw = json!({
|
||||
"type": "setCellConversation",
|
||||
"target": target.to_string()
|
||||
});
|
||||
let dto: LayoutOperationDto = serde_json::from_value(raw).unwrap();
|
||||
let op = dto.into_operation().unwrap();
|
||||
match op {
|
||||
application::LayoutOperation::SetCellConversation {
|
||||
conversation_id: None,
|
||||
..
|
||||
} => {}
|
||||
_ => panic!("expected SetCellConversation with None id"),
|
||||
}
|
||||
}
|
||||
|
||||
@ -24,6 +24,7 @@ fn profile(id: u128, name: &str, command: &str) -> AgentProfile {
|
||||
ContextInjection::convention_file("CLAUDE.md").unwrap(),
|
||||
Some(format!("{command} --version")),
|
||||
"{projectRoot}",
|
||||
None,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user