Skip to content

Commit e9e4023

Browse files
authored
fix(cron): deliver spawned child results when scheduled agents emit no text (#117308)
* fix(cron): deliver spawned child results when parents emit no text * test(cron): cover spawn-only scheduled child delivery end to end
1 parent 4e47c4c commit e9e4023

6 files changed

Lines changed: 552 additions & 8 deletions

File tree

Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
title: Isolated cron spawn-only child delivery
2+
3+
scenario:
4+
id: cron-isolated-spawn-only-child-delivery
5+
surface: cron
6+
coverage:
7+
primary:
8+
- automation.isolated-cron-execution
9+
- agent-runtime.subagent-turns-delivery
10+
secondary:
11+
- agent-runtime.subagent-turns-subagents
12+
- automation.run-history-cron
13+
- channels.qa-channel-final-reply
14+
regressionRefs:
15+
- openclaw/openclaw#117308
16+
objective: Verify a naturally fired isolated one-shot cron with a spawn-only parent delivers its child's exact reply before retiring.
17+
successCriteria:
18+
- The isolated parent successfully spawns exactly one child and finishes without producing assistant text.
19+
- The child completes successfully and its exact reply reaches the QA channel once.
20+
- Cron history records successful delivery before the one-shot job is retired.
21+
docsRefs:
22+
- docs/help/testing.md
23+
- docs/channels/qa-channel.md
24+
- docs/tools/subagents.md
25+
codeRefs:
26+
- src/cron/isolated-agent/run-finalize.ts
27+
- src/cron/isolated-agent/delivery-dispatch.ts
28+
- src/cron/service/timer-outcomes.ts
29+
- extensions/qa-lab/src/providers/mock-openai/server.ts
30+
execution:
31+
kind: flow
32+
suiteIsolation: isolated
33+
isolationReason: Owns a naturally scheduled one-shot job, subagent lifecycle, and exact QA-channel delivery.
34+
channel: qa-channel
35+
retryCount: 0
36+
timeoutMs: 180000
37+
summary: Naturally fire a spawn-only isolated cron and require one exact child delivery before one-shot retirement.
38+
config:
39+
requiredProviderMode: mock-openai
40+
channelId: qa-room
41+
fireDelayMs: 12000
42+
duplicateWindowMs: 2000
43+
promptSnippet: Subagent direct fallback QA check
44+
workerSnippet: Subagent direct fallback worker
45+
expectedLabel: qa-direct-fallback-worker
46+
expectedMarker: QA-SUBAGENT-DIRECT-FALLBACK-OK
47+
prompt: "Subagent direct fallback QA check: spawn one native subagent worker. The worker must finish with exactly QA-SUBAGENT-DIRECT-FALLBACK-OK. After the spawn is accepted, finish without assistant text. Empty response exhaustion QA check. Do not use ACP."
48+
49+
flow:
50+
steps:
51+
- name: naturally fires an isolated spawn-only one-shot job
52+
actions:
53+
- call: waitForGatewayHealthy
54+
args:
55+
- ref: env
56+
- 120000
57+
- call: waitForQaChannelReady
58+
args:
59+
- ref: env
60+
- 120000
61+
- call: reset
62+
- set: requestCursorBefore
63+
value:
64+
expr: "(await fetchJson(`${env.mock.baseUrl}/debug/request-cursor`)).cursor"
65+
- set: runStartedAt
66+
value:
67+
expr: "Date.now()"
68+
- set: scheduledFor
69+
value:
70+
expr: "new Date(runStartedAt + config.fireDelayMs).toISOString()"
71+
- call: env.gateway.call
72+
saveAs: addedJob
73+
args:
74+
- cron.add
75+
- agentId: qa
76+
name:
77+
expr: "`qa-cron-spawn-only-${randomUUID()}`"
78+
enabled: true
79+
deleteAfterRun: true
80+
schedule:
81+
kind: at
82+
at:
83+
ref: scheduledFor
84+
sessionTarget: isolated
85+
wakeMode: now
86+
payload:
87+
kind: agentTurn
88+
timeoutSeconds: 90
89+
toolsAllow:
90+
- sessions_spawn
91+
- read
92+
message:
93+
ref: config.prompt
94+
delivery:
95+
mode: announce
96+
channel: qa-channel
97+
to:
98+
expr: "`channel:${config.channelId}`"
99+
- timeoutMs: 30000
100+
- set: jobId
101+
value:
102+
expr: "addedJob.id"
103+
- assert:
104+
expr: "Boolean(jobId) && addedJob.sessionTarget === 'isolated' && addedJob.deleteAfterRun === true && JSON.stringify(addedJob.payload?.toolsAllow) === JSON.stringify(['sessions_spawn', 'read'])"
105+
message:
106+
expr: "`expected an isolated delete-after-run cron job restricted to sessions_spawn and read, got ${JSON.stringify(addedJob)}`"
107+
- call: waitForCronRunCompletion
108+
saveAs: completedRun
109+
args:
110+
- callGateway:
111+
expr: "env.gateway.call.bind(env.gateway)"
112+
jobId:
113+
ref: jobId
114+
afterTs:
115+
ref: runStartedAt
116+
timeoutMs:
117+
expr: "liveTurnTimeoutMs(env, config.fireDelayMs + 90000)"
118+
- assert:
119+
expr: "Date.now() >= new Date(scheduledFor).getTime()"
120+
message: one-shot cron completed before its natural scheduled time
121+
- assert:
122+
expr: "completedRun.status === 'ok' && completedRun.delivered === true && completedRun.deliveryStatus === 'delivered'"
123+
message:
124+
expr: "`expected successful delivered spawn-only cron run, got ${JSON.stringify(completedRun)}`"
125+
- assert:
126+
expr: "String(completedRun.summary ?? '').trim() === config.expectedMarker"
127+
message:
128+
expr: "`cron summary did not preserve the child's exact reply: ${JSON.stringify(completedRun)}`"
129+
130+
- name: proves the parent accepted its child without producing assistant text
131+
actions:
132+
- set: scenarioRequests
133+
value:
134+
expr: "await fetchJson(`${env.mock.baseUrl}/debug/requests?after=${requestCursorBefore}`)"
135+
- set: parentRequests
136+
value:
137+
expr: "scenarioRequests.filter((request) => String(request.prompt ?? '').includes(config.promptSnippet))"
138+
- set: spawnRequests
139+
value:
140+
expr: "parentRequests.filter((request) => request.plannedToolName === 'sessions_spawn')"
141+
- set: terminalRequests
142+
value:
143+
expr: "parentRequests.filter((request) => !request.plannedToolName)"
144+
- assert:
145+
expr: "parentRequests.length === 2 && spawnRequests.length === 1 && terminalRequests.length === 1 && spawnRequests[0].plannedToolArgs?.label === config.expectedLabel && spawnRequests[0].cursor < terminalRequests[0].cursor && /empty response exhaustion qa check/i.test(String(terminalRequests[0].allInputText ?? ''))"
146+
message:
147+
expr: "`expected one child spawn followed by an empty tool-free parent response, saw ${JSON.stringify(parentRequests.map((request) => ({ tool: request.plannedToolName ?? null, label: request.plannedToolArgs?.label ?? null })))}`"
148+
- set: acceptedSpawn
149+
value:
150+
expr: "(() => { let result = JSON.parse(String(terminalRequests[0].toolOutput ?? 'null')); if (result?.status === 'completed') result = result.value; return typeof result === 'string' ? JSON.parse(result) : result; })()"
151+
- assert:
152+
expr: "acceptedSpawn?.status === 'accepted' && Boolean(String(acceptedSpawn.childSessionKey ?? '').trim()) && Boolean(String(acceptedSpawn.runId ?? '').trim())"
153+
message:
154+
expr: "`parent did not receive a successful child-spawn result before its empty response: ${JSON.stringify(acceptedSpawn)}`"
155+
- set: childRequests
156+
value:
157+
expr: "scenarioRequests.filter((request) => String(request.prompt ?? '').includes(config.workerSnippet))"
158+
- assert:
159+
expr: "childRequests.length === 1 && !childRequests[0].plannedToolName"
160+
message:
161+
expr: "`expected one child assistant reply without additional tools, saw ${JSON.stringify(childRequests.map((request) => request.plannedToolName ?? null))}`"
162+
163+
- name: delivers the exact child reply once and retires the one-shot job
164+
actions:
165+
- call: waitForOutboundMessage
166+
saveAs: deliveredReply
167+
args:
168+
- ref: state
169+
- lambda:
170+
params: [candidate]
171+
expr: "candidate.conversation.id === config.channelId && String(candidate.text ?? '').trim() === config.expectedMarker"
172+
- expr: "liveTurnTimeoutMs(env, 30000)"
173+
- call: sleep
174+
args:
175+
- expr: "config.duplicateWindowMs"
176+
- set: deliveredReplies
177+
value:
178+
expr: "getTransportSnapshot().messages.filter((message) => message.direction === 'outbound' && message.conversation.id === config.channelId && String(message.text ?? '').trim() === config.expectedMarker)"
179+
- assert:
180+
expr: "deliveredReplies.length === 1"
181+
message:
182+
expr: "`expected exactly one child reply on qa-channel, saw ${deliveredReplies.length}: ${JSON.stringify(deliveredReplies.map((message) => message.text))}`"
183+
- call: waitForCondition
184+
saveAs: retiredJobs
185+
args:
186+
- lambda:
187+
async: true
188+
expr: "env.gateway.call('cron.list', { includeDisabled: true }, { timeoutMs: 30000 }).then((page) => page.jobs.some((job) => job.id === jobId) ? undefined : page.jobs)"
189+
- expr: "liveTurnTimeoutMs(env, 30000)"
190+
- 250
191+
- assert:
192+
expr: "!retiredJobs.some((job) => job.id === jobId)"
193+
message: successful one-shot job was not retired after exact child delivery
194+
detailsExpr: "`child=${config.expectedLabel} accepted=true parentVisibleText=false delivery=${completedRun.deliveryStatus} reply=${deliveredReply.text} outboundCount=${deliveredReplies.length} retired=true`"

‎src/cron/isolated-agent/delivery-dispatch-types.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ export type DispatchCronDeliveryParams = {
2727
resolvedDelivery: DeliveryTargetResolution;
2828
deliveryRequested: boolean;
2929
skipHeartbeatDelivery: boolean;
30+
spawnOnlyHandoff: boolean;
3031
sourceDeliveryOutcome: SourceDeliveryOutcome;
3132
deliveryBestEffort: boolean;
3233
deliveryPayloadHasStructuredContent: boolean;

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

Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,7 @@ function makeBaseParams(overrides: {
214214
runStartedAt?: number;
215215
sessionTarget?: string;
216216
deliveryBestEffort?: boolean;
217+
spawnOnlyHandoff?: boolean;
217218
runSessionKey?: string;
218219
resolvedDeliveryMode?: "explicit" | "implicit";
219220
}): Parameters<typeof dispatchCronDelivery>[0] {
@@ -245,6 +246,7 @@ function makeBaseParams(overrides: {
245246
resolvedDelivery,
246247
deliveryRequested: overrides.deliveryRequested ?? true,
247248
skipHeartbeatDelivery: false,
249+
spawnOnlyHandoff: overrides.spawnOnlyHandoff ?? false,
248250
sourceDeliveryOutcome: {
249251
visibleDeliveries: [],
250252
verifiedMessageToolDelivery: false,
@@ -1101,6 +1103,169 @@ describe("dispatchCronDelivery — double-announce guard", () => {
11011103
});
11021104
});
11031105

1106+
it.each([
1107+
{
1108+
name: "active direct",
1109+
activeDescendants: true,
1110+
threadId: undefined,
1111+
deliveryBestEffort: false,
1112+
},
1113+
{
1114+
name: "active threaded",
1115+
activeDescendants: true,
1116+
threadId: "42",
1117+
deliveryBestEffort: false,
1118+
},
1119+
{
1120+
name: "completed direct",
1121+
activeDescendants: false,
1122+
threadId: undefined,
1123+
deliveryBestEffort: false,
1124+
},
1125+
{
1126+
name: "completed threaded",
1127+
activeDescendants: false,
1128+
threadId: "42",
1129+
deliveryBestEffort: false,
1130+
},
1131+
{
1132+
name: "active best-effort direct",
1133+
activeDescendants: true,
1134+
threadId: undefined,
1135+
deliveryBestEffort: true,
1136+
},
1137+
])(
1138+
"delivers $name accepted child results without parent text",
1139+
async ({ activeDescendants, deliveryBestEffort, threadId }) => {
1140+
const childReply = "Completed child result visible to the user.";
1141+
if (activeDescendants) {
1142+
vi.mocked(countActiveDescendantRuns).mockReturnValueOnce(1).mockReturnValueOnce(0);
1143+
} else {
1144+
vi.mocked(countActiveDescendantRuns).mockReturnValue(0);
1145+
}
1146+
vi.mocked(waitForDescendantSubagentSummary).mockResolvedValue(undefined);
1147+
vi.mocked(readDescendantSubagentFallbackReply).mockResolvedValue(childReply);
1148+
1149+
const params = makeBaseParams({
1150+
spawnOnlyHandoff: true,
1151+
deliveryBestEffort,
1152+
synthesizedText: "",
1153+
});
1154+
params.synthesizedText = undefined;
1155+
params.deliveryPayloads = [];
1156+
params.summary = undefined;
1157+
params.outputText = undefined;
1158+
params.resolvedDelivery = makeResolvedDelivery({ threadId });
1159+
1160+
const state = await dispatchCronDelivery(params);
1161+
1162+
expect(waitForDescendantSubagentSummary).toHaveBeenCalledTimes(activeDescendants ? 1 : 0);
1163+
expect(readDescendantSubagentFallbackReply).toHaveBeenCalledWith({
1164+
sessionKey: params.runSessionKey,
1165+
runStartedAt: params.runStartedAt,
1166+
});
1167+
expect(deliverOutboundPayloads).toHaveBeenCalledTimes(1);
1168+
expectDeliveryCall(0, {
1169+
channel: "telegram",
1170+
to: "123456",
1171+
...(threadId === undefined ? {} : { threadId }),
1172+
payloads: [{ text: childReply }],
1173+
});
1174+
expect(state.delivered).toBe(true);
1175+
expect(state.deliveryAttempted).toBe(true);
1176+
},
1177+
);
1178+
1179+
it("preserves a substantive parent synthesis after an accepted child has completed", async () => {
1180+
const parentReply = "Combined parent summary already includes every child result.";
1181+
vi.mocked(countActiveDescendantRuns).mockReturnValue(0);
1182+
1183+
const state = await dispatchCronDelivery(
1184+
makeBaseParams({ spawnOnlyHandoff: false, synthesizedText: parentReply }),
1185+
);
1186+
1187+
expect(readDescendantSubagentFallbackReply).not.toHaveBeenCalled();
1188+
expectDeliveryCall(0, { payloads: [{ text: parentReply }] });
1189+
expect(state.delivered).toBe(true);
1190+
});
1191+
1192+
it("immediately delivers a substantive threaded parent while its accepted child runs", async () => {
1193+
const parentReply = "Parent summary is ready for the existing thread.";
1194+
vi.mocked(countActiveDescendantRuns).mockReturnValue(1);
1195+
const params = makeBaseParams({ spawnOnlyHandoff: false, synthesizedText: parentReply });
1196+
params.resolvedDelivery = makeResolvedDelivery({ threadId: "42" });
1197+
1198+
const state = await dispatchCronDelivery(params);
1199+
1200+
expect(waitForDescendantSubagentSummary).not.toHaveBeenCalled();
1201+
expect(deliverOutboundPayloads).toHaveBeenCalledTimes(1);
1202+
expectDeliveryCall(0, { threadId: "42", payloads: [{ text: parentReply }] });
1203+
expect(state.delivered).toBe(true);
1204+
});
1205+
1206+
it.each([
1207+
{
1208+
name: "active child times out",
1209+
activeDescendants: 1,
1210+
error: "cron child-session handoff timed out before producing a final assistant payload",
1211+
},
1212+
{
1213+
name: "completed child has no output",
1214+
activeDescendants: 0,
1215+
error: "cron child-session handoff completed without a final assistant payload",
1216+
},
1217+
])("fails an accepted spawn-only handoff when $name", async ({ activeDescendants, error }) => {
1218+
vi.mocked(countActiveDescendantRuns).mockReturnValue(activeDescendants);
1219+
const params = makeBaseParams({ spawnOnlyHandoff: true, synthesizedText: "" });
1220+
params.synthesizedText = undefined;
1221+
params.deliveryPayloads = [];
1222+
params.summary = undefined;
1223+
params.outputText = undefined;
1224+
1225+
const state = await dispatchCronDelivery(params);
1226+
1227+
expectResultFields(state.result, {
1228+
status: "error",
1229+
error,
1230+
delivered: false,
1231+
deliveryAttempted: true,
1232+
});
1233+
expect(deliverOutboundPayloads).not.toHaveBeenCalled();
1234+
});
1235+
1236+
it("preserves abort precedence when an accepted child handoff is interrupted", async () => {
1237+
const abortReason = "scheduled run aborted while waiting for its child";
1238+
vi.mocked(countActiveDescendantRuns).mockReturnValue(1);
1239+
const params = makeBaseParams({ spawnOnlyHandoff: true, synthesizedText: "" });
1240+
params.synthesizedText = undefined;
1241+
params.deliveryPayloads = [];
1242+
params.summary = undefined;
1243+
params.outputText = undefined;
1244+
params.isAborted = () => true;
1245+
params.abortReason = () => abortReason;
1246+
1247+
const state = await dispatchCronDelivery(params);
1248+
1249+
expect(waitForDescendantSubagentSummary).toHaveBeenCalledTimes(1);
1250+
expectResultFields(state.result, { status: "error", error: abortReason });
1251+
expect(deliverOutboundPayloads).not.toHaveBeenCalled();
1252+
});
1253+
1254+
it("keeps an empty no-spawn parent silent", async () => {
1255+
const params = makeBaseParams({ synthesizedText: "" });
1256+
params.synthesizedText = undefined;
1257+
params.deliveryPayloads = [];
1258+
params.summary = undefined;
1259+
params.outputText = undefined;
1260+
1261+
const state = await dispatchCronDelivery(params);
1262+
1263+
expect(waitForDescendantSubagentSummary).not.toHaveBeenCalled();
1264+
expect(readDescendantSubagentFallbackReply).not.toHaveBeenCalled();
1265+
expect(deliverOutboundPayloads).not.toHaveBeenCalled();
1266+
expect(state.deliveryAttempted).toBe(false);
1267+
});
1268+
11041269
it("uses the run-scoped session key for isolated cron descendant fallback delivery", async () => {
11051270
const runStartedAt = 1_000;
11061271
const agentSessionKey = "agent:main:cron:daily-monitor";

0 commit comments

Comments
 (0)