diff --git a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs index 90c8a95742..ffe3a4c5d1 100644 --- a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs +++ b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs @@ -59,11 +59,7 @@ use crate::agentic::skill_agent_snapshot::{ use crate::agentic::tools::pipeline::{ PrimaryModelFacts, SubagentParentInfo, ToolExecutionContext, ToolExecutionOptions, ToolPipeline, }; -use crate::agentic::tools::{ - miniapp_agent_run_tool_restrictions, - tool_restrictions_for_delegation_policy as runtime_tool_restrictions_for_delegation_policy, - ToolRuntimeRestrictions, -}; +use crate::agentic::tools::{miniapp_agent_run_tool_restrictions, ToolRuntimeRestrictions}; use crate::agentic::workspace::WorkspaceServices; use crate::agentic::WorkspaceBinding; use crate::native_hooks::{self, NativeHookSessionFacts}; @@ -12843,10 +12839,9 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet context: request.context, permission_runtime_ceiling: Some(request.permission_runtime_ceiling), delegation_policy: request.delegation_policy, + // Launch tools enforce delegation policy without changing the catalog. runtime_tool_restrictions: runtime_tool_restrictions_for_session_lifetime( - runtime_tool_restrictions_for_delegation_policy( - request.delegation_policy, - ), + ToolRuntimeRestrictions::default(), transient, ), prompt_cache_source_session_id: None, @@ -12944,8 +12939,9 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet context: request.context, permission_runtime_ceiling: Some(request.permission_runtime_ceiling), delegation_policy: request.delegation_policy, + // Match forks: keep launch tools visible and enforce delegation at invocation. runtime_tool_restrictions: runtime_tool_restrictions_for_session_lifetime( - runtime_tool_restrictions_for_delegation_policy(request.delegation_policy), + ToolRuntimeRestrictions::default(), parent_transient, ), prompt_cache_source_session_id: None, diff --git a/src/crates/assembly/core/src/agentic/coordination/coordinator/tests/subagent_input.rs b/src/crates/assembly/core/src/agentic/coordination/coordinator/tests/subagent_input.rs index 61e4a854b8..2e33f2fa6f 100644 --- a/src/crates/assembly/core/src/agentic/coordination/coordinator/tests/subagent_input.rs +++ b/src/crates/assembly/core/src/agentic/coordination/coordinator/tests/subagent_input.rs @@ -14,6 +14,397 @@ use openbitfun_runtime_ports::{ }; use std::collections::HashMap; +#[tokio::test] +async fn current_context_estimate_supports_fresh_reused_and_forked_subagents() { + use crate::service::session::{DialogTurnData, UserMessageData}; + use openbitfun_core_types::{UsageContextCategory, UsageContextEstimateRequest}; + + let workspace = tempfile::tempdir().unwrap(); + crate::service::workspace::legacy_compat::register_local_fixture_blocking(workspace.path()); + std::fs::write( + workspace.path().join("AGENTS.md"), + "Child workspace instruction", + ) + .unwrap(); + TEST_MODEL_RESOLUTION_AI_CONFIG + .scope(context_estimate_ai_config(), async { + let (coordinator, manager) = test_persistent_coordinator(); + let persistence = manager.persistence_manager(); + let parent = manager + .create_session( + "Parent".into(), + "Standard".into(), + SessionConfig { + workspace_path: Some(workspace.path().to_string_lossy().into_owned()), + model_id: Some("parent-model".into()), + ..Default::default() + }, + ) + .await + .unwrap(); + let parent_message = + Message::user("Parent context is inherited only by forks. ".repeat(100)); + manager + .replace_context_messages(&parent.session_id, vec![parent_message.clone()]) + .await; + + let mut fresh_child = None; + let mut fresh_conversation = 0; + for (index, context_mode) in [ + SubagentContextMode::Fresh, + SubagentContextMode::Fresh, + SubagentContextMode::Fork, + ] + .into_iter() + .enumerate() + { + let target = (index == 1).then(|| fresh_child.clone().unwrap()); + let prepared = coordinator + .prepare_subagent_execution_request(SubagentExecutionRequest { + task_description: format!("Inspect child context {index}"), + requested_agent_id: None, + context_mode, + target_session_id: target.clone(), + subagent_type: (target.is_none() + && context_mode == SubagentContextMode::Fresh) + .then(|| "GeneralPurpose".into()), + logical_subagent_type: None, + continuation_policy: SessionContinuationPolicy::Reusable, + model_binding_policy: SessionModelBindingPolicy::Mutable, + workspace_path: None, + model_id: Some("child-model".into()), + inherit_parent_model: false, + subagent_parent_info: SubagentParentInfo { + session_id: parent.session_id.clone(), + dialog_turn_id: "parent-turn".into(), + tool_call_id: format!("spawn-{index}"), + }, + context: HashMap::new(), + permission_runtime_ceiling: PermissionRuntimeCeiling::default(), + delegation_policy: DelegationPolicy::top_level().spawn_child(), + external_generation_lease: None, + }) + .await + .unwrap(); + let child_id = prepared.target_session_id().unwrap().to_string(); + if index == 0 { + fresh_child = Some(child_id.clone()); + } + let messages = prepared.initial_messages.clone(); + drop(prepared); + manager + .replace_context_messages(&child_id, messages.clone()) + .await; + let storage = manager + .effective_session_storage_path(&child_id) + .await + .unwrap(); + let turn = DialogTurnData::new( + format!("child-turn-{index}"), + index, + child_id.clone(), + UserMessageData { + id: format!("child-input-{index}"), + content: format!("Inspect child context {index}"), + timestamp: 1, + metadata: None, + }, + ); + persistence.save_dialog_turn(&storage, &turn).await.unwrap(); + persistence + .save_turn_context_snapshot(&storage, &child_id, index, &messages) + .await + .unwrap(); + let root = if persistence.is_resolved_sessions_dir(&storage) { + storage.clone() + } else { + persistence.path_manager().project_sessions_dir(&storage) + }; + let child_dir = root.join(&child_id); + let before = context_estimate_session_files(&child_dir); + let session_before = + serde_json::to_value(manager.get_session(&child_id).unwrap()).unwrap(); + let mut estimates = Vec::new(); + for include_contents in [false, true] { + let inputs = manager + .read_context_estimate_inputs(&storage, &child_id) + .await + .unwrap(); + assert_eq!(inputs.session.kind, SessionKind::Subagent); + let estimate = coordinator + .estimate_session_context( + inputs, + &UsageContextEstimateRequest { + include_contents, + context_only: true, + }, + ) + .await + .unwrap(); + assert!(estimate.unavailable_reason.is_none()); + assert_eq!(estimate.contents.is_empty(), !include_contents); + estimates.push(estimate); + } + assert_eq!(estimates[0].composition, estimates[1].composition); + let composition = estimates[0].composition.as_ref().unwrap(); + assert_eq!(composition.context_window, Some(256_000)); + assert!(composition.system_prompt > 0); + assert!(composition.tool_definitions > 0); + assert!(composition.rules > 0); + assert!(composition.conversation > 0); + let preview = &estimates[1].contents; + assert!( + preview[&UsageContextCategory::Rules].contains("Child workspace instruction") + ); + assert!( + preview[&UsageContextCategory::ToolDefinitions].contains("\"name\": \"Read\"") + ); + for name in ["AgentSpawn", "AgentFork"] { + assert_eq!( + preview[&UsageContextCategory::ToolDefinitions] + .contains(&format!("\"name\": \"{name}\"")), + context_mode == SubagentContextMode::Fork, + "estimates must retain each agent's own tool policy" + ); + } + if index == 0 { + fresh_conversation = composition.conversation; + assert!(!messages + .iter() + .any(|message| message.id == parent_message.id)); + } else { + assert!(composition.conversation > fresh_conversation); + } + assert_eq!(before, context_estimate_session_files(&child_dir)); + assert_eq!( + session_before, + serde_json::to_value(manager.get_session(&child_id).unwrap()).unwrap() + ); + + // Persisted children must remain inspectable without being restored + // or depending on a legacy display snapshot. + manager.unload_session_from_memory(&child_id).await.unwrap(); + std::fs::write( + child_dir.join("usage-context.json"), + b"unreadable legacy display snapshot", + ) + .unwrap(); + let before = context_estimate_session_files(&child_dir); + let inputs = manager + .read_context_estimate_inputs(&storage, &child_id) + .await + .unwrap(); + let restored = coordinator + .estimate_session_context(inputs, &UsageContextEstimateRequest::default()) + .await + .unwrap(); + assert_eq!(restored.composition, estimates[0].composition); + assert!(manager.get_session(&child_id).is_none()); + assert_eq!(before, context_estimate_session_files(&child_dir)); + } + }) + .await; +} + +#[tokio::test] +async fn current_context_estimate_remote_subagent_uses_cached_rules_without_local_fallback() { + use crate::agentic::agents::get_agent_registry; + use crate::agentic::session::CachedUserContext; + use crate::agentic::tools::ToolRuntimeRestrictions; + use crate::agentic::WorkspaceBinding; + use crate::service::remote_ssh::workspace_state::WorkspaceSessionIdentity; + use openbitfun_core_types::{UsageContextCategory, UsageContextEstimateRequest, WorkspaceKind}; + + let local = tempfile::tempdir().unwrap(); + std::fs::write( + local.path().join("AGENTS.md"), + "Controller-local private rules", + ) + .unwrap(); + // A same-named controller path must never supply remote workspace rules. + let workspace = WorkspaceBinding::new_remote( + None, + local.path().to_path_buf(), + "context-estimate-connection".into(), + "remote-host".into(), + WorkspaceSessionIdentity { + workspace_kind: WorkspaceKind::Remote, + hostname: "remote-host".into(), + logical_workspace_path: local.path().to_string_lossy().into_owned(), + remote_connection_id: Some("context-estimate-connection".into()), + }, + ); + TEST_MODEL_RESOLUTION_AI_CONFIG + .scope(context_estimate_ai_config(), async { + let (coordinator, _) = test_coordinator(); + let agent = get_agent_registry() + .get_agent("GeneralPurpose", None) + .unwrap(); + for (kind, cached) in [ + (SessionKind::Subagent, false), + (SessionKind::Subagent, true), + (SessionKind::EphemeralChild, false), + (SessionKind::EphemeralChild, true), + ] { + let mut inputs = context_estimate_subagent_inputs(&workspace); + inputs.session.kind = kind; + if kind == SessionKind::EphemeralChild { + inputs.session.created_by = Some("session-parent".into()); + } + if cached { + let identity = agent.user_context_cache_identity(); + #[cfg(feature = "remote-workspace")] + let identity = crate::agentic::session::UserContextCacheIdentity::new(format!( + "{}|remote:remote-host", + identity.scope_key + )); + inputs.prompt_cache.user_context = Some(CachedUserContext::new( + identity, + "Remote child workspace rules", + )); + } + let result = coordinator + .execution_engine + .estimate_current_context( + inputs, + workspace.clone(), + None, + coordinator.terminal_port.get(), + coordinator.remote_exec_port.get(), + ToolRuntimeRestrictions::default(), + HashMap::new(), + &UsageContextEstimateRequest { + include_contents: true, + context_only: true, + }, + ) + .await; + if cached { + let estimate = result.unwrap(); + assert!(estimate.composition.unwrap().rules > 0); + let rules = &estimate.contents[&UsageContextCategory::Rules]; + assert!(rules.contains("Remote child workspace rules")); + assert!(!rules.contains("Controller-local private rules")); + } else { + assert!(result + .unwrap_err() + .to_string() + .contains("Workspace instructions are unavailable")); + } + } + }) + .await; +} + +#[tokio::test] +async fn current_context_estimate_keeps_external_and_internal_worker_contexts_unsupported() { + use crate::agentic::tools::ToolRuntimeRestrictions; + use crate::agentic::WorkspaceBinding; + use openbitfun_core_types::{SessionAgentRouteOwner, UsageContextEstimateRequest}; + + let (coordinator, _) = test_coordinator(); + let workspace = WorkspaceBinding::new(None, std::env::temp_dir()); + for (kind, route, agent_type, reason) in [ + ( + SessionKind::EphemeralChild, + SessionAgentRouteOwner::Local, + "GeneralPurpose", + "execution-scoped tool restrictions", + ), + ( + SessionKind::Subagent, + SessionAgentRouteOwner::External, + "GeneralPurpose", + "external agent", + ), + ( + SessionKind::Subagent, + SessionAgentRouteOwner::Local, + "acp:codex", + "external agent", + ), + ] { + let mut inputs = context_estimate_subagent_inputs(&workspace); + inputs.session.kind = kind; + inputs.session.config.agent_route_owner = route; + inputs.session.agent_type = agent_type.into(); + let error = coordinator + .execution_engine + .estimate_current_context( + inputs, + workspace.clone(), + None, + None, + None, + ToolRuntimeRestrictions::default(), + HashMap::new(), + &UsageContextEstimateRequest::default(), + ) + .await + .unwrap_err(); + assert!(error.to_string().contains(reason)); + } +} + +fn context_estimate_subagent_inputs( + workspace: &crate::agentic::WorkspaceBinding, +) -> crate::agentic::session::session_manager::ContextEstimateInputs { + use crate::agentic::core::Session; + use crate::agentic::session::session_manager::ContextEstimateInputs; + + let mut session = Session::new( + "Child".into(), + "GeneralPurpose".into(), + SessionConfig { + workspace_path: Some(workspace.root_path_string()), + model_id: Some("child-model".into()), + ..Default::default() + }, + ); + session.kind = SessionKind::Subagent; + ContextEstimateInputs { + session, + messages: vec![Message::user("Child task".into())], + prompt_cache: Default::default(), + cache_ttl: None, + listing_baseline: None, + turn_id: "child-turn".into(), + turn_metadata: None, + turn_index: 0, + } +} + +fn context_estimate_ai_config() -> AIConfig { + let mut config = AIConfig::default(); + config.models = [("parent-model", 64_000), ("child-model", 256_000)] + .into_iter() + .map(|(id, context_window)| AIModelConfig { + id: id.into(), + model_name: id.into(), + enabled: true, + context_window: Some(context_window), + ..Default::default() + }) + .collect(); + config.default_models.primary = Some("parent-model".into()); + config +} + +fn context_estimate_session_files( + path: &std::path::Path, +) -> std::collections::BTreeMap> { + let mut files = std::collections::BTreeMap::new(); + for entry in std::fs::read_dir(path).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + files.extend(context_estimate_session_files(&path)); + } else { + files.insert(path.clone(), std::fs::read(path).unwrap()); + } + } + files +} + #[tokio::test] async fn reused_subagent_send_input_updates_requested_and_inherited_model() { assert_reused_subagent_model_selection(None).await; @@ -165,6 +556,12 @@ async fn assert_reused_subagent_model_selection(legacy_routing: Option<&str>) { .await .expect("send_input request should prepare with a requested model"); + assert!(!prepared.delegation_policy.allow_subagent_spawn); + for tool_name in ["AgentSpawn", "AgentFork"] { + assert!(prepared + .runtime_tool_restrictions + .is_tool_allowed(tool_name)); + } assert_eq!(prepared.session_config.model_id.as_deref(), Some("fast")); if legacy_routing.is_some() { assert_eq!( diff --git a/src/crates/assembly/core/src/agentic/coordination/coordinator/tests/subagent_workspace.rs b/src/crates/assembly/core/src/agentic/coordination/coordinator/tests/subagent_workspace.rs index 4a8450c8e2..d679bad1dc 100644 --- a/src/crates/assembly/core/src/agentic/coordination/coordinator/tests/subagent_workspace.rs +++ b/src/crates/assembly/core/src/agentic/coordination/coordinator/tests/subagent_workspace.rs @@ -117,6 +117,12 @@ async fn fresh_subagent_inherits_matching_parent_worktree_binding() { .await .expect("fresh subagent request should resolve"); + assert!(!resolved.delegation_policy.allow_subagent_spawn); + for tool_name in ["AgentSpawn", "AgentFork"] { + assert!(resolved + .runtime_tool_restrictions + .is_tool_allowed(tool_name)); + } assert_eq!( resolved.session_config.workspace_path.as_deref(), Some(workspace_path.as_str()) @@ -201,6 +207,12 @@ async fn fresh_subagent_inherits_transient_parent_persistence_boundary() { .expect("fresh subagent request should resolve"); assert!(resolved.transient); + assert!(!resolved.delegation_policy.allow_subagent_spawn); + for tool_name in ["AgentSpawn", "AgentFork"] { + assert!(resolved + .runtime_tool_restrictions + .is_tool_allowed(tool_name)); + } assert!(!resolved .runtime_tool_restrictions .is_tool_allowed("SessionControl")); diff --git a/src/crates/assembly/core/src/agentic/execution/execution_engine/context_estimate.rs b/src/crates/assembly/core/src/agentic/execution/execution_engine/context_estimate.rs index af0cc006b5..d1d0a9eea5 100644 --- a/src/crates/assembly/core/src/agentic/execution/execution_engine/context_estimate.rs +++ b/src/crates/assembly/core/src/agentic/execution/execution_engine/context_estimate.rs @@ -24,7 +24,17 @@ impl ExecutionEngine { "The external agent does not expose its current model context".into(), )); } - if session.kind != openbitfun_core_types::SessionKind::Standard { + // BTW inherits a normal conversation's catalog and carries host-assigned + // parent ownership, even before its first turn. Other ephemeral workers + // may have execution-only restrictions that inspection cannot reconstruct. + let has_conversation_parent = session + .created_by + .as_deref() + .and_then(|owner| owner.strip_prefix("session-")) + .is_some_and(|parent_id| !parent_id.is_empty()); + if session.kind == openbitfun_core_types::SessionKind::EphemeralChild + && !has_conversation_parent + { return Err(OpenBitFunError::NotImplemented( "Delegated session context requires its execution-scoped tool restrictions".into(), )); diff --git a/src/crates/assembly/core/src/agentic/session/session_manager/context_estimate.rs b/src/crates/assembly/core/src/agentic/session/session_manager/context_estimate.rs index 46fdc31e6a..d4c0662597 100644 --- a/src/crates/assembly/core/src/agentic/session/session_manager/context_estimate.rs +++ b/src/crates/assembly/core/src/agentic/session/session_manager/context_estimate.rs @@ -24,6 +24,9 @@ impl SessionManager { Some(session) => session, None => persistence.load_session_header(storage, session_id).await?, }; + if !self.should_persist_session_id(session_id) { + return self.read_in_memory_context_estimate_inputs(session); + } let boundary = persistence .load_session_revert_state(storage, session_id) .await? @@ -113,4 +116,53 @@ impl SessionManager { cache_ttl: self.config.prompt_cache_policy.cache_ttl, }) } + + fn read_in_memory_context_estimate_inputs( + &self, + session: Session, + ) -> OpenBitFunResult { + let session_id = &session.session_id; + if !self.context_store.has_session(session_id) { + return Err(OpenBitFunError::service( + "Temporary session context is unavailable for context inspection", + )); + } + let turn = self + .transient_turns + .get(session_id) + .and_then(|history| history.turns.last().cloned()); + if turn.is_none() && !session.dialog_turn_ids.is_empty() { + return Err(OpenBitFunError::service( + "Temporary session history is unavailable for context inspection", + )); + } + let messages = self.context_store.get_context_messages(session_id); + let prompt_cache = self + .prompt_cache_store + .get_cache(session_id) + .unwrap_or_default(); + let listing_baseline = self + .skill_agent_baseline_override_snapshot_store + .get(session_id) + .map(|snapshot| snapshot.value().clone()) + .or_else(|| { + self.turn_skill_agent_snapshot_store + .get_snapshot(session_id, 0) + }); + Ok(ContextEstimateInputs { + session, + messages, + prompt_cache, + listing_baseline, + turn_id: turn + .as_ref() + .map(|turn| turn.turn_id.clone()) + .unwrap_or_default(), + turn_metadata: turn + .as_ref() + .and_then(|turn| turn.user_message.metadata.clone()), + turn_index: turn.as_ref().map(|turn| turn.turn_index).unwrap_or(0), + cache_ttl: self.config.prompt_cache_policy.cache_ttl, + }) + } } diff --git a/src/crates/assembly/core/src/agentic/session/session_manager/tests/context_usage.rs b/src/crates/assembly/core/src/agentic/session/session_manager/tests/context_usage.rs index fe7da3dba9..55cdc13caa 100644 --- a/src/crates/assembly/core/src/agentic/session/session_manager/tests/context_usage.rs +++ b/src/crates/assembly/core/src/agentic/session/session_manager/tests/context_usage.rs @@ -8,6 +8,162 @@ use crate::service::session::{DialogTurnData, SessionContextUsage, SessionContex use std::path::{Path, PathBuf}; use std::sync::Arc; +#[tokio::test] +async fn current_context_estimate_reads_temporary_turns_caches_and_compression_only_from_memory() { + use crate::agentic::core::{MessageSemanticKind, SessionKind}; + use crate::agentic::session::{SystemPromptCacheIdentity, UserContextCacheIdentity}; + use crate::agentic::skill_agent_snapshot::{SkillSnapshotEntry, TurnSkillAgentSnapshot}; + + let workspace = TestWorkspace::new(); + let persistence = Arc::new(PersistenceManager::new(workspace.path_manager()).unwrap()); + let manager = test_manager(persistence.clone()); + let session = manager + .create_session_with_id_and_details( + None, + "BTW".into(), + "Standard".into(), + SessionConfig { + workspace_path: Some(workspace.path().to_string_lossy().into_owned()), + ..Default::default() + }, + Some("session-parent".into()), + SessionKind::EphemeralChild, + ) + .await + .unwrap(); + let id = &session.session_id; + let storage = manager.effective_session_storage_path(id).await.unwrap(); + let inherited = Message::user("Inherited context".into()); + manager + .replace_context_messages(id, vec![inherited.clone()]) + .await; + let initial = manager + .read_context_estimate_inputs(&storage, id) + .await + .unwrap(); + assert!(initial.turn_id.is_empty()); + assert!(initial.prompt_cache.is_empty()); + assert!(initial.listing_baseline.is_none()); + assert_eq!(initial.messages[0].id, inherited.id); + let root = if persistence.is_resolved_sessions_dir(&storage) { + storage.clone() + } else { + persistence.path_manager().project_sessions_dir(&storage) + }; + let child_dir = root.join(id); + assert!(!child_dir.exists()); + + manager + .remember_system_prompt( + id, + SystemPromptCacheIdentity::new("system"), + "Cached system".into(), + ) + .await; + manager + .remember_user_context( + id, + UserContextCacheIdentity::new("rules"), + "Cached rules".into(), + ) + .await; + let baseline = TurnSkillAgentSnapshot { + skills: vec![SkillSnapshotEntry { + name: "inherited-skill".into(), + description: "Inherited skill baseline".into(), + location: "/workspace/skill.md".into(), + }], + subagents: Vec::new(), + deferred_tools: None, + }; + manager + .skill_agent_baseline_override_snapshot_store + .insert(id.clone(), baseline.clone()); + for index in 0..2 { + let turn_id = manager + .start_dialog_turn( + id, + "Standard".into(), + format!("Question {index}"), + Some(format!("btw-turn-{index}")), + None, + Some(serde_json::json!({"kind": "btw", "questionIndex": index})), + ) + .await + .unwrap(); + if index == 0 { + manager + .complete_dialog_turn( + id, + &turn_id, + "Answer".into(), + &[], + Default::default(), + Some("stop".into()), + Some(true), + ) + .await + .unwrap(); + manager.reset_session_state_if_processing(id, &turn_id); + } + } + let mut summary = Message::user("Compressed temporary conversation".into()); + summary.metadata.semantic_kind = Some(MessageSemanticKind::CompressionSummary); + manager + .replace_context_messages(id, vec![summary.clone()]) + .await; + assert!( + !child_dir.exists(), + "temporary history and caches must not be persisted" + ); + + // Even an unrelated durable record at this ID cannot supply recovery facts. + std::fs::create_dir_all(&child_dir).unwrap(); + let poison = child_dir.join("session-revert.json"); + std::fs::write(&poison, b"not temporary session state").unwrap(); + let inputs = manager + .read_context_estimate_inputs(&storage, id) + .await + .unwrap(); + assert_eq!(inputs.turn_id, "btw-turn-1"); + assert_eq!(inputs.turn_index, 1); + assert_eq!(inputs.turn_metadata.unwrap()["questionIndex"], 1); + assert_eq!(inputs.messages.len(), 1); + assert_eq!(inputs.messages[0].id, summary.id); + assert_eq!( + inputs.prompt_cache.system_prompt.unwrap().text.content, + "Cached system" + ); + assert_eq!( + inputs.prompt_cache.user_context.unwrap().text.content, + "Cached rules" + ); + assert_eq!(inputs.listing_baseline, Some(baseline)); + assert_eq!( + std::fs::read(&poison).unwrap(), + b"not temporary session state" + ); + assert_eq!(std::fs::read_dir(&child_dir).unwrap().count(), 1); + + manager.context_store.delete_session(id); + assert!(manager + .read_context_estimate_inputs(&storage, id) + .await + .err() + .expect("missing context must fail") + .to_string() + .contains("Temporary session context is unavailable")); + manager.context_store.replace_context(id, vec![summary]); + manager.transient_turns.remove(id); + assert!(manager + .read_context_estimate_inputs(&storage, id) + .await + .err() + .expect("missing temporary history must fail") + .to_string() + .contains("Temporary session history is unavailable")); +} + #[tokio::test] async fn current_context_estimate_reads_compression_forks_and_legacy_snapshots_without_writes() { use openbitfun_services_core::session::{SessionBranchBoundary, SessionBranchRequest}; diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/tests.rs b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/tests.rs index 854f9a320c..ab34101634 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/tests.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/tests.rs @@ -1013,7 +1013,7 @@ async fn validate_input_accepts_fork_context_with_caller_selected_agent_id() { } #[tokio::test] -async fn call_impl_rejects_nested_subagent_delegation() { +async fn visible_launch_tools_reject_nested_subagent_delegation() { let policy = DelegationPolicy::top_level().spawn_child(); let context = ToolUseContext { tool_call_id: Some("tool-call-1".to_string()), @@ -1039,6 +1039,19 @@ async fn call_impl_rejects_nested_subagent_delegation() { runtime_handles: openbitfun_runtime_ports::ToolRuntimeHandles::default(), }; + let manifest = crate::agentic::tools::resolve_tool_manifest( + &["AgentSpawn".into(), "AgentFork".into()], + &Default::default(), + &context, + ) + .await; + for tool_name in ["AgentSpawn", "AgentFork"] { + assert!(manifest + .tool_definitions + .iter() + .any(|definition| definition.name == tool_name)); + } + let error = AgentExecutionTool::new() .call_impl( &json!({ @@ -1055,6 +1068,20 @@ async fn call_impl_rejects_nested_subagent_delegation() { assert!(error .to_string() .contains("Recursive subagent delegation is blocked. Use direct tools instead.")); + let spawn_error = AgentSpawnTool::new() + .call_impl( + &json!({ + "agent_id": "repo-inspector", + "prompt": "Inspect the repo", + "agent_type": "Explore" + }), + &context, + ) + .await + .expect_err("visible launch tools must enforce nested delegation restrictions"); + assert!(spawn_error + .to_string() + .contains("Recursive subagent delegation is blocked")); let fork_error = AgentForkTool::new() .call_impl( &json!({"agent_id":"review-fork", "prompt":"Review the inherited findings"}), diff --git a/src/crates/assembly/core/src/product_runtime.rs b/src/crates/assembly/core/src/product_runtime.rs index 1886540f2c..313c527d9d 100644 --- a/src/crates/assembly/core/src/product_runtime.rs +++ b/src/crates/assembly/core/src/product_runtime.rs @@ -468,6 +468,21 @@ async fn begin_session_read( let guard = session_manager.acquire_session_mutation(session_id).await?; session_manager.validate_session_storage_path_binding(session_id, storage_path)?; + // Temporary conversations have no durable revert or recovery state. Never + // consult an unrelated on-disk record with the same ID for a live memory owner. + if let Some(session) = session_manager + .get_session(session_id) + .filter(|_| !session_manager.should_persist_session_id(session_id)) + { + if let Some(expected) = expected_workspace { + validate_session_workspace_identity(&session, expected)?; + } + return Ok(CoreSessionReadPermit { + _guard: guard, + visible_turn_end: None, + }); + } + // A remote mirror's Session directory predates connection-specific snapshot // scopes. Check durable and loaded identity under the same lock before // reconciling history or exposing any operation content. @@ -5334,6 +5349,137 @@ mod tests { ); } + #[tokio::test] + async fn current_context_estimate_btw_inspects_live_state_without_durable_history() { + use crate::agentic::core::{Message, MessageSemanticKind, SessionConfig}; + use crate::agentic::session::TEST_MODEL_RESOLUTION_AI_CONFIG; + use crate::service::config::types::{AIConfig, AIModelConfig}; + use openbitfun_core_types::{UsageContextCategory, UsageContextEstimateRequest}; + + let workspace = TestWorkspace::new(); + std::fs::write(workspace.path().join("AGENTS.md"), "BTW workspace rules").unwrap(); + let persistence = Arc::new(PersistenceManager::new(workspace.path_manager()).unwrap()); + let manager = Arc::new(SessionManager::new( + Arc::new(SessionContextStore::new()), + persistence.clone(), + SessionManagerConfig { + max_active_sessions: 100, + session_idle_timeout: Duration::from_secs(3600), + auto_save_interval: Duration::from_secs(300), + enable_persistence: true, + prompt_cache_policy: PromptCachePolicy::default(), + }, + )); + let events = Arc::new(EventQueue::new(EventQueueConfig::default())); + let pipeline = Arc::new(ToolPipeline::new( + Arc::new(TokioRwLock::new(ToolRegistry::new())), + Arc::new(ToolStateManager::new(events.clone())), + None, + )); + let engine = Arc::new(ExecutionEngine::new( + Arc::new(RoundExecutor::new( + Arc::new(StreamProcessor::new(events.clone())), + events.clone(), + pipeline.clone(), + )), + events.clone(), + manager.clone(), + Arc::new(ContextCompressor::new()), + ExecutionEngineConfig::default(), + )); + let coordinator = Arc::new(ConversationCoordinator::new( + manager.clone(), + engine, + pipeline, + events, + Arc::new(EventRouter::new()), + Arc::new( + crate::runtime_ownership::CoreRuntimeOwnership::embedded_with_facts( + workspace.path().join("ownership"), + "openbitfun".into(), + "test", + ), + ), + )); + let scheduler = DialogScheduler::new(coordinator.clone(), manager.clone()); + let tokens = Arc::new( + TokenUsageService::new_in_base_dir(workspace.path().join("tokens")) + .await + .unwrap(), + ); + let port = CoreSessionOperationsPort::new(coordinator, scheduler, tokens); + let config = AIConfig { + models: vec![AIModelConfig { + id: "btw-model".into(), + model_name: "btw-model".into(), + context_window: Some(256_000), + enabled: true, + ..Default::default() + }], + ..Default::default() + }; + TEST_MODEL_RESOLUTION_AI_CONFIG.scope(config, async { + let child = manager.create_session_with_id_and_details( + None, "BTW".into(), "Standard".into(), SessionConfig { + workspace_path: Some(workspace.path().to_string_lossy().into_owned()), + model_id: Some("btw-model".into()), ..Default::default() + }, Some("session-parent".into()), SessionKind::EphemeralChild, + ).await.unwrap(); + let id = &child.session_id; + manager.replace_context_messages(id, vec![Message::user("Inherited parent context".into())]).await; + let storage = manager.effective_session_storage_path(id).await.unwrap(); + let root = if persistence.is_resolved_sessions_dir(&storage) { storage.clone() } + else { persistence.path_manager().project_sessions_dir(&storage) }; + let child_dir = root.join(id); + let request = |include_contents| AgentSessionUsageRequest { + session_id: id.clone(), workspace_id: child.config.workspace_id.clone(), workspace_path: None, + remote_connection_id: None, remote_ssh_host: None, include_system_prompt_preview: false, + context_preview_category: None, include_hidden_subagents: false, + context_estimate: Some(UsageContextEstimateRequest { include_contents, context_only: true }), + }; + let before_first_turn = port.generate_session_usage(request(false)).await.unwrap(); + assert!(before_first_turn.context_estimate.unwrap().composition.unwrap().conversation > 0); + assert!(!child_dir.exists(), "inspection must not persist a BTW before its first question"); + + let turn_id = manager.start_dialog_turn(id, "Standard".into(), "BTW question".into(), + Some("btw-live-turn".into()), None, Some(serde_json::json!({"kind": "btw"})), + ).await.unwrap(); + let mut summary = Message::user("Compressed inherited conversation".into()); + summary.metadata.semantic_kind = Some(MessageSemanticKind::CompressionSummary); + manager.replace_context_messages(id, vec![summary, Message::user("Current BTW question".into())]).await; + let session_before = serde_json::to_value(manager.get_session(id).unwrap()).unwrap(); + let numeric = port.generate_session_usage(request(false)).await.unwrap().context_estimate.unwrap(); + let preview = port.generate_session_usage(request(true)).await.unwrap().context_estimate.unwrap(); + assert!(numeric.unavailable_reason.is_none()); + assert_eq!(numeric.composition, preview.composition); + assert!(numeric.contents.is_empty()); + let composition = numeric.composition.unwrap(); + assert_eq!(composition.context_window, Some(256_000)); + assert!(composition.system_prompt > 0 && composition.tool_definitions > 0); + assert!(composition.summarized_conversation > 0 && composition.conversation > 0); + assert!(preview.contents[&UsageContextCategory::Rules].contains("BTW workspace rules")); + assert!(!child_dir.exists(), "running BTW inspection must not create history or cache files"); + assert_eq!(session_before, serde_json::to_value(manager.get_session(id).unwrap()).unwrap()); + + // An unrelated disk record must neither block a live memory query nor be repaired. + std::fs::create_dir_all(&child_dir).unwrap(); + let poison = child_dir.join("session-revert.json"); + std::fs::write(&poison, b"unrelated durable recovery data").unwrap(); + let report = port.generate_session_usage(request(true)).await.unwrap(); + assert!(report.context_estimate.unwrap().composition.is_some()); + assert_eq!(std::fs::read(&poison).unwrap(), b"unrelated durable recovery data"); + assert_eq!(std::fs::read_dir(&child_dir).unwrap().count(), 1); + assert!(matches!(manager.get_session(id).unwrap().state, + crate::agentic::core::SessionState::Processing { current_turn_id, .. } if current_turn_id == turn_id)); + + let other = TestWorkspace::new(); + let other_record = crate::service::workspace::legacy_compat::register_local_fixture_blocking(other.path()); + let mut mismatched = request(true); + mismatched.workspace_id = Some(other_record.id); + assert!(port.generate_session_usage(mismatched).await.is_err(), "memory inspection must validate storage ownership"); + }).await; + } + #[tokio::test] async fn sdk_usage_provider_validates_ids_and_keeps_live_token_enrichment() { let workspace = TestWorkspace::new(); diff --git a/src/web-ui/src/flow_chat/components/ChatInput.tsx b/src/web-ui/src/flow_chat/components/ChatInput.tsx index a73440d855..4bf6a25752 100644 --- a/src/web-ui/src/flow_chat/components/ChatInput.tsx +++ b/src/web-ui/src/flow_chat/components/ChatInput.tsx @@ -6723,6 +6723,7 @@ export const ChatInput: React.FC = ({ anchorRef: composerRef, previewSession: { sessionId: effectiveTargetSessionId, + canvasSessionId: currentSessionId ?? effectiveTargetSessionId, workspaceId: effectiveTargetSession.workspaceId ?? effectiveTargetSession.config.workspaceId, }, loadContext: loadContextUsageOverview, diff --git a/src/web-ui/src/flow_chat/components/ChatInputWorkspaceStrip.test.tsx b/src/web-ui/src/flow_chat/components/ChatInputWorkspaceStrip.test.tsx index 32ce8ef9dd..4597b664a5 100644 --- a/src/web-ui/src/flow_chat/components/ChatInputWorkspaceStrip.test.tsx +++ b/src/web-ui/src/flow_chat/components/ChatInputWorkspaceStrip.test.tsx @@ -431,6 +431,27 @@ describe('ChatInputWorkspaceStrip git refresh behavior', () => { expect(container.querySelector('[data-openbitfun-part="runtime"]')).toBeNull(); }); + it('passes the child context and parent canvas through overview category actions', async () => { + const estimate = { capturedAt: 123, contents: { rules: 'Child rules' }, composition: { + systemPrompt: 100, toolDefinitions: 100, rules: 100, skills: 0, + mcpTools: 0, subagentDefinitions: 0, summarizedConversation: 0, + conversation: 100, contextWindow: 1000, + } }; + await act(async () => root.render( + estimate, + previewSession: { sessionId: 'child-session', canvasSessionId: 'parent-session', workspaceId: 'workspace-1' } }} />, + )); + await act(async () => container.querySelector('[data-openbitfun-part="usageAction"]')!.click()); + const rulePreview = document.querySelector('[data-testid="context-usage-popover"] dl [data-usage-category="rules"] button')!; + await act(async () => rulePreview.click()); + expect(mocks.openContextPreview).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ + sessionId: 'child-session', reportSessionId: 'child-session', canvasSessionId: 'parent-session', + workspaceId: 'workspace-1', category: 'rules', estimate, + })); + }); + it('opens the overview from the context ring, highlights categories and offers explicit preview and report actions', async () => { const onOpen = vi.fn(); const onCompact = vi.fn(); diff --git a/src/web-ui/src/flow_chat/components/ChatInputWorkspaceStrip.tsx b/src/web-ui/src/flow_chat/components/ChatInputWorkspaceStrip.tsx index 11d3962386..d845ce0c33 100644 --- a/src/web-ui/src/flow_chat/components/ChatInputWorkspaceStrip.tsx +++ b/src/web-ui/src/flow_chat/components/ChatInputWorkspaceStrip.tsx @@ -56,7 +56,7 @@ export interface ChatInputWorkspaceStripProps { maxTokens: number; sessionKey?: string; anchorRef?: React.RefObject; - previewSession?: { sessionId: string; workspaceId?: string }; + previewSession?: { sessionId: string; canvasSessionId?: string; workspaceId?: string }; loadContext?: () => Promise; compactDisabled?: boolean; onCompact?: () => void; diff --git a/src/web-ui/src/flow_chat/components/usage/ContextUsagePopover.tsx b/src/web-ui/src/flow_chat/components/usage/ContextUsagePopover.tsx index ac4d389dd3..eccec11bdf 100644 --- a/src/web-ui/src/flow_chat/components/usage/ContextUsagePopover.tsx +++ b/src/web-ui/src/flow_chat/components/usage/ContextUsagePopover.tsx @@ -31,7 +31,7 @@ export function ContextUsagePopover({ currentTokens: number; maxTokens: number; loadContext?: () => Promise; - previewSession?: { sessionId: string; workspaceId?: string }; + previewSession?: { sessionId: string; canvasSessionId?: string; workspaceId?: string }; compactDisabled?: boolean; onCompact?: () => void; onClose: () => void; diff --git a/src/web-ui/src/flow_chat/components/usage/useContextPreview.ts b/src/web-ui/src/flow_chat/components/usage/useContextPreview.ts index 332e1b416f..ed4de2a9ec 100644 --- a/src/web-ui/src/flow_chat/components/usage/useContextPreview.ts +++ b/src/web-ui/src/flow_chat/components/usage/useContextPreview.ts @@ -6,7 +6,7 @@ import { notificationService } from '@/shared/notification-system'; import { getActiveSurfaceScope, isSurfaceChangedError } from '@/infrastructure/peer-device/deviceSurface'; /** Both usage surfaces open the same session-owned, capability-checked preview. */ -export function useContextPreview(params: { sessionId?: string; reportSessionId?: string; workspaceId?: string; estimate?: UsageContextEstimate; onEstimate?: (estimate: UsageContextEstimate) => void }) { +export function useContextPreview(params: { sessionId?: string; reportSessionId?: string; canvasSessionId?: string; workspaceId?: string; estimate?: UsageContextEstimate; onEstimate?: (estimate: UsageContextEstimate) => void }) { const { t } = useI18n('flow-chat'); const [previewLoading, setPreviewLoading] = useState(null); const requestRef = useRef(null); @@ -14,7 +14,7 @@ export function useContextPreview(params: { sessionId?: string; reportSessionId? requestRef.current = null; setPreviewLoading(null); return () => { requestRef.current = null; }; - }, [params.sessionId, params.reportSessionId, params.workspaceId]); + }, [params.sessionId, params.reportSessionId, params.canvasSessionId, params.workspaceId]); const previewContext = async (category: UsageContextCategory) => { if (!params.sessionId || !params.reportSessionId || requestRef.current) return; @@ -26,6 +26,7 @@ export function useContextPreview(params: { sessionId?: string; reportSessionId? try { const result = await openSessionContextPreview({ sessionId: params.sessionId, reportSessionId: params.reportSessionId, workspaceId: params.workspaceId, + ...(params.canvasSessionId ? { canvasSessionId: params.canvasSessionId } : {}), title: `${t(`usage.context.categories.${category}`)}${category === 'toolDefinitions' ? '' : '.md'}`, category, estimate: params.estimate, onEstimate: estimate => { if (isCurrent()) params.onEstimate?.(estimate); }, emptyContent: t('usage.context.previewEmpty'), }); diff --git a/src/web-ui/src/flow_chat/services/openSessionContextPreview.test.ts b/src/web-ui/src/flow_chat/services/openSessionContextPreview.test.ts index 3f91e748ab..3dab19ef8e 100644 --- a/src/web-ui/src/flow_chat/services/openSessionContextPreview.test.ts +++ b/src/web-ui/src/flow_chat/services/openSessionContextPreview.test.ts @@ -1,3 +1,4 @@ +// @vitest-environment jsdom import { beforeEach, describe, expect, it, vi } from 'vitest'; import { activateSurface } from '@/infrastructure/peer-device/deviceSurface'; import { useAgentCanvasStore, switchAgentCanvasScope, forgetAgentCanvasSession } from '@/app/components/panels/content-canvas/stores/canvasStore'; @@ -18,6 +19,8 @@ describe('system prompt preview tabs', () => { useAgentCanvasStore.getState().closeAllTabs(); forgetAgentCanvasSession(params.sessionId); forgetAgentCanvasSession('another-session'); + forgetAgentCanvasSession('parent-session'); + forgetAgentCanvasSession('sibling-child'); switchAgentCanvasScope(params.sessionId); flowChatStore.setState(state => ({ ...state, sessions: new Map(), activeSessionId: params.sessionId })); apiMocks.getSessionUsageReport.mockReset().mockResolvedValue(response()); @@ -53,6 +56,72 @@ describe('system prompt preview tabs', () => { expect(tabs()).toHaveLength(1); }); + it.each(['local', 'peer-host', 'ssh-workspace'])('opens child category previews in the parent canvas on %s', async surface => { + activateSurface(surface === 'peer-host' ? surface : 'local'); + const workspaceId = surface === 'ssh-workspace' ? 'ssh-workspace-id' : params.workspaceId; + switchAgentCanvasScope('parent-session'); + flowChatStore.setState(state => ({ ...state, activeSessionId: 'parent-session', sessions: new Map([ + [params.sessionId, { sessionId: params.sessionId, sessionKind: 'subagent', parentSessionId: 'parent-session', + workspaceId, config: { workspaceId } } as Session], + ]) })); + const onExpand = vi.fn(); + window.addEventListener('expand-right-panel', onExpand); + try { + const categories = ['systemPrompt', 'toolDefinitions', 'rules', 'skills', 'mcpTools', 'subagentDefinitions'] as const; + const estimate = { capturedAt: 123, contents: Object.fromEntries(categories.map(category => [category, `Child ${category}`])) }; + for (const category of categories) { + await expect(openSessionContextPreview({ ...params, workspaceId, category, estimate, + canvasSessionId: 'parent-session' })).resolves.toBe('opened'); + const activeTabId = useAgentCanvasStore.getState().primaryGroup.activeTabId; + expect(tabs().find(tab => tab.id === activeTabId)?.content).toMatchObject({ + type: category === 'toolDefinitions' ? 'tool-definitions' : 'markdown-editor', + data: category === 'toolDefinitions' ? { content: `Child ${category}`, readOnly: true } + : { initialContent: `Child ${category}`, readOnly: true }, + metadata: { sessionId: params.sessionId, capturedAt: 123, resourceScope: { workspaceId } }, + }); + } + expect(useAgentCanvasStore.getState().scopeKey).toBe('parent-session'); + expect(tabs()).toHaveLength(categories.length); + expect(onExpand).toHaveBeenCalledTimes(categories.length); + expect(apiMocks.getSessionUsageReport).not.toHaveBeenCalled(); + + await openSessionContextPreview({ ...params, workspaceId, estimate, canvasSessionId: 'parent-session' }); + expect(tabs()).toHaveLength(categories.length); + await openSessionContextPreview({ ...params, sessionId: 'sibling-child', reportSessionId: 'sibling-child', + workspaceId, estimate, canvasSessionId: 'parent-session' }); + expect(tabs()).toHaveLength(categories.length + 1); + switchAgentCanvasScope(params.sessionId); + expect(tabs()).toHaveLength(0); + } finally { + window.removeEventListener('expand-right-panel', onExpand); + } + }); + + it('queries child content and retains its original parent canvas after a chat switch', async () => { + switchAgentCanvasScope('parent-session'); + let finish: (value: unknown) => void = () => {}; + apiMocks.getSessionUsageReport.mockReturnValue(new Promise(resolve => { finish = resolve; })); + const onExpand = vi.fn(); + window.addEventListener('expand-right-panel', onExpand); + try { + const pending = openSessionContextPreview({ ...params, canvasSessionId: 'parent-session' }); + expect(apiMocks.getSessionUsageReport).toHaveBeenCalledExactlyOnceWith({ + sessionId: params.sessionId, workspaceId: params.workspaceId, includeHiddenSubagents: false, + contextEstimate: { includeContents: true, contextOnly: true }, + }); + switchAgentCanvasScope('another-session'); + finish(response()); + await expect(pending).resolves.toBe('opened'); + expect(tabs()).toHaveLength(0); + expect(onExpand).not.toHaveBeenCalled(); + switchAgentCanvasScope('parent-session'); + expect(tabs()).toHaveLength(1); + expect(tabs()[0].content.metadata?.sessionId).toBe(params.sessionId); + } finally { + window.removeEventListener('expand-right-panel', onExpand); + } + }); + it.each(['rules', 'skills', 'mcpTools', 'subagentDefinitions'] as const)( 'opens the requested %s from a current-context inspection', async category => { apiMocks.getSessionUsageReport.mockResolvedValue({ sessionId: params.sessionId, @@ -105,10 +174,10 @@ describe('system prompt preview tabs', () => { expect(tabs()).toHaveLength(1); }); - it('discards responses from a previous device activation', async () => { + it.each([undefined, 'parent-session'])('discards responses from a previous device activation with canvas %s', async canvasSessionId => { let finish: (value: unknown) => void = () => {}; apiMocks.getSessionUsageReport.mockReturnValue(new Promise(resolve => { finish = resolve; })); - const pending = openSessionContextPreview(params); + const pending = openSessionContextPreview({ ...params, canvasSessionId }); activateSurface('peer-host'); finish(response()); await expect(pending).resolves.toBe('stale'); @@ -121,12 +190,12 @@ describe('system prompt preview tabs', () => { expect(tabs()).toHaveLength(0); }); - it('refuses dispatch projections and mismatched target sessions without querying local content', async () => { - await expect(openSessionContextPreview({ ...params, reportSessionId: 'target-session' })).resolves.toBe('unavailable'); + it.each([undefined, 'parent-session'])('refuses dispatch projections and mismatched target sessions with canvas %s', async canvasSessionId => { + await expect(openSessionContextPreview({ ...params, canvasSessionId, reportSessionId: 'target-session' })).resolves.toBe('unavailable'); flowChatStore.setState(state => ({ ...state, sessions: new Map([[params.sessionId, { sessionId: params.sessionId, config: { dispatchJobId: 'job-1' }, } as Session]]) })); - await expect(openSessionContextPreview(params)).resolves.toBe('unavailable'); + await expect(openSessionContextPreview({ ...params, canvasSessionId })).resolves.toBe('unavailable'); expect(apiMocks.getSessionUsageReport).not.toHaveBeenCalled(); }); diff --git a/src/web-ui/src/flow_chat/services/openSessionContextPreview.ts b/src/web-ui/src/flow_chat/services/openSessionContextPreview.ts index 0ccd040df4..74682e9bc6 100644 --- a/src/web-ui/src/flow_chat/services/openSessionContextPreview.ts +++ b/src/web-ui/src/flow_chat/services/openSessionContextPreview.ts @@ -17,6 +17,8 @@ const PREVIEW_FILE_NAMES: Record = { export async function openSessionContextPreview(params: { sessionId: string; reportSessionId: string; + /** The visible conversation owns the canvas when inspecting an input-target child. */ + canvasSessionId?: string; workspaceId?: string; title: string; category: UsageContextCategory; @@ -26,6 +28,7 @@ export async function openSessionContextPreview(params: { onEstimate?: (estimate: UsageContextEstimate) => void; }): Promise<'opened' | 'unavailable' | 'stale'> { const surface = getActiveSurfaceScope(); + const canvasSessionId = params.canvasSessionId ?? params.sessionId; const session = flowChatStore.getState().sessions.get(params.sessionId); const workspaceId = params.workspaceId || session?.workspaceId || session?.config?.workspaceId; // Dispatch reports belong to the target. Never read the controller's prompt cache. @@ -52,7 +55,7 @@ export async function openSessionContextPreview(params: { const content = estimate?.contents?.[params.category]; if (typeof content !== 'string') return 'unavailable'; - openAgentCanvasTabForSession(params.sessionId, { + openAgentCanvasTabForSession(canvasSessionId, { type: params.category === 'toolDefinitions' ? 'tool-definitions' : 'markdown-editor', title: params.title, data: params.category === 'toolDefinitions' ? { content, readOnly: true } @@ -65,7 +68,7 @@ export async function openSessionContextPreview(params: { resourceScope: { surfaceId: surface.surfaceId, workspaceId }, }, }); - if (useAgentCanvasStore.getState().scopeKey === params.sessionId && typeof window !== 'undefined') { + if (useAgentCanvasStore.getState().scopeKey === canvasSessionId && typeof window !== 'undefined') { window.dispatchEvent(new window.CustomEvent('expand-right-panel')); } return 'opened';