Skip to content

Commit 724d257

Browse files
committed
fix(gateway): deliver queued WebChat replies after source completion
1 parent a74080d commit 724d257

13 files changed

Lines changed: 439 additions & 41 deletions

‎src/auto-reply/reply/followup-delivery.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -958,6 +958,45 @@ describe("deliverFollowupDecision", () => {
958958
}
959959
});
960960

961+
it("keeps a queued WebChat reply bound to its original source dispatcher", async () => {
962+
const laterDispatcher = vi.fn(async (_payload: ReplyPayload) => {});
963+
const sourceDispatcher = vi.fn(async () => {});
964+
const turn = createTurn();
965+
turn.queued.originatingChannel = "webchat";
966+
turn.queued.originatingTo = undefined;
967+
turn.queued.queuedFollowupReplyDisposition = { kind: "deliver", deliver: sourceDispatcher };
968+
deliveryState.followupRoute = { route: "dispatcher" };
969+
try {
970+
await deliverFollowupDecision({
971+
decision: { kind: "deliver", payloads: [{ text: "one" }, { text: "two" }] },
972+
turn,
973+
defaults: createDefaults(laterDispatcher),
974+
runId: "source-run",
975+
runFollowup: vi.fn(async () => {}),
976+
});
977+
expect(sourceDispatcher).toHaveBeenCalledWith({
978+
kind: "queued-followup",
979+
runId: "source-run",
980+
originatingChannel: "webchat",
981+
payloads: [{ text: "one" }, { text: "two" }],
982+
});
983+
turn.queued.queuedFollowupReplyDisposition = {
984+
kind: "drop",
985+
reason: "source-unavailable",
986+
};
987+
await deliverFollowupDecision({
988+
decision: { kind: "deliver", payloads: [{ text: "must stay dropped" }] },
989+
turn,
990+
defaults: createDefaults(laterDispatcher),
991+
runId: "dropped-run",
992+
runFollowup: vi.fn(async () => {}),
993+
});
994+
expect(laterDispatcher).not.toHaveBeenCalled();
995+
} finally {
996+
deliveryState.followupRoute = undefined;
997+
}
998+
});
999+
9611000
it("allows the latest same-channel dispatcher to recover a route failure", async () => {
9621001
const onBlockReply = vi.fn(async (_payload: ReplyPayload) => {});
9631002
deliveryState.routeReply.mockReset();

‎src/auto-reply/reply/followup-delivery.ts‎

Lines changed: 37 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,10 @@ export function resolveFollowupDeliveryDecision(params: {
7676
if (turn.sendPolicy === "deny") {
7777
return { kind: "suppress", reason: "send-policy" };
7878
}
79-
if (turn.queued.currentInboundEventKind === "room_event") {
79+
if (
80+
turn.queued.currentInboundEventKind === "room_event" &&
81+
!isInternalMessageChannel(turn.queued.originatingChannel)
82+
) {
8083
return { kind: "suppress", reason: "room-event" };
8184
}
8285
if (
@@ -322,7 +325,15 @@ async function sendFollowupPayloads(params: {
322325
if (payloads.length === 0) {
323326
return;
324327
}
325-
if (!originRoutable && !defaults.opts?.onBlockReply) {
328+
const sourceDisposition = turn.queued.queuedFollowupReplyDisposition;
329+
if (sourceDisposition?.kind === "drop") {
330+
logVerbose(`followup queue: source delivery dropped (${sourceDisposition.reason})`);
331+
return;
332+
}
333+
const deliverQueuedBatch = sourceDisposition?.deliver;
334+
const fallbackDispatcher = sourceDisposition ? undefined : defaults.opts?.onBlockReply;
335+
const dispatcherAvailable = Boolean(deliverQueuedBatch || fallbackDispatcher);
336+
if (!originRoutable && !dispatcherAvailable) {
326337
defaultRuntime.error?.(
327338
"followup queue: completed with payloads but no origin route or visible dispatcher is available",
328339
);
@@ -334,6 +345,14 @@ async function sendFollowupPayloads(params: {
334345
isHeartbeat: defaults.opts?.isHeartbeat === true,
335346
});
336347
const crossChannelFailures: ReplyPayload[] = [];
348+
const queuedPayloads: ReplyPayload[] = [];
349+
const dispatchPayload = async (payload: ReplyPayload) => {
350+
if (deliverQueuedBatch) {
351+
queuedPayloads.push(payload);
352+
} else {
353+
await fallbackDispatcher?.(payload);
354+
}
355+
};
337356
let deliveredCrossChannelOrigin = false;
338357
const provider = resolveOriginMessageProvider({
339358
provider: turn.queued.run.messageProvider,
@@ -347,22 +366,22 @@ async function sendFollowupPayloads(params: {
347366
originatingChannel,
348367
originatingTo,
349368
originRoutable,
350-
dispatcherAvailable: Boolean(defaults.opts?.onBlockReply),
369+
dispatcherAvailable,
351370
});
352371
if (providerRoute?.route === "drop") {
353372
continue;
354373
}
355374
const route =
356375
providerRoute?.route === "origin" && originRoutable
357376
? "origin"
358-
: providerRoute?.route === "dispatcher" && defaults.opts?.onBlockReply
377+
: providerRoute?.route === "dispatcher" && dispatcherAvailable
359378
? "dispatcher"
360379
: originRoutable
361380
? "origin"
362381
: "dispatcher";
363382
await typing.signalTextDelta(payload.text);
364383
if (route !== "origin") {
365-
await defaults.opts?.onBlockReply?.(payload);
384+
await dispatchPayload(payload);
366385
} else if (isRoutableChannel(originatingChannel) && originatingTo) {
367386
const metadata = getReplyPayloadMetadata(payload);
368387
const result = await routeReply({
@@ -388,9 +407,9 @@ async function sendFollowupPayloads(params: {
388407
if (!result.delivered && !result.suppressed) {
389408
const routeError = result.error ?? "no visible delivery";
390409
logVerbose(`followup queue: route-reply failed: ${routeError}`);
391-
if (sameChannelOrigin && defaults.opts?.onBlockReply) {
392-
await defaults.opts.onBlockReply(payload);
393-
} else if (defaults.opts?.onBlockReply) {
410+
if (sameChannelOrigin && dispatcherAvailable) {
411+
await dispatchPayload(payload);
412+
} else if (dispatcherAvailable) {
394413
crossChannelFailures.push(payload);
395414
} else {
396415
defaultRuntime.error?.(`followup queue: route-reply failed: ${routeError}`);
@@ -412,15 +431,23 @@ async function sendFollowupPayloads(params: {
412431
const terminalFailure = crossChannelFailures.some(isReplyPayloadTerminalContent);
413432
if (
414433
(terminalFailure || (crossChannelFailures.length > 0 && !deliveredCrossChannelOrigin)) &&
415-
defaults.opts?.onBlockReply
434+
dispatcherAvailable
416435
) {
417-
await defaults.opts.onBlockReply({
436+
await dispatchPayload({
418437
text:
419438
"Follow-up completed, but OpenClaw could not deliver it to the originating channel. " +
420439
"The reply content was not forwarded to this channel to avoid cross-channel misdelivery.",
421440
isError: true,
422441
});
423442
}
443+
if (queuedPayloads.length > 0) {
444+
await deliverQueuedBatch?.({
445+
kind: "queued-followup",
446+
runId: params.runId,
447+
originatingChannel,
448+
payloads: queuedPayloads,
449+
});
450+
}
424451
}
425452

426453
/** Performs the already-resolved follow-up delivery action. */

‎src/auto-reply/reply/get-reply-run-execute.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,13 @@ export async function executePreparedReplyRun(state: PreparedReplyRunAdmission)
366366
...(opts?.onFollowupQueueDisposition
367367
? { onQueueDisposition: opts.onFollowupQueueDisposition }
368368
: {}),
369+
...(opts && "onQueuedFollowupReplyBatch" in opts
370+
? {
371+
queuedFollowupReplyDisposition: opts.onQueuedFollowupReplyBatch
372+
? { kind: "deliver" as const, deliver: opts.onQueuedFollowupReplyBatch }
373+
: { kind: "drop" as const, reason: "source-unavailable" as const },
374+
}
375+
: {}),
369376
messageId: sessionCtx.MessageSidFull ?? sessionCtx.MessageSid,
370377
summaryLine: baseBodyTrimmedRaw,
371378
...(queuedToolsAllow !== undefined ? { toolsAllow: queuedToolsAllow } : {}),

‎src/auto-reply/reply/get-reply.types.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import type { SkillWorkshopProposalRevisionConstraint } from "../../skills/works
88
import type { GetReplyOptions } from "../get-reply-options.types.js";
99
import type { ReplyPayload } from "../reply-payload.js";
1010
import type { MsgContext } from "../templating.js";
11-
import type { FollowupQueueDisposition } from "./queue/types.js";
11+
import type { FollowupQueueDisposition, QueuedFollowupReplyBatch } from "./queue/types.js";
1212
import type { ReplyOptionsWithAdmissionTicket } from "./reply-admission-ticket.js";
1313
import type { ReplyOptionsWithOperationRunState } from "./reply-operation-run-state.js";
1414
import type { ReplyOperation } from "./reply-run-registry.js";
@@ -33,6 +33,8 @@ type InternalReplySessionOptions = {
3333
sessionPromptSourceReplyDeliveryMode?: GetReplyOptions["sourceReplyDeliveryMode"];
3434
/** Receives terminal queue-cap outcomes without widening the public reply API. */
3535
onFollowupQueueDisposition?: (disposition: FollowupQueueDisposition) => void;
36+
/** Delivers queued replies only through their originating Gateway admission. */
37+
onQueuedFollowupReplyBatch?: (batch: QueuedFollowupReplyBatch) => Promise<void> | void;
3638
/** Overrides persisted queue mode for this reply only. */
3739
queueModeOverride?: QueueMode;
3840
/** Dispatch-owned operation used to defer hooks until durable run admission. */

‎src/auto-reply/reply/queue/drain.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,7 @@ type FollowupRuntimeMetadata = Pick<
413413
| "queueAbortSignal"
414414
| "deliveryCorrelations"
415415
| "turnAdoptionLifecycle"
416+
| "queuedFollowupReplyDisposition"
416417
>;
417418

418419
function hasCurrentTurnRuntimeMetadata(item: FollowupRun): boolean {
@@ -668,6 +669,7 @@ function collectRuntimeMetadata(
668669
queueAbortSignal: items.find((item) => item.queueAbortSignal)?.queueAbortSignal,
669670
deliveryCorrelations: deliveryCorrelations.length > 0 ? deliveryCorrelations : undefined,
670671
turnAdoptionLifecycle: items.length === 1 ? items[0]?.turnAdoptionLifecycle : undefined,
672+
queuedFollowupReplyDisposition: items.at(-1)?.queuedFollowupReplyDisposition,
671673
};
672674
}
673675

‎src/auto-reply/reply/queue/types.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import type {
3333
TaskSuggestionDeliveryMode,
3434
TurnAdoptionLifecycle,
3535
} from "../../get-reply-options.types.js";
36+
import type { ReplyPayload } from "../../reply-payload.js";
3637
import type { OriginatingChannelType } from "../../templating.js";
3738
import type { ThinkingCatalogEntry } from "../../thinking.js";
3839
import type { ElevatedLevel, ReasoningLevel, ThinkLevel, VerboseLevel } from "../directives.js";
@@ -67,6 +68,17 @@ export type EnqueueFollowupRunOptions = {
6768

6869
export type FollowupQueueDisposition = "queue-cap" | "queue-cap-old" | "queue-cap-new";
6970

71+
export type QueuedFollowupReplyBatch = {
72+
kind: "queued-followup";
73+
runId: string;
74+
originatingChannel: string | undefined;
75+
payloads: ReplyPayload[];
76+
};
77+
78+
type QueuedFollowupReplyDisposition =
79+
| { kind: "deliver"; deliver: (batch: QueuedFollowupReplyBatch) => Promise<void> | void }
80+
| { kind: "drop"; reason: "source-unavailable" };
81+
7082
export class FollowupRunDeferredError extends Error {
7183
constructor(message = "Follow-up run deferred") {
7284
super(message);
@@ -104,6 +116,8 @@ export type FollowupRun = {
104116
turnAdoptionLifecycle?: TurnAdoptionLifecycle;
105117
/** Records terminal queue-cap outcomes at the queue owner before lifecycle cleanup. */
106118
onQueueDisposition?: (disposition: FollowupQueueDisposition) => void;
119+
/** Keep delivery bound to the source that owned admission, not later runner defaults. */
120+
queuedFollowupReplyDisposition?: QueuedFollowupReplyDisposition;
107121
/** Provider message ID, when available (for deduplication). */
108122
messageId?: string;
109123
summaryLine?: string;

‎src/gateway/server-methods/chat-send-agent-dispatch.ts‎

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,9 @@ export function startChatDispatch(params: StartChatDispatchParams): void {
154154
userTurnRecorder,
155155
});
156156
const queuedFollowup = createChatSendTurnAdoptionLifecycle({
157+
accountId,
157158
chatQueuedTurns: context.chatQueuedTurns,
159+
context,
158160
runId: clientRunId,
159161
controller: activeRunAbort.controller,
160162
sessionId: backingSessionId ?? clientRunId,
@@ -164,6 +166,8 @@ export function startChatDispatch(params: StartChatDispatchParams): void {
164166
ownerDeviceId: client?.connect?.device?.id,
165167
ownerKey: queuedFollowupOwnerKey,
166168
...(expectedLeafEntryId !== undefined ? { originatingLeafEntryId: expectedLeafEntryId } : {}),
169+
originatingChannel: admission.originatingRoute.originatingChannel,
170+
session,
167171
hasCronCreatorAuthority: cronCreatorAuthority !== undefined,
168172
retainWorkAdmission: retainGatewayWorkAdmission,
169173
});
@@ -285,14 +289,8 @@ export function startChatDispatch(params: StartChatDispatchParams): void {
285289
abortSignal: activeRunAbort.controller.signal,
286290
// Keep a Gateway-owned cancel identity after this chat.send
287291
// terminalizes while the prompt waits in followup/collect queue.
288-
onFollowupQueueDisposition: (reason) => {
289-
context.logGateway.info("chat queue turn intentionally skipped", {
290-
runId: clientRunId,
291-
sessionKey,
292-
outcome: "skipped",
293-
reason,
294-
});
295-
},
292+
onFollowupQueueDisposition: queuedFollowup.onQueueDisposition,
293+
onQueuedFollowupReplyBatch: queuedFollowup.onQueuedFollowupReplyBatch,
296294
turnAdoptionLifecycle: queuedFollowup.lifecycle,
297295
images: replyOptionImages,
298296
imageOrder: imageOrder.length > 0 ? imageOrder : undefined,
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import { createDeferred } from "../../../test/helpers/promise.js";
3+
import { createChatSendLateFollowupDisposition } from "./chat-send-late-followup.js";
4+
5+
describe("chat.send late queued follow-up disposition", () => {
6+
it.each([
7+
["discord", "discord", "non-webchat-origin"],
8+
["webchat", "discord", "origin-mismatch"],
9+
])("records an explicit drop for %s -> %s", async (originatingChannel, batchChannel, reason) => {
10+
const info = vi.fn();
11+
const deliver = vi.fn(async () => ({ kind: "delivered" as const }));
12+
const disposition = createChatSendLateFollowupDisposition({
13+
runId: "original-run",
14+
originatingChannel,
15+
logGateway: { info } as never,
16+
deliver,
17+
});
18+
disposition.recordQueued();
19+
await disposition.deliver({
20+
kind: "queued-followup",
21+
runId: "followup-run",
22+
originatingChannel: batchChannel,
23+
payloads: [{ text: "must not leak" }],
24+
});
25+
expect(deliver).not.toHaveBeenCalled();
26+
expect(info).toHaveBeenCalledWith(
27+
"webchat late reply disposition",
28+
expect.objectContaining({ outcome: "late-and-dropped", reason }),
29+
);
30+
});
31+
32+
it("claims delivery before awaiting and records a concurrent duplicate", async () => {
33+
const info = vi.fn();
34+
const delivery = createDeferred<{ kind: "delivered" }>();
35+
const deliver = vi.fn(() => delivery.promise);
36+
const disposition = createChatSendLateFollowupDisposition({
37+
runId: "original-run",
38+
originatingChannel: "webchat",
39+
logGateway: { info } as never,
40+
deliver,
41+
});
42+
disposition.recordQueued();
43+
const first = disposition.deliver({
44+
kind: "queued-followup",
45+
runId: "first-followup",
46+
originatingChannel: "webchat",
47+
payloads: [{ text: "first" }],
48+
});
49+
await disposition.deliver({
50+
kind: "queued-followup",
51+
runId: "duplicate-followup",
52+
originatingChannel: "webchat",
53+
payloads: [{ text: "duplicate" }],
54+
});
55+
expect(deliver).toHaveBeenCalledOnce();
56+
expect(info).toHaveBeenCalledWith(
57+
"webchat late reply disposition",
58+
expect.objectContaining({ reason: "delivery-in-flight" }),
59+
);
60+
delivery.resolve({ kind: "delivered" });
61+
await first;
62+
});
63+
64+
it("settles a failed delivery and rejects every subsequent attempt", async () => {
65+
const info = vi.fn();
66+
const deliver = vi.fn(async () => {
67+
throw new Error("broadcast failed");
68+
});
69+
const disposition = createChatSendLateFollowupDisposition({
70+
runId: "original-run",
71+
originatingChannel: "webchat",
72+
logGateway: { info } as never,
73+
deliver,
74+
});
75+
disposition.recordQueued();
76+
const batch = {
77+
kind: "queued-followup" as const,
78+
runId: "failed-followup",
79+
originatingChannel: "webchat",
80+
payloads: [{ text: "reply" }],
81+
};
82+
await expect(disposition.deliver(batch)).rejects.toThrow("broadcast failed");
83+
await disposition.deliver({ ...batch, runId: "retry" });
84+
expect(info).toHaveBeenCalledWith(
85+
"webchat late reply disposition",
86+
expect.objectContaining({ reason: "delivery-failed" }),
87+
);
88+
expect(info).toHaveBeenCalledWith(
89+
"webchat late reply disposition",
90+
expect.objectContaining({ reason: "already-settled" }),
91+
);
92+
expect(deliver).toHaveBeenCalledOnce();
93+
});
94+
});

0 commit comments

Comments
 (0)