Skip to content

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

feat(scheduled): dispatch local automations and persist run history

Jackb78357930e88
diff --git a/apps/desktop/electron/main/bootstrap/startup.ts b/apps/desktop/electron/main/bootstrap/startup.ts
index ef50c461c..477f187c3 100644
--- a/apps/desktop/electron/main/bootstrap/startup.ts
+++ b/apps/desktop/electron/main/bootstrap/startup.ts
@@ -1,4 +1,5 @@
import { app, BrowserWindow, crashReporter, Menu, safeStorage } from "electron";
+import { createScheduledRunner } from "../runtime/scheduled-runner";
import {
APP_NAME,
APP_VERSION,
@@ -285,6 +286,13 @@ export function registerApplicationStartup(deps: StartupDependencies): void {
});
}
if (!bootError) planUiProbe.install();
+ const scheduledRunner = createScheduledRunner({
+ getHost,
+ execute: (id) => invokeIpc(IPC.invoke.scheduledExecute, [id, true]),
+ report: (error) => logger.app("runtime", "warn", "scheduled task dispatch failed", { data: String(error) }),
+ });
+ scheduledRunner.start();
+ app.once("before-quit", () => scheduledRunner.stop());
if (!bootError && state.agentHostBridge) {
// Restore the persisted turn queue now that host-core answers. Restored
// entries stay held until a controller attaches (D375).
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.ts
index 60b355588..472cc63e7 100644
--- a/apps/desktop/electron/main/index.ts
+++ b/apps/desktop/electron/main/index.ts
@@ -111,7 +111,6 @@ import {
} from "./ipc/composer-ipc";
import { registerWindowIpc } from "./ipc/window-ipc";
import { registerPullsIpc } from "./ipc/pulls-ipc";
-import { registerScheduledIpc } from "./ipc/scheduled-ipc";
import { registerAgentIpc } from "./ipc/agent-ipc";
import { registerIpcHandlers } from "./ipc/register";
import {
@@ -1302,6 +1301,7 @@ function registerIpc() {
markMenuRendererReady,
executeNativeMenuAction,
scheduledRunsBySession,
+ isQuitting: () => quitting,
isDevelopmentBuild,
browserHost,
clipboardHistory,
diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.ts
index c937156fa..9859ef529 100644
--- a/apps/desktop/electron/main/ipc/register.ts
+++ b/apps/desktop/electron/main/ipc/register.ts
@@ -34,6 +34,7 @@ import type { IpcRegistrar } from "./types";
import type { createTraySessions } from "../tray-sessions";
export type RegisterIpcDependencies = {
+ isQuitting: () => boolean;
ipcMain: IpcMain;
getMainWindow: () => BrowserWindow | null;
getHost: () => HostProcess | null;
@@ -297,6 +298,12 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
registrar,
getHost,
scheduledRunsBySession,
+ isQuitting: dependencies.isQuitting,
+ invoke: async (channel, args) => {
+ const handler = ipcHandlers.get(channel);
+ if (!handler) throw new Error("scheduled prompt handler unavailable");
+ return handler(...args);
+ },
});
registerWorkspaceIpc({
registrar,
diff --git a/apps/desktop/electron/main/ipc/scheduled-ipc.ts b/apps/desktop/electron/main/ipc/scheduled-ipc.ts
index 7dd077bff..e4b4d2aea 100644
--- a/apps/desktop/electron/main/ipc/scheduled-ipc.ts
+++ b/apps/desktop/electron/main/ipc/scheduled-ipc.ts
@@ -1,18 +1,38 @@
import { IPC } from "@pi-desktop/shared";
import type { HostProcess } from "../host-process";
import type { IpcRegistrar } from "./types";
+import { executeScheduledTask } from "../runtime/scheduled-runner";
export type ScheduledIpcDependencies = {
registrar: IpcRegistrar;
getHost: () => HostProcess | null;
scheduledRunsBySession: Map<string, string>;
+ invoke: (channel: string, args: readonly unknown[]) => Promise<unknown>;
+ isQuitting: () => boolean;
};
export function registerScheduledIpc({
registrar,
getHost,
scheduledRunsBySession,
+ invoke,
+ isQuitting,
}: ScheduledIpcDependencies): void {
+ registrar.handle(IPC.invoke.scheduledListRuns, async () => {
+ const host = getHost();
+ if (!host) throw new Error("host unavailable");
+ return host.call("scheduled.listRuns", { limit: 100 });
+ });
+ registrar.handle(IPC.invoke.scheduledExecute, async (id: string, automatic = false) => {
+ if (typeof id !== "string" || typeof automatic !== "boolean") throw new Error("invalid task request");
+ const host = getHost();
+ if (!host) throw new Error("host unavailable");
+ return executeScheduledTask({
+ host, id, automatic, runs: scheduledRunsBySession,
+ isCurrent: () => !isQuitting() && getHost() === host,
+ prompt: (sessionId, content) => invoke(IPC.invoke.agentPrompt, [{ sessionId, content }]),
+ });
+ });
const handle = (channel: string, fn: (...args: any[]) => Promise<any>) => {
registrar.handle(channel, async (...args) => fn(getHost(), ...args));
};
diff --git a/apps/desktop/electron/main/runtime/scheduled-runner.ts b/apps/desktop/electron/main/runtime/scheduled-runner.ts
new file mode 100644
index 000000000..13e973eee
--- /dev/null
+++ b/apps/desktop/electron/main/runtime/scheduled-runner.ts
@@ -0,0 +1,78 @@
+type Host = { call<T>(method: string, params?: Record<string, unknown>): Promise<T> };
+export type ScheduledLaunch = { sessionId: string; prompt: string; runId: string };
+
+/** Runs through the same prompt entry point as an interactive desktop turn. */
+export async function executeScheduledTask(options: {
+ host: Host;
+ isCurrent: () => boolean;
+ id: string;
+ automatic: boolean;
+ runs: Map<string, string>;
+ prompt: (sessionId: string, content: string) => Promise<unknown>;
+}): Promise<ScheduledLaunch> {
+ const { host, id, automatic, runs, prompt, isCurrent } = options;
+ const launch = await host.call<ScheduledLaunch>("scheduled.run", { id, automatic });
+ try {
+ if (!isCurrent()) throw new Error("scheduled runtime stopped");
+ runs.set(launch.sessionId, launch.runId);
+ await prompt(launch.sessionId, launch.prompt);
+ return launch;
+ } catch (error) {
+ if (runs.get(launch.sessionId) === launch.runId) runs.delete(launch.sessionId);
+ try {
+ await host.call("scheduled.finishRun", {
+ runId: launch.runId,
+ status: "error",
+ errorCode: "SCHEDULE_DISPATCH_FAILED",
+ });
+ } catch (persistenceError) {
+ throw new AggregateError([error, persistenceError], "Scheduled dispatch and failure recording both failed");
+ }
+ throw error;
+ }
+}
+
+export function createScheduledRunner(options: {
+ getHost: () => Host | null;
+ execute: (id: string) => Promise<unknown>;
+ report: (error: unknown) => void;
+}) {
+ let stopped = false;
+ let polling = false;
+ let timer: ReturnType<typeof setInterval> | undefined;
+ const tick = async () => {
+ if (stopped || polling) return;
+ const host = options.getHost();
+ if (!host) return;
+ polling = true;
+ try {
+ 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);
+ }
+ }
+ } catch (error) {
+ options.report(error);
+ } finally {
+ polling = false;
+ }
+ };
+ return {
+ tick,
+ start() {
+ if (timer || stopped) return;
+ timer = setInterval(() => void tick(), 30_000);
+ timer.unref();
+ void tick();
+ },
+ stop() {
+ stopped = true;
+ if (timer) clearInterval(timer);
+ timer = undefined;
+ },
+ };
+}
diff --git a/apps/desktop/electron/main/user-login-path.ts b/apps/desktop/electron/main/user-login-path.ts
index c3912f918..a5e7fc29d 100644
--- a/apps/desktop/electron/main/user-login-path.ts
+++ b/apps/desktop/electron/main/user-login-path.ts
@@ -25,7 +25,7 @@ export function resetUserLoginPathCacheForTests(): void {
function defaultProbe(): string | undefined {
if (process.platform === "win32") return undefined;
const shell = [process.env.SHELL, "/bin/zsh", "/bin/bash", "/bin/sh"].find(
- (candidate): candidate is string => Boolean(candidate) && existsSync(candidate),
+ (candidate): candidate is string => !!candidate && existsSync(candidate),
);
if (!shell) return undefined;
try {
@@ -88,4 +88,3 @@ export function userLookupPath(
if (process.platform === "win32") return inherited;
return mergePathParts(probedLoginPath(probe), wellKnownUserBinDirs().join(delimiter), inherited);
}
-
diff --git a/apps/desktop/test/scheduled-runner.test.mjs b/apps/desktop/test/scheduled-runner.test.mjs
new file mode 100644
index 000000000..2637e8f5d
--- /dev/null
+++ b/apps/desktop/test/scheduled-runner.test.mjs
@@ -0,0 +1,145 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { register } from "node:module";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { createScheduledRunner, executeScheduledTask } = await import(
+ "../electron/main/runtime/scheduled-runner.ts"
+);
+
+test("scheduled execution launches the durable session through the prompt boundary", async () => {
+ const calls = [];
+ const runs = new Map();
+ const host = {
+ async call(method, params) {
+ calls.push([method, params]);
+ return { sessionId: "session", runId: "run", prompt: "Inspect project" };
+ },
+ };
+ const result = await executeScheduledTask({
+ host,
+ id: "task",
+ automatic: true,
+ runs,
+ isCurrent: () => true,
+ prompt: async (sessionId, content) => {
+ assert.equal(runs.get(sessionId), "run");
+ assert.equal(content, "Inspect project");
+ },
+ });
+ assert.equal(result.sessionId, "session");
+ assert.deepEqual(calls, [["scheduled.run", { id: "task", automatic: true }]]);
+});
+
+test("dispatch failure is recorded and cannot leave an overlapping active run", async () => {
+ const calls = [];
+ const runs = new Map();
+ const host = {
+ async call(method, params) {
+ calls.push([method, params]);
+ return { sessionId: "session", runId: "run", prompt: "Inspect" };
+ },
+ };
+ await assert.rejects(
+ executeScheduledTask({
+ host,
+ id: "task",
+ automatic: false,
+ runs,
+ isCurrent: () => true,
+ prompt: async () => {
+ throw new Error("provider unavailable");
+ },
+ }),
+ /provider unavailable/,
+ );
+ assert.equal(runs.size, 0);
+ assert.deepEqual(calls.at(-1), [
+ "scheduled.finishRun",
+ { runId: "run", status: "error", errorCode: "SCHEDULE_DISPATCH_FAILED" },
+ ]);
+});
+
+test("a stale host cannot launch into a replacement runtime", async () => {
+ let prompted = false;
+ const host = {
+ async call() {
+ return { sessionId: "session", runId: "run", prompt: "Inspect" };
+ },
+ };
+ await assert.rejects(
+ executeScheduledTask({
+ host,
+ id: "task",
+ automatic: true,
+ runs: new Map(),
+ isCurrent: () => false,
+ prompt: async () => {
+ prompted = true;
+ },
+ }),
+ /stopped/,
+ );
+ assert.equal(prompted, false);
+});
+
+test("dispatch and ledger failures remain diagnosable together", async () => {
+ const host = { async call(method) {
+ if (method === "scheduled.finishRun") throw new Error("ledger unavailable");
+ return { sessionId: "session", runId: "run", prompt: "Inspect" };
+ } };
+ await assert.rejects(executeScheduledTask({ host, id: "task", automatic: true,
+ runs: new Map(), isCurrent: () => true,
+ prompt: async () => { throw new Error("provider unavailable"); },
+ }), (error) => error instanceof AggregateError && error.errors.map((item) => item.message).join(",") === "provider unavailable,ledger unavailable");
+});
+
+test("polls serialize; stop prevents dispatch after a pending due response", async () => {
+ let resolve;
+ let polls = 0;
+ const pending = new Promise((done) => {
+ resolve = done;
+ });
+ const host = {
+ async call() {
+ polls++;
+ return pending;
+ },
+ };
+ const executed = [];
+ const runner = createScheduledRunner({
+ getHost: () => host,
+ execute: async (id) => executed.push(id),
+ report: (e) => {
+ throw e;
+ },
+ });
+ const tick = runner.tick();
+ await runner.tick();
+ assert.equal(polls, 1);
+ runner.stop();
+ resolve({ ids: ["task"] });
+ await tick;
+ assert.deepEqual(executed, []);
+});
+
+test("failure of one task does not suppress another due task", async () => {
+ const executed = [],
+ errors = [];
+ const host = {
+ async call() {
+ return { ids: ["a", "b"] };
+ },
+ };
+ const runner = createScheduledRunner({
+ getHost: () => host,
+ execute: async (id) => {
+ executed.push(id);
+ if (id === "a") throw new Error("failed");
+ },
+ report: (error) => errors.push(error.message),
+ });
+ await runner.tick();
+ runner.stop();
+ assert.deepEqual(executed, ["a", "b"]);
+ assert.deepEqual(errors, ["failed"]);
+});
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index 2267fc10f..21cef3dd4 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -1,3 +1,5 @@
+mod scheduled_rpc;
+
use std::io::{self, BufRead, BufReader as StdBufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
@@ -19,7 +21,6 @@ use crate::plugin_sessions;
use crate::plugin_usage;
use crate::providers::{self, DiscoveredModelInput, ProviderCreateInput, ProviderUpdateInput};
use crate::review;
-use crate::scheduled;
use crate::scratch;
use crate::sessions::{self, UiMessage};
use crate::state::{AppState, HOST_VERSION, PROTOCOL_VERSION};
@@ -3113,123 +3114,9 @@ async fn handle_request(
Ok(json!({ "ok": true, "changed": changed }))
}
- "scheduled.list" => {
- let st = state.lock().await;
- let tasks = scheduled::list_tasks(&st.db)
- .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
- Ok(json!({ "tasks": tasks }))
- }
- "scheduled.create" => {
- let st = state.lock().await;
- let task = scheduled::create_task(&st.db, &params)
- .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
- Ok(json!({ "task": task }))
- }
- "scheduled.update" => {
- let st = state.lock().await;
- let task = scheduled::update_task(&st.db, &params)
- .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
- .ok_or_else(|| rpc_err(1007, "task not found", "NOT_FOUND"))?;
- Ok(json!({ "task": task }))
- }
- "scheduled.delete" => {
- let id = params
- .get("id")
- .and_then(|v| v.as_str())
- .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
- let st = state.lock().await;
- let ok = scheduled::delete_task(&st.db, id)
- .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
- Ok(json!({ "ok": ok }))
- }
- "scheduled.import" => {
- let tasks = params
- .get("tasks")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
- let st = state.lock().await;
- let imported = scheduled::import_tasks(&st.db, &tasks)
- .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
- Ok(json!({ "imported": imported }))
- }
- "scheduled.run" => {
- let id = params
- .get("id")
- .and_then(|v| v.as_str())
- .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
- let st = state.lock().await;
- let task = scheduled::get_task(&st.db, id)
- .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
- .ok_or_else(|| rpc_err(1007, "task not found", "NOT_FOUND"))?;
- // Both contract modes need a human to approve their proposal (D198),
- // so neither can run unattended.
- if sessions::is_contract_mode(&task.mode) {
- return Err(plan_rpc_err("PLAN_REQUIRES_INTERACTIVE_SESSION"));
- }
- let settings = st
- .db
- .get_setting("app")
- .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
- .unwrap_or_else(|| json!({}));
- let session = sessions::create_session(
- &st.db,
- Some(task.title.clone()),
- Some("agent".into()),
- settings
- .get("defaultProviderId")
- .and_then(|v| v.as_str())
- .map(str::to_string),
- settings
- .get("defaultModelId")
- .and_then(|v| v.as_str())
- .map(str::to_string),
- st.workspace.get().map(|w| w.path),
- )
- .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
- let run_id = match scheduled::begin_run(&st.db, id, Some(&session.id)) {
- Ok(run_id) => run_id,
- Err(error) => {
- let _ = sessions::delete_session(&st.db, &session.id);
- return Err(rpc_err(1000, error.to_string(), "INTERNAL"));
- }
- };
- let task = scheduled::get_task(&st.db, id)
- .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
- .unwrap_or(task);
- Ok(json!({
- "sessionId": session.id,
- "prompt": task.prompt,
- "task": task,
- "runId": run_id
- }))
- }
- "scheduled.finishRun" => {
- let run_id = params
- .get("runId")
- .and_then(|v| v.as_str())
- .ok_or_else(|| rpc_err(1002, "runId required", "INVALID_PARAMS"))?;
- let status = params
- .get("status")
- .and_then(|v| v.as_str())
- .unwrap_or("completed");
+ method if method.starts_with("scheduled.") => {
let st = state.lock().await;
- let ok = scheduled::finish_run(
- &st.db,
- run_id,
- status,
- params.get("errorCode").and_then(|v| v.as_str()),
- )
- .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
- Ok(json!({ "ok": ok }))
- }
- "scheduled.listRuns" => {
- let task_id = params.get("taskId").and_then(|v| v.as_str());
- let limit = params.get("limit").and_then(|v| v.as_i64()).unwrap_or(50);
- let st = state.lock().await;
- let runs = scheduled::list_runs(&st.db, task_id, limit)
- .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
- Ok(json!({ "runs": runs }))
+ scheduled_rpc::handle(&st, method, params)
}
"tools.list" => Ok(json!({ "tools": tools::builtin_tool_defs() })),
diff --git a/crates/host-core/src/rpc/scheduled_rpc.rs b/crates/host-core/src/rpc/scheduled_rpc.rs
new file mode 100644
index 000000000..701dba6c9
--- /dev/null
+++ b/crates/host-core/src/rpc/scheduled_rpc.rs
@@ -0,0 +1,342 @@
+use super::{json, plan_rpc_err, rpc_err, AppState, JsonRpcError, Value};
+use crate::{scheduled, sessions};
+
+pub(super) fn handle(st: &AppState, method: &str, params: Value) -> Result<Value, JsonRpcError> {
+ handle_in_workspace(
+ st,
+ method,
+ params,
+ st.workspace.get().map(|workspace| workspace.path),
+ )
+}
+
+pub(super) fn handle_in_workspace(
+ st: &AppState,
+ method: &str,
+ params: Value,
+ workspace: Option<String>,
+) -> Result<Value, JsonRpcError> {
+ match method {
+ "scheduled.list" => {
+ let tasks = scheduled::list_tasks(&st.db)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
+ Ok(json!({ "tasks": tasks }))
+ }
+ "scheduled.create" => {
+ let mut params = params;
+ validate_schedule_input(&params)?;
+ if params.get("schedule").is_some() {
+ params["workspacePath"] = json!(workspace);
+ }
+ let task = scheduled::create_task(&st.db, &params)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
+ Ok(json!({ "task": task }))
+ }
+ "scheduled.update" => {
+ let mut params = params;
+ validate_schedule_input(&params)?;
+ if params.get("schedule").is_some() {
+ let id = params.get("id").and_then(Value::as_str).unwrap_or("");
+ let existing = scheduled::get_task(&st.db, id)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
+ if existing
+ .as_ref()
+ .is_some_and(|task| task.schedule.is_none())
+ {
+ params["workspacePath"] = json!(workspace);
+ } else if let Some(object) = params.as_object_mut() {
+ object.remove("workspacePath");
+ }
+ }
+ let task = scheduled::update_task(&st.db, &params)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
+ .ok_or_else(|| rpc_err(1007, "task not found", "NOT_FOUND"))?;
+ Ok(json!({ "task": task }))
+ }
+ "scheduled.delete" => {
+ let id = params
+ .get("id")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
+ let ok = scheduled::delete_task(&st.db, id)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
+ Ok(json!({ "ok": ok }))
+ }
+ "scheduled.import" => {
+ let tasks = params
+ .get("tasks")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+ let imported = scheduled::import_tasks(&st.db, &tasks)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
+ Ok(json!({ "imported": imported }))
+ }
+ "scheduled.run" => {
+ if params
+ .get("automatic")
+ .is_some_and(|value| !value.is_boolean())
+ {
+ return Err(rpc_err(
+ 1002,
+ "automatic must be a boolean",
+ "INVALID_PARAMS",
+ ));
+ }
+ let id = params
+ .get("id")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
+ let task = scheduled::get_task(&st.db, id)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
+ .ok_or_else(|| rpc_err(1007, "task not found", "NOT_FOUND"))?;
+ let automatic = params
+ .get("automatic")
+ .and_then(Value::as_bool)
+ .unwrap_or(false);
+ let now = crate::db::now_ms();
+ if scheduled::automation::running(&st.db, id)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
+ {
+ return Err(rpc_err(
+ 1002,
+ "task is already running",
+ "SCHEDULE_ALREADY_RUNNING",
+ ));
+ }
+ if automatic
+ && (!task.enabled
+ || !scheduled::automation::due(&st.db, now)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
+ .iter()
+ .any(|due| due == id))
+ {
+ return Err(rpc_err(1002, "task is no longer due", "SCHEDULE_NOT_DUE"));
+ }
+ if automatic {
+ scheduled::automation::reschedule(&st.db, id, now)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
+ }
+ // Both contract modes need a human to approve their proposal (D198),
+ // so neither can run unattended.
+ if sessions::is_contract_mode(&task.mode) {
+ return Err(plan_rpc_err("PLAN_REQUIRES_INTERACTIVE_SESSION"));
+ }
+ let settings = st
+ .db
+ .get_setting("app")
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
+ .unwrap_or_else(|| json!({}));
+ let options = sessions::SessionCreateOptions {
+ title: Some(task.title.clone()),
+ mode: Some("agent".into()),
+ provider_id: settings
+ .get("defaultProviderId")
+ .and_then(|v| v.as_str())
+ .map(str::to_string),
+ model_id: settings
+ .get("defaultModelId")
+ .and_then(|v| v.as_str())
+ .map(str::to_string),
+ project_path: if task.schedule.is_some() {
+ task.workspace_path.clone()
+ } else {
+ st.workspace.get().map(|w| w.path)
+ },
+ permission_mode: automatic.then(|| "ask".into()),
+ ..Default::default()
+ };
+ let session = if automatic {
+ sessions::create_session_with_options(&st.db, options)
+ } else {
+ sessions::create_session(
+ &st.db,
+ options.title,
+ options.mode,
+ options.provider_id,
+ options.model_id,
+ options.project_path,
+ )
+ }
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
+ let run_id = match scheduled::begin_run(&st.db, id, Some(&session.id)) {
+ Ok(run_id) => run_id,
+ Err(error) => {
+ let _ = sessions::delete_session(&st.db, &session.id);
+ return Err(rpc_err(1000, error.to_string(), "INTERNAL"));
+ }
+ };
+ let task = scheduled::get_task(&st.db, id)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
+ .unwrap_or(task);
+ Ok(json!({
+ "sessionId": session.id,
+ "prompt": task.prompt,
+ "task": task,
+ "runId": run_id
+ }))
+ }
+ "scheduled.due" => {
+ let ids = scheduled::automation::due(&st.db, crate::db::now_ms())
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
+ Ok(json!({ "ids": ids }))
+ }
+ "scheduled.finishRun" => {
+ let run_id = params
+ .get("runId")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| rpc_err(1002, "runId required", "INVALID_PARAMS"))?;
+ let status = params
+ .get("status")
+ .and_then(|v| v.as_str())
+ .unwrap_or("completed");
+ let ok = scheduled::finish_run(
+ &st.db,
+ run_id,
+ status,
+ params.get("errorCode").and_then(|v| v.as_str()),
+ )
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
+ Ok(json!({ "ok": ok }))
+ }
+ "scheduled.listRuns" => {
+ let task_id = params.get("taskId").and_then(|v| v.as_str());
+ let limit = params.get("limit").and_then(|v| v.as_i64()).unwrap_or(50);
+ let runs = scheduled::list_runs(&st.db, task_id, limit)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
+ Ok(json!({ "runs": runs }))
+ }
+
+ _ => Err(rpc_err(1007, "unknown scheduled method", "NOT_FOUND")),
+ }
+}
+
+fn validate_schedule_input(params: &Value) -> Result<(), JsonRpcError> {
+ if let Some(schedule) = params.get("schedule").filter(|value| !value.is_null()) {
+ let parsed: scheduled::timing::Schedule = serde_json::from_value(schedule.clone())
+ .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
+ parsed
+ .validate()
+ .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
+ if params
+ .get("prompt")
+ .and_then(Value::as_str)
+ .is_some_and(|prompt| prompt.trim().is_empty())
+ {
+ return Err(rpc_err(1002, "prompt required", "INVALID_PARAMS"));
+ }
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn selected_weekdays_round_trip_and_invalid_edits_preserve_saved_schedule() {
+ let dir = tempfile::tempdir().unwrap();
+ let state = AppState::open(dir.path()).unwrap();
+ let task = handle(
+ &state,
+ "scheduled.create",
+ json!({
+ "title":"Weekend review", "prompt":"Review", "cadence":"weekly",
+ "schedule":{"hour":9,"minute":15,"weekday":5,"weekdays":[5,6]}
+ }),
+ )
+ .unwrap()["task"]
+ .clone();
+ let id = task["id"].as_str().unwrap();
+ assert_eq!(task["schedule"]["weekdays"], json!([5, 6]));
+ for days in [
+ json!([]),
+ json!([1, 1]),
+ json!([7]),
+ json!([-1]),
+ json!("Monday"),
+ ] {
+ let error = handle(
+ &state,
+ "scheduled.update",
+ json!({
+ "id":id, "schedule":{"hour":9,"minute":15,"weekday":5,"weekdays":days}
+ }),
+ )
+ .unwrap_err();
+ assert_eq!(error.data.unwrap()["errorCode"], "INVALID_PARAMS");
+ }
+ drop(state);
+ let state = AppState::open(dir.path()).unwrap();
+ let saved = handle(&state, "scheduled.list", json!({})).unwrap();
+ assert_eq!(saved["tasks"][0]["schedule"], task["schedule"]);
+ }
+
+ #[test]
+ fn automatic_admission_is_durable_single_flight_and_uses_ask() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut state = AppState::open(dir.path()).unwrap();
+ let original_project = tempfile::tempdir().unwrap();
+ let different_project = tempfile::tempdir().unwrap();
+ let original_path = state.workspace.set(original_project.path()).path;
+ let task = handle(
+ &state,
+ "scheduled.create",
+ json!({
+ "prompt":"Review project", "cadence":"hourly",
+ "schedule":{"hour":9,"minute":15,"weekday":0}
+ }),
+ )
+ .unwrap()["task"]
+ .clone();
+ let id = task["id"].as_str().unwrap();
+ state.workspace.set(different_project.path());
+ assert!(handle(&state, "scheduled.run", json!({"id":id,"automatic":true})).is_err());
+ state.db.conn().execute(
+ "UPDATE scheduled_tasks SET config_json = json_set(config_json, '$.nextRunAt', ?1) WHERE id = ?2",
+ rusqlite::params![crate::db::now_ms(), id],
+ ).unwrap();
+ let run = handle(&state, "scheduled.run", json!({"id":id,"automatic":true})).unwrap();
+ let session = sessions::get_session(&state.db, run["sessionId"].as_str().unwrap())
+ .unwrap()
+ .unwrap();
+ assert_eq!(session.summary.permission_mode, "ask");
+ assert_eq!(
+ session.summary.project_path.as_deref(),
+ Some(original_path.as_str())
+ );
+ assert!(handle(&state, "scheduled.run", json!({"id":id})).is_err());
+ assert!(handle(&state, "scheduled.delete", json!({"id":id})).is_err());
+ handle(
+ &state,
+ "scheduled.finishRun",
+ json!({"runId":run["runId"],"status":"completed"}),
+ )
+ .unwrap();
+ assert!(handle(&state, "scheduled.run", json!({"id":id,"automatic":true})).is_err());
+ let history = handle(&state, "scheduled.listRuns", json!({"taskId":id})).unwrap();
+ assert_eq!(history["runs"][0]["status"], "completed");
+ }
+
+ #[test]
+ fn invalid_schedule_does_not_mutate_task() {
+ let dir = tempfile::tempdir().unwrap();
+ let state = AppState::open(dir.path()).unwrap();
+ let error = handle(
+ &state,
+ "scheduled.run",
+ json!({"id":"absent", "automatic":"true"}),
+ )
+ .unwrap_err();
+ assert_eq!(error.data.unwrap()["errorCode"], "INVALID_PARAMS");
+ assert!(handle(
+ &state,
+ "scheduled.create",
+ json!({
+ "prompt":"Review", "schedule":{"hour":25,"minute":0,"weekday":0}
+ })
+ )
+ .is_err());
+ assert!(scheduled::list_tasks(&state.db).unwrap().is_empty());
+ }
+}
diff --git a/crates/host-core/src/scheduled.rs b/crates/host-core/src/scheduled.rs
index ea50a5520..45a57665c 100644
--- a/crates/host-core/src/scheduled.rs
+++ b/crates/host-core/src/scheduled.rs
@@ -7,6 +7,9 @@ use uuid::Uuid;
use crate::db::{ms_to_ts, now_ms, ts_to_ms, Database};
use crate::sessions;
+pub mod automation;
+pub mod timing;
+
/// Wire format matches the legacy Electron `scheduled-tasks.json` records so
/// the renderer keeps working unchanged (camelCase, RFC3339 timestamps).
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -22,6 +25,12 @@ pub struct ScheduledTask {
pub updated_at: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub last_run_at: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub schedule: Option<timing::Schedule>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub next_run_at: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub workspace_path: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
@@ -142,6 +151,7 @@ fn updated_config_json(db: &Database, id: &str, params_json: &Value) -> Result<O
}
fn task_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<ScheduledTask> {
+ let config = config_json_value(&row.get::<_, String>(4)?);
Ok(ScheduledTask {
id: row.get(0)?,
title: row.get(1)?,
@@ -152,6 +162,17 @@ fn task_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<ScheduledTask> {
created_at: ms_to_ts(row.get(6)?),
updated_at: ms_to_ts(row.get(7)?),
last_run_at: row.get::<_, Option<i64>>(8)?.map(ms_to_ts),
+ schedule: config
+ .get("schedule")
+ .and_then(|value| serde_json::from_value(value.clone()).ok()),
+ next_run_at: config
+ .get("nextRunAt")
+ .and_then(Value::as_i64)
+ .map(ms_to_ts),
+ workspace_path: config
+ .get("workspacePath")
+ .and_then(Value::as_str)
+ .map(str::to_string),
})
}
@@ -195,16 +216,30 @@ pub fn create_task(db: &Database, params_json: &Value) -> Result<ScheduledTask>
.collect();
let cadence = normalize_cadence(params_json.get("cadence").and_then(|v| v.as_str()));
let mode = task_mode(params_json);
- let config_json = config_with_mode(config_value(config_input(params_json)), &mode);
+ let mut config = config_value(config_input(params_json));
+ automation::configure(&mut config, params_json, &cadence, now_ms())?;
+ let config_json = config_with_mode(config, &mode);
let id = Uuid::new_v4().to_string();
let now = now_ms();
+ let enabled = params_json
+ .get("enabled")
+ .and_then(Value::as_bool)
+ .unwrap_or(true);
db.conn()
.prepare_cached(
"INSERT INTO scheduled_tasks
(id, title, prompt, cadence, config_json, enabled, created_at, updated_at)
- VALUES (?1, ?2, ?3, ?4, ?5, 1, ?6, ?6)",
+ VALUES (?1, ?2, ?3, ?4, ?5, ?7, ?6, ?6)",
)?
- .execute(params![id, title, prompt, cadence, config_json, now])?;
+ .execute(params![
+ id,
+ title,
+ prompt,
+ cadence,
+ config_json,
+ now,
+ enabled
+ ])?;
Ok(get_task(db, &id)?.expect("task just inserted"))
}
@@ -219,6 +254,14 @@ pub fn update_task(db: &Database, params_json: &Value) -> Result<Option<Schedule
let Some(config_json) = updated_config_json(db, id, params_json)? else {
return Ok(None);
};
+ let mut config = config_json_value(&config_json);
+ let existing = get_task(db, id)?;
+ let effective_cadence = cadence
+ .as_deref()
+ .or_else(|| existing.as_ref().map(|task| task.cadence.as_str()))
+ .unwrap_or("manual");
+ automation::configure(&mut config, params_json, effective_cadence, now_ms())?;
+ let config_json = config.to_string();
let n = db
.conn()
.prepare_cached(
@@ -250,6 +293,9 @@ pub fn update_task(db: &Database, params_json: &Value) -> Result<Option<Schedule
}
pub fn delete_task(db: &Database, id: &str) -> Result<bool> {
+ if automation::running(db, id)? {
+ anyhow::bail!("cannot delete a running task");
+ }
let n = db
.conn()
.prepare_cached("DELETE FROM scheduled_tasks WHERE id = ?1")?
diff --git a/crates/host-core/src/scheduled/automation.rs b/crates/host-core/src/scheduled/automation.rs
new file mode 100644
index 000000000..c50a0d3ff
--- /dev/null
+++ b/crates/host-core/src/scheduled/automation.rs
@@ -0,0 +1,148 @@
+use anyhow::{bail, Result};
+use rusqlite::params;
+use serde_json::{json, Value};
+
+use super::{get_task, timing::Schedule};
+use crate::db::{now_ms, Database};
+
+pub fn configure(config: &mut Value, input: &Value, cadence: &str, now: i64) -> Result<()> {
+ if let Some(schedule) = input.get("schedule") {
+ if schedule.is_null() {
+ config["schedule"] = Value::Null;
+ } else {
+ let schedule: Schedule = serde_json::from_value(schedule.clone())?;
+ schedule.validate()?;
+ config["schedule"] = serde_json::to_value(schedule)?;
+ }
+ }
+ if let Some(workspace) = input.get("workspacePath") {
+ if !workspace.is_null() && !workspace.is_string() {
+ bail!("workspacePath must be a string or null");
+ }
+ config["workspacePath"] = workspace.clone();
+ }
+ if input.get("schedule").is_some()
+ || input.get("cadence").is_some()
+ || input.get("enabled").is_some()
+ {
+ let next = config
+ .get("schedule")
+ .and_then(|value| serde_json::from_value::<Schedule>(value.clone()).ok())
+ .and_then(|schedule| schedule.next(cadence, now));
+ config["nextRunAt"] = json!(next);
+ }
+ Ok(())
+}
+
+pub fn reschedule(db: &Database, id: &str, now: i64) -> Result<()> {
+ let Some(task) = get_task(db, id)? else {
+ return Ok(());
+ };
+ let raw: String = db.conn().query_row(
+ "SELECT config_json FROM scheduled_tasks WHERE id = ?1",
+ [id],
+ |row| row.get(0),
+ )?;
+ let mut config: Value = serde_json::from_str(&raw)?;
+ config["nextRunAt"] = json!(task
+ .schedule
+ .and_then(|schedule| schedule.next(&task.cadence, now)));
+ db.conn().execute(
+ "UPDATE scheduled_tasks SET config_json = ?1 WHERE id = ?2",
+ params![config.to_string(), id],
+ )?;
+ Ok(())
+}
+
+pub fn running(db: &Database, id: &str) -> Result<bool> {
+ Ok(db.conn().query_row(
+ "SELECT EXISTS(SELECT 1 FROM task_runs WHERE task_id = ?1 AND status = 'running')",
+ [id],
+ |row| row.get(0),
+ )?)
+}
+
+/// Polling never replays missed occurrences or overlaps an unfinished run.
+pub fn due(db: &Database, now: i64) -> Result<Vec<String>> {
+ let mut result = Vec::new();
+ for task in super::list_tasks(db)? {
+ let Some(next) = task.next_run_at.as_deref().map(crate::db::ts_to_ms) else {
+ continue;
+ };
+ if !task.enabled || task.schedule.is_none() || task.cadence == "manual" || next > now {
+ continue;
+ }
+ if now - next > 90_000 || running(db, &task.id)? {
+ reschedule(db, &task.id, now)?;
+ } else {
+ result.push(task.id);
+ }
+ }
+ Ok(result)
+}
+
+pub fn recover(db: &Database) -> Result<()> {
+ // Database boot maintenance owns interruption of orphaned task_runs.
+ // Restart starts from future occurrences; downtime never creates a burst.
+ for task in super::list_tasks(db)? {
+ if task.schedule.is_some() {
+ reschedule(db, &task.id, now_ms())?;
+ }
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::scheduled::{begin_run, create_task, finish_run, update_task};
+
+ #[test]
+ fn legacy_tasks_are_not_armed_and_explicit_schedule_survives_edits() {
+ let dir = tempfile::tempdir().unwrap();
+ let db = Database::open_in_dir(dir.path()).unwrap();
+ let task = create_task(&db, &json!({"prompt":"check", "cadence":"daily"})).unwrap();
+ assert!(task.schedule.is_none());
+ assert!(due(&db, now_ms()).unwrap().is_empty());
+ let task = update_task(
+ &db,
+ &json!({"id":task.id,"schedule":{"hour":9,"minute":0,"weekday":0}}),
+ )
+ .unwrap()
+ .unwrap();
+ assert!(task.next_run_at.is_some());
+ let edited = update_task(&db, &json!({"id":task.id,"title":"Edited"}))
+ .unwrap()
+ .unwrap();
+ assert_eq!(edited.next_run_at, task.next_run_at);
+ }
+
+ #[test]
+ fn due_paused_overlap_missed_and_restart_paths() {
+ let dir = tempfile::tempdir().unwrap();
+ let db = Database::open_in_dir(dir.path()).unwrap();
+ let task = create_task(&db, &json!({"prompt":"check", "cadence":"hourly", "schedule":{"hour":9,"minute":0,"weekday":0}})).unwrap();
+ let at = crate::db::ts_to_ms(task.next_run_at.as_ref().unwrap());
+ assert_eq!(due(&db, at).unwrap(), vec![task.id.clone()]);
+ let run = begin_run(&db, &task.id, None).unwrap();
+ assert!(due(&db, at).unwrap().is_empty());
+ finish_run(&db, &run, "completed", None).unwrap();
+ assert!(due(&db, at + 3_600_000 + 90_001).unwrap().is_empty());
+ update_task(&db, &json!({"id":task.id,"enabled":false})).unwrap();
+ assert!(due(&db, at + 10 * 3_600_000).unwrap().is_empty());
+ let interrupted = begin_run(&db, &task.id, None).unwrap();
+ drop(db);
+ let db = Database::open_in_dir(dir.path()).unwrap();
+ recover(&db).unwrap();
+ assert!(!running(&db, &task.id).unwrap());
+ assert_eq!(
+ super::super::list_runs(&db, Some(&task.id), 100)
+ .unwrap()
+ .into_iter()
+ .find(|run| run.id == interrupted)
+ .unwrap()
+ .status,
+ "aborted"
+ );
+ }
+}
diff --git a/crates/host-core/src/scheduled/timing.rs b/crates/host-core/src/scheduled/timing.rs
new file mode 100644
index 000000000..23f5c8dc7
--- /dev/null
+++ b/crates/host-core/src/scheduled/timing.rs
@@ -0,0 +1,269 @@
+use anyhow::{bail, Result};
+use chrono::{Datelike, Local, TimeZone, Timelike};
+use serde::{Deserialize, Serialize};
+
+/// Daily/weekly schedules use local time; hourly schedules use elapsed time.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct Schedule {
+ pub hour: u32,
+ pub minute: u32,
+ /// Monday = 0, Sunday = 6.
+ pub weekday: u32,
+ /// When present, replaces the legacy single weekday. Monday = 0.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub weekdays: Option<Vec<u32>>,
+}
+
+impl Schedule {
+ pub fn validate(&self) -> Result<()> {
+ if self.hour > 23 || self.minute > 59 || self.weekday > 6 {
+ bail!("invalid schedule time or weekday");
+ }
+ if let Some(days) = &self.weekdays {
+ if days.is_empty()
+ || days.len() > 7
+ || days.iter().any(|day| *day > 6)
+ || days
+ .iter()
+ .enumerate()
+ .any(|(index, day)| days[..index].contains(day))
+ {
+ bail!("weekdays must contain unique days from 0 to 6");
+ }
+ }
+ Ok(())
+ }
+
+ pub fn next(&self, cadence: &str, after: i64) -> Option<i64> {
+ self.next_in(cadence, after, &Local)
+ }
+
+ fn next_in<T: TimeZone>(&self, cadence: &str, after: i64, zone: &T) -> Option<i64> {
+ if self.validate().is_err() || !matches!(cadence, "hourly" | "daily" | "weekly") {
+ return None;
+ }
+ if cadence == "hourly" {
+ return after.checked_add(3_600_000);
+ }
+ let first = after
+ .div_euclid(60_000)
+ .checked_add(1)?
+ .checked_mul(60_000)?;
+ let current = zone.timestamp_millis_opt(after).single()?;
+ let passed_today = (current.hour(), current.minute()) >= (self.hour, self.minute);
+ // Walk instants rather than constructing nonexistent local DST times.
+ for offset in 0..(8 * 24 * 60) {
+ let timestamp = first.checked_add(offset * 60_000)?;
+ let local = zone.timestamp_millis_opt(timestamp).single()?;
+ if local.minute() == self.minute
+ && (!passed_today || local.date_naive() != current.date_naive())
+ && local.hour() == self.hour
+ && (cadence != "weekly"
+ || self.weekdays.as_ref().map_or_else(
+ || local.weekday().num_days_from_monday() == self.weekday,
+ |days| days.contains(&local.weekday().num_days_from_monday()),
+ ))
+ {
+ return Some(timestamp);
+ }
+ }
+ None
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use chrono::Utc;
+
+ #[test]
+ fn weekly_selection_skips_unselected_days_and_wraps_the_week() {
+ let mut schedule = Schedule {
+ hour: 9,
+ minute: 15,
+ weekday: 0,
+ weekdays: Some(vec![0, 2, 4]),
+ };
+ let monday = Utc
+ .with_ymd_and_hms(2026, 9, 21, 9, 15, 0)
+ .unwrap()
+ .timestamp_millis();
+ let day = 86_400_000;
+ assert_eq!(schedule.next_in("weekly", monday - 1, &Utc), Some(monday));
+ assert_eq!(
+ schedule.next_in("weekly", monday, &Utc),
+ Some(monday + 2 * day)
+ );
+ assert_eq!(
+ schedule.next_in("weekly", monday + 4 * day, &Utc),
+ Some(monday + 7 * day)
+ );
+ schedule.weekdays = Some(vec![5, 6]);
+ assert_eq!(
+ schedule.next_in("weekly", monday, &Utc),
+ Some(monday + 5 * day)
+ );
+ assert_eq!(
+ schedule.next_in("weekly", monday + 5 * day, &Utc),
+ Some(monday + 6 * day)
+ );
+ schedule.weekdays = Some(vec![0, 1, 2, 3, 4]);
+ assert_eq!(
+ schedule.next_in("weekly", monday + 4 * day, &Utc),
+ Some(monday + 7 * day)
+ );
+ schedule.weekdays = Some((0..7).collect());
+ assert_eq!(schedule.next_in("weekly", monday, &Utc), Some(monday + day));
+ }
+
+ #[test]
+ fn legacy_weekday_survives_and_invalid_day_selections_are_rejected() {
+ let raw = serde_json::json!({"hour":9,"minute":15,"weekday":4});
+ let legacy: Schedule = serde_json::from_value(raw.clone()).unwrap();
+ assert!(legacy.weekdays.is_none());
+ let monday = Utc
+ .with_ymd_and_hms(2026, 9, 21, 9, 15, 0)
+ .unwrap()
+ .timestamp_millis();
+ assert_eq!(
+ legacy.next_in("weekly", monday, &Utc),
+ Some(monday + 4 * 86_400_000)
+ );
+ for days in [vec![], vec![0, 0], vec![7], vec![0, 1, 2, 3, 4, 5, 6, 0]] {
+ let mut input = raw.clone();
+ input["weekdays"] = serde_json::json!(days);
+ let schedule: Schedule = serde_json::from_value(input).unwrap();
+ assert!(schedule.validate().is_err());
+ assert_eq!(schedule.next_in("weekly", monday, &Utc), None);
+ }
+ }
+
+ #[test]
+ fn hourly_waits_a_full_hour_independent_of_calendar_fields() {
+ let schedule = Schedule {
+ hour: 9,
+ minute: 15,
+ weekday: 0,
+ weekdays: None,
+ };
+ let start = Utc
+ .with_ymd_and_hms(2026, 9, 21, 10, 42, 37)
+ .unwrap()
+ .timestamp_millis()
+ + 123;
+ assert_eq!(
+ schedule.next_in("hourly", start, &Utc),
+ Some(start + 3_600_000)
+ );
+ assert_eq!(
+ schedule.next_in("hourly", start + 3_600_000, &Utc),
+ Some(start + 7_200_000)
+ );
+ assert_eq!(schedule.next_in("hourly", i64::MAX, &Utc), None);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn daylight_saving_skips_missing_and_duplicate_daily_times() {
+ // Isolate TZ in a child; changing the process environment during
+ // parallel Rust tests would race chrono and unrelated filesystem tests.
+ if std::env::var("PI_SCHEDULE_TZ_TEST").as_deref() != Ok("1") {
+ let output = std::process::Command::new(std::env::current_exe().unwrap())
+ .args(["--exact", "scheduled::timing::tests::daylight_saving_skips_missing_and_duplicate_daily_times"])
+ .env("TZ", "America/New_York")
+ .env("PI_SCHEDULE_TZ_TEST", "1")
+ .output().unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stdout)
+ );
+ return;
+ }
+ let timestamp = |value: &str| {
+ chrono::DateTime::parse_from_rfc3339(value)
+ .unwrap()
+ .timestamp_millis()
+ };
+ let spring = Schedule {
+ hour: 2,
+ minute: 30,
+ weekday: 0,
+ weekdays: None,
+ };
+ assert_eq!(
+ spring.next("daily", timestamp("2026-03-08T06:00:00Z")),
+ Some(timestamp("2026-03-09T06:30:00Z"))
+ );
+ let fall = Schedule {
+ hour: 1,
+ minute: 30,
+ weekday: 0,
+ weekdays: None,
+ };
+ assert_eq!(
+ fall.next("daily", timestamp("2026-11-01T05:30:00Z")),
+ Some(timestamp("2026-11-02T06:30:00Z"))
+ );
+ assert_eq!(
+ fall.next("hourly", timestamp("2026-11-01T05:30:00Z")),
+ Some(timestamp("2026-11-01T06:30:00Z"))
+ );
+ }
+
+ #[test]
+ fn next_occurrence_is_strictly_future_and_obeys_cadence() {
+ let schedule = Schedule {
+ hour: 9,
+ minute: 15,
+ weekday: 0,
+ weekdays: None,
+ };
+ let monday = Utc
+ .with_ymd_and_hms(2026, 9, 21, 9, 15, 0)
+ .unwrap()
+ .timestamp_millis();
+ assert_eq!(
+ schedule.next_in("hourly", monday, &Utc),
+ Some(monday + 3_600_000)
+ );
+ assert_eq!(
+ schedule.next_in("daily", monday, &Utc),
+ Some(monday + 86_400_000)
+ );
+ assert_eq!(
+ schedule.next_in("weekly", monday, &Utc),
+ Some(monday + 7 * 86_400_000)
+ );
+ assert_eq!(schedule.next_in("manual", monday, &Utc), None);
+ }
+
+ #[test]
+ fn rejects_invalid_times_instead_of_silently_running() {
+ assert!(Schedule {
+ hour: 24,
+ minute: 0,
+ weekday: 0,
+ weekdays: None,
+ }
+ .validate()
+ .is_err());
+ assert!(Schedule {
+ hour: 9,
+ minute: 60,
+ weekday: 0,
+ weekdays: None,
+ }
+ .validate()
+ .is_err());
+ assert!(Schedule {
+ hour: 9,
+ minute: 0,
+ weekday: 7,
+ weekdays: None,
+ }
+ .validate()
+ .is_err());
+ }
+}
diff --git a/crates/host-core/src/state.rs b/crates/host-core/src/state.rs
index 8c100ebe4..2303f63dd 100644
--- a/crates/host-core/src/state.rs
+++ b/crates/host-core/src/state.rs
@@ -72,6 +72,7 @@ pub struct AppState {
impl AppState {
pub fn open(data_dir: &std::path::Path) -> Result<Self> {
let db = Database::open_in_dir(data_dir)?;
+ crate::scheduled::automation::recover(&db)?;
// Replies that were still streaming when the previous process ended
// are promoted into their transcripts before any client can read them
// (D299). The turn sweep inside `open` has already marked those turns
diff --git a/docs/adr/README.md b/docs/adr/README.md
index ec968dc24..e995670e8 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -20,6 +20,7 @@ Each ADR includes:
| ID | Title | Status |
|---|---|---|
+| scheduled-desktop-automations | [Desktop automation scheduling](scheduled-desktop-automations.md) | Accepted for implementation |
| subagent-model-fallback | [Ordered subagent model fallback](subagent-model-fallback.md) | Accepted for implementation |
| subagent-model-opt-in | [Separate Subagent Model Opt-In from Definition Pins](subagent-model-opt-in.md) | Accepted for implementation |
| 0001 | Use Electron as the desktop shell | Accepted |
diff --git a/docs/adr/scheduled-desktop-automations.md b/docs/adr/scheduled-desktop-automations.md
new file mode 100644
index 000000000..0228869f0
--- /dev/null
+++ b/docs/adr/scheduled-desktop-automations.md
@@ -0,0 +1,59 @@
+# ADR: Desktop-owned automation dispatch with Host-owned schedules
+
+- Status: Accepted for implementation
+- Date: 2026-09-20
+
+## Context
+
+The shipped Scheduled page stores a cadence but never dispatches work when
+that cadence becomes due. The pinned pi-ai, pi-agent-core and pi-coding-agent
+0.85.1 packages supply agent execution, not a persistent desktop wall-clock
+scheduler. The existing Host-owned task and run tables already provide the
+appropriate storage boundary.
+
+## Decision
+
+Keep schedule calculation, persistence, duplicate admission and restart recovery
+in Rust host-core. A small Electron lifecycle service polls every 30 seconds
+while the app runs and dispatches admitted work through the existing agentPrompt
+handler. It never asks the renderer to execute a background task. The existing
+turn finalizer closes the task run. The service stops when the app quits.
+
+Use the existing config_json extension boundary for a validated schedule
+{hour, minute, weekday, weekdays?}, nextRunAt in epoch milliseconds and workspacePath.
+The workspace is captured when a schedule is first configured. No new tables,
+columns, schema migration or change to existing task identifiers is needed.
+Old cadence-only records remain unarmed until explicitly configured. Existing
+scheduled.run retains its prepare-only response; additive scheduledExecute IPC
+dispatches a turn, and scheduledListRuns exposes the existing run ledger.
+
+Automatic runs use Ask permission mode. They may wait for a user in their result
+conversation; this feature never grants approval. Plan/Goal rejection remains.
+The default provider/model are resolved at execution time. Retain the task's
+project even when the foreground workspace changes.
+
+Expose Scheduled through a footer clock action as well as global search.
+The page has task and run-history views, editing, pause/resume, Run now and
+conversation links. This amends the earlier omission of Scheduled from the
+home sidebar; other destinations and navigation ownership remain unchanged.
+
+## Consequences
+
+The app must remain running. A due occurrence more than 90 seconds late is
+skipped, never replayed in a burst. An active run suppresses an overlapping
+occurrence. Startup interrupts orphaned runs and arms only future occurrences.
+Daily/weekly times follow the host's local timezone. Weekly schedules accept
+a nonempty unique selection of weekdays, falling back to the legacy single
+weekday when absent. Hourly tasks instead wait one elapsed hour after saving,
+enabling, startup or the preceding admission. This avoids a minute selector
+for a fixed interval while preserving calendar semantics for daily/weekly tasks.
+No cloud execution, OS service, arbitrary cron or sub-hourly interval is added.
+Downgrading keeps the existing records readable but removes automatic execution.
+
+## Alternatives
+
+A plugin would duplicate lifecycle/storage ownership and make baseline
+automation depend on extension availability. A second agent loop would bypass
+existing admission, persistence and permissions. Both are rejected. The pi
+agent implementation remains the execution engine.
+
diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.md
index 0b3258fb4..d7b3c03ec 100644
--- a/docs/spec/03-runtime/04-data-storage.md
+++ b/docs/spec/03-runtime/04-data-storage.md
@@ -990,7 +990,16 @@ CREATE INDEX idx_task_runs ON task_runs(task_id, started_at DESC);
```
A run that spawns a session gets its transcript for free via `session_id`.
-Finer schedules (cron) land in `config_json` without a migration.
+The existing JSON extension stores `schedule: {hour, minute, weekday}`,
+`nextRunAt` (epoch milliseconds) and `workspacePath` for desktop automations.
+Optional `weekdays` stores 1–7 unique integers in 0–6, overriding legacy
+`weekday` for weekly schedules. Missing `weekdays` preserves the single-day
+behavior. Invalid or empty selections are rejected before mutation. No table
+migration is needed. Daily/weekly schedules use the host local timezone; hourly
+schedules compute `nextRunAt = now + 3_600_000`, ignoring calendar fields. Absence
+of `schedule` leaves legacy tasks unarmed. No physical schema change is made.
+Task wire fields project `schedule`, RFC3339 `nextRunAt` and `workspacePath`.
+See [the automation ADR](../../adr/scheduled-desktop-automations.md).
Scheduled task `config_json.mode` is a durable operating-mode value. There is
intentionally no physical `scheduled_tasks.mode` column. The v7→v8
diff --git a/docs/zh-CN/adr/index.md b/docs/zh-CN/adr/index.md
index 5e2f8c4c7..5a0a40ac2 100644
--- a/docs/zh-CN/adr/index.md
+++ b/docs/zh-CN/adr/index.md
@@ -315,4 +315,7 @@ ADR 记录那些不应被静默改变的架构选择。中文入口与英文索
## Tray session shortcuts
+定时任务的调度、存储、权限与桌面入口决策见
+[ADR: Desktop automations](/adr/scheduled-desktop-automations)。
+
[ADR tray-session-shortcuts](/adr/tray-session-shortcuts) defines bounded native session groups and the renderer/Main ownership boundary.
diff --git a/docs/zh-CN/spec/03-runtime/04-data-storage.md b/docs/zh-CN/spec/03-runtime/04-data-storage.md
index f99a14c4d..eb3af6c29 100644
--- a/docs/zh-CN/spec/03-runtime/04-data-storage.md
+++ b/docs/zh-CN/spec/03-runtime/04-data-storage.md
@@ -886,7 +886,11 @@ CREATE INDEX idx_task_runs ON task_runs(task_id, started_at DESC);
```
生成会话的运行通过 `session_id` 免费获取其转录本。
-更精细的计划 (cron) 无需迁移即可登陆 `config_json`。
+`config_json` 保存 `schedule: {hour, minute, weekday}`、毫秒时间戳 `nextRunAt`
+和 `workspacePath`。每天、每周按宿主本地时区计算。每小时采用 `nextRunAt = now + 3_600_000`,
+忽略日历时间字段。可选 `weekdays` 保存 1–7 个不重复的 0–6 整数,覆盖每周的旧 `weekday`;
+缺失时保留单日语义,空数组、重复或越界值在写入前拒绝。无需表结构迁移。
+无 `schedule` 的旧任务不会自动运行;无需修改表或迁移数据库。
计划任务 `config_json.mode` 是持久操作模式值。有
故意没有物理 `scheduled_tasks.mode` 列。 v7→v8
diff --git a/packages/shared/src/protocol.test.ts b/packages/shared/src/protocol.test.ts
index a4b309c5b..47f7e6492 100644
--- a/packages/shared/src/protocol.test.ts
+++ b/packages/shared/src/protocol.test.ts
@@ -37,6 +37,8 @@ describe("Plan protocol contracts", () => {
expect(IPC_WHITELIST.has(IPC.invoke.scheduledUpdate)).toBe(true);
expect(IPC_WHITELIST.has(IPC.invoke.scheduledDelete)).toBe(true);
expect(IPC_WHITELIST.has(IPC.invoke.scheduledRun)).toBe(true);
+ expect(IPC_WHITELIST.has(IPC.invoke.scheduledExecute)).toBe(true);
+ expect(IPC_WHITELIST.has(IPC.invoke.scheduledListRuns)).toBe(true);
expect(IPC.invoke.providersRefreshModelCatalog).toBe(
"pi-desktop/providers/refreshModelCatalog",
);
diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts
index 2dd8619cd..3ee1e2db4 100644
--- a/packages/shared/src/protocol.ts
+++ b/packages/shared/src/protocol.ts
@@ -142,6 +142,8 @@ export const IPC = {
scheduledUpdate: "pi-desktop/scheduled/update",
scheduledDelete: "pi-desktop/scheduled/delete",
scheduledRun: "pi-desktop/scheduled/run",
+ scheduledExecute: "pi-desktop/scheduled/execute",
+ scheduledListRuns: "pi-desktop/scheduled/listRuns",
toolResolvePermission: "pi-desktop/tool/resolvePermission",
askToolResolve: "pi-desktop/agent/askTool/resolve",
plansPending: "pi-desktop/plans/pending",
diff --git a/packages/shared/src/types/platform.ts b/packages/shared/src/types/platform.ts
index 484da2145..2a757438a 100644
--- a/packages/shared/src/types/platform.ts
+++ b/packages/shared/src/types/platform.ts
@@ -85,6 +85,19 @@ export type OnboardingState = {
export type ScheduledTaskCadence = "manual" | "hourly" | "daily" | "weekly";
+export type ScheduledTaskSchedule = {
+ hour: number;
+ minute: number;
+ /** Legacy single day, Monday = 0. Used when weekdays is absent. */
+ weekday: number;
+ /** Selected days, Monday = 0. When present, must be nonempty and unique. */
+ weekdays?: number[];
+};
+export type ScheduledTaskRun = {
+ id: string; taskId: string; sessionId: string | null;
+ status: "running" | "completed" | "aborted" | "error";
+ errorCode: string | null; startedAt: string; endedAt: string | null;
+};
export type ScheduledTask = {
id: string;
@@ -96,4 +109,7 @@ export type ScheduledTask = {
createdAt: string;
updatedAt: string;
lastRunAt?: string;
+ schedule?: ScheduledTaskSchedule | null;
+ nextRunAt?: string;
+ workspacePath?: string;
};