Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(scheduled): add a default-on feature switch in settings
vastsa05fc6f80deed
diff --git a/apps/desktop/electron/main/runtime/provider-catalog.ts b/apps/desktop/electron/main/runtime/provider-catalog.tsindex 082ad59d8..065ba1a00 100644--- a/apps/desktop/electron/main/runtime/provider-catalog.ts+++ b/apps/desktop/electron/main/runtime/provider-catalog.ts@@ -175,6 +175,8 @@ export function createProviderCatalogRuntime({.infiniteProviderRetry === true,keepAwakeWhileRunning: (value as T & { keepAwakeWhileRunning?: unknown }).keepAwakeWhileRunning === true,+ scheduledTasksEnabled: (value as T & { scheduledTasksEnabled?: unknown })+ .scheduledTasksEnabled !== false,jevEnabled: (value as T & { jevEnabled?: unknown }).jevEnabled === true,transcriptDisplayMode:(value as T & { transcriptDisplayMode?: unknown }).transcriptDisplayMode === "flat" ||@@ -197,6 +199,7 @@ export function createProviderCatalogRuntime({defaultCommandShell?: unknown;infiniteProviderRetry?: unknown;keepAwakeWhileRunning?: unknown;+ scheduledTasksEnabled?: unknown;jevEnabled?: unknown;updatePreference?: unknown;lastNotifiedUpdateVersion?: unknown;@@ -229,6 +232,14 @@ export function createProviderCatalogRuntime({errorCode: ErrorCodes.INVALID_PARAMS,});}+ if (+ Object.prototype.hasOwnProperty.call(value, "scheduledTasksEnabled") &&+ typeof value.scheduledTasksEnabled !== "boolean"+ ) {+ throw Object.assign(new Error("scheduledTasksEnabled is invalid"), {+ errorCode: ErrorCodes.INVALID_PARAMS,+ });+ }if (Object.prototype.hasOwnProperty.call(value, "jevEnabled") &&typeof value.jevEnabled !== "boolean"diff --git a/apps/desktop/src/components/SearchDialog.tsx b/apps/desktop/src/components/SearchDialog.tsxindex 62ab6b10f..798a7fc4f 100644--- a/apps/desktop/src/components/SearchDialog.tsx+++ b/apps/desktop/src/components/SearchDialog.tsx@@ -87,6 +87,7 @@ export function SearchDialog({ open, onClose }: { open: boolean; onClose: () =>// Settings search mirrors the rail: developer-only destinations stay out of// the result list while developer mode is off.const developerMode = useAppStore((s) => s.settings?.developerMode === true);+ const scheduledTasksEnabled = useAppStore((s) => s.settings?.scheduledTasksEnabled !== false);const query = useSessionSearchState((state) => state.query);const setQuery = useSessionSearchState((state) => state.setQuery);@@ -206,8 +207,10 @@ export function SearchDialog({ open, onClose }: { open: boolean; onClose: () =>const pageHits = useMemo<PageEntry[]>(() => {const q = query.trim().toLowerCase();if (!q) return [];- return PAGE_ENTRIES.filter((entry) => t(entry.labelKey).toLowerCase().includes(q));- }, [query, t]);+ return PAGE_ENTRIES.filter((entry) =>+ (entry.page !== "scheduled" || scheduledTasksEnabled) &&+ t(entry.labelKey).toLowerCase().includes(q));+ }, [query, t, scheduledTasksEnabled]);const settingsHits = useMemo<SettingsSearchHit[]>(() =>diff --git a/apps/desktop/src/components/Sidebar.tsx b/apps/desktop/src/components/Sidebar.tsxindex d670fca86..9727e8e9e 100644--- a/apps/desktop/src/components/Sidebar.tsx+++ b/apps/desktop/src/components/Sidebar.tsx@@ -2775,17 +2775,19 @@ export function Sidebar({><IconPlug size={14} aria-hidden /></TooltipButton>- <TooltipButton- type="button"- className={`footer-action ${page === "scheduled" ? "active" : ""}`}- data-nav="scheduled"- tooltip={t("scheduled.title")}- ariaLabel={t("scheduled.title")}- onClick={() => setPage("scheduled")}- aria-pressed={page === "scheduled"}- >- <IconClock size={14} aria-hidden />- </TooltipButton>+ {settings?.scheduledTasksEnabled !== false && (+ <TooltipButton+ type="button"+ className={`footer-action ${page === "scheduled" ? "active" : ""}`}+ data-nav="scheduled"+ tooltip={t("scheduled.title")}+ ariaLabel={t("scheduled.title")}+ onClick={() => setPage("scheduled")}+ aria-pressed={page === "scheduled"}+ >+ <IconClock size={14} aria-hidden />+ </TooltipButton>+ )}<NotificationCenter onBeforeOpen={() => closeMenus(false)} /></div>diff --git a/apps/desktop/src/features/app/useAppShellRuntime.tsx b/apps/desktop/src/features/app/useAppShellRuntime.tsxindex b6f4c60e5..4be556a57 100644--- a/apps/desktop/src/features/app/useAppShellRuntime.tsx+++ b/apps/desktop/src/features/app/useAppShellRuntime.tsx@@ -66,6 +66,11 @@ export function useAppShellRuntime() {const handlePlansChanged = useAppStore((s) => s.handlePlansChanged);const abort = useAppStore((s) => s.abort);const settings = useAppStore((s) => s.settings);+ useEffect(() => {+ if (page === "scheduled" && settings?.scheduledTasksEnabled === false) {+ useAppStore.getState().setPage("chat", { record: false });+ }+ }, [page, settings?.scheduledTasksEnabled]);const workPanelOpen = useAppStore((s) => s.workPanelOpen);const workPanelWidth = useAppStore((s) => s.workPanelWidth);const workPanelYieldedWidth = useAppStore((s) => s.workPanelYieldedWidth);diff --git a/apps/desktop/src/features/settings/SettingsPage.tsx b/apps/desktop/src/features/settings/SettingsPage.tsxindex ee235b9e3..e90138a43 100644--- a/apps/desktop/src/features/settings/SettingsPage.tsx+++ b/apps/desktop/src/features/settings/SettingsPage.tsx@@ -470,6 +470,21 @@ export function SettingsPage() {</SettingsRow></SettingsCard>+ <SettingsCard title={t("settings.scheduledTasks")}>+ <SettingsRow+ title={t("settings.scheduledTasks")}+ description={t("settings.scheduledTasksDesc")}+ >+ <SettingsToggle+ checked={settings.scheduledTasksEnabled !== false}+ label={t("settings.scheduledTasks")}+ onChange={() => void saveSettings({+ scheduledTasksEnabled: settings.scheduledTasksEnabled === false,+ })}+ />+ </SettingsRow>+ </SettingsCard>+<RadialMenuSettingssettings={settings}saveSettings={saveSettings}diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex cc02ff60c..30ba3fb4c 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -435,6 +435,7 @@ export function normalizeSettings(settings: AppSettings): AppSettings {sidebarRunningBadge: settings.sidebarRunningBadge !== false,sidebarRunningRail: settings.sidebarRunningRail === true,keepCommandsExpanded: settings.keepCommandsExpanded !== false,+ scheduledTasksEnabled: settings.scheduledTasksEnabled !== false,transcriptDisplayMode: isTranscriptDisplayModeValue(settings.transcriptDisplayMode)? settings.transcriptDisplayMode: "fully-folded",@@ -552,6 +553,14 @@ export function validateSettingsWrite(settings: AppSettings): AppSettings {errorCode: "INVALID_PARAMS",});}+ if (+ Object.prototype.hasOwnProperty.call(settings, "scheduledTasksEnabled") &&+ typeof settings.scheduledTasksEnabled !== "boolean"+ ) {+ throw Object.assign(new Error("scheduledTasksEnabled is invalid"), {+ errorCode: "INVALID_PARAMS",+ });+ }if (Object.prototype.hasOwnProperty.call(value, "jevEnabled") &&typeof value.jevEnabled !== "boolean"diff --git a/apps/desktop/src/lib/settings-search.ts b/apps/desktop/src/lib/settings-search.tsindex a51b86449..3a7365bf1 100644--- a/apps/desktop/src/lib/settings-search.ts+++ b/apps/desktop/src/lib/settings-search.ts@@ -88,6 +88,8 @@ export const SETTINGS_NAV: SettingsNavEntry[] = ["settings.networkRelaxedModeStrictDesc","settings.preventScreenSleep","settings.preventScreenSleepDesc",+ "settings.scheduledTasks",+ "settings.scheduledTasksDesc","settings.sidebar","settings.sidebarRunningIndicators","settings.sidebarRunningIndicatorsDesc",diff --git a/apps/desktop/test/scheduled-settings.test.mjs b/apps/desktop/test/scheduled-settings.test.mjsnew file mode 100644index 000000000..93e4ba49c--- /dev/null+++ b/apps/desktop/test/scheduled-settings.test.mjs@@ -0,0 +1,46 @@+import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));++const renderer = await import("../src/lib/api.ts");+const { createProviderCatalogRuntime } = await import("../electron/main/runtime/provider-catalog.ts");+const { searchSettings } = await import("../src/lib/settings-search.ts");+const { en } = await import("../../../packages/i18n/src/locales/en/index.ts");+const { zhCN } = await import("../../../packages/i18n/src/locales/zh-CN/index.ts");+const { flattenCatalog } = await import("../../../packages/i18n/src/locale-info.ts");+const main = createProviderCatalogRuntime({ getHost: () => null, modelsDevCatalog: {} });++test("scheduled tasks default on and preserve an explicit choice through settings edits", () => {+ const previousWindow = globalThis.window;+ globalThis.window = { piDesktop: { platform: "win32" } };+ try {+ for (const enabled of [undefined, false, true]) {+ const stored = { defaultMode: "agent", theme: "light", enterToSend: true,+ ...(enabled === undefined ? {} : { scheduledTasksEnabled: enabled }) };+ const displayed = renderer.normalizeSettings(main.normalizeSettings(stored));+ assert.equal(displayed.scheduledTasksEnabled, enabled !== false);+ const written = main.validateSettingsWrite(renderer.validateSettingsWrite({ ...displayed, theme: "dark" }));+ assert.equal(written.scheduledTasksEnabled, enabled !== false);+ }+ } finally {+ if (previousWindow === undefined) delete globalThis.window;+ else globalThis.window = previousWindow;+ }+});++test("scheduled task switch rejects non-boolean writes at renderer and main boundaries", () => {+ for (const scheduledTasksEnabled of [undefined, null, "false", 0, {}]) {+ for (const validate of [renderer.validateSettingsWrite, main.validateSettingsWrite]) {+ assert.throws(() => validate({ scheduledTasksEnabled }), /scheduledTasksEnabled is invalid/);+ }+ }+});++test("the scheduled task switch remains searchable in General in English and Chinese", () => {+ for (const [catalog, query] of [[en, "scheduled tasks"], [zhCN, "定时任务"]]) {+ const copy = flattenCatalog(catalog);+ const hits = searchSettings(query, (key) => copy[key] ?? key);+ assert.ok(hits.some((hit) => hit.tab === "general" && hit.rowKey === "settings.scheduledTasks"));+ }+});diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex 49958a549..865bcf5cb 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -4,6 +4,7 @@ mod gen_ui;mod plugin_reviews_rpc;mod remote_tools;mod scheduled_rpc;+mod scheduled_settings;mod scheduled_tools;mod todos;mod window_corner_rpc;@@ -1012,6 +1013,16 @@ fn validate_settings_value(value: &Value) -> Result<(), JsonRpcError> {let Some(object) = value.as_object() else {return Ok(());};+ if object+ .get("scheduledTasksEnabled")+ .is_some_and(|enabled| !enabled.is_boolean())+ {+ return Err(rpc_err(+ 1002,+ "scheduledTasksEnabled must be a boolean",+ "INVALID_PARAMS",+ ));+ }if let Some(policy) = object.get("networkPolicy").filter(|v| !v.is_null()) {let Some(policy) = policy.as_object() else {return Err(rpc_err(@@ -4033,8 +4044,11 @@ async fn handle_request("tools.list" => {let mut definitions = tools::builtin_tool_defs();- if let Some(items) = definitions.as_array_mut() {- items.extend(scheduled_tools::definitions());+ let st = state.lock().await;+ if scheduled_settings::enabled(&st)? {+ if let Some(items) = definitions.as_array_mut() {+ items.extend(scheduled_tools::definitions());+ }}Ok(json!({ "tools": definitions }))}diff --git a/crates/host-core/src/rpc/scheduled_rpc.rs b/crates/host-core/src/rpc/scheduled_rpc.rsindex 979cb72e6..8d68b0f3a 100644--- a/crates/host-core/src/rpc/scheduled_rpc.rs+++ b/crates/host-core/src/rpc/scheduled_rpc.rs@@ -1,3 +1,4 @@+use super::scheduled_settings::{enabled, require_enabled};use super::{json, plan_rpc_err, rpc_err, AppState, JsonRpcError, Value};use crate::{scheduled, sessions};@@ -5,6 +6,10 @@ use crate::{scheduled, sessions};#[path = "scheduled_project_tests.rs"]mod project_tests;+#[cfg(test)]+#[path = "scheduled_settings_tests.rs"]+mod settings_tests;+pub(super) fn handle(st: &AppState, method: &str, params: Value) -> Result<Value, JsonRpcError> {handle_with_workspace_policy(st,@@ -31,6 +36,12 @@ fn handle_with_workspace_policy(workspace: Option<String>,allow_workspace_override: bool,) -> Result<Value, JsonRpcError> {+ if matches!(+ method,+ "scheduled.create" | "scheduled.update" | "scheduled.delete" | "scheduled.run"+ ) {+ require_enabled(st)?;+ }match method {"scheduled.list" => {let tasks = scheduled::list_tasks(&st.db)@@ -249,6 +260,9 @@ fn handle_with_workspace_policy(}))}"scheduled.due" => {+ if !enabled(st)? {+ return Ok(json!({ "ids": [] }));+ }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 }))diff --git a/crates/host-core/src/rpc/scheduled_settings.rs b/crates/host-core/src/rpc/scheduled_settings.rsnew file mode 100644index 000000000..ea5c8b72d--- /dev/null+++ b/crates/host-core/src/rpc/scheduled_settings.rs@@ -0,0 +1,24 @@+use super::{rpc_err, AppState, JsonRpcError, Value};++pub(super) fn enabled(st: &AppState) -> Result<bool, JsonRpcError> {+ let settings = st+ .db+ .get_setting("app")+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;+ Ok(settings+ .as_ref()+ .and_then(|settings| settings.get("scheduledTasksEnabled"))+ .and_then(Value::as_bool)+ .unwrap_or(true))+}++pub(super) fn require_enabled(st: &AppState) -> Result<(), JsonRpcError> {+ if !enabled(st)? {+ return Err(rpc_err(+ 1002,+ "scheduled tasks are disabled",+ "INVALID_PARAMS",+ ));+ }+ Ok(())+}diff --git a/crates/host-core/src/rpc/scheduled_settings_tests.rs b/crates/host-core/src/rpc/scheduled_settings_tests.rsnew file mode 100644index 000000000..f7bbaf1d3--- /dev/null+++ b/crates/host-core/src/rpc/scheduled_settings_tests.rs@@ -0,0 +1,417 @@+use super::*;+use std::sync::Arc;+use tokio::sync::{mpsc, Mutex};++type State = Arc<Mutex<AppState>>;++fn open_state(path: &std::path::Path) -> State {+ let mut st = AppState::open(path).unwrap();+ st.handshook = true;+ Arc::new(Mutex::new(st))+}++async fn request(state: &State, method: &str, params: Value) -> Result<Value, JsonRpcError> {+ super::super::handle_request(state.clone(), method, params, mpsc::unbounded_channel().0).await+}++async fn call(state: &State, method: &str, params: Value) -> Value {+ request(state, method, params).await.unwrap()+}++async fn set_enabled(state: &State, enabled: bool) {+ assert_eq!(+ call(+ state,+ "settings.set",+ json!({"scheduledTasksEnabled":enabled}),+ )+ .await["ok"],+ true+ );+}++fn scheduled_names(definitions: &Value) -> Vec<&str> {+ definitions["tools"]+ .as_array()+ .unwrap()+ .iter()+ .filter_map(|tool| tool["name"].as_str())+ .filter(|name| name.starts_with("ScheduledTask"))+ .collect()+}++fn assert_disabled(error: JsonRpcError) {+ assert_eq!(error.code, 1002);+ assert_eq!(error.data.unwrap()["errorCode"], "INVALID_PARAMS");+ assert_eq!(error.message, "scheduled tasks are disabled");+}++async fn tool(state: &State, session: &str, name: &str, args: Value) -> Value {+ call(+ state,+ "tools.execute",+ json!({"sessionId":session,"toolCallId":name,"toolName":name,"args":args,"mode":"agent"}),+ )+ .await+}++#[tokio::test]+async fn scheduled_settings_defaults_to_enabled_unless_explicitly_false() {+ let dir = tempfile::tempdir().unwrap();+ let state = open_state(dir.path());+ // Legacy/malformed persisted values must not opt a user out; writes through+ // settings.set are validated separately.+ for settings in [+ None,+ Some(json!({"theme":"dark"})),+ Some(json!({"scheduledTasksEnabled":true})),+ Some(json!({"scheduledTasksEnabled":null})),+ Some(json!({"scheduledTasksEnabled":"false"})),+ Some(json!({"scheduledTasksEnabled":0})),+ ] {+ if let Some(settings) = settings {+ state.lock().await.db.set_setting("app", &settings).unwrap();+ }+ let definitions = call(&state, "tools.list", json!({})).await;+ assert_eq!(scheduled_names(&definitions).len(), 4);+ assert!(call(+ &state,+ "scheduled.create",+ json!({"prompt":"Review","cadence":"manual","schedule":null}),+ )+ .await["task"]["id"]+ .is_string());+ }+}++#[tokio::test]+async fn scheduled_settings_set_rejects_non_boolean_without_changing_settings() {+ let dir = tempfile::tempdir().unwrap();+ let state = open_state(dir.path());+ set_enabled(&state, false).await;+ let before = call(&state, "settings.get", json!({})).await;+ for invalid in [+ Value::Null,+ json!(0),+ json!(1),+ json!("false"),+ json!([]),+ json!({}),+ ] {+ let rejected = request(+ &state,+ "settings.set",+ json!({"scheduledTasksEnabled":invalid,"theme":"light"}),+ )+ .await+ .unwrap_err();+ assert_eq!(rejected.code, 1002);+ assert_eq!(rejected.data.unwrap()["errorCode"], "INVALID_PARAMS");+ assert_eq!(call(&state, "settings.get", json!({})).await, before);+ }+}++#[tokio::test]+async fn scheduled_settings_false_survives_restart_and_true_restores_the_saved_task() {+ let dir = tempfile::tempdir().unwrap();+ let state = open_state(dir.path());+ let task = call(+ &state,+ "scheduled.create",+ json!({"title":"Keep","prompt":"Review","cadence":"manual","schedule":null}),+ )+ .await["task"]+ .clone();+ call(+ &state,+ "scheduled.create",+ json!({"prompt":"Paused","cadence":"manual","schedule":null,"enabled":false}),+ )+ .await;+ let before = call(&state, "scheduled.list", json!({})).await;+ set_enabled(&state, false).await;+ call(&state, "settings.set", json!({"theme":"light"})).await;+ drop(state);++ let state = open_state(dir.path());+ assert_eq!(+ call(&state, "settings.get", json!({})).await["scheduledTasksEnabled"],+ false+ );+ assert_eq!(call(&state, "scheduled.list", json!({})).await, before);+ assert!(scheduled_names(&call(&state, "tools.list", json!({})).await).is_empty());+ assert_disabled(+ request(&state, "scheduled.run", json!({"id":task["id"]}))+ .await+ .unwrap_err(),+ );+ set_enabled(&state, true).await;+ assert_eq!(+ scheduled_names(&call(&state, "tools.list", json!({})).await).len(),+ 4+ );+ let run = call(&state, "scheduled.run", json!({"id":task["id"]})).await;+ assert_eq!(run["task"]["id"], task["id"]);+ assert_eq!(run["task"]["enabled"], true);+ assert!(call(&state, "scheduled.list", json!({})).await["tasks"]+ .as_array()+ .unwrap()+ .iter()+ .any(|task| task["prompt"] == "Paused" && task["enabled"] == false));+}++#[tokio::test]+async fn scheduled_settings_disabled_due_manual_auto_and_crud_do_not_mutate() {+ let dir = tempfile::tempdir().unwrap();+ let state = open_state(dir.path());+ let mut tasks = Vec::new();+ for (title, enabled, age) in [+ ("Due", true, 1_000),+ ("Missed", true, 120_000),+ ("Paused", false, 1_000),+ ] {+ let task = call(+ &state,+ "scheduled.create",+ json!({"title":title,"prompt":"Review","cadence":"hourly","enabled":enabled,+ "schedule":{"hour":0,"minute":0,"weekday":0}}),+ )+ .await["task"]+ .clone();+ state.lock().await.db.conn().execute(+ "UPDATE scheduled_tasks SET config_json = json_set(config_json, '$.nextRunAt', ?1) WHERE id = ?2",+ rusqlite::params![crate::db::now_ms() - age, task["id"].as_str().unwrap()],+ ).unwrap();+ tasks.push(task);+ }+ let before = call(&state, "scheduled.list", json!({})).await;+ let sessions_before = call(&state, "session.list", json!({})).await;+ let runs_before = call(&state, "scheduled.listRuns", json!({})).await;+ set_enabled(&state, false).await;+ assert_eq!(call(&state, "scheduled.list", json!({})).await, before);+ assert_eq!(+ call(&state, "scheduled.due", json!({})).await,+ json!({"ids":[]})+ );+ for task in &tasks {+ for automatic in [false, true] {+ assert_disabled(+ request(+ &state,+ "scheduled.run",+ json!({"id":task["id"],"automatic":automatic}),+ )+ .await+ .unwrap_err(),+ );+ }+ }+ for (method, params) in [+ (+ "scheduled.create",+ json!({"prompt":"New","cadence":"manual"}),+ ),+ (+ "scheduled.update",+ json!({"id":tasks[0]["id"],"enabled":false}),+ ),+ ("scheduled.delete", json!({"id":tasks[0]["id"]})),+ ] {+ assert_disabled(request(&state, method, params).await.unwrap_err());+ }+ assert_eq!(call(&state, "scheduled.list", json!({})).await, before);+ assert_eq!(+ call(&state, "session.list", json!({})).await,+ sessions_before+ );+ assert_eq!(+ call(&state, "scheduled.listRuns", json!({})).await,+ runs_before+ );+ assert_eq!(+ call(&state, "scheduled.listRuns", json!({"latestPerTask":true})).await,+ runs_before+ );++ set_enabled(&state, true).await;+ let run = call(+ &state,+ "scheduled.run",+ json!({"id":tasks[0]["id"],"automatic":true}),+ )+ .await;+ assert!(run["sessionId"].is_string());+ assert_ne!(+ run["task"]["nextRunAt"],+ before["tasks"]+ .as_array()+ .unwrap()+ .iter()+ .find(|task| task["id"] == tasks[0]["id"])+ .unwrap()["nextRunAt"]+ );+ assert_eq!(run["task"]["enabled"], true);+}++#[tokio::test]+async fn scheduled_settings_tools_hide_and_reject_stale_calls_including_list() {+ let dir = tempfile::tempdir().unwrap();+ let state = open_state(dir.path());+ call(+ &state,+ "settings.set",+ json!({"defaultPermissionMode":"auto"}),+ )+ .await;+ let session = {+ let st = state.lock().await;+ sessions::create_session(&st.db, None, Some("agent".into()), None, None, None)+ .unwrap()+ .id+ };+ let definitions_before = call(&state, "tools.list", json!({})).await;+ let created = tool(+ &state,+ &session,+ "ScheduledTaskCreate",+ json!({"title":"Keep","prompt":"Review","cadence":"manual"}),+ )+ .await;+ assert_eq!(created["ok"], true, "{created}");+ let id = &created["content"]["task"]["id"];+ assert_eq!(+ tool(&state, &session, "ScheduledTaskList", json!({})).await["ok"],+ true+ );+ let before = call(&state, "scheduled.list", json!({})).await;+ set_enabled(&state, false).await;+ let definitions = call(&state, "tools.list", json!({})).await;+ assert!(scheduled_names(&definitions).is_empty());+ let expected: Vec<_> = definitions_before["tools"]+ .as_array()+ .unwrap()+ .iter()+ .filter(|item| !item["name"].as_str().unwrap().starts_with("ScheduledTask"))+ .cloned()+ .collect();+ assert_eq!(definitions["tools"], json!(expected));+ for (name, args) in [+ ("ScheduledTaskList", json!({})),+ (+ "ScheduledTaskCreate",+ json!({"title":"New","prompt":"Review","cadence":"manual"}),+ ),+ ("ScheduledTaskUpdate", json!({"id":id,"title":"Changed"})),+ ("ScheduledTaskDelete", json!({"id":id})),+ ] {+ let rejected = tool(&state, &session, name, args).await;+ assert_eq!(rejected["ok"], false, "{rejected}");+ assert_eq!(rejected["isError"], true);+ assert_eq!(rejected["errorCode"], "INVALID_PARAMS");+ assert_eq!(rejected["content"]["error"], "scheduled tasks are disabled");+ }+ // The adapter's guard precedes session lookup and argument validation, not+ // only the mutation RPCs (List bypasses those RPCs).+ let params = serde_json::from_value(json!({"sessionId":"missing","toolCallId":"stale","toolName":"ScheduledTaskList","args":null,"mode":"agent"})).unwrap();+ let rejected = {+ let st = state.lock().await;+ super::super::scheduled_tools::execute(&st, ¶ms)+ };+ assert_eq!(rejected.error_code.as_deref(), Some("INVALID_PARAMS"));+ assert_eq!(call(&state, "scheduled.list", json!({})).await, before);+ set_enabled(&state, true).await;+ assert_eq!(+ tool(&state, &session, "ScheduledTaskList", json!({})).await["content"],+ before+ );+ assert_eq!(+ tool(&state, &session, "ScheduledTaskDelete", json!({"id":id})).await["ok"],+ true+ );+}++#[tokio::test]+async fn scheduled_settings_disabled_keeps_import_history_and_in_flight_completion_available() {+ let dir = tempfile::tempdir().unwrap();+ let state = open_state(dir.path());+ let task = call(+ &state,+ "scheduled.create",+ json!({"prompt":"Review","cadence":"manual","schedule":null}),+ )+ .await["task"]+ .clone();+ let run = call(&state, "scheduled.run", json!({"id":task["id"]})).await;+ let task_before = call(&state, "scheduled.list", json!({})).await;+ set_enabled(&state, false).await;+ assert_eq!(+ call(+ &state,+ "scheduled.finishRun",+ json!({"runId":run["runId"],"status":"completed"})+ )+ .await["ok"],+ true+ );+ let history = call(&state, "scheduled.listRuns", json!({"taskId":task["id"]})).await;+ assert_eq!(history["runs"][0]["status"], "completed");+ assert_eq!(history["runs"][0]["sessionId"], run["sessionId"]);+ assert_eq!(call(&state, "scheduled.list", json!({})).await, task_before);+ assert_eq!(call(&state, "scheduled.import", json!({"tasks":[{"id":"legacy","prompt":"Keep imported","cadence":"manual","enabled":false}]})).await["imported"], 1);+ assert_eq!(+ call(&state, "scheduled.list", json!({})).await["tasks"]+ .as_array()+ .unwrap()+ .len(),+ 2+ );+ assert_disabled(+ request(&state, "scheduled.run", json!({"id":"legacy"}))+ .await+ .unwrap_err(),+ );+ drop(state);+ let state = open_state(dir.path());+ assert_eq!(+ call(&state, "scheduled.listRuns", json!({"taskId":task["id"]})).await,+ history+ );+ assert_eq!(+ call(&state, "settings.get", json!({})).await["scheduledTasksEnabled"],+ false+ );+}++#[tokio::test]+async fn scheduled_settings_read_errors_propagate_instead_of_enabling_execution() {+ let dir = tempfile::tempdir().unwrap();+ let state = open_state(dir.path());+ set_enabled(&state, false).await;+ state+ .lock()+ .await+ .db+ .conn()+ .execute(+ "UPDATE kv SET value_json = '{' WHERE ns = 'app' AND key = 'app'",+ [],+ )+ .unwrap();+ for method in [+ "tools.list",+ "scheduled.due",+ "scheduled.run",+ "scheduled.create",+ "scheduled.update",+ "scheduled.delete",+ ] {+ let error = request(&state, method, json!({})).await.unwrap_err();+ assert_eq!(error.code, 1000, "{method}");+ assert_eq!(error.data.unwrap()["errorCode"], "INTERNAL", "{method}");+ }+ let params = serde_json::from_value(json!({"sessionId":"missing","toolCallId":"stale","toolName":"ScheduledTaskList","args":{},"mode":"agent"})).unwrap();+ let st = state.lock().await;+ let result = super::super::scheduled_tools::execute(&st, ¶ms);+ assert!(!result.ok);+ assert_eq!(result.error_code.as_deref(), Some("INTERNAL"));+}diff --git a/crates/host-core/src/rpc/scheduled_tools.rs b/crates/host-core/src/rpc/scheduled_tools.rsindex 584e1c883..2866f9100 100644--- a/crates/host-core/src/rpc/scheduled_tools.rs+++ b/crates/host-core/src/rpc/scheduled_tools.rs@@ -43,6 +43,7 @@ fn invalid(message: &str) -> JsonRpcError {}fn execute_inner(st: &AppState, p: &ToolsExecuteParams) -> Result<Value, JsonRpcError> {+ super::scheduled_settings::require_enabled(st)?;// The index row answers both questions this needs — does the session exist,// and what is its project? — so no transcript is materialized here.let summary = sessions::session_summary(&st.db, &p.session_id)diff --git a/docs/guide/automations.md b/docs/guide/automations.mdindex 7d3f5547b..0122a8f85 100644--- a/docs/guide/automations.md+++ b/docs/guide/automations.md@@ -6,7 +6,13 @@ description: Configure recurring local agent tasks and review their results.# Scheduled tasksOpen the clock in the sidebar footer, or search for **Scheduled** with-Ctrl/Cmd+K. Create a task with a name, prompt and cadence:+Ctrl/Cmd+K.++Scheduled tasks are enabled by default. Turn them off or back on in+**Settings → General → Scheduled tasks**. Turning the switch off hides the+clock and Scheduled search entry, disables the AI task tools, and prevents new+runs. Existing tasks and history stay saved, and an already-running task can+finish. Search still finds the settings switch while the feature is off.New tasks start in Manual. Choose a recurring cadence to enable automation.@@ -45,6 +51,8 @@ scheduler or cron-expression support is installed.Scheduled tasks now execute while the desktop is running, with hourly intervals and time/weekdayconfiguration, per-task project/permission/model choices, editing, pause/resume, a visible clock entry and run history.Existing data stays readable; old cadence-only records do not start automatically.+The default-on Scheduled tasks switch in General settings now lets you turn+the feature off without deleting task definitions or run history.## Manage tasks in a conversationdiff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.mdindex afa703b3a..a89951888 100644--- a/docs/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md@@ -1414,6 +1414,14 @@ ScheduledTaskUpdate and ScheduledTaskDelete tools. They run throughthe scheduled RPC domain handlers. List is low risk; mutations require normalapproval in Ask/Accept Edits. Plan/Goal deny all four even under Auto.+`AppSettings.scheduledTasksEnabled` is an optional boolean, enabled when absent.+When false, `tools.list` omits all four tools and stale calls are rejected.+The Host returns no ids from `scheduled.due` and rejects `scheduled.run`,+create/update/delete with `INVALID_PARAMS` before admission or mutation.+Read/import/finish-run operations remain available so saved data and in-flight+completion are preserved. Re-enabling retains per-task enable states and the+existing no-catch-up due-time policy; no schema or protocol version changes.+The Host rechecks durable session mode and derives project scope from thecalling session, never the foreground workspace or model-supplied paths.Create binds that scope; list filters it; update/delete require matching scope.diff --git a/docs/spec/04-ux/01-ui-ia.md b/docs/spec/04-ux/01-ui-ia.mdindex a940d74e9..082423213 100644--- a/docs/spec/04-ux/01-ui-ia.md+++ b/docs/spec/04-ux/01-ui-ia.md@@ -303,6 +303,11 @@ destination, chat as the home surface, tools and permissions inline.focus.### 3.3 Scheduled+Settings → General → Scheduled tasks controls this feature, on by default+(`scheduledTasksEnabled` absent or true). Off hides the footer and search page+entries and prevents new runs without deleting tasks or run history. The+settings switch remains searchable so the feature can be re-enabled.+A task column beside the selected task's page, with an explicit create/edit form, a cadence dropdown, time,next occurrence, saved project, per-task permission/model selection, a per-task conversation mode (a new conversation per run, or one conversation every run continues), pause/resume and delete confirmation. Hourlyschedules repeat at one-hour intervals without a time selector. An intervaldiff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.mdindex 76394c01b..fb1679a3a 100644--- a/docs/spec/04-ux/06-settings-ia.md+++ b/docs/spec/04-ux/06-settings-ia.md@@ -192,6 +192,13 @@ Settings is a **full-window page** that replaces the app sidebar + main chrome (the previous choice instead of resetting it. The affordances themselves aredescribed in[01-ui-ia.md §3.2](01-ui-ia.md#32-sidebar-project-groups).+- **Scheduled tasks** card: an app-wide switch persisting as optional+ `AppSettings.scheduledTasksEnabled`, on when absent or true. Off hides the+ footer clock and global-search page entry, leaves the route if already open,+ withholds scheduled Agent tools, and blocks new manual/automatic runs and task+ edits at the Host. Existing task enable states, schedules, and history remain+ unchanged; active runs can finish. Re-enabling restores access and resumes+ normal due-time admission without replaying missed occurrences.- **Network** card:- **Proxy**: a segmented control — System, Direct, Custom. System is thedefault and lets Chromium follow the OS proxy; Direct disables the proxy;diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 58d3855b8..d1d973d13 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -40,6 +40,24 @@## 1. Goals+### E2E-SCHEDULED-settings-switch++- **Preconditions:** Candidate Desktop, Host and reused local dependencies;+ isolated profile/data/project and the local scheduled-model fixture.+- **Steps:** With a saved task, open Settings → General, observe the default-on+ Scheduled tasks switch, turn it off, return to the app and search.+ Reload the renderer, verify the saved off state, re-enable and run the task.+- **Expected:** The footer and page-search entry disappear while off; the+ settings row remains searchable. New runs are rejected, task configuration+ and history survive, reload preserves the choice and re-enabling restores+ the same task and normal execution. Host tests also cover due admission,+ stale tools, restart and completion of an already-admitted run while off.+- **Coverage:** `node scripts/e2e-scheduled.mjs --settings-switch-only`,+ `apps/desktop/test/scheduled-settings.test.mjs`, Host scheduled settings tests.+- **Specs:** `04-ux/06-settings-ia.md`, `04-ux/01-ui-ia.md` §3.3.+- **Acceptance:** No data/schema migration; default-on backwards compatibility.+- **Milestone:** Maintenance. **Status:** Automated.+### E2E-PROVIDER-retry-backoff-is-not-idle- **Entry:** Build shared and the production sidecar bundle, then rundiff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex ed37c88eb..34e530f7a 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -805,6 +805,8 @@ export const de = {"dismiss": "Verwerfen"},"settings": {+ scheduledTasks: "Geplante Aufgaben",+ scheduledTasksDesc: "Wenn deaktiviert, werden geplante Aufgaben ausgeblendet und keine neuen Ausführungen gestartet. Vorhandene Aufgaben und der Verlauf bleiben erhalten.",storage: {unavailableHint: "Das Speicherverzeichnis ist derzeit nicht verfügbar. Verbinden Sie das Laufwerk vor dem Start erneut. Die App erstellt keine leeren Daten und wechselt nicht in ein anderes Verzeichnis.",browserSource: "Quelle der Browserdaten",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex d707cddfc..b0cd39a02 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -1515,6 +1515,8 @@ sklm: {inlineVisualizationsDesc: "Show the interactive HTML cards the agent writes into the session's visualization directory. Off by default: the prompt advertises no visualization directory, the visualize skill is withheld, and existing reference lines stay hidden.",preventScreenSleep: "Prevent screen sleep",preventScreenSleepDesc: "Keep the display awake while the app is running. Uses system power management APIs on all platforms.",+ scheduledTasks: "Scheduled tasks",+ scheduledTasksDesc: "Turning this off hides scheduled tasks and stops new runs. Existing tasks and history are kept.",windowTranslucency: "Translucent window",windowTranslucencyDesc: "Keep the macOS window translucent over the desktop blur, which is the default. It costs more GPU while the window is visible; turn it off for an opaque window with the lowest idle load. A change applies after a restart.",windowTranslucencyRestart: "Restart to apply",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 27400a7b8..16164263b 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -805,6 +805,8 @@ export const es = {"dismiss": "Descartar"},"settings": {+ scheduledTasks: "Tareas programadas",+ scheduledTasksDesc: "Al desactivar, se ocultan las tareas programadas y se detienen las nuevas ejecuciones. Se conservan las tareas existentes y el historial.",storage: {unavailableHint: "El directorio de almacenamiento no está disponible. Vuelve a conectar la unidad antes de iniciar; la aplicación no creará datos vacíos ni cambiará a otro directorio.",browserSource: "Origen de los datos del navegador",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 20f418ee0..b7691e6da 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -805,6 +805,8 @@ export const fr = {"dismiss": "Ignorer"},"settings": {+ scheduledTasks: "Tâches planifiées",+ scheduledTasksDesc: "Désactiver masque les tâches planifiées et empêche de nouvelles exécutions. Les tâches existantes et leur historique sont conservés.",storage: {unavailableHint: "Le dossier de stockage est actuellement indisponible. Reconnectez le disque avant de démarrer ; l’application ne créera pas de données vides et ne changera pas de dossier.",browserSource: "Source des données du navigateur",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex f32595497..f71e3aee0 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -1511,6 +1511,8 @@ sklm: {inlineVisualizationsDesc: "에이전트가 세션 시각화 디렉터리에 작성한 대화형 HTML 카드를 대화에 표시합니다. 기본적으로 꺼져 있습니다: 프롬프트에 시각화 디렉터리를 제공하지 않고 visualize 스킬을 숨기며 기존 참조 줄도 표시하지 않습니다.",preventScreenSleep: "화면 절전 방지",preventScreenSleepDesc: "앱이 실행되는 동안 화면이 꺼지지 않도록 합니다. 모든 플랫폼에서 시스템 전원 관리 API를 사용합니다.",+ scheduledTasks: "예약 작업",+ scheduledTasksDesc: "끄면 예약 작업이 숨겨지고 새 실행이 중지됩니다. 기존 작업과 기록은 유지됩니다.",windowTranslucency: "반투명 창",windowTranslucencyDesc: "macOS 창을 데스크톱 흐림 위에 반투명하게 유지합니다(기본값). 창이 보이는 동안 GPU를 더 사용하므로, 유휴 부하를 가장 낮추려면 끄세요. 변경 사항은 재시작 후 적용됩니다.",windowTranslucencyRestart: "적용하려면 재시작",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex 4ee0b61d2..3e10fabf8 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -1474,6 +1474,8 @@ export const ptBR = {inlineVisualizationsDesc: "Mostra os cartões HTML interativos que o agente escreve no diretório de visualizações da sessão. Desativado por padrão: o prompt não anuncia diretório de visualizações, a habilidade visualize fica oculta e as linhas de referência existentes permanecem escondidas.",preventScreenSleep: "Impedir suspensão da tela",preventScreenSleepDesc: "Mantém a tela ligada enquanto o app está em execução. Usa as APIs de gerenciamento de energia do sistema em todas as plataformas.",+ scheduledTasks: "Tarefas agendadas",+ scheduledTasksDesc: "Ao desativar, oculta as tarefas agendadas e impede novas execuções. As tarefas existentes e o histórico são mantidos.",windowTranslucency: "Janela translúcida",windowTranslucencyDesc: "Mantém a janela do macOS translúcida sobre o desfoque da área de trabalho, que é o padrão. Usa mais GPU enquanto a janela está visível; desative para uma janela opaca com a menor carga ociosa. A alteração vale após reiniciar.",windowTranslucencyRestart: "Reiniciar para aplicar",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 880ee1a77..7a9f1319c 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -1505,6 +1505,8 @@ sklm: {inlineVisualizationsDesc: "Aracının oturumun görselleştirme dizinine yazdığı etkileşimli HTML kartlarını gösterir. Varsayılan olarak kapalı: istem görselleştirme dizinini bildirmez, visualize becerisi gizlenir ve mevcut referans satırları gösterilmez.",preventScreenSleep: "Ekran uykusunu engelle",preventScreenSleepDesc: "Uygulama çalışırken ekranı açık tutar. Tüm platformlarda sistem güç yönetimi API'lerini kullanır.",+ scheduledTasks: "Zamanlanmış görevler",+ scheduledTasksDesc: "Kapatıldığında zamanlanmış görevler gizlenir ve yeni çalıştırmalar durur. Mevcut görevler ve geçmiş korunur.",windowTranslucency: "Saydam pencere",windowTranslucencyDesc: "macOS penceresini masaüstü bulanıklığı üzerinde saydam tutar; varsayılan budur. Pencere görünürken daha fazla GPU kullanır; en düşük boşta yük için kapatın. Değişiklik yeniden başlatmadan sonra uygulanır.",windowTranslucencyRestart: "Uygulamak için yeniden başlatın",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex d245d6425..d6ab6352d 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -1495,6 +1495,8 @@ sklm: {inlineVisualizationsDesc: "在对话中显示智能体写入会话可视化目录的交互式 HTML 卡片。默认关闭:不向模型提供可视化目录,同时隐藏 visualize 技能,历史引用行也不再显示。",preventScreenSleep: "阻止屏幕休眠",preventScreenSleepDesc: "应用运行时保持屏幕常亮,跨平台使用系统电源管理接口。",+ scheduledTasks: "定时任务",+ scheduledTasksDesc: "关闭后隐藏定时任务入口并停止启动新任务,已有任务和历史记录保留。",windowTranslucency: "窗口透明效果",windowTranslucencyDesc: "让 macOS 窗口保持透明并显示桌面模糊背景(默认开启)。窗口可见时会占用更多 GPU;关闭后使用不透明窗口,空闲占用最低。修改后需重启生效。",windowTranslucencyRestart: "重启后生效",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex a4a62e24b..6615ea19d 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -1495,6 +1495,8 @@ sklm: {inlineVisualizationsDesc: "在對話中顯示智慧代理寫入工作階段視覺化目錄的互動式 HTML 卡片。預設停用:不向模型提供視覺化目錄,同時隱藏 visualize 技能,歷史引用行也不再顯示。",preventScreenSleep: "防止螢幕休眠",preventScreenSleepDesc: "應用程式執行時保持螢幕常亮,跨平台使用系統電源管理介面。",+ scheduledTasks: "排程任務",+ scheduledTasksDesc: "關閉後隱藏排程任務入口並停止啟動新任務,現有任務與歷史記錄會保留。",windowTranslucency: "視窗透明效果",windowTranslucencyDesc: "讓 macOS 視窗保持透明並顯示桌面模糊背景(預設開啟)。視窗可見時會佔用更多 GPU;關閉後使用不透明視窗,閒置佔用最低。修改後需重新啟動生效。",windowTranslucencyRestart: "重新啟動後生效",diff --git a/packages/shared/src/types/settings.ts b/packages/shared/src/types/settings.tsindex 7bdc33a35..3e17e2571 100644--- a/packages/shared/src/types/settings.ts+++ b/packages/shared/src/types/settings.ts@@ -63,6 +63,8 @@ export type AppSettings = {jevEnabled?: boolean;/** Prevent idle system sleep while this desktop app runs; off when absent. */keepAwakeWhileRunning?: boolean;+ /** Enable scheduled task UI, tools and new runs. Absent means enabled. */+ scheduledTasksEnabled?: boolean;/** Configured command shell for the agent Bash protocol tool. */defaultCommandShell?: CommandShellId;/** @deprecated Retained for one-time migration into pi.prompt-enhancement. */diff --git a/scripts/e2e-scheduled.mjs b/scripts/e2e-scheduled.mjsindex 5043c5ada..4d176c360 100644--- a/scripts/e2e-scheduled.mjs+++ b/scripts/e2e-scheduled.mjs@@ -11,6 +11,7 @@ import { Host, resolveHostBinary } from "./e2e/host.mjs";import { resolveElectronBinary } from "./e2e/boot.mjs";import { waitFor } from "./e2e/wait.mjs";import { scheduledModelFixture } from "./e2e/scheduled-model.mjs";+import { verifyScheduledSettingsSwitch } from "./e2e/scheduled-settings.mjs";const root = mkdtempSync(join(tmpdir(), "pi-scheduled-e2e-"));const dataDir = join(root, "data"),@@ -18,6 +19,8 @@ const dataDir = join(root, "data"),alternateProject = join(root, "project-alt");mkdirSync(project);mkdirSync(alternateProject);+const home = join(root, "home");+mkdirSync(home);// The Host canonicalizes the workspace path it is given, and macOS hands out// `TMPDIR` under the `/var` symlink, so compare resolved paths on both sides.const canonical = (value) => realpathSync(value).replaceAll("\\", "/").toLowerCase();@@ -26,7 +29,7 @@ if (evidence) mkdirSync(evidence, { recursive: true });const model = scheduledModelFixture();const server = createServer(model.handler);await new Promise((done) => server.listen(0, "127.0.0.1", done));-const host = new Host(resolveHostBinary(), dataDir);+const host = new Host(resolveHostBinary(), dataDir, { env: { HOME: home, USERPROFILE: home } });await host.start();await host.call("workspace.set", { path: project });const { provider } = await host.call("providers.create", {@@ -69,6 +72,8 @@ const { appDir, electronBinary } = resolveElectronBinary();const port = Number(process.env.PI_SCHEDULED_CDP_PORT || 9378);const env = {...process.env,+ HOME: home,+ USERPROFILE: home,PI_DESKTOP_DATA_DIR: dataDir,PI_DESKTOP_START_MAXIMIZED: "0",ELECTRON_RENDERER_URL: "",@@ -217,6 +222,15 @@ try {await screenshot("failure.png");throw error;}+ if (process.argv.includes("--settings-switch-only")) {+ const { task } = await invoke("scheduledCreate", {+ title: "Project review", prompt: "Reply OK", cadence: "manual", permissionMode: "auto",+ });+ await verifyScheduledSettingsSwitch({ task, invoke, evaluate, click, fill, key, send });+ await click("Run now");+ await waitFor(async () => (await invoke("scheduledListRuns")).runs[0]?.status === "completed", 30_000, "re-enabled task runs through the local model");+ console.log("PASS re-enabled task executes through real Host and agent sidecar");+ } else {await evaluate(`document.querySelector('[data-nav="scheduled"]').click()`);await waitFor(() => evaluate(`document.querySelector('.page-title')?.textContent === 'Scheduled'`),@@ -379,6 +393,7 @@ try {"edit",);await screenshot("after-tasks.png");+ await verifyScheduledSettingsSwitch({ task: { ...task, title: "Project review" }, invoke, evaluate, click, fill, key, send });await click("Run now");let runs;await waitFor(@@ -463,6 +478,7 @@ try {console.log("PASS scheduled user path: create, time, weekday dropdown/multiple selection, validation, keyboard, hourly interval, edit, pause/resume, manual run, transcript, automatic run, delete",);+ }console.log(`Evidence: ${evidence ?? "not requested"}; isolated profile: ${root}`);} catch (error) {console.error(output.slice(-4000));diff --git a/scripts/e2e/scheduled-settings.mjs b/scripts/e2e/scheduled-settings.mjsnew file mode 100644index 000000000..dc774bae3--- /dev/null+++ b/scripts/e2e/scheduled-settings.mjs@@ -0,0 +1,34 @@+import assert from "node:assert/strict";+import { waitFor } from "./wait.mjs";++export async function verifyScheduledSettingsSwitch({ task, invoke, evaluate, click, fill, key, send }) {+ const beforeDisable = await invoke("scheduledList");+ await evaluate(`document.querySelector('[data-nav="settings"]').click()`);+ await click("General", ".settings-nav-item");+ await waitFor(() => evaluate(`document.querySelector('[role="switch"][aria-label="Scheduled tasks"]')?.getAttribute('aria-checked') === 'true'`), 10_000, "scheduled tasks enabled by default");+ await click("Scheduled tasks", '[role="switch"]', true);+ await waitFor(async () => (await invoke("settingsGet")).scheduledTasksEnabled === false, 5000, "disabled setting persisted");+ await click("Back to app", '[data-nav="back-to-app"]');+ assert.equal(await evaluate(`!!document.querySelector('[data-nav="scheduled"]')`), false);+ assert.deepEqual(await invoke("scheduledList"), beforeDisable, "switch cannot rewrite individual tasks");+ await assert.rejects(() => invoke("scheduledExecute", task.id), /INVALID_PARAMS/);+ await click("Search", "button", true);+ await fill(".search-input", "Scheduled");+ await waitFor(() => evaluate(`document.querySelector('.search-dialog')?.innerText.includes('Scheduled tasks')`), 5000, "settings switch remains discoverable");+ assert.equal(await evaluate(`[...document.querySelectorAll('.search-item-title')].some(e => e.textContent.trim() === 'Scheduled')`), false, "disabled page is absent from search");+ await key("Escape", 27);+ await send("Page.reload");+ await waitFor(() => evaluate(`!!document.querySelector('[data-nav="settings"]') && !document.querySelector('.startup-splash')`), 30_000, "renderer reload with saved settings");+ assert.equal(await evaluate(`!!document.querySelector('[data-nav="scheduled"]')`), false);+ await evaluate(`document.querySelector('[data-nav="settings"]').click()`);+ await click("General", ".settings-nav-item");+ await waitFor(() => evaluate(`document.querySelector('[role="switch"][aria-label="Scheduled tasks"]')?.getAttribute('aria-checked') === 'false'`), 10_000, "disabled switch restored");+ await click("Scheduled tasks", '[role="switch"]', true);+ await waitFor(async () => (await invoke("settingsGet")).scheduledTasksEnabled === true, 5000, "enabled setting persisted");+ await click("Back to app", '[data-nav="back-to-app"]');+ await waitFor(() => evaluate(`!!document.querySelector('[data-nav="scheduled"]')`), 5000, "scheduled entry restored");+ await evaluate(`document.querySelector('[data-nav="scheduled"]').click()`);+ await waitFor(() => evaluate(`!!document.querySelector('.page-title') && document.body.innerText.includes(${JSON.stringify(task.title)})`), 10_000, "same scheduled task restored");+ assert.deepEqual(await invoke("scheduledList"), beforeDisable);+ console.log("PASS scheduled settings: default on, disable, hide navigation/search, reject runs, reload, re-enable, preserve tasks");+}