Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(projects): preserve sessions when replacing a moved folder
Linuxdazhaobe7a3499a6c9
diff --git a/crates/host-core/src/db/project_groups.rs b/crates/host-core/src/db/project_groups.rsindex 643b6d749..514e56463 100644--- a/crates/host-core/src/db/project_groups.rs+++ b/crates/host-core/src/db/project_groups.rs@@ -357,6 +357,7 @@ impl Database {}return self.rename_project_group(¤t.id, name);}+ let transaction = self.conn.unchecked_transaction()?;let current_primary = canonical_project_path(¤t.primary_path).ok_or_else(|| anyhow!("project group primary path is invalid"))?;let requested_primary = primary@@ -394,12 +395,14 @@ impl Database {"the primary folder must be one of the group folders: {requested}"))}- None if selected.iter().any(|path| path == ¤t_primary) => current_primary,+ None if selected.iter().any(|path| path == ¤t_primary) => current_primary.clone(),None => return Err(anyhow!("the primary folder cannot be removed")),};let mut ordered = vec![primary.clone()];ordered.extend(selected.into_iter().filter(|path| path != &primary));+ let relocating_single_root =+ current.roots.len() == 1 && ordered.len() == 1 && primary != current_primary;let removed = current.roots.iter()@@ -407,22 +410,32 @@ impl Database {.filter(|path| !ordered.iter().any(|candidate| candidate == path)).collect::<Vec<_>>();let mut removed_without_sessions = Vec::new();- for path in &removed {- let has_sessions: bool = self.conn.query_row(- "SELECT EXISTS(- SELECT 1 FROM sessions s- JOIN projects p ON p.id = s.project_id- WHERE p.path = ?1- )",- params![path],- |row| row.get(0),- )?;- if !has_sessions {- removed_without_sessions.push(*path);+ if !relocating_single_root {+ for path in &removed {+ let has_sessions: bool = self.conn.query_row(+ "SELECT EXISTS(+ SELECT 1 FROM sessions s+ JOIN projects p ON p.id = s.project_id+ WHERE p.path = ?1+ )",+ params![path],+ |row| row.get(0),+ )?;+ if !has_sessions {+ removed_without_sessions.push(*path);+ }}}- for path in &ordered {- self.ensure_project(path, false)?;+ if relocating_single_root {+ super::project_path_migration::relocate_project_path(+ &self.conn,+ ¤t_primary,+ &primary,+ )?;+ } else {+ for path in &ordered {+ self.ensure_project(path, false)?;+ }}if current.legacy && ordered.len() == 1 {@@ -431,6 +444,13 @@ impl Database {.execute(params![name, primary])?;let mut legacy = current;legacy.name = name.to_string();+ if relocating_single_root {+ legacy.id = format!("legacy:{primary}");+ legacy.primary_path = primary.clone();+ legacy.roots[0].path = primary.clone();+ legacy.roots[0].name = project_display_name(&primary);+ }+ transaction.commit()?;return Ok(legacy);}@@ -507,6 +527,7 @@ impl Database {}}self.kv_set(GROUP_NAMESPACE, &group.id, &serde_json::to_value(&group)?)?;+ transaction.commit()?;Ok(group)}diff --git a/crates/host-core/src/db/project_path_migration.rs b/crates/host-core/src/db/project_path_migration.rsindex dd3a2a821..d22192b00 100644--- a/crates/host-core/src/db/project_path_migration.rs+++ b/crates/host-core/src/db/project_path_migration.rs@@ -121,6 +121,97 @@ pub(super) fn reconcile_project_paths(conn: &Connection, target: Option<&str>) -Ok(())}+/// Move one explicitly selected project to its replacement directory while+/// retaining the project id used by sessions and scheduled tasks. The target+/// may be an empty shadow row created by opening the replacement path first;+/// a target with its own chats, tasks, or memory is never merged implicitly.+pub(super) fn relocate_project_path(conn: &Connection, old: &str, new: &str) -> Result<i64> {+ let source = conn+ .query_row("SELECT id FROM projects WHERE path=?1", [old], |row| {+ row.get::<_, i64>(0)+ })+ .optional()?+ .ok_or_else(|| anyhow!("project to relocate was not found: {old}"))?;+ let target = conn+ .query_row("SELECT id FROM projects WHERE path=?1", [new], |row| {+ row.get::<_, i64>(0)+ })+ .optional()?;+ let task_paths = {+ let mut statement = conn.prepare(+ "SELECT id,json_extract(config_json,'$.workspacePath') FROM scheduled_tasks+ WHERE json_extract(config_json,'$.workspacePath') IS NOT NULL",+ )?;+ let rows = statement+ .query_map([], |row| {+ Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))+ })?+ .collect::<rusqlite::Result<Vec<_>>>()?;+ rows+ };+ let target_task = task_paths+ .iter()+ .any(|(_, path)| path.as_deref().and_then(canonical_project_path).as_deref() == Some(new));+ let occupied: bool = target_task+ || conn.query_row(+ "SELECT EXISTS(SELECT 1 FROM kv WHERE ns='projectMemory' AND key=?1)+ OR EXISTS(SELECT 1 FROM sessions WHERE project_id=?2)+ OR EXISTS(SELECT 1 FROM scheduled_tasks WHERE project_id=?2)",+ params![new, target],+ |row| row.get(0),+ )?;+ if occupied {+ return Err(anyhow!(+ "replacement folder belongs to a non-empty project: {new}"+ ));+ }++ conn.execute_batch("SAVEPOINT relocate_project_path")?;+ let result = (|| -> Result<()> {+ if let Some(target) = target {+ conn.execute(+ "UPDATE projects SET pinned=MAX(pinned,(SELECT pinned FROM projects WHERE id=?2)),+ created_at=MIN(created_at,(SELECT created_at FROM projects WHERE id=?2)),+ last_opened_at=MAX(last_opened_at,(SELECT last_opened_at FROM projects WHERE id=?2)),+ worktree_setup_command=COALESCE(worktree_setup_command,(SELECT worktree_setup_command FROM projects WHERE id=?2))+ WHERE id=?1",+ params![source, target],+ )?;+ conn.execute(+ "UPDATE kv SET value_json=?1 WHERE ns='app' AND key='currentProjectId'+ AND (value_json=?2 OR value_json=printf('\"%d\"',?2))",+ params![source.to_string(), target],+ )?;+ conn.execute("DELETE FROM projects WHERE id=?1", [target])?;+ }+ for (id, path) in &task_paths {+ if path.as_deref().and_then(canonical_project_path).as_deref() == Some(old) {+ conn.execute(+ "UPDATE scheduled_tasks SET config_json=json_set(config_json,'$.workspacePath',?1)+ WHERE id=?2",+ params![new, id],+ )?;+ }+ }+ conn.execute(+ "UPDATE kv SET key=?1 WHERE ns='projectMemory' AND key=?2",+ params![new, old],+ )?;+ conn.execute(+ "UPDATE projects SET path=?1 WHERE id=?2",+ params![new, source],+ )?;+ conn.execute_batch("RELEASE relocate_project_path")?;+ Ok(())+ })();+ if let Err(error) = result {+ conn.execute_batch("ROLLBACK TO relocate_project_path; RELEASE relocate_project_path")+ .context("roll back explicit project relocation")?;+ return Err(error);+ }+ Ok(source)+}+impl Database {/// A destructive operation must prefer the selected stored row. Resolving/// symlinks/case first can silently select a different historical row.diff --git a/crates/host-core/src/db/tests.rs b/crates/host-core/src/db/tests.rsindex 4f3e115aa..39002987a 100644--- a/crates/host-core/src/db/tests.rs+++ b/crates/host-core/src/db/tests.rs@@ -1857,6 +1857,243 @@ fn project_group_update_switches_the_primary_root() {assert_eq!(unchanged.primary_path, canonical_member);}+#[test]+fn single_root_replacement_preserves_legacy_project_and_its_owned_data() {+ let dir = tempfile::tempdir().unwrap();+ let old = dir.path().join("old");+ let new = dir.path().join("new");+ std::fs::create_dir(&old).unwrap();+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();+ let source = db.ensure_project(&old.to_string_lossy(), false).unwrap();+ db.conn()+ .execute(+ "INSERT INTO sessions(id,project_id,created_at,updated_at) VALUES('session',?1,1,1)",+ [source],+ )+ .unwrap();+ db.conn()+ .execute(+ "INSERT INTO scheduled_tasks(id,title,prompt,project_id,config_json,created_at,updated_at)+ VALUES('task','Task','Prompt',?1,json_object('workspacePath',?2),1,1)",+ params![+ source,+ format!(+ "{}/",+ crate::db::canonical_project_path(&old.to_string_lossy()).unwrap()+ )+ ],+ )+ .unwrap();+ db.set_project_memory(&old.to_string_lossy(), "Keep this context")+ .unwrap();+ let group = db+ .list_project_groups()+ .unwrap()+ .into_iter()+ .find(|group| group.legacy)+ .unwrap();++ std::fs::rename(&old, &new).unwrap();+ let shadow = db.ensure_project(&new.to_string_lossy(), false).unwrap();+ db.kv_set(+ "app",+ "currentProjectId",+ &serde_json::json!(shadow.to_string()),+ )+ .unwrap();+ let updated = db+ .update_project_group(+ &group.id,+ "Relocated",+ &[new.to_string_lossy().into_owned()],+ Some(&new.to_string_lossy()),+ )+ .unwrap();++ let canonical_new = crate::db::canonical_project_path(&new.to_string_lossy()).unwrap();+ assert_eq!(updated.primary_path, canonical_new);+ assert_eq!(+ db.project_path(source).unwrap().as_deref(),+ Some(canonical_new.as_str())+ );+ assert!(db.get_project(shadow).unwrap().is_none());+ assert_eq!(db.list_projects().unwrap().len(), 1);+ let owner: i64 = db+ .conn()+ .query_row(+ "SELECT project_id FROM sessions WHERE id='session'",+ [],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(owner, source);+ let task_owner: i64 = db+ .conn()+ .query_row(+ "SELECT project_id FROM scheduled_tasks WHERE id='task'",+ [],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(task_owner, source);+ let task_workspace: String = db+ .conn()+ .query_row(+ "SELECT json_extract(config_json,'$.workspacePath') FROM scheduled_tasks WHERE id='task'",+ [],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(task_workspace, canonical_new);+ assert_eq!(+ db.get_project_memory(&new.to_string_lossy())+ .unwrap()+ .content,+ "Keep this context"+ );+ assert!(db+ .get_project_memory(&old.to_string_lossy())+ .unwrap()+ .content+ .is_empty());+ assert_eq!(+ db.kv_get("app", "currentProjectId").unwrap(),+ Some(serde_json::json!(source))+ );+}++#[test]+fn single_root_replacement_refuses_a_non_empty_target_project() {+ let dir = tempfile::tempdir().unwrap();+ let old = dir.path().join("old");+ let new = dir.path().join("new");+ std::fs::create_dir(&old).unwrap();+ std::fs::create_dir(&new).unwrap();+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();+ let group = db+ .create_project_group("Source", &[old.to_string_lossy().into_owned()])+ .unwrap();+ let source = db.ensure_project(&old.to_string_lossy(), false).unwrap();+ let target = db.ensure_project(&new.to_string_lossy(), false).unwrap();+ db.conn()+ .execute(+ "INSERT INTO sessions(id,project_id,created_at,updated_at) VALUES('source-session',?1,1,1)",+ [source],+ )+ .unwrap();+ db.conn()+ .execute(+ "INSERT INTO scheduled_tasks(id,title,prompt,config_json,created_at,updated_at)+ VALUES('target-task','Target','Prompt',json_object('workspacePath',?1),1,1)",+ [format!(+ "{}/",+ crate::db::canonical_project_path(&new.to_string_lossy()).unwrap()+ )],+ )+ .unwrap();+ std::fs::remove_dir(&old).unwrap();++ let error = db+ .update_project_group(+ &group.id,+ "Source",+ &[new.to_string_lossy().into_owned()],+ Some(&new.to_string_lossy()),+ )+ .unwrap_err();+ assert!(error.to_string().contains("non-empty project"));+ assert_eq!(+ db.project_path(source).unwrap(),+ Some(group.primary_path.clone())+ );+ assert_eq!(+ db.project_path(target).unwrap(),+ Some(crate::db::canonical_project_path(&new.to_string_lossy()).unwrap())+ );+ assert_eq!(db.list_projects().unwrap().len(), 2);+ assert_eq!(+ db.list_project_groups()+ .unwrap()+ .into_iter()+ .find(|candidate| candidate.id == group.id)+ .unwrap()+ .primary_path,+ group.primary_path+ );+}++#[test]+fn single_root_replacement_refuses_orphaned_target_memory() {+ let dir = tempfile::tempdir().unwrap();+ let old = dir.path().join("old");+ let new = dir.path().join("new");+ std::fs::create_dir(&old).unwrap();+ std::fs::create_dir(&new).unwrap();+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();+ let group = db+ .create_project_group("Source", &[old.to_string_lossy().into_owned()])+ .unwrap();+ let source = db.ensure_project(&old.to_string_lossy(), false).unwrap();+ let canonical_new = crate::db::canonical_project_path(&new.to_string_lossy()).unwrap();+ db.kv_set(+ "projectMemory",+ &canonical_new,+ &serde_json::json!({"content":"Independent memory"}),+ )+ .unwrap();+ std::fs::remove_dir(&old).unwrap();++ assert!(db+ .update_project_group(+ &group.id,+ "Source",+ &[new.to_string_lossy().into_owned()],+ Some(&new.to_string_lossy()),+ )+ .unwrap_err()+ .to_string()+ .contains("non-empty project"));+ assert_eq!(db.project_path(source).unwrap(), Some(group.primary_path));+ assert_eq!(+ db.get_project_memory(&new.to_string_lossy())+ .unwrap()+ .content,+ "Independent memory"+ );+}++#[test]+fn single_root_replacement_rolls_back_an_empty_target_delete_on_failure() {+ let dir = tempfile::tempdir().unwrap();+ let old = dir.path().join("old");+ let new = dir.path().join("new");+ std::fs::create_dir(&old).unwrap();+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();+ let group = db+ .create_project_group("Source", &[old.to_string_lossy().into_owned()])+ .unwrap();+ let source = db.ensure_project(&old.to_string_lossy(), false).unwrap();+ std::fs::rename(&old, &new).unwrap();+ let target = db.ensure_project(&new.to_string_lossy(), false).unwrap();+ db.conn()+ .execute_batch(&format!(+ "CREATE TRIGGER reject_relocation BEFORE UPDATE OF path ON projects+ WHEN OLD.id={source} BEGIN SELECT RAISE(ABORT,'blocked'); END;"+ ))+ .unwrap();++ assert!(db+ .update_project_group(+ &group.id,+ "Source",+ &[new.to_string_lossy().into_owned()],+ Some(&new.to_string_lossy()),+ )+ .is_err());+ assert!(db.get_project(target).unwrap().is_some());+ assert_eq!(db.project_path(source).unwrap(), Some(group.primary_path));+}+#[test]fn project_group_update_allows_a_root_renamed_away_externally() {// #1869: when a group folder is renamed (or unmounted) outside the app,diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex 2d16e85b4..bb41be500 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -2173,11 +2173,25 @@ async fn handle_request(.map(str::to_string).collect::<Vec<_>>();let primary = params.get("primary").and_then(Value::as_str);- let st = state.lock().await;+ let mut st = state.lock().await;+ let active_group = match st.workspace.path.as_deref() {+ Some(path) => st+ .db+ .project_group_for_path(path)+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?,+ None => None,+ };let group = st.db.update_project_group(group_id, name, &folders, primary).map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;+ if active_group.is_some_and(|current| {+ current.id == group_id+ && current.roots.len() == 1+ && current.primary_path != group.primary_path+ }) {+ st.workspace.set(PathBuf::from(&group.primary_path));+ }Ok(json!({ "group": group }))}"project.group.rename" => {@@ -6541,6 +6555,54 @@ mod tests {assert_eq!(updated["group"]["roots"].as_array().unwrap().len(), 2);}+ #[tokio::test]+ async fn project_group_update_rpc_relocates_the_active_single_root_workspace() {+ let data_dir = tempfile::tempdir().unwrap();+ let old = data_dir.path().join("old");+ let new = data_dir.path().join("new");+ fs::create_dir(&old).unwrap();+ let mut app_state = AppState::open(data_dir.path()).unwrap();+ app_state.handshook = true;+ app_state.workspace.set(&old);+ let state = Arc::new(Mutex::new(app_state));+ let created = handle_request(+ state.clone(),+ "project.group.create",+ json!({ "name": "Movable", "folders": [old] }),+ mpsc::unbounded_channel().0,+ )+ .await+ .unwrap();+ let group_id = created["group"]["id"].as_str().unwrap();+ fs::rename(&old, &new).unwrap();++ handle_request(+ state.clone(),+ "project.group.update",+ json!({+ "groupId": group_id,+ "name": "Movable",+ "folders": [new],+ "primary": new,+ }),+ mpsc::unbounded_channel().0,+ )+ .await+ .unwrap();+ let workspace = handle_request(+ state,+ "workspace.get",+ json!({}),+ mpsc::unbounded_channel().0,+ )+ .await+ .unwrap();+ assert_eq!(+ workspace["workspace"]["path"],+ json!(crate::db::canonical_project_path(&new.to_string_lossy()).unwrap())+ );+ }+#[tokio::test]async fn project_group_update_rpc_switches_the_primary_folder() {let data_dir = tempfile::tempdir().unwrap();diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex d30704340..aab840dd0 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -91,6 +91,13 @@ with sessions is omitted from `detachedPaths` and remains readable as a standalolegacy group; removing a root from group membership never deletes sessions or files.Existing path projects are projected as legacy single-root groups at read time;their path-scoped memory and filesystem instructions remain readable.+Replacing the sole root of a legacy or stored single-root group is an explicit+project relocation, not a detach. The host retains the original project id and+updates its canonical path in the same transaction as the group edit, moves the+old path's `projectMemory` key and bound scheduled-task `workspacePath`, and+absorbs only an empty target project row. Existing chats and scheduled tasks+therefore retain their owner. A target that already owns chats, tasks, or memory+project. Multi-root detachment keeps the existing standalone-project behavior.5. **Plan/Goal checkpoints are immutable host artifacts** with recorded path,hash, and size; the existing approval row also carries execution fields.Startup interruption is the process-epoch fence and no work is replayed.diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.mdindex 1dd79426f..f79725544 100644--- a/docs/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md@@ -286,7 +286,12 @@ type ToolBudgetHealth = {are removed, a `primary` outside `folders` is rejected, roots owned byanother non-legacy group are rejected, and a root with existing chats cannotbe detached. Removed roots are retained as suppressed historical paths rather- than reappearing as standalone legacy groups.+ than reappearing as standalone legacy groups. Replacing the only root of a+ legacy or stored single-root group instead relocates its existing project row:+ the canonical path and path-scoped memory move while the project id, chats,+ scheduled tasks, and group id remain stable. An empty shadow row at the new+ path is absorbed; a target with its own chats, tasks, or memory is rejected,+ and every database change rolls back together on failure.- `project.group.memory.get/set({ groupId, entries })` — reads or normalizesshared group memory using the existing 32 KiB entry limit.- `project.group.instructions.get/set({ groupId, content })` — reads or storesdiff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 3df2c0fef..72afab34e 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -658,8 +658,12 @@ visually distinct from list content.removal of a folder that still owns chats. Every other folder row carries aSet as Primary action that promotes it: the row moves to the top, the Primarytag moves with it, and the host stores the promoted folder as the group's- primary root on save. A remote project keeps its host-owned binding and shows- no promotion action. Background session or run-status updates+ primary root on save. When a single-root project was moved externally, adding+ its replacement, promoting it, and removing the stale row in one save+ relocates the existing project instead of creating a replacement with+ orphaned chats. A non-empty independent project at the replacement path+ rejects the save unchanged. A remote project keeps its host-owned binding and+ shows no promotion action.must preserve unsaved name, folder, and primary edits in the open editor.Git repository as equal filled tiles without strokes (D297); the active sourceuses a deeper tile, not a selected border. A repository URL reuses the clonediff --git a/docs/spec/06-delivery/e2e/tools-and-workspace.md b/docs/spec/06-delivery/e2e/tools-and-workspace.mdindex 690ac46be..e34837722 100644--- a/docs/spec/06-delivery/e2e/tools-and-workspace.md+++ b/docs/spec/06-delivery/e2e/tools-and-workspace.md@@ -560,6 +560,37 @@ journeys cover successful reads, saves and directory browsing.`sidebar-preferences.test.mjs`); rendered scenario Draft, with primarypromotion covered by `node scripts/e2e-project-edit.mjs`+## E2E-PROJECT-relocate-single-root-with-existing-sessions++- **Preconditions**: A legacy or stored single-root local project has an idle+ saved chat, a scheduled task, and project memory. Its directory can be+ renamed outside the app. A second independent project can occupy the+ replacement path for the conflict variant.+- **Steps**: 1) Rename the only project directory outside the app. 2) Open Edit+ project, add the replacement, promote it to Primary, remove the stale row,+ and save once. 3) Reopen the original chat and run a workspace-dependent+ Read or Bash call. 4) Inspect project memory, the scheduled task, the project+ list, and the binding after restart. 5) Repeat with an empty shadow project+ previously opened at the replacement path. 6) Repeat with a non-empty+ independent target project and verify that saving is rejected.+- **Expected**: The original project id and stored group id survive, its path+ becomes the canonical replacement, and the existing chat, scheduled task, and+ path-scoped memory remain available without recreating the session. The old+ workspace call succeeds at the replacement path. An empty shadow row is+ absorbed, leaving one project. A target with its own chats, tasks, or memory+ blocks the operation with both projects and the original group unchanged.+ Multi-root detachment still preserves a removed root's chats as a standalone+ project; no automatic directory-move detection or implicit project merge is+ introduced.+- **Specs linked**: `03-runtime/04-data-storage.md`,+ `03-runtime/06-host-rpc-protocol.md` (Projects),+ `04-ux/08-component-spec.md` (project editor).+- **Acceptance**: C (project and chat interaction), D (workspace identity),+ F (persistence), Quality.+- **Milestone**: M5+- **Status**: Host integration-covered by the four+ `single_root_replacement_*` regressions and the active-workspace RPC regression; full UI scenario Draft+## E2E-048c: Detach a project folder with chats and delete it- **Preconditions**: One retained logical project has a primary folder and an