Skip to content

feat(system_scheduler): 添加系统级定时任务注册和管理功能#24

Open
ravizhan wants to merge 37 commits into
mainfrom
feat/system-schedule
Open

feat(system_scheduler): 添加系统级定时任务注册和管理功能#24
ravizhan wants to merge 37 commits into
mainfrom
feat/system-schedule

Conversation

@ravizhan

@ravizhan ravizhan commented Jul 6, 2026

Copy link
Copy Markdown
Owner

This pull request introduces system-level scheduling support to the scheduler, including UI, API, and store changes, as well as new internationalization strings. Users can now register tasks as system-level, select their scope (user/system), and repair system task registrations. The UI reflects system scheduling status and provides actions for repair.

System-level scheduling support:

  • Added SystemTaskService to app_state.py and a new system_scheduler attribute, preparing the backend for system-level scheduling. [1] [2]
  • Implemented API methods for registering, unregistering, querying status, listing, and repairing system-registered tasks in front/src/services/api/modules/scheduler.ts. [1] [2]
  • Updated the scheduler store to manage system task statuses and registrations, and to call the new API methods. The createTask method now returns the created task for further processing. [1] [2] [3] [4]

UI enhancements for system scheduling:

  • Enhanced the scheduler task dialog (SchedulerTaskDialog.vue) to allow enabling system-level scheduling, selecting scope, and handling registration/unregistration on save. [1] [2] [3] [4] [5] [6]
  • Updated the scheduler task list (SchedulerTaskList.vue) to display system scheduling status with tags, including "In-Process", "Needs Repair", "System·User", and "System·System". [1] [2] [3]
  • Added a "Repair All" button in the scheduler settings section to batch repair system task registrations. [1] [2] [3]

Internationalization (i18n) updates:

  • Added English and Chinese strings for system scheduling, statuses, scope selection, warnings, and repair actions. [1] [2] [3] [4]

Summary by Sourcery

引入操作系统原生的调度与执行协调功能,实现无头模式下的系统级唤醒,并提供健壮的锁机制、执行追踪,以及用于处理冲突和历史记录的 UI 支持。

New Features:

  • 添加运行时 ExecutionCoordinatorExecutionStore,用于集中管理手动和计划任务执行的准入控制与持久化存储。
  • 添加系统级调度器后端和 SystemScheduler,通过无头 CLI 入口在 Windows、macOS 和 Linux 上注册、验证并收敛操作系统原生的唤醒任务。
  • 在调度器 UI 中暴露原生唤醒控制,包括按任务的唤醒开关、来源/状态标签,以及在繁忙或更新进行中场景下的冲突对话框。

Enhancements:

  • 重构 SchedulerManager,使其专注于 APS 任务生命周期,将执行委托给协调器,并在任务创建、更新、暂停、恢复和删除流程中接入原生唤醒注册。
  • 强化更新器,加入显式文件锁、原子化文件替换、崩溃安全的自更新恢复、路径校验以及结构化退出码,以便与运行时安全协同。
  • 加强路径处理和接口加载,通过收紧导入解析、避免不安全的符号链接解析,并改进版本与流水线关闭行为。

Build:

  • 更新 Python 和 Go 依赖,增加原生调度和安全更新器运行所需的文件锁与系统支持库。

CI:

  • 添加单独的 CI 工作流任务,在多种操作系统上构建并运行更新器的 Go 测试,以验证跨平台行为。

Tests:

  • 添加针对执行协调、执行存储、调度器任务编解码、原生 cron 翻译、系统调度器收敛、进程锁以及跨平台更新器行为的单元测试。
  • 扩展调度器和设备连接存储的前端测试,覆盖原生唤醒标志、启动/停止冲突处理,以及更丰富的执行状态和来源展示。
  • 在 CI 中引入专门的更新器 Go 测试任务,在 Linux、macOS 和 Windows 上运行平台特定测试。
Original summary in English

Summary by Sourcery

Introduce OS-native scheduling and execution coordination, enabling headless system-level wakeups with robust locking, execution tracking, and UI support for conflicts and history.

New Features:

  • Add a runtime ExecutionCoordinator and ExecutionStore to centralize admission control and persistence for manual and scheduled task executions.
  • Add system-level scheduler backend and SystemScheduler to register, verify, and converge OS-native wakeup tasks across Windows, macOS, and Linux using headless CLI entrypoints.
  • Expose native wakeup controls in the scheduler UI, including per-task wakeup toggles, origin/status tags, and a conflict dialog for busy or update-in-progress scenarios.

Enhancements:

  • Refactor SchedulerManager to focus on APS job lifecycle, delegating execution to the coordinator and wiring native wakeup registration into task creation, update, pause, resume, and delete flows.
  • Harden the updater with explicit file locking, atomic file replacement, crash-safe self-update recovery, path validation, and structured exit codes to safely coordinate with the runtime.
  • Strengthen path handling and interface loading by tightening import resolution, avoiding unsafe symlink resolution, and improving version and pipeline shutdown behavior.

Build:

  • Update Python and Go dependencies to include file locking and system support libraries required for native scheduling and safe updater operation.

CI:

  • Add a separate CI workflow job to build and run updater Go tests on multiple operating systems to validate cross-platform behavior.

Tests:

  • Add unit tests for execution coordination, execution storage, scheduler job codec, native cron translation, system scheduler convergence, process locking, and updater behavior across platforms.
  • Extend frontend tests for scheduler and device connection stores to cover native wakeup flags, start/stop conflict handling, and enriched execution status and origin display.
  • Introduce a dedicated updater Go test job in CI to run platform-specific tests on Linux, macOS, and Windows.
Original summary in English

Summary by Sourcery

引入操作系统原生的调度与执行协调功能,实现无头模式下的系统级唤醒,并提供健壮的锁机制、执行追踪,以及用于处理冲突和历史记录的 UI 支持。

New Features:

  • 添加运行时 ExecutionCoordinatorExecutionStore,用于集中管理手动和计划任务执行的准入控制与持久化存储。
  • 添加系统级调度器后端和 SystemScheduler,通过无头 CLI 入口在 Windows、macOS 和 Linux 上注册、验证并收敛操作系统原生的唤醒任务。
  • 在调度器 UI 中暴露原生唤醒控制,包括按任务的唤醒开关、来源/状态标签,以及在繁忙或更新进行中场景下的冲突对话框。

Enhancements:

  • 重构 SchedulerManager,使其专注于 APS 任务生命周期,将执行委托给协调器,并在任务创建、更新、暂停、恢复和删除流程中接入原生唤醒注册。
  • 强化更新器,加入显式文件锁、原子化文件替换、崩溃安全的自更新恢复、路径校验以及结构化退出码,以便与运行时安全协同。
  • 加强路径处理和接口加载,通过收紧导入解析、避免不安全的符号链接解析,并改进版本与流水线关闭行为。

Build:

  • 更新 Python 和 Go 依赖,增加原生调度和安全更新器运行所需的文件锁与系统支持库。

CI:

  • 添加单独的 CI 工作流任务,在多种操作系统上构建并运行更新器的 Go 测试,以验证跨平台行为。

Tests:

  • 添加针对执行协调、执行存储、调度器任务编解码、原生 cron 翻译、系统调度器收敛、进程锁以及跨平台更新器行为的单元测试。
  • 扩展调度器和设备连接存储的前端测试,覆盖原生唤醒标志、启动/停止冲突处理,以及更丰富的执行状态和来源展示。
  • 在 CI 中引入专门的更新器 Go 测试任务,在 Linux、macOS 和 Windows 上运行平台特定测试。
Original summary in English

Summary by Sourcery

Introduce OS-native scheduling and execution coordination, enabling headless system-level wakeups with robust locking, execution tracking, and UI support for conflicts and history.

New Features:

  • Add a runtime ExecutionCoordinator and ExecutionStore to centralize admission control and persistence for manual and scheduled task executions.
  • Add system-level scheduler backend and SystemScheduler to register, verify, and converge OS-native wakeup tasks across Windows, macOS, and Linux using headless CLI entrypoints.
  • Expose native wakeup controls in the scheduler UI, including per-task wakeup toggles, origin/status tags, and a conflict dialog for busy or update-in-progress scenarios.

Enhancements:

  • Refactor SchedulerManager to focus on APS job lifecycle, delegating execution to the coordinator and wiring native wakeup registration into task creation, update, pause, resume, and delete flows.
  • Harden the updater with explicit file locking, atomic file replacement, crash-safe self-update recovery, path validation, and structured exit codes to safely coordinate with the runtime.
  • Strengthen path handling and interface loading by tightening import resolution, avoiding unsafe symlink resolution, and improving version and pipeline shutdown behavior.

Build:

  • Update Python and Go dependencies to include file locking and system support libraries required for native scheduling and safe updater operation.

CI:

  • Add a separate CI workflow job to build and run updater Go tests on multiple operating systems to validate cross-platform behavior.

Tests:

  • Add unit tests for execution coordination, execution storage, scheduler job codec, native cron translation, system scheduler convergence, process locking, and updater behavior across platforms.
  • Extend frontend tests for scheduler and device connection stores to cover native wakeup flags, start/stop conflict handling, and enriched execution status and origin display.
  • Introduce a dedicated updater Go test job in CI to run platform-specific tests on Linux, macOS, and Windows.

新功能:

  • 添加无头 CLI 模式,以在不启动 Web 服务器的情况下执行特定的计划任务,并提供结构化的退出码以便与调度器集成。
  • 提供后端 API 和服务,用于在 Windows、macOS 和 Linux 上注册、注销、查询、列出和修复操作系统级计划任务。
  • 在 UI 中暴露系统级调度控制,允许用户启用系统注册、选择用户/系统作用域、查看状态标签,并触发系统任务的批量修复。

改进:

  • 持久化系统任务注册元数据,并在启动时进行自愈,当可执行文件路径变化或操作系统注册缺失时自动修复。
  • 将已删除的调度器任务在系统层面标记为孤立,以便 UI 能显示需要手动清理的操作。
  • 将更新锁机制集成到更新器中,与无头执行协调,避免在更新期间运行任务。

测试:

  • 为系统调度器的后端工具和触发器映射逻辑添加单元测试。
  • 为 SystemTaskService 添加单元测试,覆盖状态持久化、注册/注销流程、修复行为、孤立标记以及状态查询。
Original summary in English

Summary by Sourcery

引入操作系统原生的调度与执行协调功能,实现无头模式下的系统级唤醒,并提供健壮的锁机制、执行追踪,以及用于处理冲突和历史记录的 UI 支持。

New Features:

  • 添加运行时 ExecutionCoordinatorExecutionStore,用于集中管理手动和计划任务执行的准入控制与持久化存储。
  • 添加系统级调度器后端和 SystemScheduler,通过无头 CLI 入口在 Windows、macOS 和 Linux 上注册、验证并收敛操作系统原生的唤醒任务。
  • 在调度器 UI 中暴露原生唤醒控制,包括按任务的唤醒开关、来源/状态标签,以及在繁忙或更新进行中场景下的冲突对话框。

Enhancements:

  • 重构 SchedulerManager,使其专注于 APS 任务生命周期,将执行委托给协调器,并在任务创建、更新、暂停、恢复和删除流程中接入原生唤醒注册。
  • 强化更新器,加入显式文件锁、原子化文件替换、崩溃安全的自更新恢复、路径校验以及结构化退出码,以便与运行时安全协同。
  • 加强路径处理和接口加载,通过收紧导入解析、避免不安全的符号链接解析,并改进版本与流水线关闭行为。

Build:

  • 更新 Python 和 Go 依赖,增加原生调度和安全更新器运行所需的文件锁与系统支持库。

CI:

  • 添加单独的 CI 工作流任务,在多种操作系统上构建并运行更新器的 Go 测试,以验证跨平台行为。

Tests:

  • 添加针对执行协调、执行存储、调度器任务编解码、原生 cron 翻译、系统调度器收敛、进程锁以及跨平台更新器行为的单元测试。
  • 扩展调度器和设备连接存储的前端测试,覆盖原生唤醒标志、启动/停止冲突处理,以及更丰富的执行状态和来源展示。
  • 在 CI 中引入专门的更新器 Go 测试任务,在 Linux、macOS 和 Windows 上运行平台特定测试。
Original summary in English

Summary by Sourcery

Introduce OS-native scheduling and execution coordination, enabling headless system-level wakeups with robust locking, execution tracking, and UI support for conflicts and history.

New Features:

  • Add a runtime ExecutionCoordinator and ExecutionStore to centralize admission control and persistence for manual and scheduled task executions.
  • Add system-level scheduler backend and SystemScheduler to register, verify, and converge OS-native wakeup tasks across Windows, macOS, and Linux using headless CLI entrypoints.
  • Expose native wakeup controls in the scheduler UI, including per-task wakeup toggles, origin/status tags, and a conflict dialog for busy or update-in-progress scenarios.

Enhancements:

  • Refactor SchedulerManager to focus on APS job lifecycle, delegating execution to the coordinator and wiring native wakeup registration into task creation, update, pause, resume, and delete flows.
  • Harden the updater with explicit file locking, atomic file replacement, crash-safe self-update recovery, path validation, and structured exit codes to safely coordinate with the runtime.
  • Strengthen path handling and interface loading by tightening import resolution, avoiding unsafe symlink resolution, and improving version and pipeline shutdown behavior.

Build:

  • Update Python and Go dependencies to include file locking and system support libraries required for native scheduling and safe updater operation.

CI:

  • Add a separate CI workflow job to build and run updater Go tests on multiple operating systems to validate cross-platform behavior.

Tests:

  • Add unit tests for execution coordination, execution storage, scheduler job codec, native cron translation, system scheduler convergence, process locking, and updater behavior across platforms.
  • Extend frontend tests for scheduler and device connection stores to cover native wakeup flags, start/stop conflict handling, and enriched execution status and origin display.
  • Introduce a dedicated updater Go test job in CI to run platform-specific tests on Linux, macOS, and Windows.
Original summary in English

Summary by Sourcery

引入操作系统原生的调度与执行协调功能,实现无头模式下的系统级唤醒,并提供健壮的锁机制、执行追踪,以及用于处理冲突和历史记录的 UI 支持。

New Features:

  • 添加运行时 ExecutionCoordinatorExecutionStore,用于集中管理手动和计划任务执行的准入控制与持久化存储。
  • 添加系统级调度器后端和 SystemScheduler,通过无头 CLI 入口在 Windows、macOS 和 Linux 上注册、验证并收敛操作系统原生的唤醒任务。
  • 在调度器 UI 中暴露原生唤醒控制,包括按任务的唤醒开关、来源/状态标签,以及在繁忙或更新进行中场景下的冲突对话框。

Enhancements:

  • 重构 SchedulerManager,使其专注于 APS 任务生命周期,将执行委托给协调器,并在任务创建、更新、暂停、恢复和删除流程中接入原生唤醒注册。
  • 强化更新器,加入显式文件锁、原子化文件替换、崩溃安全的自更新恢复、路径校验以及结构化退出码,以便与运行时安全协同。
  • 加强路径处理和接口加载,通过收紧导入解析、避免不安全的符号链接解析,并改进版本与流水线关闭行为。

Build:

  • 更新 Python 和 Go 依赖,增加原生调度和安全更新器运行所需的文件锁与系统支持库。

CI:

  • 添加单独的 CI 工作流任务,在多种操作系统上构建并运行更新器的 Go 测试,以验证跨平台行为。

Tests:

  • 添加针对执行协调、执行存储、调度器任务编解码、原生 cron 翻译、系统调度器收敛、进程锁以及跨平台更新器行为的单元测试。
  • 扩展调度器和设备连接存储的前端测试,覆盖原生唤醒标志、启动/停止冲突处理,以及更丰富的执行状态和来源展示。
  • 在 CI 中引入专门的更新器 Go 测试任务,在 Linux、macOS 和 Windows 上运行平台特定测试。
Original summary in English

Summary by Sourcery

Introduce OS-native scheduling and execution coordination, enabling headless system-level wakeups with robust locking, execution tracking, and UI support for conflicts and history.

New Features:

  • Add a runtime ExecutionCoordinator and ExecutionStore to centralize admission control and persistence for manual and scheduled task executions.
  • Add system-level scheduler backend and SystemScheduler to register, verify, and converge OS-native wakeup tasks across Windows, macOS, and Linux using headless CLI entrypoints.
  • Expose native wakeup controls in the scheduler UI, including per-task wakeup toggles, origin/status tags, and a conflict dialog for busy or update-in-progress scenarios.

Enhancements:

  • Refactor SchedulerManager to focus on APS job lifecycle, delegating execution to the coordinator and wiring native wakeup registration into task creation, update, pause, resume, and delete flows.
  • Harden the updater with explicit file locking, atomic file replacement, crash-safe self-update recovery, path validation, and structured exit codes to safely coordinate with the runtime.
  • Strengthen path handling and interface loading by tightening import resolution, avoiding unsafe symlink resolution, and improving version and pipeline shutdown behavior.

Build:

  • Update Python and Go dependencies to include file locking and system support libraries required for native scheduling and safe updater operation.

CI:

  • Add a separate CI workflow job to build and run updater Go tests on multiple operating systems to validate cross-platform behavior.

Tests:

  • Add unit tests for execution coordination, execution storage, scheduler job codec, native cron translation, system scheduler convergence, process locking, and updater behavior across platforms.
  • Extend frontend tests for scheduler and device connection stores to cover native wakeup flags, start/stop conflict handling, and enriched execution status and origin display.
  • Introduce a dedicated updater Go test job in CI to run platform-specific tests on Linux, macOS, and Windows.

@sourcery-ai

sourcery-ai Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

此 PR 引入了一套加固的、与操作系统集成的调度栈:将 APS 任务处理重构为“编解码器 + 执行协调器”架构;在 Windows/macOS/Linux 上通过 SystemScheduler 增加原生用户级唤醒能力;Go 更新器获得更健壮的文件锁定、原子自更新与变更应用逻辑;前端/UI/store 增强了系统级调度控制、手动启动冲突处理以及更丰富的执行历史展示;测试和 CI 也已扩展以覆盖这些行为。

原生 OS 唤醒与任务执行的时序图

sequenceDiagram
    actor OSScheduler
    participant MWUHeadless as main.py(headless)
    participant FastAPI as FastAPIApp
    participant SchedulerManager
    participant ExecutionCoordinator

    OSScheduler->>MWUHeadless: start MWU.exe --scheduled-task <task_id>
    MWUHeadless->>MWUHeadless: acquire_runtime_ownership()
    MWUHeadless->>FastAPI: uvicorn.run(app)
    MWUHeadless->>FastAPI: delegate_native_dispatch(task_id)
    FastAPI->>FastAPI: POST /api/internal/scheduler/native-dispatch
    FastAPI->>SchedulerManager: get_task(task_id)
    SchedulerManager-->>FastAPI: ScheduledTask
    FastAPI->>ExecutionCoordinator: submit_scheduled(task, origin="native")
    ExecutionCoordinator-->>FastAPI: Admission(accepted/skip)
    ExecutionCoordinator->>ExecutionCoordinator: _prepare_and_run(...)
    ExecutionCoordinator-->>OSScheduler: TaskExecution result via UpdateResult / logs
Loading

文件级改动

Change Details Files
将调度执行管线重构为“由编解码器驱动的 APS Job 模型 + 负责准入、设备准备和执行跟踪的 ExecutionCoordinator”,同时移除调度管理器内部的历史记录存储。
  • scheduler_job_codec 辅助函数替换遗留的 execute_scheduled_task 和内联 APS 触发器重建逻辑,统一用于触发器构建/解码以及执行参数(kwargs)编码。
  • 引入 ExecutionCoordinatorExecutionStore,集中处理手动/原生/应用内的执行准入,强制单一活动运行并通过更新门控控制,同时在 SQLite 中持久化 TaskExecution 记录和执行实例声明。
  • 让主 FastAPI 应用初始化 ExecutionCoordinator/ExecutionStore,暴露新的 /api/start/api/stop/api/scheduler/executions 以及 native-dispatch 端点,并通过 scheduled_job_fired 将 APS Job 路由到协调器,而不是直接调用 MaaWorker。
scheduler_manager.py
scheduler_job_codec.py
services/execution_coordinator.py
services/execution_store.py
main.py
models/scheduler.py
services/process_lock.py
app_state.py
新增 SystemScheduler 及平台特定后端,在 Windows、macOS 和 Linux 上为计划任务实现基于 cron 的用户级 OS 唤醒,并在启动时收敛 APS 期望任务与已有原生注册之间的差异。
  • 定义 SystemSchedulerNativeTaskSpec,提供 converge() 用于对比 APS 中启用 wakeup_enabled 的任务与 OS 当前状态,按需注册/注销并验证注册结果;并将其集成进 SchedulerManager 的创建/更新/删除/暂停/恢复流程。
  • 实现 system_scheduler_backend 的平台后端:Windows(schtasks XML)、macOS(launchd LaunchAgents)和 Linux(用户 crontab),包括标识符约定、对导出的注册项进行验证,以及对原生命令路径的安全处理。
  • 新增 services/native_cron 辅助方法,用于解析和校验允许用于原生唤醒的 cron 表达式,将其转化为各平台的调度参数(schtasks 规格、launchd StartCalendarInterval、crontab 行),并编写单元测试以强制这些约束。
services/system_scheduler.py
services/system_scheduler_backend.py
services/native_cron.py
scheduler_manager.py
main.py
tests/unit/test_system_scheduler_converge.py
tests/unit/test_native_cron.py
围绕锁拥有权、原子自更新、路径校验和变更应用语义加固基于 Go 的更新器,同时让协作者可注入以便测试,并添加跨平台测试。
  • updater/main.go 重构为 run(deps, cfg) 函数,引入 deps 结构体用于注入可替换行为;在其中强制严格的锁获取顺序(先 update.lockruntime.lock)、对自更新(.new/.old)进行崩溃恢复,并实现在重启前释放 runtime.lock 的交接序列。
  • 实现原子文件替换工具函数(atomicReplaceFileatomicWriteFilereplaceFileWithBackup),包含 fsync 及目录同步;校验 ChangeLog 路径以防止越过根目录,并重写 getChanges 以并行化哈希计算和错误传播。
  • replaceFilesyncDir、主程序重启配置(restartMain)以及安装所有者捕获实现平台特定版本(Windows 与 Unix),并添加内部 filelock 包以提供跨语言建议性锁,以及用于测试互操作的 lockhelper CLI;扩展 updater/main_test.go 和 filelock 测试以覆盖错误路径和互操作场景。
  • 更新 go.mod/go.sum 和 CI 工作流,在各平台(Linux、macOS、Windows)安装 Go 并新增 updater-tests 任务。
updater/main.go
updater/platform_windows.go
updater/platform_unix.go
updater/internal/filelock/filelock.go
updater/internal/filelock/filelock_test.go
updater/internal/filelock/filelock_subprocess_test.go
updater/cmd/lockhelper/main.go
updater/main_test.go
updater/go.mod
updater/go.sum
.github/workflows/test.yml
增强前端调度 UI、API 和 stores,以支持系统级唤醒标记、更丰富的执行来源/状态展示,以及通过“停止并重启”流程处理手动启动冲突。
  • 修改调度任务模型和列表组件,使用 trigger_config.type 替代 trigger_type,在 ScheduledTask DTO 中增加 wakeup_enabled,在列表和 routine 健康卡片中展示“关闭时仍运行”标签,并更新调度 store 测试以覆盖 wakeup_enabled 行为。
  • 扩展 SchedulerTaskDialog,通过 trigger_config.type 管理触发器类型,增加启用原生唤醒的复选框并对 cron 表达式做适配性校验;在创建/更新请求中发送 wakeup_enabled,并依赖 SchedulerManager 完成原生注册。
  • 优化任务启动/停止 API,使其与 ManualStartPayload/ManualStartResult 协同工作;让 deviceConnection store 构建包含 controller/device/resource 的完整启动载荷,使用 startConflict 状态处理冲突,并提供 stopActiveAndRestart 辅助方法;新增 StartConflictDialog 以及在 TasksView 中的接线以展示冲突解决 UI。
  • 更新调度执行历史 UI 和调度展示工具,使其显示来源徽章(manual/in_app/native)、扩展状态变体(skipped_*missed_deadline)及对应图标/标签,并基于 executionStore 提供数据;相应调整 Vitest 规格。
  • 修改 task.ts 中的 startTask API 封装,解析结构化的启动响应(success/conflict/error),并传播冲突细节,而非使用扁平的布尔值。
  • 调整前端针对 deviceConnection、调度 store、调度 API 以及调度展示工具的测试,以覆盖新的类型、wakeup_enabled 处理、来源/状态标签以及冲突流程。
front/src/types/schedulerModel.ts
front/src/stores/scheduler/scheduler.ts
front/src/stores/scheduler/scheduler.test.ts
front/src/components/settings/scheduler/SchedulerTaskList.vue
front/src/components/settings/dialogs/SchedulerTaskDialog.vue
front/src/components/home/RoutineHealthCard.vue
front/src/components/settings/scheduler/SchedulerExecutionHistory.vue
front/src/utils/scheduler/display.ts
front/src/utils/scheduler/display.test.ts
front/src/stores/device/deviceConnection.ts
front/src/stores/device/deviceConnection.test.ts
front/src/components/settings/scheduler/StartConflictDialog.vue
front/src/views/TasksView.vue
front/src/services/api/modules/task.ts
front/src/services/api/modules/scheduler.ts
front/src/services/api/modules/scheduler.test.ts
收紧 Python 运行时在代理环境、关闭流程和接口加载方面的行为,以支持无头/原生执行并提高测试的健壮性。
  • 修改 maa_worker/agent_service,从 interface_base_dir/version 读取客户端版本,在缺失时进行防御性回退为 "unknown",避免直接依赖当前工作目录中的版本文件。
  • 更新 maa_utils.shutdown,在注销 sinks 和 agents 前停止任何正在运行的任务流水线,防止在关闭或更新期间出现并发任务执行。
  • 放宽 interface_loader 的路径解析,不再强制绝对解析路径,从而简化导入路径检查和测试;并在相关接口模型测试中移除未使用的导入。
  • 新增 tests/conftest.py 中的 main_module fixture,用于在单元测试中导入 main,无需用户集成文件,同时覆写接口加载和 StaticFiles 目录检查;扩展 task_config/interface_loader/interface_model 测试以适配这一新行为。
  • 更新 pyproject.toml 依赖,将 apscheduler 固定为 <4 并添加 filelock,使 Python 运行时锁与 Go filelock 互操作保持一致。
maa_worker/agent_service.py
maa_utils.py
models/interface_loader.py
tests/unit/test_interface_loader.py
tests/unit/test_interface_model.py
tests/unit/test_task_config.py
tests/conftest.py
pyproject.toml

可能关联的 Issue

  • #(unknown):Issue 要求注册 Windows 计划任务定时拉起程序;PR 正式集成系统级调度(含 Windows Task Scheduler 原生唤醒),实现该功能并扩展到其他平台。

Tips and commands

Interacting with Sourcery

  • 触发新的 Review: 在 Pull Request 中评论 @sourcery-ai review
  • 继续讨论: 直接回复 Sourcery 的评审评论。
  • 从评审评论生成 GitHub Issue: 通过回复评审评论让 Sourcery 创建 Issue。也可以在评审评论中回复 @sourcery-ai issue 来创建对应的 Issue。
  • 生成 Pull Request 标题: 在 Pull Request 标题中任意位置写入 @sourcery-ai,即可随时生成标题。也可以在 Pull Request 中评论 @sourcery-ai title 来(重新)生成标题。
  • 生成 Pull Request 摘要: 在 Pull Request 正文中任意位置写入 @sourcery-ai summary,即可在指定位置生成 PR 摘要。也可以在 Pull Request 中评论 @sourcery-ai summary 来(重新)生成摘要。
  • 生成 Reviewer's Guide: 在 Pull Request 中评论 @sourcery-ai guide,即可随时(重新)生成 Reviewer's Guide。
  • 一次性解决所有 Sourcery 评论: 在 Pull Request 中评论 @sourcery-ai resolve,即可将所有 Sourcery 评论标记为已解决。如果你已经处理完所有评论且不希望再看到它们,这会很实用。
  • 全部撤销 Sourcery 评审: 在 Pull Request 中评论 @sourcery-ai dismiss,即可撤销所有现有的 Sourcery 评审。如果你希望从一个全新的评审开始,尤其有用——别忘了再评论 @sourcery-ai review 来触发新的评审!

Customizing Your Experience

前往你的 dashboard

  • 启用或禁用评审功能,例如 Sourcery 自动生成的 Pull Request 摘要、Reviewer's Guide 等。
  • 更改评审语言。
  • 添加、移除或编辑自定义评审指令。
  • 调整其他评审设置。

Getting Help

Original review guide in English

Reviewer's Guide

This PR introduces a hardened, OS-integrated scheduling stack: APS job handling is refactored into a codec and an execution coordinator, native user-level wakeup is added across Windows/macOS/Linux with a SystemScheduler, the Go updater gains robust file locking, atomic self-update, and change application, and the frontend/UI/store gain system-level scheduling controls, conflict handling for manual starts, and richer execution history; tests and CI are extended to cover these behaviors.

Sequence diagram for native OS wakeup and task execution

sequenceDiagram
    actor OSScheduler
    participant MWUHeadless as main.py(headless)
    participant FastAPI as FastAPIApp
    participant SchedulerManager
    participant ExecutionCoordinator

    OSScheduler->>MWUHeadless: start MWU.exe --scheduled-task <task_id>
    MWUHeadless->>MWUHeadless: acquire_runtime_ownership()
    MWUHeadless->>FastAPI: uvicorn.run(app)
    MWUHeadless->>FastAPI: delegate_native_dispatch(task_id)
    FastAPI->>FastAPI: POST /api/internal/scheduler/native-dispatch
    FastAPI->>SchedulerManager: get_task(task_id)
    SchedulerManager-->>FastAPI: ScheduledTask
    FastAPI->>ExecutionCoordinator: submit_scheduled(task, origin="native")
    ExecutionCoordinator-->>FastAPI: Admission(accepted/skip)
    ExecutionCoordinator->>ExecutionCoordinator: _prepare_and_run(...)
    ExecutionCoordinator-->>OSScheduler: TaskExecution result via UpdateResult / logs
Loading

File-Level Changes

Change Details Files
Refactor scheduler execution pipeline into a codec-driven APS job model and an ExecutionCoordinator that owns admission, device preparation, and execution tracking, while removing in-manager history storage.
  • Replace legacy execute_scheduled_task and inline APS trigger reconstruction with scheduler_job_codec helpers for trigger build/decode and execution kwargs encoding.
  • Introduce ExecutionCoordinator and ExecutionStore to centralize manual/native/in-app admission, enforce single active run with update gate, and persist TaskExecution records and occurrence claims in SQLite.
  • Wire the main FastAPI app to initialize ExecutionCoordinator/ExecutionStore, expose new /api/start, /api/stop, /api/scheduler/executions, and native-dispatch endpoints, and route APS jobs through scheduled_job_fired into the coordinator instead of directly invoking MaaWorker.
scheduler_manager.py
scheduler_job_codec.py
services/execution_coordinator.py
services/execution_store.py
main.py
models/scheduler.py
services/process_lock.py
app_state.py
Add SystemScheduler and platform-specific backends to materialize cron-based user-level OS wakeup for scheduled tasks on Windows, macOS, and Linux, plus startup converge logic to reconcile APS desired tasks with existing native registrations.
  • Define SystemScheduler and NativeTaskSpec, with converge() to diff APS wakeup_enabled tasks against OS state, register/unregister as needed, and verify registrations; integrate it into SchedulerManager for create/update/delete/pause/resume flows.
  • Implement system_scheduler_backend backends for Windows (schtasks XML), macOS (launchd LaunchAgents), and Linux (user crontab) including identifier conventions, verification of exported registrations, and safe path handling for native commands.
  • Add services/native_cron helpers to parse and validate cron expressions allowed for native wakeup, translate them into platform-specific scheduling parameters (schtasks specs, launchd StartCalendarInterval, crontab lines), and unit tests to enforce these constraints.
services/system_scheduler.py
services/system_scheduler_backend.py
services/native_cron.py
scheduler_manager.py
main.py
tests/unit/test_system_scheduler_converge.py
tests/unit/test_native_cron.py
Harden the Go-based updater around lock ownership, atomic self-update, path validation, and change application semantics, while making its collaborators injectable for testing and adding cross-platform tests.
  • Refactor updater/main.go into a run(deps, cfg) function with a deps struct for injectable behaviors, enforcing strict lock acquisition ordering (update.lock then runtime.lock), crash recovery of self-update (.new/.old), and a handoff sequence that releases runtime.lock before restart.
  • Implement atomic file replacement utilities (atomicReplaceFile, atomicWriteFile, replaceFileWithBackup) with fsync and directory sync, validate ChangeLog paths to prevent root escapes, and rework getChanges to parallelize hashing and propagate errors.
  • Add platform-specific implementations for replaceFile, syncDir, restartMain configuration, and install owner capture on Windows and Unix, along with an internal filelock package for cross-language advisory locks and a lockhelper CLI for test interop; extend updater/main_test.go and filelock tests to cover error paths and interop.
  • Update go.mod/go.sum and CI workflow to install Go and add an updater-tests job across Linux, macOS, and Windows agents.
updater/main.go
updater/platform_windows.go
updater/platform_unix.go
updater/internal/filelock/filelock.go
updater/internal/filelock/filelock_test.go
updater/internal/filelock/filelock_subprocess_test.go
updater/cmd/lockhelper/main.go
updater/main_test.go
updater/go.mod
updater/go.sum
.github/workflows/test.yml
Enhance frontend scheduling UI, API, and stores to support system-level wakeup flags, richer execution origin/status display, and manual start conflict handling with stop-and-restart flows.
  • Change scheduler task models and list components to use trigger_config.type instead of trigger_type, add wakeup_enabled to ScheduledTask DTOs, surface "runs when closed" tags in lists and routine health cards, and update scheduler store tests to cover wakeup_enabled behavior.
  • Extend SchedulerTaskDialog to manage trigger type via trigger_config.type, add a checkbox for enabling native wakeup with eligibility validation on cron expressions, send wakeup_enabled through create/update payloads, and rely on SchedulerManager for native registration.
  • Refine task start/stop APIs to work with ManualStartPayload/ManualStartResult, teach the deviceConnection store to build full start payloads with controller/device/resource, handle conflicts via startConflict state and a stopActiveAndRestart helper, and add StartConflictDialog plus TasksView wiring to show conflict resolution UI.
  • Update scheduler execution history UI and scheduler display utilities to show origin badges (manual/in_app/native), expanded status variants (skipped_* and missed_deadline) with icons/labels, and executionStore-backed data; adjust related Vitest specs.
  • Modify task.ts startTask API wrapper to parse structured start responses (success/conflict/error) and propagate conflict details instead of using a flat boolean.
  • Adjust front-end tests for deviceConnection, scheduler store, scheduler API, and scheduler display utilities to cover the new types, wakeup_enabled handling, origin/status labeling, and conflict flows.
front/src/types/schedulerModel.ts
front/src/stores/scheduler/scheduler.ts
front/src/stores/scheduler/scheduler.test.ts
front/src/components/settings/scheduler/SchedulerTaskList.vue
front/src/components/settings/dialogs/SchedulerTaskDialog.vue
front/src/components/home/RoutineHealthCard.vue
front/src/components/settings/scheduler/SchedulerExecutionHistory.vue
front/src/utils/scheduler/display.ts
front/src/utils/scheduler/display.test.ts
front/src/stores/device/deviceConnection.ts
front/src/stores/device/deviceConnection.test.ts
front/src/components/settings/scheduler/StartConflictDialog.vue
front/src/views/TasksView.vue
front/src/services/api/modules/task.ts
front/src/services/api/modules/scheduler.ts
front/src/services/api/modules/scheduler.test.ts
Tighten Python runtime behavior around agent environment, shutdown, and interface loading to support headless/native execution and robust testing.
  • Modify MaaWorker agent_service to read the client version from interface_base_dir/version with a defensive fallback to "unknown" when missing, avoiding direct cwd version file assumptions.
  • Update maa_utils.shutdown to stop any running task pipelines before unregistering sinks and agents, preventing concurrent task execution during shutdown or update.
  • Relax interface_loader path resolution to avoid forcing absolute resolved paths, simplifying import path checks and tests; adjust related interface model tests by removing unused imports.
  • Add tests/conftest.py main_module fixture to import main in unit tests without requiring user integration files, overriding interface loading and StaticFiles directory checks, and extend task_config/interface_loader/interface_model tests to work with the new behavior.
  • Update pyproject.toml dependencies to pin apscheduler<4 and add filelock, aligning Python runtime locking with Go filelock interop.
maa_worker/agent_service.py
maa_utils.py
models/interface_loader.py
tests/unit/test_interface_loader.py
tests/unit/test_interface_model.py
tests/unit/test_task_config.py
tests/conftest.py
pyproject.toml

Possibly linked issues

  • #(unknown): Issue 要求注册 Windows 计划任务定时拉起程序;PR 正式集成系统级调度含 Windows Task Scheduler 原生唤醒,实现该功能并扩展到其他平台。

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

ravizhan added 4 commits July 17, 2026 01:41
… and UI integration

- Add cross-platform kernel advisory locks (process_lock.py) with Python/Go interop
- Replace PID/port race with real runtime ownership and bounded update-lock retry
- Headless uses paused APScheduler, rejects disabled jobs, no double-dispatch
- Normative capability matrix: implemented/verified/enabled per platform/scope/trigger
- Correct Windows XML (schema-valid SYSTEM, full semantic verification), macOS (no Year,
  chmod 0600, argv elevation), Linux (shlex quoting, field bounds, atomic cron.d)
- Transactional registration state machine: pending_register/active/orphaned/
  pending_cleanup/error with compensation, recovery, and scope migration rollback
- Orphan intent before APScheduler deletion; corrupt state fails closed
- Updater: app-root locks before staging/self-update, atomic recoverable replacement,
  direct restart confirmation, install-owner restoration, CLOEXEC/sticky-dir
- Frontend: capability-gated system scheduling UI in daisyUI dialog/list/RoutinesView
- Extended SystemTaskStatus with authoritative observed state; no synthesized success
- 315 Python tests, 46 Go tests, 289 frontend tests, all passing
- Fix SystemTaskObservation to match backend ObservedNativeState fields
  (scope/identifier/present/verified/details instead of registered/native_present)
- Fix last_registered_at and scope to be nullable
- Fix fetchAllSystemStatuses mapping to use correct field names
- Remove dead dir() check and fix reason inversion in system_scheduler.py
- Remove redundant test_headless_and_exit_codes.py (superseded by
  test_oracle_phase2_fixes.py real run_headless tests)
- 312 Python tests, 46 Go tests, 289 frontend tests, all passing
@ravizhan
ravizhan force-pushed the feat/system-schedule branch from 7b9a531 to 46b7f38 Compare July 16, 2026 17:42
@ravizhan
ravizhan force-pushed the feat/system-schedule branch from 5b3286a to 18eb36d Compare July 17, 2026 09:23
@ravizhan

Copy link
Copy Markdown
Owner Author

@sourcery-ai guide

@ravizhan

Copy link
Copy Markdown
Owner Author

@sourcery-ai summary

@ravizhan ravizhan self-assigned this Jul 19, 2026
@ravizhan
ravizhan marked this pull request as ready for review July 20, 2026 09:15

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry @ravizhan, your pull request is larger than the review limit of 150000 diff characters

@ravizhan
ravizhan requested a review from Copilot July 20, 2026 09:16

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@greptile-apps

greptile-apps Bot commented Jul 20, 2026

Copy link
Copy Markdown

Confidence Score: 4/5

Native dispatch failures can still be reported as successful process exits.

HTTP rejection and retry exhaustion can return exit code zero without submitting the task.

No additional distinct blocking issue qualifies for this review round.

T-Rex T-Rex Logs

What T-Rex did

  • T-Rex produced a proof for the posted P1 finding.
  • Contract validation verified the HEAD interaction trace changes, confirmed native scheduling state was enabled, and verified that scope controls found=0 and repair controls found=0, while using actual routes, components, and stylesheets; the browser logs showed expected 502 responses after the backend startup blocker, and the scheduler dialog remained usable throughout the validation.

View all artifacts

T-Rex Ran code and verified through T-Rex

Important Files Changed

Filename Overview
main.py Adds headless scheduled-task startup, delegation, execution coordination, and native dispatch APIs.
services/system_scheduler_backend.py Adds platform-specific registration for native scheduled-task commands.
scheduler_manager.py Integrates scheduled-task lifecycle management with native wakeup registration.
services/execution_coordinator.py Centralizes admission, conflict handling, execution tracking, and scheduled-run dispatch.
front/src/components/settings/dialogs/SchedulerTaskDialog.vue Adds native wakeup configuration and updates scheduler task editing and validation.

Comments Outside Diff (1)

  1. General comment

    P1 Scheduler UI does not provide scope selection or registration repair controls

    • Bug
      • The PR validation request claims users can select native scheduling scope and repair registrations. On the actual HEAD /routines dialog, an eligible cron exposes only one “Register as system scheduled task” toggle. Playwright found zero scope controls and zero repair controls, and the captured dialog text contains neither capability. Consequently, users cannot perform two advertised native scheduling workflows from this frontend surface.
    • Cause
      • The changed frontend implements only wakeupEnabled in SchedulerTaskDialog.vue and a wakeup_enabled status marker in SchedulerTaskList.vue; there are no scope or repair fields, buttons, handlers, or service calls in the changed scheduler UI.
    • Fix
      • Add the intended scope selector and registration-repair action to the real scheduler UI, model their API state, and surface repair success/failure. If these capabilities are deliberately out of scope, narrow the PR claim and validation request to the implemented boolean wakeup toggle and list marker.

    T-Rex Ran code and verified through T-Rex

Reviews (3): Last reviewed commit: "refactor(scheduler): 更新 cron 表达式验证逻辑" | Re-trigger Greptile

Comment thread main.py Outdated
Repository owner deleted a comment from greptile-apps Bot Jul 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants