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

@ -54,6 +54,7 @@ pub fn reference_profiles() -> Vec<AgentProfile> {
.expect("CLAUDE.md is a valid convention target"),
Some("claude --version".to_owned()),
"{agentRunDir}",
None,
)
.expect("claude reference profile is valid"),
AgentProfile::new(
@ -65,6 +66,7 @@ pub fn reference_profiles() -> Vec<AgentProfile> {
.expect("AGENTS.md is a valid convention target"),
Some("codex --version".to_owned()),
"{agentRunDir}",
None,
)
.expect("codex reference profile is valid"),
AgentProfile::new(
@ -76,6 +78,7 @@ pub fn reference_profiles() -> Vec<AgentProfile> {
.expect("GEMINI.md is a valid convention target"),
Some("gemini --version".to_owned()),
"{agentRunDir}",
None,
)
.expect("gemini reference profile is valid"),
AgentProfile::new(
@ -87,6 +90,7 @@ pub fn reference_profiles() -> Vec<AgentProfile> {
.expect("aider flag template is non-empty"),
Some("aider --version".to_owned()),
"{agentRunDir}",
None,
)
.expect("aider reference profile is valid"),
]

View File

@ -0,0 +1,142 @@
//! Best-effort conversation inspection use case (CONTEXT §T7, Part A).
//!
//! [`InspectConversation`] enriches a resume popup with the *last topic* and a
//! *token indicator* read from a CLI's on-disk transcript. It is **best-effort
//! by construction**: it routes the agent's [`AgentProfile`] to the first
//! injected [`SessionInspector`] that [`supports`](SessionInspector::supports)
//! it, and *any* miss — no inspector at all, an unsupported profile,
//! [`InspectError::NotFound`], or [`InspectError::Read`] — degrades to **empty
//! details** (`last_topic: None, token_count: None`) instead of an error. The
//! resume must never be blocked by inspection.
//!
//! Extensibility (Open/Closed): adding a new inspectable CLI is *pushing one
//! more adapter into the `Vec`* at the composition root — no change here.
//!
//! Like [`super::lifecycle::LaunchAgent`], it resolves the agent from the
//! project manifest and its profile from the [`ProfileStore`], and inspects
//! against the agent's **isolated run directory** (the very `cwd` the CLI was
//! launched with) so the inspector points at the right transcript folder.
use std::sync::Arc;
use domain::ports::{
AgentContextStore, ConversationDetails, InspectError, ProfileStore, SessionInspector,
};
use domain::{AgentId, Project};
use super::lifecycle::agent_run_dir;
use crate::error::AppError;
/// Input for [`InspectConversation::execute`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InspectConversationInput {
/// The project owning the agent.
pub project: Project,
/// The agent whose conversation is being inspected.
pub agent_id: AgentId,
/// The persistent CLI conversation id recorded on the hosting cell.
pub conversation_id: String,
}
/// Output of [`InspectConversation::execute`]: the (possibly empty) best-effort
/// details. Never an inspection error — a miss surfaces as empty fields.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InspectConversationOutput {
/// Enriched, best-effort details (every field optional).
pub details: ConversationDetails,
}
/// Reads best-effort [`ConversationDetails`] for an agent's conversation.
///
/// Holds a (possibly empty) `Vec<Arc<dyn SessionInspector>>`: the agent's
/// profile is routed to the first inspector that supports it. The use case still
/// needs the context store (resolve the agent) and the profile store (resolve
/// the profile), exactly like [`super::lifecycle::LaunchAgent`].
pub struct InspectConversation {
contexts: Arc<dyn AgentContextStore>,
profiles: Arc<dyn ProfileStore>,
inspectors: Vec<Arc<dyn SessionInspector>>,
}
impl InspectConversation {
/// Builds the use case from its injected ports and the inspector list (which
/// may be empty: that path simply yields empty details).
#[must_use]
pub fn new(
contexts: Arc<dyn AgentContextStore>,
profiles: Arc<dyn ProfileStore>,
inspectors: Vec<Arc<dyn SessionInspector>>,
) -> Self {
Self {
contexts,
profiles,
inspectors,
}
}
/// Resolves the agent + profile + run dir, then asks the first supporting
/// inspector for details. Returns **empty** details when no inspector
/// matches or inspection misses (`NotFound`/`Read`); only genuine store
/// failures (loading the manifest / profiles) surface as an error.
///
/// # Errors
/// - [`AppError::NotFound`] if the agent or its profile is unknown,
/// - [`AppError::Invalid`] if a persisted manifest entry / run dir is invalid,
/// - [`AppError::Store`] on a manifest / profile store failure.
pub async fn execute(
&self,
input: InspectConversationInput,
) -> Result<InspectConversationOutput, AppError> {
// Resolve the agent from the manifest (for its profile + run dir).
let manifest = self.contexts.load_manifest(&input.project).await?;
let entry = manifest
.entries
.iter()
.find(|e| e.agent_id == input.agent_id)
.ok_or_else(|| AppError::NotFound(format!("agent {}", input.agent_id)))?;
let agent = entry
.to_agent()
.map_err(|e| AppError::Invalid(e.to_string()))?;
let profile = self
.profiles
.list()
.await?
.into_iter()
.find(|p| p.id == agent.profile_id)
.ok_or_else(|| AppError::NotFound(format!("profile {} for agent", agent.profile_id)))?;
// The CLI runs with its isolated run dir as cwd; the inspector keys its
// transcript lookup off that same cwd (same value LaunchAgent uses).
let run_dir = agent_run_dir(&input.project.root, &agent.id)
.map_err(|e| AppError::Invalid(e.to_string()))?;
// Route to the first inspector that supports this profile. No match ⇒
// empty details (best-effort).
let Some(inspector) = self.inspectors.iter().find(|i| i.supports(&profile)) else {
return Ok(InspectConversationOutput {
details: empty_details(),
});
};
// Any inspection miss (NotFound / Read) degrades to empty details — it
// must never block a resume.
let details = match inspector
.details(&profile, &input.conversation_id, &run_dir)
.await
{
Ok(details) => details,
Err(InspectError::NotFound | InspectError::Read(_)) => empty_details(),
};
Ok(InspectConversationOutput { details })
}
}
/// The empty, fully-degraded [`ConversationDetails`] (no topic, no tokens).
fn empty_details() -> ConversationDetails {
ConversationDetails {
last_topic: None,
token_count: None,
}
}

View File

@ -14,12 +14,14 @@
use std::sync::Arc;
use domain::ports::{
AgentContextStore, AgentRuntime, ContextInjectionPlan, EventBus, FileSystem, PreparedContext,
ProfileStore, PtyPort, RemotePath, SkillStore, SpawnSpec, StoreError,
AgentContextStore, AgentRuntime, ContextInjectionPlan, EventBus, FileSystem, IdGenerator,
PreparedContext, ProfileStore, PtyPort, RemotePath, SessionPlan, SkillStore, SpawnSpec,
StoreError,
};
use domain::{
Agent, AgentId, AgentManifest, AgentOrigin, DomainEvent, ManifestEntry, MarkdownDoc, NodeId,
Project, ProfileId, ProjectPath, PtySize, SessionKind, SessionStatus, Skill, TerminalSession,
Agent, AgentId, AgentManifest, AgentOrigin, AgentProfile, ContextInjection, DomainEvent,
ManifestEntry, MarkdownDoc, NodeId, Project, ProfileId, ProjectPath, PtySize, SessionKind,
SessionStatus, Skill, TerminalSession,
};
use crate::error::AppError;
@ -327,6 +329,12 @@ pub struct LaunchAgentInput {
pub cols: u16,
/// The layout leaf hosting the session (a fresh node when `None`).
pub node_id: Option<NodeId>,
/// The persistent CLI conversation id currently recorded on the hosting cell,
/// if any. `Some` means a previous conversation exists and the launch should
/// **resume** it; `None` means a fresh cell (the launch may *assign* a new id
/// when the profile supports it). The caller (which owns the layout) reads this
/// from the leaf's [`domain::layout::LeafCell::conversation_id`].
pub conversation_id: Option<String>,
}
/// Output of [`LaunchAgent::execute`].
@ -334,6 +342,13 @@ pub struct LaunchAgentInput {
pub struct LaunchAgentOutput {
/// The created agent terminal session.
pub session: TerminalSession,
/// The conversation id **assigned** by this launch, when the profile supports
/// session assignment and the cell had none yet. The caller persists it on the
/// hosting leaf (via the layout flow, e.g. `set_cell_conversation`) so the next
/// open resumes instead of re-assigning. `None` when nothing new was assigned
/// (resume of an existing id, degraded mode, or a profile without a session
/// block) — the caller has nothing to persist.
pub assigned_conversation_id: Option<String>,
}
/// Launches an agent: resolve profile + context, prepare the invocation, apply
@ -353,6 +368,7 @@ pub struct LaunchAgent {
skills: Arc<dyn SkillStore>,
sessions: Arc<TerminalSessions>,
events: Arc<dyn EventBus>,
ids: Arc<dyn IdGenerator>,
}
impl LaunchAgent {
@ -368,6 +384,7 @@ impl LaunchAgent {
skills: Arc<dyn SkillStore>,
sessions: Arc<TerminalSessions>,
events: Arc<dyn EventBus>,
ids: Arc<dyn IdGenerator>,
) -> Self {
Self {
contexts,
@ -378,6 +395,7 @@ impl LaunchAgent {
skills,
sessions,
events,
ids,
}
}
@ -459,6 +477,16 @@ impl LaunchAgent {
.create_dir_all(&RemotePath::new(run_dir.as_str().to_owned()))
.await?;
// 3b. Seed the CLI's permission config in the run dir so the agent runs
// with the project's full autonomy and never blocks on per-command
// permission prompts. The agent's cwd is the run dir, so the CLI
// writes/reads its permission file there; without a seed, the CLI
// accumulates narrow per-command approvals and keeps prompting.
// Pragmatic per-CLI seed pending the universal `.ideai/permissions.json`
// + OS-sandbox model. Non-clobbering and best-effort.
self.seed_cli_permissions(&profile, &run_dir, &input.project.root)
.await?;
// 4. Prepare the invocation (pure): command + args + injection plan + cwd.
// The run dir is passed as the cwd base; the profile's `{agentRunDir}`
// placeholder resolves against it.
@ -466,9 +494,15 @@ impl LaunchAgent {
content: content.clone(),
relative_path: agent.context_path.clone(),
};
let mut spec = self
.runtime
.prepare_invocation(&profile, &prepared, &run_dir)?;
// 4a. Resolve the session intention (T4). The conversation id is a property
// of the *cell*, not the PTY: the caller (which owns the layout) passes
// the cell's current `conversation_id`. Any id this launch *assigns* is
// returned in the output so the caller persists it on the leaf.
let (session_plan, assigned_conversation_id) =
self.resolve_session_plan(&profile, input.conversation_id.clone());
let mut spec =
self.runtime
.prepare_invocation(&profile, &prepared, &run_dir, &session_plan)?;
// 5. Resolve the agent's assigned skills (their `.md` bodies), then apply
// the injection plan side effects *before* spawning.
@ -503,7 +537,102 @@ impl LaunchAgent {
session_id,
});
Ok(LaunchAgentOutput { session })
Ok(LaunchAgentOutput {
session,
assigned_conversation_id,
})
}
/// Resolves the [`SessionPlan`] for a launch from the profile's session
/// strategy and the cell's current `conversation_id` (T4).
///
/// Returns the plan *and* — when this launch mints a fresh id — that id, so the
/// caller can persist it on the hosting leaf. The id is only generated for an
/// `Assign` (profile has a `session` block with an `assign_flag`, and the cell
/// had no id yet); every other branch returns `None` (nothing to persist).
///
/// Branches:
/// - cell already has an id ⇒ [`SessionPlan::Resume`] (reopen) — no new id;
/// - no id, profile has `session.assign_flag` ⇒ mint a UUID, [`SessionPlan::Assign`];
/// - no id, profile has `session` but no `assign_flag` (degraded) ⇒
/// [`SessionPlan::None`] (nothing to resume on a first launch; the adapter
/// uses the bare resume flag only on later reopens);
/// - profile without a `session` block ⇒ [`SessionPlan::None`] (legacy).
fn resolve_session_plan(
&self,
profile: &AgentProfile,
cell_conversation_id: Option<String>,
) -> (SessionPlan, Option<String>) {
// No session strategy at all: behave exactly as before.
let Some(session) = &profile.session else {
return (SessionPlan::None, None);
};
// The cell already carries a conversation: resume it (no new id minted).
if let Some(conversation_id) = cell_conversation_id {
return (SessionPlan::Resume { conversation_id }, None);
}
// Fresh cell. Only mint+assign an id when the profile can assign one;
// otherwise (degraded mode) the first launch has nothing to resume.
if session.assign_flag.is_some() {
let conversation_id = self.ids.new_uuid().to_string();
(
SessionPlan::Assign {
conversation_id: conversation_id.clone(),
},
Some(conversation_id),
)
} else {
(SessionPlan::None, None)
}
}
/// Seeds the agent's run dir with the CLI permission config matching its
/// context-injection convention, so the agent inherits the project's autonomy
/// instead of prompting per command.
///
/// Conditioned on the CLI convention (only Claude Code — convention file
/// `CLAUDE.md` — has a known seed today); a no-op for any other CLI.
/// Best-effort and **non-clobbering**: an existing file (possibly user-edited)
/// is left untouched.
///
/// # Errors
/// [`AppError::FileSystem`] if the directory/file cannot be written.
async fn seed_cli_permissions(
&self,
profile: &AgentProfile,
run_dir: &ProjectPath,
project_root: &ProjectPath,
) -> Result<(), AppError> {
let is_claude = matches!(
&profile.context_injection,
ContextInjection::ConventionFile { target }
if target
.rsplit(['/', '\\'])
.next()
.unwrap_or(target)
.eq_ignore_ascii_case("CLAUDE.md")
);
if !is_claude {
return Ok(());
}
let settings_path =
RemotePath::new(format!("{}/.claude/settings.local.json", run_dir.as_str()));
if self.fs.exists(&settings_path).await? {
return Ok(());
}
self.fs
.create_dir_all(&RemotePath::new(format!("{}/.claude", run_dir.as_str())))
.await?;
self.fs
.write(
&settings_path,
claude_settings_seed(project_root.as_str()).as_bytes(),
)
.await?;
Ok(())
}
/// Applies the context-injection plan that must happen *before* spawn:
@ -561,10 +690,76 @@ fn join(base: &ProjectPath, rel: &str) -> String {
/// # Errors
/// Propagates [`DomainError`](domain::error::DomainError) if the joined path is
/// not a valid [`ProjectPath`] (should not happen for an absolute project root).
fn agent_run_dir(root: &ProjectPath, agent_id: &AgentId) -> Result<ProjectPath, domain::error::DomainError> {
pub(crate) fn agent_run_dir(root: &ProjectPath, agent_id: &AgentId) -> Result<ProjectPath, domain::error::DomainError> {
ProjectPath::new(join(root, &format!(".ideai/run/{agent_id}")))
}
/// Builds the Claude Code permission seed (`.claude/settings.local.json`) written
/// into an agent's run dir: full project autonomy (`bypassPermissions` + broad
/// Read/Edit/Write/Bash) with the project root granted as an additional working
/// directory (the cwd is the run dir, the agent works on the root above it), while
/// keeping destructive/out-of-project commands denied. `project_root` is embedded
/// verbatim; it is JSON-escaped to stay valid for unusual paths.
///
/// Pure (no I/O), so it is unit-testable in isolation.
#[must_use]
fn claude_settings_seed(project_root: &str) -> String {
let root = json_escape(project_root);
format!(
r#"{{
"permissions": {{
"defaultMode": "bypassPermissions",
"additionalDirectories": [
"{root}"
],
"allow": [
"Read",
"Edit",
"Write",
"Bash"
],
"deny": [
"Bash(sudo *)",
"Bash(rm -rf /)",
"Bash(rm -rf /*)",
"Bash(rm -rf ~)",
"Bash(rm -rf ~/)",
"Bash(rm -rf ~/*)",
"Bash(rm -rf $HOME*)",
"Bash(mkfs*)",
"Bash(dd if=*)",
"Bash(shutdown*)",
"Bash(reboot*)"
]
}},
"skipDangerousModePermissionPrompt": true,
"sandbox": {{
"enabled": false
}}
}}
"#
)
}
/// Minimal JSON string escaper for embedding a filesystem path in the settings
/// seed (handles the characters that actually occur in paths: backslash, quote,
/// and control chars).
fn json_escape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out
}
/// Composes the convention file IdeA writes into an agent's run directory: an
/// absolute project-root header (the agent's cwd is the run dir, *not* the root,
/// so it must be told where to work), the agent's persona `.md`, then the bodies
@ -700,4 +895,38 @@ mod tests {
assert!(doc.contains("## refactor"));
assert!(doc.contains("## review"));
}
#[test]
fn claude_settings_seed_grants_autonomy_and_keeps_guardrails() {
let json = claude_settings_seed("/home/me/proj");
// Full autonomy.
assert!(json.contains("\"defaultMode\": \"bypassPermissions\""));
assert!(json.contains("\"Bash\""));
// Project root granted as an additional working directory.
assert!(json.contains("\"/home/me/proj\""));
// Destructive guardrails preserved.
assert!(json.contains("Bash(sudo *)"));
assert!(json.contains("Bash(rm -rf /)"));
assert!(json.contains("Bash(mkfs*)"));
// Valid JSON.
let parsed: serde_json::Value = serde_json::from_str(&json).expect("seed is valid JSON");
assert_eq!(parsed["permissions"]["defaultMode"], "bypassPermissions");
assert_eq!(
parsed["permissions"]["additionalDirectories"][0],
"/home/me/proj"
);
}
#[test]
fn claude_settings_seed_escapes_paths_for_valid_json() {
// A path with a backslash and a quote must not break the JSON.
let json = claude_settings_seed(r#"/weird\path"x"#);
let parsed: serde_json::Value =
serde_json::from_str(&json).expect("seed with odd path is valid JSON");
assert_eq!(
parsed["permissions"]["additionalDirectories"][0],
r#"/weird\path"x"#
);
}
}

View File

@ -7,12 +7,16 @@
//! ports. Launching an agent (PTY + injection) is L6.
mod catalogue;
mod inspect;
mod lifecycle;
mod usecases;
pub(crate) use lifecycle::unique_md_path;
pub use catalogue::{reference_profile_id, reference_profiles};
pub use inspect::{
InspectConversation, InspectConversationInput, InspectConversationOutput,
};
pub use lifecycle::{
CreateAgentFromScratch, CreateAgentInput, CreateAgentOutput, DeleteAgent, DeleteAgentInput,
LaunchAgent, LaunchAgentInput, LaunchAgentOutput, ListAgents, ListAgentsInput, ListAgentsOutput,

View File

@ -21,9 +21,13 @@
//! `TerminalSessions` registry, keyed by that same `SessionId`.
mod management;
mod snapshot;
mod store;
mod usecases;
pub use snapshot::{
SnapshotRunningAgents, SnapshotRunningAgentsInput, SnapshotRunningAgentsOutput,
};
pub use management::{
CreateLayout, CreateLayoutInput, CreateLayoutOutput, DeleteLayout, DeleteLayoutInput,
DeleteLayoutOutput, LayoutInfo, ListLayouts, ListLayoutsInput, ListLayoutsOutput, RenameLayout,

View File

@ -0,0 +1,113 @@
//! [`SnapshotRunningAgents`] — freeze, at close time, which agent cells still
//! held a live PTY (feature: "conversation resume", task T5).
//!
//! When the IDE (or a single project) closes, every live PTY is about to be
//! killed. *Before* that happens, we record on each agent-bearing leaf whether
//! its agent process was still running (`agent_was_running = true`) or had
//! already exited / never launched (`false`). On reopen, that flag is what tells
//! the resume popup "this conversation was still in progress" vs "it was closed".
//!
//! The decision is **universal**: it is derived purely from the process
//! lifecycle (the live-session registry), never from parsing CLI output. The use
//! case itself is a thin orchestrator over:
//! - the persisted layouts store ([`super::store`]),
//! - the pure domain operation [`domain::LayoutTree::set_agent_running`],
//! - a [`LiveAgentRegistry`] liveness query.
//!
//! **Ordering contract:** this snapshot reads the registry *as it is at call
//! time*. The composition root (app-tauri) is responsible for calling it
//! **before** the global PTY kill; if the kill ran first, every agent would look
//! "closed". See `app-tauri`'s `CloseRequested` hook and `close.rs` callers.
use std::sync::Arc;
use domain::ports::{FileSystem, ProjectStore};
use domain::ProjectId;
use crate::error::AppError;
use crate::terminal::LiveAgentRegistry;
use super::store::{persist_doc, resolve_doc};
/// Input for [`SnapshotRunningAgents::execute`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SnapshotRunningAgentsInput {
/// The project whose layouts must be frozen.
pub project_id: ProjectId,
}
/// Output of [`SnapshotRunningAgents::execute`].
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SnapshotRunningAgentsOutput {
/// Number of agent-bearing leaves that were found running at snapshot time.
pub running: usize,
/// Number of agent-bearing leaves that were found stopped at snapshot time.
pub stopped: usize,
}
/// Freezes the `agent_was_running` flag on every agent leaf of a project's
/// layouts, from the live-session registry, then persists the layouts.
pub struct SnapshotRunningAgents {
store: Arc<dyn ProjectStore>,
fs: Arc<dyn FileSystem>,
live: Arc<dyn LiveAgentRegistry>,
}
impl SnapshotRunningAgents {
/// Builds the use case from its injected ports.
#[must_use]
pub fn new(
store: Arc<dyn ProjectStore>,
fs: Arc<dyn FileSystem>,
live: Arc<dyn LiveAgentRegistry>,
) -> Self {
Self { store, fs, live }
}
/// Executes the snapshot for one project.
///
/// Walks every named layout of the project; for each agent-bearing leaf it
/// applies [`domain::LayoutTree::set_agent_running`] with the agent's *current*
/// liveness, then persists the whole layouts store. A project with no
/// agent leaf is a no-op (the doc is still resolved/healed, never written if
/// unchanged).
///
/// # Errors
/// - [`AppError::NotFound`] if the project is unknown,
/// - [`AppError::FileSystem`] on persistence failure,
/// - [`AppError::Store`] on registry I/O failure.
pub async fn execute(
&self,
input: SnapshotRunningAgentsInput,
) -> Result<SnapshotRunningAgentsOutput, AppError> {
let project = self.store.load_project(input.project_id).await?;
let mut doc = resolve_doc(self.fs.as_ref(), &project).await?;
let mut out = SnapshotRunningAgentsOutput::default();
let mut changed = false;
for named in &mut doc.layouts {
for (leaf_id, agent_id) in named.tree.agent_leaves() {
let running = self.live.is_agent_live(&agent_id);
if running {
out.running += 1;
} else {
out.stopped += 1;
}
// Pure op: only NodeNotFound is possible, which cannot happen
// since `leaf_id` came from this very tree.
named.tree = named
.tree
.set_agent_running(leaf_id, running)
.map_err(|e| AppError::Invalid(e.to_string()))?;
changed = true;
}
}
if changed {
persist_doc(self.fs.as_ref(), &project, &doc).await?;
}
Ok(out)
}
}

View File

@ -103,6 +103,8 @@ pub fn default_tree() -> LayoutTree {
id: NodeId::new_random(),
session: None,
agent: None,
conversation_id: None,
agent_was_running: false,
})
}

View File

@ -76,6 +76,17 @@ pub enum LayoutOperation {
/// Agent to associate, or `None` to clear.
agent: Option<AgentId>,
},
/// Record (or clear) the persistent CLI conversation id on a leaf (T4b).
///
/// Persisting the id minted at first launch is what makes session resume
/// effective: on the next open, the leaf carries the id and the launch
/// resumes the conversation instead of assigning a new one.
SetCellConversation {
/// The hosting leaf.
target: NodeId,
/// Conversation id to record, or `None` to clear.
conversation_id: Option<String>,
},
}
impl LayoutOperation {
@ -94,6 +105,8 @@ impl LayoutOperation {
id: *new_leaf,
session: None,
agent: None,
conversation_id: None,
agent_was_running: false,
},
*container,
),
@ -105,6 +118,10 @@ impl LayoutOperation {
Self::Move { from, to } => tree.move_session(*from, *to),
Self::SetSession { target, session } => tree.set_session(*target, *session),
Self::SetCellAgent { target, agent } => tree.set_cell_agent(*target, *agent),
Self::SetCellConversation {
target,
conversation_id,
} => tree.set_cell_conversation(*target, conversation_id.clone()),
};
result.map_err(map_layout_err)
}

View File

@ -28,7 +28,8 @@ pub use agent::{
reference_profile_id, reference_profiles, ConfigureProfiles, ConfigureProfilesInput,
ConfigureProfilesOutput, CreateAgentFromScratch, CreateAgentInput, CreateAgentOutput,
DeleteAgent, DeleteAgentInput, DeleteProfile, DeleteProfileInput, DetectProfiles,
DetectProfilesInput, DetectProfilesOutput, FirstRunState, FirstRunStateOutput, LaunchAgent,
DetectProfilesInput, DetectProfilesOutput, FirstRunState, FirstRunStateOutput,
InspectConversation, InspectConversationInput, InspectConversationOutput, LaunchAgent,
LaunchAgentInput, LaunchAgentOutput, ListAgents, ListAgentsInput, ListAgentsOutput,
ListProfiles, ListProfilesOutput, ProfileAvailability, ReadAgentContext, ReadAgentContextInput,
ReadAgentContextOutput, ReferenceProfiles, ReferenceProfilesOutput, SaveProfile,
@ -49,7 +50,8 @@ pub use layout::{
DeleteLayoutOutput, LayoutInfo, LayoutKind, LayoutOperation, LayoutsDoc, ListLayouts,
ListLayoutsInput, ListLayoutsOutput, LoadLayout, LoadLayoutInput, LoadLayoutOutput,
MutateLayout, MutateLayoutInput, MutateLayoutOutput, NamedLayout, RenameLayout,
RenameLayoutInput, SetActiveLayout, SetActiveLayoutInput, LAYOUTS_FILE,
RenameLayoutInput, SetActiveLayout, SetActiveLayoutInput, SnapshotRunningAgents,
SnapshotRunningAgentsInput, SnapshotRunningAgentsOutput, LAYOUTS_FILE,
};
pub use project::{
CloseProject, CloseProjectInput, CloseProjectOutput, CloseTab, CloseTabInput, CreateProject,
@ -71,6 +73,7 @@ pub use skill::{
UpdateSkillOutput,
};
pub use terminal::{
LiveAgentRegistry,
CloseTerminal, CloseTerminalInput, CloseTerminalOutput, OpenTerminal, OpenTerminalInput,
OpenTerminalOutput, ResizeTerminal, ResizeTerminalInput, TerminalSessions, WriteToTerminal,
WriteToTerminalInput,

View File

@ -144,6 +144,7 @@ impl OrchestratorService {
rows: DEFAULT_ROWS,
cols: DEFAULT_COLS,
node_id: None,
conversation_id: None,
})
.await?;
@ -294,6 +295,7 @@ mod tests {
ContextInjection::convention_file("CLAUDE.md").unwrap(),
None,
"{agentRunDir}",
None,
)
.unwrap()
}

View File

@ -28,7 +28,7 @@
mod registry;
mod usecases;
pub use registry::TerminalSessions;
pub use registry::{LiveAgentRegistry, TerminalSessions};
pub use usecases::{
CloseTerminal, CloseTerminalInput, CloseTerminalOutput, OpenTerminal, OpenTerminalInput,
OpenTerminalOutput, ResizeTerminal, ResizeTerminalInput, WriteToTerminal, WriteToTerminalInput,

View File

@ -19,12 +19,30 @@ struct Entry {
session: TerminalSession,
}
/// Read-only liveness query over the agents that currently own a live PTY.
///
/// Abstracted as a trait so use cases that only need to ask "is this agent
/// running right now?" (e.g. the close-time snapshot of running agents) depend
/// on the *capability*, not on the whole [`TerminalSessions`] registry — and can
/// be tested against a trivial fake. [`TerminalSessions`] is the production
/// implementation.
pub trait LiveAgentRegistry: Send + Sync {
/// Whether `agent_id` currently has a live session in the registry.
fn is_agent_live(&self, agent_id: &AgentId) -> bool;
}
/// In-memory registry of active terminal sessions.
#[derive(Default)]
pub struct TerminalSessions {
entries: Mutex<HashMap<SessionId, Entry>>,
}
impl LiveAgentRegistry for TerminalSessions {
fn is_agent_live(&self, agent_id: &AgentId) -> bool {
self.session_for_agent(agent_id).is_some()
}
}
impl TerminalSessions {
/// Creates an empty registry.
#[must_use]