Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Bring back draft threads (#54292)
Mikayla Makibbe23cc40bbc
diff --git a/crates/agent_ui/src/agent_panel.rs b/crates/agent_ui/src/agent_panel.rsindex 2a2a42b3951..ba5dc488db9 100644--- a/crates/agent_ui/src/agent_panel.rs+++ b/crates/agent_ui/src/agent_panel.rs@@ -198,12 +198,17 @@ struct SerializedAgentPanel {last_created_entry_kind: AgentPanelEntryKind,#[serde(default)]last_active_thread: Option<SerializedActiveThread>,- draft_thread_prompt: Option<Vec<acp::ContentBlock>>,+ #[serde(default)]+ new_draft_thread_id: Option<ThreadId>,}#[derive(Serialize, Deserialize, Debug)]struct SerializedActiveThread {+ /// For drafts this is `None`; use `thread_id` to address them instead.session_id: Option<String>,+ /// Optional for back-compat with older serialized payloads that only carried `session_id`.+ #[serde(default)]+ thread_id: Option<ThreadId>,agent_type: Agent,title: Option<String>,work_dirs: Option<SerializedPathList>,@@ -213,9 +218,9 @@ pub fn init(cx: &mut App) {cx.observe_new(|workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {workspace- .register_action(|workspace, _: &NewThread, window, cx| {+ .register_action(|workspace, action: &NewThread, window, cx| {if let Some(panel) = workspace.panel::<AgentPanel>(cx) {- panel.update(cx, |panel, cx| panel.new_entry(Some(workspace), window, cx));+ panel.update(cx, |panel, cx| panel.new_thread(action, window, cx));workspace.focus_panel::<AgentPanel>(window, cx);}})@@ -812,6 +817,8 @@ pub struct AgentPanel {_draft_editor_observation: Option<Subscription>,_thread_metadata_store_subscription: Subscription,last_context_source: Option<AgentContextSource>,++ is_active: bool,}impl AgentPanel {@@ -824,6 +831,11 @@ impl AgentPanel {let last_created_entry_kind = self.last_created_entry_kind;let is_draft_active = self.active_thread_is_draft(cx);+ let active_thread_id = self.active_thread_id(cx);+ let active_thread_agent = self+ .active_conversation_view()+ .map(|cv| cv.read(cx).agent_key().clone())+ .unwrap_or_else(|| self.selected_agent.clone());let last_active_thread = self.active_agent_thread(cx).map(|thread| {@@ -833,7 +845,8 @@ impl AgentPanel {let work_dirs = thread.work_dirs().cloned();SerializedActiveThread {session_id: (!is_draft_active).then(|| thread.session_id().0.to_string()),- agent_type: self.selected_agent.clone(),+ thread_id: active_thread_id,+ agent_type: active_thread_agent.clone(),title: title.map(|t| t.to_string()),work_dirs: work_dirs.map(|dirs| dirs.serialize()),}@@ -853,7 +866,8 @@ impl AgentPanel {.and_then(|store| store.read(cx).entry_by_session(&session_id).cloned());Some(SerializedActiveThread {session_id: Some(session_id.0.to_string()),- agent_type: self.selected_agent.clone(),+ thread_id: active_thread_id,+ agent_type: active_thread_agent.clone(),title: metadata.as_ref().and_then(|m| m.title.as_ref())@@ -862,19 +876,12 @@ impl AgentPanel {})});+ let new_draft_thread_id = self+ .draft_thread+ .as_ref()+ .map(|draft| draft.read(cx).thread_id);+let kvp = KeyValueStore::global(cx);- let draft_thread_prompt = self.draft_thread.as_ref().and_then(|conversation| {- Some(- conversation- .read(cx)- .root_thread_view()?- .read(cx)- .thread- .read(cx)- .draft_prompt()?- .to_vec(),- )- });self.pending_serialization = Some(cx.background_spawn(async move {save_serialized_panel(workspace_id,@@ -882,7 +889,7 @@ impl AgentPanel {selected_agent: Some(selected_agent),last_created_entry_kind,last_active_thread,- draft_thread_prompt,+ new_draft_thread_id,},kvp,)@@ -922,131 +929,99 @@ impl AgentPanel {}).await;- let was_draft_active = serialized_panel- .as_ref()- .and_then(|p| p.last_active_thread.as_ref())- .is_some_and(|t| t.session_id.is_none());-- let last_active_thread = if let Some(thread_info) = serialized_panel+ let thread_to_restore = serialized_panel.as_ref()- .and_then(|p| p.last_active_thread.as_ref())- {- match &thread_info.session_id {- Some(session_id_str) => {- let session_id = acp::SessionId::new(session_id_str.clone());- let is_restorable = cx- .update(|_window, cx| {- let store = ThreadMetadataStore::global(cx);- store- .read(cx)- .entry_by_session(&session_id)- .is_some_and(|entry| !entry.archived)- })- .unwrap_or(false);- if is_restorable {- Some(thread_info)- } else {+ .and_then(|panel| panel.last_active_thread.as_ref())+ .and_then(|info| {+ let lookup = cx.update(|_window, cx| {+ let store = ThreadMetadataStore::global(cx);+ let store = store.read(cx);+ let primary = info.thread_id.and_then(|tid| store.entry(tid));+ let fallback = info.session_id.as_ref().and_then(|sid| {+ store.entry_by_session(&acp::SessionId::new(sid.clone()))+ });+ primary+ .or(fallback)+ .filter(|entry| !entry.archived)+ .map(|entry| entry.thread_id)+ });+ match lookup {+ Ok(Some(thread_id)) => Some((info, thread_id)),+ Ok(None) => {log::info!(- "last active thread {} is archived or missing, skipping restoration",- session_id_str+ "last active thread is archived or missing, skipping restoration");None}+ Err(err) => {+ log::warn!("failed to look up last active thread metadata: {err}");+ None+ }}- None => None,- }- } else {- None- };+ });let panel = workspace.update_in(cx, |workspace, window, cx| {let panel = cx.new(|cx| Self::new(workspace, prompt_store, window, cx));panel.update(cx, |panel, cx| {let is_via_collab = panel.project.read(cx).is_via_collab();-- // Only apply a non-native global fallback to local projects.- // Collab workspaces only support NativeAgent, so inheriting a- // custom agent would cause set_active → new_agent_thread_inner- // to bypass the collab guard in external_thread.+ // Collab workspaces only support NativeAgent; clamp any+ // non-native choice so `set_active` can't bypass the+ // collab guard in `external_thread`.+ let clamp = |agent: Agent| {+ if is_via_collab && !agent.is_native() {+ Agent::NativeAgent+ } else {+ agent+ }+ };let global_fallback =global_last_used_agent.filter(|agent| !is_via_collab || agent.is_native());if let Some(serialized_panel) = &serialized_panel {panel.last_created_entry_kind = serialized_panel.last_created_entry_kind;- if let Some(selected_agent) = serialized_panel.selected_agent.clone() {- panel.selected_agent = selected_agent;- } else if let Some(agent) = global_fallback {- panel.selected_agent = agent;- }- } else if let Some(agent) = global_fallback {- panel.selected_agent = agent;}- cx.notify();- });- if let Some(thread_info) = last_active_thread {- if let Some(session_id_str) = &thread_info.session_id {- let agent = thread_info.agent_type.clone();- let session_id: acp::SessionId = session_id_str.clone().into();- panel.update(cx, |panel, cx| {- panel.selected_agent = agent.clone();- panel.load_agent_thread(- agent,- session_id,- thread_info.work_dirs.as_ref().map(|dirs| PathList::deserialize(dirs)),- thread_info.title.as_ref().map(|t| t.clone().into()),- false,- "agent_panel",- window,- cx,- );- });+ // The thread being restored may have been bound to an+ // agent different from the panel's last selected one+ // (e.g. a draft created while a different agent was+ // active). When restoring a thread, prefer its agent+ // so the draft survives reload bound to the right+ // backend; otherwise fall back to the serialized+ // selection, then the global last-used agent.+ let initial_agent = match &thread_to_restore {+ Some((info, _)) => Some(clamp(info.agent_type.clone())),+ None => serialized_panel+ .as_ref()+ .and_then(|p| p.selected_agent.clone())+ .map(clamp)+ .or(global_fallback),+ };+ if let Some(agent) = initial_agent {+ panel.selected_agent = agent;}- }-- let draft_prompt = serialized_panel- .as_ref()- .and_then(|p| p.draft_thread_prompt.clone());- if draft_prompt.is_some() || was_draft_active {- panel.update(cx, |panel, cx| {- let agent = if panel.project.read(cx).is_via_collab() {- Agent::NativeAgent- } else {- panel.selected_agent.clone()- };- let initial_content = draft_prompt.map(|blocks| {- AgentInitialContent::ContentBlock {- blocks,- auto_submit: false,- }- });- let thread = panel.create_agent_thread(+ if let Some((info, thread_id)) = thread_to_restore {+ let agent = panel.selected_agent.clone();+ panel.load_agent_thread(agent,- None,- None,- None,- initial_content,+ thread_id,+ info.work_dirs.as_ref().map(PathList::deserialize),+ info.title.clone().map(Into::into),+ false,"agent_panel",window,cx,);- panel.draft_thread = Some(thread.conversation_view.clone());- panel.observe_draft_editor(&thread.conversation_view, cx);-- if was_draft_active && last_active_thread.is_none() {- panel.set_base_view(- BaseView::AgentThread {- conversation_view: thread.conversation_view,- },- false,- window,- cx,- );- }- });- }+ }+ if let Some(new_draft_thread_id) = serialized_panel+ .as_ref()+ .and_then(|p| p.new_draft_thread_id)+ {+ panel.restore_new_draft(new_draft_thread_id, window, cx);+ }+ cx.notify();+ });panel})?;@@ -1176,6 +1151,7 @@ impl AgentPanel {_draft_editor_observation: None,_thread_metadata_store_subscription,last_context_source: None,+ is_active: false,};// Initial sync of agent servers from extensions@@ -1255,16 +1231,55 @@ impl AgentPanel {window: &mut Window,cx: &mut Context<Self>,) {- self.load_agent_thread(- crate::Agent::NativeAgent,- session_id,- work_dirs,- title,- true,- "agent_panel",- window,- cx,+ // Share links / clipboard imports enter with only a session id. If+ // this machine already has a metadata row for the session, route+ // through the normal thread-id path.+ let existing_thread_id = ThreadMetadataStore::try_global(cx).and_then(|store| {+ store+ .read(cx)+ .entry_by_session(&session_id)+ .map(|m| m.thread_id)+ });+ if let Some(thread_id) = existing_thread_id {+ self.load_agent_thread(+ crate::Agent::NativeAgent,+ thread_id,+ work_dirs,+ title,+ true,+ "agent_panel",+ window,+ cx,+ );+ } else {+ self.external_thread_by_session(+ crate::Agent::NativeAgent,+ session_id,+ work_dirs,+ title,+ true,+ "agent_panel",+ window,+ cx,+ );+ }+ }++ fn external_thread_by_session(+ &mut self,+ agent: Agent,+ session_id: acp::SessionId,+ work_dirs: Option<PathList>,+ title: Option<SharedString>,+ focus: bool,+ _source: &'static str,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ let thread = self.create_agent_thread_with_server_for_external_session(+ agent, None, session_id, work_dirs, title, None, window, cx,);+ self.set_base_view(thread.into(), focus, window, cx);}pub(crate) fn context_server_registry(&self) -> &Entity<ContextServerRegistry> {@@ -1299,28 +1314,17 @@ impl AgentPanel {cx.notify();}- pub fn new_entry(- &mut self,- workspace: Option<&Workspace>,- window: &mut Window,- cx: &mut Context<Self>,- ) {+ pub fn new_thread(&mut self, _action: &NewThread, window: &mut Window, cx: &mut Context<Self>) {if self.should_create_terminal_for_new_entry(cx) {- self.new_terminal(workspace, window, cx);+ // `new_terminal` falls back to `default_terminal_working_directory`+ // when no workspace is passed; we pass `None` here because the+ // panel already holds a `WeakEntity<Workspace>` it can resolve.+ self.new_terminal(None, window, cx);} else {self.activate_new_thread(true, "agent_panel", window, cx);}}- pub fn new_thread(&mut self, _action: &NewThread, window: &mut Window, cx: &mut Context<Self>) {- self.new_entry(None, window, cx);- }-- fn new_agent_thread(&mut self, agent: Agent, window: &mut Window, cx: &mut Context<Self>) {- self.selected_agent = agent;- self.activate_new_thread(true, "agent_panel", window, cx);- }-pub fn activate_new_thread(&mut self,focus: bool,@@ -1329,16 +1333,130 @@ impl AgentPanel {cx: &mut Context<Self>,) {self.set_last_created_entry_kind(AgentPanelEntryKind::Thread, cx);++ // If the user is viewing a *parked* draft and the ephemeral+ // new-draft slot is occupied, pressing `+` should just focus the+ // ephemeral draft — not park it and create yet another empty one.+ // This matches the mental model of `+` as "go to my new-thread+ // slot". The parked draft will be put back into `retained_threads`+ // by `set_base_view`'s `retain_running_thread` call.+ if let Some(draft) = self.draft_thread.clone()+ && self.active_thread_is_draft(cx)+ && !self.active_view_is_new_draft(cx)+ {+ self.set_base_view(+ BaseView::AgentThread {+ conversation_view: draft,+ },+ focus,+ window,+ cx,+ );+ return;+ }++ if let Some(draft) = self.draft_thread.clone()+ && self.draft_has_content(&draft, cx)+ {+ let draft_id = draft.read(cx).thread_id;+ self.draft_thread = None;+ self._draft_editor_observation = None;+ self.retained_threads.insert(draft_id, draft);+ }self.activate_draft(focus, trigger, window, cx);}+ fn draft_has_content(&self, draft: &Entity<ConversationView>, cx: &App) -> bool {+ let cv = draft.read(cx);+ if let Some(thread_view) = cv.active_thread() {+ let text = thread_view.read(cx).message_editor.read(cx).text(cx);+ if !text.trim().is_empty() {+ return true;+ }+ }+ if let Some(acp_thread) = cv.root_thread(cx) {+ let thread = acp_thread.read(cx);+ if !thread.is_draft_thread() {+ return true;+ }+ if thread+ .draft_prompt()+ .is_some_and(|blocks| !blocks.is_empty())+ {+ return true;+ }+ }+ false+ }++ /// Reattaches the panel's new-draft slot to the persisted `thread_id`,+ /// seeding the editor with any prompt text from the draft-prompt kvp+ /// store.+ ///+ /// If the active view already holds this thread — because the user's+ /// last-active thread was the new-draft itself — we reuse that+ /// ConversationView instead of building a second one.+ fn restore_new_draft(+ &mut self,+ thread_id: ThreadId,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ let active_matching = match &self.base_view {+ BaseView::AgentThread { conversation_view }+ if conversation_view.read(cx).thread_id == thread_id =>+ {+ Some(conversation_view.clone())+ }+ _ => None,+ };+ if let Some(conversation_view) = active_matching {+ self.observe_draft_editor(&conversation_view, cx);+ self.draft_thread = Some(conversation_view);+ return;+ }++ let Some(metadata) = ThreadMetadataStore::try_global(cx)+ .and_then(|store| store.read(cx).entry(thread_id).cloned())+ .filter(|m| m.is_draft())+ else {+ return;+ };++ let agent = if self.project.read(cx).is_via_collab() {+ Agent::NativeAgent+ } else {+ Agent::from(metadata.agent_id.clone())+ };+ let initial_content = crate::draft_prompt_store::read(thread_id, cx).map(|blocks| {+ AgentInitialContent::ContentBlock {+ blocks,+ auto_submit: false,+ }+ });+ let thread = self.create_agent_thread_with_server(+ agent,+ None,+ Some(thread_id),+ Some(metadata.folder_paths().clone()),+ metadata.title.clone(),+ initial_content,+ "agent_panel",+ window,+ cx,+ );+ self.observe_draft_editor(&thread.conversation_view, cx);+ self.draft_thread = Some(thread.conversation_view);+ }+pub fn new_external_agent_thread(&mut self,action: &NewExternalAgentThread,window: &mut Window,cx: &mut Context<Self>,) {- self.new_agent_thread(action.agent.clone().into(), window, cx);+ self.selected_agent = action.agent.clone().into();+ self.activate_new_thread(true, "agent_panel", window, cx);}pub fn new_terminal(@@ -1914,20 +2032,41 @@ impl AgentPanel {) -> Entity<ConversationView> {let desired_agent = self.selected_agent(cx);if let Some(draft) = &self.draft_thread {+ let draft_entity = draft.entity_id();let agent_matches = *draft.read(cx).agent_key() == desired_agent;- if agent_matches {+ let has_editor_content = draft.read(cx).root_thread_view().is_some_and(|tv| {+ !tv.read(cx)+ .message_editor+ .read(cx)+ .text(cx)+ .trim()+ .is_empty()+ });+ // Only retarget the empty draft when the user is actively+ // viewing it — that's the case where switching agents in the+ // toolbar should replace the draft with one bound to the+ // newly-selected agent. When the draft is parked in its slot+ // while the user is viewing a real thread, `selected_agent`+ // reflects that real thread's agent and must not be allowed+ // to silently rebuild the draft.+ let draft_is_active = matches!(+ &self.base_view,+ BaseView::AgentThread { conversation_view }+ if conversation_view.entity_id() == draft_entity+ );+ if agent_matches || has_editor_content || !draft_is_active {return draft.clone();}self.draft_thread = None;self._draft_editor_observation = None;}- let previous_content = self.active_initial_content(cx);- let thread = self.create_agent_thread(+ let thread = self.create_agent_thread_with_server(desired_agent,None,None,None,- previous_content,+ None,+ None,source,window,cx,@@ -1968,7 +2107,15 @@ impl AgentPanel {window: &mut Window,cx: &mut Context<Self>,) {- let Some(conversation_view) = self.retained_threads.remove(&id) else {+ let conversation_view = if let Some(view) = self.retained_threads.remove(&id) {+ view+ } else if let Some(draft) = &self.draft_thread {+ if draft.read(cx).thread_id == id {+ draft.clone()+ } else {+ return;+ }+ } else {return;};self.set_base_view(@@ -1988,6 +2135,39 @@ impl AgentPanel {}}+ /// Drops a thread — retained or the active ephemeral draft — from+ /// the panel and deletes its metadata row. Used by the sidebar when+ /// the user dismisses a parked draft.+ pub fn remove_thread(&mut self, id: ThreadId, window: &mut Window, cx: &mut Context<Self>) {+ self.retained_threads.remove(&id);+ ThreadMetadataStore::global(cx).update(cx, |store, cx| {+ store.delete(id, cx);+ });++ if self+ .draft_thread+ .as_ref()+ .is_some_and(|d| d.read(cx).thread_id == id)+ {+ self.draft_thread = None;+ self._draft_editor_observation = None;+ }++ if self.active_thread_id(cx) == Some(id) {+ self.clear_overlay_state();+ self.activate_draft(false, "agent_panel", window, cx);+ self.serialize(cx);+ cx.emit(AgentPanelEvent::ActiveViewChanged);+ cx.notify();+ }+ }++ pub fn ephemeral_draft_thread_id(&self, cx: &App) -> Option<ThreadId> {+ self.draft_thread+ .as_ref()+ .map(|draft| draft.read(cx).thread_id)+ }+pub fn active_terminal_id(&self) -> Option<TerminalId> {match &self.base_view {BaseView::Terminal { terminal_id } => Some(*terminal_id),@@ -2019,6 +2199,11 @@ impl AgentPanel {let cv = self.retained_threads.get(&id)+ .or_else(|| {+ self.draft_thread+ .as_ref()+ .filter(|draft| draft.read(cx).thread_id == id)+ }).or_else(|| match &self.base_view {BaseView::AgentThread { conversation_view }if conversation_view.read(cx).thread_id == id =>@@ -2086,7 +2271,7 @@ impl AgentPanel {fn external_thread(&mut self,agent_choice: Option<crate::Agent>,- resume_session_id: Option<acp::SessionId>,+ resume_thread_id: Option<ThreadId>,work_dirs: Option<PathList>,title: Option<SharedString>,initial_content: Option<AgentInitialContent>,@@ -2096,9 +2281,10 @@ impl AgentPanel {cx: &mut Context<Self>,) {let agent = agent_choice.unwrap_or_else(|| self.selected_agent(cx));- let thread = self.create_agent_thread(+ let thread = self.create_agent_thread_with_server(agent,- resume_session_id,+ None,+ resume_thread_id,work_dirs,title,initial_content,@@ -2909,6 +3095,10 @@ impl AgentPanel {let Some(thread_id) = this.active_thread_id(cx) else {return;};+ // If the draft was the active thread, it has now been+ // promoted to a real thread. Clear the ephemeral+ // pointer; the ConversationView itself stays put as+ // the active base view.if this.draft_thread.as_ref().is_some_and(|d| {this.active_conversation_view().is_some_and(|active| active.entity_id() == d.entity_id())@@ -2971,7 +3161,7 @@ impl AgentPanel {pub fn load_agent_thread(&mut self,agent: Agent,- session_id: acp::SessionId,+ thread_id: ThreadId,work_dirs: Option<PathList>,title: Option<SharedString>,focus: bool,@@ -2980,57 +3170,67 @@ impl AgentPanel {cx: &mut Context<Self>,) {if let Some(store) = ThreadMetadataStore::try_global(cx) {- let thread_id = store- .read(cx)- .entry_by_session(&session_id)- .map(|t| t.thread_id);- if let Some(thread_id) = thread_id {- store.update(cx, |store, cx| {- store.unarchive(thread_id, cx);- });- }+ store.update(cx, |store, cx| {+ store.unarchive(thread_id, cx);+ });}- let has_session = |cv: &Entity<ConversationView>| -> bool {- cv.read(cx)- .root_session_id- .as_ref()- .is_some_and(|id| id == &session_id)- };-- // Check if the active view already has this session.+ // Check if the active view already holds this thread.if let BaseView::AgentThread { conversation_view } = &self.base_view {- if has_session(conversation_view) {+ if conversation_view.read(cx).thread_id == thread_id {self.clear_overlay_state();cx.emit(AgentPanelEvent::ActiveViewChanged);return;}}- // Check if a retained thread has this session — promote it.- let retained_key = self- .retained_threads- .iter()- .find(|(_, cv)| has_session(cv))- .map(|(id, _)| *id);- if let Some(thread_id) = retained_key {- if let Some(conversation_view) = self.retained_threads.remove(&thread_id) {- self.set_base_view(- BaseView::AgentThread { conversation_view },- focus,- window,- cx,- );- return;- }+ // Check if the thread is already in memory — either as the+ // ephemeral draft pointer or in retained_threads. Either way we+ // can just reactivate without touching storage.+ if let Some(draft) = self.draft_thread.clone()+ && draft.read(cx).thread_id == thread_id+ {+ self.set_base_view(+ BaseView::AgentThread {+ conversation_view: draft,+ },+ focus,+ window,+ cx,+ );+ return;+ }+ if let Some(conversation_view) = self.retained_threads.remove(&thread_id) {+ self.set_base_view(+ BaseView::AgentThread { conversation_view },+ focus,+ window,+ cx,+ );+ return;}+ // Not in memory. Build a fresh ConversationView. For drafts we+ // also seed the message editor with any prompt text the user had+ // typed before closing the window (persisted in the scoped kvp+ // draft-prompt store).+ let is_draft = ThreadMetadataStore::try_global(cx)+ .and_then(|store| store.read(cx).entry(thread_id).map(|m| m.is_draft()))+ .unwrap_or(false);+ let initial_content = is_draft+ .then(|| crate::draft_prompt_store::read(thread_id, cx))+ .flatten()+ .map(|blocks| AgentInitialContent::ContentBlock {+ blocks,+ auto_submit: false,+ });+self.external_thread(Some(agent),- Some(session_id),+ Some(thread_id),work_dirs,title,- None,+ initial_content,focus,source,window,@@ -3038,10 +3238,11 @@ impl AgentPanel {);}- pub(crate) fn create_agent_thread(+ pub(crate) fn create_agent_thread_with_server(&mut self,agent: Agent,- resume_session_id: Option<acp::SessionId>,+ server_override: Option<Rc<dyn AgentServer>>,+ resume_thread_id: Option<ThreadId>,work_dirs: Option<PathList>,title: Option<SharedString>,initial_content: Option<AgentInitialContent>,@@ -3049,9 +3250,14 @@ impl AgentPanel {window: &mut Window,cx: &mut Context<Self>,) -> AgentThread {- self.create_agent_thread_with_server(+ let resume_session_id = resume_thread_id.and_then(|tid| {+ ThreadMetadataStore::try_global(cx)+ .and_then(|store| store.read(cx).entry(tid).and_then(|m| m.session_id.clone()))+ });+ self.create_agent_thread_inner(agent,- None,+ server_override,+ resume_thread_id,resume_session_id,work_dirs,title,@@ -3062,11 +3268,45 @@ impl AgentPanel {)}- fn create_agent_thread_with_server(+ /// Legacy entry that resumes a thread by raw ACP session id when no+ /// local [`ThreadMetadata`] row exists yet (share-link imports and+ /// clipboard imports).+ ///+ /// TODO(legacy-session-id): migrate remaining callers (share-link+ /// handler, clipboard import) to mint a [`ThreadId`] + seed metadata+ /// so they can route through [`create_agent_thread_with_server`] and+ /// this entry can be deleted.+ fn create_agent_thread_with_server_for_external_session(&mut self,agent: Agent,server_override: Option<Rc<dyn AgentServer>>,- resume_session_id: Option<acp::SessionId>,+ resume_session_id: acp::SessionId,+ work_dirs: Option<PathList>,+ title: Option<SharedString>,+ initial_content: Option<AgentInitialContent>,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) -> AgentThread {+ self.create_agent_thread_inner(+ agent,+ server_override,+ None,+ Some(resume_session_id),+ work_dirs,+ title,+ initial_content,+ "agent_panel",+ window,+ cx,+ )+ }++ fn create_agent_thread_inner(+ &mut self,+ agent: Agent,+ server_override: Option<Rc<dyn AgentServer>>,+ resume_thread_id: Option<ThreadId>,+ resume_session_id: Option<acp::SessionId>,work_dirs: Option<PathList>,title: Option<SharedString>,initial_content: Option<AgentInitialContent>,@@ -3074,14 +3314,7 @@ impl AgentPanel {window: &mut Window,cx: &mut Context<Self>,) -> AgentThread {- let existing_metadata = resume_session_id.as_ref().and_then(|sid| {- ThreadMetadataStore::try_global(cx)- .and_then(|store| store.read(cx).entry_by_session(sid).cloned())- });- let thread_id = existing_metadata- .as_ref()- .map(|m| m.thread_id)- .unwrap_or_else(ThreadId::new);+ let thread_id = resume_thread_id.unwrap_or_else(ThreadId::new);let workspace = self.workspace.clone();let project = self.project.clone();@@ -3151,12 +3384,18 @@ impl AgentPanel {.is_some_and(|thread| !thread.read(cx).entries().is_empty())}- pub fn active_thread_is_draft(&self, _cx: &App) -> bool {+ /// Whether the active view is in the **ephemeral** new-draft slot+ pub fn active_view_is_new_draft(&self, _cx: &App) -> bool {self.draft_thread.as_ref().is_some_and(|draft| {self.active_conversation_view().is_some_and(|active| active.entity_id() == draft.entity_id())})}+ /// Whether the active thread is any kind of draft+ pub fn active_thread_is_draft(&self, cx: &App) -> bool {+ self.active_agent_thread(cx)+ .is_some_and(|thread| thread.read(cx).is_draft_thread())+ }}impl Focusable for AgentPanel {@@ -3254,6 +3493,7 @@ impl Panel for AgentPanel {}fn set_active(&mut self, active: bool, window: &mut Window, cx: &mut Context<Self>) {+ self.is_active = active;if active {self.ensure_thread_initialized(window, cx);}@@ -3407,11 +3647,12 @@ impl AgentPanel {return false;};- let thread = self.create_agent_thread(+ let thread = self.create_agent_thread_with_server(agent,None,None,None,+ None,Some(initial_content),"agent_panel",window,@@ -3782,8 +4023,10 @@ impl AgentPanel {workspace.panel::<AgentPanel>(cx){panel.update(cx, |panel, cx| {- panel.new_agent_thread(- Agent::NativeAgent,+ panel.selected_agent = Agent::NativeAgent;+ panel.activate_new_thread(+ true,+ "agent_panel",window,cx,);@@ -4491,6 +4734,12 @@ impl AgentPanel {Self::new(workspace, None, window, cx)}+ /// Drops a thread's `ConversationView` from `retained_threads` without+ /// deleting its metadata or kvp state. Simulates the post-restart+ pub fn test_unload_retained_thread(&mut self, id: ThreadId) -> bool {+ self.retained_threads.remove(&id).is_some()+ }+/// Opens an external thread using an arbitrary AgentServer.////// This is a test-only helper that allows visual tests and integration tests@@ -4535,10 +4784,20 @@ impl AgentPanel {id: server.agent_id(),};+ // The panel addresses threads by `ThreadId` after the draft work;+ // map the test-provided `session_id` back through the metadata+ // store so this helper still resumes the right thread.+ let resume_thread_id = ThreadMetadataStore::try_global(cx).and_then(|store| {+ store+ .read(cx)+ .entry_by_session(&resume_session_id)+ .map(|m| m.thread_id)+ });+let thread = self.create_agent_thread_with_server(ext_agent,Some(server),- Some(resume_session_id),+ resume_thread_id,None,None,None,@@ -5482,27 +5741,24 @@ mod tests {let draft_session_id = active_session_id(&panel, cx);let thread_id = active_thread_id(&panel, cx);- // No metadata should exist yet for a draft.+ // A draft thread is persisted with session_id: None.cx.update(|_window, cx| {let store = ThreadMetadataStore::global(cx).read(cx);+ let entry = store+ .entry(thread_id)+ .expect("draft thread should have a metadata row");assert!(- store.entry(thread_id).is_none(),- "draft thread should not have metadata in the store"+ entry.is_draft(),+ "draft thread metadata should have session_id=None, got {:?}",+ entry.session_id,);});- // Set draft prompt and serialize — the draft should survive a round-trip- // with its prompt intact but a fresh ACP session.- let draft_prompt_blocks = vec![acp::ContentBlock::Text(acp::TextContent::new(- "Hello from draft",- ))];- panel.update(cx, |panel, cx| {- let thread = panel.active_agent_thread(cx).unwrap();- thread.update(cx, |thread, cx| {- thread.set_draft_prompt(Some(draft_prompt_blocks.clone()), cx);- });- panel.serialize(cx);- });+ // Type into the message editor; the editor observer pushes the text+ // into `AcpThread.draft_prompt`, which emits `PromptUpdated` and+ // persists the prompt to the kvp store.+ crate::test_support::type_draft_prompt(&panel, "Hello from draft", cx);+ panel.update(cx, |panel, cx| panel.serialize(cx));cx.run_until_parked();let async_cx = cx.update(|window, cx| window.to_async(cx));@@ -5517,34 +5773,50 @@ mod tests {"reloaded panel should still show the draft as active");assert!(- panel.draft_thread.is_some(),- "reloaded panel should have a draft_thread"+ panel.active_view_is_new_draft(cx),+ "reloaded draft should still occupy the new-draft slot: \+ what's in the new-draft slot stays there across restarts, \+ regardless of whether it's also the active view"+ );+ let active_entity = panel.active_conversation_view().map(|v| v.entity_id());+ let draft_entity = panel.draft_thread.as_ref().map(|v| v.entity_id());+ assert!(+ active_entity.is_some() && active_entity == draft_entity,+ "active view and draft slot should share a single ConversationView entity \+ (active={active_entity:?}, draft={draft_entity:?})");});+ // Thread identity is stable across reload — the metadata row we wrote+ // pre-reload maps back to the same ConversationView.+ let reloaded_thread_id = active_thread_id(&reloaded_panel, cx);+ assert_eq!(+ reloaded_thread_id, thread_id,+ "reloaded draft should preserve its ThreadId"+ );++ // ACP session_id is NOT preserved: drafts don't persist a session id,+ // so the reloaded ConversationView opens a fresh ACP session.let reloaded_session_id = active_session_id(&reloaded_panel, cx);assert_ne!(reloaded_session_id, draft_session_id,"reloaded draft should have a fresh ACP session ID");- let restored_text = reloaded_panel.read_with(cx, |panel, cx| {- let thread_id = panel.active_thread_id(cx).unwrap();- panel.editor_text(thread_id, cx)- });+ let restored_text =+ reloaded_panel.read_with(cx, |panel, cx| panel.editor_text(reloaded_thread_id, cx));assert_eq!(restored_text.as_deref(),Some("Hello from draft"),- "draft prompt text should be preserved across serialization"+ "draft prompt text should be restored from the draft-prompt kvp store");- // Send a message on the reloaded panel — this promotes the draft to a real thread.+ // Send a message on the reloaded panel — this promotes the draft to a+ // real thread. `ThreadId` stays the same; `session_id` is populated.let panel = reloaded_panel;- let draft_session_id = reloaded_session_id;- let thread_id = active_thread_id(&panel, cx);+ let promoted_session_id = reloaded_session_id;send_message(&panel, cx);- // Verify promotion: draft_thread is cleared, metadata exists.panel.read_with(cx, |panel, cx| {assert!(!panel.active_thread_is_draft(cx),@@ -5557,7 +5829,7 @@ mod tests {assert_eq!(panel.active_thread_id(cx),Some(thread_id),- "same thread ID should remain active after promotion"+ "same ThreadId should remain active after promotion");});@@ -5567,17 +5839,17 @@ mod tests {.entry(thread_id).expect("promoted thread should have metadata");assert!(- metadata.session_id.is_some(),- "promoted thread metadata should have a real session_id"+ !metadata.is_draft(),+ "promoted thread metadata should no longer be a draft");assert_eq!(- metadata.session_id.as_ref().unwrap(),- &draft_session_id,+ metadata.session_id.as_ref(),+ Some(&promoted_session_id),"metadata session_id should match the thread's ACP session");});- // Serialize the panel, then reload it.+ // Serialize the panel, then reload it again.panel.update(cx, |panel, cx| panel.serialize(cx));cx.run_until_parked();@@ -5587,7 +5859,8 @@ mod tests {.expect("panel load should succeed");cx.run_until_parked();- // The loaded panel should restore the real thread (not the draft).+ // The second load should restore the promoted real thread, keyed by+ // its session_id.loaded_panel.read_with(cx, |panel, cx| {let active_id = panel.active_thread_id(cx);assert_eq!(@@ -5602,6 +5875,323 @@ mod tests {});}+ #[gpui::test]+ async fn test_new_draft_survives_reload_when_real_thread_is_active(cx: &mut TestAppContext) {+ init_test(cx);+ cx.update(|cx| {+ agent::ThreadStore::init_global(cx);+ language_model::LanguageModelRegistry::test(cx);+ });++ let fs = FakeFs::new(cx.executor());+ fs.insert_tree("/project", json!({ "file.txt": "" })).await;+ let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;++ let multi_workspace =+ cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));+ let workspace = multi_workspace+ .read_with(cx, |mw, _cx| mw.workspace().clone())+ .unwrap();+ workspace.update(cx, |workspace, _cx| workspace.set_random_database_id());++ let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);+ let panel = workspace.update_in(cx, |workspace, window, cx| {+ let panel = cx.new(|cx| AgentPanel::new(workspace, None, window, cx));+ workspace.add_panel(panel.clone(), window, cx);+ panel+ });++ // Register a shared stub connection under `Agent::Stub` so every+ // ConversationView the panel creates in this test (including any+ // post-reload rehydrations) reaches Connected synchronously.+ let stub_connection =+ crate::test_support::set_stub_agent_connection(StubAgentConnection::new());+ stub_connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(+ acp::ContentChunk::new("ok".into()),+ )]);++ // 1. Create a real thread by sending a message.+ panel.update_in(cx, |panel, window, cx| {+ panel.selected_agent = Agent::Stub;+ panel.activate_draft(true, "agent_panel", window, cx);+ });+ cx.run_until_parked();+ crate::test_support::send_message(&panel, cx);+ let real_thread_id = crate::test_support::active_thread_id(&panel, cx);+ let real_session_id = crate::test_support::active_session_id(&panel, cx);+ cx.run_until_parked();++ // 2. Open a draft, type into it, then press Cmd-N again to+ // park it into retained_threads as a *retained* draft.+ panel.update_in(cx, |panel, window, cx| {+ panel.activate_draft(true, "agent_panel", window, cx);+ });+ cx.run_until_parked();+ let retained_draft_id = crate::test_support::active_thread_id(&panel, cx);+ crate::test_support::type_draft_prompt(&panel, "retained draft text", cx);++ panel.update_in(cx, |panel, window, cx| {+ panel.new_thread(&NewThread, window, cx);+ });+ cx.run_until_parked();++ // The pre-existing draft is now in retained_threads (parked),+ // and a fresh empty ephemeral new-draft is active.+ panel.read_with(cx, |panel, cx| {+ assert!(+ panel.retained_threads.contains_key(&retained_draft_id),+ "first draft with content should be parked into retained_threads"+ );+ assert_ne!(+ panel.active_thread_id(cx),+ Some(retained_draft_id),+ "active view should be a fresh ephemeral draft, not the retained one"+ );+ });++ // 3. Type into the new ephemeral draft.+ let draft_thread_id = crate::test_support::active_thread_id(&panel, cx);+ crate::test_support::type_draft_prompt(&panel, "in-flight draft text", cx);++ // Sanity-check: both drafts' text has been persisted to the kvp+ // store via the editor observer / PromptUpdated chain.+ let (ephemeral_kvp, retained_kvp) = cx.update(|_, cx| {+ (+ crate::draft_prompt_store::read(draft_thread_id, cx),+ crate::draft_prompt_store::read(retained_draft_id, cx),+ )+ });+ assert!(+ ephemeral_kvp.is_some(),+ "ephemeral draft's prompt should be in the kvp store"+ );+ assert!(+ retained_kvp.is_some(),+ "retained draft's prompt should be in the kvp store"+ );++ assert_ne!(real_thread_id, draft_thread_id);+ assert_ne!(retained_draft_id, draft_thread_id);+ panel.read_with(cx, |panel, cx| {+ assert!(+ panel.active_view_is_new_draft(cx),+ "draft should currently occupy the new-draft slot"+ );+ });++ // 4. Switch the active view back to the real thread. The ephemeral+ // draft remains in `draft_thread` (the ephemeral slot) but is+ // no longer the active view.+ panel.update_in(cx, |panel, window, cx| {+ panel.load_agent_thread(+ Agent::Stub,+ real_thread_id,+ None,+ None,+ false,+ "agent_panel",+ window,+ cx,+ );+ });+ cx.run_until_parked();++ panel.read_with(cx, |panel, cx| {+ assert_eq!(panel.active_thread_id(cx), Some(real_thread_id));+ assert!(!panel.active_view_is_new_draft(cx));+ });++ // 5. Serialize + reload.+ panel.update(cx, |panel, cx| panel.serialize(cx));+ cx.run_until_parked();+ let async_cx = cx.update(|window, cx| window.to_async(cx));+ let loaded_panel = AgentPanel::load(workspace.downgrade(), async_cx)+ .await+ .expect("panel load should succeed");+ cx.run_until_parked();++ // 6. The real thread is the active view on reload AND the draft+ // slot is still occupied by the ephemeral new-draft thread.+ loaded_panel.read_with(cx, |panel, cx| {+ assert_eq!(+ panel.active_thread_id(cx),+ Some(real_thread_id),+ "real thread should be the active view after reload"+ );+ assert!(+ !panel.active_thread_is_draft(cx),+ "real thread is not a draft"+ );+ let restored_draft_id = panel.draft_thread.as_ref().map(|d| d.read(cx).thread_id);+ assert_eq!(+ restored_draft_id,+ Some(draft_thread_id),+ "new-draft slot should be repopulated with the pre-reload draft"+ );+ });++ // 7. All three threads' metadata rows survive the reload.+ cx.update(|_window, cx| {+ let store = ThreadMetadataStore::global(cx).read(cx);+ let ephemeral_row = store+ .entry(draft_thread_id)+ .expect("ephemeral draft metadata row should survive reload");+ assert!(+ ephemeral_row.is_draft(),+ "ephemeral draft row should still be a draft"+ );+ let retained_row = store+ .entry(retained_draft_id)+ .expect("retained draft metadata row should survive reload");+ assert!(+ retained_row.is_draft(),+ "retained draft row should still be a draft"+ );+ let real_row = store+ .entry(real_thread_id)+ .expect("real thread metadata row should survive reload");+ assert_eq!(real_row.session_id.as_ref(), Some(&real_session_id));+ });++ // 8. Opening the ephemeral draft via load_agent_thread activates+ // the restored new-draft ConversationView and exposes its+ // kvp-seeded prompt text in the editor.+ loaded_panel.update_in(cx, |panel, window, cx| {+ panel.load_agent_thread(+ Agent::Stub,+ draft_thread_id,+ None,+ None,+ false,+ "agent_panel",+ window,+ cx,+ );+ });+ cx.run_until_parked();++ let restored_ephemeral_text =+ loaded_panel.read_with(cx, |panel, cx| panel.editor_text(draft_thread_id, cx));+ assert_eq!(+ restored_ephemeral_text.as_deref(),+ Some("in-flight draft text"),+ "ephemeral draft prompt text should be restored from the kvp store"+ );++ // 9. Opening the retained draft via load_agent_thread builds a+ // fresh ConversationView (since retained_threads was not+ // carried across the reload) and seeds its editor from the+ // kvp store.+ loaded_panel.update_in(cx, |panel, window, cx| {+ panel.load_agent_thread(+ Agent::Stub,+ retained_draft_id,+ None,+ None,+ false,+ "agent_panel",+ window,+ cx,+ );+ });+ cx.run_until_parked();++ let restored_retained_text =+ loaded_panel.read_with(cx, |panel, cx| panel.editor_text(retained_draft_id, cx));+ assert_eq!(+ restored_retained_text.as_deref(),+ Some("retained draft text"),+ "retained draft prompt text should be restored from the kvp store"+ );+ }++ #[gpui::test]+ async fn test_reloaded_ephemeral_draft_preserves_original_agent(cx: &mut TestAppContext) {+ init_test(cx);+ cx.update(|cx| {+ agent::ThreadStore::init_global(cx);+ language_model::LanguageModelRegistry::test(cx);+ });++ let fs = FakeFs::new(cx.executor());+ fs.insert_tree("/project", json!({ "file.txt": "" })).await;+ let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;++ let multi_workspace =+ cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));+ let workspace = multi_workspace+ .read_with(cx, |mw, _cx| mw.workspace().clone())+ .unwrap();+ workspace.update(cx, |workspace, _cx| workspace.set_random_database_id());++ let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);+ let panel = workspace.update_in(cx, |workspace, window, cx| {+ let panel = cx.new(|cx| AgentPanel::new(workspace, None, window, cx));+ workspace.add_panel(panel.clone(), window, cx);+ panel+ });++ let _stub_connection =+ crate::test_support::set_stub_agent_connection(StubAgentConnection::new());+ panel.update_in(cx, |panel, window, cx| {+ panel.selected_agent = Agent::Stub;+ panel.activate_draft(true, "agent_panel", window, cx);+ });+ cx.run_until_parked();++ let draft_thread_id = crate::test_support::active_thread_id(&panel, cx);+ crate::test_support::type_draft_prompt(&panel, "pinned to stub", cx);++ // Diverge `selected_agent` from the draft's bound agent before+ // serialize.+ let other_agent = Agent::Custom {+ id: "other-agent".into(),+ };+ panel.update(cx, |panel, _cx| {+ panel.selected_agent = other_agent.clone();+ });+ panel.update(cx, |panel, cx| panel.serialize(cx));+ cx.run_until_parked();++ // Sanity-check: the draft's metadata row has agent_id="stub",+ // not "other-agent".+ cx.update(|_, cx| {+ let store = ThreadMetadataStore::global(cx).read(cx);+ let row = store+ .entry(draft_thread_id)+ .expect("draft metadata row should exist");+ assert_eq!(+ row.agent_id.as_ref(),+ "stub",+ "draft metadata should retain its original agent binding"+ );+ });++ let async_cx = cx.update(|window, cx| window.to_async(cx));+ let reloaded_panel = AgentPanel::load(workspace.downgrade(), async_cx)+ .await+ .expect("panel load should succeed");+ cx.run_until_parked();++ reloaded_panel.read_with(cx, |panel, cx| {+ let draft_view = panel+ .draft_thread+ .as_ref()+ .expect("draft slot should be repopulated");+ assert_eq!(+ draft_view.read(cx).thread_id,+ draft_thread_id,+ "restored draft should have the same ThreadId"+ );+ assert_eq!(+ draft_view.read(cx).agent_key(),+ &Agent::Stub,+ "restored draft should still be bound to its original Agent::Stub, \+ not the panel's current `selected_agent`"+ );+ });+ }+async fn setup_panel(cx: &mut TestAppContext) -> (Entity<AgentPanel>, VisualTestContext) {init_test(cx);cx.update(|cx| {@@ -6004,7 +6594,7 @@ mod tests {panel.update_in(&mut cx, |panel, window, cx| {panel.load_agent_thread(panel.selected_agent(cx),- session_id_a.clone(),+ thread_id_a,None,None,true,@@ -6906,6 +7496,8 @@ mod tests {let initial_draft_id = panel.read_with(cx, |panel, _cx| {panel.draft_thread.as_ref().unwrap().entity_id()});+ let initial_thread_id =+ panel.read_with(cx, |panel, cx| panel.active_thread_id(cx).unwrap());// Type some text into the draft editor.let thread_view = panel.read_with(cx, |panel, cx| panel.active_thread_view(cx).unwrap());@@ -6914,31 +7506,151 @@ mod tests {editor.set_text("Don't lose me!", window, cx);});- // Press cmd-n (activate_draft again with the same agent).+ // Press cmd-n on a typed draft — the draft is parked into+ // `retained_threads` so the user can return to it from the+ // sidebar, and a fresh, *empty* ephemeral draft becomes active.+ // The parked draft retains the prompt; the new one is a blank+ // slate.cx.dispatch_action(NewThread);cx.run_until_parked();- // The draft entity should not have changed.panel.read_with(cx, |panel, _cx| {- assert_eq!(- panel.draft_thread.as_ref().unwrap().entity_id(),- initial_draft_id,- "cmd-n should not replace the draft when already on it"+ assert!(+ panel.retained_threads.contains_key(&initial_thread_id),+ "typed draft should have been parked into retained_threads"+ );+ let active_draft_id = panel.draft_thread.as_ref().unwrap().entity_id();+ assert_ne!(+ active_draft_id, initial_draft_id,+ "cmd-n should produce a fresh ephemeral draft");});- // The editor content should be preserved.- let thread_id = panel.read_with(cx, |panel, cx| panel.active_thread_id(cx).unwrap());- let text = panel.read_with(cx, |panel, cx| panel.editor_text(thread_id, cx));+ // The parked draft still holds the typed prompt.+ let parked_text = panel.read_with(cx, |panel, cx| panel.editor_text(initial_thread_id, cx));assert_eq!(- text.as_deref(),+ parked_text.as_deref(),Some("Don't lose me!"),- "typed content should be preserved when pressing cmd-n on the draft"+ "parked draft should retain the typed prompt"+ );++ // The new active draft starts empty — no carry-over.+ let active_thread_id = panel.read_with(cx, |panel, cx| panel.active_thread_id(cx).unwrap());+ let active_text = panel.read_with(cx, |panel, cx| panel.editor_text(active_thread_id, cx));+ assert_eq!(+ active_text, None,+ "fresh ephemeral draft should start empty, not carry the parked draft's prompt");}+ /// When the user is viewing a *parked* draft (selected from the+ /// sidebar) and presses `+`, the panel should just focus the+ /// ephemeral new-draft slot — not park it and create yet another+ /// empty draft. `+` is "go to my new-thread slot", not "reset state".#[gpui::test]- async fn test_draft_content_carried_over_when_switching_agents(cx: &mut TestAppContext) {+ async fn test_plus_with_parked_draft_active_focuses_ephemeral(cx: &mut TestAppContext) {+ init_test(cx);+ let fs = FakeFs::new(cx.executor());+ cx.update(|cx| {+ agent::ThreadStore::init_global(cx);+ language_model::LanguageModelRegistry::test(cx);+ <dyn fs::Fs>::set_global(fs.clone(), cx);+ });++ let project = Project::test(fs.clone(), [], cx).await;+ let multi_workspace =+ cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));+ let workspace = multi_workspace+ .read_with(cx, |multi_workspace, _cx| {+ multi_workspace.workspace().clone()+ })+ .unwrap();+ workspace.update(cx, |workspace, _cx| workspace.set_random_database_id());+ let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);+ let panel = workspace.update_in(cx, |workspace, window, cx| {+ let panel = cx.new(|cx| AgentPanel::new(workspace, None, window, cx));+ workspace.add_panel(panel.clone(), window, cx);+ panel+ });++ // Open an initial draft, type into it, then press `+` to park it+ // and create a fresh ephemeral. The fresh ephemeral is what we'll+ // expect to refocus later.+ panel.update_in(cx, |panel, window, cx| {+ panel.selected_agent = Agent::Stub;+ panel.activate_draft(true, "agent_panel", window, cx);+ });+ cx.run_until_parked();+ let parked_thread_id = crate::test_support::active_thread_id(&panel, cx);+ crate::test_support::type_draft_prompt(&panel, "parked draft prompt", cx);+ panel.update_in(cx, |panel, window, cx| {+ panel.new_thread(&NewThread, window, cx);+ });+ cx.run_until_parked();++ let ephemeral_thread_id = crate::test_support::active_thread_id(&panel, cx);+ let ephemeral_entity_id = panel.read_with(cx, |panel, _cx| {+ panel.draft_thread.as_ref().unwrap().entity_id()+ });+ assert_ne!(+ ephemeral_thread_id, parked_thread_id,+ "sanity: parking should have produced a fresh ephemeral draft"+ );++ // Activate the parked draft (simulates clicking it in the sidebar).+ panel.update_in(cx, |panel, window, cx| {+ panel.load_agent_thread(+ Agent::Stub,+ parked_thread_id,+ None,+ None,+ true,+ "sidebar",+ window,+ cx,+ );+ });+ cx.run_until_parked();+ assert_eq!(+ crate::test_support::active_thread_id(&panel, cx),+ parked_thread_id,+ "sanity: parked draft should be the active view after load_agent_thread"+ );+ panel.read_with(cx, |panel, _cx| {+ assert_eq!(+ panel.draft_thread.as_ref().unwrap().entity_id(),+ ephemeral_entity_id,+ "sanity: the ephemeral draft slot should still hold the fresh draft"+ );+ });++ // Now press `+`. The ephemeral draft should become the active+ // view; no new draft should be created.+ panel.update_in(cx, |panel, window, cx| {+ panel.new_thread(&NewThread, window, cx);+ });+ cx.run_until_parked();++ panel.read_with(cx, |panel, cx| {+ assert_eq!(+ panel.active_thread_id(cx),+ Some(ephemeral_thread_id),+ "`+` should have switched back to the existing ephemeral draft"+ );+ assert_eq!(+ panel.draft_thread.as_ref().unwrap().entity_id(),+ ephemeral_entity_id,+ "`+` should not have replaced the ephemeral draft"+ );+ assert!(+ panel.retained_threads.contains_key(&parked_thread_id),+ "parked draft should remain in `retained_threads`"+ );+ });+ }++ #[gpui::test]+ async fn test_typed_draft_is_parked_when_switching_agents(cx: &mut TestAppContext) {init_test(cx);let fs = FakeFs::new(cx.executor());cx.update(|cx| {@@ -6983,16 +7695,20 @@ mod tests {let initial_draft_id = panel.read_with(cx, |panel, _cx| {panel.draft_thread.as_ref().unwrap().entity_id()});+ let initial_thread_id =+ panel.read_with(cx, |panel, cx| panel.active_thread_id(cx).unwrap());// Type text into the first draft's editor.let thread_view = panel.read_with(cx, |panel, cx| panel.active_thread_view(cx).unwrap());let message_editor = thread_view.read_with(cx, |view, _cx| view.message_editor.clone());message_editor.update_in(cx, |editor, window, cx| {- editor.set_text("carry me over", window, cx);+ editor.set_text("saved prompt", window, cx);});- // Switch to a different agent. ensure_draft should extract the typed- // content from the old draft and pre-fill the new one.+ // Switch to a different agent. The typed draft should be parked+ // into `retained_threads` (keeping the user's prompt accessible+ // from the sidebar) and a fresh empty draft on the new agent+ // should become active.cx.dispatch_action(NewExternalAgentThread {agent: Agent::Stub.id(),});@@ -7011,15 +7727,26 @@ mod tests {Agent::Stub,"new draft should use the new agent");+ assert!(+ panel.retained_threads.contains_key(&initial_thread_id),+ "typed draft should have been parked into retained_threads"+ );});- // The new draft's editor should contain the text typed in the old draft.- let thread_id = panel.read_with(cx, |panel, cx| panel.active_thread_id(cx).unwrap());- let text = panel.read_with(cx, |panel, cx| panel.editor_text(thread_id, cx));+ // The parked draft retains the prompt.+ let parked_text = panel.read_with(cx, |panel, cx| panel.editor_text(initial_thread_id, cx));+ assert_eq!(+ parked_text.as_deref(),+ Some("saved prompt"),+ "parked draft should retain the user's prompt"+ );++ // The new draft on the new agent starts empty.+ let active_thread_id = panel.read_with(cx, |panel, cx| panel.active_thread_id(cx).unwrap());+ let active_text = panel.read_with(cx, |panel, cx| panel.editor_text(active_thread_id, cx));assert_eq!(- text.as_deref(),- Some("carry me over"),- "content should be carried over to the new agent's draft"+ active_text, None,+ "new draft on the new agent should start empty, not carry the parked draft's prompt");}@@ -7336,7 +8063,8 @@ mod tests {acp::ContentChunk::new("response a".into()),)]);open_thread_with_connection(&panel, connection_a, &mut cx);- let session_id_a = active_session_id(&panel, &cx);+ let _session_id_a = active_session_id(&panel, &cx);+ let thread_id_a = active_thread_id(&panel, &cx);send_message(&panel, &mut cx);cx.run_until_parked();@@ -7369,7 +8097,7 @@ mod tests {panel.update_in(&mut cx, |panel, window, cx| {panel.load_agent_thread(stub_agent.clone(),- session_id_a.clone(),+ thread_id_a,None,None,true,diff --git a/crates/agent_ui/src/agent_ui.rs b/crates/agent_ui/src/agent_ui.rsindex e81ce8b8d76..01bf1019d1e 100644--- a/crates/agent_ui/src/agent_ui.rs+++ b/crates/agent_ui/src/agent_ui.rs@@ -11,6 +11,7 @@ mod context;mod context_server_configuration;pub(crate) mod conversation_view;mod diagnostics;+pub mod draft_prompt_store;mod entry_view_state;mod external_source_prompt;mod favorite_models;diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex 7269f210e40..3a4cd03042f 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -101,6 +101,8 @@ use crate::{const STOPWATCH_THRESHOLD: Duration = Duration::from_secs(30);const TOKEN_THRESHOLD: u64 = 250;+pub(crate) const DRAFT_PROMPT_PERSIST_DEBOUNCE: Duration = Duration::from_millis(250);+mod thread_view;pub use thread_view::*;@@ -505,6 +507,7 @@ pub struct ConversationView {notifications: Vec<WindowHandle<AgentNotification>>,notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,auth_task: Option<Task<()>>,+ draft_prompt_persist_task: Option<Task<()>>,_subscriptions: Vec<Subscription>,}@@ -751,6 +754,7 @@ impl ConversationView {notifications: Vec::new(),notification_subscriptions: HashMap::default(),auth_task: None,+ draft_prompt_persist_task: None,_subscriptions: subscriptions,focus_handle: cx.focus_handle(),}@@ -763,6 +767,9 @@ impl ConversationView {self.server_state = state;cx.emit(AcpServerViewEvent::ActiveThreadChanged);+ if matches!(&self.server_state, ServerState::Connected(_)) {+ cx.emit(RootThreadUpdated);+ }cx.notify();}@@ -1672,12 +1679,43 @@ impl ConversationView {cx.notify();}AcpThreadEvent::PromptUpdated => {+ if !is_subagent && thread.read(cx).is_draft_thread() {+ self.schedule_draft_prompt_persist(cx);+ }cx.notify();}}cx.notify();}+ fn schedule_draft_prompt_persist(&mut self, cx: &mut Context<Self>) {+ let thread_id = self.thread_id;+ self.draft_prompt_persist_task = Some(cx.spawn(async move |this, cx| {+ cx.background_executor()+ .timer(DRAFT_PROMPT_PERSIST_DEBOUNCE)+ .await;+ let persist = this.update(cx, |this, cx| {+ let thread = this.root_thread(cx)?;+ let thread = thread.read(cx);+ if !thread.is_draft_thread() {+ return None;+ }+ let snapshot: Vec<acp::ContentBlock> = thread+ .draft_prompt()+ .map(|p| p.to_vec())+ .unwrap_or_default();+ Some(if snapshot.is_empty() {+ crate::draft_prompt_store::delete(thread_id, cx)+ } else {+ crate::draft_prompt_store::write(thread_id, &snapshot, cx)+ })+ });+ if let Ok(Some(persist)) = persist {+ persist.await.log_err();+ }+ }));+ }+fn authenticate(&mut self,method: acp::AuthMethodId,@@ -2522,7 +2560,7 @@ impl ConversationView {return;};let root_thread = root_thread.read(cx).thread.read(cx);- let root_session_id = root_thread.session_id().clone();+ let root_thread_id = self.thread_id;let root_work_dirs = root_thread.work_dirs().cloned();let root_title = root_thread.title();@@ -2536,7 +2574,7 @@ impl ConversationView {icon,caption.into(),title,- root_session_id,+ root_thread_id,root_work_dirs,root_title,window,@@ -2552,7 +2590,7 @@ impl ConversationView {icon,caption.clone(),title.clone(),- root_session_id.clone(),+ root_thread_id,root_work_dirs.clone(),root_title.clone(),window,@@ -2572,7 +2610,7 @@ impl ConversationView {icon: IconName,caption: SharedString,title: SharedString,- root_session_id: acp::SessionId,+ root_thread_id: ThreadId,root_work_dirs: Option<PathList>,root_title: Option<SharedString>,window: &mut Window,@@ -2615,7 +2653,6 @@ impl ConversationView {let workspace_handle = this.workspace.clone();let agent = this.connection_key.clone();- let root_session_id = root_session_id.clone();let root_work_dirs = root_work_dirs.clone();let root_title = root_title.clone();@@ -2638,7 +2675,7 @@ impl ConversationView {panel.update(cx, |panel, cx| {panel.load_agent_thread(agent.clone(),- root_session_id.clone(),+ root_thread_id,root_work_dirs.clone(),root_title.clone(),true,diff --git a/crates/agent_ui/src/draft_prompt_store.rs b/crates/agent_ui/src/draft_prompt_store.rsnew file mode 100644index 00000000000..4070b549190--- /dev/null+++ b/crates/agent_ui/src/draft_prompt_store.rs@@ -0,0 +1,175 @@+//! Per-thread draft prompt persistence and display label rendering.+//!+//! Drafts are persisted in the thread metadata store with `session_id: None`,+//! but their unsent prompt text is kept separately here so we don't have to+//! plumb draft-prompt storage through the native agent's thread database.+//!+//! The display-label helpers ([`display_label_for_draft`] and friends) live+//! alongside the storage so the sidebar's preview rendering can't drift from+//! the format we persist.++use agent_client_protocol::schema as acp;+use anyhow::Context as _;+use db::kvp::KeyValueStore;+use gpui::{App, AppContext as _, Entity, Task};+use ui::SharedString;+use util::ResultExt as _;+use workspace::Workspace;++use crate::AgentPanel;+use crate::thread_metadata_store::ThreadId;++const NAMESPACE: &str = "agent_draft_prompts";++/// Maximum length (in characters) of a draft label rendered in the sidebar.+const MAX_LABEL_CHARS: usize = 250;++pub fn read(thread_id: ThreadId, cx: &App) -> Option<Vec<acp::ContentBlock>> {+ let kvp = KeyValueStore::global(cx);+ let raw = kvp+ .scoped(NAMESPACE)+ .read(&thread_id_key(thread_id))+ .log_err()+ .flatten()?;+ serde_json::from_str(&raw).log_err()+}++pub fn write(+ thread_id: ThreadId,+ prompt: &[acp::ContentBlock],+ cx: &App,+) -> Task<anyhow::Result<()>> {+ let kvp = KeyValueStore::global(cx);+ let key = thread_id_key(thread_id);+ let payload = match serde_json::to_string(prompt).context("serializing draft prompt") {+ Ok(payload) => payload,+ Err(err) => return Task::ready(Err(err)),+ };+ cx.background_spawn(async move { kvp.scoped(NAMESPACE).write(key, payload).await })+}++pub fn delete(thread_id: ThreadId, cx: &App) -> Task<anyhow::Result<()>> {+ let kvp = KeyValueStore::global(cx);+ let key = thread_id_key(thread_id);+ cx.background_spawn(async move { kvp.scoped(NAMESPACE).delete(key).await })+}++fn thread_id_key(thread_id: ThreadId) -> String {+ thread_id.to_key_string()+}++/// Rewrites `[@Something](scheme://...)` mention links as `@Something` so the+/// sidebar's draft-title preview doesn't show raw markdown link syntax.+pub fn clean_mention_links(input: &str) -> String {+ let mut result = String::with_capacity(input.len());+ let mut remaining = input;++ while let Some(start) = remaining.find("[@") {+ result.push_str(&remaining[..start]);+ let after_bracket = &remaining[start + 1..];+ if let Some(close_bracket) = after_bracket.find("](") {+ let mention = &after_bracket[..close_bracket];+ let after_link_start = &after_bracket[close_bracket + 2..];+ if let Some(close_paren) = after_link_start.find(')') {+ result.push_str(mention);+ remaining = &after_link_start[close_paren + 1..];+ continue;+ }+ }+ result.push_str("[@");+ remaining = &remaining[start + 2..];+ }+ result.push_str(remaining);+ result+}++/// Collapses whitespace and truncates raw editor text for display as a draft+/// label in the sidebar.+pub fn truncate_draft_label(raw: &str) -> Option<SharedString> {+ let first_line = raw.lines().next().unwrap_or("");+ let cleaned = clean_mention_links(first_line);+ let mut text: String = cleaned.split_whitespace().collect::<Vec<_>>().join(" ");+ if text.is_empty() {+ return None;+ }+ if let Some((truncate_at, _)) = text.char_indices().nth(MAX_LABEL_CHARS) {+ text.truncate(truncate_at);+ }+ Some(text.into())+}++/// Renders a draft thread's display label for sidebar rows and similar+/// preview UI.+///+/// Prefers the live message editor's text (when the thread's+/// `ConversationView` is loaded in the workspace's `AgentPanel`), and+/// otherwise falls back to the persisted draft prompt in the kvp store so+/// drafts restored from disk — but not yet opened — still show a meaningful+/// title instead of the generic default.+pub fn display_label_for_draft(+ workspace: Option<&Entity<Workspace>>,+ thread_id: ThreadId,+ cx: &App,+) -> Option<SharedString> {+ let from_editor = workspace+ .and_then(|ws| ws.read(cx).panel::<AgentPanel>(cx))+ .and_then(|panel| panel.read(cx).editor_text(thread_id, cx));+ if let Some(raw) = from_editor+ && let Some(label) = truncate_draft_label(&raw)+ {+ return Some(label);+ }++ let blocks = read(thread_id, cx)?;+ let raw = blocks+ .iter()+ .filter_map(|block| match block {+ acp::ContentBlock::Text(text) => Some(text.text.as_str()),+ acp::ContentBlock::ResourceLink(link) => Some(link.uri.as_str()),+ _ => None,+ })+ .collect::<Vec<_>>()+ .join(" ");+ truncate_draft_label(&raw)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_clean_mention_links() {+ // Simple mention link.+ assert_eq!(+ clean_mention_links("check [@Button.tsx](file:///path/to/Button.tsx)"),+ "check @Button.tsx"+ );++ // Multiple mention links on one line.+ assert_eq!(+ clean_mention_links("look at [@foo.rs](file:///foo.rs) and [@bar.rs](file:///bar.rs)"),+ "look at @foo.rs and @bar.rs"+ );++ // Plain text without mentions is preserved.+ assert_eq!(+ clean_mention_links("plain text with no mentions"),+ "plain text with no mentions"+ );++ // Broken syntax (no closing bracket) is left alone.+ assert_eq!(+ clean_mention_links("broken [@mention without closing"),+ "broken [@mention without closing"+ );++ // Non-`@` markdown links are not touched.+ assert_eq!(+ clean_mention_links("see [docs](https://example.com)"),+ "see [docs](https://example.com)"+ );++ // Empty input.+ assert_eq!(clean_mention_links(""), "");+ }+}diff --git a/crates/agent_ui/src/test_support.rs b/crates/agent_ui/src/test_support.rsindex 1f409ebfc74..7f4cb59a634 100644--- a/crates/agent_ui/src/test_support.rs+++ b/crates/agent_ui/src/test_support.rs@@ -123,6 +123,19 @@ pub fn open_thread_with_connection(cx.run_until_parked();}+/// Opens a draft thread against a stub server so the panel's `draft_thread`+/// pointer is populated for tests that care about draft UX.+pub fn open_draft_with_connection(+ panel: &Entity<AgentPanel>,+ connection: StubAgentConnection,+ cx: &mut VisualTestContext,+) {+ panel.update_in(cx, |panel, window, cx| {+ panel.open_draft_with_server(Rc::new(StubAgentServer::new(connection)), window, cx);+ });+ cx.run_until_parked();+}+pub fn open_thread_with_custom_connection<C>(panel: &Entity<AgentPanel>,connection: C,@@ -150,6 +163,20 @@ pub fn send_message(panel: &Entity<AgentPanel>, cx: &mut VisualTestContext) {cx.run_until_parked();}+pub fn type_draft_prompt(panel: &Entity<AgentPanel>, text: &str, cx: &mut VisualTestContext) {+ let thread_view = panel.read_with(cx, |panel, cx| panel.active_thread_view(cx).unwrap());+ let message_editor = thread_view.read_with(cx, |view, _cx| view.message_editor.clone());+ message_editor.update_in(cx, |editor, window, cx| {+ editor.set_text(text, window, cx);+ });+ cx.run_until_parked();+ // Drain the debounced draft-prompt persist task so the kvp write has+ // landed by the time we return.+ cx.executor()+ .advance_clock(crate::conversation_view::DRAFT_PROMPT_PERSIST_DEBOUNCE * 2);+ cx.run_until_parked();+}+pub fn active_session_id(panel: &Entity<AgentPanel>, cx: &VisualTestContext) -> acp::SessionId {panel.read_with(cx, |panel, cx| {let thread = panel.active_agent_thread(cx).unwrap();diff --git a/crates/agent_ui/src/thread_metadata_store.rs b/crates/agent_ui/src/thread_metadata_store.rsindex 00d132f5a36..127cd9ee6ae 100644--- a/crates/agent_ui/src/thread_metadata_store.rs+++ b/crates/agent_ui/src/thread_metadata_store.rs@@ -25,7 +25,7 @@ pub use project::WorktreePaths;use project::{AgentId, linked_worktree_short_name};use remote::{RemoteConnectionOptions, same_remote_connection_identity};use ui::{App, Context, SharedString, ThreadItemWorktreeInfo, WorktreeKind};-use util::{ResultExt as _, debug_panic};+use util::ResultExt as _;use workspace::{PathList, SerializedWorkspaceLocation, WorkspaceDb};use crate::DEFAULT_THREAD_TITLE;@@ -37,6 +37,11 @@ impl ThreadId {pub fn new() -> Self {Self(uuid::Uuid::new_v4())}++ /// Stable, hyphenated string form suitable for use as a key.+ pub fn to_key_string(&self) -> String {+ self.0.hyphenated().to_string()+ }}impl Bind for ThreadId {@@ -316,6 +321,12 @@ pub struct ThreadMetadata {}impl ThreadMetadata {+ /// A thread is a draft until its first message is sent, at which point+ /// it gets an ACP `session_id`.+ pub fn is_draft(&self) -> bool {+ self.session_id.is_none()+ }+pub fn display_title(&self) -> SharedString {self.title.clone()@@ -664,11 +675,6 @@ impl ThreadMetadataStore {}fn save_internal(&mut self, metadata: ThreadMetadata) {- if metadata.session_id.is_none() {- debug_panic!("cannot store thread metadata without a session_id");- return;- };-if let Some(thread) = self.threads.get(&metadata.thread_id) {if thread.folder_paths() != metadata.folder_paths() {if let Some(thread_ids) = self.threads_by_paths.get_mut(thread.folder_paths()) {@@ -694,13 +700,12 @@ impl ThreadMetadataStore {}fn cache_thread_metadata(&mut self, metadata: ThreadMetadata) {- let Some(session_id) = metadata.session_id.as_ref() else {- debug_panic!("cannot store thread metadata without a session_id");- return;- };-- self.threads_by_session- .insert(session_id.clone(), metadata.thread_id);+ // Drafts may not have a session_id yet; only index by session+ // when one is present.+ if let Some(session_id) = metadata.session_id.as_ref() {+ self.threads_by_session+ .insert(session_id.clone(), metadata.thread_id);+ }self.threads.insert(metadata.thread_id, metadata.clone());@@ -1080,6 +1085,7 @@ impl ThreadMetadataStore {self.pending_thread_ops_tx.try_send(DbOperation::Delete(thread_id)).log_err();+ crate::draft_prompt_store::delete(thread_id, cx).detach_and_log_err(cx);cx.notify();}@@ -1176,12 +1182,19 @@ impl ThreadMetadataStore {};let thread_ref = thread.read(cx);- if thread_ref.is_draft_thread() || thread_ref.project().read(cx).is_via_collab() {+ // Collab-hosted threads don't own their metadata locally.+ if thread_ref.project().read(cx).is_via_collab() {return;}-+ let is_draft = thread_ref.is_draft_thread();let existing_thread = self.entry(thread_id);- let session_id = Some(thread_ref.session_id().clone());++ // Draft session IDs may change on reload, so let's not save them until they're valid+ let session_id = if is_draft {+ None+ } else {+ Some(thread_ref.session_id().clone())+ };let title = thread_ref.title();let updated_at = Utc::now();@@ -1223,6 +1236,14 @@ impl ThreadMetadataStore {.map(|t| t.archived).unwrap_or(worktree_paths.is_empty());+ let was_draft = existing_thread.map_or(true, |t| t.is_draft());+ if was_draft && !is_draft {+ // Draft has been promoted: drop its persisted prompt since the+ // promoted thread now owns its prompt state via the native+ // agent's thread database.+ crate::draft_prompt_store::delete(thread_id, cx).detach_and_log_err(cx);+ }+let metadata = ThreadMetadata {thread_id,session_id,@@ -1353,7 +1374,6 @@ impl ThreadMetadataDb {pub fn list_ids(&self) -> anyhow::Result<Vec<ThreadId>> {self.select::<ThreadId>("SELECT thread_id FROM sidebar_threads \- WHERE session_id IS NOT NULL \ORDER BY updated_at DESC",)?()}@@ -1362,7 +1382,6 @@ impl ThreadMetadataDb {created_at, interacted_at, folder_paths, folder_paths_order, archived, main_worktree_paths, \main_worktree_paths_order, remote_connection \FROM sidebar_threads \- WHERE session_id IS NOT NULL \ORDER BY updated_at DESC";/// List all sidebar thread metadata, ordered by updated_at descending.@@ -1373,12 +1392,11 @@ impl ThreadMetadataDb {}/// Upsert metadata for a thread.+ ///+ /// Drafts are persisted with `session_id = None`. They get a real+ /// session_id on promotion (when the first message is sent) and+ /// then flow through this same upsert path.pub async fn save(&self, row: ThreadMetadata) -> anyhow::Result<()> {- anyhow::ensure!(- row.session_id.is_some(),- "refusing to persist thread metadata without a session_id"- );-let session_id = row.session_id.as_ref().map(|s| s.0.clone());let agent_id = if row.agent_id.as_ref() == ZED_AGENT_ID.as_ref() {None@@ -2416,7 +2434,7 @@ mod tests {}#[gpui::test]- async fn test_empty_thread_events_do_not_create_metadata(cx: &mut TestAppContext) {+ async fn test_draft_thread_metadata_promotes_on_first_message(cx: &mut TestAppContext) {init_test(cx);let fs = FakeFs::new(cx.executor());@@ -2430,14 +2448,19 @@ mod tests {let session_id = thread.read_with(&vcx, |t, _| t.session_id().clone());let thread_id = crate::test_support::active_thread_id(&panel, &vcx);- // Draft threads no longer create metadata entries.+ // Empty (draft) threads are persisted with `session_id: None`.cx.read(|cx| {let store = ThreadMetadataStore::global(cx).read(cx);- assert_eq!(store.entry_ids().count(), 0);+ assert_eq!(store.entry_ids().count(), 1);+ let entry = store.entry(thread_id).expect("draft metadata row");+ assert!(+ entry.is_draft(),+ "expected draft row to have session_id=None, got {:?}",+ entry.session_id+ );});- // Setting a title on an empty thread should be ignored by the- // event handler (entries are empty), so no metadata is created.+ // Updating the title while still a draft keeps the row as a draft.thread.update_in(&mut vcx, |thread, _window, cx| {thread.set_title("Draft Thread".into(), cx).detach();});@@ -2445,15 +2468,15 @@ mod tests {cx.read(|cx| {let store = ThreadMetadataStore::global(cx).read(cx);+ let entry = store.entry(thread_id).expect("draft metadata row");+ assert!(entry.is_draft(), "still a draft after title update");assert_eq!(- store.entry_ids().count(),- 0,- "expected title updates on empty thread to not create metadata"+ entry.title.as_ref().map(|t| t.as_ref()),+ Some("Draft Thread"));});- // Pushing content makes entries non-empty, so the event handler- // should now update metadata with the real session_id.+ // Pushing content promotes the draft: session_id is now populated.thread.update_in(&mut vcx, |thread, _window, cx| {thread.push_user_content_block(None, "Hello".into(), cx);});diff --git a/crates/agent_ui/src/ui/mention_crease.rs b/crates/agent_ui/src/ui/mention_crease.rsindex 236e57ddffb..902196657e3 100644--- a/crates/agent_ui/src/ui/mention_crease.rs+++ b/crates/agent_ui/src/ui/mention_crease.rs@@ -14,8 +14,6 @@ use theme_settings::ThemeSettings;use ui::{ButtonLike, TintColor, Tooltip, prelude::*};use workspace::{OpenOptions, Workspace};-use crate::Agent;-#[derive(IntoElement)]pub struct MentionCrease {id: ElementId,@@ -271,24 +269,30 @@ fn open_thread(window: &mut Window,cx: &mut Context<Workspace>,) {- use crate::AgentPanel;+ use crate::{Agent, AgentPanel, thread_metadata_store::ThreadMetadataStore};let Some(panel) = workspace.panel::<AgentPanel>(cx) else {return;};- // Right now we only support loading threads in the native agent+ // Right now we only support loading threads in the native agent.panel.update(cx, |panel, cx| {- panel.load_agent_thread(- Agent::NativeAgent,- id,- None,- Some(name.into()),- true,- "agent_panel",- window,- cx,- )+ let thread_id = ThreadMetadataStore::try_global(cx)+ .and_then(|store| store.read(cx).entry_by_session(&id).map(|m| m.thread_id));+ if let Some(thread_id) = thread_id {+ panel.load_agent_thread(+ Agent::NativeAgent,+ thread_id,+ None,+ Some(name.into()),+ true,+ "agent_panel",+ window,+ cx,+ );+ } else {+ panel.open_thread(id, None, Some(name.into()), window, cx);+ }});}diff --git a/crates/sidebar/src/sidebar.rs b/crates/sidebar/src/sidebar.rsindex 9bbe0db90f2..5f39556893e 100644--- a/crates/sidebar/src/sidebar.rs+++ b/crates/sidebar/src/sidebar.rs@@ -227,6 +227,7 @@ struct ThreadEntry {is_live: bool,is_background: bool,is_title_generating: bool,+ is_draft: bool,highlight_positions: Vec<usize>,worktrees: Vec<ThreadItemWorktreeInfo>,diff_stats: DiffStats,@@ -600,6 +601,7 @@ pub struct Sidebar {project_header_menu_handles: HashMap<usize, PopoverMenuHandle<ContextMenu>>,project_header_menu_ix: Option<usize>,_subscriptions: Vec<gpui::Subscription>,+ _draft_editor_observations: Vec<gpui::Subscription>,/// For the thread import banners, if there is just one we show "Import/// Threads" but if we are showing both the external agents and other/// channels import banners then we change the text to disambiguate the@@ -707,6 +709,7 @@ impl Sidebar {project_header_menu_handles: HashMap::new(),project_header_menu_ix: None,_subscriptions: Vec::new(),+ _draft_editor_observations: Vec::new(),import_banners_use_verbose_labels: None,}}@@ -1244,6 +1247,15 @@ impl Sidebar {if should_load_threads {let thread_store = ThreadMetadataStore::global(cx);+ let ephemeral_drafts: HashSet<ThreadId> = group_workspaces+ .iter()+ .filter_map(|ws| {+ ws.read(cx)+ .panel::<AgentPanel>(cx)+ .and_then(|panel| panel.read(cx).ephemeral_draft_thread_id(cx))+ })+ .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.@@ -1272,6 +1284,7 @@ impl Sidebar {let (icon, icon_from_external_svg) = resolve_agent_icon(&row.agent_id);let worktrees =worktree_info_from_thread_paths(&row.worktree_paths, &branch_by_path);+ let is_draft = row.is_draft();ThreadEntry {metadata: row,icon,@@ -1281,6 +1294,7 @@ impl Sidebar {is_live: false,is_background: false,is_title_generating: false,+ is_draft,highlight_positions: Vec::new(),worktrees,diff_stats: DiffStats::default(),@@ -1382,6 +1396,26 @@ impl Sidebar {}}+ if !ephemeral_drafts.is_empty() {+ threads.retain(|thread| !ephemeral_drafts.contains(&thread.metadata.thread_id));+ }+ for thread in &mut threads {+ if !thread.is_draft {+ continue;+ }+ let workspace = match &thread.workspace {+ ThreadEntryWorkspace::Open(workspace) => Some(workspace),+ ThreadEntryWorkspace::Closed { .. } => None,+ };+ if let Some(text) = agent_ui::draft_prompt_store::display_label_for_draft(+ workspace,+ thread.metadata.thread_id,+ cx,+ ) {+ thread.metadata.title = Some(text);+ }+ }+// Build a lookup from live_infos and compute running/waiting// counts in a single pass.let mut live_info_by_session: HashMap<&acp::SessionId, &ActiveThreadInfo> =@@ -1589,6 +1623,7 @@ impl Sidebar {let scroll_position = self.list_state.logical_scroll_top();self.rebuild_contents(cx);+ self.refresh_draft_editor_observations(cx);self.list_state.reset(self.contents.entries.len());self.list_state.scroll_to(scroll_position);@@ -1602,6 +1637,41 @@ impl Sidebar {cx.notify();}+ /// Re-establishes subscriptions to each visible draft's message editor+ /// so we rebuild entries (and their displayed titles) as the user types.+ fn refresh_draft_editor_observations(&mut self, cx: &mut Context<Self>) {+ let Some(multi_workspace) = self.multi_workspace.upgrade() else {+ self._draft_editor_observations.clear();+ return;+ };++ let draft_conversation_views: Vec<Entity<agent_ui::ConversationView>> = multi_workspace+ .read(cx)+ .workspaces()+ .filter_map(|ws| ws.read(cx).panel::<AgentPanel>(cx))+ .flat_map(|panel| panel.read(cx).conversation_views())+ .collect();++ let mut subscriptions = Vec::with_capacity(draft_conversation_views.len());+ for cv in draft_conversation_views {+ if let Some(thread_view) = cv.read(cx).active_thread() {+ let editor = thread_view.read(cx).message_editor.clone();+ subscriptions.push(cx.observe(&editor, |this, _editor, cx| {+ this.update_entries(cx);+ }));+ } else {+ // Editor hasn't been constructed yet (still Loading). Observe+ // the ConversationView and re-run this wiring once it flips+ // to Connected.+ subscriptions.push(cx.observe(&cv, |this, _cv, cx| {+ this.refresh_draft_editor_observations(cx);+ this.update_entries(cx);+ }));+ }+ }+ self._draft_editor_observations = subscriptions;+ }+fn select_first_entry(&mut self) {self.selection = self.contents@@ -1656,7 +1726,7 @@ impl Sidebar {let panel = panel.read(cx);// An active terminal is its own surface, not a draft.panel.active_terminal_id().is_none()- && (panel.active_thread_is_draft(cx)+ && (panel.active_view_is_new_draft(cx)|| panel.active_conversation_view().is_none())});self.project_header_menu_handles.entry(ix).or_default();@@ -2305,7 +2375,7 @@ impl Sidebar {let panel = panel.read(cx);// An active terminal is its own surface, not a draft.panel.active_terminal_id().is_none()- && (panel.active_thread_is_draft(cx)+ && (panel.active_view_is_new_draft(cx)|| panel.active_conversation_view().is_none())});let header_element = self.render_project_header(@@ -2622,13 +2692,10 @@ impl Sidebar {focus: bool,window: &mut Window,cx: &mut App| {- let Some(session_id) = metadata.session_id.clone() else {- return;- };agent_panel.update(cx, |panel, cx| {panel.load_agent_thread(Agent::from(metadata.agent_id.clone()),- session_id,+ metadata.thread_id,Some(metadata.folder_paths().clone()),metadata.title.clone(),focus,@@ -2703,10 +2770,7 @@ impl Sidebar {workspace: workspace.clone(),});self.record_thread_access(&metadata.thread_id);-- if metadata.session_id.is_some() {- self.pending_thread_activation = Some(metadata.thread_id);- }+ self.pending_thread_activation = Some(metadata.thread_id);multi_workspace.update(cx, |multi_workspace, cx| {multi_workspace.activate(workspace.clone(), None, window, cx);@@ -2715,22 +2779,7 @@ impl Sidebar {}});- // Drafts (and other retained threads without a session_id) are- // already in memory — activate them directly instead of loading.- let thread_id = metadata.thread_id;- if metadata.session_id.is_none() {- workspace.update(cx, |ws, cx| {- if let Some(panel) = ws.panel::<AgentPanel>(cx) {- panel.update(cx, |panel, cx| {- panel.activate_retained_thread(thread_id, true, window, cx);- });- }- ws.focus_panel::<AgentPanel>(window, cx);- });- self.pending_thread_activation = None;- } else {- Self::load_agent_thread_in_workspace(workspace, metadata, true, window, cx);- }+ Self::load_agent_thread_in_workspace(workspace, metadata, true, window, cx);self.update_entries(cx);}@@ -3906,7 +3955,13 @@ impl Sidebar {}AgentThreadStatus::Completed | AgentThreadStatus::Error => {}}- if let Some(session_id) = thread.metadata.session_id.clone() {+ if thread.is_draft {+ if let ThreadEntryWorkspace::Open(workspace) = &thread.workspace {+ let workspace = workspace.clone();+ let draft_id = thread.metadata.thread_id;+ self.remove_draft(draft_id, &workspace, window, cx);+ }+ } else if let Some(session_id) = thread.metadata.session_id.clone() {self.archive_thread(&session_id, window, cx);}}@@ -4353,6 +4408,7 @@ impl Sidebar {let is_hovered = self.hovered_thread_index == Some(ix);let is_selected = is_active;+ let is_draft = thread.is_draft;let is_running = matches!(thread.status,AgentThreadStatus::Running | AgentThreadStatus::WaitingForConfirmation@@ -4378,12 +4434,23 @@ impl Sidebar {cx.flag_value::<AgentThreadWorktreeLabelFlag>(),);+ let icon = if is_draft {+ IconName::Plus+ } else {+ thread.icon+ };+ let icon_svg = if is_draft {+ None+ } else {+ thread.icon_from_external_svg.clone()+ };+ThreadItem::new(id, title).base_bg(sidebar_bg)- .icon(thread.icon)+ .icon(icon).status(thread.status).is_remote(is_remote)- .when_some(thread.icon_from_external_svg.clone(), |this, svg| {+ .when_some(icon_svg, |this, svg| {this.custom_icon_from_external_svg(svg)}).worktrees(worktrees)@@ -4422,7 +4489,7 @@ impl Sidebar {}),)})- .when(is_hovered && !is_running, |this| {+ .when(is_hovered && !is_running && !is_draft, |this| {this.action_slot(IconButton::new("archive-thread", IconName::Archive).icon_size(IconSize::Small)@@ -4448,6 +4515,22 @@ impl Sidebar {}),)})+ .when(is_hovered && !is_running && is_draft, |this| {+ this.action_slot(+ IconButton::new("close-draft", IconName::Close)+ .icon_size(IconSize::Small)+ .icon_color(Color::Muted)+ .tooltip(Tooltip::text("Remove Draft"))+ .on_click({+ let thread_workspace = thread_workspace.clone();+ cx.listener(move |this, _, window, cx| {+ if let ThreadEntryWorkspace::Open(workspace) = &thread_workspace {+ this.remove_draft(thread_id_for_actions, workspace, window, cx);+ }+ })+ }),+ )+ }).on_click({cx.listener(move |this, _, window, cx| {this.selection = None;@@ -4629,6 +4712,35 @@ impl Sidebar {}}+ /// Deletes a parked draft thread (its metadata row, any kvp-stored+ /// draft prompt) and promotes a sibling in the same group, if any, to+ /// the active entry.+ fn remove_draft(+ &mut self,+ draft_id: ThreadId,+ workspace: &Entity<Workspace>,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ workspace.update(cx, |ws, cx| {+ if let Some(panel) = ws.panel::<AgentPanel>(cx) {+ panel.update(cx, |panel, cx| {+ panel.remove_thread(draft_id, window, cx);+ });+ }+ });++ let was_active = self+ .active_entry+ .as_ref()+ .is_some_and(|e| e.is_active_thread(&draft_id));+ if was_active {+ self.active_entry = None;+ }++ self.update_entries(cx);+ }+fn create_new_entry(&mut self,workspace: &Entity<Workspace>,diff --git a/crates/sidebar/src/sidebar_tests.rs b/crates/sidebar/src/sidebar_tests.rsindex a7fb81c9033..9b906f0c12d 100644--- a/crates/sidebar/src/sidebar_tests.rs+++ b/crates/sidebar/src/sidebar_tests.rs@@ -261,6 +261,15 @@ async fn save_named_thread_metadata(cx.run_until_parked();}+/// Seeds a pre-built [`ThreadMetadata`] into the global store so tests can+/// exercise flows that resolve a thread by id.+fn seed_thread_metadata(metadata: ThreadMetadata, cx: &mut TestAppContext) {+ cx.update(|cx| {+ ThreadMetadataStore::global(cx).update(cx, |store, cx| store.save(metadata, cx));+ });+ cx.run_until_parked();+}+/// Spins up a fresh remote project backed by a headless server sharing/// `server_fs`, opens the given worktree path on it, and returns the/// project together with the headless entity (which the caller must keep@@ -895,6 +904,7 @@ async fn test_visible_entries_as_strings(cx: &mut TestAppContext) {is_live: false,is_background: false,is_title_generating: false,+ is_draft: false,highlight_positions: Vec::new(),worktrees: Vec::new(),diff_stats: DiffStats::default(),@@ -920,6 +930,7 @@ async fn test_visible_entries_as_strings(cx: &mut TestAppContext) {is_live: true,is_background: false,is_title_generating: false,+ is_draft: false,highlight_positions: Vec::new(),worktrees: Vec::new(),diff_stats: DiffStats::default(),@@ -945,6 +956,7 @@ async fn test_visible_entries_as_strings(cx: &mut TestAppContext) {is_live: true,is_background: false,is_title_generating: false,+ is_draft: false,highlight_positions: Vec::new(),worktrees: Vec::new(),diff_stats: DiffStats::default(),@@ -971,6 +983,7 @@ async fn test_visible_entries_as_strings(cx: &mut TestAppContext) {is_live: false,is_background: false,is_title_generating: false,+ is_draft: false,highlight_positions: Vec::new(),worktrees: Vec::new(),diff_stats: DiffStats::default(),@@ -997,6 +1010,7 @@ async fn test_visible_entries_as_strings(cx: &mut TestAppContext) {is_live: true,is_background: true,is_title_generating: false,+ is_draft: false,highlight_positions: Vec::new(),worktrees: Vec::new(),diff_stats: DiffStats::default(),@@ -3144,6 +3158,314 @@ async fn test_new_thread_button_works_after_adding_folder(cx: &mut TestAppContex);});}++#[gpui::test]+async fn test_draft_title_updates_from_editor_text(cx: &mut TestAppContext) {+ // When the user types into a draft, the parked draft entry's title in+ // the sidebar should reflect the editor's text — both while the+ // draft's `ConversationView` is still loaded (source: live message+ // editor) and after it has been evicted (source: kvp draft prompt+ // store, the same path used when drafts are restored from disk).+ 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);+ cx.run_until_parked();++ // Open an ephemeral draft via a stub connection so the conversation+ // view reaches Connected synchronously and the panel's draft_thread+ // pointer is populated.+ let connection = StubAgentConnection::new();+ agent_ui::test_support::open_draft_with_connection(&panel, connection, cx);+ cx.run_until_parked();+ let draft_id = panel.read_with(cx, |panel, cx| panel.active_thread_id(cx).unwrap());++ // Type into the (active) draft's message editor. The helper drains the+ // kvp-write debounce, so by the time it returns the prompt is on disk+ // — important for Phase 2 below, which exercises the kvp fallback.+ agent_ui::test_support::type_draft_prompt(&panel, "Fix the login bug", cx);++ // Park the draft by pressing Cmd-N while it has content.+ panel.update_in(cx, |panel, window, cx| {+ panel.new_thread(&NewThread, window, cx);+ });+ cx.run_until_parked();++ let draft_title = |sidebar: &Entity<Sidebar>, cx: &mut gpui::VisualTestContext| {+ sidebar.read_with(cx, |sidebar, _cx| {+ sidebar+ .contents+ .entries+ .iter()+ .find_map(|entry| match entry {+ ListEntry::Thread(thread)+ if thread.is_draft && thread.metadata.thread_id == draft_id =>+ {+ Some(thread.metadata.display_title())+ }+ _ => None,+ })+ .expect("parked draft entry should be present")+ })+ };++ // Phase 1: ConversationView is still loaded in `retained_threads`;+ // the title comes from its live message editor.+ assert_eq!(+ draft_title(&sidebar, cx).as_ref(),+ "Fix the login bug",+ "parked draft title should match its editor text while loaded"+ );+ panel.read_with(cx, |panel, _cx| {+ assert!(+ panel.retained_threads().contains_key(&draft_id),+ "draft should be in retained_threads while loaded"+ );+ });++ // Phase 2: drop the draft's ConversationView from memory, mirroring+ // the state the sidebar sees immediately after a process restart+ // — the metadata row and the kvp draft prompt are on disk, but no+ // ConversationView has been rehydrated yet.+ let unloaded = panel.update(cx, |panel, _cx| panel.test_unload_retained_thread(draft_id));+ assert!(unloaded, "draft should have been present before unload");+ sidebar.update(cx, |sidebar, cx| sidebar.update_entries(cx));+ cx.run_until_parked();++ assert_eq!(+ draft_title(&sidebar, cx).as_ref(),+ "Fix the login bug",+ "parked draft title should still come from the kvp draft prompt store \+ even after its ConversationView is unloaded"+ );+}++#[gpui::test]+async fn test_plus_button_reuses_empty_draft(cx: &mut TestAppContext) {+ // Clicking `+` when an empty draft is already active should focus it+ // instead of creating and parking a new one.+ 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);+ cx.run_until_parked();++ // Open an initial draft against a stub so it connects synchronously.+ let connection = StubAgentConnection::new();+ agent_ui::test_support::open_draft_with_connection(&panel, connection, cx);+ cx.run_until_parked();++ let first_id = panel.read_with(cx, |panel, cx| {+ panel+ .active_thread_id(cx)+ .expect("draft should be active after open_draft_with_connection")+ });++ // Cmd-N with an empty draft should reuse it.+ panel.update_in(cx, |panel, window, cx| {+ panel.new_thread(&NewThread, window, cx);+ });+ cx.run_until_parked();++ let second_id = panel.read_with(cx, |panel, cx| {+ panel+ .active_thread_id(cx)+ .expect("draft should still be active after Cmd-N")+ });+ assert_eq!(+ first_id, second_id,+ "an empty draft should be reused, not replaced"+ );+ let draft_rows = sidebar.read_with(cx, |sidebar, _| {+ sidebar+ .contents+ .entries+ .iter()+ .filter(|entry| matches!(entry, ListEntry::Thread(t) if t.is_draft))+ .count()+ });+ assert_eq!(+ draft_rows, 0,+ "active ephemeral draft should not appear as a sidebar row"+ );+}++#[gpui::test]+async fn test_plus_button_parks_nonempty_draft(cx: &mut TestAppContext) {+ // Clicking `+` while the current draft has content should park the+ // current draft (surface it as a sidebar row) and create a new empty+ // draft as active.+ 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);+ cx.run_until_parked();++ // Open a draft via a stub so the ConversationView reaches Connected and+ // we can type into its editor.+ let connection = StubAgentConnection::new();+ agent_ui::test_support::open_draft_with_connection(&panel, connection, cx);+ cx.run_until_parked();+ let first_id = panel.read_with(cx, |panel, cx| panel.active_thread_id(cx).unwrap());+ let thread_view = panel.read_with(cx, |panel, cx| panel.active_thread_view(cx).unwrap());+ let editor = thread_view.read_with(cx, |view, _| view.message_editor.clone());+ editor.update_in(cx, |editor, window, cx| {+ editor.set_text("something the user typed", window, cx);+ });+ cx.run_until_parked();++ // Cmd-N parks the first draft and creates a new empty draft.+ panel.update_in(cx, |panel, window, cx| {+ panel.new_thread(&NewThread, window, cx);+ });+ cx.run_until_parked();++ let second_id = panel.read_with(cx, |panel, cx| panel.active_thread_id(cx).unwrap());+ assert_ne!(+ first_id, second_id,+ "non-empty draft should be parked and a fresh draft activated"+ );++ // The parked (now non-active) first draft shows as a sidebar row with+ // its editor-derived title.+ let parked_titles: Vec<SharedString> = sidebar.read_with(cx, |sidebar, _| {+ sidebar+ .contents+ .entries+ .iter()+ .filter_map(|entry| match entry {+ ListEntry::Thread(t) if t.is_draft => Some(t.metadata.display_title()),+ _ => None,+ })+ .collect()+ });+ assert_eq!(+ parked_titles.len(),+ 1,+ "expected the parked draft to be visible as a sidebar row, got {parked_titles:?}"+ );+ assert_eq!(parked_titles[0].as_ref(), "something the user typed");+}++#[gpui::test]+async fn test_remove_draft_deletes_metadata_row(cx: &mut TestAppContext) {+ // The close-draft button deletes the metadata row and the kvp draft prompt,+ // and the draft disappears from the sidebar.+ 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);+ cx.run_until_parked();++ // Open a draft with content, park it by pressing Cmd-N.+ let connection = StubAgentConnection::new();+ agent_ui::test_support::open_draft_with_connection(&panel, connection, cx);+ cx.run_until_parked();+ let draft_id = panel.read_with(cx, |panel, cx| panel.active_thread_id(cx).unwrap());+ agent_ui::test_support::type_draft_prompt(&panel, "will be discarded", cx);+ panel.update_in(cx, |panel, window, cx| {+ panel.new_thread(&NewThread, window, cx);+ });+ cx.run_until_parked();++ // The parked draft is visible.+ let draft_index = sidebar.read_with(cx, |sidebar, _| {+ sidebar+ .contents+ .entries+ .iter()+ .position(|e| matches!(e, ListEntry::Thread(t) if t.metadata.thread_id == draft_id))+ .expect("parked draft should be visible before removal")+ });++ // Select the parked draft and dispatch the action a real user would+ // (Shift-Backspace, bound to `ArchiveSelectedThread`). The handler+ // routes to `remove_draft` for parked drafts.+ sidebar.update_in(cx, |sidebar, window, cx| {+ sidebar.selection = Some(draft_index);+ sidebar.archive_selected_thread(&agent_ui::ArchiveSelectedThread, window, cx);+ });+ cx.run_until_parked();++ // Metadata row and persisted draft prompt should both be gone.+ cx.update(|_window, cx| {+ let store = ThreadMetadataStore::global(cx).read(cx);+ assert!(+ store.entry(draft_id).is_none(),+ "removed draft metadata should be deleted"+ );+ assert!(+ agent_ui::draft_prompt_store::read(draft_id, cx).is_none(),+ "removed draft's kvp prompt should also be deleted"+ );+ });+ // And the row should be gone from the sidebar.+ let still_visible = sidebar.read_with(cx, |sidebar, _| {+ sidebar+ .contents+ .entries+ .iter()+ .any(|e| matches!(e, ListEntry::Thread(t) if t.metadata.thread_id == draft_id))+ });+ assert!(+ !still_visible,+ "removed draft should no longer appear in the sidebar"+ );+}++#[gpui::test]+async fn test_sending_message_from_draft_promotes_in_place(cx: &mut TestAppContext) {+ // Sending a message from a draft should keep the same ThreadId, set the+ // session_id on its metadata row, and clear the `draft_thread` pointer.+ 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);+ cx.run_until_parked();++ let connection = StubAgentConnection::new();+ connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(+ acp::ContentChunk::new("ok".into()),+ )]);+ open_thread_with_connection(&panel, connection, cx);+ let draft_id = panel.read_with(cx, |panel, cx| panel.active_thread_id(cx).unwrap());++ // Before sending: draft metadata row exists with session_id = None.+ cx.update(|_window, cx| {+ let store = ThreadMetadataStore::global(cx).read(cx);+ let entry = store.entry(draft_id).expect("draft metadata row");+ assert!(entry.is_draft(), "expected draft row before sending");+ });++ send_message(&panel, cx);+ cx.run_until_parked();++ // After sending: draft_thread is cleared, metadata row has a session_id.+ panel.read_with(cx, |panel, cx| {+ assert!(+ !panel.active_thread_is_draft(cx),+ "should no longer be a draft after send"+ );+ assert!(+ panel.ephemeral_draft_thread_id(cx).is_none(),+ "ephemeral draft pointer should be cleared after promotion"+ );+ assert_eq!(+ panel.active_thread_id(cx),+ Some(draft_id),+ "ThreadId stays the same across promotion"+ );+ });+ cx.update(|_window, cx| {+ let store = ThreadMetadataStore::global(cx).read(cx);+ let entry = store.entry(draft_id).expect("promoted metadata row");+ assert!(+ !entry.is_draft(),+ "promoted thread should have a session_id"+ );+ });+}+#[gpui::test]async fn test_cmd_n_shows_new_thread_entry(cx: &mut TestAppContext) {// When the user presses Cmd-N (NewThread action) while viewing a@@ -3333,6 +3655,169 @@ async fn test_cmd_n_shows_new_thread_entry_in_absorbed_worktree(cx: &mut TestApp});}+#[gpui::test]+async fn test_all_ephemeral_drafts_in_group_are_hidden_from_sidebar(cx: &mut TestAppContext) {+ // An ephemeral new-draft is surfaced through its panel's `+` button,+ // never as a sidebar row. This rule must hold:+ // 1. For every workspace in a project group (not just the active one).+ // 2. Whether or not the draft is the active view of its panel —+ // i.e. even when the user has navigated away to a real thread+ // within that same panel, the draft stays in the new-draft slot+ // and stays out of the sidebar.+ agent_ui::test_support::init_test(cx);+ cx.update(|cx| {+ 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: std::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, |p, cx| p.git_scans_complete(cx))+ .await;+ worktree_project+ .update(cx, |p, cx| p.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, main_panel) = setup_sidebar_with_agent_panel(&multi_workspace, cx);+ let worktree_workspace = multi_workspace.update_in(cx, |mw, window, cx| {+ mw.test_add_workspace(worktree_project.clone(), window, cx)+ });+ let worktree_panel = add_agent_panel(&worktree_workspace, cx);+ cx.run_until_parked();++ // Give the main panel a real thread we can park the draft behind+ // later. Send a message to promote the draft→real thread.+ let real_connection = StubAgentConnection::new();+ real_connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(+ acp::ContentChunk::new("done".into()),+ )]);+ agent_ui::test_support::open_thread_with_connection(&main_panel, real_connection, cx);+ agent_ui::test_support::send_message(&main_panel, cx);+ let main_real_thread_id =+ main_panel.read_with(cx, |panel, cx| panel.active_thread_id(cx).unwrap());+ cx.run_until_parked();++ // Now open a fresh ephemeral draft in the main panel.+ agent_ui::test_support::open_draft_with_connection(&main_panel, StubAgentConnection::new(), cx);+ cx.run_until_parked();+ let main_draft_id = main_panel.read_with(cx, |panel, cx| panel.active_thread_id(cx).unwrap());+ assert_ne!(main_draft_id, main_real_thread_id);++ // And an ephemeral draft in the worktree panel as well.+ agent_ui::test_support::open_draft_with_connection(+ &worktree_panel,+ StubAgentConnection::new(),+ cx,+ );+ cx.run_until_parked();+ let worktree_draft_id =+ worktree_panel.read_with(cx, |panel, cx| panel.active_thread_id(cx).unwrap());+ assert_ne!(main_draft_id, worktree_draft_id);++ let is_draft_row_visible =+ |sidebar: &Entity<Sidebar>, cx: &mut gpui::VisualTestContext, id: ThreadId| -> bool {+ sidebar.read_with(cx, |sidebar, _| {+ sidebar.contents.entries.iter().any(+ |entry| matches!(entry, ListEntry::Thread(t) if t.metadata.thread_id == id),+ )+ })+ };++ // Baseline: both ephemeral drafts are hidden while each is the+ // active view of its own panel.+ assert!(+ !is_draft_row_visible(&sidebar, cx, main_draft_id),+ "main panel's ephemeral draft should be hidden while it is active"+ );+ assert!(+ !is_draft_row_visible(&sidebar, cx, worktree_draft_id),+ "worktree panel's ephemeral draft should be hidden while it is active"+ );++ // Navigate the main panel AWAY from its draft to the real thread.+ // The draft is no longer the active view of its panel, but it is+ // still in the ephemeral slot — it must stay out of the sidebar.+ main_panel.update_in(cx, |panel, window, cx| {+ panel.load_agent_thread(+ agent_ui::Agent::NativeAgent,+ main_real_thread_id,+ None,+ None,+ false,+ "agent_panel",+ window,+ cx,+ );+ });+ cx.run_until_parked();++ main_panel.read_with(cx, |panel, cx| {+ assert_eq!(+ panel.active_thread_id(cx),+ Some(main_real_thread_id),+ "main panel should now be viewing the real thread"+ );+ assert_eq!(+ panel.ephemeral_draft_thread_id(cx),+ Some(main_draft_id),+ "the ephemeral draft slot should still hold the parked draft"+ );+ });++ assert!(+ !is_draft_row_visible(&sidebar, cx, main_draft_id),+ "parked ephemeral draft should stay hidden when the panel's active view is a real thread"+ );+ assert!(+ !is_draft_row_visible(&sidebar, cx, worktree_draft_id),+ "worktree panel's ephemeral draft should also stay hidden"+ );++ // Switch the active workspace to the worktree: all of the above+ // assertions still hold, from the other side.+ multi_workspace.update_in(cx, |mw, window, cx| {+ mw.activate(worktree_workspace.clone(), None, window, cx);+ });+ cx.run_until_parked();++ assert!(+ !is_draft_row_visible(&sidebar, cx, main_draft_id),+ "main panel's parked ephemeral draft should stay hidden when worktree is active"+ );+ assert!(+ !is_draft_row_visible(&sidebar, cx, worktree_draft_id),+ "worktree panel's ephemeral draft should stay hidden when worktree is active"+ );+}+async fn init_test_project_with_git(worktree_path: &str,cx: &mut TestAppContext,@@ -4903,26 +5388,24 @@ async fn test_activate_archived_thread_reuses_workspace_in_another_window_with_tlet _panel_b = add_agent_panel(&workspace_b, cx_b);let session_id = acp::SessionId::new(Arc::from("archived-cross-window-with-sidebar"));+ let metadata = ThreadMetadata {+ thread_id: ThreadId::new(),+ session_id: Some(session_id.clone()),+ agent_id: agent::ZED_AGENT_ID.clone(),+ title: Some("Cross Window Thread".into()),+ updated_at: Utc::now(),+ created_at: None,+ interacted_at: None,+ worktree_paths: WorktreePaths::from_folder_paths(&PathList::new(&[PathBuf::from(+ "/project-b",+ )])),+ archived: false,+ remote_connection: None,+ };+ seed_thread_metadata(metadata.clone(), cx_a);sidebar_a.update_in(cx_a, |sidebar, window, cx| {- sidebar.open_thread_from_archive(- ThreadMetadata {- thread_id: ThreadId::new(),- session_id: Some(session_id.clone()),- agent_id: agent::ZED_AGENT_ID.clone(),- title: Some("Cross Window Thread".into()),- updated_at: Utc::now(),- created_at: None,- interacted_at: None,- worktree_paths: WorktreePaths::from_folder_paths(&PathList::new(&[PathBuf::from(- "/project-b",- )])),- archived: false,- remote_connection: None,- },- window,- cx,- );+ sidebar.open_thread_from_archive(metadata, window, cx);});cx_a.run_until_parked();@@ -4987,26 +5470,24 @@ async fn test_activate_archived_thread_prefers_current_window_for_matching_pathslet sidebar_a = setup_sidebar(&multi_workspace_a_entity, cx_a);let session_id = acp::SessionId::new(Arc::from("archived-current-window"));+ let metadata = ThreadMetadata {+ thread_id: ThreadId::new(),+ session_id: Some(session_id.clone()),+ agent_id: agent::ZED_AGENT_ID.clone(),+ title: Some("Current Window Thread".into()),+ updated_at: Utc::now(),+ created_at: None,+ interacted_at: None,+ worktree_paths: WorktreePaths::from_folder_paths(&PathList::new(&[PathBuf::from(+ "/project-a",+ )])),+ archived: false,+ remote_connection: None,+ };+ seed_thread_metadata(metadata.clone(), cx_a);sidebar_a.update_in(cx_a, |sidebar, window, cx| {- sidebar.open_thread_from_archive(- ThreadMetadata {- thread_id: ThreadId::new(),- session_id: Some(session_id.clone()),- agent_id: agent::ZED_AGENT_ID.clone(),- title: Some("Current Window Thread".into()),- updated_at: Utc::now(),- created_at: None,- interacted_at: None,- worktree_paths: WorktreePaths::from_folder_paths(&PathList::new(&[PathBuf::from(- "/project-a",- )])),- archived: false,- remote_connection: None,- },- window,- cx,- );+ sidebar.open_thread_from_archive(metadata, window, cx);});cx_a.run_until_parked();@@ -6679,24 +7160,28 @@ async fn test_unarchive_only_shows_restored_thread(cx: &mut TestAppContext) {});// Unarchive it — the draft should be replaced by the restored thread.+ let restored_title = metadata.display_title();sidebar.update_in(cx, |sidebar, window, cx| {sidebar.open_thread_from_archive(metadata, window, cx);});cx.run_until_parked();- // Only the unarchived thread should be visible — no drafts, no other threads.+ // The restored thread should be visible. A fresh draft may also be+ // visible as a sidebar row: archive_thread auto-activates one via+ // clear_base_view, and the unarchive then parks it by pushing the+ // restored thread into the base view.let entries = visible_entries_as_strings(&sidebar, cx);+ assert!(+ entries.iter().any(|e| e.contains(restored_title.as_ref())),+ "expected the restored thread to be visible, got entries: {entries:?}"+ );let thread_count = entries.iter().filter(|e| !e.starts_with("v ") && !e.starts_with("> ")).count();- assert_eq!(- thread_count, 1,- "expected exactly 1 thread entry (the restored one), got entries: {entries:?}"- );assert!(- !entries.iter().any(|e| e.contains("Draft")),- "expected no drafts after restoring, got entries: {entries:?}"+ thread_count <= 2,+ "expected at most the restored thread plus a parked draft, got entries: {entries:?}");}@@ -7370,6 +7855,8 @@ async fn test_unarchive_does_not_create_duplicate_real_thread_metadata(cx: &mut.iter().filter(|entry| !entry.starts_with("v ") && !entry.starts_with("> ")).filter(|entry| !entry.contains("Draft"))+ // Parked drafts render with the default title until the user types.+ .filter(|entry| !entry.contains(DEFAULT_THREAD_TITLE)).count();assert_eq!(real_thread_rows, 1,@@ -8146,117 +8633,6 @@ async fn test_archive_thread_on_linked_worktree_selects_sibling_thread(cx: &mut);}-// TODO: Restore this test once linked worktree draft entries are re-implemented.-// The draft-in-sidebar approach was reverted in favor of just the + button toggle.-#[gpui::test]-#[ignore = "linked worktree draft entries not yet implemented"]-async fn test_linked_worktree_workspace_reachable_and_dismissable(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(- "/wt-feature-a",- 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"),- 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, |p, cx| p.git_scans_complete(cx))- .await;- worktree_project- .update(cx, |p, cx| p.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);-- // Open the linked worktree as a separate workspace (simulates cmd-o).- let worktree_workspace = multi_workspace.update_in(cx, |mw, window, cx| {- mw.test_add_workspace(worktree_project.clone(), window, cx)- });- add_agent_panel(&worktree_workspace, cx);- cx.run_until_parked();-- // Explicitly create a draft thread from the linked worktree workspace.- // Auto-created drafts use the group's first workspace (the main one),- // so a user-created draft is needed to make the linked worktree reachable.- sidebar.update_in(cx, |sidebar, window, cx| {- sidebar.create_new_thread(&worktree_workspace, window, cx);- });- cx.run_until_parked();-- // Switch back to the main workspace.- multi_workspace.update_in(cx, |mw, window, cx| {- let main_ws = mw.workspaces().next().unwrap().clone();- mw.activate(main_ws, None, window, cx);- });- cx.run_until_parked();-- sidebar.update_in(cx, |sidebar, _window, cx| {- sidebar.update_entries(cx);- });- cx.run_until_parked();-- // The linked worktree workspace must be reachable from some sidebar entry.- let worktree_ws_id = worktree_workspace.entity_id();- let reachable: Vec<gpui::EntityId> = sidebar.read_with(cx, |sidebar, cx| {- let mw = multi_workspace.read(cx);- sidebar- .contents- .entries- .iter()- .flat_map(|entry| entry.reachable_workspaces(mw, cx))- .map(|ws| ws.entity_id())- .collect()- });- assert!(- reachable.contains(&worktree_ws_id),- "linked worktree workspace should be reachable, but reachable are: {reachable:?}"- );-- // Find the draft Thread entry whose workspace is the linked worktree.- let _ = (worktree_ws_id, sidebar, multi_workspace);- // todo("re-implement once linked worktree draft entries exist");-}-#[gpui::test]async fn test_linked_worktree_workspace_shows_main_worktree_threads(cx: &mut TestAppContext) {// When only a linked worktree workspace is open (not the main repo),@@ -10136,15 +10512,14 @@ mod property_test {// 4. Exactly one entry in sidebar contents must be uniquely// identified by the active_entry — unless the panel is showing- // a draft, which is represented by the + button's active state- // rather than a sidebar row.- // TODO: Make this check more complete+ // the new-draft slot (which is represented by the + button's+ // active state rather than a sidebar row) or nothing at all.// Active terminals must still match a row, so don't treat the absence- // of a conversation view as "draft" when a terminal is active.- let is_draft = panel.read(cx).active_terminal_id().is_none()- && (panel.read(cx).active_thread_is_draft(cx)+ // of a conversation view as "new-draft" when a terminal is active.+ let hidden_from_sidebar = panel.read(cx).active_terminal_id().is_none()+ && (panel.read(cx).active_view_is_new_draft(cx)|| panel.read(cx).active_conversation_view().is_none());- if is_draft {+ if hidden_from_sidebar {return Ok(());}let matching_count = sidebar