Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

agent_ui: Preserve input through ACP reconnect and replay (#65841)

Ben Brandt784e431c42c5
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs
index 500e7c5cb94..e0816ce698c 100644
--- a/crates/acp_thread/src/acp_thread.rs
+++ b/crates/acp_thread/src/acp_thread.rs
@@ -3646,6 +3646,7 @@ pub enum AcpThreadEvent {
stop_reason: Option<acp_v2::StopReason>,
},
Error,
+ ConnectionLost,
LoadError(LoadError),
PromptCapabilitiesUpdated,
Refusal,
@@ -3790,6 +3791,7 @@ impl AcpThread {
| AcpThreadEvent::SubagentSpawned(_)
| AcpThreadEvent::Stopped { .. }
| AcpThreadEvent::Error
+ | AcpThreadEvent::ConnectionLost
| AcpThreadEvent::LoadError(_)
| AcpThreadEvent::PromptCapabilitiesUpdated
| AcpThreadEvent::Refusal
@@ -4199,6 +4201,10 @@ impl AcpThread {
self.submissions.recoverable()
}
+ pub fn is_observation_closed(&self) -> bool {
+ self.activity.observation_closed()
+ }
+
pub fn is_idle_for_retention(&self) -> bool {
self.status() == ThreadStatus::Idle
&& !self.has_unsettled_submissions()
@@ -4225,6 +4231,7 @@ impl AcpThread {
/// Ends receipt and cancellation observations without declaring remote execution stopped.
pub fn handle_connection_lost(&mut self, cx: &mut Context<Self>) {
+ let was_observable = self.activity.ensure_observable().is_ok();
self.activity.close_observation();
let changed = self.submissions.disconnect();
if !changed.is_empty() {
@@ -4233,6 +4240,10 @@ impl AcpThread {
}
cx.notify();
}
+ if was_observable {
+ cx.emit(AcpThreadEvent::ConnectionLost);
+ cx.notify();
+ }
}
pub fn prepare_session_close(&mut self, cx: &mut Context<Self>) {
diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rs
index 9ede73f7abd..7de513c2ca5 100644
--- a/crates/acp_thread/src/connection.rs
+++ b/crates/acp_thread/src/connection.rs
@@ -961,6 +961,7 @@ mod test_support {
permission_requests: HashMap<acp_v2::ToolCallId, PermissionOptions>,
next_prompt_updates: Arc<Mutex<Vec<StubPromptUpdate>>>,
next_prompt_response: Arc<Mutex<Option<oneshot::Receiver<Result<acp_v1::PromptResponse>>>>>,
+ next_load_error: Arc<Mutex<Option<anyhow::Error>>>,
next_receipt_response:
Arc<Mutex<Option<oneshot::Receiver<Result<acp_v2::PromptResponse>>>>>,
receipt_prompt: Arc<Mutex<Option<Vec<acp_v2::ContentBlock>>>>,
@@ -1005,6 +1006,7 @@ mod test_support {
Self {
next_prompt_updates: Default::default(),
next_prompt_response: Default::default(),
+ next_load_error: Default::default(),
next_receipt_response: Default::default(),
receipt_prompt: Default::default(),
next_truncate: Default::default(),
@@ -1033,6 +1035,10 @@ mod test_support {
}
}
+ pub fn set_next_load_error(&self, error: anyhow::Error) {
+ *self.next_load_error.lock() = Some(error);
+ }
+
pub fn set_next_prompt_updates(&self, updates: Vec<acp_v1::SessionUpdate>) {
*self.next_prompt_updates.lock() = updates
.into_iter()
@@ -1308,6 +1314,9 @@ mod test_support {
return Task::ready(Err(anyhow::Error::msg("Loading sessions is not supported")));
}
+ if let Some(error) = self.next_load_error.lock().take() {
+ return Task::ready(Err(error));
+ }
let thread = self.create_session(session_id, project, work_dirs, title, cx);
Task::ready(Ok(thread))
}
diff --git a/crates/acp_thread/src/submission.rs b/crates/acp_thread/src/submission.rs
index 5f28e087151..10c2e6d3ea3 100644
--- a/crates/acp_thread/src/submission.rs
+++ b/crates/acp_thread/src/submission.rs
@@ -108,7 +108,7 @@ impl Future for Submission {
}
}
-#[derive(Debug)]
+#[derive(Clone, Debug, serde::Serialize)]
pub enum SubmissionState {
Pending,
Accepted {
@@ -441,6 +441,10 @@ impl SessionActivity {
Ok(())
}
+ pub(crate) fn observation_closed(&self) -> bool {
+ self.observation_closed
+ }
+
pub(crate) fn close_observation(&mut self) {
self.observation_closed = true;
self.cancel_waiters.clear();
diff --git a/crates/agent_ui/src/agent_diff.rs b/crates/agent_ui/src/agent_diff.rs
index 128b6736d5f..91d5725bd10 100644
--- a/crates/agent_ui/src/agent_diff.rs
+++ b/crates/agent_ui/src/agent_diff.rs
@@ -1464,7 +1464,10 @@ impl AgentDiff {
AcpThreadEvent::Stopped { .. } => {
self.update_reviewing_editors(workspace, window, cx);
}
- AcpThreadEvent::Error | AcpThreadEvent::LoadError(_) | AcpThreadEvent::Refusal => {
+ AcpThreadEvent::Error
+ | AcpThreadEvent::ConnectionLost
+ | AcpThreadEvent::LoadError(_)
+ | AcpThreadEvent::Refusal => {
self.update_reviewing_editors(workspace, window, cx);
}
AcpThreadEvent::TitleUpdated
diff --git a/crates/agent_ui/src/agent_panel.rs b/crates/agent_ui/src/agent_panel.rs
index 171c2569738..d992a673901 100644
--- a/crates/agent_ui/src/agent_panel.rs
+++ b/crates/agent_ui/src/agent_panel.rs
@@ -1826,7 +1826,7 @@ impl AgentPanel {
fn draft_has_content(&self, draft: &Entity<ConversationView>, cx: &App) -> bool {
let cv = draft.read(cx);
- if cv.has_pending_selections() {
+ if cv.has_pending_selections() || cv.has_saved_input() {
return true;
}
if let Some(thread_view) = cv.active_thread() {
@@ -4303,7 +4303,7 @@ impl AgentPanel {
.iter()
.filter(|(_id, view)| {
let view = view.read(cx);
- if view.has_pending_selections() {
+ if view.has_pending_selections() || view.has_saved_input() {
return false;
}
let Some(thread_view) = view.root_thread_view() else {
@@ -11910,6 +11910,46 @@ mod tests {
});
}
+ #[gpui::test]
+ async fn test_disconnected_saved_input_is_not_evicted_as_idle(cx: &mut TestAppContext) {
+ let (panel, mut cx) = setup_panel(cx).await;
+ let connection = StubAgentConnection::new()
+ .with_receipt_submissions(true)
+ .with_supports_load_session(true);
+ open_thread_with_custom_connection(&panel, connection.clone(), &mut cx);
+ let saved = panel.read_with(&cx, |panel, _| {
+ panel
+ .active_conversation_view()
+ .expect("conversation")
+ .clone()
+ });
+ let _response = connection.defer_next_receipt_response();
+ send_message(&panel, &mut cx);
+ let thread = saved.read_with(&cx, |view, cx| view.root_thread(cx).expect("thread"));
+ thread.update(&mut cx, |thread, cx| thread.handle_connection_lost(cx));
+ cx.run_until_parked();
+ assert!(saved.read_with(&cx, |view, _| view.has_saved_input()));
+
+ cx.update(|_, cx| {
+ AgentSettings::override_global(
+ AgentSettings {
+ max_idle_retained_threads: 0,
+ ..AgentSettings::get_global(cx).clone()
+ },
+ cx,
+ );
+ });
+ open_thread_with_custom_connection(&panel, connection, &mut cx);
+ panel.update(&mut cx, |panel, cx| {
+ panel.cleanup_retained_threads(cx);
+ assert!(
+ panel
+ .retained_threads
+ .contains_key(&saved.read(cx).thread_id)
+ );
+ });
+ }
+
#[gpui::test]
async fn test_completed_retained_thread_is_unloaded_when_retained_thread_limit_is_zero(
cx: &mut TestAppContext,
diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs
index 5786e6231fe..ee321378226 100644
--- a/crates/agent_ui/src/conversation_view.rs
+++ b/crates/agent_ui/src/conversation_view.rs
@@ -355,6 +355,7 @@ impl Conversation {
| AcpThreadEvent::SubagentSpawned(_)
| AcpThreadEvent::Stopped { .. }
| AcpThreadEvent::Error
+ | AcpThreadEvent::ConnectionLost
| AcpThreadEvent::LoadError(_)
| AcpThreadEvent::PromptCapabilitiesUpdated
| AcpThreadEvent::Refusal
@@ -758,6 +759,7 @@ fn affects_thread_metadata(event: &AcpThreadEvent) -> bool {
| AcpThreadEvent::ElicitationResponded(_)
| AcpThreadEvent::Stopped { .. }
| AcpThreadEvent::Error
+ | AcpThreadEvent::ConnectionLost
| AcpThreadEvent::LoadError(_)
| AcpThreadEvent::Refusal
| AcpThreadEvent::WorkingDirectoriesUpdated => true,
@@ -796,6 +798,8 @@ pub struct ConversationView {
pub(crate) thread_id: ThreadId,
pub(crate) root_session_id: Option<acp_v2::SessionId>,
server_state: ServerState,
+ recovery: Option<ThreadRecovery>,
+ saved_submissions: Vec<SavedSubmission>,
pending_selections: Vec<AgentContextSelection>,
focus_handle: FocusHandle,
notifications: Vec<WindowHandle<AgentNotification>>,
@@ -837,6 +841,10 @@ impl ConversationView {
}
}
+ pub(crate) fn has_saved_input(&self) -> bool {
+ self.recovery.is_some() || !self.saved_submissions.is_empty()
+ }
+
pub fn pending_tool_call<'a>(
&'a self,
cx: &'a App,
@@ -1121,6 +1129,8 @@ impl ConversationView {
window,
cx,
),
+ recovery: None,
+ saved_submissions: Vec::new(),
pending_selections: Vec::new(),
notifications: Vec::new(),
notification_subscriptions: HashMap::default(),
@@ -1136,6 +1146,13 @@ impl ConversationView {
}
fn set_server_state(&mut self, state: ServerState, cx: &mut Context<Self>) {
+ if matches!(&state, ServerState::LoadError { .. })
+ && let Some(view) = self.root_thread_view()
+ && let Some(recovery) = view.read(cx).snapshot_recovery(cx)
+ {
+ self.draft_prompt_persist_task.take();
+ self.recovery = Some(recovery);
+ }
let previous_request_elicitation_connection = self.request_elicitation_connection();
let next_request_elicitation_connection =
Self::request_elicitation_connection_for_state(&state);
@@ -1229,6 +1246,15 @@ impl ConversationView {
thread.title(),
)
})
+ .or_else(|| {
+ self.recovery.as_ref().map(|recovery| {
+ (
+ Some(recovery.session_id.clone()),
+ recovery.work_dirs.clone(),
+ recovery.title.clone(),
+ )
+ })
+ })
.unwrap_or_else(|| {
let session_id = self.root_session_id.clone();
let (work_dirs, title) = session_id
@@ -1357,6 +1383,12 @@ impl ConversationView {
);
let mut resumed_without_history = false;
+ let Some(recovering) = this
+ .read_with(cx, |this, _| this.recovery.is_some())
+ .log_err()
+ else {
+ return;
+ };
let result = if let Some(session_id) = resume_session_id.clone() {
cx.update(|_, cx| {
if connection.supports_load_session() {
@@ -1367,6 +1399,10 @@ impl ConversationView {
title,
cx,
)
+ } else if recovering {
+ Task::ready(Err(anyhow!(
+ "Reconnecting requires full history replay. Saved input has been kept."
+ )))
} else if connection.supports_resume_session() {
resumed_without_history = true;
connection.clone().resume_session(
@@ -1413,6 +1449,11 @@ impl ConversationView {
this.update_in(cx, |this, window, cx| {
match result {
Ok(thread) => {
+ if let Some(recovery) = &this.recovery {
+ thread.update(cx, |thread, cx| {
+ thread.set_draft_prompt(Some(recovery.draft.clone()), cx);
+ });
+ }
this.clear_resolved_request_elicitations_for_connection(&connection, cx);
let root_session_id = thread.read(cx).session_id().clone();
@@ -1431,6 +1472,12 @@ impl ConversationView {
cx,
);
+ if let Some(recovery) = &this.recovery {
+ current.update(cx, |view, cx| {
+ view.restore_recovery(recovery, window, cx);
+ });
+ }
+
if this.has_pending_selections() {
current.update(cx, |thread, cx| {
thread.message_editor.update(cx, |editor, cx| {
@@ -1464,6 +1511,9 @@ impl ConversationView {
}),
cx,
);
+ if let Some(recovery) = this.recovery.take() {
+ this.saved_submissions.extend(recovery.submissions);
+ }
}
Err(err) => {
this.handle_load_error(
@@ -1759,6 +1809,10 @@ impl ConversationView {
window: &mut Window,
cx: &mut Context<Self>,
) {
+ // Reattachment after observation loss must not reuse the cached, closed connection.
+ if self.recovery.is_some() {
+ return;
+ }
// If we're in a LoadError state OR have a thread_error set (which can happen
// when agent.connect() fails during loading), retry loading the thread.
// This handles the case where a thread is restored before authentication completes.
@@ -2146,7 +2200,17 @@ impl ConversationView {
);
}
}
+ AcpThreadEvent::ConnectionLost => {
+ self.handle_load_error(
+ LoadError::Other(
+ "Agent connection lost. Reconnect to restore the conversation.".into(),
+ ),
+ window,
+ cx,
+ );
+ }
AcpThreadEvent::LoadError(error) => {
+ thread.update(cx, |thread, cx| thread.handle_connection_lost(cx));
if let Some(view) = self.root_thread_view() {
if view
.read(cx)
@@ -3085,6 +3149,35 @@ impl ConversationView {
);
}
+ fn copy_saved_input_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
+ div()
+ .debug_selector(|| "copy-saved-agent-input".into())
+ .child(
+ Button::new("copy-saved-agent-input", "Copy Saved Input")
+ .tooltip(Tooltip::text(
+ "Copy the original content and receipt evidence as JSON",
+ ))
+ .on_click(cx.listener(|this, _, window, cx| {
+ match ThreadRecovery::to_json(
+ this.root_session_id.as_ref(),
+ this.recovery.as_ref(),
+ &this.saved_submissions,
+ ) {
+ Ok(saved) => {
+ cx.write_to_clipboard(ClipboardItem::new_string(saved));
+ }
+ Err(error) => this.handle_load_error(
+ LoadError::Other(
+ format!("Failed to copy saved input: {error}").into(),
+ ),
+ window,
+ cx,
+ ),
+ }
+ })),
+ )
+ }
+
fn render_load_error(
&self,
e: &LoadError,
@@ -3834,6 +3927,36 @@ impl Render for ConversationView {
.size_full()
.bg(cx.theme().colors().panel_background)
.child(v_flex().flex_1().min_h_0().child(content))
+ .when(self.has_saved_input(), |this| {
+ this.child(
+ h_flex()
+ .p_2()
+ .gap_2()
+ .flex_wrap()
+ .child(self.copy_saved_input_button(cx))
+ .when(
+ !self.saved_submissions.is_empty()
+ || self.recovery.as_ref().is_some_and(|recovery| !recovery.submissions.is_empty()),
+ |this| {
+ this.child(
+ div()
+ .debug_selector(|| "discard-saved-agent-submissions".into())
+ .child(
+ Button::new("discard-saved-agent-submissions", "Discard Saved Submissions")
+ .tooltip(Tooltip::text("Discard local copies only; does not cancel agent work"))
+ .on_click(cx.listener(|this, _, _, cx| {
+ this.saved_submissions.clear();
+ if let Some(recovery) = &mut this.recovery {
+ recovery.submissions.clear();
+ }
+ cx.notify();
+ })),
+ ),
+ )
+ },
+ ),
+ )
+ })
.when(!active_thread_renders_request_elicitations, |this| {
this.children(request_elicitation_connection.as_ref().map_or_else(
Vec::new,
@@ -5572,9 +5695,7 @@ pub(crate) mod tests {
}
#[gpui::test]
- async fn test_receipt_disconnect_preserves_draft_without_restore_or_resend(
- cx: &mut TestAppContext,
- ) {
+ async fn test_reconnect_without_full_replay_keeps_saved_input(cx: &mut TestAppContext) {
init_test(cx);
let connection = StubAgentConnection::new().with_receipt_submissions(true);
let (conversation_view, cx) =
@@ -5602,12 +5723,34 @@ pub(crate) mod tests {
editor.read_with(cx, |editor, cx| editor.text(cx)),
"keep my draft"
);
- let copy: &'static str =
- Box::leak(format!("copy-submission-{}", pending_id.as_u64()).into_boxed_str());
- let restore: &'static str =
- Box::leak(format!("restore-submission-{}", pending_id.as_u64()).into_boxed_str());
- assert!(cx.debug_bounds(copy).is_some());
- assert!(cx.debug_bounds(restore).is_none());
+ conversation_view.update_in(cx, |view, window, cx| view.retry_connection(window, cx));
+ cx.run_until_parked();
+ conversation_view.read_with(cx, |view, _| {
+ assert!(matches!(&view.server_state,
+ ServerState::LoadError { error } if error.to_string().contains("full history replay")
+ ));
+ assert!(view.recovery.is_some());
+ });
+ let copy = cx
+ .debug_bounds("copy-saved-agent-input")
+ .expect("saved input remains accessible");
+ cx.simulate_click(copy.center(), gpui::Modifiers::default());
+ let saved: serde_json::Value = serde_json::from_str(
+ &cx.update(|_, cx| cx.read_from_clipboard().and_then(|item| item.text()))
+ .expect("saved input"),
+ )
+ .expect("JSON export");
+ assert_eq!(saved["draft"][0]["text"], "keep my draft");
+ assert_eq!(saved["submissions"][0][0][0]["text"], "unknown content");
+ thread.read_with(cx, |thread, _| {
+ assert!(matches!(
+ thread
+ .submission(pending_id)
+ .expect("original record")
+ .state,
+ acp_thread::SubmissionState::Disconnected { receipt: None }
+ ));
+ });
assert!(connection.take_receipt_prompt().is_none());
}
@@ -7169,6 +7312,206 @@ pub(crate) mod tests {
});
}
+ #[gpui::test]
+ async fn test_reconnect_preserves_input_through_failure_and_authentication(
+ cx: &mut TestAppContext,
+ ) {
+ use std::sync::atomic::Ordering;
+
+ init_test(cx);
+ let connection = StubAgentConnection::new()
+ .with_receipt_submissions(true)
+ .with_supports_load_session(true);
+ let (server, fail) = FlakyAgentServer::new(connection.clone());
+ fail.store(false, Ordering::SeqCst);
+ let (conversation_view, cx) = setup_conversation_view(server, cx).await;
+ add_to_workspace_with_size(conversation_view.clone(), true, cx);
+ let previous_view = active_thread(&conversation_view, cx);
+ let previous_thread = previous_view.read_with(cx, |view, _| view.thread.clone());
+ let session_id = previous_thread.read_with(cx, |thread, _| thread.session_id().clone());
+ let receipt = acp_v2::PromptResponse::new("accepted").meta(acp_v2::Meta::from_iter([(
+ "evidence".into(),
+ json!({"opaque": [null, true]}),
+ )]));
+ let accepted = connection.defer_next_receipt_response();
+ let submission = previous_thread.update(cx, |thread, cx| {
+ thread.send(vec!["accepted input".into()], cx)
+ });
+ accepted.send(Ok(receipt.clone())).expect("pending receipt");
+ submission.await.expect("accepted input");
+ let _unknown_response = connection.defer_next_receipt_response();
+ let unknown = previous_thread.update(cx, |thread, cx| {
+ thread.send(vec!["uncertain input".into()], cx)
+ });
+ assert!(connection.take_receipt_prompt().is_some());
+ let queued: Vec<acp_v2::ContentBlock> = serde_json::from_value(json!([
+ {"type": "_future", "data": {"nested": [null, true]}, "_meta": {"source": "queue"}}
+ ]))
+ .expect("opaque queued input");
+ previous_view.update_in(cx, |view, window, cx| {
+ view.add_to_queue(queued.clone(), vec![], window, cx);
+ view.message_editor.update(cx, |editor, cx| {
+ editor.set_text("keep this draft", window, cx);
+ });
+ });
+ previous_thread.update(cx, |thread, cx| thread.handle_connection_lost(cx));
+ cx.run_until_parked();
+ assert!(unknown.await.is_err());
+ drop(previous_view);
+
+ fail.store(true, Ordering::SeqCst);
+ for _ in 0..2 {
+ conversation_view.update_in(cx, |view, window, cx| view.retry_connection(window, cx));
+ cx.run_until_parked();
+ conversation_view.read_with(cx, |view, _| {
+ assert!(matches!(view.server_state, ServerState::LoadError { .. }));
+ assert!(view.recovery.is_some());
+ assert_eq!(view.root_session_id.as_ref(), Some(&session_id));
+ });
+ }
+ let copy = cx
+ .debug_bounds("copy-saved-agent-input")
+ .expect("copy while disconnected");
+ cx.simulate_click(copy.center(), gpui::Modifiers::default());
+ let saved: serde_json::Value = serde_json::from_str(
+ &cx.update(|_, cx| cx.read_from_clipboard().and_then(|item| item.text()))
+ .expect("saved JSON"),
+ )
+ .expect("recovery export");
+ assert_eq!(
+ saved["queued"][0],
+ serde_json::to_value(&queued).expect("source")
+ );
+ assert_eq!(saved["draft"][0]["text"], "keep this draft");
+ assert_eq!(
+ saved["submissions"][0][1]["Disconnected"]["receipt"],
+ serde_json::to_value(&receipt).expect("receipt evidence")
+ );
+ fail.store(false, Ordering::SeqCst);
+ conversation_view.update(cx, |view, cx| {
+ view.project
+ .read(cx)
+ .agent_server_store()
+ .clone()
+ .update(cx, |_, cx| {
+ cx.emit(project::AgentServersUpdated);
+ });
+ });
+ cx.run_until_parked();
+ conversation_view.read_with(cx, |view, _| {
+ assert!(matches!(view.server_state, ServerState::LoadError { .. }));
+ });
+
+ connection.set_next_load_error(anyhow!(AuthRequired::new()));
+ conversation_view.update_in(cx, |view, window, cx| view.retry_connection(window, cx));
+ cx.run_until_parked();
+ conversation_view.read_with(cx, |view, _| {
+ assert!(matches!(
+ view.as_connected().expect("authentication gate").auth_state,
+ AuthState::Unauthenticated { .. }
+ ));
+ assert!(view.recovery.is_some());
+ });
+ assert!(cx.debug_bounds("copy-saved-agent-input").is_some());
+ conversation_view.update_in(cx, |view, window, cx| view.reset(window, cx));
+ cx.run_until_parked();
+ let current_view = active_thread(&conversation_view, cx);
+ let current_thread = current_view.read_with(cx, |view, _| view.thread.clone());
+ assert_ne!(current_thread, previous_thread);
+ current_thread.read_with(cx, |thread, cx| {
+ assert_eq!(thread.session_id(), &session_id);
+ assert!(!Rc::ptr_eq(
+ thread.connection(),
+ previous_thread.read(cx).connection()
+ ));
+ assert_eq!(thread.recoverable_submissions().count(), 0);
+ assert!(thread.latest_submission_id().is_none());
+ });
+ conversation_view.read_with(cx, |view, _| {
+ let records = &view.saved_submissions;
+ assert_eq!(records.len(), 2);
+ assert!(matches!(&records[0].state, acp_thread::SubmissionState::Disconnected { receipt: Some(saved) } if saved == &receipt));
+ assert!(matches!(&records[1].state, acp_thread::SubmissionState::Disconnected { receipt: None }));
+ assert_eq!(records[0].content.as_ref(), &["accepted input".into()]);
+ assert_eq!(records[1].content.as_ref(), &["uncertain input".into()]);
+ });
+ for _ in 0..2 {
+ current_thread.update(cx, |_, cx| cx.emit(AcpThreadEvent::ActivityConfirmedIdle));
+ cx.run_until_parked();
+ current_view.read_with(cx, |view, cx| {
+ assert_eq!(view.message_editor.read(cx).text(cx), "keep this draft");
+ assert!(view.thread_error.is_none());
+ assert_eq!(view.message_queue.len(), 1);
+ assert_eq!(
+ serde_json::to_value(&view.message_queue.first().expect("saved queue").content)
+ .expect("queue"),
+ serde_json::to_value(&queued).expect("original queue"),
+ );
+ });
+ }
+ assert!(
+ connection.take_receipt_prompt().is_none(),
+ "recovery must not send input"
+ );
+ conversation_view.read_with(cx, |view, _| assert!(view.recovery.is_none()));
+ let copy = cx
+ .debug_bounds("copy-saved-agent-input")
+ .expect("old submissions stay copyable");
+ cx.simulate_click(copy.center(), gpui::Modifiers::default());
+ let after_reconnect: serde_json::Value = serde_json::from_str(
+ &cx.update(|_, cx| cx.read_from_clipboard().and_then(|item| item.text()))
+ .expect("saved copies"),
+ )
+ .expect("JSON export");
+ assert_eq!(after_reconnect["submissions"], saved["submissions"]);
+
+ current_thread.update(cx, |thread, cx| {
+ thread
+ .upsert_user_message(
+ acp_v2::UserMessage::new("accepted").content(vec!["accepted input".into()]),
+ cx,
+ )
+ .expect("canonical history does not reconcile saved copies");
+ thread.set_draft_prompt(Some(queued.clone()), cx);
+ });
+ current_view.update_in(cx, |view, window, cx| {
+ view.message_editor.update(cx, |editor, cx| {
+ editor.set_read_only(true, cx);
+ editor.set_source_message(queued.clone(), window, cx);
+ });
+ });
+ current_thread.update(cx, |thread, cx| thread.handle_connection_lost(cx));
+ cx.run_until_parked();
+ conversation_view.update_in(cx, |view, window, cx| view.retry_connection(window, cx));
+ cx.run_until_parked();
+ active_thread(&conversation_view, cx).read_with(cx, |view, cx| {
+ assert!(view.message_editor.read(cx).editor().read(cx).read_only(cx));
+ assert_eq!(
+ serde_json::to_value(view.thread.read(cx).draft_prompt()).expect("recovered draft"),
+ serde_json::to_value(&queued).expect("original source"),
+ );
+ assert_eq!(view.thread.read(cx).recoverable_submissions().count(), 0);
+ assert_eq!(view.message_queue.len(), 1);
+ });
+ conversation_view.read_with(cx, |view, _| assert_eq!(view.saved_submissions.len(), 2));
+ let discard = cx
+ .debug_bounds("discard-saved-agent-submissions")
+ .expect("discard local copies");
+ cx.simulate_click(discard.center(), gpui::Modifiers::default());
+ cx.run_until_parked();
+ conversation_view.read_with(cx, |view, _| assert!(view.saved_submissions.is_empty()));
+ assert!(cx.debug_bounds("copy-saved-agent-input").is_none());
+ active_thread(&conversation_view, cx).read_with(cx, |view, cx| {
+ assert_eq!(
+ view.message_queue.len(),
+ 1,
+ "discarding copies leaves the restored queue alone"
+ );
+ assert!(view.thread.read(cx).draft_prompt().is_some());
+ });
+ assert!(connection.take_receipt_prompt().is_none());
+ }
+
#[gpui::test]
async fn test_reset_ignores_events_from_retained_previous_owner(cx: &mut TestAppContext) {
init_test(cx);
diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs
index 94f523a39db..1ae7e55a6b8 100644
--- a/crates/agent_ui/src/conversation_view/thread_view.rs
+++ b/crates/agent_ui/src/conversation_view/thread_view.rs
@@ -59,6 +59,60 @@ use super::*;
const DATA_RETENTION_LEARN_MORE_URL: &str = "https://support.claude.com/en/articles/15425996-data-retention-practices-for-mythos-class-models";
+pub(super) struct ThreadRecovery {
+ pub session_id: acp_v2::SessionId,
+ pub work_dirs: Option<PathList>,
+ pub title: Option<SharedString>,
+ pub submissions: Vec<SavedSubmission>,
+ pub draft: Vec<acp_v2::ContentBlock>,
+ queued: Vec<QueuedMessageRecovery>,
+}
+
+struct QueuedMessageRecovery {
+ content: Vec<acp_v2::ContentBlock>,
+ tracked_buffers: Vec<Entity<Buffer>>,
+}
+
+pub(super) struct SavedSubmission {
+ pub content: Arc<[acp_v2::ContentBlock]>,
+ pub state: SubmissionState,
+}
+
+impl ThreadRecovery {
+ pub(super) fn to_json(
+ session_id: Option<&acp_v2::SessionId>,
+ recovery: Option<&Self>,
+ saved_submissions: &[SavedSubmission],
+ ) -> Result<String> {
+ #[derive(serde::Serialize)]
+ struct SavedInput<'a> {
+ session_id: Option<&'a acp_v2::SessionId>,
+ draft: &'a [acp_v2::ContentBlock],
+ queued: Vec<&'a [acp_v2::ContentBlock]>,
+ submissions: Vec<(&'a [acp_v2::ContentBlock], &'a SubmissionState)>,
+ }
+
+ Ok(serde_json::to_string_pretty(&SavedInput {
+ session_id,
+ draft: recovery.map_or(&[], |recovery| recovery.draft.as_slice()),
+ queued: recovery
+ .into_iter()
+ .flat_map(|recovery| &recovery.queued)
+ .map(|queued| queued.content.as_slice())
+ .collect(),
+ submissions: saved_submissions
+ .iter()
+ .chain(
+ recovery
+ .into_iter()
+ .flat_map(|recovery| &recovery.submissions),
+ )
+ .map(|submission| (submission.content.as_ref(), &submission.state))
+ .collect(),
+ })?)
+ }
+}
+
#[derive(Default)]
struct ThreadFeedbackState {
feedback: Option<ThreadFeedback>,
@@ -784,6 +838,67 @@ pub fn open_markdown_in_workspace(
}
impl ThreadView {
+ pub(super) fn snapshot_recovery(&self, cx: &App) -> Option<ThreadRecovery> {
+ let thread = self.thread.read(cx);
+ if !thread.uses_reported_activity() || !thread.is_observation_closed() {
+ return None;
+ }
+ let editor = self.message_editor.read(cx);
+ let draft = if editor.editor().read(cx).read_only(cx) {
+ thread
+ .draft_prompt()
+ .map(<[_]>::to_vec)
+ .unwrap_or_else(|| editor.draft_content_blocks_snapshot(cx))
+ } else {
+ editor.draft_content_blocks_snapshot(cx)
+ };
+ Some(ThreadRecovery {
+ session_id: thread.session_id().clone(),
+ work_dirs: thread.work_dirs().cloned(),
+ title: thread.title(),
+ submissions: thread
+ .recoverable_submissions()
+ .map(|(_, record)| SavedSubmission {
+ content: record.content.clone(),
+ state: record.state.clone(),
+ })
+ .collect(),
+ draft,
+ queued: self
+ .message_queue
+ .iter()
+ .map(|entry| {
+ let editor = entry.editor.read(cx);
+ QueuedMessageRecovery {
+ content: if editor.editor().read(cx).read_only(cx) {
+ entry.content.clone()
+ } else {
+ editor.draft_content_blocks_snapshot(cx)
+ },
+ tracked_buffers: entry.tracked_buffers.clone(),
+ }
+ })
+ .collect(),
+ })
+ }
+
+ pub(super) fn restore_recovery(
+ &mut self,
+ recovery: &ThreadRecovery,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ for queued in &recovery.queued {
+ self.add_to_queue(
+ queued.content.clone(),
+ queued.tracked_buffers.clone(),
+ window,
+ cx,
+ );
+ }
+ self.message_queue.pause();
+ }
+
pub(crate) fn new(
root_thread_id: ThreadId,
thread: Entity<AcpThread>,