Skip to content

Add wait mode for manual cron runs - #81929

Merged
galiniliev merged 4 commits into
openclaw:mainfrom
ificator:ificator/cronrunwait
May 16, 2026
Merged

galiniliev merged 4 commits into
openclaw:mainfrom
ificator:ificator/cronrunwait

Conversation

@ificator

@ificator ificator commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: openclaw cron run <job-id> returned after enqueueing a manual run, so shutdown/pre-stop automation could not directly wait for the cron work to finish.
  • Why it matters: container idle-shutdown hooks need a deterministic way to block until critical maintenance jobs, such as memory flush cron jobs, reach a terminal status.
  • What changed: added openclaw cron run --wait, configurable --wait-timeout and --poll-interval, exact runId filtering for cron.runs, protocol/schema wiring, generated Swift protocol sync, focused tests, and docs.
  • What did NOT change (scope boundary): default openclaw cron run <job-id> behavior remains non-blocking; the Gateway cron.run RPC still enqueues rather than holding the request open; no cron scheduler semantics changed.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

  • Closes #
  • Related #
  • This PR fixes a bug or regression

Real behavior proof (required for external PRs)

  • Behavior addressed: openclaw cron run <job-id> --wait waits for the returned manual run runId to finish, returns completed: true, reports the terminal status, and exits successfully only for ok. openclaw cron runs --run-id can retrieve the exact completed run.
  • Real environment tested: Docker Desktop Linux container using node:24-bookworm, repository copied into a Linux volume, isolated OPENCLAW_STATE_DIR, real OpenClaw Gateway on loopback with token auth, and CLI commands run through corepack pnpm openclaw against that Gateway. Token value below is redacted.
  • Exact steps or command run after this patch: Started openclaw gateway run --dev --reset --port 18789 --bind loopback --auth token --token [redacted-test-token], created a real system-event cron job with openclaw cron add --token [redacted-test-token] --name "wait proof" --every 1h --system-event "cron wait proof" --json, ran openclaw cron run <job-id> --token [redacted-test-token] --wait --wait-timeout 30s --poll-interval 500ms, then queried openclaw cron runs --token [redacted-test-token] --id <job-id> --run-id <run-id> --limit 1.
  • Evidence after fix (screenshot, recording, terminal capture, console output, redacted runtime log, linked artifact, or copied live output):
container_node=v24.15.0
pnpm=11.1.0
dependencies_already_installed
starting_gateway
gateway_port_ready=127.0.0.1:18789
creating_cron_job
$ node scripts/run-node.mjs cron add --token [redacted-test-token] --name 'wait proof' --every 1h --system-event 'cron wait proof' --json
cron add output:
{
  "id": "8674012e-1ad6-4856-ad76-08856d1e61f8",
  "name": "wait proof",
  "enabled": true,
  "createdAtMs": 1778798176117,
  "updatedAtMs": 1778798176117,
  "schedule": {
    "kind": "every",
    "everyMs": 3600000,
    "anchorMs": 1778798176117
  },
  "sessionTarget": "main",
  "wakeMode": "now",
  "payload": {
    "kind": "systemEvent",
    "text": "cron wait proof"
  },
  "state": {
    "nextRunAtMs": 1778801776117
  }
}
job_id=8674012e-1ad6-4856-ad76-08856d1e61f8
health_after_cron_add:
$ node scripts/run-node.mjs gateway call health --token [redacted-test-token] --json
{
  "ok": true,
  "plugins": {
    "loaded": [
      "acpx",
      "browser",
      "canvas",
      "device-pair",
      "file-transfer",
      "memory-core",
      "phone-control",
      "talk-voice"
    ],
    "errors": []
  },
  "defaultAgentId": "dev"
}
running_cron_with_wait
$ node scripts/run-node.mjs cron run 8674012e-1ad6-4856-ad76-08856d1e61f8 --token [redacted-test-token] --wait --wait-timeout 30s --poll-interval 500ms
cron run --wait output:
{
  "ok": true,
  "enqueued": true,
  "runId": "manual:8674012e-1ad6-4856-ad76-08856d1e61f8:1778798183694:1",
  "completed": true,
  "status": "ok",
  "run": {
    "ts": 1778798183707,
    "jobId": "8674012e-1ad6-4856-ad76-08856d1e61f8",
    "action": "finished",
    "status": "ok",
    "summary": "cron wait proof",
    "runId": "manual:8674012e-1ad6-4856-ad76-08856d1e61f8:1778798183694:1",
    "runAtMs": 1778798183695,
    "durationMs": 9,
    "nextRunAtMs": 1778801776117,
    "deliveryStatus": "not-requested"
  }
}
exit_code=0
run_id=manual:8674012e-1ad6-4856-ad76-08856d1e61f8:1778798183694:1
terminal_status=ok
cron runs --run-id output:
$ node scripts/run-node.mjs cron runs --token [redacted-test-token] --id 8674012e-1ad6-4856-ad76-08856d1e61f8 --run-id manual:8674012e-1ad6-4856-ad76-08856d1e61f8:1778798183694:1 --limit 1
{
  "entries": [
    {
      "ts": 1778798183707,
      "jobId": "8674012e-1ad6-4856-ad76-08856d1e61f8",
      "action": "finished",
      "status": "ok",
      "summary": "cron wait proof",
      "runId": "manual:8674012e-1ad6-4856-ad76-08856d1e61f8:1778798183694:1",
      "runAtMs": 1778798183695,
      "durationMs": 9,
      "nextRunAtMs": 1778801776117,
      "deliveryStatus": "not-requested"
    }
  ],
  "total": 1,
  "offset": 0,
  "limit": 1,
  "hasMore": false,
  "nextOffset": null
}
  • Observed result after fix: The real Gateway accepted a cron job, cron run --wait returned the manual runId, blocked until the run log entry reached terminal status ok, returned completed: true, exited with exit_code=0, and cron runs --run-id returned exactly one matching finished entry.
  • What was not tested: No external provider/channel delivery was exercised; proof used a local system-event cron job against a real loopback Gateway.
  • Before evidence (optional but encouraged): Existing code path returned { ok: true, enqueued: true, runId } immediately from enqueueRun, leaving wrappers to poll run history manually.

Root Cause (if applicable)

  • Root cause: N/A; this is an additive CLI capability.
  • Missing detection / guardrail: Manual cron runs already emitted runId, but the CLI did not provide a first-party wait mode or exact-run history filter.
  • Contributing context (if known): Operational shutdown hooks need completion semantics without changing the default non-blocking Gateway RPC contract.

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file: src/cli/cron-cli.test.ts, src/cron/run-log.test.ts, src/gateway/protocol/cron-validators.test.ts, src/gateway/protocol/native-protocol-levels.guard.test.ts.
  • Scenario the test should lock in: --wait polls the exact runId, exits 0 for ok, exits non-zero for error and skipped, and protocol/run-log filtering accepts and applies runId.
  • Why this is the smallest reliable guardrail: The behavior is a CLI wait loop over the existing cron run-log contract, so mocked Gateway responses and run-log filtering tests cover the new logic without requiring a live scheduler.
  • Existing test that already covers this (if any): Existing cron CLI run tests covered queued/non-queued exit behavior; this PR extends them for wait behavior.
  • If no new test is added, why not: N/A; focused tests were added.

User-visible / Behavior Changes

openclaw cron run <job-id> remains non-blocking by default. Users can now pass --wait, --wait-timeout <duration>, and --poll-interval <duration> to block until the queued manual run completes. openclaw cron runs --id <job-id> --run-id <run-id> filters run history to one exact run.

Diagram (if applicable)

Before:
openclaw cron run <job-id> -> enqueue run -> print runId -> exit

After:
openclaw cron run <job-id> --wait -> enqueue run -> poll cron.runs by runId -> terminal status -> exit code

Security Impact (required)

  • New permissions/capabilities? (Yes/No) No
  • Secrets/tokens handling changed? (Yes/No) No
  • New/changed network calls? (Yes/No) No
  • Command/tool execution surface changed? (Yes/No) No
  • Data access scope changed? (Yes/No) No
  • If any Yes, explain risk + mitigation: N/A

Repro + Verification

Environment

  • OS: Docker Desktop Linux container from Windows checkout
  • Runtime/container: node:24-bookworm, Node v24.15.0, pnpm 11.1.0 through Corepack
  • Model/provider: N/A
  • Integration/channel (if any): local OpenClaw Gateway loopback with token auth
  • Relevant config (redacted): isolated OPENCLAW_STATE_DIR; test token redacted in evidence

Steps

  1. Run focused cron CLI, run-log, protocol validator, and native protocol guard tests.
  2. Run changed checks and docs list.
  3. Start a real Gateway in Docker and run cron add, cron run --wait, and cron runs --run-id against it.
  4. Inspect the PR diff for the CLI, Gateway protocol, run-log, generated Swift model, and docs updates.

Expected

  • --wait polls the exact returned run id and maps terminal statuses to the documented exit codes.
  • cron.runs accepts and filters by runId.
  • Protocol validators and generated Swift models stay in sync.
  • Real Gateway proof shows returned runId, terminal status, and exit code.

Actual

  • Focused tests passed.
  • Changed checks passed.
  • Docs list passed.
  • Whitespace check passed.
  • Docker Gateway proof passed with returned runId, terminal status ok, completed: true, exit_code=0, and exact cron runs --run-id history lookup.

Evidence

Attach at least one:

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Human Verification (required)

What you personally verified (not just CI), and how:

  • Verified scenarios: ok, error, and skipped terminal statuses for cron run --wait; exact runId filtering in cron run-log pages; protocol validator acceptance/rejection; generated Swift model includes runId; docs cover new CLI usage; real Gateway cron wait path returns completed: true, status ok, and exit code 0.
  • Edge cases checked: missing or empty runId validation, non-ok terminal statuses exiting non-zero, default non-wait behavior remaining unchanged.
  • What you did not verify: External provider/channel delivery; proof used a local system-event cron job.

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? (Yes/No) Yes
  • Config/env changes? (Yes/No) No
  • Migration needed? (Yes/No) No
  • If yes, exact upgrade steps: N/A

Risks and Mitigations

  • Risk: --wait could hang longer than expected if a run never records a terminal log entry.
    • Mitigation: --wait-timeout defaults to a bounded duration and exits non-zero on timeout.
  • Risk: polling could observe another run for the same job.
    • Mitigation: cron.runs now supports exact runId filtering and --wait uses it.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime cli CLI command changes size: S triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. triage: mock-only-proof Candidate: PR proof only shows tests, mocks, snapshots, lint, typecheck, or CI. and removed triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 14, 2026
@clawsweeper

clawsweeper Bot commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

Summary
The PR adds openclaw cron run --wait, wait timeout and poll interval flags, exact cron.runs --run-id filtering, protocol/schema and Swift model updates, tests, docs, and changelog text.

Reproducibility: not applicable. this is an additive feature PR, not a broken existing behavior report. Source inspection confirms current main lacks the wait/run-id filter surfaces, and the PR body supplies live after-fix Gateway output for the intended behavior.

Real behavior proof
Sufficient (live_output): The PR body includes redacted live output from a real loopback Gateway showing after-fix cron run --wait completion and exact cron runs --run-id lookup.

Next step before merge
A narrow automated repair can make --wait-timeout a true upper bound and add focused coverage before maintainers make the final feature/API decision.

Security
Cleared: The diff adds CLI/protocol/runtime filtering, generated Swift model fields, docs, tests, and changelog text without dependency, workflow, secret, permission, or artifact-execution changes.

Review findings

  • [P2] Cap each sleep to the remaining wait timeout — src/cli/cron-cli/register.cron-simple.ts:77
Review details

Best possible solution:

Fix the wait-loop timeout bound, then land after maintainer approval and green CI while preserving the non-blocking cron.run RPC and using run-id-filtered history for completion.

Do we have a high-confidence way to reproduce the issue?

Not applicable: this is an additive feature PR, not a broken existing behavior report. Source inspection confirms current main lacks the wait/run-id filter surfaces, and the PR body supplies live after-fix Gateway output for the intended behavior.

Is this the best way to solve the issue?

No: polling cron.runs by the returned runId is the right narrow design, but the current wait loop must cap sleep to the remaining timeout so --wait-timeout is a true maximum.

Full review comments:

  • [P2] Cap each sleep to the remaining wait timeout — src/cli/cron-cli/register.cron-simple.ts:77
    The loop checks the timeout before sleeping, then always sleeps for the full pollIntervalMs. If a run never records a terminal entry and a caller uses --wait-timeout 1s --poll-interval 10s, the command can block for roughly 10 seconds before the next timeout check, which breaks the documented maximum wait and matters for shutdown/pre-stop hooks. Clamp the sleep to the remaining timeout or use a timeout-aware timer.
    Confidence: 0.91

Overall correctness: patch is incorrect
Overall confidence: 0.88

Acceptance criteria:

  • node scripts/run-vitest.mjs src/cli/cron-cli.test.ts src/cron/run-log.test.ts src/gateway/protocol/cron-validators.test.ts
  • git diff --check

What I checked:

  • Current main CLI behavior: Current main registers cron runs with only --id and --limit, and cron run calls cron.run, prints the enqueue response, and exits without a wait loop. (src/cli/cron-cli/register.cron-simple.ts:151, aa6ea4510ca9)
  • Current main run correlation: Current main already creates and returns manual run ids from enqueueRun, so the PR is correctly building on the existing correlation point rather than changing cron.run into a blocking RPC. (src/cron/service/ops.ts:854, aa6ea4510ca9)
  • PR wait implementation: The PR head polls cron.runs by runId, but after each unsuccessful poll it sleeps the full poll interval even when less timeout remains. (src/cli/cron-cli/register.cron-simple.ts:77, 99d1303c8e66)
  • PR run-id protocol wiring: The PR adds optional non-empty runId to CronRunsParamsSchema and forwards it through Gateway cron handlers into job/all run-log paging. (src/gateway/protocol/schema/cron.ts:415, 99d1303c8e66)
  • PR tests: The PR adds CLI wait coverage for ok/error/skipped statuses and zero poll-interval rejection, but it does not cover the case where poll interval exceeds the remaining wait timeout. (src/cli/cron-cli.test.ts:308, 99d1303c8e66)
  • Maintainer discussion: A reviewer had already identified the zero poll-interval guardrail; the later commits address that specific guardrail, but the remaining max-timeout oversleep issue is distinct. (99d1303c8e66)

Likely related people:

  • @pfrederiksen: Merged history shows commit f30dc0aeb4ce87ada1aef40042fda5729951a0bf persisted manual runId values in cron history, which is the correlation mechanism this PR relies on. (role: manual run-id history contributor; confidence: high; commits: f30dc0aeb4ce; files: src/cron/run-log.ts, src/cron/service/ops.ts, src/gateway/protocol/schema/cron.ts)
  • @tyler6204: Merged history shows commit 38543d819690155b350fa358cf68b98d11a0fe6d changed manual cron triggering to the fire-and-forget Gateway surface that this PR extends. (role: manual-run queue behavior contributor; confidence: high; commits: 38543d819690; files: src/cli/cron-cli/register.cron-simple.ts, src/cron/service/ops.ts, src/gateway/server-methods/cron.ts)
  • @steipete: Commit a6dd9fdf08369a06e7e281bed80e62bc3243b3e7 recently changed cron run-log and cron delivery fields adjacent to the run-history surface touched here. (role: recent cron run-log contributor; confidence: medium; commits: a6dd9fdf0836; files: src/cron/run-log.ts, src/cron/service/ops.ts, src/cron/types.ts)

Remaining risk / open question:

  • --wait-timeout can be exceeded by up to the full poll interval when no terminal run entry appears.
  • Current-head CI was not terminal green during the live check.
  • The new CLI flags and additive Gateway protocol field still need maintainer product/API approval.

Codex review notes: model gpt-5.5, reasoning high; reviewed against aa6ea4510ca9.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added proof: supplied External PR includes structured after-fix real behavior proof. and removed triage: mock-only-proof Candidate: PR proof only shows tests, mocks, snapshots, lint, typecheck, or CI. labels May 14, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 14, 2026
@stielemans

This comment was marked as low quality.

@openclaw-barnacle openclaw-barnacle Bot added size: M and removed size: S proof: sufficient ClawSweeper judged the real behavior proof convincing. labels May 14, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 15, 2026
@galiniliev galiniliev self-assigned this May 15, 2026
@galiniliev
galiniliev force-pushed the ificator/cronrunwait branch from bb8dd9b to bb923dc Compare May 15, 2026 20:07
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 15, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 15, 2026
@galiniliev
galiniliev force-pushed the ificator/cronrunwait branch from bb923dc to 333f376 Compare May 15, 2026 23:12
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 15, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 15, 2026
ificator and others added 4 commits May 16, 2026 02:43
Add an opt-in wait mode for manual cron runs that polls the exact run id until the run log records a terminal status. Document the new CLI behavior and sync protocol schema consumers.

Co-authored-by: Copilot <[email protected]>
@galiniliev
galiniliev force-pushed the ificator/cronrunwait branch from 333f376 to 99d1303 Compare May 16, 2026 02:50
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 16, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 16, 2026
@galiniliev

Copy link
Copy Markdown
Contributor

Maintainer verification for landing:

  • PR head: 99d1303c8e6663e5c4a1f1c05365fb9e27e9fc45
  • Rebased onto upstream/main f1c8570e0c
  • GitHub checks: 95 successful, 23 skipped, 1 neutral, 0 pending, 0 failed at pre-merge poll
  • Azure Crabbox evidence: provider azure, slug quick-barnacle, lease cbx_0cedc7c9500e, command pnpm check:test-types, exit 0; evidence file .crabbox/evidence/pr-81929-check-test-types-20260516T024941Z.txt

Commands run after the maintainer rebase/docs update:

git diff --check upstream/main...HEAD
node scripts/check-changelog-attributions.mjs CHANGELOG.md
pnpm docs:list
node scripts/run-vitest.mjs src/cli/cron-cli.test.ts src/cron/run-log.test.ts src/gateway/protocol/cron-validators.test.ts src/gateway/protocol/native-protocol-levels.guard.test.ts
pnpm check:test-types
CRABBOX_AZURE_NETWORK=private CRABBOX_ID=quick-barnacle /home/galini/.codex/skills/crabbox-oc-evidence/scripts/collect-openclaw-evidence.sh --name pr-81929-check-test-types --command 'pnpm check:test-types'

Focused Vitest result: 6 files, 116 tests passed. No known proof gaps for the changed cron CLI/run-log/protocol/docs surface.

@galiniliev
galiniliev merged commit 372a8e4 into openclaw:main May 16, 2026
119 checks passed
@galiniliev

Copy link
Copy Markdown
Contributor

Landed in 372a8e4.

Source head was 99d1303. Targeted duplicate search for cron wait/manual run wait follow-ups did not find associated open issues or PRs to close.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
Adds wait mode for manual cron runs, exact run-id lookup for cron run logs, protocol/Swift schema support, and docs/changelog coverage.
galiniliev pushed a commit to galiniliev/openclaw that referenced this pull request May 25, 2026
Adds wait mode for manual cron runs, exact run-id lookup for cron run logs, protocol/Swift schema support, and docs/changelog coverage.
jameslcowan pushed a commit to jameslcowan/openclaw that referenced this pull request Jun 2, 2026
Adds wait mode for manual cron runs, exact run-id lookup for cron run logs, protocol/Swift schema support, and docs/changelog coverage.
sablehead pushed a commit to sablehead/openclaw that referenced this pull request Jun 10, 2026
Adds wait mode for manual cron runs, exact run-id lookup for cron run logs, protocol/Swift schema support, and docs/changelog coverage.
obviyus added a commit that referenced this pull request Oct 1, 2026
…call (#162481)

## What Problem This Solves

Fixes: when an agent runs an automation with `automations run`, the call returns as soon as the run is queued, so the model never learns whether the run worked. It then posts guesses, or schedules a separate "verify" job. That job runs with only its own scope, can't see the result, and reports a false "blocked".

## User Impact

User impact: when an agent runs an automation, it gets the finished run (status, error, delivery status and summary) in the same tool result if the run ends within the call's `timeoutMs` (default 60 s, capped at 10 min). A longer run returns its `runId` and a note to check it later with `runs jobId runId`, not with a scheduled check. The CLI is unchanged.

## Why This Change Was Made

`cron.run` became enqueue-only in #40204 (closing #40192). Back then a synchronous run held the RPC until the 60 s gateway timeout and returned a misleading timeout error while the job kept running. #81929 later added `openclaw cron run --wait`, polling `cron.runs` from the client, and deliberately kept `cron.run` from holding the request open. The agent tool never got a wait at all. A client-side poller would not work for the tool anyway: management-grant turns can run a job, but `cron.runs` is not one of their allowed methods.

This PR keeps that invariant (no unbounded request, no false failure) and gives the one owner of run completion a bounded, opt-in wait:

- The cron service records each accepted manual run's settlement. `waitForManualRun(runId, timeoutMs, signal)` resolves when the run has written its history row. It is event-driven, with no polling.
- `cron.run` accepts an optional `waitTimeoutMs`. When the run finishes in time, the ack also carries `run`, read through the existing `cron.runs` handler so the same visibility and authority rules apply. When the wait ends first, the ack is unchanged and the run continues.
- When an agent turn runs a main-session job, or a `session:<key>` job in its own session, the call returns at once. The caller's turn holds the main lane and its own session lane: heartbeats skip while `CommandLane.Main` is busy, and a main-session run waits up to 2 min for that busy turn. Waiting there would only burn the budget.
- The `automations` tool's `run` passes its `timeoutMs` as the wait. `runs` now forwards `runId`. The tool descriptions now steer models away from verify jobs. Against a shipped Gateway, which rejects the new param before enqueueing, the tool retries the plain call once, the same way it already does for `compact` on `cron.list`.
- Accepted runs stay accepted, and outcomes go only to callers that may still read them. After the history read, the handler rechecks read authority (caller authority, agent runtime and any management grant), with no await between that check and the response. If the read or the recheck is refused, for example because a delegated grant lapsed or was revoked during a long wait, the caller gets the plain ack and nothing about the outcome. If the run finished but its history is not visible (for example a one-shot that deleted itself after succeeding), the ack carries `finished: true`. Management-only turns are pointed to the Automations page instead of `runs`.

The CLI keeps its client-side `--wait` polling in this PR. Moving it onto the Gateway wait is a separate, compatibility-reviewed follow-up.

## Evidence

- Real isolated Gateway, real Telegram plugin on the Crabline synthetic Bot API, and a deterministic Responses provider. An owner DM turn calls the `automations` tool (throwaway harness, not committed).
  - Before (origin/main build): every `run` returned only `{ ok, enqueued, runId, processInstanceId }` in under 1 s, with no outcome. The report still reached the chat, so the model couldn't tell the run had succeeded.
  - After: the isolated job's `run` returned in 4.3 s with `run { status: "ok", completionStatus: "succeeded", deliveryStatus: "delivered", summary: "FAST-REPORT-DELIVERED" }`, and the report reached the chat. A slow job (8 s, called with `timeoutMs: 2000`) returned after 2.6 s with its `runId` and the `runs jobId runId` note. The run kept going and delivered, and a later `runs` call with that `runId` returned the single finished entry. A main-session job run from the owner's main-session DM returned in 0.6 s with the note instead of blocking the turn.
- Gateway regression (`src/gateway/server.cron.test.ts`): `waitTimeoutMs: 50` returns only the `runId` while the run is blocked. `waitTimeoutMs: 10000` returns `run { runId, status: "ok", completionStatus: "succeeded", summary }`. On origin/main this fails because the closed schema rejects `waitTimeoutMs`.
- Same-session skip (`cron.validation.test.ts`): from an agent turn, `main` and `session:<own key>` jobs return the plain ack without waiting. `isolated` jobs wait.
- Authority chain (`cron.validation.test.ts`, through the real `cron.run` and `cron.runs` handlers with a stored run record): a caller that is still authorized gets `run { runId, status: "ok" }`. A caller revoked during the history read gets only the accepted ack. Before this change the revoked case turned into a request error.
- Tool (`cron-tool.test.ts`): the wait is capped at 10 min, and the RPC timeout is the wait plus 60 s. An unfinished run gets the `runs jobId runId` note.
- Tool contract (`cron-tool.output-contract.test.ts`): a shipped Gateway that rejects `waitTimeoutMs` still enqueues through a single retry, and the result stays valid against the output schema. The `run` output type only declares the outcome fields, so the generated code-mode declarations stay within their size allowance.
- Measured local wall times on head `cf942df0601` (one `node scripts/run-vitest.mjs <file>` per file; wrapper wall / Vitest duration): `cron-tool.output-contract` 5 tests, 24s / 7.0s; `cron-tool` 72 tests, 19s / 16.2s; `server-cron-lazy` 25 tests, 21s / 17.6s; `cron.validation` 261 tests, 24s / 21.4s; `server.cron` 17 tests, 46s / 43.8s. There are no CI seconds yet: CI skips the test jobs while the PR is a draft, and the only job that ran, "PR context and evidence", passed in 38s.
- `pnpm tsgo:core` is clean. Targeted tests pass: `server.cron`, `cron.validation`, `cron-tool`, `server-cron-lazy`.

### Bounded cost

- The wait is bounded by `timeoutMs` (default 60 s, capped at 10 min in the tool) and ends early if the caller aborts. The `cron.run` RPC timeout is the wait plus a 60 s enqueue budget, so the response always arrives before the client gives up.
- No new model calls or job runs. The waiter only watches a run that was already accepted. It does not retry, re-run or alert.
- No nested waits. Automation-run sessions are limited to self status/list/get/runs/remove, so a job's run cannot call `run`. A job running itself gets `already-running`. Main-session and same-session runs, which can only start after the caller's turn, skip the wait.

### Hermes

Hermes `cronjob(action="run")` sends the job to its async-delegation pool and returns a handle with "Do not wait or poll". The outcome comes back into the conversation as a new turn, and Hermes runs the job inline when no session can receive it. This PR borrows "the tool owns the follow-up, so the model doesn't poll". Feeding completions back into the conversation is not done here: OpenClaw already delivers run output to the job's target. It's a possible follow-up for long runs.

LOC (commit): production about +125/-12, tests about +96, docs +3.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
…call (openclaw#162481)

## What Problem This Solves

Fixes: when an agent runs an automation with `automations run`, the call returns as soon as the run is queued, so the model never learns whether the run worked. It then posts guesses, or schedules a separate "verify" job. That job runs with only its own scope, can't see the result, and reports a false "blocked".

## User Impact

User impact: when an agent runs an automation, it gets the finished run (status, error, delivery status and summary) in the same tool result if the run ends within the call's `timeoutMs` (default 60 s, capped at 10 min). A longer run returns its `runId` and a note to check it later with `runs jobId runId`, not with a scheduled check. The CLI is unchanged.

## Why This Change Was Made

`cron.run` became enqueue-only in openclaw#40204 (closing openclaw#40192). Back then a synchronous run held the RPC until the 60 s gateway timeout and returned a misleading timeout error while the job kept running. openclaw#81929 later added `openclaw cron run --wait`, polling `cron.runs` from the client, and deliberately kept `cron.run` from holding the request open. The agent tool never got a wait at all. A client-side poller would not work for the tool anyway: management-grant turns can run a job, but `cron.runs` is not one of their allowed methods.

This PR keeps that invariant (no unbounded request, no false failure) and gives the one owner of run completion a bounded, opt-in wait:

- The cron service records each accepted manual run's settlement. `waitForManualRun(runId, timeoutMs, signal)` resolves when the run has written its history row. It is event-driven, with no polling.
- `cron.run` accepts an optional `waitTimeoutMs`. When the run finishes in time, the ack also carries `run`, read through the existing `cron.runs` handler so the same visibility and authority rules apply. When the wait ends first, the ack is unchanged and the run continues.
- When an agent turn runs a main-session job, or a `session:<key>` job in its own session, the call returns at once. The caller's turn holds the main lane and its own session lane: heartbeats skip while `CommandLane.Main` is busy, and a main-session run waits up to 2 min for that busy turn. Waiting there would only burn the budget.
- The `automations` tool's `run` passes its `timeoutMs` as the wait. `runs` now forwards `runId`. The tool descriptions now steer models away from verify jobs. Against a shipped Gateway, which rejects the new param before enqueueing, the tool retries the plain call once, the same way it already does for `compact` on `cron.list`.
- Accepted runs stay accepted, and outcomes go only to callers that may still read them. After the history read, the handler rechecks read authority (caller authority, agent runtime and any management grant), with no await between that check and the response. If the read or the recheck is refused, for example because a delegated grant lapsed or was revoked during a long wait, the caller gets the plain ack and nothing about the outcome. If the run finished but its history is not visible (for example a one-shot that deleted itself after succeeding), the ack carries `finished: true`. Management-only turns are pointed to the Automations page instead of `runs`.

The CLI keeps its client-side `--wait` polling in this PR. Moving it onto the Gateway wait is a separate, compatibility-reviewed follow-up.

## Evidence

- Real isolated Gateway, real Telegram plugin on the Crabline synthetic Bot API, and a deterministic Responses provider. An owner DM turn calls the `automations` tool (throwaway harness, not committed).
  - Before (origin/main build): every `run` returned only `{ ok, enqueued, runId, processInstanceId }` in under 1 s, with no outcome. The report still reached the chat, so the model couldn't tell the run had succeeded.
  - After: the isolated job's `run` returned in 4.3 s with `run { status: "ok", completionStatus: "succeeded", deliveryStatus: "delivered", summary: "FAST-REPORT-DELIVERED" }`, and the report reached the chat. A slow job (8 s, called with `timeoutMs: 2000`) returned after 2.6 s with its `runId` and the `runs jobId runId` note. The run kept going and delivered, and a later `runs` call with that `runId` returned the single finished entry. A main-session job run from the owner's main-session DM returned in 0.6 s with the note instead of blocking the turn.
- Gateway regression (`src/gateway/server.cron.test.ts`): `waitTimeoutMs: 50` returns only the `runId` while the run is blocked. `waitTimeoutMs: 10000` returns `run { runId, status: "ok", completionStatus: "succeeded", summary }`. On origin/main this fails because the closed schema rejects `waitTimeoutMs`.
- Same-session skip (`cron.validation.test.ts`): from an agent turn, `main` and `session:<own key>` jobs return the plain ack without waiting. `isolated` jobs wait.
- Authority chain (`cron.validation.test.ts`, through the real `cron.run` and `cron.runs` handlers with a stored run record): a caller that is still authorized gets `run { runId, status: "ok" }`. A caller revoked during the history read gets only the accepted ack. Before this change the revoked case turned into a request error.
- Tool (`cron-tool.test.ts`): the wait is capped at 10 min, and the RPC timeout is the wait plus 60 s. An unfinished run gets the `runs jobId runId` note.
- Tool contract (`cron-tool.output-contract.test.ts`): a shipped Gateway that rejects `waitTimeoutMs` still enqueues through a single retry, and the result stays valid against the output schema. The `run` output type only declares the outcome fields, so the generated code-mode declarations stay within their size allowance.
- Measured local wall times on head `cf942df0601` (one `node scripts/run-vitest.mjs <file>` per file; wrapper wall / Vitest duration): `cron-tool.output-contract` 5 tests, 24s / 7.0s; `cron-tool` 72 tests, 19s / 16.2s; `server-cron-lazy` 25 tests, 21s / 17.6s; `cron.validation` 261 tests, 24s / 21.4s; `server.cron` 17 tests, 46s / 43.8s. There are no CI seconds yet: CI skips the test jobs while the PR is a draft, and the only job that ran, "PR context and evidence", passed in 38s.
- `pnpm tsgo:core` is clean. Targeted tests pass: `server.cron`, `cron.validation`, `cron-tool`, `server-cron-lazy`.

### Bounded cost

- The wait is bounded by `timeoutMs` (default 60 s, capped at 10 min in the tool) and ends early if the caller aborts. The `cron.run` RPC timeout is the wait plus a 60 s enqueue budget, so the response always arrives before the client gives up.
- No new model calls or job runs. The waiter only watches a run that was already accepted. It does not retry, re-run or alert.
- No nested waits. Automation-run sessions are limited to self status/list/get/runs/remove, so a job's run cannot call `run`. A job running itself gets `already-running`. Main-session and same-session runs, which can only start after the caller's turn, skip the wait.

### Hermes

Hermes `cronjob(action="run")` sends the job to its async-delegation pool and returns a handle with "Do not wait or poll". The outcome comes back into the conversation as a new turn, and Hermes runs the job inline when no session can receive it. This PR borrows "the tool owns the follow-up, so the model doesn't poll". Feeding completions back into the conversation is not done here: OpenClaw already delivers run output to the job's target. It's a possible follow-up for long runs.

LOC (commit): production about +125/-12, tests about +96, docs +3.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui cli CLI command changes docs Improvements or additions to documentation gateway Gateway runtime proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: supplied External PR includes structured after-fix real behavior proof. size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants