Skip to content

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

fix(scheduled): dispatch due tasks without serial startup waits

hui455c3aa74e3bc66
diff --git a/apps/desktop/electron/main/runtime/scheduled-runner.ts b/apps/desktop/electron/main/runtime/scheduled-runner.ts
index 13e973eee..944642987 100644
--- a/apps/desktop/electron/main/runtime/scheduled-runner.ts
+++ b/apps/desktop/electron/main/runtime/scheduled-runner.ts
@@ -40,6 +40,7 @@ export function createScheduledRunner(options: {
let stopped = false;
let polling = false;
let timer: ReturnType<typeof setInterval> | undefined;
+ const dispatches = new Map<string, { host: Host }>();
const tick = async () => {
if (stopped || polling) return;
const host = options.getHost();
@@ -49,11 +50,22 @@ export function createScheduledRunner(options: {
const { ids } = await host.call<{ ids: string[] }>("scheduled.due");
for (const id of ids) {
if (stopped || options.getHost() !== host) break;
- try {
- await options.execute(id);
- } catch (error) {
- options.report(error);
- }
+ if (dispatches.get(id)?.host === host) continue;
+ const owner = { host };
+ dispatches.set(id, owner);
+ // Polling owns admission requests, not the duration of prompt setup.
+ // Host remains authoritative for enabled/due/overlap checks. Keep a
+ // local owner until setup settles so another poll cannot dispatch the
+ // same task while its admission request is still in flight.
+ void (async () => {
+ try {
+ await options.execute(id);
+ } catch (error) {
+ options.report(error);
+ } finally {
+ if (dispatches.get(id) === owner) dispatches.delete(id);
+ }
+ })();
}
} catch (error) {
options.report(error);
diff --git a/apps/desktop/test/scheduled-runner.test.mjs b/apps/desktop/test/scheduled-runner.test.mjs
index 2637e8f5d..f2fcc1566 100644
--- a/apps/desktop/test/scheduled-runner.test.mjs
+++ b/apps/desktop/test/scheduled-runner.test.mjs
@@ -6,6 +6,57 @@ const { createScheduledRunner, executeScheduledTask } = await import(
"../electron/main/runtime/scheduled-runner.ts"
);
+test("slow dispatch does not hold later tasks or subsequent polls", async () => {
+ let release;
+ const blocked = new Promise((resolve) => { release = resolve; });
+ let enter;
+ const entered = new Promise((resolve) => { enter = resolve; });
+ const launched = [];
+ let ids = ["slow", "other"];
+ const host = { async call() { return { ids }; } };
+ const runner = createScheduledRunner({getHost:()=>host, report:(error)=>{throw error;},
+ execute:async(id)=>{launched.push(id);if(id==="slow"){enter();await blocked;}}});
+ const first = runner.tick();
+ await entered;
+ // Drain the promise continuations, without releasing the slow preparation.
+ await new Promise((resolve)=>setImmediate(resolve));
+ const beforeRelease = [...launched];
+ ids = ["slow", "third"];
+ await runner.tick();
+ await new Promise((resolve)=>setImmediate(resolve));
+ const afterPoll = [...launched];
+ runner.stop(); release(); await first;
+ assert.deepEqual(beforeRelease,["slow","other"]);
+ assert.deepEqual(afterPoll,["slow","other","third"]);
+});
+
+test("a replacement host owns its dispatch even when an old setup settles", async () => {
+ const firstHost={async call(){return {ids:["task","task"]};}};
+ const secondHost={async call(){return {ids:["task","task"]};}};
+ let host=firstHost;
+ const releases=[];const starts=[];
+ const runner=createScheduledRunner({getHost:()=>host,report:()=>{},execute:(id)=>{
+ starts.push({host,id});return new Promise(resolve=>releases.push(resolve));
+ }});
+ await runner.tick();assert.equal(starts.length,1);
+ host=secondHost;await runner.tick();assert.equal(starts.length,2);
+ releases[0]();await new Promise(resolve=>setImmediate(resolve));
+ await runner.tick();assert.equal(starts.length,2,"old cleanup must not clear replacement owner");
+ runner.stop();releases[1]();await new Promise(resolve=>setImmediate(resolve));
+ await runner.tick();assert.equal(starts.length,2);
+});
+
+test("a rejected startup remains observable and releases its local owner", async () => {
+ const host={async call(){return {ids:["task"]};}};
+ let attempts=0;const errors=[];
+ const runner=createScheduledRunner({getHost:()=>host,report:error=>errors.push(error.message),execute:async()=>{
+ attempts++;throw new Error("setup failed");
+ }});
+ await runner.tick();await new Promise(resolve=>setImmediate(resolve));
+ await runner.tick();await new Promise(resolve=>setImmediate(resolve));runner.stop();
+ assert.equal(attempts,2);assert.deepEqual(errors,["setup failed","setup failed"]);
+});
+
test("scheduled execution launches the durable session through the prompt boundary", async () => {
const calls = [];
const runs = new Map();
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index 7be3e8e3a..580fac239 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: independent task dispatch
+
+The Electron runner admits independent due tasks without awaiting another task's prompt setup. Local in-flight ownership is keyed by task ID and Host instance until setup settles; Host remains authoritative for enabled, due and overlap checks. A replaced Host's completion cannot clear its successor's local ownership. Stop prevents new polls; admitted work keeps the existing execution/failure lifecycle. Failures remain observable and the 90-second late policy is unchanged.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index e6fbc9513..a539d5734 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-dispatch
+
+- **Scenario:** Independent task dispatch.
+- **Expected:** The Electron runner admits independent due tasks without awaiting another task's prompt setup. Local in-flight ownership is keyed by task ID and Host instance until setup settles; Host remains authoritative for enabled, due and overlap checks. A replaced Host's completion cannot clear its successor's local ownership. Stop prevents new polls; admitted work keeps the existing execution/failure lifecycle. Failures remain observable and the 90-second late policy is unchanged.
+- **Automation:** `node --experimental-strip-types scripts/e2e-scheduled-dispatch.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..8d22b17c2 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,11 @@ Host 重新检查会话的持久化模式,按调用会话的项目限制访问
提示词、非法时间和星期在写入前拒绝;不能删除运行中的任务。创建需 title、prompt、cadence;
每天/每周自动任务需 schedule。修改使用已存在的 ID 并保留未指定字段。界面虽只提供四个
时段,工具仍支持具体本地时间。不新增数据库 schema 或传输协议。
+
+### 定时任务:独立分发到期任务
+
+Electron runner 无需等待其他任务的提示词准备完成,即可准入彼此独立的到期任务。
+本地执行中所有权按任务 ID 和 Host 实例记录,直到准备结束;enabled、due 和重叠
+检查仍由 Host 决定。旧 Host 的完成不会清除替代 Host 的所有权。停止 runner
+只阻止新轮询,已准入任务继续使用现有执行和失败生命周期;错误仍可观察,迟到
+90 秒的规则保持不变。
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..b4a16aa11 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-dispatch
+
+- **场景**:独立分发到期任务。
+- **预期**:Electron runner 无需等待其他任务的提示词准备即可准入彼此独立的
+ 到期任务;本地所有权按任务 ID 和 Host 实例保留,Host 继续负责 enabled、
+ due 和重叠检查。停止只阻止新轮询,错误仍可观察,迟到 90 秒的规则不变。
+- **自动化**:`node --experimental-strip-types scripts/e2e-scheduled-dispatch.mjs`
+ 使用隔离的真实 Host 与 SQLite 配置,不向真实提供商发送推理请求。
diff --git a/scripts/e2e-scheduled-dispatch.mjs b/scripts/e2e-scheduled-dispatch.mjs
new file mode 100644
index 000000000..a52968187
--- /dev/null
+++ b/scripts/e2e-scheduled-dispatch.mjs
@@ -0,0 +1,76 @@
+// Real Host admission and persistence; inference is held at the prompt boundary.
+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";
+import { createScheduledRunner, executeScheduledTask } from "../apps/desktop/electron/main/runtime/scheduled-runner.ts";
+
+const root = await mkdtemp(join(tmpdir(), "pi-scheduled-dispatch-"));
+const project = join(root, "project");
+await mkdir(project);
+const host = new Host(resolveHostBinary(), join(root, "data"));
+const held = Promise.withResolvers();
+const bothStarted = Promise.withResolvers();
+const launches = [], executions = [], errors = [];
+let runner;
+let deadline;
+try {
+ await host.start();
+ await host.call("workspace.set", { path: project });
+ const tasks = [];
+ for (const title of ["First", "Second"]) {
+ const { task } = await host.call("scheduled.create", {
+ title, prompt: "Reply OK", cadence: "hourly",
+ schedule: { hour: 0, minute: 0, weekday: 0 },
+ });
+ // Controlled due instant in an isolated profile, without wall-clock sleeps.
+ await host.call("scheduled.update", { id: task.id, configJson: { nextRunAt: Date.now() } });
+ tasks.push(task);
+ }
+ runner = createScheduledRunner({
+ getHost: () => host,
+ report: error => errors.push(error),
+ execute: id => {
+ const execution = executeScheduledTask({
+ host, id, automatic: true, runs: new Map(), isCurrent: () => true,
+ prompt: async sessionId => {
+ launches.push({ id, sessionId });
+ if (launches.length === 2) bothStarted.resolve();
+ if (launches.length === 1) await held.promise;
+ },
+ });
+ executions.push(execution);
+ return execution;
+ },
+ });
+ const tick = runner.tick();
+ await Promise.race([
+ bothStarted.promise,
+ new Promise((_, reject) => { deadline = setTimeout(() => reject(new Error("Second task blocked by first prompt setup")), 5000); }),
+ ]);
+ clearTimeout(deadline);
+ await tick;
+ await runner.tick();
+ assert.equal(launches.length, 2);
+ for (const task of tasks) {
+ assert.equal((await host.call("scheduled.listRuns", { taskId: task.id })).runs.length, 1);
+ }
+ held.resolve();
+ for (const run of await Promise.all(executions)) {
+ await host.call("scheduled.finishRun", { runId: run.runId, status: "completed" });
+ }
+ runner.stop();
+ assert.deepEqual(errors, []);
+ await host.restart();
+ for (const task of tasks) {
+ assert.equal((await host.call("scheduled.listRuns", { taskId: task.id })).runs[0].status, "completed");
+ }
+ console.log("PASS independent admission, overlap prevention, stop, durable completed runs after restart");
+} finally {
+ clearTimeout(deadline);
+ runner?.stop();
+ held.resolve();
+ await Promise.allSettled(executions);
+ await host.stop();
+}