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:
2026-06-07 22:27:08 +02:00
parent d11eaaa8c0
commit 3ed0f6b45f
61 changed files with 5098 additions and 98 deletions

View File

@ -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)?;

View File

@ -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,
}
}
}

View File

@ -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,

View File

@ -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) {