diff --git a/crates/agent_runtime/src/lib.rs b/crates/agent_runtime/src/lib.rs index a4cb81308..1715e34dd 100644 --- a/crates/agent_runtime/src/lib.rs +++ b/crates/agent_runtime/src/lib.rs @@ -40,10 +40,10 @@ pub use resource::{ pub use resource_scope::{AgentResourceScope, DefaultTarget, DefaultTargetReason, ResourceCatalog}; pub use risk::RiskLevel; pub use runtime::{ - DEFAULT_AGENT_MAX_ITERATIONS, MAX_AGENT_MAX_ITERATIONS, MIN_AGENT_MAX_ITERATIONS, AcpSessionRef, - PendingToolCallSummary, Runtime, RuntimeCommand, RuntimeEvent, RuntimeEventReceiver, - RuntimeServices, Session, SessionSnapshot, TaskKind, TaskOutcome, ToolExecutionMode, - TurnContext, UserInput, + AcpSessionRef, DEFAULT_AGENT_MAX_ITERATIONS, MAX_AGENT_MAX_ITERATIONS, + MIN_AGENT_MAX_ITERATIONS, PendingToolCallSummary, Runtime, RuntimeCommand, RuntimeEvent, + RuntimeEventReceiver, RuntimeServices, Session, SessionHost, SessionSnapshot, TaskKind, + TaskOutcome, ToolExecutionMode, TurnContext, UserInput, }; pub use runtime::{InputImage, TurnInput}; pub use skill::{ diff --git a/crates/agent_runtime/src/runtime/mod.rs b/crates/agent_runtime/src/runtime/mod.rs index b5dd63395..c1f83ee11 100644 --- a/crates/agent_runtime/src/runtime/mod.rs +++ b/crates/agent_runtime/src/runtime/mod.rs @@ -18,7 +18,7 @@ pub use command::RuntimeCommand; pub use event::{RuntimeEvent, RuntimeEventReceiver, RuntimeEventSender}; pub use input_queue::{InputImage, InputQueue, TurnInput, UserInput}; pub use session::Session; -pub use session::{AcpSessionRef, SessionSnapshot}; +pub use session::{AcpSessionRef, SessionHost, SessionSnapshot}; pub use session_manager::SessionManager; pub use session_state::SessionState; pub use task::{ diff --git a/crates/agent_runtime/src/runtime/session.rs b/crates/agent_runtime/src/runtime/session.rs index e037bbb59..3438473fb 100644 --- a/crates/agent_runtime/src/runtime/session.rs +++ b/crates/agent_runtime/src/runtime/session.rs @@ -7,7 +7,7 @@ use crate::history::{HistoryItem, RuntimeHistory}; use crate::ids::{SessionId, SubAgentId, TurnId}; use crate::planner::{Plan, StepStatus}; -use crate::resource::ResourceContext; +use crate::resource::{ResourceContext, ResourceKind}; use crate::runtime::active_turn::ActiveTurn; use crate::runtime::event::{RuntimeEvent, RuntimeEventSender}; use crate::runtime::input_queue::{InputQueue, TurnInput, UserInput}; @@ -35,6 +35,27 @@ pub struct AcpSessionRef { pub session_id: String, } +/// 会话首次落盘时定格的 SSH 主机归属。 +/// +/// 只保存稳定 ID 和当时的显示名;实时执行资源仍由 `ResourceContext` 管理, +/// 切换当前连接不会改写历史归属。 +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SessionHost { + pub id: String, + pub name: String, +} + +impl SessionHost { + /// 当前 SSH 主机优先;没有当前项时,仅在 SSH 候选唯一时关联,避免猜测。 + pub fn from_resources(resources: &ResourceContext) -> Option { + let resource = resources.default_target_of_kind(&ResourceKind::Ssh)?; + Some(Self { + id: resource.id.as_str().to_owned(), + name: resource.label.clone(), + }) + } +} + /// 会话的可持久化快照:足以重建一个 [`Session`] 全部对话状态的最小集合。 /// /// 只包含可序列化的对话事实(标识、资源、历史、当前计划),**不含**运行时瞬态 @@ -59,6 +80,9 @@ pub struct SessionSnapshot { /// 旧快照没有该字段,反序列化为 `None`(侧栏归入「未分组」)。 #[serde(default)] pub workspace_root: Option, + /// 会话首次落盘时关联的 SSH 主机;旧快照保持未关联。 + #[serde(default)] + pub host: Option, /// 用户在输入框里**尚未发送**的文字(会话草稿)。 /// /// 切换会话时由视图捕获/恢复;随快照落盘,重启后回到对应会话仍能看到。 @@ -157,9 +181,9 @@ impl Session { history, plan, system_instruction, - // 会话归属由持久化层在落盘时按「首存定格」规则补写,见 - // ai_chat_view::persistence::save_session_with_workspace。 + // 工作区与主机归属由外壳持久化层在落盘时按「首存定格」规则补写。 workspace_root: None, + host: None, draft: self.draft(), context_tokens: self.context_tokens(), acp: self.acp_ref(), @@ -744,6 +768,43 @@ mod tests { assert_eq!(restored.draft().as_deref(), Some("未发送的文字")); } + #[test] + fn host_association_prefers_current_ssh_and_rejects_ambiguity() { + let first = crate::resource::ResourceRef::new( + "host-1", + crate::resource::ResourceKind::Ssh, + "生产一机", + ); + let second = crate::resource::ResourceRef::new( + "host-2", + crate::resource::ResourceKind::Ssh, + "生产二机", + ); + let resources = ResourceContext::new() + .with_resource(first) + .with_resource(second.clone()); + let host = SessionHost::from_resources(&resources).expect("当前 SSH 主机"); + assert_eq!("host-1", host.id); + assert_eq!("生产一机", host.name); + + let mut resources = resources; + resources.current = Some(second.id); + assert_eq!( + Some("host-2".to_owned()), + SessionHost::from_resources(&resources).map(|host| host.id) + ); + + resources.current = None; + assert!(SessionHost::from_resources(&resources).is_none()); + } + + #[test] + fn legacy_snapshot_without_host_field_deserializes_to_none() { + let json = r#"{"id":"sess_x","history":[]}"#; + let parsed: SessionSnapshot = serde_json::from_str(json).expect("旧快照应可反序列化"); + assert_eq!(parsed.host, None); + } + #[test] fn legacy_snapshot_without_draft_field_deserializes_to_none() { let json = r#"{"id":"sess_x","history":[]}"#; diff --git a/crates/ai_chat_view/src/agent_view.rs b/crates/ai_chat_view/src/agent_view.rs index 9ad7ad007..e2e3415a9 100644 --- a/crates/ai_chat_view/src/agent_view.rs +++ b/crates/ai_chat_view/src/agent_view.rs @@ -18,8 +18,8 @@ use agent_client_protocol::schema::v1::{ }; use agent_runtime::{ AgentResourceScope, HistoryItem, ResourceCatalog, ResourceContext, ResourceId, ResourceKind, - ResourceRef, Runtime, RuntimeEvent, RuntimeEventReceiver, SessionId, TaskKind, ToolCallId, - ToolExecutionMode, ToolRegistry, TurnId, UserInput, + ResourceRef, Runtime, RuntimeEvent, RuntimeEventReceiver, SessionHost, SessionId, TaskKind, + ToolCallId, ToolExecutionMode, ToolRegistry, TurnId, UserInput, }; use gpui::prelude::FluentBuilder; use gpui::{ @@ -1373,6 +1373,13 @@ pub struct AgentChatView { sessions: Vec, /// 会话 id → 归属工作区。创建/载入时定格,落盘时随快照写出。 session_roots: HashMap, + /// 会话 id → 首次落盘时的 SSH 主机归属。 + /// + /// 键存在表示这是新建或已明确登记归属的会话;`None` 表示新会话暂时没有 + /// 唯一主机,可在首次落盘时补定。旧快照没有 host 时不登记键,避免误挂当前主机。 + session_hosts: HashMap>, + /// 新会话首次真正落盘后,主机(包括「无明确主机」)都不再变化。 + finalized_session_hosts: HashSet, /// 尚未完全由持久化历史覆盖的实时会话摘要(当前会话和后台运行会话)。 live_sessions: Vec, /// 非当前会话的实时转录,切换回来时可继续看到流式进度。 @@ -1484,13 +1491,6 @@ pub struct AgentChatView { drafted_sessions: HashSet, /// 排队中的草稿防抖保存;再输入一次会把它顶掉重排(旧任务随 drop 取消)。 draft_save_task: Option>, - /// 业务资源那一批 `@` 提及项(连接、SSH 主机…)。 - /// - /// 工作区文件是**后到**的(目录遍历在后台跑),所以这一批要留一份: - /// 换根重新收集时要跟文件那份重新合并,而不是把业务资源丢在路上。 - resource_mentions: Vec, - /// 后台的工作区文件遍历任务;换根会把它顶掉(旧任务随 drop 取消)。 - workspace_mentions_task: Option>, /// 侧边栏是否显示「已归档」会话(否则显示活跃会话)。 show_archived: bool, /// 侧边栏视图(窄面板)模式:头部走新建对话 / 历史记录紧凑布局,不常驻会话列表。 @@ -1836,11 +1836,15 @@ impl AgentChatView { transcript.set_resource_context(&resources); // 活跃列表立即展示当前实时会话;持久化历史和后台任务随后统一合并。 - let live_sessions = vec![SessionSummary::new( - current_session.clone(), - current_agent_task_title(), - now_secs(), - )]; + let initial_host = SessionHost::from_resources(&resources); + let live_sessions = vec![ + SessionSummary::new( + current_session.clone(), + current_agent_task_title(), + now_secs(), + ) + .with_host(initial_host.clone()), + ]; let running_sessions = HashSet::new(); let sessions = merge_live_session_summaries( persistence::list_summaries(cx), @@ -1857,8 +1861,10 @@ impl AgentChatView { current_session.clone(), workspace_root.to_string_lossy().into_owned(), )]); + // 实时列表先显示当前主机,但空白会话直到首次落盘才定格归属。 + let initial_session_hosts = HashMap::from([(current_session.clone(), None)]); - let mut new_view = Self { + let new_view = Self { runtime, session_id, resources, @@ -1914,8 +1920,6 @@ impl AgentChatView { // 启动时从库里取一次:上次没发出去的草稿要在列表上标出来。 drafted_sessions: persistence::drafted_session_uids(cx), draft_save_task: None, - resource_mentions: base_mentions.clone(), - workspace_mentions_task: None, show_archived: false, sidebar_mode, show_sidebar_header, @@ -1964,6 +1968,8 @@ impl AgentChatView { reasoning_effort_override: None, is_running: false, session_roots: initial_session_roots, + session_hosts: initial_session_hosts, + finalized_session_hosts: HashSet::new(), system_instruction: seed_system_instruction, system_instruction_from_settings, theme, @@ -1978,8 +1984,6 @@ impl AgentChatView { if new_view.system_instruction.is_some() { new_view.apply_system_instruction_to_current_session(); } - // `@` 里的工作区文件:起手收集一次(后台跑,见方法说明)。 - new_view.refresh_workspace_mentions(cx); new_view } @@ -2738,6 +2742,10 @@ impl AgentChatView { .as_deref() .and_then(crate::command_palette::workspace_label) }), + search_terms: session + .host + .as_ref() + .map_or_else(Vec::new, |host| vec![host.name.clone(), host.id.clone()]), }) .collect(); @@ -5056,8 +5064,6 @@ impl AgentChatView { self.workspace_root = root.clone(); // 项目级 skills 跟随工作区;选择集合只保留仍然存在的路径。 self.skills.reload_for_workspace(&root); - // `@` 里的文件也要换:引用的是**当前**工作区里的东西。 - self.refresh_workspace_mentions(cx); self.sync_session_skills(); // 换工作区会丢弃旧连接;连接前的模型选择也不再适用于新 agent 会话。 self.pending_acp_model = None; @@ -5951,6 +5957,7 @@ impl AgentChatView { self.session_id.to_string(), self.workspace_root.to_string_lossy().into_owned(), ); + self.session_hosts.insert(self.session_id.to_string(), None); if self.system_instruction_from_settings { // 新会话跟随设置的最新值(含清空);外部显式指令保持不变。 self.system_instruction = AppSettings::current(cx) @@ -6058,6 +6065,10 @@ impl AgentChatView { let Some(session) = self.runtime.session(&session_id) else { return; }; + if session.history_snapshot().items().is_empty() { + self.record_local_usage_sample(uid, &session, cx); + return; + } // 归属定格:优先创建/载入时记录的工作区;缺失(旧数据在本次升级后 // 首次落盘)才用当前工作区补。 let workspace_root = self @@ -6065,9 +6076,21 @@ impl AgentChatView { .get(uid) .cloned() .unwrap_or_else(|| self.workspace_root.to_string_lossy().into_owned()); - if let Some((title, updated_at)) = - persistence::save_session_with_workspace(cx, &session, Some(&workspace_root)) - { + let host = self.session_hosts.get(uid).cloned().flatten().or_else(|| { + (self.session_hosts.contains_key(uid) && !self.finalized_session_hosts.contains(uid)) + .then(|| SessionHost::from_resources(&self.resources)) + .flatten() + }); + if let Some((title, updated_at)) = persistence::save_session_with_context( + cx, + &session, + Some(&workspace_root), + host.clone(), + ) { + if self.session_hosts.contains_key(uid) { + self.session_hosts.insert(uid.to_string(), host); + self.finalized_session_hosts.insert(uid.to_string()); + } self.upsert_live_summary(uid.to_string(), title, updated_at); } self.record_local_usage_sample(uid, &session, cx); @@ -6098,12 +6121,31 @@ impl AgentChatView { persistence::record_usage_sample(cx, uid, used, window, model.as_deref()); } + /// 新会话首次落盘时可补定唯一 SSH 主机;旧会话没有登记就不从当前资源推断。 + pub(super) fn session_host_for_save(&mut self, uid: &str) -> Option { + let registered = self.session_hosts.get(uid)?.clone(); + if self.finalized_session_hosts.contains(uid) { + return registered; + } + let host = SessionHost::from_resources(&self.resources); + self.session_hosts.insert(uid.to_string(), host.clone()); + self.finalized_session_hosts.insert(uid.to_string()); + host + } + fn upsert_live_summary(&mut self, uid: String, title: String, updated_at: i64) { self.live_sessions.retain(|summary| summary.id != uid); let workspace_root = self.session_roots.get(&uid).cloned(); + let host = self.session_hosts.get(&uid).cloned().flatten().or_else(|| { + (self.session_hosts.contains_key(&uid) && !self.finalized_session_hosts.contains(&uid)) + .then(|| SessionHost::from_resources(&self.resources)) + .flatten() + }); self.live_sessions.insert( 0, - SessionSummary::new(uid, title, updated_at).with_workspace_root(workspace_root), + SessionSummary::new(uid, title, updated_at) + .with_workspace_root(workspace_root) + .with_host(host), ); } @@ -6649,6 +6691,10 @@ impl AgentChatView { if let Some(root) = snapshot.workspace_root.clone() { self.session_roots.insert(uid.to_string(), root); } + if let Some(host) = snapshot.host.clone() { + self.session_hosts.insert(uid.to_string(), Some(host)); + self.finalized_session_hosts.insert(uid.to_string()); + } let restored = self.runtime.restore_session(snapshot); restored.set_resources(self.resources.clone()); restored @@ -7003,9 +7049,9 @@ impl AgentChatView { self.skills.items(), self.local_context_tokens(), ); - // 业务资源换了:留一份给工作区文件重新合并用(文件那份不用重扫,根没动)。 - self.resource_mentions = mentions; - self.refresh_workspace_mentions(cx); + // `@` 只列连接资源;工作区文件走附件选择器,不混入连接补全。 + self.input + .update(cx, |input, cx| input.set_mentions(mentions, cx)); // 同 `sync_resource_targets`:目标选择器只喂 One agent 那份,上下文按后端送。 self.input.update(cx, |input, cx| { input.set_target_options(target_options, cx); @@ -7019,28 +7065,6 @@ impl AgentChatView { cx.notify(); } - /// 重新收集 `@` 里的工作区文件,并与业务资源合并推给输入框。 - /// - /// 目录遍历放后台:工作区可能有几万个文件,把它压在首帧或换根那一帧里, - /// 用户会看到面板卡一下再出现。代价是补全菜单里文件**稍后**才出现—— - /// 键入 `@` 花的几百毫秒通常足够遍历跑完。 - pub(crate) fn refresh_workspace_mentions(&mut self, cx: &mut Context) { - let root = self.workspace_root.clone(); - let base = self.resource_mentions.clone(); - let input = self.input.clone(); - self.workspace_mentions_task = Some(cx.spawn(async move |_this, cx| { - let files = cx - .background_executor() - .spawn( - async move { crate::workspace_files::collect_workspace_files_default(&root) }, - ) - .await; - let mut all = base; - all.extend(files); - input.update(cx, |input, cx| input.set_mentions(all, cx)); - })); - } - /// 注册代码块操作。 pub fn register_code_block_action(&mut self, action: CodeBlockAction, _cx: &mut Context) { self.code_block_actions.register(action); @@ -13612,6 +13636,7 @@ mod tests { system_instruction: None, skills: agent_runtime::SkillContext::new(), workspace_root: None, + host: None, draft: None, context_tokens: None, acp: None, @@ -13674,6 +13699,61 @@ mod tests { }); } + #[gpui::test] + fn reused_blank_session_freezes_the_current_host_on_first_save(cx: &mut TestAppContext) { + use agent_runtime::{ResourceId, ResourceKind, ResourceRef}; + + init_test_ui(cx); + let resources = ResourceContext { + current: Some(ResourceId::new("ssh-a")), + resources: vec![ResourceRef::new( + ResourceId::new("ssh-a"), + ResourceKind::Ssh, + "主机 A", + )], + }; + let config = AgentChatViewConfig::new(test_runtime("m"), resources, Vec::new()); + let (view, cx) = + cx.add_window_view(move |window, cx| AgentChatView::new(config, window, cx)); + + view.update_in(cx, |view, window, cx| { + let first = view.current_session.clone(); + view.runtime + .session(&SessionId::from_string(first.clone())) + .expect("first session is live") + .record_user_input("已有会话"); + + view.new_session(cx); + let blank = view.current_session.clone(); + view.apply_pending_input_draft(window, cx); + view.switch_session(&first, cx); + assert_eq!(Some(blank.clone()), view.draft_session); + + view.resources = ResourceContext { + current: Some(ResourceId::new("ssh-b")), + resources: vec![ResourceRef::new( + ResourceId::new("ssh-b"), + ResourceKind::Ssh, + "主机 B", + )], + }; + view.new_session(cx); + assert_eq!(blank, view.current_session); + view.runtime + .session(&SessionId::from_string(blank.clone())) + .expect("reused session is live") + .record_user_input("在主机 B 上的首条消息"); + + assert_eq!( + Some("ssh-b"), + view.session_host_for_save(&blank) + .map(|host| host.id) + .as_deref(), + "白纸在主机 B 下复用时,首条消息不能仍记到创建时的主机 A" + ); + }); + } + /// 记下的白纸一旦真有了历史,就不能再被当白纸复用——否则「新建会话」 /// 会把用户送进一段他以为已经清空的对话。 #[gpui::test] @@ -13852,6 +13932,7 @@ mod tests { system_instruction: None, skills: agent_runtime::SkillContext::new(), workspace_root: None, + host: None, draft: None, context_tokens: None, acp: Some(agent_runtime::AcpSessionRef { @@ -17091,6 +17172,32 @@ mod tests { ); } + #[test] + fn live_summaries_never_change_persisted_host_association() { + let original = agent_runtime::SessionHost { + id: "ssh-1".into(), + name: "原主机".into(), + }; + let current = agent_runtime::SessionHost { + id: "ssh-2".into(), + name: "当前主机".into(), + }; + let persisted = vec![ + SessionSummary::new("selected", "选中任务", 10).with_host(Some(original.clone())), + SessionSummary::new("legacy", "旧任务", 9), + ]; + let live = vec![ + SessionSummary::new("selected", "选中任务", 11).with_host(Some(current.clone())), + SessionSummary::new("legacy", "旧任务", 10).with_host(Some(current)), + ]; + + let merged = + merge_live_session_summaries(persisted, &live, "selected", &HashSet::new(), false); + + assert_eq!(Some(original), merged[0].host, "已有关联合理应保持原主机"); + assert_eq!(None, merged[1].host, "旧会话不能实时挂到当前主机"); + } + #[test] fn archived_sidebar_does_not_mix_in_live_workbench_tasks() { let archived = vec![SessionSummary::new("archived", "归档任务", 10)]; @@ -17112,6 +17219,36 @@ mod tests { assert!(!should_stop_task_before_session_switch(Backend::Acp)); } + #[gpui::test] + fn command_palette_matches_history_host_name_and_id(cx: &mut TestAppContext) { + init_test_ui(cx); + let config = + AgentChatViewConfig::new(test_runtime("m"), ResourceContext::new(), Vec::new()); + let (view, cx) = + cx.add_window_view(move |window, cx| AgentChatView::new(config, window, cx)); + + view.update(cx, |view, _cx| { + view.sessions.push( + SessionSummary::new("host-history", "数据库巡检", 1).with_host(Some(SessionHost { + id: "ssh-42".into(), + name: "生产 API 主机".into(), + })), + ); + for query in ["API 主机", "SSH-42"] { + let items = view.palette_items(); + assert!( + crate::command_palette::visible_items(&items, query) + .iter() + .any(|item| item.action + == crate::command_palette::PaletteAction::OpenSession( + "host-history".into() + )), + "命令面板应能按 {query} 找到历史任务" + ); + } + }); + } + /// 启动时那张初始会话也要记住自己的工作区。 /// /// `session_roots` 是侧栏归属在内存里的依据。漏了这条会话,它第一次落盘 @@ -17135,6 +17272,103 @@ mod tests { }); } + #[gpui::test] + fn initial_session_freezes_host_on_first_save_and_legacy_sessions_stay_unassigned( + cx: &mut TestAppContext, + ) { + use agent_runtime::{ResourceId, ResourceKind, ResourceRef}; + + init_test_ui(cx); + let resources = ResourceContext { + current: Some(ResourceId::new("ssh-1")), + resources: vec![ResourceRef::new( + ResourceId::new("ssh-1"), + ResourceKind::Ssh, + "原主机", + )], + }; + let config = AgentChatViewConfig::new(test_runtime("m"), resources, vec![]); + let (view, cx) = + cx.add_window_view(move |window, cx| AgentChatView::new(config, window, cx)); + + view.update_in(cx, |view, _window, _cx| { + let uid = view.current_session.clone(); + assert_eq!( + Some("原主机"), + view.sessions[0] + .host + .as_ref() + .map(|host| host.name.as_str()), + "初始会话在首次落盘前也应显示主机归属" + ); + view.resources = ResourceContext { + current: Some(ResourceId::new("ssh-2")), + resources: vec![ResourceRef::new( + ResourceId::new("ssh-2"), + ResourceKind::Ssh, + "当前另一台主机", + )], + }; + assert_eq!( + Some("ssh-2"), + view.session_host_for_save(&uid) + .map(|host| host.id) + .as_deref(), + "空白会话在首次落盘时应定格当时的主机" + ); + view.resources = ResourceContext { + current: Some(ResourceId::new("ssh-1")), + resources: vec![ResourceRef::new( + ResourceId::new("ssh-1"), + ResourceKind::Ssh, + "原主机", + )], + }; + assert_eq!( + Some("ssh-2"), + view.session_host_for_save(&uid) + .map(|host| host.id) + .as_deref(), + "首次落盘后,当前连接变化不得改写已定格归属" + ); + assert_eq!( + None, + view.session_host_for_save("legacy-without-host"), + "没有登记主机的旧会话不能从当前资源补归属" + ); + }); + } + + #[gpui::test] + fn unassigned_new_session_does_not_gain_a_host_after_first_save(cx: &mut TestAppContext) { + use agent_runtime::{ResourceId, ResourceKind, ResourceRef}; + + init_test_ui(cx); + let config = + AgentChatViewConfig::new(test_runtime("m"), ResourceContext::new(), Vec::new()); + let (view, cx) = + cx.add_window_view(move |window, cx| AgentChatView::new(config, window, cx)); + + view.update(cx, |view, _cx| { + let uid = view.current_session.clone(); + assert_eq!(None, view.session_host_for_save(&uid)); + + view.resources = ResourceContext { + current: Some(ResourceId::new("ssh-late")), + resources: vec![ResourceRef::new( + ResourceId::new("ssh-late"), + ResourceKind::Ssh, + "后来选择的主机", + )], + }; + assert_eq!( + None, + view.session_host_for_save(&uid), + "首次落盘没有明确主机时,也不能在后续保存中误挂到另一台主机" + ); + }); + } + /// 一条只带会话内容的存储后端;用来造「快照里没有工作区归属」的旧会话。 fn test_session_storage() -> one_core::storage::StorageManager { use one_core::llm::chat_history::{ @@ -17222,7 +17456,7 @@ mod tests { ); } - /// `@` 菜单里除了业务资源还要有工作区文件,且遍历在后台跑完才并进来。 + /// `@` 只列连接资源;工作区文件走附件,不应混进连接补全列表。 #[gpui::test] fn gpui_workspace_files_join_the_mention_menu(cx: &mut TestAppContext) { init_test_ui(cx); @@ -17256,8 +17490,8 @@ mod tests { let labels = view.read_with(cx, |view, cx| view.input.read(cx).mention_labels()); assert!( - labels.iter().any(|label| label == "src/main.rs"), - "工作区文件该出现在 `@` 菜单里,实际 {labels:?}" + !labels.iter().any(|label| label == "src/main.rs"), + "工作区文件不应出现在 `@` 连接菜单里,实际 {labels:?}" ); assert!( labels.iter().any(|label| label == "prod-db"), @@ -17297,6 +17531,7 @@ mod tests { system_instruction: None, skills: agent_runtime::SkillContext::new(), workspace_root: None, + host: None, draft: None, context_tokens: None, acp: None, @@ -17486,7 +17721,9 @@ mod tests { /// 就改写它,用户看到的就是「无分组的自己跑到分组下面去了」。 #[gpui::test] fn opening_a_legacy_session_without_a_workspace_does_not_assign_one(cx: &mut TestAppContext) { - use agent_runtime::{HistoryItem, SessionId, SessionSnapshot}; + use agent_runtime::{ + HistoryItem, ResourceId, ResourceKind, ResourceRef, SessionId, SessionSnapshot, + }; use one_core::llm::chat_history::AgentSessionRepository; use one_core::storage::GlobalStorageState; @@ -17507,6 +17744,7 @@ mod tests { system_instruction: None, skills: agent_runtime::SkillContext::new(), workspace_root: None, + host: None, draft: None, context_tokens: None, acp: None, @@ -17521,7 +17759,15 @@ mod tests { .expect("写入一条无归属旧会话"); cx.update(|cx| cx.set_global(GlobalStorageState { storage })); - let config = AgentChatViewConfig::new(test_runtime("m"), ResourceContext::new(), vec![]) + let resources = ResourceContext { + current: Some(ResourceId::new("ssh-current")), + resources: vec![ResourceRef::new( + ResourceId::new("ssh-current"), + ResourceKind::Ssh, + "当前主机", + )], + }; + let config = AgentChatViewConfig::new(test_runtime("m"), resources, vec![]) .with_workspace_root(std::path::PathBuf::from("/tmp/navop-test-ws-a")); let (view, cx) = cx.add_window_view(move |window, cx| AgentChatView::new(config, window, cx)); @@ -17538,6 +17784,18 @@ mod tests { view.session_roots.get(legacy_uid).map(String::as_str), "点开旧会话只是看一眼,不该凭空给它定一个工作区归属" ); + assert_eq!( + None, + view.session_host_for_save(legacy_uid), + "旧会话也不能因为当前选中了 SSH 就补一个主机归属" + ); + assert!( + crate::persistence::load_snapshot(cx, legacy_uid) + .expect("旧会话仍可读取") + .host + .is_none(), + "查看旧会话不得把当前主机写回快照" + ); }); } diff --git a/crates/ai_chat_view/src/agent_view/acp_sessions.rs b/crates/ai_chat_view/src/agent_view/acp_sessions.rs index df707d56b..fae56b373 100644 --- a/crates/ai_chat_view/src/agent_view/acp_sessions.rs +++ b/crates/ai_chat_view/src/agent_view/acp_sessions.rs @@ -110,6 +110,10 @@ impl AgentChatView { agent_id: agent_id.to_string(), session_id, }; + let had_meaningful_session = self.external_session_title(uid).is_some() + || self.acp_cached_transcripts.contains(uid) + || persistence::load_snapshot(cx, uid) + .is_some_and(|snapshot| !snapshot.history.is_empty() || snapshot.host.is_some()); // 运行时会话也记住这个地址:之后任何一次本地落盘都不会把它抹掉, // 切到这条会话时也能凭它知道「这段对话归外部 agent 管」。 let session_id = SessionId::from_string(uid.to_string()); @@ -145,11 +149,15 @@ impl AgentChatView { .unwrap_or_else(|| self.workspace_root.to_string_lossy().into_owned()); // 落盘与 live 摘要用同一份时间:被动落盘(点开看一眼)时取回的是库里 // 原有的时间,不会因为打开会话就把它顶到列表最前面;只有真有过动静才提。 - if let Some((saved_title, updated_at)) = persistence::save_acp_session( + let host = had_meaningful_session + .then(|| self.session_host_for_save(uid)) + .flatten(); + if let Some((saved_title, updated_at)) = persistence::save_acp_session_with_context( cx, uid, &title, Some(&workspace_root), + host, reference, mark_active, ) { diff --git a/crates/ai_chat_view/src/command_palette.rs b/crates/ai_chat_view/src/command_palette.rs index 1278c20cf..89a41d1b8 100644 --- a/crates/ai_chat_view/src/command_palette.rs +++ b/crates/ai_chat_view/src/command_palette.rs @@ -114,6 +114,8 @@ pub struct PaletteItem { /// 右侧补充说明:会话的来源 agent 或所在工作区目录名。 pub detail: Option, pub action: PaletteAction, + /// 仅供检索、不额外占用候选项展示空间的主机名等关键词。 + search_terms: Vec, } impl PaletteItem { @@ -122,6 +124,7 @@ impl PaletteItem { label, detail, action, + search_terms: Vec::new(), } } @@ -131,6 +134,7 @@ impl PaletteItem { label: title, detail: Some(snippet), action: PaletteAction::OpenSessionAtMatch { uid, query }, + search_terms: Vec::new(), } } } @@ -172,6 +176,8 @@ pub struct PaletteSession { pub title: String, /// 来源 agent 短标识或工作区目录名。 pub detail: Option, + /// 主机名、连接 id 等只参与检索的补充关键词。 + pub search_terms: Vec, } /// 固定命令项。 @@ -212,6 +218,7 @@ pub fn session_items(sessions: &[PaletteSession]) -> Vec { label: session.title.clone(), detail: session.detail.clone(), action: PaletteAction::OpenSession(session.uid.clone()), + search_terms: session.search_terms.clone(), }) .collect() } @@ -253,6 +260,10 @@ fn matches_query(item: &PaletteItem, query: &str) -> bool { .detail .as_deref() .is_some_and(|detail| detail.to_lowercase().contains(query)) + || item + .search_terms + .iter() + .any(|term| term.to_lowercase().contains(query)) } /// 上下移动高亮,两端绕回。 @@ -555,6 +566,20 @@ mod tests { assert_eq!(None, workspace_label(" ")); } + #[test] + fn session_items_match_hidden_host_name_and_id() { + let items = session_items(&[PaletteSession { + uid: "session-1".into(), + title: "数据库巡检".into(), + detail: None, + search_terms: vec!["生产 API 主机".into(), "ssh-42".into()], + }]); + + assert_eq!(1, visible_items(&items, "API 主机").len()); + assert_eq!(1, visible_items(&items, "SSH-42").len()); + assert!(visible_items(&items, "测试主机").is_empty()); + } + #[test] fn sessions_become_open_actions() { let items = session_items(&[ @@ -562,11 +587,13 @@ mod tests { uid: "s-1".into(), title: "预算审批".into(), detail: Some("codex".into()), + search_terms: Vec::new(), }, PaletteSession { uid: "s-2".into(), title: "发布说明".into(), detail: None, + search_terms: Vec::new(), }, ]); diff --git a/crates/ai_chat_view/src/persistence.rs b/crates/ai_chat_view/src/persistence.rs index 1af7381ff..7fd0289a1 100644 --- a/crates/ai_chat_view/src/persistence.rs +++ b/crates/ai_chat_view/src/persistence.rs @@ -8,7 +8,7 @@ //! DB 操作为同步、低频(每轮结束保存一次 / 切换会话时读取一次)、载荷小,直接在 //! 调用线程执行,沿用项目既有的同步 Repository 调用风格。 -use agent_runtime::{AcpSessionRef, HistoryItem, Session, SessionSnapshot}; +use agent_runtime::{AcpSessionRef, HistoryItem, Session, SessionHost, SessionSnapshot}; use one_core::{ llm::chat_history::{AgentSessionRepository, ChatMessage, MessageRepository}, storage::GlobalStorageState, @@ -28,10 +28,21 @@ const MAX_TITLE_CHARS: usize = 40; /// 否则写本次传入的当前工作区。之后无论外壳切到哪个工作区,该会话都留在 /// 首次落盘时的工作区(侧栏分组与底部新建对话下拉都以此为准)。 /// 不需要归属时传 `None`。 +#[cfg(test)] pub fn save_session_with_workspace( cx: &App, session: &Session, workspace_root: Option<&str>, +) -> Option<(String, i64)> { + save_session_with_context(cx, session, workspace_root, None) +} + +/// 带工作区与 SSH 主机归属定格的保存。 +pub fn save_session_with_context( + cx: &App, + session: &Session, + workspace_root: Option<&str>, + host: Option, ) -> Option<(String, i64)> { let mut snapshot = session.snapshot(); if snapshot.history.is_empty() { @@ -42,6 +53,11 @@ pub fn save_session_with_workspace( { snapshot.workspace_root = Some(root); } + if snapshot.host.is_none() { + snapshot.host = load_snapshot(cx, &snapshot.id.to_string()) + .and_then(|saved| saved.host) + .or(host); + } let title = derive_title(&snapshot); let snapshot_json = serde_json::to_string(&snapshot).ok()?; let repo = agent_session_repository(cx)?; @@ -133,7 +149,7 @@ fn agent_usage_repository(cx: &App) -> Option Option, acp: AcpSessionRef, mark_active: bool, +) -> Option<(String, i64)> { + save_acp_session_with_context(cx, uid, title, workspace_root, None, acp, mark_active) +} + +/// 保存 ACP 会话,并允许外壳首次写入固定的工作区与主机归属。 +pub fn save_acp_session_with_context( + cx: &App, + uid: &str, + title: &str, + workspace_root: Option<&str>, + host: Option, + acp: AcpSessionRef, + mark_active: bool, ) -> Option<(String, i64)> { let uid = uid.trim(); if uid.is_empty() || acp.agent_id.trim().is_empty() || acp.session_id.trim().is_empty() { @@ -164,6 +194,9 @@ pub fn save_acp_session( { snapshot.workspace_root = Some(root); } + if snapshot.host.is_none() { + snapshot.host = host; + } let title = match title.trim() { "" => derive_title(&snapshot), text => truncate_title(text), @@ -191,6 +224,7 @@ fn empty_snapshot(uid: &str) -> SessionSnapshot { system_instruction: None, skills: agent_runtime::SkillContext::new(), workspace_root: None, + host: None, draft: None, context_tokens: None, acp: None, @@ -252,7 +286,7 @@ fn message_repository(cx: &App) -> Option> { fn list_summaries_by_archived(cx: &App, archived: bool) -> Vec { // 只取摘要行:`snapshot_json` 本体(实测本机未归档 356 行合计 76.8MB、单条 - // 最大 19.2MB)不再进入进程内存,工作区归属与外部 agent 来源这两个来自快照的 + // 最大 19.2MB)不再进入进程内存,工作区、主机与外部 agent 来源这些快照摘要 // 字段由 SQL 层的 `json_extract` 直接给出。 // // 这里以前是把整列快照读上来、再逐行整体反序列化两次(一次取 workspace_root、 @@ -263,8 +297,13 @@ fn list_summaries_by_archived(cx: &App, archived: bool) -> Vec { .unwrap_or_default() .into_iter() .map(|row| { + let host = row.host_id.filter(|id| !id.trim().is_empty()).map(|id| { + let name = row.host_name.unwrap_or_else(|| id.clone()); + SessionHost { id, name } + }); SessionSummary::new(row.uid, row.title, row.updated_at) .with_workspace_root(snapshot_workspace_root(row.workspace_root)) + .with_host(host) .with_external_agent(external_agent_label(row.acp_agent_id)) }) .collect() @@ -392,6 +431,7 @@ mod tests { system_instruction: None, skills: agent_runtime::SkillContext::new(), workspace_root: None, + host: None, draft: None, context_tokens: None, acp: None, @@ -515,6 +555,7 @@ mod tests { system_instruction: None, skills: agent_runtime::SkillContext::new(), workspace_root: None, + host: None, draft: None, context_tokens: None, acp: None, @@ -522,6 +563,92 @@ mod tests { assert_eq!(derive_title(&snap), "新 Agent 会话"); } + #[gpui::test] + fn host_association_round_trips_and_appears_in_summaries(cx: &mut TestAppContext) { + cx.update(|cx| { + cx.set_global(GlobalStorageState { + storage: test_storage(), + }); + }); + let session = test_session(); + session.record_user_input("检查生产主机负载"); + let host = agent_runtime::SessionHost { + id: "ssh-42".into(), + name: "生产 API 主机".into(), + }; + + cx.update(|cx| save_session_with_context(cx, &session, None, Some(host.clone()))) + .expect("保存带主机的会话"); + cx.update(|cx| { + save_session_with_context( + cx, + &session, + None, + Some(agent_runtime::SessionHost { + id: "ssh-99".into(), + name: "另一台主机".into(), + }), + ) + }) + .expect("重复保存不得漂移主机归属"); + + let summaries = cx.update(|cx| list_summaries(cx)); + assert_eq!(Some(&host), summaries[0].host.as_ref()); + let snapshot = cx + .update(|cx| load_snapshot(cx, "sess_persist")) + .expect("读回快照"); + assert_eq!(Some(host), snapshot.host); + } + + #[gpui::test] + fn acp_host_association_round_trips_and_does_not_drift(cx: &mut TestAppContext) { + cx.update(|cx| { + cx.set_global(GlobalStorageState { + storage: test_storage(), + }); + }); + let host = agent_runtime::SessionHost { + id: "ssh-7".into(), + name: "生产 SSH".into(), + }; + cx.update(|cx| { + save_acp_session_with_context( + cx, + "sess_acp_host", + "检查生产服务", + None, + Some(host.clone()), + acp_ref("agent-1", "acp-1"), + true, + ) + }) + .expect("保存带主机的 ACP 会话"); + cx.update(|cx| { + save_acp_session_with_context( + cx, + "sess_acp_host", + "检查生产服务", + None, + Some(agent_runtime::SessionHost { + id: "ssh-8".into(), + name: "当前另一台主机".into(), + }), + acp_ref("agent-1", "acp-2"), + true, + ) + }) + .expect("再次保存 ACP 会话"); + + let snapshot = cx + .update(|cx| load_snapshot(cx, "sess_acp_host")) + .expect("读回 ACP 快照"); + assert_eq!(Some(host.clone()), snapshot.host); + assert_eq!( + Some(&host), + cx.update(|cx| list_summaries(cx))[0].host.as_ref() + ); + } + #[gpui::test] fn agent_session_persistence_round_trips_and_manages_lifecycle(cx: &mut TestAppContext) { cx.update(|cx| { diff --git a/crates/ai_chat_view/src/session_sidebar.rs b/crates/ai_chat_view/src/session_sidebar.rs index 5b1fb0d5e..c09c348ef 100644 --- a/crates/ai_chat_view/src/session_sidebar.rs +++ b/crates/ai_chat_view/src/session_sidebar.rs @@ -3,6 +3,7 @@ //! 与具体业务的会话存储完全解耦:调用方把自己的会话映射成 [`SessionSummary`] 即可。 //! 折叠 / 展开、点击交互等编排由上层视图(`ChatView`)负责,本模块只提供「长什么样」。 +use agent_runtime::SessionHost; use gpui::prelude::FluentBuilder; use gpui::{ App, Div, FontWeight, Hsla, InteractiveElement, ParentElement, SharedString, Styled, div, px, @@ -22,6 +23,8 @@ pub struct SessionSummary { pub updated_at: i64, /// 会话归属的工作区根目录。`None` 表示旧数据 / 未分组。 pub workspace_root: Option, + /// 首次落盘时关联的 SSH 主机;旧会话保持 `None`。 + pub host: Option, /// 会话由外部 agent(ACP)承载时的来源短标识(如 `codex`)。 /// /// `None` = 本地会话。行上标出来源,用户才知道点它会去连外部 agent, @@ -57,6 +60,7 @@ impl SessionSummary { name: name.into(), updated_at, workspace_root: None, + host: None, external_agent: None, } } @@ -67,6 +71,12 @@ impl SessionSummary { self } + /// 附加首次落盘时定格的 SSH 主机归属。 + pub fn with_host(mut self, host: Option) -> Self { + self.host = host; + self + } + /// 附加「外部 agent 承载」的来源标记(链式)。 pub fn with_external_agent(mut self, agent: Option) -> Self { self.external_agent = agent; @@ -136,23 +146,32 @@ pub fn session_row_with_style( .when(has_draft, |this| this.child(draft_dot(&session.id, cx))) .child( div() + .w_full() + .truncate() .text_xs() .text_color(if is_current { style.selected_foreground.opacity(0.72) } else { style.muted_foreground }) - .child(match session.external_agent.as_ref() { - Some(agent) => { - format!("{} · {}", agent, format_timestamp(session.updated_at)) - } - None => format_timestamp(session.updated_at), - }), + .child(session_metadata(session)), ), ), ) } +fn session_metadata(session: &SessionSummary) -> String { + let mut parts = Vec::new(); + if let Some(host) = &session.host { + parts.push(host.name.clone()); + } + if let Some(agent) = &session.external_agent { + parts.push(agent.to_string()); + } + parts.push(format_timestamp(session.updated_at)); + parts.join(" · ") +} + /// 当前 Unix 秒。 /// /// 抽出来是为了让分组逻辑可测——测试注入固定 `now`,不依赖真实时钟。 @@ -422,7 +441,7 @@ pub fn format_timestamp(timestamp: i64) -> String { relative_time_label(relative_time_unit(now_unix().saturating_sub(timestamp))) } -/// 按查询串过滤会话:对名称与 id 做大小写不敏感的子串匹配。 +/// 按查询串过滤会话:对名称、会话 id、主机名与主机 id 做大小写不敏感的子串匹配。 /// /// 空(或全空白)查询原样返回全部。 pub fn filter_sessions<'a>( @@ -438,6 +457,10 @@ pub fn filter_sessions<'a>( .filter(|summary| { summary.name.to_lowercase().contains(&query) || summary.id.to_lowercase().contains(&query) + || summary.host.as_ref().is_some_and(|host| { + host.name.to_lowercase().contains(&query) + || host.id.to_lowercase().contains(&query) + }) }) .collect() } @@ -558,6 +581,21 @@ mod group_tests { assert!(filter_sessions(&sessions, "nope").is_empty()); } + #[test] + fn filter_matches_host_name_and_id() { + let sessions = vec![ + SessionSummary::new("a", "检查负载", 100).with_host(Some(agent_runtime::SessionHost { + id: "ssh-42".into(), + name: "生产 API 主机".into(), + })), + SessionSummary::new("b", "本地整理", 200), + ]; + + assert_eq!(1, filter_sessions(&sessions, "API 主机").len()); + assert_eq!(1, filter_sessions(&sessions, "SSH-42").len()); + assert!(filter_sessions(&sessions, "测试主机").is_empty()); + } + #[test] fn workspace_groups_order_by_latest_and_put_ungrouped_last() { let sessions = vec![ diff --git a/crates/ai_chat_view/src/workbench/shell/nav.rs b/crates/ai_chat_view/src/workbench/shell/nav.rs index 5acacc4f6..14c42585f 100644 --- a/crates/ai_chat_view/src/workbench/shell/nav.rs +++ b/crates/ai_chat_view/src/workbench/shell/nav.rs @@ -488,8 +488,11 @@ impl WorkbenchShell { let element_id = SharedString::from(format!("workbench-session-{}", summary.id)); let archive_panel = panel.clone(); let archive_uid = id.clone(); - // 会话名过长会截断,完整名放 tooltip。 - let row_tooltip = summary.name.to_string(); + // 会话名和主机名过长会截断,完整信息放 tooltip。 + let row_tooltip = match summary.host.as_ref() { + Some(host) => format!("{} · {}", summary.name, host.name), + None => summary.name.to_string(), + }; // 有草稿的会话在名字后面点一个点:切走以后还能看出哪条剩着没发出去的东西。 // 先算成元素再挂上去——`.when` 里现读 `cx` 会和行上其它闭包抢同一个可变借用。 let draft_dot = panel @@ -497,7 +500,7 @@ impl WorkbenchShell { .session_has_draft(&id, cx) .then(|| crate::session_sidebar::draft_dot(&id, cx)); - // Finch 式单行会话条目:名称居左,归档按钮与相对时间居右。 + // 名称与固定主机归属居左,归档按钮与相对时间居右。 h_flex() .id(element_id) .group("session-row") @@ -513,13 +516,31 @@ impl WorkbenchShell { .when(selected, |this| this.bg(theme.panel_hover)) .hover(move |style| style.bg(hover)) .child( - div() + v_flex() .flex_1() .min_w_0() - .truncate() - .text_sm() - .text_color(theme.foreground) - .child(summary.name.clone()), + .gap_0p5() + .child( + div() + .w_full() + .truncate() + .text_sm() + .text_color(theme.foreground) + .child(summary.name.clone()), + ) + .when_some( + summary.host.as_ref().map(|host| host.name.clone()), + |this, host_name| { + this.child( + div() + .w_full() + .truncate() + .text_xs() + .text_color(theme.muted_foreground) + .child(host_name), + ) + }, + ), ) .when_some(draft_dot, |this, dot| this.child(dot)) // 平时隐藏,hover 行时浮现;换用 Archive 图标(Delete 是删除语义)。 diff --git a/crates/core/src/llm/chat_history.rs b/crates/core/src/llm/chat_history.rs index 917bc2373..710ca9e37 100644 --- a/crates/core/src/llm/chat_history.rs +++ b/crates/core/src/llm/chat_history.rs @@ -21,11 +21,11 @@ pub struct AgentSession { /// 侧栏会话列表需要的一行,**不含** `snapshot_json` 本体。 /// -/// 列表只用得到快照里的两个顶层字段(工作区归属、外部 agent 来源)。把整列 -/// `snapshot_json` 读上来、再在调用侧反序列化,代价与快照体积成正比(实测本机 +/// 列表只用得到快照里的三个顶层字段(工作区归属、主机归属、外部 agent 来源)。 +/// 把整列 `snapshot_json` 读上来、再在调用侧反序列化,代价与快照体积成正比(实测本机 /// 未归档 356 行合计 76.8MB、单条最大 19.2MB;debug 下光反序列化就要 1.6s), /// 而列表刷新跑在 UI 线程上且触发频繁(切会话 / 每轮结束 / 连接就绪都会跑)。 -/// 因此这两个字段下推到 SQL 层用 `json_extract` 提取:快照本体不再进入进程内存。 +/// 因此这些字段下推到 SQL 层用 `json_extract` 提取:快照本体不再进入进程内存。 #[derive(Debug, Clone, PartialEq, Eq)] pub struct AgentSessionSummaryRow { pub id: i64, @@ -38,6 +38,9 @@ pub struct AgentSessionSummaryRow { pub workspace_root: Option, /// 快照里的 `acp.agent_id`(这段会话由外部 agent 承载)。判定同上。 pub acp_agent_id: Option, + /// 首次落盘时定格的 SSH 主机 ID 与显示名。 + pub host_id: Option, + pub host_name: Option, } /// 正文命中的一条会话。 @@ -454,7 +457,7 @@ impl AgentSessionRepository { /// 列出摘要行(侧栏用),**不读** `snapshot_json` 本体。 /// - /// 过滤与排序与 [`Self::list_by_archived`] 完全一致,只是把来自快照的两个字段 + /// 过滤与排序与 [`Self::list_by_archived`] 完全一致,只是把来自快照的摘要字段 /// 下推到 SQL 层提取。调用侧因此不必把几十 MB 的快照 JSON 搬进内存、更不必逐行 /// 反序列化。 /// @@ -479,7 +482,11 @@ impl AgentSessionRepository { CASE WHEN json_valid(snapshot_json) THEN json_extract(snapshot_json, '$.workspace_root') END AS workspace_root, CASE WHEN json_valid(snapshot_json) - THEN json_extract(snapshot_json, '$.acp.agent_id') END AS acp_agent_id + THEN json_extract(snapshot_json, '$.acp.agent_id') END AS acp_agent_id, + CASE WHEN json_valid(snapshot_json) + THEN json_extract(snapshot_json, '$.host.id') END AS host_id, + CASE WHEN json_valid(snapshot_json) + THEN json_extract(snapshot_json, '$.host.name') END AS host_name FROM chat_sessions WHERE archived = ?1 ORDER BY updated_at DESC", @@ -495,6 +502,8 @@ impl AgentSessionRepository { updated_at: row.get("updated_at")?, workspace_root: row.get("workspace_root")?, acp_agent_id: row.get("acp_agent_id")?, + host_id: row.get("host_id")?, + host_name: row.get("host_name")?, }) })?; let mut results = Vec::new(); diff --git a/crates/navop_app/src/home/ai_workbench.rs b/crates/navop_app/src/home/ai_workbench.rs index 7dea4003b..fb93332b0 100644 --- a/crates/navop_app/src/home/ai_workbench.rs +++ b/crates/navop_app/src/home/ai_workbench.rs @@ -90,10 +90,7 @@ pub(crate) fn build_ai_workbench_shell( ) -> Entity { let theme = workspace_theme(cx); let workspace_root = workspace_root(cx); - // 工作区文件进 `@` 菜单:连接提及(调用方传入)之后追加,有界收集不拖慢输入框。 - let mut mentions = mentions; - mentions - .extend(ai_chat_view::workspace_files::collect_workspace_files_default(&workspace_root)); + // `@` 只负责连接资源;文件通过附件选择器引入,避免文件淹没连接列表。 let editor = cx.new(|_| WorkspaceEditor::new(theme)); let explorer = cx.new(|cx| { WorkspaceExplorer::new( diff --git a/crates/terminal_view/locales/terminal_view.yml b/crates/terminal_view/locales/terminal_view.yml index 723d48a29..c6053812f 100644 --- a/crates/terminal_view/locales/terminal_view.yml +++ b/crates/terminal_view/locales/terminal_view.yml @@ -706,10 +706,14 @@ Settings: en: Search... zh-CN: 搜索... zh-HK: 搜尋... + search_open_hint: + en: "Open with %{shortcut} or the terminal right-click menu." + zh-CN: "可按 %{shortcut},或使用终端右键菜单打开。" + zh-HK: "可按 %{shortcut},或使用終端右鍵選單開啟。" search_shortcuts_hint: - en: Press ⌘G for next, ⇧⌘G for previous - zh-CN: 按 ⌘G 跳到下一个,按 ⇧⌘G 跳到上一个 - zh-HK: 按 ⌘G 跳到下一個,按 ⇧⌘G 跳到上一個 + en: Press Enter for next, Shift+Enter for previous + zh-CN: 按 Enter 跳到下一个,按 Shift+Enter 跳到上一个 + zh-HK: 按 Enter 跳到下一個,按 Shift+Enter 跳到上一個 font_size: en: Font Size zh-CN: 字体大小 @@ -1056,6 +1060,10 @@ CustomHighlight: # 右键菜单 ContextMenu: + search_with_shortcut: + en: "Search (%{shortcut})" + zh-CN: "搜索(%{shortcut})" + zh-HK: "搜尋(%{shortcut})" copy: en: Copy zh-CN: 复制 diff --git a/crates/terminal_view/src/sidebar/settings_panel.rs b/crates/terminal_view/src/sidebar/settings_panel.rs index 182349208..836abc253 100644 --- a/crates/terminal_view/src/sidebar/settings_panel.rs +++ b/crates/terminal_view/src/sidebar/settings_panel.rs @@ -931,6 +931,39 @@ impl SettingsPanel { .into_any_element() } + /// 只说明搜索入口;搜索输入与匹配状态仍由终端独立浮层持有。 + fn render_search_help_section(&self, cx: &mut Context) -> impl IntoElement { + let colors = self.colors(); + let border = colors.border; + let muted_fg = colors.muted_foreground; + let shortcut = crate::view::keybindings::terminal_search_shortcut_label(cx); + + v_flex() + .gap_2() + .p_3() + .border_t_1() + .border_color(border) + .child( + div() + .text_xs() + .font_weight(FontWeight::MEDIUM) + .text_color(muted_fg) + .child(t!("Settings.search").to_uppercase()), + ) + .child( + div() + .text_xs() + .text_color(muted_fg) + .child(t!("Settings.search_open_hint", shortcut = shortcut)), + ) + .child( + div() + .text_xs() + .text_color(muted_fg) + .child(t!("Settings.search_shortcuts_hint")), + ) + } + /// 渲染字体设置区域 fn render_font_section(&self, _cx: &mut Context) -> impl IntoElement { let colors = self.colors(); @@ -1966,6 +1999,7 @@ impl Render for SettingsPanel { v_flex() .flex_shrink_0() .pb_4() + .child(self.render_search_help_section(cx)) .child(self.render_font_section(cx)) .child(self.render_scrollback_section(cx)) .child(self.render_cursor_section(cx)) diff --git a/crates/terminal_view/src/view.rs b/crates/terminal_view/src/view.rs index 8cd6b11c7..8294b31c4 100644 --- a/crates/terminal_view/src/view.rs +++ b/crates/terminal_view/src/view.rs @@ -156,7 +156,7 @@ mod host_key_confirmation; mod init_config; mod initialization; mod input_handler; -mod keybindings; +pub(crate) mod keybindings; mod mouse_down; mod mouse_selection; mod paste_confirm_dialog; @@ -201,7 +201,7 @@ use keybindings::{ TERMINAL_CLEAR_SCREEN_SHORTCUT, TERMINAL_CONTEXT, TERMINAL_COPY_SHORTCUT, TERMINAL_PASTE_SHORTCUT, TERMINAL_SEARCH_CONTEXT, TERMINAL_SELECT_ALL_SHORTCUT, TERMINAL_TOGGLE_VI_MODE_SHORTCUT, is_terminal_action_shortcut, terminal_paste_defaults, - terminal_shortcut_label, + terminal_search_shortcut_label, terminal_shortcut_label, }; pub use keybindings::{init, refresh_keybindings}; pub use recording_playback_config::RecordingPlaybackViewConfig; diff --git a/crates/terminal_view/src/view/keybindings.rs b/crates/terminal_view/src/view/keybindings.rs index 2c4d04be5..e9843fd4e 100644 --- a/crates/terminal_view/src/view/keybindings.rs +++ b/crates/terminal_view/src/view/keybindings.rs @@ -46,6 +46,18 @@ pub(super) fn terminal_shortcut_label(shortcut: &str) -> SharedString { .into() } +/// 搜索入口展示当前生效的快捷键;用户禁用快捷键时不再展示无效提示。 +pub(crate) fn terminal_search_shortcut_label(cx: &App) -> SharedString { + shortcuts_for( + cx, + action_id::TERMINAL_SEARCH_FORWARD, + &[TERMINAL_SEARCH_FORWARD_SHORTCUT], + ) + .first() + .map(|shortcut| terminal_shortcut_label(shortcut)) + .unwrap_or_default() +} + /// 对路径进行简单 shell 转义(用单引号包裹,处理内部单引号) pub fn init(cx: &mut App) { crate::settings::init_settings(cx); @@ -119,7 +131,19 @@ pub(super) fn init_keybindings(cx: &App) -> Vec { &[TERMINAL_SEARCH_FORWARD_SHORTCUT], ) .into_iter() - .map(|key| one_core::keybindings::load_dynamic_keybinding(&key, SearchForward, Some(TERMINAL_CONTEXT), cx)), + .flat_map(|key| { + [TERMINAL_CONTEXT, TERMINAL_SEARCH_CONTEXT] + .into_iter() + .map(|context| { + one_core::keybindings::load_dynamic_keybinding( + &key, + SearchForward, + Some(context), + cx, + ) + }) + .collect::>() + }), ); keybindings.extend( shortcuts_for( @@ -128,7 +152,19 @@ pub(super) fn init_keybindings(cx: &App) -> Vec { &[TERMINAL_SEARCH_BACKWARD_SHORTCUT], ) .into_iter() - .map(|key| one_core::keybindings::load_dynamic_keybinding(&key, SearchBackward, Some(TERMINAL_CONTEXT), cx)), + .flat_map(|key| { + [TERMINAL_CONTEXT, TERMINAL_SEARCH_CONTEXT] + .into_iter() + .map(|context| { + one_core::keybindings::load_dynamic_keybinding( + &key, + SearchBackward, + Some(context), + cx, + ) + }) + .collect::>() + }), ); keybindings.extend( shortcuts_for( @@ -258,20 +294,22 @@ pub(super) fn refreshable_keybindings(cx: &App) -> Vec { Some(TERMINAL_CONTEXT), ClearSelection, )); - keybindings.extend(rebind_keybindings( - cx, - action_id::TERMINAL_SEARCH_FORWARD, - &[TERMINAL_SEARCH_FORWARD_SHORTCUT], - Some(TERMINAL_CONTEXT), - SearchForward, - )); - keybindings.extend(rebind_keybindings( - cx, - action_id::TERMINAL_SEARCH_BACKWARD, - &[TERMINAL_SEARCH_BACKWARD_SHORTCUT], - Some(TERMINAL_CONTEXT), - SearchBackward, - )); + for context in [TERMINAL_CONTEXT, TERMINAL_SEARCH_CONTEXT] { + keybindings.extend(rebind_keybindings( + cx, + action_id::TERMINAL_SEARCH_FORWARD, + &[TERMINAL_SEARCH_FORWARD_SHORTCUT], + Some(context), + SearchForward, + )); + keybindings.extend(rebind_keybindings( + cx, + action_id::TERMINAL_SEARCH_BACKWARD, + &[TERMINAL_SEARCH_BACKWARD_SHORTCUT], + Some(context), + SearchBackward, + )); + } keybindings.extend(rebind_keybindings( cx, action_id::TERMINAL_TOGGLE_VI_MODE, diff --git a/crates/terminal_view/src/view/selection_search.rs b/crates/terminal_view/src/view/selection_search.rs index d828d39bd..e89ebf852 100644 --- a/crates/terminal_view/src/view/selection_search.rs +++ b/crates/terminal_view/src/view/selection_search.rs @@ -80,7 +80,7 @@ impl TerminalView { ); } - fn open_search(&mut self, window: &mut Window, cx: &mut Context) { + pub(super) fn open_search(&mut self, window: &mut Window, cx: &mut Context) { self.search_open = true; let focus_handle = self.search_input.read(cx).focus_handle(cx); focus_handle.focus(window, cx); diff --git a/crates/terminal_view/src/view/terminal_render.rs b/crates/terminal_view/src/view/terminal_render.rs index 6e23059b2..a5ec9f902 100644 --- a/crates/terminal_view/src/view/terminal_render.rs +++ b/crates/terminal_view/src/view/terminal_render.rs @@ -290,6 +290,7 @@ impl TerminalView { _cx: &mut Context, ) -> PopupMenu { let view_copy = view.clone(); + let view_search = view.clone(); let view_paste_selection = view.clone(); let view_paste = view.clone(); let view_select_all = view.clone(); @@ -303,8 +304,26 @@ impl TerminalView { let paste_shortcut = terminal_shortcut_label(TERMINAL_PASTE_SHORTCUT); let select_all_shortcut = terminal_shortcut_label(TERMINAL_SELECT_ALL_SHORTCUT); let clear_screen_shortcut = terminal_shortcut_label(TERMINAL_CLEAR_SCREEN_SHORTCUT); + let search_shortcut = terminal_search_shortcut_label(_cx); + let search_label = if search_shortcut.is_empty() { + t!("Settings.search") + } else { + t!("ContextMenu.search_with_shortcut", shortcut = search_shortcut) + }; let mut menu = menu + // 搜索是只读操作,实时终端与回放都应可用,且不依赖键盘。 + .item( + PopupMenuItem::new(search_label) + .icon(IconName::Search) + .action(Box::new(SearchForward)) + .on_click(move |_, window, cx| { + let _ = view_search.update(cx, |this, cx| { + this.open_search(window, cx); + }); + }), + ) + .separator() // 复制 .item( PopupMenuItem::new(t!( diff --git a/crates/terminal_view/src/view/tests/capabilities.rs b/crates/terminal_view/src/view/tests/capabilities.rs index e0dfd118c..7277080fa 100644 --- a/crates/terminal_view/src/view/tests/capabilities.rs +++ b/crates/terminal_view/src/view/tests/capabilities.rs @@ -706,6 +706,49 @@ fn terminal_search_uses_an_independent_overlay_without_opening_settings() { ); } +#[test] +fn terminal_search_has_mouse_entries_and_accurate_trigger_help() { + let context_menu = include_str!("../terminal_render.rs"); + assert!( + context_menu.contains("ContextMenu.search_with_shortcut") + && context_menu.contains("this.open_search(window, cx)"), + "终端右键菜单必须提供无需键盘的搜索入口" + ); + + let sidebar = include_str!("../../sidebar/mod.rs"); + assert!( + !sidebar.contains("terminal-toolbar-search") + && !sidebar.contains("self.render_search_button(item_size, &snapshot.colors, cx)"), + "侧边工具栏不再保留搜索按钮,避免重复入口" + ); + + let command_bar = include_str!("../command_bar/render.rs"); + let command_bar_events = include_str!("../command_bar_events.rs"); + assert!( + !command_bar.contains("render_search_button") + && !command_bar_events.contains("TerminalCommandBarEvent::OpenSearch"), + "搜索入口不应放在底部命令栏" + ); + + let settings = include_str!("../../sidebar/settings_panel.rs"); + assert!( + settings.contains("Settings.search_open_hint") + && settings.contains("Settings.search_shortcuts_hint"), + "设置中应说明鼠标入口与前后匹配按键" + ); + + let keybindings = include_str!("../keybindings.rs"); + assert!( + keybindings.contains("pub(crate) fn terminal_search_shortcut_label") + && keybindings.contains("shortcuts_for("), + "入口提示必须读取用户当前快捷键,而不是硬编码默认键位" + ); + assert!( + keybindings.contains("[TERMINAL_CONTEXT, TERMINAL_SEARCH_CONTEXT]"), + "搜索快捷键在输入框聚焦后仍应可用" + ); +} + #[test] fn terminal_search_never_waits_for_the_parser_on_the_gpui_thread() { let source = include_str!("../sidebar_events.rs");