Skip to content

Commit 38543d8

Browse files
authored
fix(cron): consolidate announce delivery, fire-and-forget trigger, and minimal prompt mode (#40204)
* fix(cron): consolidate announce delivery and detach manual runs * fix: queue detached cron runs (#40204)
1 parent 7dfd77a commit 38543d8

16 files changed

Lines changed: 534 additions & 88 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@ Docs: https://docs.openclaw.ai
123123
- Agents/compaction safeguard pre-check: skip embedded compaction before entering the Pi SDK when a session has no real conversation messages, avoiding unnecessary LLM API calls on idle sessions. (#36451) thanks @Sid-Qin.
124124
- Config/schema cache key stability: build merged schema cache keys with incremental hashing to avoid large single-string serialization and prevent `RangeError: Invalid string length` on high-cardinality plugin/channel metadata. (#36603) Thanks @powermaster888.
125125
- iMessage/cron completion announces: strip leaked inline reply tags (for example `[[reply_to:6100]]`) from user-visible completion text so announcement deliveries do not expose threading metadata. (#24600) Thanks @vincentkoc.
126+
- Cron/manual run enqueue flow: queue `cron.run` requests behind the cron execution lane, return immediate `{ ok: true, enqueued: true, runId }` acknowledgements, preserve `{ ok: true, ran: false, reason }` skip responses for already-running and not-due jobs, and document the asynchronous completion flow. (#40204)
126127
- Control UI/iMessage duplicate reply routing: keep internal webchat turns on dispatcher delivery (instead of origin-channel reroute) so Control UI chats do not duplicate replies into iMessage, while preserving webchat-provider relayed routing for external surfaces. Fixes #33483. Thanks @alicexmolt.
127128
- Sessions/daily reset transcript archival: archive prior transcript files during stale-session scheduled/daily resets by capturing the previous session entry before rollover, preventing orphaned transcript files on disk. (#35493) Thanks @byungsker.
128129
- Feishu/group slash command detection: normalize group mention wrappers before command-authorization probing so mention-prefixed commands (for example `@Bot/model` and `@Bot /reset`) are recognized as gateway commands instead of being forwarded to the agent. (#35994) Thanks @liuxiaopai-ai.

‎docs/automation/cron-jobs.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -620,6 +620,8 @@ openclaw cron run <jobId>
620620
openclaw cron run <jobId> --due
621621
```
622622

623+
`cron.run` now acknowledges once the manual run is queued, not after the job finishes. Successful queue responses look like `{ ok: true, enqueued: true, runId }`. If the job is already running or `--due` finds nothing due, the response stays `{ ok: true, ran: false, reason }`. Use `openclaw cron runs --id <jobId>` or the `cron.runs` gateway method to inspect the eventual finished entry.
624+
623625
Edit an existing job (patch fields):
624626

625627
```bash

‎docs/cli/cron.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ Note: one-shot (`--at`) jobs delete after success by default. Use `--keep-after-
2323

2424
Note: recurring jobs now use exponential retry backoff after consecutive errors (30s → 1m → 5m → 15m → 60m), then return to normal schedule after the next successful run.
2525

26+
Note: `openclaw cron run` now returns as soon as the manual run is queued for execution. Successful responses include `{ ok: true, enqueued: true, runId }`; use `openclaw cron runs --id <job-id>` to follow the eventual outcome.
27+
2628
Note: retention/pruning is controlled in config:
2729

2830
- `cron.sessionRetention` (default `24h`) prunes completed isolated run sessions.

‎src/agents/pi-embedded-runner/run/attempt.test.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -135,9 +135,15 @@ describe("resolvePromptModeForSession", () => {
135135
expect(resolvePromptModeForSession("agent:main:subagent:child")).toBe("minimal");
136136
});
137137

138-
it("uses full mode for cron sessions", () => {
139-
expect(resolvePromptModeForSession("agent:main:cron:job-1")).toBe("full");
140-
expect(resolvePromptModeForSession("agent:main:cron:job-1:run:run-abc")).toBe("full");
138+
it("uses minimal mode for cron sessions", () => {
139+
expect(resolvePromptModeForSession("agent:main:cron:job-1")).toBe("minimal");
140+
expect(resolvePromptModeForSession("agent:main:cron:job-1:run:run-abc")).toBe("minimal");
141+
});
142+
143+
it("uses full mode for regular and undefined sessions", () => {
144+
expect(resolvePromptModeForSession(undefined)).toBe("full");
145+
expect(resolvePromptModeForSession("agent:main")).toBe("full");
146+
expect(resolvePromptModeForSession("agent:main:thread:abc")).toBe("full");
141147
});
142148
});
143149

‎src/agents/pi-embedded-runner/run/attempt.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import type {
1919
PluginHookBeforeAgentStartResult,
2020
PluginHookBeforePromptBuildResult,
2121
} from "../../../plugins/types.js";
22-
import { isSubagentSessionKey } from "../../../routing/session-key.js";
22+
import { isCronSessionKey, isSubagentSessionKey } from "../../../routing/session-key.js";
2323
import { joinPresentTextSegments } from "../../../shared/text/join-segments.js";
2424
import { resolveSignalReactionLevel } from "../../../signal/reaction-level.js";
2525
import { resolveTelegramInlineButtonsScope } from "../../../telegram/inline-buttons.js";
@@ -613,7 +613,7 @@ export function resolvePromptModeForSession(sessionKey?: string): "minimal" | "f
613613
if (!sessionKey) {
614614
return "full";
615615
}
616-
return isSubagentSessionKey(sessionKey) ? "minimal" : "full";
616+
return isSubagentSessionKey(sessionKey) || isCronSessionKey(sessionKey) ? "minimal" : "full";
617617
}
618618

619619
export function resolveAttemptFsWorkspaceOnly(params: {

‎src/agents/subagent-announce.timeout.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,25 @@ describe("subagent announce timeout config", () => {
197197
expect(internalEvents[0]?.announceType).toBe("cron job");
198198
});
199199

200+
it("regression, keeps child announce internal when requester is a cron run session", async () => {
201+
const cronSessionKey = "agent:main:cron:daily-check:run:run-123";
202+
203+
await runAnnounceFlowForTest("run-cron-internal", {
204+
requesterSessionKey: cronSessionKey,
205+
requesterDisplayKey: cronSessionKey,
206+
requesterOrigin: { channel: "discord", to: "channel:cron-results", accountId: "acct-1" },
207+
});
208+
209+
const directAgentCall = findGatewayCall(
210+
(call) => call.method === "agent" && call.expectFinal === true,
211+
);
212+
expect(directAgentCall?.params?.sessionKey).toBe(cronSessionKey);
213+
expect(directAgentCall?.params?.deliver).toBe(false);
214+
expect(directAgentCall?.params?.channel).toBeUndefined();
215+
expect(directAgentCall?.params?.to).toBeUndefined();
216+
expect(directAgentCall?.params?.accountId).toBeUndefined();
217+
});
218+
200219
it("regression, routes child announce to parent session instead of grandparent when parent session still exists", async () => {
201220
const parentSessionKey = "agent:main:subagent:parent";
202221
requesterDepthResolver = (sessionKey?: string) =>

‎src/agents/subagent-announce.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import type { ConversationRef } from "../infra/outbound/session-binding-service.
1414
import { getGlobalHookRunner } from "../plugins/hook-runner-global.js";
1515
import { normalizeAccountId, normalizeMainKey } from "../routing/session-key.js";
1616
import { defaultRuntime } from "../runtime.js";
17+
import { isCronSessionKey } from "../sessions/session-key-utils.js";
1718
import { extractTextFromChatContent } from "../shared/chat-content.js";
1819
import {
1920
type DeliveryContext,
@@ -78,6 +79,10 @@ function resolveSubagentAnnounceTimeoutMs(cfg: ReturnType<typeof loadConfig>): n
7879
return Math.min(Math.max(1, Math.floor(configured)), MAX_TIMER_SAFE_TIMEOUT_MS);
7980
}
8081

82+
function isInternalAnnounceRequesterSession(sessionKey: string | undefined): boolean {
83+
return getSubagentDepthFromSessionStore(sessionKey) >= 1 || isCronSessionKey(sessionKey);
84+
}
85+
8186
function summarizeDeliveryError(error: unknown): string {
8287
if (error instanceof Error) {
8388
return error.message || "error";
@@ -580,8 +585,7 @@ async function resolveSubagentCompletionOrigin(params: {
580585
async function sendAnnounce(item: AnnounceQueueItem) {
581586
const cfg = loadConfig();
582587
const announceTimeoutMs = resolveSubagentAnnounceTimeoutMs(cfg);
583-
const requesterDepth = getSubagentDepthFromSessionStore(item.sessionKey);
584-
const requesterIsSubagent = requesterDepth >= 1;
588+
const requesterIsSubagent = isInternalAnnounceRequesterSession(item.sessionKey);
585589
const origin = item.origin;
586590
const threadId =
587591
origin?.threadId != null && origin.threadId !== "" ? String(origin.threadId) : undefined;
@@ -1216,6 +1220,8 @@ export async function runSubagentAnnounceFlow(params: {
12161220
}
12171221

12181222
let requesterDepth = getSubagentDepthFromSessionStore(targetRequesterSessionKey);
1223+
const requesterIsInternalSession = () =>
1224+
requesterDepth >= 1 || isCronSessionKey(targetRequesterSessionKey);
12191225

12201226
let childCompletionFindings: string | undefined;
12211227
let subagentRegistryRuntime:
@@ -1339,7 +1345,7 @@ export async function runSubagentAnnounceFlow(params: {
13391345
const announceSessionId = childSessionId || "unknown";
13401346
const findings = childCompletionFindings || reply || "(no output)";
13411347

1342-
let requesterIsSubagent = requesterDepth >= 1;
1348+
let requesterIsSubagent = requesterIsInternalSession();
13431349
if (requesterIsSubagent) {
13441350
const {
13451351
isSubagentSessionRunActive,
@@ -1363,7 +1369,7 @@ export async function runSubagentAnnounceFlow(params: {
13631369
targetRequesterOrigin =
13641370
normalizeDeliveryContext(fallback.requesterOrigin) ?? targetRequesterOrigin;
13651371
requesterDepth = getSubagentDepthFromSessionStore(targetRequesterSessionKey);
1366-
requesterIsSubagent = requesterDepth >= 1;
1372+
requesterIsSubagent = requesterIsInternalSession();
13671373
}
13681374
}
13691375
}

‎src/cli/cron-cli.test.ts‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -156,15 +156,24 @@ async function expectCronEditWithScheduleLookupExit(
156156
).rejects.toThrow("__exit__:1");
157157
}
158158

159-
async function runCronRunAndCaptureExit(params: { ran: boolean; args?: string[] }) {
159+
async function runCronRunAndCaptureExit(params: {
160+
ran?: boolean;
161+
enqueued?: boolean;
162+
args?: string[];
163+
}) {
160164
resetGatewayMock();
161165
callGatewayFromCli.mockImplementation(
162166
async (method: string, _opts: unknown, callParams?: unknown) => {
163167
if (method === "cron.status") {
164168
return { enabled: true };
165169
}
166170
if (method === "cron.run") {
167-
return { ok: true, params: callParams, ran: params.ran };
171+
return {
172+
ok: true,
173+
params: callParams,
174+
...(typeof params.ran === "boolean" ? { ran: params.ran } : {}),
175+
...(typeof params.enqueued === "boolean" ? { enqueued: params.enqueued } : {}),
176+
};
168177
}
169178
return { ok: true, params: callParams };
170179
},
@@ -195,13 +204,18 @@ describe("cron cli", () => {
195204
ran: true,
196205
expectedExitCode: 0,
197206
},
207+
{
208+
name: "exits 0 for cron run when job is queued successfully",
209+
enqueued: true,
210+
expectedExitCode: 0,
211+
},
198212
{
199213
name: "exits 1 for cron run when job does not execute",
200214
ran: false,
201215
expectedExitCode: 1,
202216
},
203-
])("$name", async ({ ran, expectedExitCode }) => {
204-
const { exitSpy } = await runCronRunAndCaptureExit({ ran });
217+
])("$name", async ({ ran, enqueued, expectedExitCode }) => {
218+
const { exitSpy } = await runCronRunAndCaptureExit({ ran, enqueued });
205219
expect(exitSpy).toHaveBeenCalledWith(expectedExitCode);
206220
});
207221

‎src/cli/cron-cli/register.cron-simple.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,8 +99,8 @@ export function registerCronSimpleCommands(cron: Command) {
9999
mode: opts.due ? "due" : "force",
100100
});
101101
printCronJson(res);
102-
const result = res as { ok?: boolean; ran?: boolean } | undefined;
103-
defaultRuntime.exit(result?.ok && result?.ran ? 0 : 1);
102+
const result = res as { ok?: boolean; ran?: boolean; enqueued?: boolean } | undefined;
103+
defaultRuntime.exit(result?.ok && (result?.ran || result?.enqueued) ? 0 : 1);
104104
} catch (err) {
105105
handleCronCliError(err);
106106
}

‎src/cron/isolated-agent/delivery-dispatch.double-announce.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,29 @@ describe("dispatchCronDelivery — double-announce guard", () => {
208208
expect(runSubagentAnnounceFlow).not.toHaveBeenCalled();
209209
});
210210

211+
it("consolidates descendant output into the cron announce path", async () => {
212+
vi.mocked(countActiveDescendantRuns).mockReturnValue(0);
213+
vi.mocked(isLikelyInterimCronMessage).mockReturnValue(true);
214+
vi.mocked(readDescendantSubagentFallbackReply).mockResolvedValue(
215+
"Detailed child result, everything finished successfully.",
216+
);
217+
vi.mocked(runSubagentAnnounceFlow).mockResolvedValue(true);
218+
219+
const params = makeBaseParams({ synthesizedText: "on it" });
220+
const state = await dispatchCronDelivery(params);
221+
222+
expect(state.deliveryAttempted).toBe(true);
223+
expect(state.delivered).toBe(true);
224+
expect(runSubagentAnnounceFlow).toHaveBeenCalledTimes(1);
225+
expect(runSubagentAnnounceFlow).toHaveBeenCalledWith(
226+
expect.objectContaining({
227+
roundOneReply: "Detailed child result, everything finished successfully.",
228+
expectsCompletionMessage: true,
229+
announceType: "cron job",
230+
}),
231+
);
232+
});
233+
211234
it("normal announce success delivers exactly once and sets deliveryAttempted=true", async () => {
212235
vi.mocked(countActiveDescendantRuns).mockReturnValue(0);
213236
vi.mocked(isLikelyInterimCronMessage).mockReturnValue(false);

0 commit comments

Comments
 (0)