Skip to content

fix(cron): wait for spawned subagents before marking cron job complete - #4304

Closed
michaelxer wants to merge 0 commit into
HKUDS:mainfrom
michaelxer:michaelxer/cron-await-subagent-4290
Closed

fix(cron): wait for spawned subagents before marking cron job complete#4304
michaelxer wants to merge 0 commit into
HKUDS:mainfrom
michaelxer:michaelxer/cron-await-subagent-4290

Conversation

@michaelxer

@michaelxer michaelxer commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

Problem

Cron jobs that spawn subagents via the spawn tool are marked as completed as soon as the agent's main turn finishes (process_direct returns), while the subagent's asyncio.Task is still running in the background.

From the logs in #4290:

14:00:31  Spawned subagent [77dba3c5]: cron-2pm
14:00:44  Cron: job 'cron-2pm' completed    ← too early
14:02:38  Subagent [77dba3c5] completed successfully

The cron service records the run as "ok" and advances to the next scheduled time before the subagent has produced any output. If the job is one-shot (kind: "at") it may even be deleted before the subagent finishes.

Fixes #4290

Fix

SubagentManager already tracks per-session background tasks in _session_tasks. This PR adds:

  1. SubagentManager.await_by_session(session_key) -- waits for all running tasks spawned under that session key to finish (mirrors the existing cancel_by_session).

  2. Call in on_cron_job -- after agent.process_direct() returns, the cron handler now calls await agent.subagents.await_by_session(f"cron:{job.id}") before evaluating the response or returning. The cron service therefore holds the job open until every background subagent completes.

This does not change the spawn tool's behaviour for interactive sessions -- only the cron path awaits.

Testing

Four new tests in tests/agent/test_subagent_lifecycle.py (TestAwaitBySession):

Test Verifies
test_waits_for_running_tasks Blocks until the subagent task finishes
test_no_tasks_returns_immediately No-op when no subagents exist for the session
test_already_done_returns_immediately No-op when subagents finished before the call
test_waits_for_multiple_tasks Waits for all tasks, not just the first

Full suite: 122 passed (subagent + cron + lifecycle tests).

Limitations

This fix ensures the cron job waits for subagent completion. It does not yet feed the subagent's result back into the agent's cron turn as additional context -- that would require a multi-turn cron execution model and is a separate enhancement.

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.

cronjob ends early when there's a subagent spawned

1 participant