agent: Save threads before closing them (#51744)

Ben Brandt created

Closes #46078

When we unloaded sessions, we weren't necesarily making sure we had
saved the current state. Now we save it whenever we remove it from the
session map.

Release Notes:

- Agent: Fix cases where thread state wasn't saved before closing the
thread.

Change summary

crates/agent/src/agent.rs | 19 ++++++++++---------
1 file changed, 10 insertions(+), 9 deletions(-)

Detailed changes

crates/agent/src/agent.rs 🔗

@@ -1429,15 +1429,16 @@ impl acp_thread::AgentConnection for NativeAgentConnection {
         session_id: &acp::SessionId,
         cx: &mut App,
     ) -> Task<Result<()>> {
-        self.0.update(cx, |agent, _cx| {
-            let project_id = agent.sessions.get(session_id).map(|s| s.project_id);
-            agent.sessions.remove(session_id);
-
-            if let Some(project_id) = project_id {
-                let has_remaining = agent.sessions.values().any(|s| s.project_id == project_id);
-                if !has_remaining {
-                    agent.projects.remove(&project_id);
-                }
+        self.0.update(cx, |agent, cx| {
+            let Some(session) = agent.sessions.remove(session_id) else {
+                return;
+            };
+            let project_id = session.project_id;
+            agent.save_thread(session.thread, cx);
+
+            let has_remaining = agent.sessions.values().any(|s| s.project_id == project_id);
+            if !has_remaining {
+                agent.projects.remove(&project_id);
             }
         });
         Task::ready(Ok(()))