Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
sidebar: Persist terminal threads in sidebar metadata (#56966)
Ben Brandte1f13a84b768
diff --git a/crates/agent_ui/src/agent_panel.rs b/crates/agent_ui/src/agent_panel.rsindex 635ad042b84..8401b521abd 100644--- a/crates/agent_ui/src/agent_panel.rs+++ b/crates/agent_ui/src/agent_panel.rs@@ -34,6 +34,7 @@ use crate::ExpandMessageEditor;use crate::ManageProfiles;use crate::agent_connection_store::AgentConnectionStore;use crate::completion_provider::AgentContextSource;+use crate::terminal_thread_metadata_store::{TerminalThreadMetadata, TerminalThreadMetadataStore};use crate::thread_metadata_store::{ThreadId, ThreadMetadataStore, ThreadMetadataStoreEvent};use crate::{AddContextServer, AgentDiffPane, ConversationView, CopyThreadToClipboard, Follow,@@ -110,9 +111,17 @@ impl MaxIdleRetainedThreads {pub struct TerminalId(uuid::Uuid);impl TerminalId {- fn new() -> Self {+ pub(crate) fn new() -> Self {Self(uuid::Uuid::new_v4())}++ pub(crate) fn to_key_string(self) -> String {+ self.0.hyphenated().to_string()+ }++ pub(crate) fn from_key_string(key: &str) -> anyhow::Result<Self> {+ Ok(Self(uuid::Uuid::parse_str(key)?))+ }}impl fmt::Display for TerminalId {@@ -127,6 +136,8 @@ pub struct AgentPanelTerminalInfo {pub title: SharedString,pub created_at: DateTime<Utc>,pub has_notification: bool,+ pub custom_title: Option<SharedString>,+ pub working_directory: Option<PathBuf>,}#[derive(Serialize, Deserialize)]@@ -701,6 +712,7 @@ struct AgentTerminal {title_editor_initial_title: Option<String>,title_editor_subscription: Option<Subscription>,last_known_title: String,+ working_directory: Option<PathBuf>,created_at: DateTime<Utc>,has_notification: bool,notification_windows: Vec<WindowHandle<AgentNotification>>,@@ -711,7 +723,7 @@ struct AgentTerminal {impl AgentTerminal {fn title(&self, cx: &App) -> SharedString {let view = self.view.read(cx);- if let Some(custom_title) = view.custom_title() {+ let title = if let Some(custom_title) = view.custom_title() {SharedString::from(custom_title)} else {let terminal = view.terminal().read(cx);@@ -725,6 +737,12 @@ impl AgentTerminal {} else {terminal.breadcrumb_text.clone().into()}+ };++ if title.is_empty() && !self.last_known_title.is_empty() {+ SharedString::from(self.last_known_title.clone())+ } else {+ title}}@@ -736,6 +754,22 @@ impl AgentTerminal {}changed}++ fn refresh_metadata(&mut self, cx: &mut App) -> bool {+ let title_changed = self.refresh_title(cx);+ let current_working_directory = self.view.read(cx).terminal().read(cx).working_directory();+ let working_directory_changed = current_working_directory+ .as_ref()+ .is_some_and(|current| self.working_directory.as_ref() != Some(current));+ if working_directory_changed {+ self.working_directory = current_working_directory;+ }+ title_changed || working_directory_changed+ }++ fn custom_title(&self, cx: &App) -> Option<SharedString> {+ self.view.read(cx).custom_title().map(SharedString::from)+ }}enum BaseView {@@ -1105,9 +1139,11 @@ impl AgentPanel {cx.subscribe(&project, |this, _project, event, cx| match event {project::Event::WorktreeAdded(_)| project::Event::WorktreeRemoved(_)- | project::Event::WorktreeOrderChanged => {+ | project::Event::WorktreeOrderChanged+ | project::Event::WorktreePathsChanged { .. } => {this.ensure_native_agent_connection(cx);this.update_thread_work_dirs(cx);+ this.persist_all_terminal_metadata(cx);cx.notify();}_ => {}@@ -1513,6 +1549,10 @@ impl AgentPanel {self.spawn_terminal(TerminalId::new(),working_directory,+ None,+ None,+ None,+ true,true,source,window,@@ -1554,11 +1594,16 @@ impl AgentPanel {&mut self,terminal_id: TerminalId,working_directory: Option<PathBuf>,+ custom_title: Option<SharedString>,+ initial_title: Option<SharedString>,+ created_at: Option<DateTime<Utc>>,+ select: bool,focus: bool,source: AgentThreadSource,window: &mut Window,cx: &mut Context<Self>,) {+ let terminal_working_directory = working_directory.clone();let terminal_task = self.project.update(cx, |project, cx| {project.create_terminal_shell(working_directory, cx)});@@ -1581,7 +1626,19 @@ impl AgentPanel {let terminal_view = cx.new(|cx| {TerminalView::new(terminal, workspace, workspace_id, project, window, cx)});- this.insert_terminal(terminal_id, terminal_view, focus, source, window, cx);+ this.insert_terminal(+ terminal_id,+ terminal_view,+ terminal_working_directory,+ custom_title,+ initial_title,+ created_at,+ select,+ focus,+ source,+ window,+ cx,+ );})?;anyhow::Ok(())})@@ -1592,17 +1649,27 @@ impl AgentPanel {&mut self,terminal_id: TerminalId,terminal_view: Entity<TerminalView>,+ working_directory: Option<PathBuf>,+ custom_title: Option<SharedString>,+ initial_title: Option<SharedString>,+ created_at: Option<DateTime<Utc>>,+ select: bool,focus: bool,source: AgentThreadSource,window: &mut Window,cx: &mut Context<Self>,) {+ if let Some(custom_title) = custom_title {+ terminal_view.update(cx, |terminal_view, cx| {+ terminal_view.set_custom_title(Some(custom_title.to_string()), cx);+ });+ }let terminal_entity = terminal_view.read(cx).terminal().clone();let view_subscription = cx.subscribe(&terminal_view,move |this, _terminal_view, event: &ItemEvent, cx| match event {ItemEvent::UpdateTab | ItemEvent::UpdateBreadcrumbs => {- this.refresh_terminal_title(terminal_id, cx);+ this.refresh_terminal_metadata(terminal_id, cx);}ItemEvent::CloseItem | ItemEvent::Edit => {}},@@ -1616,11 +1683,11 @@ impl AgentPanel {TerminalEvent::TitleChanged| TerminalEvent::Wakeup| TerminalEvent::BreadcrumbsChanged => {- this.refresh_terminal_title(terminal_id, cx);+ this.refresh_terminal_metadata(terminal_id, cx);}TerminalEvent::Bell => this.mark_terminal_notification(terminal_id, window, cx),TerminalEvent::CloseTerminal => {- this.close_terminal(terminal_id, window, cx);+ this.close_terminal_from_terminal_event(terminal_id, window, cx);}TerminalEvent::BlinkChanged(_)| TerminalEvent::SelectionsChanged@@ -1634,19 +1701,23 @@ impl AgentPanel {title_editor: None,title_editor_initial_title: None,title_editor_subscription: None,- last_known_title: String::new(),- created_at: Utc::now(),+ last_known_title: initial_title+ .map(|title| title.to_string())+ .unwrap_or_default(),+ working_directory,+ created_at: created_at.unwrap_or_else(Utc::now),has_notification: false,notification_windows: Vec::new(),notification_subscriptions: Vec::new(),_subscriptions: vec![view_subscription, terminal_subscription],};self.set_last_created_entry_kind(AgentPanelEntryKind::Terminal, cx);- terminal.refresh_title(cx);+ terminal.refresh_metadata(cx);self.terminals.insert(terminal_id, terminal);+ self.persist_terminal_metadata(terminal_id, cx);self.emit_terminal_thread_started(source, cx);- if focus {- self.set_base_view(BaseView::Terminal { terminal_id }, true, window, cx);+ if select {+ self.set_base_view(BaseView::Terminal { terminal_id }, focus, window, cx);}cx.emit(AgentPanelEvent::EntryChanged);cx.notify();@@ -1679,6 +1750,26 @@ impl AgentPanel {terminal_id: TerminalId,window: &mut Window,cx: &mut Context<Self>,+ ) {+ self.close_terminal_internal(terminal_id, true, None, window, cx);+ }++ pub fn close_terminal_without_activating_draft(+ &mut self,+ terminal_id: TerminalId,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ self.close_terminal_internal(terminal_id, false, None, window, cx);+ }++ fn close_terminal_internal(+ &mut self,+ terminal_id: TerminalId,+ activate_draft_after_close: bool,+ terminal_closed_metadata: Option<TerminalThreadMetadata>,+ window: &mut Window,+ cx: &mut Context<Self>,) {let was_active = self.active_terminal_id() == Some(terminal_id);@@ -1686,16 +1777,36 @@ impl AgentPanel {if self.terminals.remove(&terminal_id).is_none() {return;}+ if let Some(store) = TerminalThreadMetadataStore::try_global(cx) {+ store.update(cx, |store, cx| {+ store.delete(terminal_id, cx);+ });+ }if was_active {self.base_view = BaseView::Uninitialized;self.refresh_base_view_subscriptions(window, cx);- self.activate_draft(false, AgentThreadSource::AgentPanel, window, cx);+ if activate_draft_after_close {+ self.activate_draft(false, AgentThreadSource::AgentPanel, window, cx);+ }}+ if let Some(metadata) = terminal_closed_metadata {+ cx.emit(AgentPanelEvent::TerminalClosed { metadata });+ }cx.emit(AgentPanelEvent::EntryChanged);cx.notify();}+ fn close_terminal_from_terminal_event(+ &mut self,+ terminal_id: TerminalId,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ let metadata = self.terminal_metadata(terminal_id, cx);+ self.close_terminal_internal(terminal_id, false, metadata, window, cx);+ }+fn emit_terminal_thread_started(&self, source: AgentThreadSource, cx: &App) {telemetry::event!("Agent Thread Started",@@ -1706,15 +1817,110 @@ impl AgentPanel {);}- fn refresh_terminal_title(&mut self, terminal_id: TerminalId, cx: &mut Context<Self>) {+ fn refresh_terminal_metadata(&mut self, terminal_id: TerminalId, cx: &mut Context<Self>) {if let Some(terminal) = self.terminals.get_mut(&terminal_id)- && terminal.refresh_title(cx)+ && terminal.refresh_metadata(cx){+ self.persist_terminal_metadata(terminal_id, cx);cx.emit(AgentPanelEvent::EntryChanged);cx.notify();}}+ fn persist_all_terminal_metadata(&self, cx: &mut Context<Self>) {+ let terminal_ids = self.terminals.keys().copied().collect::<Vec<_>>();+ for terminal_id in terminal_ids {+ self.persist_terminal_metadata(terminal_id, cx);+ }+ }++ fn persist_terminal_metadata(&self, terminal_id: TerminalId, cx: &mut Context<Self>) {+ let Some(store) = TerminalThreadMetadataStore::try_global(cx) else {+ return;+ };+ let Some(metadata) = self.terminal_metadata(terminal_id, cx) else {+ return;+ };+ store.update(cx, |store, cx| {+ store.save(metadata, cx);+ });+ }++ fn terminal_metadata(+ &self,+ terminal_id: TerminalId,+ cx: &App,+ ) -> Option<TerminalThreadMetadata> {+ let terminal = self.terminals.get(&terminal_id)?;+ let project = self.project.read(cx);+ Some(TerminalThreadMetadata {+ terminal_id,+ title: terminal.title(cx),+ custom_title: terminal.custom_title(cx),+ created_at: terminal.created_at,+ worktree_paths: project.worktree_paths(cx),+ remote_connection: project.remote_connection_options(cx),+ working_directory: terminal.working_directory.clone(),+ })+ }++ pub fn restore_terminal(+ &mut self,+ metadata: TerminalThreadMetadata,+ focus: bool,+ source: AgentThreadSource,+ workspace: Option<&Workspace>,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ if self.has_terminal(metadata.terminal_id) {+ self.activate_terminal(metadata.terminal_id, focus, window, cx);+ return;+ }++ if !self.supports_terminal(cx) {+ return;+ }++ let working_directory = self.terminal_restore_working_directory(&metadata, workspace, cx);+ let initial_title = Self::terminal_restore_initial_title(&metadata);+ self.spawn_terminal(+ metadata.terminal_id,+ working_directory,+ metadata.custom_title.clone(),+ initial_title,+ Some(metadata.created_at),+ true,+ focus,+ source,+ window,+ cx,+ );+ }++ fn terminal_restore_working_directory(+ &self,+ metadata: &TerminalThreadMetadata,+ workspace: Option<&Workspace>,+ cx: &App,+ ) -> Option<PathBuf> {+ metadata+ .working_directory+ .clone()+ .or_else(|| {+ workspace+ .and_then(|workspace| terminal_view::default_working_directory(workspace, cx))+ })+ .or_else(|| self.default_terminal_working_directory(cx))+ }++ fn terminal_restore_initial_title(metadata: &TerminalThreadMetadata) -> Option<SharedString> {+ metadata+ .custom_title+ .clone()+ .or_else(|| (!metadata.title.is_empty()).then(|| metadata.title.clone()))+ }+fn edit_terminal_title(&mut self,terminal_id: TerminalId,@@ -2430,6 +2636,8 @@ impl AgentPanel {title: terminal.title(cx),created_at: terminal.created_at,has_notification: terminal.has_notification,+ custom_title: terminal.custom_title(cx),+ working_directory: terminal.working_directory.clone(),}).collect()}@@ -3693,6 +3901,7 @@ pub enum AgentPanelEvent {ActiveViewChanged,ActiveViewFocused,EntryChanged,+ TerminalClosed { metadata: TerminalThreadMetadata },ThreadInteracted { thread_id: ThreadId },}@@ -5294,6 +5503,70 @@ impl AgentPanel {cx: &mut Context<Self>,) -> Result<TerminalId> {let terminal_id = TerminalId::new();+ self.insert_display_only_terminal(+ terminal_id,+ None,+ Some(SharedString::from(title.into())),+ None,+ None,+ focus,+ focus,+ AgentThreadSource::AgentPanel,+ window,+ cx,+ )?;+ Ok(terminal_id)+ }++ #[cfg(any(test, feature = "test-support"))]+ pub fn restore_test_terminal(+ &mut self,+ metadata: TerminalThreadMetadata,+ focus: bool,+ source: AgentThreadSource,+ workspace: Option<&Workspace>,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) -> Result<()> {+ if self.has_terminal(metadata.terminal_id) {+ self.activate_terminal(metadata.terminal_id, focus, window, cx);+ return Ok(());+ }++ if !self.supports_terminal(cx) {+ return Ok(());+ }++ let working_directory = self.terminal_restore_working_directory(&metadata, workspace, cx);+ let initial_title = Self::terminal_restore_initial_title(&metadata);+ self.insert_display_only_terminal(+ metadata.terminal_id,+ working_directory,+ metadata.custom_title.clone(),+ initial_title,+ Some(metadata.created_at),+ true,+ focus,+ source,+ window,+ cx,+ )+ }++ #[cfg(any(test, feature = "test-support"))]+ fn insert_display_only_terminal(+ &mut self,+ terminal_id: TerminalId,+ working_directory: Option<PathBuf>,+ custom_title: Option<SharedString>,+ initial_title: Option<SharedString>,+ created_at: Option<DateTime<Utc>>,+ select: bool,+ focus: bool,+ source: AgentThreadSource,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) -> Result<()> {let settings = TerminalSettings::get_global(cx).clone();let path_style = self.project.read(cx).path_style(cx);let builder = terminal::TerminalBuilder::new_display_only(@@ -5315,18 +5588,20 @@ impl AgentPanel {cx,)});- terminal_view.update(cx, |terminal_view, cx| {- terminal_view.set_custom_title(Some(title.into()), cx);- });self.insert_terminal(terminal_id,terminal_view,+ working_directory,+ custom_title,+ initial_title,+ created_at,+ select,focus,- AgentThreadSource::AgentPanel,+ source,window,cx,);- Ok(terminal_id)+ Ok(())}#[cfg(any(test, feature = "test-support"))]@@ -5342,6 +5617,20 @@ impl AgentPanel {cx.emit(TerminalEvent::Bell);});}++ #[cfg(any(test, feature = "test-support"))]+ pub fn emit_test_terminal_close(&mut self, terminal_id: TerminalId, cx: &mut Context<Self>) {+ let Some(terminal_entity) = self+ .terminals+ .get(&terminal_id)+ .map(|terminal| terminal.view.read(cx).terminal().clone())+ else {+ return;+ };+ terminal_entity.update(cx, |_terminal, cx| {+ cx.emit(TerminalEvent::CloseTerminal);+ });+ }}#[cfg(test)]@@ -5360,7 +5649,7 @@ mod tests {use fs::FakeFs;use gpui::{App, TestAppContext, VisualTestContext};use parking_lot::Mutex;- use project::Project;+ use project::{Project, WorktreePaths};use std::any::Any;use serde_json::json;@@ -6959,6 +7248,39 @@ mod tests {});}+ #[gpui::test]+ async fn test_terminal_close_event_closes_without_sidebar(cx: &mut TestAppContext) {+ let (panel, mut cx) = setup_panel(cx).await;+ cx.update(|_, cx| {+ TerminalThreadMetadataStore::init_global(cx);+ });++ let terminal_id = panel+ .update_in(&mut cx, |panel, window, cx| {+ panel.insert_test_terminal("Dev Server", true, window, cx)+ })+ .expect("test terminal should be inserted");+ cx.run_until_parked();++ panel.update(&mut cx, |panel, cx| {+ panel.emit_test_terminal_close(terminal_id, cx);+ });+ cx.run_until_parked();++ panel.read_with(&cx, |panel, _cx| {+ assert!(!panel.has_terminal(terminal_id));+ });+ cx.update(|_, cx| {+ assert!(+ TerminalThreadMetadataStore::global(cx)+ .read(cx)+ .entry(terminal_id)+ .is_none(),+ "terminal metadata should be deleted by the fallback close"+ );+ });+ }+#[gpui::test]async fn test_new_thread_dismisses_settings_overlay(cx: &mut TestAppContext) {let (panel, mut cx) = setup_panel(cx).await;@@ -7117,6 +7439,95 @@ mod tests {});}+ #[gpui::test]+ async fn test_restored_terminal_uses_metadata_title_until_shell_title_arrives(+ cx: &mut TestAppContext,+ ) {+ let (panel, mut cx) = setup_panel(cx).await;+ let terminal_id = TerminalId::new();+ let now = Utc::now();+ let metadata = TerminalThreadMetadata {+ terminal_id,+ title: "Persisted Shell Title".into(),+ custom_title: None,+ created_at: now,+ worktree_paths: WorktreePaths::from_folder_paths(&PathList::new(&[PathBuf::from(+ "/project",+ )])),+ remote_connection: None,+ working_directory: None,+ };++ panel.update_in(&mut cx, |panel, window, cx| {+ panel+ .restore_test_terminal(metadata, true, AgentThreadSource::Sidebar, None, window, cx)+ .expect("test terminal should be restored");+ });+ cx.run_until_parked();++ let terminal_view = panel.read_with(&cx, |panel, cx| {+ let terminals = panel.terminals(cx);+ assert_eq!(terminals.len(), 1);+ assert_eq!(terminals[0].title.as_ref(), "Persisted Shell Title");+ panel+ .terminals+ .get(&terminal_id)+ .expect("terminal should be restored")+ .view+ .clone()+ });++ let terminal_entity =+ terminal_view.read_with(&cx, |terminal_view, _cx| terminal_view.terminal().clone());+ terminal_entity.update(&mut cx, |terminal, cx| {+ terminal.breadcrumb_text = "Fresh Shell Title".to_string();+ cx.emit(TerminalEvent::BreadcrumbsChanged);+ });+ cx.run_until_parked();++ panel.read_with(&cx, |panel, cx| {+ let terminals = panel.terminals(cx);+ assert_eq!(terminals.len(), 1);+ assert_eq!(terminals[0].title.as_ref(), "Fresh Shell Title");+ });+ }++ #[gpui::test]+ async fn test_restored_terminal_selects_without_focusing(cx: &mut TestAppContext) {+ let (panel, mut cx) = setup_panel(cx).await;+ let terminal_id = TerminalId::new();+ let now = Utc::now();+ let metadata = TerminalThreadMetadata {+ terminal_id,+ title: "Persisted Shell Title".into(),+ custom_title: None,+ created_at: now,+ worktree_paths: WorktreePaths::from_folder_paths(&PathList::new(&[PathBuf::from(+ "/project",+ )])),+ remote_connection: None,+ working_directory: None,+ };++ panel.update_in(&mut cx, |panel, window, cx| {+ panel+ .restore_test_terminal(+ metadata,+ false,+ AgentThreadSource::Sidebar,+ None,+ window,+ cx,+ )+ .expect("test terminal should be restored");+ });+ cx.run_until_parked();++ panel.read_with(&cx, |panel, _cx| {+ assert_eq!(panel.active_terminal_id(), Some(terminal_id));+ });+ }+#[gpui::test]async fn test_terminal_working_directory_uses_active_workspace_while_workspace_is_updating(cx: &mut TestAppContext,@@ -7169,7 +7580,7 @@ mod tests {});panel.update(&mut cx, |panel, cx| {- panel.refresh_terminal_title(terminal_id, cx);+ panel.refresh_terminal_metadata(terminal_id, cx);});cx.run_until_parked();diff --git a/crates/agent_ui/src/agent_ui.rs b/crates/agent_ui/src/agent_ui.rsindex 99297e20a70..f67a1d11aaf 100644--- a/crates/agent_ui/src/agent_ui.rs+++ b/crates/agent_ui/src/agent_ui.rs@@ -26,6 +26,7 @@ mod model_selector_popover;mod profile_selector;mod terminal_codegen;mod terminal_inline_assistant;+pub mod terminal_thread_metadata_store;#[cfg(any(test, feature = "test-support"))]pub mod test_support;mod thread_import;@@ -513,6 +514,7 @@ pub fn init(agent_panel::init(cx);context_server_configuration::init(language_registry.clone(), fs.clone(), cx);thread_metadata_store::init(cx);+ terminal_thread_metadata_store::init(cx);inline_assistant::init(fs.clone(), prompt_builder.clone(), cx);terminal_inline_assistant::init(fs.clone(), prompt_builder, cx);diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex 6ecb85267a7..5e5f6af52b3 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -2793,6 +2793,7 @@ impl ConversationView {dismiss_if_visible(this, window, cx);}AgentPanelEvent::EntryChanged+ | AgentPanelEvent::TerminalClosed { .. }| AgentPanelEvent::ThreadInteracted { .. } => {}},));diff --git a/crates/agent_ui/src/terminal_thread_metadata_store.rs b/crates/agent_ui/src/terminal_thread_metadata_store.rsnew file mode 100644index 00000000000..e3d5c9fdef8--- /dev/null+++ b/crates/agent_ui/src/terminal_thread_metadata_store.rs@@ -0,0 +1,617 @@+use std::path::{Path, PathBuf};++use anyhow::Context as _;+use chrono::{DateTime, Utc};+use collections::{HashMap, HashSet};+use db::{+ sqlez::{+ bindable::Column, domain::Domain, statement::Statement,+ thread_safe_connection::ThreadSafeConnection,+ },+ sqlez_macros::sql,+};+use gpui::{AppContext as _, Entity, Global, Task};+use remote::{RemoteConnectionOptions, same_remote_connection_identity};+use ui::{App, Context, SharedString};+use util::ResultExt as _;+use workspace::PathList;++use crate::{TerminalId, thread_metadata_store::WorktreePaths};++pub fn init(cx: &mut App) {+ TerminalThreadMetadataStore::init_global(cx);+}++struct GlobalTerminalThreadMetadataStore(Entity<TerminalThreadMetadataStore>);+impl Global for GlobalTerminalThreadMetadataStore {}++#[cfg(any(test, feature = "test-support"))]+pub struct TestTerminalMetadataDbName(pub String);+#[cfg(any(test, feature = "test-support"))]+impl Global for TestTerminalMetadataDbName {}++#[cfg(any(test, feature = "test-support"))]+impl TestTerminalMetadataDbName {+ pub fn global(cx: &App) -> String {+ cx.try_global::<Self>()+ .map(|global| global.0.clone())+ .unwrap_or_else(|| {+ let thread = std::thread::current();+ let test_name = thread.name().unwrap_or("unknown_test");+ format!("TERMINAL_THREAD_METADATA_DB_{}", test_name)+ })+ }+}++#[derive(Debug, Clone, PartialEq)]+pub struct TerminalThreadMetadata {+ pub terminal_id: TerminalId,+ pub title: SharedString,+ pub custom_title: Option<SharedString>,+ pub created_at: DateTime<Utc>,+ pub worktree_paths: WorktreePaths,+ pub remote_connection: Option<RemoteConnectionOptions>,+ pub working_directory: Option<PathBuf>,+}++impl TerminalThreadMetadata {+ pub fn folder_paths(&self) -> &PathList {+ self.worktree_paths.folder_path_list()+ }++ pub fn main_worktree_paths(&self) -> &PathList {+ self.worktree_paths.main_worktree_path_list()+ }+}++pub struct TerminalThreadMetadataStore {+ db: TerminalThreadMetadataDb,+ terminals: HashMap<TerminalId, TerminalThreadMetadata>,+ terminals_by_paths: HashMap<PathList, HashSet<TerminalId>>,+ terminals_by_main_paths: HashMap<PathList, HashSet<TerminalId>>,+ pending_terminal_ops_tx: async_channel::Sender<DbOperation>,+ _db_operations_task: Task<()>,+}++#[derive(Debug, PartialEq)]+enum DbOperation {+ Upsert(TerminalThreadMetadata),+ Delete(TerminalId),+}++impl DbOperation {+ fn id(&self) -> TerminalId {+ match self {+ DbOperation::Upsert(metadata) => metadata.terminal_id,+ DbOperation::Delete(terminal_id) => *terminal_id,+ }+ }+}++impl TerminalThreadMetadataStore {+ #[cfg(not(any(test, feature = "test-support")))]+ pub fn init_global(cx: &mut App) {+ if cx.has_global::<GlobalTerminalThreadMetadataStore>() {+ return;+ }++ let db = TerminalThreadMetadataDb::global(cx);+ let terminal_store = cx.new(|cx| Self::new(db, cx));+ cx.set_global(GlobalTerminalThreadMetadataStore(terminal_store));+ }++ #[cfg(any(test, feature = "test-support"))]+ pub fn init_global(cx: &mut App) {+ let db_name = TestTerminalMetadataDbName::global(cx);+ let db = gpui::block_on(db::open_test_db::<TerminalThreadMetadataDb>(&db_name));+ let terminal_store = cx.new(|cx| Self::new(TerminalThreadMetadataDb(db), cx));+ cx.set_global(GlobalTerminalThreadMetadataStore(terminal_store));+ }++ pub fn try_global(cx: &App) -> Option<Entity<Self>> {+ cx.try_global::<GlobalTerminalThreadMetadataStore>()+ .map(|store| store.0.clone())+ }++ pub fn global(cx: &App) -> Entity<Self> {+ cx.global::<GlobalTerminalThreadMetadataStore>().0.clone()+ }++ pub fn entry(&self, terminal_id: TerminalId) -> Option<&TerminalThreadMetadata> {+ self.terminals.get(&terminal_id)+ }++ pub fn entries(&self) -> impl Iterator<Item = &TerminalThreadMetadata> + '_ {+ self.terminals.values()+ }++ pub fn entries_for_path<'a>(+ &'a self,+ path_list: &PathList,+ remote_connection: Option<&'a RemoteConnectionOptions>,+ ) -> impl Iterator<Item = &'a TerminalThreadMetadata> + 'a {+ self.terminals_by_paths+ .get(path_list)+ .into_iter()+ .flatten()+ .filter_map(|id| self.terminals.get(id))+ .filter(move |terminal| {+ same_remote_connection_identity(+ terminal.remote_connection.as_ref(),+ remote_connection,+ )+ })+ }++ pub fn entries_for_main_worktree_path<'a>(+ &'a self,+ path_list: &PathList,+ remote_connection: Option<&'a RemoteConnectionOptions>,+ ) -> impl Iterator<Item = &'a TerminalThreadMetadata> + 'a {+ self.terminals_by_main_paths+ .get(path_list)+ .into_iter()+ .flatten()+ .filter_map(|id| self.terminals.get(id))+ .filter(move |terminal| {+ same_remote_connection_identity(+ terminal.remote_connection.as_ref(),+ remote_connection,+ )+ })+ }++ pub fn path_is_referenced_by_terminal(+ &self,+ terminal_id: Option<TerminalId>,+ path: &Path,+ remote_connection: Option<&RemoteConnectionOptions>,+ ) -> bool {+ self.entries().any(|terminal| {+ Some(terminal.terminal_id) != terminal_id+ && same_remote_connection_identity(+ terminal.remote_connection.as_ref(),+ remote_connection,+ )+ && terminal+ .folder_paths()+ .paths()+ .iter()+ .any(|folder_path| folder_path.as_path() == path)+ })+ }++ pub fn save(&mut self, metadata: TerminalThreadMetadata, cx: &mut Context<Self>) {+ self.save_internal(metadata);+ cx.notify();+ }++ pub fn change_worktree_paths(+ &mut self,+ current_folder_paths: &PathList,+ remote_connection: Option<&RemoteConnectionOptions>,+ mutate: impl Fn(&mut WorktreePaths),+ cx: &mut Context<Self>,+ ) {+ let terminal_ids: Vec<_> = self+ .terminals_by_paths+ .get(current_folder_paths)+ .into_iter()+ .flatten()+ .filter(|id| {+ self.terminals.get(id).is_some_and(|terminal| {+ same_remote_connection_identity(+ terminal.remote_connection.as_ref(),+ remote_connection,+ )+ })+ })+ .copied()+ .collect();++ if terminal_ids.is_empty() {+ return;+ }++ for terminal_id in terminal_ids {+ if let Some(mut terminal) = self.terminals.get(&terminal_id).cloned() {+ mutate(&mut terminal.worktree_paths);+ self.save_internal(terminal);+ }+ }++ cx.notify();+ }++ fn save_internal(&mut self, metadata: TerminalThreadMetadata) {+ if let Some(existing) = self.terminals.get(&metadata.terminal_id) {+ if existing.folder_paths() != metadata.folder_paths()+ && let Some(ids) = self.terminals_by_paths.get_mut(existing.folder_paths())+ {+ ids.remove(&metadata.terminal_id);+ }++ if existing.main_worktree_paths() != metadata.main_worktree_paths()+ && let Some(ids) = self+ .terminals_by_main_paths+ .get_mut(existing.main_worktree_paths())+ {+ ids.remove(&metadata.terminal_id);+ }+ }++ self.cache_terminal_metadata(metadata.clone());+ self.pending_terminal_ops_tx+ .try_send(DbOperation::Upsert(metadata))+ .log_err();+ }++ fn cache_terminal_metadata(&mut self, metadata: TerminalThreadMetadata) {+ self.terminals+ .insert(metadata.terminal_id, metadata.clone());++ self.terminals_by_paths+ .entry(metadata.folder_paths().clone())+ .or_default()+ .insert(metadata.terminal_id);++ if !metadata.main_worktree_paths().is_empty() {+ self.terminals_by_main_paths+ .entry(metadata.main_worktree_paths().clone())+ .or_default()+ .insert(metadata.terminal_id);+ }+ }++ pub fn delete(&mut self, terminal_id: TerminalId, cx: &mut Context<Self>) {+ if let Some(terminal) = self.terminals.remove(&terminal_id) {+ if let Some(ids) = self.terminals_by_paths.get_mut(terminal.folder_paths()) {+ ids.remove(&terminal_id);+ }+ if !terminal.main_worktree_paths().is_empty()+ && let Some(ids) = self+ .terminals_by_main_paths+ .get_mut(terminal.main_worktree_paths())+ {+ ids.remove(&terminal_id);+ }+ }+ self.pending_terminal_ops_tx+ .try_send(DbOperation::Delete(terminal_id))+ .log_err();+ cx.notify();+ }++ fn new(db: TerminalThreadMetadataDb, cx: &mut Context<Self>) -> Self {+ let (tx, rx) = async_channel::unbounded();+ let _db_operations_task = cx.background_spawn({+ let db = db.clone();+ async move {+ while let Ok(first_update) = rx.recv().await {+ let mut updates = vec![first_update];+ while let Ok(update) = rx.try_recv() {+ updates.push(update);+ }+ let updates = Self::dedup_db_operations(updates);+ for operation in updates {+ match operation {+ DbOperation::Upsert(metadata) => {+ db.save(metadata).await.log_err();+ }+ DbOperation::Delete(terminal_id) => {+ db.delete(terminal_id).await.log_err();+ }+ }+ }+ }+ }+ });++ let mut this = Self {+ db,+ terminals: HashMap::default(),+ terminals_by_paths: HashMap::default(),+ terminals_by_main_paths: HashMap::default(),+ pending_terminal_ops_tx: tx,+ _db_operations_task,+ };+ this.reload(cx);+ this+ }++ fn dedup_db_operations(operations: Vec<DbOperation>) -> Vec<DbOperation> {+ let mut ops = HashMap::default();+ for operation in operations.into_iter().rev() {+ if ops.contains_key(&operation.id()) {+ continue;+ }+ ops.insert(operation.id(), operation);+ }+ ops.into_values().collect()+ }++ fn reload(&mut self, cx: &mut Context<Self>) {+ let db = self.db.clone();+ cx.spawn(async move |this, cx| {+ let rows = cx+ .background_spawn(async move {+ db.list()+ .context("Failed to fetch terminal thread metadata")+ })+ .await+ .log_err()+ .unwrap_or_default();++ this.update(cx, |this, cx| {+ this.terminals.clear();+ this.terminals_by_paths.clear();+ this.terminals_by_main_paths.clear();++ for row in rows {+ this.cache_terminal_metadata(row);+ }++ cx.notify();+ })+ .ok();+ })+ .detach();+ }+}++struct TerminalThreadMetadataDb(ThreadSafeConnection);++impl Domain for TerminalThreadMetadataDb {+ const NAME: &str = stringify!(TerminalThreadMetadataDb);++ const MIGRATIONS: &[&str] = &[sql!(+ CREATE TABLE IF NOT EXISTS sidebar_terminal_threads(+ terminal_id TEXT PRIMARY KEY,+ title TEXT NOT NULL,+ custom_title TEXT,+ created_at TEXT NOT NULL,+ working_directory TEXT,+ folder_paths TEXT,+ folder_paths_order TEXT,+ main_worktree_paths TEXT,+ main_worktree_paths_order TEXT,+ remote_connection TEXT+ ) STRICT;+ )];+}++db::static_connection!(TerminalThreadMetadataDb, []);++impl TerminalThreadMetadataDb {+ pub fn list(&self) -> anyhow::Result<Vec<TerminalThreadMetadata>> {+ self.select::<TerminalThreadMetadata>(+ "SELECT terminal_id, title, custom_title, created_at, \+ working_directory, folder_paths, folder_paths_order, main_worktree_paths, \+ main_worktree_paths_order, remote_connection \+ FROM sidebar_terminal_threads \+ ORDER BY created_at DESC",+ )?()+ }++ pub async fn save(&self, row: TerminalThreadMetadata) -> anyhow::Result<()> {+ let terminal_id = row.terminal_id.to_key_string();+ let title = row.title.to_string();+ let custom_title = row.custom_title.as_ref().map(ToString::to_string);+ let created_at = row.created_at.to_rfc3339();+ let working_directory = row+ .working_directory+ .as_ref()+ .map(|path| path.to_string_lossy().into_owned());+ let serialized = row.folder_paths().serialize();+ let (folder_paths, folder_paths_order) = if row.folder_paths().is_empty() {+ (None, None)+ } else {+ (Some(serialized.paths), Some(serialized.order))+ };+ let main_serialized = row.main_worktree_paths().serialize();+ let (main_worktree_paths, main_worktree_paths_order) =+ if row.main_worktree_paths().is_empty() {+ (None, None)+ } else {+ (Some(main_serialized.paths), Some(main_serialized.order))+ };+ let remote_connection = row+ .remote_connection+ .as_ref()+ .map(serde_json::to_string)+ .transpose()+ .context("serialize terminal thread remote connection")?;++ self.write(move |conn| {+ let sql = "INSERT INTO sidebar_terminal_threads(terminal_id, title, custom_title, created_at, working_directory, folder_paths, folder_paths_order, main_worktree_paths, main_worktree_paths_order, remote_connection) \+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10) \+ ON CONFLICT(terminal_id) DO UPDATE SET \+ title = excluded.title, \+ custom_title = excluded.custom_title, \+ created_at = excluded.created_at, \+ working_directory = excluded.working_directory, \+ folder_paths = excluded.folder_paths, \+ folder_paths_order = excluded.folder_paths_order, \+ main_worktree_paths = excluded.main_worktree_paths, \+ main_worktree_paths_order = excluded.main_worktree_paths_order, \+ remote_connection = excluded.remote_connection";+ let mut stmt = Statement::prepare(conn, sql)?;+ let mut i = stmt.bind(&terminal_id, 1)?;+ i = stmt.bind(&title, i)?;+ i = stmt.bind(&custom_title, i)?;+ i = stmt.bind(&created_at, i)?;+ i = stmt.bind(&working_directory, i)?;+ i = stmt.bind(&folder_paths, i)?;+ i = stmt.bind(&folder_paths_order, i)?;+ i = stmt.bind(&main_worktree_paths, i)?;+ i = stmt.bind(&main_worktree_paths_order, i)?;+ stmt.bind(&remote_connection, i)?;+ stmt.exec()+ })+ .await+ }++ pub async fn delete(&self, terminal_id: TerminalId) -> anyhow::Result<()> {+ let terminal_id = terminal_id.to_key_string();+ self.write(move |conn| {+ let mut stmt = Statement::prepare(+ conn,+ "DELETE FROM sidebar_terminal_threads WHERE terminal_id = ?",+ )?;+ stmt.bind(&terminal_id, 1)?;+ stmt.exec()+ })+ .await+ }+}++impl Column for TerminalThreadMetadata {+ fn column(statement: &mut Statement, start_index: i32) -> anyhow::Result<(Self, i32)> {+ let (terminal_id, next): (String, i32) = Column::column(statement, start_index)?;+ let (title, next): (String, i32) = Column::column(statement, next)?;+ let (custom_title, next): (Option<String>, i32) = Column::column(statement, next)?;+ let (created_at, next): (String, i32) = Column::column(statement, next)?;+ let (working_directory, next): (Option<String>, i32) = Column::column(statement, next)?;+ let (folder_paths_str, next): (Option<String>, i32) = Column::column(statement, next)?;+ let (folder_paths_order_str, next): (Option<String>, i32) =+ Column::column(statement, next)?;+ let (main_worktree_paths_str, next): (Option<String>, i32) =+ Column::column(statement, next)?;+ let (main_worktree_paths_order_str, next): (Option<String>, i32) =+ Column::column(statement, next)?;+ let (remote_connection_json, next): (Option<String>, i32) =+ Column::column(statement, next)?;++ let folder_paths = folder_paths_str+ .map(|paths| {+ PathList::deserialize(&util::path_list::SerializedPathList {+ paths,+ order: folder_paths_order_str.unwrap_or_default(),+ })+ })+ .unwrap_or_default();++ let main_worktree_paths = main_worktree_paths_str+ .map(|paths| {+ PathList::deserialize(&util::path_list::SerializedPathList {+ paths,+ order: main_worktree_paths_order_str.unwrap_or_default(),+ })+ })+ .unwrap_or_default();++ let remote_connection = remote_connection_json+ .as_deref()+ .map(serde_json::from_str::<RemoteConnectionOptions>)+ .transpose()+ .context("deserialize terminal thread remote connection")?;++ let worktree_paths = WorktreePaths::from_path_lists(main_worktree_paths, folder_paths)+ .unwrap_or_else(|_| WorktreePaths::default());++ Ok((+ TerminalThreadMetadata {+ terminal_id: TerminalId::from_key_string(&terminal_id)?,+ title: SharedString::from(title),+ custom_title: custom_title+ .filter(|title| !title.trim().is_empty())+ .map(SharedString::from),+ created_at: DateTime::parse_from_rfc3339(&created_at)?.with_timezone(&Utc),+ worktree_paths,+ remote_connection,+ working_directory: working_directory.map(PathBuf::from),+ },+ next,+ ))+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use gpui::TestAppContext;+ use std::path::Path;++ fn init_test(cx: &mut TestAppContext) {+ cx.update(|cx| {+ TerminalThreadMetadataStore::init_global(cx);+ });+ cx.run_until_parked();+ }++ fn metadata(title: &str, worktree_paths: WorktreePaths) -> TerminalThreadMetadata {+ let now = Utc::now();+ TerminalThreadMetadata {+ terminal_id: TerminalId::new(),+ title: SharedString::from(title.to_string()),+ custom_title: None,+ created_at: now,+ worktree_paths,+ remote_connection: None,+ working_directory: None,+ }+ }++ #[gpui::test]+ async fn test_change_worktree_paths_reindexes_terminal_metadata(cx: &mut TestAppContext) {+ init_test(cx);++ let old_main_paths = PathList::new(&[Path::new("/repo")]);+ let old_folder_paths = PathList::new(&[Path::new("/repo-feature")]);+ let new_main_path = Path::new("/repo");+ let new_folder_path = Path::new("/repo-feature-renamed");+ let new_folder_paths = PathList::new(&[new_folder_path]);+ let metadata = metadata(+ "Dev Server",+ WorktreePaths::from_path_lists(old_main_paths.clone(), old_folder_paths.clone())+ .unwrap(),+ );+ let terminal_id = metadata.terminal_id;++ cx.update(|cx| {+ TerminalThreadMetadataStore::global(cx).update(cx, |store, cx| {+ store.save(metadata, cx);+ });+ });++ cx.update(|cx| {+ TerminalThreadMetadataStore::global(cx).update(cx, |store, cx| {+ store.change_worktree_paths(+ &old_folder_paths,+ None,+ |paths| {+ paths.add_path(new_main_path, new_folder_path);+ paths.remove_folder_path(Path::new("/repo-feature"));+ },+ cx,+ );+ });+ });++ cx.update(|cx| {+ let store = TerminalThreadMetadataStore::global(cx);+ let store = store.read(cx);+ assert!(+ store+ .entries_for_path(&old_folder_paths, None)+ .next()+ .is_none()+ );+ assert_eq!(+ store+ .entries_for_path(&new_folder_paths, None)+ .map(|entry| entry.terminal_id)+ .collect::<Vec<_>>(),+ vec![terminal_id]+ );+ assert_eq!(+ store+ .entry(terminal_id)+ .unwrap()+ .main_worktree_paths()+ .paths(),+ old_main_paths.paths()+ );+ });+ }+}diff --git a/crates/agent_ui/src/test_support.rs b/crates/agent_ui/src/test_support.rsindex 7f4cb59a634..509dfdbb559 100644--- a/crates/agent_ui/src/test_support.rs+++ b/crates/agent_ui/src/test_support.rs@@ -105,6 +105,7 @@ pub fn init_test(cx: &mut TestAppContext) {editor::init(cx);release_channel::init("0.0.0".parse().unwrap(), cx);agent_panel::init(cx);+ crate::terminal_thread_metadata_store::TerminalThreadMetadataStore::init_global(cx);});}diff --git a/crates/agent_ui/src/thread_metadata_store.rs b/crates/agent_ui/src/thread_metadata_store.rsindex 591e65a9d72..9787d3d9d7d 100644--- a/crates/agent_ui/src/thread_metadata_store.rs+++ b/crates/agent_ui/src/thread_metadata_store.rs@@ -844,17 +844,17 @@ impl ThreadMetadataStore {self.in_flight_archives.remove(&thread_id);}- /// Returns `true` if any unarchived thread other than `current_session_id`+ /// Returns `true` if any unarchived thread other than `thread_id`/// references `path` in its folder paths. Used to determine whether a/// worktree can safely be removed from disk.- pub fn path_is_referenced_by_other_unarchived_threads(+ pub fn path_is_referenced_by_unarchived_threads(&self,- thread_id: ThreadId,+ thread_id: Option<ThreadId>,path: &Path,remote_connection: Option<&RemoteConnectionOptions>,) -> bool {self.entries().any(|thread| {- thread.thread_id != thread_id+ Some(thread.thread_id) != thread_id&& !thread.archived&& same_remote_connection_identity(thread.remote_connection.as_ref(),diff --git a/crates/sidebar/src/sidebar.rs b/crates/sidebar/src/sidebar.rsindex 877b37c59e2..735421f858d 100644--- a/crates/sidebar/src/sidebar.rs+++ b/crates/sidebar/src/sidebar.rs@@ -4,6 +4,9 @@ use acp_thread::ThreadStatus;use action_log::DiffStats;use agent_client_protocol::schema as acp;use agent_settings::AgentSettings;+use agent_ui::terminal_thread_metadata_store::{+ TerminalThreadMetadata, TerminalThreadMetadataStore,+};use agent_ui::thread_metadata_store::{ThreadMetadata, ThreadMetadataStore, WorktreePaths, worktree_info_from_thread_paths,};@@ -13,9 +16,9 @@ use agent_ui::threads_archive_view::{fuzzy_match_positions,};use agent_ui::{- AcpThreadImportOnboarding, Agent, AgentPanel, AgentPanelEvent, AgentPanelTerminalInfo,- AgentThreadSource, ArchiveSelectedThread, CrossChannelImportOnboarding, DEFAULT_THREAD_TITLE,- NewThread, TerminalId, ThreadId, ThreadImportModal, channels_with_threads,+ AcpThreadImportOnboarding, Agent, AgentPanel, AgentPanelEvent, AgentThreadSource,+ ArchiveSelectedThread, CrossChannelImportOnboarding, DEFAULT_THREAD_TITLE, NewThread,+ TerminalId, ThreadId, ThreadImportModal, channels_with_threads,import_threads_from_other_channels,};use chrono::{DateTime, Utc};@@ -174,7 +177,7 @@ impl ActiveEntry {.is_some_and(|(a, b)| a == b)}(ActiveEntry::Terminal { terminal_id, .. }, ListEntry::Terminal(terminal)) => {- *terminal_id == terminal.id+ *terminal_id == terminal.metadata.terminal_id}_ => false,}@@ -197,9 +200,9 @@ struct ActiveThreadInfo {enum ThreadEntryWorkspace {Open(Entity<Workspace>),Closed {- /// The paths this thread uses (may point to linked worktrees).+ /// The paths this entry uses (may point to linked worktrees).folder_paths: PathList,- /// The project group this thread belongs to.+ /// The project group this entry belongs to.project_group_key: ProjectGroupKey,},}@@ -235,11 +238,9 @@ struct ThreadEntry {#[derive(Clone)]struct TerminalEntry {- id: TerminalId,- title: SharedString,- workspace: Entity<Workspace>,+ metadata: TerminalThreadMetadata,+ workspace: ThreadEntryWorkspace,worktrees: Vec<ThreadItemWorktreeInfo>,- created_at: DateTime<Utc>,has_notification: bool,highlight_positions: Vec<usize>,}@@ -284,8 +285,8 @@ enum ActivatableEntry {workspace: ThreadEntryWorkspace,},Terminal {- terminal_id: TerminalId,- workspace: Entity<Workspace>,+ metadata: TerminalThreadMetadata,+ workspace: ThreadEntryWorkspace,},}@@ -297,7 +298,7 @@ impl ActivatableEntry {workspace: thread.workspace.clone(),}),ListEntry::Terminal(terminal) => Some(Self::Terminal {- terminal_id: terminal.id,+ metadata: terminal.metadata.clone(),workspace: terminal.workspace.clone(),}),ListEntry::ProjectHeader { .. } => None,@@ -309,6 +310,10 @@ impl ActivatableEntry {Self::Thread {workspace: ThreadEntryWorkspace::Open(workspace),..+ }+ | Self::Terminal {+ workspace: ThreadEntryWorkspace::Open(workspace),+ ..} => (PathList::new(&workspace.read(cx).root_paths(cx)),workspace.read(cx).project_group_key(cx),@@ -320,11 +325,15 @@ impl ActivatableEntry {project_group_key,},..+ }+ | Self::Terminal {+ workspace:+ ThreadEntryWorkspace::Closed {+ folder_paths,+ project_group_key,+ },+ ..} => (folder_paths.clone(), project_group_key.clone()),- Self::Terminal { workspace, .. } => (- PathList::new(&workspace.read(cx).root_paths(cx)),- workspace.read(cx).project_group_key(cx),- ),}}}@@ -348,7 +357,10 @@ impl ListEntry {ThreadEntryWorkspace::Open(ws) => vec![ws.clone()],ThreadEntryWorkspace::Closed { .. } => Vec::new(),},- ListEntry::Terminal(terminal) => vec![terminal.workspace.clone()],+ ListEntry::Terminal(terminal) => match &terminal.workspace {+ ThreadEntryWorkspace::Open(workspace) => vec![workspace.clone()],+ ThreadEntryWorkspace::Closed { .. } => Vec::new(),+ },ListEntry::ProjectHeader { key, .. } => multi_workspace.workspaces_for_project_group(key, cx).unwrap_or_default(),@@ -413,23 +425,52 @@ fn workspace_path_list(workspace: &Entity<Workspace>, cx: &App) -> PathList {PathList::new(&workspace.read(cx).root_paths(cx))}-fn workspace_has_agent_panel_terminals(workspace: &Entity<Workspace>, cx: &App) -> bool {- workspace- .read(cx)- .panel::<AgentPanel>(cx)- .is_some_and(|panel| !panel.read(cx).terminals(cx).is_empty())+fn linked_worktree_path_lists_for_workspaces(+ workspaces: &[Entity<Workspace>],+ cx: &App,+) -> Vec<PathList> {+ let mut linked_worktree_paths = HashSet::new();+ for workspace in workspaces {+ if workspace.read(cx).visible_worktrees(cx).count() != 1 {+ continue;+ }+ for snapshot in root_repository_snapshots(workspace, cx) {+ for linked_worktree in snapshot.linked_worktrees() {+ linked_worktree_paths.insert(linked_worktree.path.clone());+ }+ }+ }++ let mut linked_worktree_paths = linked_worktree_paths.into_iter().collect::<Vec<_>>();+ linked_worktree_paths.sort();+ linked_worktree_paths+ .into_iter()+ .map(|path| PathList::new(std::slice::from_ref(&path)))+ .collect()+}++fn workspace_has_terminal_metadata(workspace: &Entity<Workspace>, cx: &App) -> bool {+ workspace_has_terminal_metadata_except(workspace, None, cx)}-fn workspace_contains_worktree_path(+fn workspace_has_terminal_metadata_except(workspace: &Entity<Workspace>,- worktree_path: &Path,+ except_terminal_id: Option<TerminalId>,cx: &App,) -> bool {- let project = workspace.read(cx).project().clone();- project+ let Some(store) = TerminalThreadMetadataStore::try_global(cx) else {+ return false;+ };+ let path_list = workspace_path_list(workspace, cx);+ let remote_connection = workspace+ .read(cx)+ .project().read(cx)- .visible_worktrees(cx)- .any(|worktree| worktree.read(cx).abs_path().as_ref() == worktree_path)+ .remote_connection_options(cx);+ store+ .read(cx)+ .entries_for_path(&path_list, remote_connection.as_ref())+ .any(|terminal| except_terminal_id != Some(terminal.terminal_id))}#[derive(Clone)]@@ -545,16 +586,6 @@ fn apply_worktree_label_mode(worktrees}-fn terminal_worktree_info<S: std::hash::BuildHasher>(- workspace: &Entity<Workspace>,- branch_by_path: &HashMap<PathBuf, SharedString, S>,- cx: &App,-) -> Vec<ThreadItemWorktreeInfo> {- let project = workspace.read(cx).project().clone();- let worktree_paths = project.read(cx).worktree_paths(cx);- worktree_info_from_thread_paths(&worktree_paths, branch_by_path)-}-/// Shows a [`RemoteConnectionModal`] on the given workspace and establishes/// an SSH connection. Suitable for passing to/// [`MultiWorkspace::find_or_create_workspace`] as the `connect_remote`@@ -668,10 +699,21 @@ impl Sidebar {}).detach();- let workspaces: Vec<_> = multi_workspace.read(cx).workspaces().cloned().collect();+ cx.observe(+ &TerminalThreadMetadataStore::global(cx),+ |this, _store, cx| {+ this.update_entries(cx);+ },+ )+ .detach();++ let deferred_multi_workspace = multi_workspace.downgrade();cx.defer_in(window, move |this, window, cx| {- for workspace in &workspaces {- this.subscribe_to_workspace(workspace, window, cx);+ if let Some(multi_workspace) = deferred_multi_workspace.upgrade() {+ let workspaces: Vec<_> = multi_workspace.read(cx).workspaces().cloned().collect();+ for workspace in &workspaces {+ this.subscribe_to_workspace(workspace, window, cx);+ }}this.update_entries(cx);});@@ -756,7 +798,7 @@ impl Sidebar {this.update_entries(cx);}ProjectEvent::WorktreePathsChanged { old_worktree_paths } => {- this.move_thread_paths(project, old_worktree_paths, cx);+ this.move_entry_paths(project, old_worktree_paths, cx);this.update_entries(cx);}_ => {}@@ -787,10 +829,10 @@ impl Sidebar {cx.subscribe_in(workspace,window,- |this, _workspace, event: &workspace::Event, window, cx| {+ move |this, workspace, event: &workspace::Event, window, cx| {if let workspace::Event::PanelAdded(view) = event {if let Ok(agent_panel) = view.clone().downcast::<AgentPanel>() {- this.subscribe_to_agent_panel(&agent_panel, window, cx);+ this.subscribe_to_agent_panel(workspace, &agent_panel, window, cx);this.update_entries(cx);}}@@ -801,11 +843,11 @@ impl Sidebar {self.observe_docks(workspace, cx);if let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) {- self.subscribe_to_agent_panel(&agent_panel, window, cx);+ self.subscribe_to_agent_panel(workspace, &agent_panel, window, cx);}}- fn move_thread_paths(+ fn move_entry_paths(&mut self,project: &Entity<project::Project>,old_paths: &WorktreePaths,@@ -841,18 +883,27 @@ impl Sidebar {}let remote_connection = project.read(cx).remote_connection_options(cx);+ let apply_path_changes = |paths: &mut WorktreePaths| {+ for (main_path, folder_path) in &added_pairs {+ paths.add_path(main_path, folder_path);+ }+ for path in &removed_folder_paths {+ paths.remove_folder_path(path);+ }+ };ThreadMetadataStore::global(cx).update(cx, |store, store_cx| {store.change_worktree_paths(&old_folder_paths,remote_connection.as_ref(),- |paths| {- for (main_path, folder_path) in &added_pairs {- paths.add_path(main_path, folder_path);- }- for path in &removed_folder_paths {- paths.remove_folder_path(path);- }- },+ &apply_path_changes,+ store_cx,+ );+ });+ TerminalThreadMetadataStore::global(cx).update(cx, |store, store_cx| {+ store.change_worktree_paths(+ &old_folder_paths,+ remote_connection.as_ref(),+ &apply_path_changes,store_cx,);});@@ -860,20 +911,28 @@ impl Sidebar {fn subscribe_to_agent_panel(&mut self,+ workspace: &Entity<Workspace>,agent_panel: &Entity<AgentPanel>,window: &mut Window,cx: &mut Context<Self>,) {+ let workspace = workspace.downgrade();cx.subscribe_in(agent_panel,window,- |this, agent_panel, event: &AgentPanelEvent, _window, cx| match event {+ move |this, agent_panel, event: &AgentPanelEvent, window, cx| match event {AgentPanelEvent::ActiveViewChanged| AgentPanelEvent::ActiveViewFocused| AgentPanelEvent::EntryChanged => {this.sync_active_entry_from_panel(agent_panel, cx);this.update_entries(cx);}+ AgentPanelEvent::TerminalClosed { metadata } => {+ if let Some(workspace) = workspace.upgrade() {+ let workspace = ThreadEntryWorkspace::Open(workspace);+ this.close_terminal(metadata, &workspace, window, cx);+ }+ }AgentPanelEvent::ThreadInteracted { thread_id } => {this.record_thread_interacted(thread_id, cx);this.update_entries(cx);@@ -1136,6 +1195,7 @@ impl Sidebar {let mut current_terminal_ids: HashSet<TerminalId> = HashSet::new();let mut project_header_indices: Vec<usize> = Vec::new();let mut seen_thread_ids: HashSet<agent_ui::ThreadId> = HashSet::new();+ let mut seen_terminal_ids: HashSet<TerminalId> = HashSet::new();let has_open_projects = workspaces.iter()@@ -1156,6 +1216,18 @@ impl Sidebar {};let groups = mw.project_groups(cx);+ let mut live_notified_terminal_ids: HashSet<TerminalId> = HashSet::new();+ for workspace in &workspaces {+ if let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) {+ live_notified_terminal_ids.extend(+ agent_panel+ .read(cx)+ .terminals(cx)+ .into_iter()+ .filter_map(|terminal| terminal.has_notification.then_some(terminal.id)),+ );+ }+ }let mut all_paths: Vec<PathBuf> = groups.iter()@@ -1195,18 +1267,101 @@ impl Sidebar {for group in &groups {let group_key = &group.key;let group_workspaces = &group.workspaces;- let terminals: Vec<TerminalEntry> = group_workspaces++ let workspace_by_path_list: HashMap<PathList, &Entity<Workspace>> = group_workspaces.iter()- .flat_map(|workspace| {- terminal_entries_for_workspace(workspace, &branch_by_path, cx)- })+ .map(|ws| (workspace_path_list(ws, cx), ws)).collect();- current_terminal_ids.extend(terminals.iter().map(|terminal| terminal.id));- notified_terminals.extend(+ let resolve_workspace = |folder_paths: &PathList| -> ThreadEntryWorkspace {+ workspace_by_path_list+ .get(folder_paths)+ .map(|ws| ThreadEntryWorkspace::Open((*ws).clone()))+ .unwrap_or_else(|| ThreadEntryWorkspace::Closed {+ folder_paths: folder_paths.clone(),+ project_group_key: group_key.clone(),+ })+ };+ let linked_worktree_path_lists =+ linked_worktree_path_lists_for_workspaces(group_workspaces, cx);+ let make_terminal_entry =+ |metadata: TerminalThreadMetadata, workspace: ThreadEntryWorkspace| {+ let worktrees =+ worktree_info_from_thread_paths(&metadata.worktree_paths, &branch_by_path);+ let has_notification =+ live_notified_terminal_ids.contains(&metadata.terminal_id);+ TerminalEntry {+ metadata,+ workspace,+ worktrees,+ has_notification,+ highlight_positions: Vec::new(),+ }+ };++ let mut terminals = Vec::new();+ let terminal_store = TerminalThreadMetadataStore::global(cx);+ let group_host = group_key.host();+ let mut push_terminal_metadata =+ |metadata: TerminalThreadMetadata, workspace: ThreadEntryWorkspace| {+ if !seen_terminal_ids.insert(metadata.terminal_id) {+ return;+ }+ terminals.push(make_terminal_entry(metadata, workspace));+ };+ for row in terminal_store+ .read(cx)+ .entries_for_main_worktree_path(group_key.path_list(), group_host.as_ref())+ .cloned()+ {+ let workspace = resolve_workspace(row.folder_paths());+ push_terminal_metadata(row, workspace);+ }+ for row in terminal_store+ .read(cx)+ .entries_for_path(group_key.path_list(), group_host.as_ref())+ .cloned()+ {+ let workspace = resolve_workspace(row.folder_paths());+ push_terminal_metadata(row, workspace);+ }+ for ws in group_workspaces {+ let ws_paths = workspace_path_list(ws, cx);+ if ws_paths.paths().is_empty() {+ continue;+ }+ for row in terminal_store+ .read(cx)+ .entries_for_path(&ws_paths, group_host.as_ref())+ .cloned()+ {+ push_terminal_metadata(row, ThreadEntryWorkspace::Open(ws.clone()));+ }+ }+ for worktree_path_list in &linked_worktree_path_lists {+ for row in terminal_store+ .read(cx)+ .entries_for_path(worktree_path_list, group_host.as_ref())+ .cloned()+ {+ push_terminal_metadata(+ row,+ ThreadEntryWorkspace::Closed {+ folder_paths: worktree_path_list.clone(),+ project_group_key: group_key.clone(),+ },+ );+ }+ }+ current_terminal_ids.extend(terminals.iter()- .filter_map(|terminal| terminal.has_notification.then_some(terminal.id)),+ .map(|terminal| terminal.metadata.terminal_id),);+ notified_terminals.extend(terminals.iter().filter_map(|terminal| {+ terminal+ .has_notification+ .then_some(terminal.metadata.terminal_id)+ }));if group_key.path_list().paths().is_empty() {continue;}@@ -1243,29 +1398,6 @@ impl Sidebar {}).collect();- // Build a lookup from workspace root paths to their workspace- // entity, used to assign ThreadEntryWorkspace::Open for threads- // whose folder_paths match an open workspace.- let workspace_by_path_list: HashMap<PathList, &Entity<Workspace>> =- group_workspaces- .iter()- .map(|ws| (workspace_path_list(ws, cx), ws))- .collect();-- // Resolve a ThreadEntryWorkspace for a thread row. If any open- // workspace's root paths match the thread's folder_paths, use- // Open; otherwise use Closed.- let resolve_workspace = |row: &ThreadMetadata| -> ThreadEntryWorkspace {- workspace_by_path_list- .get(row.folder_paths())- .map(|ws| ThreadEntryWorkspace::Open((*ws).clone()))- .unwrap_or_else(|| ThreadEntryWorkspace::Closed {- folder_paths: row.folder_paths().clone(),- project_group_key: group_key.clone(),- })- };-- // Build a ThreadEntry from a metadata row.let make_thread_entry =|row: ThreadMetadata, workspace: ThreadEntryWorkspace| -> ThreadEntry {let (icon, icon_from_external_svg) = resolve_agent_icon(&row.agent_id);@@ -1300,7 +1432,7 @@ impl Sidebar {if !seen_thread_ids.insert(row.thread_id) {continue;}- let workspace = resolve_workspace(&row);+ let workspace = resolve_workspace(row.folder_paths());threads.push(make_thread_entry(row, workspace));}@@ -1316,7 +1448,7 @@ impl Sidebar {if !seen_thread_ids.insert(row.thread_id) {continue;}- let workspace = resolve_workspace(&row);+ let workspace = resolve_workspace(row.folder_paths());threads.push(make_thread_entry(row, workspace));}@@ -1351,23 +1483,11 @@ impl Sidebar {}}- // Load any legacy threads for any single linked wortree of this project group.- let mut linked_worktree_paths = HashSet::new();- for workspace in group_workspaces {- if workspace.read(cx).visible_worktrees(cx).count() != 1 {- continue;- }- for snapshot in root_repository_snapshots(workspace, cx) {- for linked_worktree in snapshot.linked_worktrees() {- linked_worktree_paths.insert(linked_worktree.path.clone());- }- }- }- for path in linked_worktree_paths {- let worktree_path_list = PathList::new(std::slice::from_ref(&path));+ // Load any legacy threads for any single linked worktree of this project group.+ for worktree_path_list in &linked_worktree_path_lists {for row in thread_store.read(cx)- .entries_for_path(&worktree_path_list, group_host.as_ref())+ .entries_for_path(worktree_path_list, group_host.as_ref()).cloned(){if !seen_thread_ids.insert(row.thread_id) {@@ -1512,7 +1632,8 @@ impl Sidebar {let mut matched_terminals: Vec<TerminalEntry> = Vec::new();for mut terminal in terminals {let mut terminal_matched = false;- if let Some(positions) = fuzzy_match_positions(&query, &terminal.title) {+ if let Some(positions) = fuzzy_match_positions(&query, &terminal.metadata.title)+ {terminal.highlight_positions = positions;terminal_matched = true;}@@ -2626,8 +2747,9 @@ impl Sidebar {}}ListEntry::Terminal(terminal) => {+ let metadata = terminal.metadata.clone();let workspace = terminal.workspace.clone();- self.activate_terminal(&workspace, terminal.id, false, window, cx);+ self.activate_terminal_entry(metadata, workspace, false, window, cx);}}}@@ -3313,24 +3435,120 @@ impl Sidebar {true}ActivatableEntry::Terminal {- terminal_id,+ metadata,workspace,} => {- let Some(workspace) = self- .find_workspace_in_current_window(cx, |candidate, _| candidate == workspace)- else {- return false;- };- self.activate_terminal(&workspace, *terminal_id, false, window, cx);+ self.activate_terminal_entry(+ metadata.clone(),+ workspace.clone(),+ false,+ window,+ cx,+ );true}}}- fn activate_terminal(+ fn activate_terminal_entry(&mut self,+ metadata: TerminalThreadMetadata,+ workspace: ThreadEntryWorkspace,+ retain: bool,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ match workspace {+ ThreadEntryWorkspace::Open(workspace) => {+ self.activate_terminal_in_workspace(&workspace, metadata, retain, window, cx);+ }+ ThreadEntryWorkspace::Closed {+ folder_paths,+ project_group_key,+ } => {+ self.open_workspace_and_activate_terminal(+ metadata,+ folder_paths,+ &project_group_key,+ window,+ cx,+ );+ }+ }+ }++ fn load_agent_terminal_in_workspace(workspace: &Entity<Workspace>,- terminal_id: TerminalId,+ metadata: &TerminalThreadMetadata,+ focus: bool,+ window: &mut Window,+ cx: &mut App,+ ) {+ let restore_terminal = |agent_panel: Entity<AgentPanel>,+ metadata: &TerminalThreadMetadata,+ focus: bool,+ workspace: Option<&Workspace>,+ window: &mut Window,+ cx: &mut App| {+ agent_panel.update(cx, |panel, cx| {+ panel.restore_terminal(+ metadata.clone(),+ focus,+ AgentThreadSource::Sidebar,+ workspace,+ window,+ cx,+ );+ });+ };++ let mut existing_panel = None;+ workspace.update(cx, |workspace, cx| {+ if let Some(panel) = workspace.panel::<AgentPanel>(cx) {+ existing_panel = Some(panel);+ }+ });++ if let Some(agent_panel) = existing_panel {+ restore_terminal(agent_panel, metadata, focus, None, window, cx);+ workspace.update(cx, |workspace, cx| {+ if focus {+ workspace.focus_panel::<AgentPanel>(window, cx);+ } else {+ workspace.reveal_panel::<AgentPanel>(window, cx);+ }+ });+ return;+ }++ let workspace = workspace.downgrade();+ let metadata = metadata.clone();+ let mut async_window_cx = window.to_async(cx);+ cx.spawn(async move |_cx| {+ let panel = AgentPanel::load(workspace.clone(), async_window_cx.clone()).await?;++ workspace.update_in(&mut async_window_cx, |workspace, window, cx| {+ let panel = workspace.panel::<AgentPanel>(cx).unwrap_or_else(|| {+ workspace.add_panel(panel.clone(), window, cx);+ panel.clone()+ });+ restore_terminal(panel, &metadata, focus, Some(workspace), window, cx);+ if focus {+ workspace.focus_panel::<AgentPanel>(window, cx);+ } else {+ workspace.reveal_panel::<AgentPanel>(window, cx);+ }+ })?;++ anyhow::Ok(())+ })+ .detach_and_log_err(cx);+ }++ fn activate_terminal_in_workspace(+ &mut self,+ workspace: &Entity<Workspace>,+ metadata: TerminalThreadMetadata,retain: bool,window: &mut Window,cx: &mut Context<Self>,@@ -3339,6 +3557,7 @@ impl Sidebar {return;};+ let terminal_id = metadata.terminal_id;self.record_terminal_access(terminal_id);self.active_entry = Some(ActiveEntry::Terminal {terminal_id,@@ -3352,54 +3571,498 @@ impl Sidebar {}});- workspace.update(cx, |workspace, cx| {- if let Some(panel) = workspace.panel::<AgentPanel>(cx) {- panel.update(cx, |panel, cx| {- panel.activate_terminal(terminal_id, true, window, cx);- });- }- workspace.focus_panel::<AgentPanel>(window, cx);- });+ Self::load_agent_terminal_in_workspace(workspace, &metadata, true, window, cx);self.update_entries(cx);}- fn close_terminal(+ fn open_workspace_and_activate_terminal(&mut self,- workspace: &Entity<Workspace>,- terminal_id: TerminalId,+ metadata: TerminalThreadMetadata,+ folder_paths: PathList,+ project_group_key: &ProjectGroupKey,window: &mut Window,cx: &mut Context<Self>,) {- let is_active = self- .active_entry- .as_ref()- .is_some_and(|entry| entry.is_active_terminal(terminal_id));- let neighbor = self- .contents- .entries- .iter()- .position(|entry| matches!(entry, ListEntry::Terminal(terminal) if terminal.id == terminal_id))- .and_then(|position| {- self.neighboring_activatable_entry(position)- });+ let Some(multi_workspace) = self.multi_workspace.upgrade() else {+ return;+ };- // Closing from the sidebar must not steal focus, since the row's- // workspace may not be the active workspace.- workspace.update(cx, |workspace, cx| {- if let Some(panel) = workspace.panel::<AgentPanel>(cx) {- panel.update(cx, |panel, cx| {- panel.close_terminal(terminal_id, window, cx);- });- }+ let host = project_group_key.host();+ let provisional_key = Some(project_group_key.clone());+ let active_workspace = multi_workspace.read(cx).workspace().clone();+ let modal_workspace = active_workspace.clone();++ let open_task = multi_workspace.update(cx, |this, cx| {+ this.find_or_create_workspace(+ folder_paths,+ host,+ provisional_key,+ |options, window, cx| connect_remote(active_workspace, options, window, cx),+ &[],+ None,+ OpenMode::Activate,+ window,+ cx,+ )});- if is_active {- self.active_entry = None;- if neighbor- .as_ref()- .is_some_and(|neighbor| self.activate_entry(neighbor, window, cx))- {+ cx.spawn_in(window, async move |this, cx| {+ let result = open_task.await;+ remote_connection::dismiss_connection_modal(&modal_workspace, cx);+ let workspace = result?;+ this.update_in(cx, |this, window, cx| {+ this.activate_terminal_in_workspace(&workspace, metadata, false, window, cx);+ })?;+ anyhow::Ok(())+ })+ .detach_and_log_err(cx);+ }++ fn should_load_closed_workspace_for_archive(+ folder_paths: &PathList,+ project_group_key: &ProjectGroupKey,+ remote_connection: Option<&RemoteConnectionOptions>,+ except_thread_id: Option<ThreadId>,+ except_terminal_id: Option<TerminalId>,+ cx: &App,+ ) -> bool {+ if folder_paths.is_empty() || folder_paths == project_group_key.path_list() {+ return false;+ }++ let thread_store = ThreadMetadataStore::global(cx);+ let thread_store = thread_store.read(cx);+ if folder_paths.ordered_paths().any(|path| {+ thread_store.path_is_referenced_by_unarchived_threads(+ except_thread_id,+ path,+ remote_connection,+ )+ }) {+ return false;+ }++ TerminalThreadMetadataStore::try_global(cx).is_none_or(|terminal_store| {+ let terminal_store = terminal_store.read(cx);+ !folder_paths.ordered_paths().any(|path| {+ terminal_store.path_is_referenced_by_terminal(+ except_terminal_id,+ path,+ remote_connection,+ )+ })+ })+ }++ async fn wait_for_archive_workspace_metadata(+ workspace: &Entity<Workspace>,+ cx: &mut gpui::AsyncApp,+ ) {+ let scans_complete =+ workspace.read_with(cx, |workspace, cx| workspace.worktree_scans_complete(cx));+ scans_complete.await;++ let project = workspace.read_with(cx, |workspace, _| workspace.project().clone());+ let barriers = project.update(cx, |project, cx| {+ let repositories = project+ .repositories(cx)+ .values()+ .cloned()+ .collect::<Vec<_>>();+ repositories+ .into_iter()+ .map(|repository| repository.update(cx, |repository, _| repository.barrier()))+ .collect::<Vec<_>>()+ });+ for barrier in barriers {+ let result: anyhow::Result<()> = barrier.await.map_err(|_| {+ anyhow::anyhow!("git repository barrier canceled while archiving worktree")+ });+ result.log_err();+ }+ }++ fn open_workspace_for_archive(+ &mut self,+ folder_paths: PathList,+ project_group_key: ProjectGroupKey,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) -> Option<(Task<anyhow::Result<Entity<Workspace>>>, Entity<Workspace>)> {+ let Some(multi_workspace) = self.multi_workspace.upgrade() else {+ return None;+ };++ let host = project_group_key.host();+ let active_workspace = multi_workspace.read(cx).workspace().clone();+ let modal_workspace = active_workspace.clone();++ let open_task = multi_workspace.update(cx, |this, cx| {+ this.find_or_create_workspace(+ folder_paths,+ host,+ Some(project_group_key),+ |options, window, cx| connect_remote(active_workspace, options, window, cx),+ &[],+ None,+ OpenMode::Add,+ window,+ cx,+ )+ });++ Some((open_task, modal_workspace))+ }++ fn open_workspace_and_archive_thread(+ &mut self,+ session_id: acp::SessionId,+ folder_paths: PathList,+ project_group_key: ProjectGroupKey,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ let Some((open_task, modal_workspace)) =+ self.open_workspace_for_archive(folder_paths, project_group_key, window, cx)+ else {+ return;+ };++ cx.spawn_in(window, async move |this, cx| {+ let result = open_task.await;+ remote_connection::dismiss_connection_modal(&modal_workspace, cx);+ let workspace = result?;+ Self::wait_for_archive_workspace_metadata(&workspace, cx).await;++ this.update_in(cx, |this, window, cx| {+ this.update_entries(cx);+ this.archive_thread(&session_id, window, cx);+ })?;+ anyhow::Ok(())+ })+ .detach_and_log_err(cx);+ }++ fn open_workspace_and_close_terminal(+ &mut self,+ metadata: TerminalThreadMetadata,+ folder_paths: PathList,+ project_group_key: ProjectGroupKey,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ let Some((open_task, modal_workspace)) =+ self.open_workspace_for_archive(folder_paths, project_group_key, window, cx)+ else {+ return;+ };++ cx.spawn_in(window, async move |this, cx| {+ let result = open_task.await;+ remote_connection::dismiss_connection_modal(&modal_workspace, cx);+ let workspace = result?;+ Self::wait_for_archive_workspace_metadata(&workspace, cx).await;++ this.update_in(cx, |this, window, cx| {+ let workspace = ThreadEntryWorkspace::Open(workspace);+ this.close_terminal(&metadata, &workspace, window, cx);+ })?;+ anyhow::Ok(())+ })+ .detach_and_log_err(cx);+ }++ fn close_terminal(+ &mut self,+ metadata: &TerminalThreadMetadata,+ workspace: &ThreadEntryWorkspace,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ if let ThreadEntryWorkspace::Closed {+ folder_paths,+ project_group_key,+ } = workspace+ && Self::should_load_closed_workspace_for_archive(+ folder_paths,+ project_group_key,+ metadata.remote_connection.as_ref(),+ None,+ Some(metadata.terminal_id),+ cx,+ )+ {+ self.open_workspace_and_close_terminal(+ metadata.clone(),+ folder_paths.clone(),+ project_group_key.clone(),+ window,+ cx,+ );+ return;+ }++ let terminal_id = metadata.terminal_id;+ let is_active = self+ .active_entry+ .as_ref()+ .is_some_and(|entry| entry.is_active_terminal(terminal_id));+ let neighbor = self+ .contents+ .entries+ .iter()+ .position(|entry| {+ matches!(+ entry,+ ListEntry::Terminal(terminal)+ if terminal.metadata.terminal_id == terminal_id+ )+ })+ .and_then(|position| self.neighboring_activatable_entry(position));++ let terminal_folder_paths = metadata.folder_paths().clone();+ let roots_to_archive = {+ let mut workspaces = self+ .multi_workspace+ .upgrade()+ .map(|multi_workspace| {+ multi_workspace+ .read(cx)+ .workspaces()+ .cloned()+ .collect::<Vec<_>>()+ })+ .unwrap_or_default();+ for workspace in thread_worktree_archive::all_open_workspaces(cx) {+ if !workspaces.contains(&workspace) {+ workspaces.push(workspace);+ }+ }++ metadata+ .folder_paths()+ .ordered_paths()+ .filter_map(|path| {+ thread_worktree_archive::build_root_plan(+ path,+ metadata.remote_connection.as_ref(),+ &workspaces,+ cx,+ )+ })+ .filter(|plan| {+ let store = ThreadMetadataStore::global(cx);+ let store = store.read(cx);+ !store.path_is_referenced_by_unarchived_threads(+ None,+ &plan.root_path,+ metadata.remote_connection.as_ref(),+ )+ })+ .filter(|root| {+ TerminalThreadMetadataStore::try_global(cx).is_none_or(|terminal_store| {+ !terminal_store.read(cx).path_is_referenced_by_terminal(+ Some(terminal_id),+ root.root_path.as_path(),+ metadata.remote_connection.as_ref(),+ )+ })+ })+ .collect::<Vec<_>>()+ };++ let workspace_to_remove = if terminal_folder_paths.is_empty() {+ None+ } else {+ let remaining = ThreadMetadataStore::global(cx)+ .read(cx)+ .entries_for_path(&terminal_folder_paths, metadata.remote_connection.as_ref())+ .count();++ if remaining > 0 {+ None+ } else {+ let workspace = self.multi_workspace.upgrade().and_then(|multi_workspace| {+ multi_workspace+ .read(cx)+ .workspace_for_paths(&terminal_folder_paths, None, cx)+ });++ workspace.and_then(|workspace| {+ if workspace_has_terminal_metadata_except(&workspace, Some(terminal_id), cx) {+ return None;+ }++ let group_key = workspace.read(cx).project_group_key(cx);+ (group_key.path_list() != &terminal_folder_paths).then_some(workspace)+ })+ }+ };++ let mut workspaces_to_remove: Vec<Entity<Workspace>> =+ workspace_to_remove.into_iter().collect();+ let close_item_tasks = self.close_items_for_archived_worktrees(+ &roots_to_archive,+ &mut workspaces_to_remove,+ window,+ cx,+ );++ if !workspaces_to_remove.is_empty() {+ let multi_workspace = self.multi_workspace.upgrade().unwrap();+ let terminal_workspace_removed = matches!(+ workspace,+ ThreadEntryWorkspace::Open(workspace) if workspaces_to_remove.contains(workspace)+ );+ let (fallback_paths, project_group_key) = neighbor+ .as_ref()+ .map(|neighbor| neighbor.project_location(cx))+ .unwrap_or_else(|| {+ workspaces_to_remove+ .first()+ .map(|workspace| {+ let key = workspace.read(cx).project_group_key(cx);+ (key.path_list().clone(), key)+ })+ .unwrap_or_default()+ });++ let excluded = workspaces_to_remove.clone();+ let remove_task = multi_workspace.update(cx, |multi_workspace, cx| {+ multi_workspace.remove(+ workspaces_to_remove,+ move |this, window, cx| {+ let active_workspace = this.workspace().clone();+ this.find_or_create_workspace(+ fallback_paths,+ project_group_key.host(),+ Some(project_group_key),+ |options, window, cx| {+ connect_remote(active_workspace, options, window, cx)+ },+ &excluded,+ None,+ OpenMode::Activate,+ window,+ cx,+ )+ },+ window,+ cx,+ )+ });++ let metadata = metadata.clone();+ let workspace = workspace.clone();+ cx.spawn_in(window, async move |this, cx| {+ if !remove_task.await? {+ return anyhow::Ok(());+ }++ for task in close_item_tasks {+ let result: anyhow::Result<()> = task.await;+ result.log_err();+ }++ this.update_in(cx, |this, window, cx| {+ // If the terminal's workspace has already been removed,+ // don't synthesize a fallback draft in the detached+ // AgentPanel.+ this.close_terminal_entry(+ &metadata,+ &workspace,+ is_active,+ neighbor.as_ref(),+ !terminal_workspace_removed,+ roots_to_archive,+ window,+ cx,+ );+ })?;+ anyhow::Ok(())+ })+ .detach_and_log_err(cx);+ } else if !close_item_tasks.is_empty() {+ let metadata = metadata.clone();+ let workspace = workspace.clone();+ cx.spawn_in(window, async move |this, cx| {+ for task in close_item_tasks {+ let result: anyhow::Result<()> = task.await;+ result.log_err();+ }++ this.update_in(cx, |this, window, cx| {+ this.close_terminal_entry(+ &metadata,+ &workspace,+ is_active,+ neighbor.as_ref(),+ true,+ roots_to_archive,+ window,+ cx,+ );+ })?;+ anyhow::Ok(())+ })+ .detach_and_log_err(cx);+ } else {+ self.close_terminal_entry(+ metadata,+ workspace,+ is_active,+ neighbor.as_ref(),+ true,+ roots_to_archive,+ window,+ cx,+ );+ }+ }++ fn close_terminal_entry(+ &mut self,+ metadata: &TerminalThreadMetadata,+ workspace: &ThreadEntryWorkspace,+ is_active: bool,+ neighbor: Option<&ActivatableEntry>,+ activate_panel_draft: bool,+ roots_to_archive: Vec<thread_worktree_archive::RootPlan>,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ let terminal_id = metadata.terminal_id;++ // Closing from the sidebar must not steal focus, since the row's+ // workspace may not be the active workspace.+ if let ThreadEntryWorkspace::Open(workspace) = workspace {+ workspace.update(cx, |workspace, cx| {+ if let Some(panel) = workspace.panel::<AgentPanel>(cx) {+ panel.update(cx, |panel, cx| {+ if activate_panel_draft {+ panel.close_terminal(terminal_id, window, cx);+ } else {+ panel.close_terminal_without_activating_draft(terminal_id, window, cx);+ }+ });+ }+ });+ }+ if let Some(store) = TerminalThreadMetadataStore::try_global(cx) {+ store.update(cx, |store, cx| {+ store.delete(terminal_id, cx);+ });+ }++ self.start_detached_archive_worktree_task(roots_to_archive, cx);++ if is_active {+ self.active_entry = None;+ if neighbor+ .as_ref()+ .is_some_and(|neighbor| self.activate_entry(neighbor, window, cx))+ {return;}self.sync_active_entry_from_active_workspace(cx);@@ -3407,6 +4070,84 @@ impl Sidebar {self.update_entries(cx);}+ fn close_items_for_archived_worktrees(+ &self,+ roots_to_archive: &[thread_worktree_archive::RootPlan],+ workspaces_to_remove: &mut Vec<Entity<Workspace>>,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) -> Vec<Task<anyhow::Result<()>>> {+ if roots_to_archive.is_empty() {+ return Vec::new();+ }++ let archive_paths: HashSet<&Path> = roots_to_archive+ .iter()+ .map(|root| root.root_path.as_path())+ .collect();++ let mut mixed_workspaces: Vec<(Entity<Workspace>, Vec<WorktreeId>)> = Vec::new();++ if let Some(multi_workspace) = self.multi_workspace.upgrade() {+ let all_workspaces: Vec<_> = multi_workspace.read(cx).workspaces().cloned().collect();++ for workspace in all_workspaces {+ if workspaces_to_remove.contains(&workspace) {+ continue;+ }++ let project = workspace.read(cx).project().read(cx);+ let visible_worktrees: Vec<_> = project+ .visible_worktrees(cx)+ .map(|worktree| (worktree.read(cx).id(), worktree.read(cx).abs_path()))+ .collect();++ let archived_worktree_ids: Vec<WorktreeId> = visible_worktrees+ .iter()+ .filter(|(_, path)| archive_paths.contains(path.as_ref()))+ .map(|(id, _)| *id)+ .collect();++ if archived_worktree_ids.is_empty() {+ continue;+ }++ if visible_worktrees.len() == archived_worktree_ids.len() {+ workspaces_to_remove.push(workspace);+ } else {+ mixed_workspaces.push((workspace, archived_worktree_ids));+ }+ }+ }++ let mut close_item_tasks = Vec::new();+ for (workspace, archived_worktree_ids) in &mixed_workspaces {+ let panes: Vec<_> = workspace.read(cx).panes().to_vec();+ for pane in panes {+ let items_to_close: Vec<EntityId> = pane+ .read(cx)+ .items()+ .filter(|item| {+ item.project_path(cx)+ .is_some_and(|pp| archived_worktree_ids.contains(&pp.worktree_id))+ })+ .map(|item| item.item_id())+ .collect();++ if !items_to_close.is_empty() {+ let task = pane.update(cx, |pane, cx| {+ pane.close_items(window, cx, SaveIntent::Close, &|item_id| {+ items_to_close.contains(&item_id)+ })+ });+ close_item_tasks.push(task);+ }+ }+ }++ close_item_tasks+ }+fn archive_thread(&mut self,session_id: &acp::SessionId,@@ -3433,6 +4174,41 @@ impl Sidebar {.as_ref().map(|workspace| PathList::new(&workspace.read(cx).root_paths(cx)))});+ let thread_entry_workspace = self.contents.entries.iter().find_map(|entry| match entry {+ ListEntry::Thread(thread) => thread_id+ .map_or_else(+ || thread.metadata.session_id.as_ref() == Some(session_id),+ |tid| thread.metadata.thread_id == tid,+ )+ .then(|| thread.workspace.clone()),+ _ => None,+ });++ if let (+ Some(metadata),+ Some(ThreadEntryWorkspace::Closed {+ folder_paths,+ project_group_key,+ }),+ ) = (metadata.as_ref(), thread_entry_workspace)+ && Self::should_load_closed_workspace_for_archive(+ &folder_paths,+ &project_group_key,+ metadata.remote_connection.as_ref(),+ Some(metadata.thread_id),+ None,+ cx,+ )+ {+ self.open_workspace_and_archive_thread(+ session_id.clone(),+ folder_paths,+ project_group_key,+ window,+ cx,+ );+ return;+ }// Compute which linked worktree roots should be archived from disk if// this thread is archived. This must happen before we remove any@@ -3471,23 +4247,20 @@ impl Sidebar {}).filter(|plan| {thread_id.map_or(true, |tid| {- !store- .read(cx)- .path_is_referenced_by_other_unarchived_threads(- tid,- &plan.root_path,- metadata.remote_connection.as_ref(),- )+ !store.read(cx).path_is_referenced_by_unarchived_threads(+ Some(tid),+ &plan.root_path,+ metadata.remote_connection.as_ref(),+ )})}).filter(|root| {- !workspaces.iter().any(|workspace| {- workspace_has_agent_panel_terminals(workspace, cx)- && workspace_contains_worktree_path(- workspace,- root.root_path.as_path(),- cx,- )+ TerminalThreadMetadataStore::try_global(cx).is_none_or(|terminal_store| {+ !terminal_store.read(cx).path_is_referenced_by_terminal(+ None,+ root.root_path.as_path(),+ metadata.remote_connection.as_ref(),+ )})}).collect::<Vec<_>>()@@ -3528,7 +4301,7 @@ impl Sidebar {.read(cx).workspace_for_paths(folder_paths, None, cx)?;- if workspace_has_agent_panel_terminals(&workspace, cx) {+ if workspace_has_terminal_metadata(&workspace, cx) {return None;}@@ -3547,74 +4320,12 @@ impl Sidebar {// dropped without destroying the user's workspace layout.let mut workspaces_to_remove: Vec<Entity<Workspace>> =workspace_to_remove.into_iter().collect();- let mut close_item_tasks: Vec<Task<anyhow::Result<()>>> = Vec::new();-- let archive_paths: HashSet<&Path> = roots_to_archive- .iter()- .map(|root| root.root_path.as_path())- .collect();-- // Classify workspaces into "exclusive" (all worktrees archived)- // and "mixed" (some worktrees archived, some not).- let mut mixed_workspaces: Vec<(Entity<Workspace>, Vec<WorktreeId>)> = Vec::new();-- if let Some(multi_workspace) = self.multi_workspace.upgrade() {- let all_workspaces: Vec<_> = multi_workspace.read(cx).workspaces().cloned().collect();-- for workspace in all_workspaces {- if workspaces_to_remove.contains(&workspace) {- continue;- }-- let project = workspace.read(cx).project().read(cx);- let visible_worktrees: Vec<_> = project- .visible_worktrees(cx)- .map(|wt| (wt.read(cx).id(), wt.read(cx).abs_path()))- .collect();-- let archived_worktree_ids: Vec<WorktreeId> = visible_worktrees- .iter()- .filter(|(_, path)| archive_paths.contains(path.as_ref()))- .map(|(id, _)| *id)- .collect();-- if archived_worktree_ids.is_empty() {- continue;- }-- if visible_worktrees.len() == archived_worktree_ids.len() {- workspaces_to_remove.push(workspace);- } else {- mixed_workspaces.push((workspace, archived_worktree_ids));- }- }- }-- // For mixed workspaces, close only items belonging to the- // worktrees being archived.- for (workspace, archived_worktree_ids) in &mixed_workspaces {- let panes: Vec<_> = workspace.read(cx).panes().to_vec();- for pane in panes {- let items_to_close: Vec<EntityId> = pane- .read(cx)- .items()- .filter(|item| {- item.project_path(cx)- .is_some_and(|pp| archived_worktree_ids.contains(&pp.worktree_id))- })- .map(|item| item.item_id())- .collect();-- if !items_to_close.is_empty() {- let task = pane.update(cx, |pane, cx| {- pane.close_items(window, cx, SaveIntent::Close, &|item_id| {- items_to_close.contains(&item_id)- })- });- close_item_tasks.push(task);- }- }- }+ let close_item_tasks = self.close_items_for_archived_worktrees(+ &roots_to_archive,+ &mut workspaces_to_remove,+ window,+ cx,+ );if !workspaces_to_remove.is_empty() {let multi_workspace = self.multi_workspace.upgrade().unwrap();@@ -3853,6 +4564,29 @@ impl Sidebar {Some((task, cancel_tx))}+ fn start_detached_archive_worktree_task(+ &self,+ roots: Vec<thread_worktree_archive::RootPlan>,+ cx: &mut Context<Self>,+ ) {+ if roots.is_empty() {+ return;+ }++ let (cancel_tx, cancel_rx) = async_channel::bounded::<()>(1);+ cx.spawn(async move |_this, cx| {+ let outcome = Self::archive_worktree_roots(roots, cancel_rx, cx).await;+ drop(cancel_tx);+ match outcome {+ Ok(ArchiveWorktreeOutcome::Success | ArchiveWorktreeOutcome::Cancelled) => {}+ Err(error) => {+ log::error!("Failed to archive worktree after closing terminal: {error:#}");+ }+ }+ })+ .detach();+ }+async fn archive_worktree_roots(roots: Vec<thread_worktree_archive::RootPlan>,cancel_rx: async_channel::Receiver<()>,@@ -3945,9 +4679,9 @@ impl Sidebar {}}Some(ListEntry::Terminal(terminal)) => {+ let metadata = terminal.metadata.clone();let workspace = terminal.workspace.clone();- let terminal_id = terminal.id;- self.close_terminal(&workspace, terminal_id, window, cx);+ self.close_terminal(&metadata, &workspace, window, cx);}_ => {}}@@ -3982,7 +4716,7 @@ impl Sidebar {fn display_time(entry: &ListEntry) -> DateTime<Utc> {match entry {ListEntry::Thread(thread) => Sidebar::thread_display_time(&thread.metadata),- ListEntry::Terminal(terminal) => terminal.created_at,+ ListEntry::Terminal(terminal) => terminal.metadata.created_at,ListEntry::ProjectHeader { .. } => unreachable!(),}}@@ -4019,9 +4753,9 @@ impl Sidebar {.unwrap_or(entry.metadata.updated_at),ThreadSwitcherEntry::Terminal(entry) => self.terminal_last_accessed- .get(&entry.terminal_id)+ .get(&entry.metadata.terminal_id).copied()- .unwrap_or(entry.created_at),+ .unwrap_or(entry.metadata.created_at),};// .reverse() = most recent first@@ -4086,10 +4820,9 @@ impl Sidebar {}ListEntry::Terminal(terminal) => {let timestamp: SharedString =- format_history_entry_timestamp(terminal.created_at).into();+ format_history_entry_timestamp(terminal.metadata.created_at).into();Some(ThreadSwitcherEntry::Terminal(ThreadSwitcherTerminalEntry {- terminal_id: terminal.id,- title: terminal.title.clone(),+ metadata: terminal.metadata.clone(),workspace: terminal.workspace.clone(),project_name: current_header_label.clone(),worktrees: terminal@@ -4101,8 +4834,9 @@ impl Sidebar {wt}).collect(),- created_at: terminal.created_at,- notified: self.contents.is_terminal_notified(terminal.id),+ notified: self+ .contents+ .is_terminal_notified(terminal.metadata.terminal_id),timestamp,}))}@@ -4158,27 +4892,22 @@ impl Sidebar {Self::load_agent_thread_in_workspace(workspace, metadata, false, window, cx);}ThreadSwitcherSelection::Terminal {- terminal_id,+ metadata,workspace,} => {- if let Some(multi_workspace) = self.multi_workspace.upgrade() {- multi_workspace.update(cx, |multi_workspace, cx| {- multi_workspace.activate(workspace.clone(), None, window, cx);- });- }- self.active_entry = Some(ActiveEntry::Terminal {- terminal_id: *terminal_id,- workspace: workspace.clone(),- });- self.update_entries(cx);- workspace.update(cx, |workspace, cx| {- if let Some(panel) = workspace.panel::<AgentPanel>(cx) {- panel.update(cx, |panel, cx| {- panel.activate_terminal(*terminal_id, false, window, cx);+ if let ThreadEntryWorkspace::Open(workspace) = workspace {+ if let Some(multi_workspace) = self.multi_workspace.upgrade() {+ multi_workspace.update(cx, |multi_workspace, cx| {+ multi_workspace.activate(workspace.clone(), None, window, cx);});}- workspace.reveal_panel::<AgentPanel>(window, cx);- });+ self.active_entry = Some(ActiveEntry::Terminal {+ terminal_id: metadata.terminal_id,+ workspace: workspace.clone(),+ });+ self.update_entries(cx);+ Self::load_agent_terminal_in_workspace(workspace, metadata, false, window, cx);+ }}}}@@ -4211,11 +4940,11 @@ impl Sidebar {Self::load_agent_thread_in_workspace(workspace, metadata, true, window, cx);}ThreadSwitcherSelection::Terminal {- terminal_id,+ metadata,workspace,} => {self.dismiss_thread_switcher(cx);- self.activate_terminal(workspace, *terminal_id, true, window, cx);+ self.activate_terminal_entry(metadata.clone(), workspace.clone(), true, window, cx);}}}@@ -4537,24 +5266,26 @@ impl Sidebar {is_focused: bool,cx: &mut Context<Self>,) -> AnyElement {- let id = ElementId::from(format!("terminal-{}", terminal.id));- let timestamp = format_history_entry_timestamp(terminal.created_at);+ let id = ElementId::from(format!("terminal-{}", terminal.metadata.terminal_id));+ let timestamp = format_history_entry_timestamp(terminal.metadata.created_at);let is_hovered = self.hovered_thread_index == Some(ix);let color = cx.theme().colors();let sidebar_bg = color.title_bar_background.blend(color.panel_background.opacity(0.25));- let terminal_id = terminal.id;+ let metadata = terminal.metadata.clone();let workspace = terminal.workspace.clone();let focus_handle = self.focus_handle.clone();let worktrees = apply_worktree_label_mode(terminal.worktrees.clone(),cx.flag_value::<AgentThreadWorktreeLabelFlag>(),);+ let is_remote = terminal.workspace.is_remote(cx);- ThreadItem::new(id, terminal.title.clone())+ ThreadItem::new(id, terminal.metadata.title.clone()).base_bg(sidebar_bg).icon(IconName::Terminal)+ .is_remote(is_remote).worktrees(worktrees).timestamp(timestamp).notified(terminal.has_notification)@@ -4587,14 +5318,21 @@ impl Sidebar {}}).on_click(cx.listener(move |this, _, window, cx| {- this.close_terminal(&workspace, terminal_id, window, cx);+ this.close_terminal(&metadata, &workspace, window, cx);})),)}).on_click(cx.listener({+ let metadata = terminal.metadata.clone();let workspace = terminal.workspace.clone();move |this, _, window, cx| {- this.activate_terminal(&workspace, terminal_id, false, window, cx);+ this.activate_terminal_entry(+ metadata.clone(),+ workspace.clone(),+ false,+ window,+ cx,+ );}})).into_any_element()@@ -4996,8 +5734,9 @@ impl Sidebar {}}ListEntry::Terminal(terminal) => {+ let metadata = terminal.metadata.clone();let workspace = terminal.workspace.clone();- self.activate_terminal(&workspace, terminal.id, true, window, cx);+ self.activate_terminal_entry(metadata, workspace, true, window, cx);}ListEntry::ProjectHeader { .. } => {}}@@ -5693,29 +6432,6 @@ impl Render for Sidebar {}}-fn terminal_entries_for_workspace<S: std::hash::BuildHasher>(- workspace: &Entity<Workspace>,- branch_by_path: &HashMap<PathBuf, SharedString, S>,- cx: &App,-) -> impl Iterator<Item = TerminalEntry> {- let Some(agent_panel) = workspace.read(cx).panel::<AgentPanel>(cx) else {- return None.into_iter().flatten();- };- let terminals = agent_panel.read(cx).terminals(cx).into_iter().map(- move |terminal: AgentPanelTerminalInfo| TerminalEntry {- id: terminal.id,- title: terminal.title,- workspace: workspace.clone(),- worktrees: terminal_worktree_info(workspace, branch_by_path, cx),- created_at: terminal.created_at,- has_notification: terminal.has_notification,- highlight_positions: Vec::new(),- },- );-- Some(terminals).into_iter().flatten()-}-fn all_thread_infos_for_workspace(workspace: &Entity<Workspace>,cx: &App,diff --git a/crates/sidebar/src/sidebar_tests.rs b/crates/sidebar/src/sidebar_tests.rsindex 4817ab5ebc6..cb385828dc6 100644--- a/crates/sidebar/src/sidebar_tests.rs+++ b/crates/sidebar/src/sidebar_tests.rs@@ -3,8 +3,12 @@ use acp_thread::{AcpThread, PermissionOptions, StubAgentConnection};use agent::ThreadStore;use agent_ui::{ThreadId,+ terminal_thread_metadata_store::{+ TerminalThreadMetadata, TerminalThreadMetadataStore, TestTerminalMetadataDbName,+ },test_support::{- active_session_id, active_thread_id, open_thread_with_connection, send_message,+ active_session_id, active_thread_id, open_thread_with_connection,+ open_thread_with_custom_connection, send_message,},thread_metadata_store::{ThreadMetadata, WorktreePaths},};@@ -28,6 +32,7 @@ fn init_test(cx: &mut TestAppContext) {editor::init(cx);ThreadStore::init_global(cx);ThreadMetadataStore::init_global(cx);+ TerminalThreadMetadataStore::init_global(cx);language_model::LanguageModelRegistry::test(cx);prompt_store::init(cx);});@@ -148,7 +153,7 @@ fn assert_remote_project_integration_sidebar_state(ListEntry::Terminal(terminal) => {panic!("unexpected sidebar terminal while simulating remote project integration flicker: title=`{}`",- terminal.title+ terminal.metadata.title);}}@@ -534,7 +539,7 @@ fn visible_entries_as_strings(}}ListEntry::Terminal(terminal) => {- let title = &terminal.title;+ let title = &terminal.metadata.title;let worktree = format_linked_worktree_chips(&terminal.worktrees);format!(" {title}{worktree}{selected}")}@@ -1502,11 +1507,25 @@ async fn test_agent_panel_terminals_appear_in_sidebar_and_search(cx: &mut TestAp);assert!(sidebar.contents.entries.iter().any(|entry| {- matches!(entry, ListEntry::Terminal(terminal) if terminal.id == terminal_id && terminal.title.as_ref() == "Dev Server")+ matches!(entry, ListEntry::Terminal(terminal) if terminal.metadata.terminal_id == terminal_id && terminal.metadata.title.as_ref() == "Dev Server")}),"expected the inserted terminal to appear in sidebar contents",);});+ sidebar.read_with(cx, |_sidebar, cx| {+ let store = TerminalThreadMetadataStore::global(cx).read(cx);+ let metadata = store+ .entry(terminal_id)+ .expect("terminal metadata should be persisted");+ assert_eq!(metadata.title.as_ref(), "Dev Server");+ assert!(+ metadata+ .folder_paths()+ .paths()+ .iter()+ .any(|path| path.as_path() == Path::new("/my-project"))+ );+ });type_in_search(&sidebar, "server", cx);assert_eq!(@@ -1522,24 +1541,931 @@ async fn test_agent_panel_terminals_appear_in_sidebar_and_search(cx: &mut TestAp}#[gpui::test]-async fn test_agent_panel_terminal_shows_project_and_linked_worktree(cx: &mut TestAppContext) {- agent_ui::test_support::init_test(cx);- cx.update(|cx| {- cx.set_global(agent_ui::MaxIdleRetainedThreads(1));- ThreadStore::init_global(cx);- ThreadMetadataStore::init_global(cx);- language_model::LanguageModelRegistry::test(cx);- prompt_store::init(cx);- });+async fn test_agent_panel_terminal_metadata_remains_visible_after_panel_is_removed(+ cx: &mut TestAppContext,+) {+ let project = init_test_project_with_agent_panel("/my-project", cx).await;+ let (multi_workspace, cx) =+ cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));+ let (sidebar, panel) = setup_sidebar_with_agent_panel(&multi_workspace, cx);+ let workspace = multi_workspace.read_with(cx, |multi_workspace, _cx| {+ multi_workspace.workspace().clone()+ });++ let terminal_id = panel+ .update_in(cx, |panel, window, cx| {+ panel.insert_test_terminal("Dev Server", true, window, cx)+ })+ .expect("test terminal should be inserted");+ cx.run_until_parked();++ workspace.update_in(cx, |workspace, window, cx| {+ workspace.remove_panel(&panel, window, cx);+ });+ sidebar.update(cx, |sidebar, cx| sidebar.update_entries(cx));+ cx.run_until_parked();++ assert!(workspace.read_with(cx, |workspace, cx| {+ workspace.panel::<AgentPanel>(cx).is_none()+ }));+ assert_eq!(+ visible_entries_as_strings(&sidebar, cx),+ vec!["v [my-project]", " Dev Server"]+ );++ sidebar.read_with(cx, |sidebar, _cx| {+ assert!(sidebar.contents.entries.iter().any(|entry| {+ matches!(entry, ListEntry::Terminal(terminal) if terminal.metadata.terminal_id == terminal_id)+ }));+ });+}++#[gpui::test]+async fn test_terminal_metadata_is_deduped_across_project_groups(cx: &mut TestAppContext) {+ agent_ui::test_support::init_test(cx);+ cx.update(|cx| {+ cx.set_global(agent_ui::MaxIdleRetainedThreads(1));+ ThreadStore::init_global(cx);+ ThreadMetadataStore::init_global(cx);+ language_model::LanguageModelRegistry::test(cx);+ prompt_store::init(cx);+ });++ let fs = FakeFs::new(cx.executor());+ fs.insert_tree("/project-a", serde_json::json!({ "src": {} }))+ .await;+ fs.insert_tree("/project-b", serde_json::json!({ "src": {} }))+ .await;+ cx.update(|cx| <dyn fs::Fs>::set_global(fs.clone(), cx));++ let project_a = project::Project::test(fs.clone(), ["/project-a".as_ref()], cx).await;+ let project_b = project::Project::test(fs.clone(), ["/project-b".as_ref()], cx).await;+ let (multi_workspace, cx) =+ cx.add_window_view(|window, cx| MultiWorkspace::test_new(project_a, window, cx));+ let (sidebar, panel) = setup_sidebar_with_agent_panel(&multi_workspace, cx);+ let workspace_a = multi_workspace.read_with(cx, |multi_workspace, _cx| {+ multi_workspace.workspace().clone()+ });+ multi_workspace.update_in(cx, |multi_workspace, window, cx| {+ multi_workspace.test_add_workspace(project_b, window, cx);+ });+ let terminal_id = panel+ .update_in(cx, |panel, window, cx| {+ panel.insert_test_terminal("Original", true, window, cx)+ })+ .expect("test terminal should be inserted");+ cx.run_until_parked();++ workspace_a.update_in(cx, |workspace, window, cx| {+ workspace.remove_panel(&panel, window, cx);+ });+ let now = Utc::now();+ let metadata = TerminalThreadMetadata {+ terminal_id,+ title: "Dev Server".into(),+ custom_title: None,+ created_at: now,+ worktree_paths: WorktreePaths::from_path_lists(+ PathList::new(&[PathBuf::from("/project-a")]),+ PathList::new(&[PathBuf::from("/project-b")]),+ )+ .unwrap(),+ remote_connection: None,+ working_directory: None,+ };++ cx.update(|_, cx| {+ TerminalThreadMetadataStore::global(cx).update(cx, |store, cx| {+ store.save(metadata, cx);+ });+ });+ sidebar.update(cx, |sidebar, cx| sidebar.update_entries(cx));+ cx.run_until_parked();++ sidebar.read_with(cx, |sidebar, _cx| {+ assert_eq!(+ sidebar+ .contents+ .entries+ .iter()+ .filter(|entry| {+ matches!(+ entry,+ ListEntry::Terminal(terminal)+ if terminal.metadata.terminal_id == terminal_id+ )+ })+ .count(),+ 1+ );+ });+}++#[gpui::test]+async fn test_agent_panel_terminal_shows_project_and_linked_worktree(cx: &mut TestAppContext) {+ agent_ui::test_support::init_test(cx);+ cx.update(|cx| {+ cx.set_global(agent_ui::MaxIdleRetainedThreads(1));+ ThreadStore::init_global(cx);+ ThreadMetadataStore::init_global(cx);+ language_model::LanguageModelRegistry::test(cx);+ prompt_store::init(cx);+ });++ let fs = FakeFs::new(cx.executor());+ fs.insert_tree("/project", serde_json::json!({ ".git": {}, "src": {} }))+ .await;+ fs.add_linked_worktree_for_repo(+ Path::new("/project/.git"),+ false,+ git::repository::Worktree {+ path: PathBuf::from("/wt-feature-a"),+ ref_name: Some("refs/heads/feature-a".into()),+ sha: "aaa".into(),+ is_main: false,+ is_bare: false,+ },+ )+ .await;+ cx.update(|cx| <dyn fs::Fs>::set_global(fs.clone(), cx));++ let main_project = project::Project::test(fs.clone(), ["/project".as_ref()], cx).await;+ let worktree_project = project::Project::test(fs.clone(), ["/wt-feature-a".as_ref()], cx).await;++ main_project+ .update(cx, |project, cx| project.git_scans_complete(cx))+ .await;+ worktree_project+ .update(cx, |project, cx| project.git_scans_complete(cx))+ .await;++ let (multi_workspace, cx) =+ cx.add_window_view(|window, cx| MultiWorkspace::test_new(main_project.clone(), window, cx));+ let sidebar = setup_sidebar(&multi_workspace, cx);+ let worktree_workspace = multi_workspace.update_in(cx, |multi_workspace, window, cx| {+ multi_workspace.test_add_workspace(worktree_project.clone(), window, cx)+ });+ let panel = add_agent_panel(&worktree_workspace, cx);++ panel+ .update_in(cx, |panel, window, cx| {+ panel.insert_test_terminal("Dev Server", true, window, cx)+ })+ .expect("test terminal should be inserted");+ cx.run_until_parked();++ assert_eq!(+ visible_entries_as_strings(&sidebar, cx),+ vec!["v [project]", " Dev Server {wt-feature-a}"]+ );++ type_in_search(&sidebar, "wt-feature-a", cx);+ assert_eq!(+ visible_entries_as_strings(&sidebar, cx),+ vec!["v [project]", " Dev Server {wt-feature-a} <== selected"]+ );+}++#[gpui::test]+async fn test_terminal_close_event_on_archived_linked_worktree_removes_workspace(+ cx: &mut TestAppContext,+) {+ init_test(cx);++ let fs = FakeFs::new(cx.executor());+ fs.insert_tree(+ "/project",+ serde_json::json!({+ ".git": {+ "worktrees": {+ "feature-a": {+ "commondir": "../../",+ "HEAD": "ref: refs/heads/feature-a",+ },+ },+ },+ "src": {},+ }),+ )+ .await;+ fs.insert_tree(+ "/worktrees/project/feature-a/project",+ serde_json::json!({+ ".git": "gitdir: /project/.git/worktrees/feature-a",+ "src": {},+ }),+ )+ .await;+ fs.add_linked_worktree_for_repo(+ Path::new("/project/.git"),+ false,+ git::repository::Worktree {+ path: PathBuf::from("/worktrees/project/feature-a/project"),+ ref_name: Some("refs/heads/feature-a".into()),+ sha: "aaa".into(),+ is_main: false,+ is_bare: false,+ },+ )+ .await;+ cx.update(|cx| <dyn fs::Fs>::set_global(fs.clone(), cx));++ let main_project = project::Project::test(fs.clone(), ["/project".as_ref()], cx).await;+ let worktree_project = project::Project::test(+ fs.clone(),+ ["/worktrees/project/feature-a/project".as_ref()],+ cx,+ )+ .await;++ main_project+ .update(cx, |project, cx| project.git_scans_complete(cx))+ .await;+ worktree_project+ .update(cx, |project, cx| project.git_scans_complete(cx))+ .await;++ let (multi_workspace, cx) =+ cx.add_window_view(|window, cx| MultiWorkspace::test_new(main_project.clone(), window, cx));+ let sidebar = setup_sidebar(&multi_workspace, cx);+ let worktree_workspace = multi_workspace.update_in(cx, |multi_workspace, window, cx| {+ multi_workspace.test_add_workspace(worktree_project.clone(), window, cx)+ });+ let worktree_panel = add_agent_panel(&worktree_workspace, cx);++ let archived_session_id = acp::SessionId::new(Arc::from("archived-wt-thread"));+ save_thread_metadata(+ archived_session_id.clone(),+ Some("Archived Worktree Thread".into()),+ chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, 0, 0, 0).unwrap(),+ None,+ None,+ &worktree_project,+ cx,+ );+ let archived_thread_id = cx.update(|_, cx| {+ ThreadMetadataStore::global(cx)+ .read(cx)+ .entry_by_session(&archived_session_id)+ .expect("archived thread metadata should exist")+ .thread_id+ });+ cx.update(|_, cx| {+ ThreadMetadataStore::global(cx).update(cx, |store, cx| {+ store.archive(archived_thread_id, None, cx);+ });+ });+ save_thread_metadata(+ acp::SessionId::new(Arc::from("main-thread")),+ Some("Main Thread".into()),+ chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 2, 0, 0, 0).unwrap(),+ None,+ None,+ &main_project,+ cx,+ );++ let terminal_id = worktree_panel+ .update_in(cx, |panel, window, cx| {+ panel.insert_test_terminal("Dev Server", true, window, cx)+ })+ .expect("test terminal should be inserted");+ cx.run_until_parked();++ assert_eq!(+ multi_workspace.read_with(cx, |multi_workspace, _| multi_workspace+ .workspaces()+ .count()),+ 2,+ "should start with main and linked worktree workspaces"+ );+ let entries_before = visible_entries_as_strings(&sidebar, cx);+ assert!(+ entries_before+ .iter()+ .any(|entry| entry.contains("Dev Server") && entry.contains('{')),+ "expected linked worktree terminal before closing, got: {entries_before:?}"+ );++ worktree_panel.update(cx, |panel, cx| {+ panel.emit_test_terminal_close(terminal_id, cx);+ });+ for _ in 0..4 {+ cx.run_until_parked();+ }++ let terminal_metadata_deleted = cx.update(|_, cx| {+ TerminalThreadMetadataStore::global(cx)+ .read(cx)+ .entry(terminal_id)+ .is_none()+ });+ assert!(+ terminal_metadata_deleted,+ "terminal metadata should be deleted after close"+ );+ let unarchived_worktree_threads = cx.update(|_, cx| {+ let worktree_path_list =+ PathList::new(&[PathBuf::from("/worktrees/project/feature-a/project")]);+ ThreadMetadataStore::global(cx)+ .read(cx)+ .entries_for_path(&worktree_path_list, None)+ .count()+ });+ assert_eq!(+ unarchived_worktree_threads, 0,+ "closing the terminal must not create a fallback draft for the removed worktree"+ );+ assert_eq!(+ multi_workspace.read_with(cx, |multi_workspace, _| multi_workspace+ .workspaces()+ .count()),+ 1,+ "linked worktree workspace should be removed after closing its last terminal"+ );+ let entries_after = visible_entries_as_strings(&sidebar, cx);+ assert!(+ !entries_after.iter().any(|entry| entry.contains('{')),+ "no sidebar entry should reference the archived worktree, got: {entries_after:?}"+ );+ assert!(+ !fs.is_dir(Path::new("/worktrees/project/feature-a/project"))+ .await,+ "linked worktree directory should be removed from disk after closing its last terminal"+ );+}++#[gpui::test]+async fn test_terminal_close_event_closes_sidebar_terminal(cx: &mut TestAppContext) {+ let project = init_test_project_with_agent_panel("/my-project", cx).await;+ let (multi_workspace, cx) =+ cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));+ let (sidebar, panel) = setup_sidebar_with_agent_panel(&multi_workspace, cx);++ let terminal_id = panel+ .update_in(cx, |panel, window, cx| {+ panel.insert_test_terminal("Dev Server", true, window, cx)+ })+ .expect("test terminal should be inserted");+ cx.run_until_parked();++ assert_eq!(+ visible_entries_as_strings(&sidebar, cx),+ vec!["v [my-project]", " Dev Server"]+ );++ panel.update(cx, |panel, cx| {+ panel.emit_test_terminal_close(terminal_id, cx);+ });+ cx.run_until_parked();++ panel.read_with(cx, |panel, _cx| {+ assert!(!panel.has_terminal(terminal_id));+ });+ sidebar.read_with(cx, |sidebar, _cx| {+ assert!(sidebar.contents.entries.iter().all(|entry| {+ !matches!(entry, ListEntry::Terminal(terminal) if terminal.metadata.terminal_id == terminal_id)+ }));+ });+ sidebar.read_with(cx, |_sidebar, cx| {+ assert!(+ TerminalThreadMetadataStore::global(cx)+ .read(cx)+ .entry(terminal_id)+ .is_none(),+ "terminal metadata should be deleted when the terminal requests close"+ );+ });+}++#[gpui::test]+async fn test_agent_panel_terminal_notifications_update_sidebar(cx: &mut TestAppContext) {+ let project = init_test_project_with_agent_panel("/my-project", cx).await;+ let (multi_workspace, cx) =+ cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));+ let (sidebar, panel) = setup_sidebar_with_agent_panel(&multi_workspace, cx);++ let build_terminal_id = panel+ .update_in(cx, |panel, window, cx| {+ panel.insert_test_terminal("Build", true, window, cx)+ })+ .expect("build test terminal should be inserted");+ let server_terminal_id = panel+ .update_in(cx, |panel, window, cx| {+ panel.insert_test_terminal("Server", true, window, cx)+ })+ .expect("server test terminal should be inserted");+ cx.run_until_parked();++ panel.read_with(cx, |panel, _cx| {+ assert_eq!(panel.active_terminal_id(), Some(server_terminal_id));+ });++ panel.update(cx, |panel, cx| {+ panel.emit_test_terminal_bell(build_terminal_id, cx);+ });+ cx.run_until_parked();++ sidebar.read_with(cx, |sidebar, cx| {+ assert!(sidebar.has_notifications(cx));+ assert!(sidebar.contents.notified_terminals.contains(&build_terminal_id));+ assert!(sidebar.contents.entries.iter().any(|entry| {+ matches!(entry, ListEntry::Terminal(terminal) if terminal.metadata.terminal_id == build_terminal_id && terminal.has_notification)+ }));+ });++ panel.update_in(cx, |panel, window, cx| {+ panel.activate_terminal(build_terminal_id, true, window, cx);+ });+ cx.run_until_parked();++ sidebar.read_with(cx, |sidebar, cx| {+ assert!(!sidebar.has_notifications(cx));+ assert!(+ !sidebar+ .contents+ .notified_terminals+ .contains(&build_terminal_id)+ );+ });+}++#[gpui::test]+async fn test_thread_switcher_can_activate_agent_panel_terminal(cx: &mut TestAppContext) {+ let project = init_test_project_with_agent_panel("/my-project", cx).await;+ let (multi_workspace, cx) =+ cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));+ let (sidebar, panel) = setup_sidebar_with_agent_panel(&multi_workspace, cx);++ let build_terminal_id = panel+ .update_in(cx, |panel, window, cx| {+ panel.insert_test_terminal("Build", true, window, cx)+ })+ .expect("build test terminal should be inserted");+ let server_terminal_id = panel+ .update_in(cx, |panel, window, cx| {+ panel.insert_test_terminal("Server", true, window, cx)+ })+ .expect("server test terminal should be inserted");+ cx.run_until_parked();++ focus_sidebar(&sidebar, cx);+ sidebar.update_in(cx, |sidebar, window, cx| {+ sidebar.on_toggle_thread_switcher(&ToggleThreadSwitcher::default(), window, cx);+ });+ cx.run_until_parked();++ let (entry_terminal_ids, selected_terminal_id) = sidebar.read_with(cx, |sidebar, cx| {+ let switcher = sidebar+ .thread_switcher+ .as_ref()+ .expect("switcher should be open");+ let switcher = switcher.read(cx);+ let entry_terminal_ids = switcher+ .entries()+ .iter()+ .map(|entry| {+ entry+ .terminal_id()+ .expect("expected terminal switcher entry")+ })+ .collect::<Vec<_>>();+ let selected_terminal_id = switcher+ .selected_entry()+ .expect("switcher should have selected entry")+ .terminal_id()+ .expect("expected selected terminal switcher entry");+ (entry_terminal_ids, selected_terminal_id)+ });++ assert_eq!(entry_terminal_ids.len(), 2);+ assert!(entry_terminal_ids.contains(&build_terminal_id));+ assert!(entry_terminal_ids.contains(&server_terminal_id));++ sidebar.update_in(cx, |sidebar, window, cx| {+ let switcher = sidebar+ .thread_switcher+ .as_ref()+ .expect("switcher should be open");+ let focus = switcher.focus_handle(cx);+ focus.dispatch_action(&menu::Confirm, window, cx);+ });+ cx.run_until_parked();++ panel.read_with(cx, |panel, _cx| {+ assert_eq!(panel.active_terminal_id(), Some(selected_terminal_id));+ });+ sidebar.read_with(cx, |sidebar, _cx| {+ assert!(+ matches!(&sidebar.active_entry, Some(ActiveEntry::Terminal { terminal_id, .. }) if *terminal_id == selected_terminal_id),+ "expected selected terminal to become active, got {:?}",+ sidebar.active_entry,+ );+ });+}++#[gpui::test]+async fn test_thread_switcher_includes_terminal_metadata_for_open_project_group(+ cx: &mut TestAppContext,+) {+ let project = init_test_project_with_agent_panel("/project", cx).await;+ let (multi_workspace, cx) =+ cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));+ let (sidebar, panel) = setup_sidebar_with_agent_panel(&multi_workspace, cx);++ let terminal_id = panel+ .update_in(cx, |panel, window, cx| {+ panel.insert_test_terminal("Feature Terminal", true, window, cx)+ })+ .expect("test terminal should be inserted");+ panel.update_in(cx, |panel, window, cx| {+ panel.close_terminal(terminal_id, window, cx);+ });+ save_thread_metadata(+ acp::SessionId::new(Arc::from("thread-newer")),+ Some("Newer Thread".into()),+ chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 3, 0, 0, 0).unwrap(),+ None,+ None,+ &project,+ cx,+ );+ save_thread_metadata(+ acp::SessionId::new(Arc::from("thread-older")),+ Some("Older Thread".into()),+ chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 2, 0, 0, 0).unwrap(),+ None,+ None,+ &project,+ cx,+ );++ let created_at = chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, 0, 0, 0).unwrap();+ let metadata = TerminalThreadMetadata {+ terminal_id,+ title: "Feature Terminal".into(),+ custom_title: None,+ created_at,+ worktree_paths: WorktreePaths::from_path_lists(+ PathList::new(&[PathBuf::from("/project")]),+ PathList::new(&[PathBuf::from("/project-feature")]),+ )+ .unwrap(),+ remote_connection: None,+ working_directory: None,+ };+ cx.update(|_, cx| {+ TerminalThreadMetadataStore::global(cx).update(cx, |store, cx| {+ store.save(metadata, cx);+ });+ });+ sidebar.update(cx, |sidebar, cx| sidebar.update_entries(cx));+ cx.run_until_parked();++ focus_sidebar(&sidebar, cx);+ sidebar.update_in(cx, |sidebar, window, cx| {+ sidebar.on_toggle_thread_switcher(&ToggleThreadSwitcher::default(), window, cx);+ });+ cx.run_until_parked();++ sidebar.read_with(cx, |sidebar, cx| {+ let switcher = sidebar+ .thread_switcher+ .as_ref()+ .expect("switcher should be open");+ assert!(+ switcher+ .read(cx)+ .entries()+ .iter()+ .any(|entry| entry.terminal_id() == Some(terminal_id)),+ "terminal metadata row should be included like a closed thread row"+ );+ });+}++#[gpui::test]+async fn test_thread_switcher_preserves_closed_terminal_linked_worktree_workspace(+ cx: &mut TestAppContext,+) {+ init_test(cx);++ let fs = FakeFs::new(cx.executor());+ fs.insert_tree(+ "/project",+ serde_json::json!({+ ".git": {+ "worktrees": {+ "feature-a": {+ "commondir": "../../",+ "HEAD": "ref: refs/heads/feature-a",+ },+ },+ },+ "src": {},+ }),+ )+ .await;+ fs.insert_tree(+ "/worktrees/project/feature-a/project",+ serde_json::json!({+ ".git": "gitdir: /project/.git/worktrees/feature-a",+ "src": {},+ }),+ )+ .await;+ fs.add_linked_worktree_for_repo(+ Path::new("/project/.git"),+ false,+ git::repository::Worktree {+ path: PathBuf::from("/worktrees/project/feature-a/project"),+ ref_name: Some("refs/heads/feature-a".into()),+ sha: "aaa".into(),+ is_main: false,+ is_bare: false,+ },+ )+ .await;+ cx.update(|cx| <dyn fs::Fs>::set_global(fs.clone(), cx));++ let main_project = project::Project::test(fs.clone(), ["/project".as_ref()], cx).await;+ main_project+ .update(cx, |project, cx| project.git_scans_complete(cx))+ .await;++ let (multi_workspace, cx) =+ cx.add_window_view(|window, cx| MultiWorkspace::test_new(main_project.clone(), window, cx));+ let (sidebar, panel) = setup_sidebar_with_agent_panel(&multi_workspace, cx);++ let terminal_id = panel+ .update_in(cx, |panel, window, cx| {+ panel.insert_test_terminal("Feature Terminal", true, window, cx)+ })+ .expect("test terminal should be inserted");+ panel.update_in(cx, |panel, window, cx| {+ panel.close_terminal(terminal_id, window, cx);+ });+ let created_at = chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, 0, 0, 0).unwrap();+ let worktree_folder_paths =+ PathList::new(&[PathBuf::from("/worktrees/project/feature-a/project")]);+ let metadata = TerminalThreadMetadata {+ terminal_id,+ title: "Feature Terminal".into(),+ custom_title: None,+ created_at,+ worktree_paths: WorktreePaths::from_path_lists(+ PathList::new(&[PathBuf::from("/project")]),+ worktree_folder_paths.clone(),+ )+ .unwrap(),+ remote_connection: None,+ working_directory: None,+ };+ cx.update(|_, cx| {+ TerminalThreadMetadataStore::global(cx).update(cx, |store, cx| {+ store.save(metadata, cx);+ });+ });+ save_thread_metadata(+ acp::SessionId::new(Arc::from("main-thread")),+ Some("Main Thread".into()),+ chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 2, 0, 0, 0).unwrap(),+ None,+ None,+ &main_project,+ cx,+ );+ sidebar.update(cx, |sidebar, cx| sidebar.update_entries(cx));+ cx.run_until_parked();++ assert!(+ multi_workspace+ .read_with(cx, |multi_workspace, cx| {+ multi_workspace.workspace_for_paths(&worktree_folder_paths, None, cx)+ })+ .is_none(),+ "linked worktree workspace should start closed"+ );++ focus_sidebar(&sidebar, cx);+ sidebar.update_in(cx, |sidebar, window, cx| {+ sidebar.on_toggle_thread_switcher(&ToggleThreadSwitcher::default(), window, cx);+ });+ cx.run_until_parked();++ sidebar.read_with(cx, |sidebar, cx| {+ let switcher = sidebar+ .thread_switcher+ .as_ref()+ .expect("switcher should be open");+ match switcher+ .read(cx)+ .selected_entry()+ .expect("switcher should select the terminal row by default")+ {+ ThreadSwitcherEntry::Terminal(entry) => {+ assert_eq!(entry.metadata.terminal_id, terminal_id);+ match &entry.workspace {+ ThreadEntryWorkspace::Closed {+ folder_paths,+ project_group_key,+ } => {+ assert_eq!(folder_paths, &worktree_folder_paths);+ assert_eq!(+ project_group_key.path_list(),+ &PathList::new(&[PathBuf::from("/project")])+ );+ }+ ThreadEntryWorkspace::Open(_) => {+ panic!("closed terminal row should retain its linked worktree target")+ }+ }+ }+ ThreadSwitcherEntry::Thread(_) => {+ panic!("terminal row should be selected by default")+ }+ }+ });+}++#[gpui::test]+async fn test_archive_selected_terminal_archives_closed_linked_worktree(cx: &mut TestAppContext) {+ init_test(cx);++ let fs = FakeFs::new(cx.executor());+ fs.insert_tree(+ "/project",+ serde_json::json!({+ ".git": {+ "worktrees": {+ "feature-a": {+ "commondir": "../../",+ "HEAD": "ref: refs/heads/feature-a",+ },+ },+ },+ "src": {},+ }),+ )+ .await;+ fs.insert_tree(+ "/worktrees/project/feature-a/project",+ serde_json::json!({+ ".git": "gitdir: /project/.git/worktrees/feature-a",+ "src": {},+ }),+ )+ .await;+ fs.add_linked_worktree_for_repo(+ Path::new("/project/.git"),+ false,+ git::repository::Worktree {+ path: PathBuf::from("/worktrees/project/feature-a/project"),+ ref_name: Some("refs/heads/feature-a".into()),+ sha: "aaa".into(),+ is_main: false,+ is_bare: false,+ },+ )+ .await;+ cx.update(|cx| <dyn fs::Fs>::set_global(fs.clone(), cx));++ let main_project = project::Project::test(fs.clone(), ["/project".as_ref()], cx).await;+ main_project+ .update(cx, |project, cx| project.git_scans_complete(cx))+ .await;++ let (multi_workspace, cx) =+ cx.add_window_view(|window, cx| MultiWorkspace::test_new(main_project.clone(), window, cx));+ let (sidebar, panel) = setup_sidebar_with_agent_panel(&multi_workspace, cx);++ let terminal_id = panel+ .update_in(cx, |panel, window, cx| {+ panel.insert_test_terminal("Feature Terminal", true, window, cx)+ })+ .expect("test terminal should be inserted");+ panel.update_in(cx, |panel, window, cx| {+ panel.close_terminal(terminal_id, window, cx);+ });+ let worktree_folder_paths =+ PathList::new(&[PathBuf::from("/worktrees/project/feature-a/project")]);+ let metadata = TerminalThreadMetadata {+ terminal_id,+ title: "Feature Terminal".into(),+ custom_title: None,+ created_at: chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, 0, 0, 0).unwrap(),+ worktree_paths: WorktreePaths::from_path_lists(+ PathList::new(&[PathBuf::from("/project")]),+ worktree_folder_paths.clone(),+ )+ .unwrap(),+ remote_connection: None,+ working_directory: None,+ };+ cx.update(|_, cx| {+ TerminalThreadMetadataStore::global(cx).update(cx, |store, cx| {+ store.save(metadata, cx);+ });+ });+ sidebar.update(cx, |sidebar, cx| sidebar.update_entries(cx));+ cx.run_until_parked();++ let terminal_index = sidebar.read_with(cx, |sidebar, _cx| {+ sidebar+ .contents+ .entries+ .iter()+ .position(|entry| matches!(entry, ListEntry::Terminal(terminal) if terminal.metadata.terminal_id == terminal_id))+ .expect("terminal should be visible in sidebar")+ });+ sidebar.read_with(cx, |sidebar, _cx| {+ match &sidebar.contents.entries[terminal_index] {+ ListEntry::Terminal(terminal) => match &terminal.workspace {+ ThreadEntryWorkspace::Closed { folder_paths, .. } => {+ assert_eq!(folder_paths, &worktree_folder_paths);+ }+ ThreadEntryWorkspace::Open(_) => {+ panic!("linked worktree terminal should start closed")+ }+ },+ _ => panic!("expected terminal row"),+ }+ });++ focus_sidebar(&sidebar, cx);+ sidebar.update_in(cx, |sidebar, _window, _cx| {+ sidebar.selection = Some(terminal_index);+ });+ cx.dispatch_action(ArchiveSelectedThread);+ for _ in 0..8 {+ cx.run_until_parked();+ }++ let terminal_metadata_deleted = cx.update(|_, cx| {+ TerminalThreadMetadataStore::global(cx)+ .read(cx)+ .entry(terminal_id)+ .is_none()+ });+ assert!(+ terminal_metadata_deleted,+ "terminal metadata should be deleted after closing from the sidebar"+ );+ assert!(+ multi_workspace+ .read_with(cx, |multi_workspace, cx| {+ multi_workspace.workspace_for_paths(&worktree_folder_paths, None, cx)+ })+ .is_none(),+ "temporary linked worktree workspace should be removed after archiving"+ );+ assert_eq!(+ multi_workspace.read_with(cx, |multi_workspace, _| multi_workspace+ .workspaces()+ .count()),+ 1,+ "closing a closed linked worktree terminal should leave only the main workspace"+ );+ assert!(+ !fs.is_dir(Path::new("/worktrees/project/feature-a/project"))+ .await,+ "linked worktree directory should be removed from disk after closing its terminal"+ );+}++#[gpui::test]+async fn test_archive_selected_thread_archives_closed_linked_worktree(cx: &mut TestAppContext) {+ init_test(cx);let fs = FakeFs::new(cx.executor());- fs.insert_tree("/project", serde_json::json!({ ".git": {}, "src": {} }))- .await;+ fs.insert_tree(+ "/project",+ serde_json::json!({+ ".git": {+ "worktrees": {+ "feature-a": {+ "commondir": "../../",+ "HEAD": "ref: refs/heads/feature-a",+ },+ },+ },+ "src": {},+ }),+ )+ .await;+ fs.insert_tree(+ "/worktrees/project/feature-a/project",+ serde_json::json!({+ ".git": "gitdir: /project/.git/worktrees/feature-a",+ "src": {},+ }),+ )+ .await;fs.add_linked_worktree_for_repo(Path::new("/project/.git"),false,git::repository::Worktree {- path: PathBuf::from("/wt-feature-a"),+ path: PathBuf::from("/worktrees/project/feature-a/project"),ref_name: Some("refs/heads/feature-a".into()),sha: "aaa".into(),is_main: false,@@ -1550,166 +2476,99 @@ async fn test_agent_panel_terminal_shows_project_and_linked_worktree(cx: &mut Tecx.update(|cx| <dyn fs::Fs>::set_global(fs.clone(), cx));let main_project = project::Project::test(fs.clone(), ["/project".as_ref()], cx).await;- let worktree_project = project::Project::test(fs.clone(), ["/wt-feature-a".as_ref()], cx).await;-main_project.update(cx, |project, cx| project.git_scans_complete(cx)).await;- worktree_project- .update(cx, |project, cx| project.git_scans_complete(cx))- .await;let (multi_workspace, cx) =cx.add_window_view(|window, cx| MultiWorkspace::test_new(main_project.clone(), window, cx));let sidebar = setup_sidebar(&multi_workspace, cx);- let worktree_workspace = multi_workspace.update_in(cx, |multi_workspace, window, cx| {- multi_workspace.test_add_workspace(worktree_project.clone(), window, cx)- });- let panel = add_agent_panel(&worktree_workspace, cx);-- panel- .update_in(cx, |panel, window, cx| {- panel.insert_test_terminal("Dev Server", true, window, cx)- })- .expect("test terminal should be inserted");- cx.run_until_parked();- assert_eq!(- visible_entries_as_strings(&sidebar, cx),- vec!["v [project]", " Dev Server {wt-feature-a}"]+ let worktree_session_id = acp::SessionId::new(Arc::from("worktree-thread"));+ let worktree_folder_paths =+ PathList::new(&[PathBuf::from("/worktrees/project/feature-a/project")]);+ save_thread_metadata_with_main_paths(+ "worktree-thread",+ "Worktree Thread",+ worktree_folder_paths.clone(),+ PathList::new(&[PathBuf::from("/project")]),+ chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 1, 0, 0, 0).unwrap(),+ cx,);-- type_in_search(&sidebar, "wt-feature-a", cx);- assert_eq!(- visible_entries_as_strings(&sidebar, cx),- vec!["v [project]", " Dev Server {wt-feature-a} <== selected"]+ save_thread_metadata(+ acp::SessionId::new(Arc::from("main-thread")),+ Some("Main Thread".into()),+ chrono::TimeZone::with_ymd_and_hms(&Utc, 2024, 1, 2, 0, 0, 0).unwrap(),+ None,+ None,+ &main_project,+ cx,);-}--#[gpui::test]-async fn test_agent_panel_terminal_notifications_update_sidebar(cx: &mut TestAppContext) {- let project = init_test_project_with_agent_panel("/my-project", cx).await;- let (multi_workspace, cx) =- cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));- let (sidebar, panel) = setup_sidebar_with_agent_panel(&multi_workspace, cx);-- let build_terminal_id = panel- .update_in(cx, |panel, window, cx| {- panel.insert_test_terminal("Build", true, window, cx)- })- .expect("build test terminal should be inserted");- let server_terminal_id = panel- .update_in(cx, |panel, window, cx| {- panel.insert_test_terminal("Server", true, window, cx)- })- .expect("server test terminal should be inserted");- cx.run_until_parked();-- panel.read_with(cx, |panel, _cx| {- assert_eq!(panel.active_terminal_id(), Some(server_terminal_id));- });-- panel.update(cx, |panel, cx| {- panel.emit_test_terminal_bell(build_terminal_id, cx);- });+ sidebar.update(cx, |sidebar, cx| sidebar.update_entries(cx));cx.run_until_parked();- sidebar.read_with(cx, |sidebar, cx| {- assert!(sidebar.has_notifications(cx));- assert!(sidebar.contents.notified_terminals.contains(&build_terminal_id));- assert!(sidebar.contents.entries.iter().any(|entry| {- matches!(entry, ListEntry::Terminal(terminal) if terminal.id == build_terminal_id && terminal.has_notification)- }));- });-- panel.update_in(cx, |panel, window, cx| {- panel.activate_terminal(build_terminal_id, true, window, cx);+ let thread_index = sidebar.read_with(cx, |sidebar, _cx| {+ sidebar+ .contents+ .entries+ .iter()+ .position(|entry| matches!(entry, ListEntry::Thread(thread) if thread.metadata.session_id.as_ref() == Some(&worktree_session_id)))+ .expect("worktree thread should be visible in sidebar")});- cx.run_until_parked();-- sidebar.read_with(cx, |sidebar, cx| {- assert!(!sidebar.has_notifications(cx));- assert!(- !sidebar- .contents- .notified_terminals- .contains(&build_terminal_id)- );+ sidebar.read_with(cx, |sidebar, _cx| {+ match &sidebar.contents.entries[thread_index] {+ ListEntry::Thread(thread) => match &thread.workspace {+ ThreadEntryWorkspace::Closed { folder_paths, .. } => {+ assert_eq!(folder_paths, &worktree_folder_paths);+ }+ ThreadEntryWorkspace::Open(_) => {+ panic!("linked worktree thread should start closed")+ }+ },+ _ => panic!("expected thread row"),+ }});-}--#[gpui::test]-async fn test_thread_switcher_can_activate_agent_panel_terminal(cx: &mut TestAppContext) {- let project = init_test_project_with_agent_panel("/my-project", cx).await;- let (multi_workspace, cx) =- cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));- let (sidebar, panel) = setup_sidebar_with_agent_panel(&multi_workspace, cx);-- let build_terminal_id = panel- .update_in(cx, |panel, window, cx| {- panel.insert_test_terminal("Build", true, window, cx)- })- .expect("build test terminal should be inserted");- let server_terminal_id = panel- .update_in(cx, |panel, window, cx| {- panel.insert_test_terminal("Server", true, window, cx)- })- .expect("server test terminal should be inserted");- cx.run_until_parked();focus_sidebar(&sidebar, cx);- sidebar.update_in(cx, |sidebar, window, cx| {- sidebar.on_toggle_thread_switcher(&ToggleThreadSwitcher::default(), window, cx);- });- cx.run_until_parked();-- let (entry_terminal_ids, selected_terminal_id) = sidebar.read_with(cx, |sidebar, cx| {- let switcher = sidebar- .thread_switcher- .as_ref()- .expect("switcher should be open");- let switcher = switcher.read(cx);- let entry_terminal_ids = switcher- .entries()- .iter()- .map(|entry| {- entry- .terminal_id()- .expect("expected terminal switcher entry")- })- .collect::<Vec<_>>();- let selected_terminal_id = switcher- .selected_entry()- .expect("switcher should have selected entry")- .terminal_id()- .expect("expected selected terminal switcher entry");- (entry_terminal_ids, selected_terminal_id)- });-- assert_eq!(entry_terminal_ids.len(), 2);- assert!(entry_terminal_ids.contains(&build_terminal_id));- assert!(entry_terminal_ids.contains(&server_terminal_id));-- sidebar.update_in(cx, |sidebar, window, cx| {- let switcher = sidebar- .thread_switcher- .as_ref()- .expect("switcher should be open");- let focus = switcher.focus_handle(cx);- focus.dispatch_action(&menu::Confirm, window, cx);+ sidebar.update_in(cx, |sidebar, _window, _cx| {+ sidebar.selection = Some(thread_index);});- cx.run_until_parked();+ cx.dispatch_action(ArchiveSelectedThread);+ for _ in 0..8 {+ cx.run_until_parked();+ }- panel.read_with(cx, |panel, _cx| {- assert_eq!(panel.active_terminal_id(), Some(selected_terminal_id));- });- sidebar.read_with(cx, |sidebar, _cx| {- assert!(- matches!(&sidebar.active_entry, Some(ActiveEntry::Terminal { terminal_id, .. }) if *terminal_id == selected_terminal_id),- "expected selected terminal to become active, got {:?}",- sidebar.active_entry,- );+ let thread_archived = cx.update(|_, cx| {+ ThreadMetadataStore::global(cx)+ .read(cx)+ .entry_by_session(&worktree_session_id)+ .map(|thread| thread.archived)});+ assert_eq!(+ thread_archived,+ Some(true),+ "thread metadata should remain archived after worktree archival"+ );+ assert!(+ multi_workspace+ .read_with(cx, |multi_workspace, cx| {+ multi_workspace.workspace_for_paths(&worktree_folder_paths, None, cx)+ })+ .is_none(),+ "temporary linked worktree workspace should be removed after archiving"+ );+ assert_eq!(+ multi_workspace.read_with(cx, |multi_workspace, _| multi_workspace+ .workspaces()+ .count()),+ 1,+ "archiving a closed linked worktree thread should leave only the main workspace"+ );+ assert!(+ !fs.is_dir(Path::new("/worktrees/project/feature-a/project"))+ .await,+ "linked worktree directory should be removed from disk after archiving its thread"+ );}#[gpui::test]@@ -1734,7 +2593,7 @@ async fn test_archive_selected_thread_closes_selected_agent_panel_terminal(.contents.entries.iter()- .position(|entry| matches!(entry, ListEntry::Terminal(terminal) if terminal.id == terminal_id))+ .position(|entry| matches!(entry, ListEntry::Terminal(terminal) if terminal.metadata.terminal_id == terminal_id)).expect("terminal should be visible in sidebar")});sidebar.update_in(cx, |sidebar, _window, _cx| {@@ -1748,9 +2607,16 @@ async fn test_archive_selected_thread_closes_selected_agent_panel_terminal(});sidebar.read_with(cx, |sidebar, _cx| {assert!(sidebar.contents.entries.iter().all(|entry| {- !matches!(entry, ListEntry::Terminal(terminal) if terminal.id == terminal_id)+ !matches!(entry, ListEntry::Terminal(terminal) if terminal.metadata.terminal_id == terminal_id)}));});+ sidebar.read_with(cx, |_sidebar, cx| {+ let store = TerminalThreadMetadataStore::global(cx).read(cx);+ assert!(+ store.entry(terminal_id).is_none(),+ "terminal metadata should be deleted when closing from the sidebar"+ );+ });}#[gpui::test]@@ -1759,10 +2625,6 @@ async fn test_closing_active_agent_panel_terminal_activates_neighbor(cx: &mut Telet (multi_workspace, cx) =cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));let (sidebar, panel) = setup_sidebar_with_agent_panel(&multi_workspace, cx);- let workspace = multi_workspace.read_with(cx, |multi_workspace, _cx| {- multi_workspace.workspace().clone()- });-let build_terminal_id = panel.update_in(cx, |panel, window, cx| {panel.insert_test_terminal("Build", true, window, cx)@@ -1775,8 +2637,23 @@ async fn test_closing_active_agent_panel_terminal_activates_neighbor(cx: &mut Te.expect("server test terminal should be inserted");cx.run_until_parked();+ let (server_metadata, server_workspace) = sidebar.read_with(cx, |sidebar, _cx| {+ sidebar+ .contents+ .entries+ .iter()+ .find_map(|entry| match entry {+ ListEntry::Terminal(terminal)+ if terminal.metadata.terminal_id == server_terminal_id =>+ {+ Some((terminal.metadata.clone(), terminal.workspace.clone()))+ }+ _ => None,+ })+ .expect("server terminal should be visible in sidebar")+ });sidebar.update_in(cx, |sidebar, window, cx| {- sidebar.close_terminal(&workspace, server_terminal_id, window, cx);+ sidebar.close_terminal(&server_metadata, &server_workspace, window, cx);});cx.run_until_parked();@@ -4788,7 +5665,7 @@ async fn test_clicking_worktree_thread_does_not_briefly_render_as_separate_projeListEntry::Terminal(terminal) => {panic!("unexpected sidebar terminal while opening linked worktree thread: title=`{}`",- terminal.title+ terminal.metadata.title);}}@@ -10073,15 +10950,24 @@ mod property_test {let panel =workspace.read_with(cx, |workspace, cx| workspace.panel::<AgentPanel>(cx));if let Some(panel) = panel {- let connection = StubAgentConnection::new();- connection.set_next_prompt_updates(vec![- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(- "Done".into(),- )),- ]);- open_thread_with_connection(&panel, connection, cx);- send_message(&panel, cx);+ let agent_id = AgentId::new(format!("prop-agent-{}", state.thread_counter));+ let connection = StubAgentConnection::new().with_agent_id(agent_id.clone());+ open_thread_with_custom_connection(&panel, connection.clone(), cx);+ let thread_id = active_thread_id(&panel, cx);let session_id = active_session_id(&panel, cx);+ // Make the thread non-draft without exercising the prompt+ // send path; these invariants are about sidebar state, not+ // git checkpointing during user prompts.+ cx.update(|_, cx| {+ connection.send_update(+ session_id.clone(),+ acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(+ "Done".into(),+ )),+ cx,+ );+ });+ cx.run_until_parked();state.saved_thread_ids.push(session_id.clone());let title: SharedString = format!("Thread {}", state.thread_counter).into();@@ -10090,15 +10976,24 @@ mod property_test {chrono::TimeZone::with_ymd_and_hms(&chrono::Utc, 2024, 1, 1, 0, 0, 0).unwrap()+ chrono::Duration::seconds(state.thread_counter as i64);- save_thread_metadata(- session_id,- Some(title),+ let metadata = cx.update(|_, cx| ThreadMetadata {+ thread_id,+ session_id: Some(session_id),+ agent_id,+ title: Some(title),+ title_override: None,updated_at,- None,- None,- &project,- cx,- );+ created_at: None,+ interacted_at: None,+ worktree_paths: project.read(cx).worktree_paths(cx),+ archived: false,+ remote_connection: project.read(cx).remote_connection_options(cx),+ });+ cx.update(|_, cx| {+ ThreadMetadataStore::global(cx)+ .update(cx, |store, cx| store.save(metadata, cx))+ });+ cx.run_until_parked();}}Operation::SaveWorktreeThread { worktree_index } => {@@ -10564,11 +11459,12 @@ mod property_test {// content yet.let panel = active_workspace.read(cx).panel::<AgentPanel>(cx).unwrap();let panel_has_content = panel.read(cx).active_thread_id(cx).is_some()- || panel.read(cx).active_conversation_view().is_some();+ || panel.read(cx).active_conversation_view().is_some()+ || panel.read(cx).active_terminal_id().is_some();let Some(entry) = sidebar.active_entry.as_ref() else {if panel_has_content {- anyhow::bail!("active_entry is None but panel has content (draft or thread)");+ anyhow::bail!("active_entry is None but panel has content");}return Ok(());};@@ -10721,15 +11617,19 @@ mod property_test {use std::sync::atomic::{AtomicUsize, Ordering};static NEXT_PROPTEST_DB: AtomicUsize = AtomicUsize::new(0);+ let test_db_id = NEXT_PROPTEST_DB.fetch_add(1, Ordering::SeqCst);+ cx.update(|cx| {+ cx.set_global(TestTerminalMetadataDbName(format!(+ "PROPTEST_TERMINAL_THREAD_METADATA_{test_db_id}"+ )));+ });+agent_ui::test_support::init_test(cx);cx.update(|cx| {cx.set_global(db::AppDatabase::test_new());cx.set_global(agent_ui::MaxIdleRetainedThreads(1));cx.set_global(agent_ui::thread_metadata_store::TestMetadataDbName(- format!(- "PROPTEST_THREAD_METADATA_{}",- NEXT_PROPTEST_DB.fetch_add(1, Ordering::SeqCst)- ),+ format!("PROPTEST_THREAD_METADATA_{test_db_id}"),));ThreadStore::init_global(cx);diff --git a/crates/sidebar/src/thread_switcher.rs b/crates/sidebar/src/thread_switcher.rsindex a91ae5fe067..e2f9cddd747 100644--- a/crates/sidebar/src/thread_switcher.rs+++ b/crates/sidebar/src/thread_switcher.rs@@ -1,5 +1,9 @@use action_log::DiffStats;-use agent_ui::{TerminalId, thread_metadata_store::ThreadMetadata};+#[cfg(test)]+use agent_ui::TerminalId;+use agent_ui::{+ terminal_thread_metadata_store::TerminalThreadMetadata, thread_metadata_store::ThreadMetadata,+};use gpui::{Action as _, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, Modifiers,ModifiersChangedEvent, Render, ScrollHandle, SharedString, prelude::*,@@ -8,6 +12,8 @@ use ui::{AgentThreadStatus, ThreadItem, ThreadItemWorktreeInfo, WithScrollbar, puse workspace::{ModalView, Workspace};use zed_actions::agents_sidebar::ToggleThreadSwitcher;+use super::ThreadEntryWorkspace;+#[derive(Clone)]pub(crate) struct ThreadSwitcherThreadEntry {pub title: SharedString,@@ -27,12 +33,10 @@ pub(crate) struct ThreadSwitcherThreadEntry {#[derive(Clone)]pub(crate) struct ThreadSwitcherTerminalEntry {- pub terminal_id: TerminalId,- pub title: SharedString,- pub workspace: Entity<Workspace>,+ pub metadata: TerminalThreadMetadata,+ pub(super) workspace: ThreadEntryWorkspace,pub project_name: Option<SharedString>,pub worktrees: Vec<ThreadItemWorktreeInfo>,- pub created_at: chrono::DateTime<chrono::Utc>,pub notified: bool,pub timestamp: SharedString,}@@ -44,26 +48,26 @@ pub(crate) enum ThreadSwitcherEntry {}#[derive(Clone)]-pub(crate) enum ThreadSwitcherSelection {+pub(super) enum ThreadSwitcherSelection {Thread {metadata: ThreadMetadata,workspace: Entity<Workspace>,},Terminal {- terminal_id: TerminalId,- workspace: Entity<Workspace>,+ metadata: TerminalThreadMetadata,+ workspace: ThreadEntryWorkspace,},}impl ThreadSwitcherEntry {- pub(crate) fn selection(&self) -> ThreadSwitcherSelection {+ pub(super) fn selection(&self) -> ThreadSwitcherSelection {match self {Self::Thread(entry) => ThreadSwitcherSelection::Thread {metadata: entry.metadata.clone(),workspace: entry.workspace.clone(),},Self::Terminal(entry) => ThreadSwitcherSelection::Terminal {- terminal_id: entry.terminal_id,+ metadata: entry.metadata.clone(),workspace: entry.workspace.clone(),},}@@ -75,16 +79,17 @@ impl ThreadSwitcherEntry {"thread-switcher-thread-{:?}",entry.metadata.thread_id)),- Self::Terminal(entry) => {- SharedString::from(format!("thread-switcher-terminal-{}", entry.terminal_id))- }+ Self::Terminal(entry) => SharedString::from(format!(+ "thread-switcher-terminal-{}",+ entry.metadata.terminal_id+ )),}}fn title(&self) -> SharedString {match self {Self::Thread(entry) => entry.title.clone(),- Self::Terminal(entry) => entry.title.clone(),+ Self::Terminal(entry) => entry.metadata.title.clone(),}}@@ -172,12 +177,12 @@ impl ThreadSwitcherEntry {pub fn terminal_id(&self) -> Option<TerminalId> {match self {Self::Thread(_) => None,- Self::Terminal(entry) => Some(entry.terminal_id),+ Self::Terminal(entry) => Some(entry.metadata.terminal_id),}}}-pub(crate) enum ThreadSwitcherEvent {+pub(super) enum ThreadSwitcherEvent {Preview(ThreadSwitcherSelection),Confirmed(ThreadSwitcherSelection),Dismissed,