Skip to content

Commit ba7edcd

Browse files
committed
fix(auto-reply): reject undelivered ask_user prompts
1 parent 5b96cbc commit ba7edcd

5 files changed

Lines changed: 148 additions & 18 deletions

‎src/auto-reply/reply/dispatch-from-config.execute.ts‎

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ import {
2828
} from "./dispatch-from-config.payloads.js";
2929
import { extendPreparedDispatchState } from "./dispatch-from-config.phase-state.js";
3030
import type { PrepareDispatchExecutionReadyState } from "./dispatch-from-config.prepare-execution.js";
31+
import { requireQueuedReplyDelivery } from "./dispatch-from-config.turn-ledger.js";
3132
import { bindPreparedReplyDispatchRuntime } from "./prepared-reply-dispatch-context.js";
32-
import { waitForReplyDispatcherIdle } from "./reply-dispatcher.js";
3333
import { REPLY_OPERATION_RUN_STATE } from "./reply-operation-run-state.js";
3434

3535
export async function executeDispatch(state: PrepareDispatchExecutionReadyState) {
@@ -209,10 +209,8 @@ export async function executeDispatch(state: PrepareDispatchExecutionReadyState)
209209
markInboundDedupeReplayUnsafe();
210210
// Buffered commentary preceded this tool; land it before the summary.
211211
await flushPendingCommentaryProgress();
212-
// When the operator opts into messages.suppressToolErrors, never
213-
// surface tool-error tool-result payloads as channel progress,
214-
// regardless of source delivery mode. payloads.ts already drops
215-
// the warning text; this drops the visible progress delivery too.
212+
// Tool-error suppression covers visible progress as well as warning text,
213+
// regardless of source delivery mode.
216214
if (
217215
payload.isError === true &&
218216
replyConfig.messages?.suppressToolErrors === true
@@ -332,15 +330,13 @@ export async function executeDispatch(state: PrepareDispatchExecutionReadyState)
332330
if (shouldRouteToOriginating) {
333331
await sendPayloadAsync(deliveryPayload, undefined, false);
334332
} else {
335-
markInboundDedupeReplayUnsafe();
336-
const delivered = state.turnLedger.sendQueued("tool", deliveryPayload).queued;
337-
if (delivered && hasAskUserPayload(deliveryPayload)) {
338-
// ask_user blocks until this callback resolves; drain its prompt now
339-
// or the answerable UI can remain queued behind the blocked agent run.
340-
await waitForReplyDispatcherIdle(
333+
const delivery = state.turnLedger.sendQueued("tool", deliveryPayload);
334+
if (hasAskUserPayload(deliveryPayload)) {
335+
await requireQueuedReplyDelivery({
336+
delivery,
341337
dispatcher,
342-
getDispatchAbortOperation()?.abortSignal,
343-
);
338+
abortSignal: getDispatchAbortOperation()?.abortSignal,
339+
});
344340
}
345341
}
346342
};

‎src/auto-reply/reply/dispatch-from-config.prepare-delivery.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
} from "../reply-payload.js";
1212
import { resolveRoutedPolicyConversationType } from "./dispatch-from-config.context.js";
1313
import type { GatherDispatchRequestReadyState } from "./dispatch-from-config.gather.js";
14+
import { hasAskUserPayload } from "./dispatch-from-config.payloads.js";
1415
import { extendPreparedDispatchState } from "./dispatch-from-config.phase-state.js";
1516
import {
1617
loadReplyMediaPathsRuntime,
@@ -212,6 +213,9 @@ export async function prepareDispatchDelivery(state: GatherDispatchRequestReadyS
212213
if (result && !result.ok) {
213214
logVerbose(`dispatch-from-config: route-reply failed: ${result.error ?? "unknown error"}`);
214215
}
216+
if (hasAskUserPayload(payload) && !effectiveAbortSignal?.aborted && !result?.delivered) {
217+
throw new Error("ask_user prompt delivery failed");
218+
}
215219
return result;
216220
};
217221

‎src/auto-reply/reply/dispatch-from-config.routing.test-utils.ts‎

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import {
2626
globalBeforeAll0,
2727
describe0BeforeEach0,
2828
} from "./dispatch-from-config.test-harness.js";
29+
import { createReplyDispatcher } from "./reply-dispatcher.js";
2930
import { resolveRoutedDeliveryThreadId } from "./routed-delivery-thread.js";
3031
import { buildTestCtx } from "./test-ctx.js";
3132

@@ -427,6 +428,110 @@ describe("dispatchReplyFromConfig", () => {
427428
).toBe(true);
428429
});
429430

431+
it.each([
432+
["cancelled", "cancelled", true],
433+
["failed before transport", "failed-before-deliver", true],
434+
["delivered", "delivered", false],
435+
["failed during transport", "failed-deliver", false],
436+
] as const)(
437+
"settles ask_user delivery when the prompt is %s",
438+
async (_name, outcome, rejects) => {
439+
hookMocks.runner.hasHooks.mockReturnValue(false);
440+
const deliver = vi.fn(async (_payload: ReplyPayload, info: { kind: string }) => {
441+
if (outcome === "failed-deliver" && info.kind === "tool") {
442+
throw new Error("transport failure");
443+
}
444+
});
445+
const dispatcher = createReplyDispatcher({
446+
deliver,
447+
beforeDeliver: async (candidate, info) => {
448+
if (info.kind !== "tool") {
449+
return candidate;
450+
}
451+
if (outcome === "cancelled") {
452+
return null;
453+
}
454+
if (outcome === "failed-before-deliver") {
455+
throw new Error("before-delivery failure");
456+
}
457+
return candidate;
458+
},
459+
});
460+
const payload = {
461+
text: "Question for you: Where should this deploy?",
462+
channelData: { askUser: { questionId: "question-not-delivered" } },
463+
} satisfies ReplyPayload;
464+
465+
const dispatch = dispatchReplyFromConfig({
466+
ctx: buildTestCtx({ Provider: "telegram", ChatType: "direct" }),
467+
cfg: emptyConfig,
468+
dispatcher,
469+
replyResolver: async (_ctx, opts) => {
470+
await requireToolResultHandler(opts?.onToolResult)(payload);
471+
return { text: "done" };
472+
},
473+
});
474+
475+
if (rejects) {
476+
await expect(dispatch).rejects.toThrow();
477+
} else {
478+
await expect(dispatch).resolves.toMatchObject({ queuedFinal: true });
479+
}
480+
},
481+
);
482+
483+
it("rejects ask_user prompts not delivered to the originating channel", async () => {
484+
setNoAbort();
485+
installThreadingTestPlugin({ id: "telegram" });
486+
mocks.routeReply.mockResolvedValue({ ok: false, delivered: false, error: "not delivered" });
487+
const payload = {
488+
text: "Question for you: Where should this deploy?",
489+
channelData: { askUser: { questionId: "question-not-routed" } },
490+
} satisfies ReplyPayload;
491+
const dispatcher = createDispatcher();
492+
const ctx = buildTestCtx({
493+
Provider: "webchat",
494+
Surface: "telegram",
495+
OriginatingChannel: "telegram",
496+
OriginatingTo: "telegram:999",
497+
});
498+
const replyResolver = async (
499+
_ctx: MsgContext,
500+
opts?: GetReplyOptions,
501+
_cfg?: OpenClawConfig,
502+
) => {
503+
await requireToolResultHandler(opts?.onToolResult)(payload);
504+
return undefined;
505+
};
506+
507+
await expect(
508+
dispatchReplyFromConfig({ ctx, cfg: emptyConfig, dispatcher, replyResolver }),
509+
).rejects.toThrow();
510+
});
511+
512+
it("rejects ask_user prompts declined by the dispatcher", async () => {
513+
setNoAbort();
514+
const payload = {
515+
text: "Question for you: Where should this deploy?",
516+
channelData: { askUser: { questionId: "question-not-admitted" } },
517+
} satisfies ReplyPayload;
518+
const dispatcher = createDispatcher();
519+
vi.mocked(dispatcher.sendToolResult).mockReturnValue(false);
520+
const ctx = buildTestCtx({ Provider: "telegram", ChatType: "direct" });
521+
const replyResolver = async (
522+
_ctx: MsgContext,
523+
opts?: GetReplyOptions,
524+
_cfg?: OpenClawConfig,
525+
) => {
526+
await requireToolResultHandler(opts?.onToolResult)(payload);
527+
return undefined;
528+
};
529+
530+
await expect(
531+
dispatchReplyFromConfig({ ctx, cfg: emptyConfig, dispatcher, replyResolver }),
532+
).rejects.toThrow();
533+
});
534+
430535
it("delivers approval-unavailable notices when verbose tool progress is disabled", async () => {
431536
setNoAbort();
432537
const payload = {

‎src/auto-reply/reply/dispatch-from-config.turn-ledger.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,12 @@
55
// no-visible-reply fallback gate with a fresh inference flag.
66
import { hasOutboundReplyContent } from "openclaw/plugin-sdk/reply-payload";
77
import type { ReplyPayload } from "../reply-payload.js";
8+
import { runWithDispatchAbortSignal } from "./dispatch-from-config.abort.js";
89
import {
910
captureReplyDispatchDeliveryOutcome,
11+
isReplyDispatchProvenInvisible,
1012
type ReplyDispatchDeliveryOutcome,
13+
waitForReplyDispatcherIdle,
1114
} from "./reply-dispatcher.js";
1215
import type { ReplyDispatchKind, ReplyDispatcher } from "./reply-dispatcher.types.js";
1316

@@ -40,6 +43,27 @@ type ReplyTurnLedger = {
4043
hasForeignQueuedAdmissions: () => boolean;
4144
};
4245

46+
export async function requireQueuedReplyDelivery(params: {
47+
delivery: LedgerQueuedSend;
48+
dispatcher: Pick<ReplyDispatcher, "waitForIdle">;
49+
abortSignal: AbortSignal | undefined;
50+
}): Promise<void> {
51+
if (!params.delivery.queued) {
52+
throw new Error("queued reply delivery failed");
53+
}
54+
const outcome = params.delivery.outcome;
55+
// Core dispatchers expose the payload's exact settlement. Custom dispatchers
56+
// expose only an idle barrier, which preserves their existing admission contract.
57+
if (!outcome) {
58+
await waitForReplyDispatcherIdle(params.dispatcher, params.abortSignal);
59+
return;
60+
}
61+
const settledOutcome = await runWithDispatchAbortSignal(params.abortSignal, () => outcome);
62+
if (isReplyDispatchProvenInvisible(settledOutcome)) {
63+
throw new Error("queued reply delivery failed");
64+
}
65+
}
66+
4367
export function createReplyTurnLedger(dispatcher: ReplyDispatcher): ReplyTurnLedger {
4468
let visibleDeliveries = 0;
4569
let queuedAdmissions = 0;
@@ -80,7 +104,7 @@ export function createReplyTurnLedger(dispatcher: ReplyDispatcher): ReplyTurnLed
80104
// chunked sends may already have shown partial content, so only
81105
// outcomes that never reached the transport ("cancelled",
82106
// "failed-before-deliver") count as proven-invisible.
83-
if (contentful && outcome !== "cancelled" && outcome !== "failed-before-deliver") {
107+
if (contentful && !isReplyDispatchProvenInvisible(outcome)) {
84108
visibleDeliveries += 1;
85109
}
86110
}),

‎src/auto-reply/reply/reply-dispatcher.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,10 @@ export type ReplyDispatchDeliveryOutcome =
5858
| "failed-before-deliver"
5959
| "failed-deliver";
6060

61+
export function isReplyDispatchProvenInvisible(outcome: ReplyDispatchDeliveryOutcome): boolean {
62+
return outcome === "cancelled" || outcome === "failed-before-deliver";
63+
}
64+
6165
function isRetryableNoSendFailure(error: unknown): boolean {
6266
return (
6367
isProvenDeliveryNotSentError(error) &&
@@ -624,10 +628,7 @@ export function createReplyDispatcher(options: ReplyDispatcherOptions): ReplyDis
624628
}
625629
const dispatchInfo = buildReplyDispatchRuntimeInfo(normalized, kind);
626630
deliveryOutcome = await deliverOnce(normalized, dispatchInfo);
627-
if (
628-
deliveryFallback &&
629-
(deliveryOutcome === "cancelled" || deliveryOutcome === "failed-before-deliver")
630-
) {
631+
if (deliveryFallback && isReplyDispatchProvenInvisible(deliveryOutcome)) {
631632
deliveryOutcome = await deliverOnce(deliveryFallback, dispatchInfo);
632633
}
633634
if (deliveryOutcome === "cancelled") {

0 commit comments

Comments
 (0)