Skip to content

Commit 037850c

Browse files
committed
fix(cron): deliver final descendant results for threaded jobs
## What Problem This Solves Scheduled jobs that handed work to child agents could publish interim orchestration text, lose the final descendant result, or misroute structured threaded output across channel-specific delivery targets. ## Why This Change Was Made The cron delivery owner now treats completed and awaited child results through one canonical final-output flow, recognizes interim-only spawn handoffs, preserves structured payload classification, and chooses threaded direct versus normal delivery from the prepared target contract. ## User Impact Scheduled Telegram, Discord, Slack, Matrix, and Teams jobs deliver their actual final child response to the intended thread instead of leaking placeholder text, dropping completed work, or emitting duplicate announcements. ## Context Exact final-source trusted remote proof passed 259 tests across seven focused files, including actual channel target normalization and all five channel delivery families. The previously failing core and plugin-boundary type-aware lint gate passed after correcting the implementation; all six changed files pass formatting. Production code decreases by 12 lines.
1 parent 8fdf757 commit 037850c

6 files changed

Lines changed: 354 additions & 65 deletions

File tree

‎src/cron/isolated-agent.helpers.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -313,7 +313,7 @@ describe("resolveCronPayloadOutcome", () => {
313313
expect(result.deliveryPayload).toEqual({ text: "section 2" });
314314
});
315315

316-
it("keeps structured-content detection scoped to the last delivery payload", () => {
316+
it("detects structured content anywhere in the selected delivery batch", () => {
317317
const result = resolveCronPayloadOutcome({
318318
payloads: [{ mediaUrl: "https://example.com/report.png" }, { text: "final text" }],
319319
finalAssistantVisibleText: "full final report",
@@ -326,7 +326,7 @@ describe("resolveCronPayloadOutcome", () => {
326326
]);
327327
expect(result.outputText).toBe("final text");
328328
expect(result.synthesizedText).toBe("final text");
329-
expect(result.deliveryPayloadHasStructuredContent).toBe(false);
329+
expect(result.deliveryPayloadHasStructuredContent).toBe(true);
330330
});
331331

332332
it("keeps presentation-only delivery payloads instead of collapsing to final text", () => {

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

Lines changed: 205 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,16 @@ import { createRequireRecord } from "openclaw/plugin-sdk/test-fixtures";
1414
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
1515
import { SILENT_REPLY_TOKEN } from "../../auto-reply/tokens.js";
1616
import * as deliveryQueueSqlite from "../../infra/delivery-queue-sqlite.js";
17+
import {
18+
captureActivePluginRegistrySnapshot,
19+
restoreActivePluginRegistrySnapshot,
20+
setActivePluginRegistry,
21+
} from "../../plugins/runtime.js";
22+
import {
23+
createDirectOutboundTestAdapter,
24+
createOutboundTestPlugin,
25+
createTestRegistry,
26+
} from "../../test-utils/channel-plugins.js";
1727

1828
const directCronCompletionRetention = {
1929
idPrefix: "cron-direct-delivery:v1:",
@@ -1172,6 +1182,130 @@ describe("dispatchCronDelivery — double-announce guard", () => {
11721182
},
11731183
);
11741184

1185+
it.each([
1186+
{
1187+
name: "active Telegram topic",
1188+
channel: "telegram",
1189+
to: "123456",
1190+
threadId: 42,
1191+
activeDescendants: true,
1192+
deliveryBestEffort: false,
1193+
},
1194+
{
1195+
name: "completed Telegram topic",
1196+
channel: "telegram",
1197+
to: "123456",
1198+
threadId: "42",
1199+
activeDescendants: false,
1200+
deliveryBestEffort: false,
1201+
},
1202+
{
1203+
name: "active Discord thread",
1204+
channel: "discord",
1205+
to: "123456789012345678",
1206+
threadId: "123456789012345679",
1207+
activeDescendants: true,
1208+
deliveryBestEffort: false,
1209+
},
1210+
{
1211+
name: "completed Slack thread",
1212+
channel: "slack",
1213+
to: "C1234567890",
1214+
threadId: "1712345678.123456",
1215+
activeDescendants: false,
1216+
deliveryBestEffort: false,
1217+
},
1218+
{
1219+
name: "active Matrix thread",
1220+
channel: "matrix",
1221+
to: "!room:example.org",
1222+
threadId: "$event:example.org",
1223+
activeDescendants: true,
1224+
deliveryBestEffort: false,
1225+
},
1226+
{
1227+
name: "completed Microsoft Teams thread",
1228+
channel: "msteams",
1229+
1230+
threadId: "1712345678901",
1231+
activeDescendants: false,
1232+
deliveryBestEffort: false,
1233+
},
1234+
{
1235+
name: "active best-effort Slack thread",
1236+
channel: "slack",
1237+
to: "C1234567890",
1238+
threadId: "1712345678.654321",
1239+
activeDescendants: true,
1240+
deliveryBestEffort: true,
1241+
},
1242+
])(
1243+
"delivers the child result instead of an interim parent reply to an $name",
1244+
async ({ activeDescendants, channel, deliveryBestEffort, threadId, to }) => {
1245+
const parentReply = "on it, pulling everything together";
1246+
const childReply = "Completed child result visible to the user.";
1247+
vi.mocked(isLikelyInterimCronMessage).mockImplementation((text) => text === parentReply);
1248+
if (activeDescendants) {
1249+
vi.mocked(countActiveDescendantRuns).mockReturnValueOnce(1).mockReturnValueOnce(0);
1250+
vi.mocked(waitForDescendantSubagentSummary).mockResolvedValue(childReply);
1251+
} else {
1252+
vi.mocked(countActiveDescendantRuns).mockReturnValue(0);
1253+
vi.mocked(readDescendantSubagentFallbackReply).mockResolvedValue(childReply);
1254+
}
1255+
1256+
const params = makeBaseParams({
1257+
spawnOnlyHandoff: true,
1258+
synthesizedText: parentReply,
1259+
deliveryBestEffort,
1260+
});
1261+
params.agentSessionKey = "agent:main:cron:test-job";
1262+
params.runSessionKey = "agent:main:cron:test-job:run:test-session-id";
1263+
params.job.deleteAfterRun = true;
1264+
params.resolvedDelivery = makeResolvedDelivery({ channel, to, threadId });
1265+
const normalizeTarget = vi.fn((raw: string) => raw.trim());
1266+
const previousPluginRegistry = captureActivePluginRegistrySnapshot();
1267+
let state: Awaited<ReturnType<typeof dispatchCronDelivery>>;
1268+
try {
1269+
setActivePluginRegistry(
1270+
createTestRegistry([
1271+
{
1272+
pluginId: channel,
1273+
source: "test",
1274+
plugin: createOutboundTestPlugin({
1275+
id: channel,
1276+
outbound: createDirectOutboundTestAdapter({ channel }),
1277+
messaging: { normalizeTarget },
1278+
}),
1279+
},
1280+
]),
1281+
);
1282+
state = await dispatchCronDelivery(params);
1283+
} finally {
1284+
restoreActivePluginRegistrySnapshot(previousPluginRegistry);
1285+
}
1286+
1287+
expect(waitForDescendantSubagentSummary).toHaveBeenCalledTimes(activeDescendants ? 1 : 0);
1288+
if (activeDescendants) {
1289+
expect(waitForDescendantSubagentSummary).toHaveBeenCalledWith(
1290+
expect.objectContaining({ initialReply: parentReply }),
1291+
);
1292+
}
1293+
expect(deliverOutboundPayloads).toHaveBeenCalledTimes(1);
1294+
expectDeliveryCall(0, {
1295+
channel,
1296+
to,
1297+
threadId,
1298+
payloads: [{ text: childReply }],
1299+
});
1300+
expect(normalizeTarget).toHaveBeenCalledWith(to);
1301+
expect(state.delivered).toBe(true);
1302+
expect(state.cronRunSessionCleanupAttempted).toBe(true);
1303+
expect(callGateway).toHaveBeenCalledWith(
1304+
expect.objectContaining({ method: "sessions.delete" }),
1305+
);
1306+
},
1307+
);
1308+
11751309
it("preserves a substantive parent synthesis after an accepted child has completed", async () => {
11761310
const parentReply = "Combined parent summary already includes every child result.";
11771311
vi.mocked(countActiveDescendantRuns).mockReturnValue(0);
@@ -1199,35 +1333,88 @@ describe("dispatchCronDelivery — double-announce guard", () => {
11991333
expect(state.delivered).toBe(true);
12001334
});
12011335

1336+
it("preserves structured parent output followed by an interim threaded reply", async () => {
1337+
const mediaPayload = { mediaUrl: "https://example.invalid/chart.png" };
1338+
const interimPayload = { text: "on it, pulling everything together" };
1339+
vi.mocked(countActiveDescendantRuns).mockReturnValue(1);
1340+
vi.mocked(isLikelyInterimCronMessage).mockReturnValue(true);
1341+
const params = makeBaseParams({
1342+
spawnOnlyHandoff: false,
1343+
synthesizedText: interimPayload.text,
1344+
});
1345+
params.deliveryPayloadHasStructuredContent = true;
1346+
params.deliveryPayloads = [mediaPayload, interimPayload];
1347+
params.resolvedDelivery = makeResolvedDelivery({ threadId: "42" });
1348+
1349+
const state = await dispatchCronDelivery(params);
1350+
1351+
expect(waitForDescendantSubagentSummary).not.toHaveBeenCalled();
1352+
expect(deliverOutboundPayloads).toHaveBeenCalledOnce();
1353+
expectDeliveryCall(0, {
1354+
threadId: "42",
1355+
payloads: [mediaPayload, interimPayload],
1356+
});
1357+
expect(state.delivered).toBe(true);
1358+
});
1359+
12021360
it.each([
12031361
{
1204-
name: "active child times out",
1362+
name: "active child with no parent text times out",
12051363
activeDescendants: 1,
1364+
parentReply: undefined,
12061365
error: "cron child-session handoff timed out before producing a final assistant payload",
12071366
},
12081367
{
1209-
name: "completed child has no output",
1368+
name: "completed child with no parent text has no output",
12101369
activeDescendants: 0,
1370+
parentReply: undefined,
12111371
error: "cron child-session handoff completed without a final assistant payload",
12121372
},
1213-
])("fails an accepted spawn-only handoff when $name", async ({ activeDescendants, error }) => {
1214-
vi.mocked(countActiveDescendantRuns).mockReturnValue(activeDescendants);
1215-
const params = makeBaseParams({ spawnOnlyHandoff: true, synthesizedText: "" });
1216-
params.synthesizedText = undefined;
1217-
params.deliveryPayloads = [];
1218-
params.summary = undefined;
1219-
params.outputText = undefined;
1373+
{
1374+
name: "active child leaves only the interim parent reply",
1375+
activeDescendants: 1,
1376+
parentReply: "on it, pulling everything together",
1377+
error: "cron child-session handoff timed out before producing a final assistant payload",
1378+
},
1379+
{
1380+
name: "completed child leaves only the interim parent reply",
1381+
activeDescendants: 0,
1382+
parentReply: "on it, pulling everything together",
1383+
error: "cron child-session handoff completed without a final assistant payload",
1384+
},
1385+
])(
1386+
"keeps a one-shot child-owned handoff when $name",
1387+
async ({ activeDescendants, error, parentReply }) => {
1388+
vi.mocked(countActiveDescendantRuns).mockReturnValue(activeDescendants);
1389+
vi.mocked(isLikelyInterimCronMessage).mockImplementation((text) => text === parentReply);
1390+
const params = makeBaseParams({
1391+
spawnOnlyHandoff: true,
1392+
synthesizedText: parentReply ?? "",
1393+
});
1394+
params.agentSessionKey = "agent:main:cron:test-job";
1395+
params.job.deleteAfterRun = true;
1396+
params.resolvedDelivery = makeResolvedDelivery({ threadId: "42" });
1397+
if (!parentReply) {
1398+
params.synthesizedText = undefined;
1399+
params.deliveryPayloads = [];
1400+
params.summary = undefined;
1401+
params.outputText = undefined;
1402+
}
12201403

1221-
const state = await dispatchCronDelivery(params);
1404+
const state = await dispatchCronDelivery(params);
12221405

1223-
expectResultFields(state.result, {
1224-
status: "error",
1225-
error,
1226-
delivered: false,
1227-
deliveryAttempted: true,
1228-
});
1229-
expect(deliverOutboundPayloads).not.toHaveBeenCalled();
1230-
});
1406+
expectResultFields(state.result, {
1407+
status: "error",
1408+
error,
1409+
delivered: false,
1410+
deliveryAttempted: true,
1411+
});
1412+
expect(state.synthesizedText).toBeUndefined();
1413+
expect(state.deliveryPayloads).toEqual([]);
1414+
expect(deliverOutboundPayloads).not.toHaveBeenCalled();
1415+
expect(callGateway).not.toHaveBeenCalled();
1416+
},
1417+
);
12311418

12321419
it("preserves abort precedence when an accepted child handoff is interrupted", async () => {
12331420
const abortReason = "scheduled run aborted while waiting for its child";

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

Lines changed: 25 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -70,17 +70,6 @@ const deliveryOutboundRuntimeLoader = createLazyImportLoader(
7070
const subagentFollowupRuntimeLoader = createLazyImportLoader(
7171
() => import("./subagent-followup.runtime.js"),
7272
);
73-
async function loadDeliveryOutboundRuntime(): Promise<
74-
typeof import("./delivery-outbound.runtime.js")
75-
> {
76-
return await deliveryOutboundRuntimeLoader.load();
77-
}
78-
79-
async function loadSubagentFollowupRuntime(): Promise<
80-
typeof import("./subagent-followup.runtime.js")
81-
> {
82-
return await subagentFollowupRuntimeLoader.load();
83-
}
8473

8574
export {
8675
cleanupDirectCronSession,
@@ -201,7 +190,7 @@ export async function dispatchCronDelivery(
201190
createOutboundSendDeps,
202191
resolveAgentOutboundIdentity,
203192
sendDurableMessageBatch,
204-
} = await loadDeliveryOutboundRuntime();
193+
} = await deliveryOutboundRuntimeLoader.load();
205194
const identity = resolveAgentOutboundIdentity(params.cfgWithAgentDefaults, params.agentId);
206195
try {
207196
const summaryFallbackText = resolveDirectCronSummaryFallbackText({
@@ -590,7 +579,7 @@ export async function dispatchCronDelivery(
590579
const needsSubagentFollowupRuntime =
591580
shouldCheckCompletedDescendants || activeSubagentRuns > 0 || expectedSubagentFollowup;
592581
const subagentFollowupRuntime = needsSubagentFollowupRuntime
593-
? await loadSubagentFollowupRuntime()
582+
? await subagentFollowupRuntimeLoader.load()
594583
: undefined;
595584
// Also check for already-completed descendants. If the subagent finished
596585
// before delivery-dispatch runs, activeSubagentRuns is 0 and
@@ -604,11 +593,13 @@ export async function dispatchCronDelivery(
604593
})
605594
: undefined;
606595
const hadDescendants = activeSubagentRuns > 0 || Boolean(completedDescendantReply);
596+
// Already-finished and awaited children share the same final-output owner.
597+
let finalReply = completedDescendantReply;
607598
if (
608599
(!params.deliveryBestEffort || spawnOnlyHandoff) &&
609600
(activeSubagentRuns > 0 || expectedSubagentFollowup)
610601
) {
611-
let finalReply = await subagentFollowupRuntime?.waitForDescendantSubagentSummary({
602+
finalReply = await subagentFollowupRuntime?.waitForDescendantSubagentSummary({
612603
sessionKey: subagentFollowupSessionKey,
613604
initialReply: initialSynthesizedText,
614605
timeoutMs: params.timeoutMs,
@@ -623,23 +614,23 @@ export async function dispatchCronDelivery(
623614
runStartedAt: params.runStartedAt,
624615
});
625616
}
626-
if (finalReply && activeSubagentRuns === 0) {
627-
outputText = finalReply;
628-
summary = pickSummaryFromOutput(finalReply) ?? summary;
629-
synthesizedText = finalReply;
630-
deliveryPayloads = [{ text: finalReply }];
631-
}
632-
} else if (completedDescendantReply) {
633-
// Descendants already finished before we got here. Use their output
634-
// directly instead of the cron agent's interim text.
635-
outputText = completedDescendantReply;
636-
summary = pickSummaryFromOutput(completedDescendantReply) ?? summary;
637-
synthesizedText = completedDescendantReply;
638-
deliveryPayloads = [{ text: completedDescendantReply }];
639617
}
640-
if (spawnOnlyHandoff && !synthesizedText?.trim()) {
618+
if (finalReply && activeSubagentRuns === 0) {
619+
outputText = finalReply;
620+
summary = pickSummaryFromOutput(finalReply) ?? summary;
621+
synthesizedText = finalReply;
622+
deliveryPayloads = [{ text: finalReply }];
623+
}
624+
const unchangedInterimHandoff =
625+
synthesizedText?.trim() === initialSynthesizedText &&
626+
isLikelyInterimCronMessage(initialSynthesizedText);
627+
if (spawnOnlyHandoff && (!synthesizedText?.trim() || unchangedInterimHandoff)) {
641628
// An accepted spawn is the turn's only completion; retiring it without
642629
// child output permanently loses one-shot scheduled work.
630+
synthesizedText = undefined;
631+
outputText = undefined;
632+
summary = undefined;
633+
deliveryPayloads = [];
643634
const error = params.isAborted()
644635
? params.abortReason()
645636
: activeSubagentRuns > 0
@@ -669,8 +660,7 @@ export async function dispatchCronDelivery(
669660
}
670661
if (
671662
hadDescendants &&
672-
synthesizedText?.trim() === initialSynthesizedText &&
673-
isLikelyInterimCronMessage(initialSynthesizedText) &&
663+
unchangedInterimHandoff &&
674664
!isSilentReplyText(initialSynthesizedText, SILENT_REPLY_TOKEN)
675665
) {
676666
// Descendants existed but no post-orchestration synthesis arrived AND
@@ -739,16 +729,11 @@ export async function dispatchCronDelivery(
739729
const useDirectDelivery =
740730
params.deliveryPayloadHasStructuredContent ||
741731
(params.resolvedDelivery.threadId != null && !params.spawnOnlyHandoff);
742-
if (useDirectDelivery) {
743-
const directResult = await deliverViaDirectAndCleanup(params.resolvedDelivery);
744-
if (directResult) {
745-
return buildDeliveryState(directResult);
746-
}
747-
} else {
748-
const finalizedTextResult = await finalizeTextDelivery(params.resolvedDelivery);
749-
if (finalizedTextResult) {
750-
return buildDeliveryState(finalizedTextResult);
751-
}
732+
const deliveryResult = useDirectDelivery
733+
? await deliverViaDirectAndCleanup(params.resolvedDelivery)
734+
: await finalizeTextDelivery(params.resolvedDelivery);
735+
if (deliveryResult) {
736+
return buildDeliveryState(deliveryResult);
752737
}
753738
}
754739

0 commit comments

Comments
 (0)