Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(scheduled): pause bound automations when removing projects

hui4558819eec250d7
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index a58381c16..0350846c9 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -1639,6 +1639,15 @@ async fn handle_request(
let path = crate::db::canonical_project_path(path)
.ok_or_else(|| rpc_err(1002, "path required", "INVALID_PARAMS"))?;
let st = state.lock().await;
+ if crate::scheduled::project::has_running_tasks(&st.db, &path)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
+ {
+ return Err(rpc_err(
+ 1008,
+ "project has running scheduled tasks",
+ "CONFLICT",
+ ));
+ }
// A path that belongs to a multi-folder project group must stay put:
// deleting one root would orphan the rest of the group, so callers
// remove the folder from the group first. A single-folder stored
@@ -1674,6 +1683,8 @@ async fn handle_request(
return Err(rpc_err(1008, "project has running sessions", "CONFLICT"));
}
}
+ crate::scheduled::project::pause(&st.db, &path)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
let mut sessions_removed = 0;
for id in &session_ids {
if sessions::delete_session(&st.db, id)
diff --git a/crates/host-core/src/rpc/scheduled_project_tests.rs b/crates/host-core/src/rpc/scheduled_project_tests.rs
new file mode 100644
index 000000000..999656992
--- /dev/null
+++ b/crates/host-core/src/rpc/scheduled_project_tests.rs
@@ -0,0 +1,108 @@
+use super::*;
+use std::sync::Arc;
+use tokio::sync::{mpsc, Mutex};
+
+#[tokio::test]
+async fn removal_pauses_only_bound_tasks_and_preserves_definitions_and_history() {
+ let dir = tempfile::tempdir().unwrap();
+ let a = tempfile::tempdir().unwrap();
+ let b = tempfile::tempdir().unwrap();
+ let mut st = AppState::open(dir.path()).unwrap();
+ st.handshook = true;
+ let path = st.workspace.set(a.path()).path;
+ let mut ids = Vec::new();
+ for cadence in ["manual", "hourly", "daily", "weekly"] {
+ let task=handle(&st,"scheduled.create",json!({"title":"Keep title","prompt":"Keep prompt","cadence":cadence,"schedule":if cadence=="manual"{Value::Null}else{json!({"hour":9,"minute":30,"weekday":0})}})).unwrap()["task"].clone();
+ ids.push(task["id"].as_str().unwrap().to_string());
+ }
+ let run = handle(&st, "scheduled.run", json!({"id":ids[0]})).unwrap();
+ handle(
+ &st,
+ "scheduled.finishRun",
+ json!({"runId":run["runId"],"status":"completed"}),
+ )
+ .unwrap();
+ st.workspace.set(b.path());
+ let unrelated = handle(
+ &st,
+ "scheduled.create",
+ json!({"prompt":"Other","cadence":"hourly","schedule":{"hour":0,"minute":0,"weekday":0}}),
+ )
+ .unwrap()["task"]
+ .clone();
+ let state = Arc::new(Mutex::new(st));
+ let deleted = super::super::handle_request(
+ state.clone(),
+ "projects.remove",
+ json!({"path":path}),
+ mpsc::unbounded_channel().0,
+ )
+ .await
+ .unwrap();
+ assert_eq!(deleted["removed"], true);
+ drop(state);
+ let st = AppState::open(dir.path()).unwrap();
+ for id in &ids {
+ let task = scheduled::get_task(&st.db, id).unwrap().unwrap();
+ assert!(!task.enabled);
+ assert_eq!(task.title, "Keep title");
+ assert_eq!(task.prompt, "Keep prompt");
+ assert_eq!(
+ task.workspace_path
+ .as_deref()
+ .and_then(crate::db::canonical_project_path),
+ crate::db::canonical_project_path(&path)
+ );
+ let rejected = handle(&st, "scheduled.run", json!({"id":id,"automatic":true})).unwrap_err();
+ assert_eq!(rejected.data.unwrap()["errorCode"], "SCHEDULE_NOT_DUE");
+ }
+ assert!(
+ scheduled::get_task(&st.db, unrelated["id"].as_str().unwrap())
+ .unwrap()
+ .unwrap()
+ .enabled
+ );
+ let history = scheduled::list_runs(&st.db, Some(&ids[0]), 100).unwrap();
+ assert_eq!(history.len(), 1);
+ assert_eq!(history[0].status, "completed");
+ assert!(history[0].session_id.is_none());
+}
+
+#[tokio::test]
+async fn admitted_scheduled_run_blocks_removal_before_a_turn_is_opened() {
+ let dir = tempfile::tempdir().unwrap();
+ let project = tempfile::tempdir().unwrap();
+ let mut st = AppState::open(dir.path()).unwrap();
+ st.handshook = true;
+ let path = st.workspace.set(project.path()).path;
+ let task = handle(
+ &st,
+ "scheduled.create",
+ json!({"prompt":"Review","cadence":"manual","schedule":null}),
+ )
+ .unwrap()["task"]
+ .clone();
+ let run = handle(&st, "scheduled.run", json!({"id":task["id"]})).unwrap();
+ let state = Arc::new(Mutex::new(st));
+ let rejected = super::super::handle_request(
+ state.clone(),
+ "projects.remove",
+ json!({"path":path}),
+ mpsc::unbounded_channel().0,
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(rejected.data.unwrap()["errorCode"], "CONFLICT");
+ let st = state.lock().await;
+ assert!(
+ sessions::get_session(&st.db, run["sessionId"].as_str().unwrap())
+ .unwrap()
+ .is_some()
+ );
+ assert!(
+ scheduled::get_task(&st.db, task["id"].as_str().unwrap())
+ .unwrap()
+ .unwrap()
+ .enabled
+ );
+}
diff --git a/crates/host-core/src/rpc/scheduled_rpc.rs b/crates/host-core/src/rpc/scheduled_rpc.rs
index 3b47a7fef..fab53ad08 100644
--- a/crates/host-core/src/rpc/scheduled_rpc.rs
+++ b/crates/host-core/src/rpc/scheduled_rpc.rs
@@ -1,6 +1,10 @@
use super::{json, plan_rpc_err, rpc_err, AppState, JsonRpcError, Value};
use crate::{scheduled, sessions};
+#[cfg(test)]
+#[path = "scheduled_project_tests.rs"]
+mod project_tests;
+
pub(super) fn handle(st: &AppState, method: &str, params: Value) -> Result<Value, JsonRpcError> {
handle_in_workspace(
st,
@@ -233,6 +237,70 @@ fn validate_schedule_input(params: &Value) -> Result<(), JsonRpcError> {
mod tests {
use super::*;
+ #[tokio::test]
+ async fn review_deleted_project_is_not_recreated_by_automatic_task() {
+ use std::sync::Arc;
+ use tokio::sync::{mpsc, Mutex};
+ let dir = tempfile::tempdir().unwrap();
+ let project = tempfile::tempdir().unwrap();
+ let mut st = AppState::open(dir.path()).unwrap();
+ st.handshook = true;
+ let path = st.workspace.set(project.path()).path;
+ sessions::create_session(
+ &st.db,
+ None,
+ Some("agent".into()),
+ None,
+ None,
+ Some(path.clone()),
+ )
+ .unwrap();
+ let task = handle(
+ &st,
+ "scheduled.create",
+ json!({
+ "title":"Review", "prompt":"Review project", "cadence":"hourly",
+ "schedule":{"hour":0,"minute":0,"weekday":0}
+ }),
+ )
+ .unwrap()["task"]
+ .clone();
+ let state = Arc::new(Mutex::new(st));
+ let removed = super::super::handle_request(
+ state.clone(),
+ "projects.remove",
+ json!({"path":path}),
+ mpsc::unbounded_channel().0,
+ )
+ .await
+ .unwrap();
+ assert_eq!(removed["removed"], true);
+ let st = state.lock().await;
+ let count = || {
+ st.db
+ .conn()
+ .query_row("SELECT COUNT(*) FROM projects", [], |row| {
+ row.get::<_, i64>(0)
+ })
+ .unwrap()
+ };
+ assert_eq!(count(), 0);
+ st.db.conn().execute(
+ "UPDATE scheduled_tasks SET config_json = json_set(config_json, '$.nextRunAt', ?1) WHERE id = ?2",
+ rusqlite::params![crate::db::now_ms(), task["id"].as_str().unwrap()],
+ ).unwrap();
+ let launched = handle(
+ &st,
+ "scheduled.run",
+ json!({"id":task["id"],"automatic":true}),
+ );
+ assert_eq!(
+ count(),
+ 0,
+ "Automatic admission resurrected the deleted project: {launched:?}"
+ );
+ }
+
#[test]
fn manual_task_keeps_saved_workspace_across_run_edit_and_restart() {
for project_bound in [true, false] {
diff --git a/crates/host-core/src/scheduled.rs b/crates/host-core/src/scheduled.rs
index 2b83a446b..287e2402f 100644
--- a/crates/host-core/src/scheduled.rs
+++ b/crates/host-core/src/scheduled.rs
@@ -8,6 +8,7 @@ use crate::db::{ms_to_ts, now_ms, ts_to_ms, Database};
use crate::sessions;
pub mod automation;
+pub mod project;
pub mod timing;
/// Wire format matches the legacy Electron `scheduled-tasks.json` records so
diff --git a/crates/host-core/src/scheduled/project.rs b/crates/host-core/src/scheduled/project.rs
new file mode 100644
index 000000000..e41364a13
--- /dev/null
+++ b/crates/host-core/src/scheduled/project.rs
@@ -0,0 +1,41 @@
+use crate::db::{canonical_project_path, now_ms, Database};
+use anyhow::Result;
+
+fn bound_tasks(db: &Database, path: &str) -> Result<Vec<super::ScheduledTask>> {
+ let path = canonical_project_path(path);
+ Ok(super::list_tasks(db)?
+ .into_iter()
+ .filter(|task| {
+ path.is_some()
+ && task
+ .workspace_path
+ .as_deref()
+ .and_then(canonical_project_path)
+ == path
+ })
+ .collect())
+}
+
+/// Admission owns a task before its session has opened a turn.
+pub fn has_running_tasks(db: &Database, path: &str) -> Result<bool> {
+ for task in bound_tasks(db, path)? {
+ if super::automation::running(db, &task.id)? {
+ return Ok(true);
+ }
+ }
+ Ok(false)
+}
+
+/// Keep definitions and history, but require explicit user action to run again.
+pub fn pause(db: &Database, path: &str) -> Result<()> {
+ let tasks = bound_tasks(db, path)?;
+ let transaction = db.conn().unchecked_transaction()?;
+ for task in tasks {
+ transaction.execute(
+ "UPDATE scheduled_tasks SET enabled = 0, updated_at = ?1 WHERE id = ?2",
+ rusqlite::params![now_ms(), task.id],
+ )?;
+ }
+ transaction.commit()?;
+ Ok(())
+}
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index 7be3e8e3a..f10575b2d 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -1211,3 +1211,7 @@ Create requires title, prompt and cadence; automatic daily/weekly tasks require
a schedule. Update takes an existing ID and partial fields, preserving all
unspecified configuration. Exact local times remain supported despite the
UI's four period presets. No new DB schema or transport is introduced.
+
+### Scheduled tasks: project removal and automations
+
+Removing a project pauses its bound scheduled tasks without deleting their definitions, schedule, workspace binding or run history. Session references in history may become null when the project's conversations are removed. Already admitted task runs block removal even before a conversation turn starts. Tasks belonging to other projects and unbound legacy tasks are unaffected. Explicit resume or Run now may recreate a project from the preserved path; automatic polling cannot do so while paused.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index e6fbc9513..db65e17db 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -14402,3 +14402,9 @@ the latest destination. These assertions measure work counts, not device FPS.
`fork_preserves_referenced_pasted_files_independently` and `sessions::fork_files`
cover ownership, deletion, repeated/bounded forks, retained checkpoint paths,
expired inputs, rollback, and symlink rejection.
+
+### E2E-SCHEDULED-project-removal
+
+- **Scenario:** Project removal and automations.
+- **Expected:** Removing a project pauses its bound scheduled tasks without deleting their definitions, schedule, workspace binding or run history. Session references in history may become null when the project's conversations are removed. Already admitted task runs block removal even before a conversation turn starts. Tasks belonging to other projects and unbound legacy tasks are unaffected. Explicit resume or Run now may recreate a project from the preserved path; automatic polling cannot do so while paused.
+- **Automation:** `node --experimental-strip-types scripts/e2e-scheduled-project-removal.mjs` uses an isolated real Host and SQLite profile. Inference is not sent to a live provider.
diff --git a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
index 9e2dc820d..ed6e41d6c 100644
--- a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
@@ -986,3 +986,10 @@ Host 重新检查会话的持久化模式,按调用会话的项目限制访问
提示词、非法时间和星期在写入前拒绝;不能删除运行中的任务。创建需 title、prompt、cadence;
每天/每周自动任务需 schedule。修改使用已存在的 ID 并保留未指定字段。界面虽只提供四个
时段,工具仍支持具体本地时间。不新增数据库 schema 或传输协议。
+
+### 定时任务:删除项目与自动任务
+
+删除项目时暂停与其绑定的定时任务,但保留任务定义、schedule、工作区绑定和运行历史。
+删除项目会话后,历史中的会话引用可能变为 null。已经准入的任务即使尚未开始会话
+轮次,也会阻止项目删除。其他项目的任务和未绑定的旧任务不受影响。用户显式恢复
+任务或点击 Run now 时可以从保留路径重新创建项目;暂停状态下的自动轮询不会这样做。
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 2f38aa1b0..7e49faa21 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -8563,3 +8563,12 @@ the latest destination. These assertions measure work counts, not device FPS.
- **规格**:`04-ux/08-component-spec.md`、`04-ux/09-interaction-patterns.md`。
- **验收 / 里程碑**:C、Quality / M6+。
- **状态**:组件与状态层用户路径由 `queue-pending-actions.test.mjs` 覆盖。
+
+### E2E-SCHEDULED-project-removal
+
+- **场景**:删除项目与自动任务。
+- **预期**:删除项目会暂停其绑定任务,并保留任务定义、schedule、工作区绑定和
+ 运行历史;已准入的任务会阻止删除。其他项目和未绑定旧任务不受影响。用户显式
+ 恢复或 Run now 可以重新创建项目,暂停状态下的自动轮询不会这样做。
+- **自动化**:`node --experimental-strip-types scripts/e2e-scheduled-project-removal.mjs`
+ 使用隔离的真实 Host 与 SQLite 配置,不向真实提供商发送推理请求。
diff --git a/scripts/e2e-scheduled-project-removal.mjs b/scripts/e2e-scheduled-project-removal.mjs
new file mode 100644
index 000000000..f29c5193b
--- /dev/null
+++ b/scripts/e2e-scheduled-project-removal.mjs
@@ -0,0 +1,25 @@
+import assert from "node:assert/strict";
+import { mkdtemp,mkdir } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { Host, resolveHostBinary } from "./e2e/host.mjs";
+const root=await mkdtemp(join(tmpdir(),"pi-scheduled-project-"));
+const project=join(root,"project");await mkdir(project);
+const host=new Host(resolveHostBinary(),join(root,"data"));
+try {
+ await host.start();await host.call("workspace.set",{path:project});
+ const {task}=await host.call("scheduled.create",{title:"Review",prompt:"Reply OK",cadence:"hourly",schedule:{hour:0,minute:0,weekday:0}});
+ const run=await host.call("scheduled.run",{id:task.id});
+ await assert.rejects(host.call("projects.remove",{path:project}),error=>error.errorCode==="CONFLICT");
+ await host.call("scheduled.finishRun",{runId:run.runId,status:"completed"});
+ assert.equal((await host.call("projects.remove",{path:project})).removed,true);
+ await host.restart();const saved=(await host.call("scheduled.list")).tasks.find(item=>item.id===task.id);
+ assert.equal(saved.enabled,false);assert.equal(saved.workspacePath,task.workspacePath);assert.equal(saved.prompt,task.prompt);
+ await host.call("scheduled.update",{id:task.id,configJson:{nextRunAt:Date.now()}});
+ assert.ok(!(await host.call("scheduled.due")).ids.includes(task.id));
+ await assert.rejects(host.call("scheduled.run",{id:task.id,automatic:true}),error=>error.errorCode==="SCHEDULE_NOT_DUE");
+ const {runs}=await host.call("scheduled.listRuns",{taskId:task.id});assert.equal(runs[0].status,"completed");
+ await host.call("scheduled.update",{id:task.id,enabled:true});
+ assert.ok(Date.parse((await host.call("scheduled.list")).tasks.find(item=>item.id===task.id).nextRunAt)>Date.now());
+ console.log("PASS admission blocks project removal; completed task survives paused with history; explicit resume rearms future only");
+} finally {await host.stop();}