Skip to content

Commit dbb9665

Browse files
authored
fix(discord): let active turns receive steering (#122452)
Remove Discord's duplicate whole-turn session serialization so corrections reach shared reply admission and steer the active run. Preserve shared steer, followup, collect, and interrupt behavior. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 7511160 commit dbb9665

5 files changed

Lines changed: 66 additions & 168 deletions

File tree

‎extensions/discord/src/monitor/inbound-job.test.ts‎

Lines changed: 0 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -11,28 +11,6 @@ function jsonRoundTrip<T>(value: T): T {
1111
}
1212

1313
describe("buildDiscordInboundJob", () => {
14-
it("prefers route session key, then base session key, then channel id for queueing", async () => {
15-
const routed = await createBaseDiscordMessageContext({
16-
route: { sessionKey: "agent:main:discord:direct:routed" },
17-
baseSessionKey: "agent:main:discord:direct:base",
18-
messageChannelId: "channel-routed",
19-
});
20-
const baseOnly = await createBaseDiscordMessageContext({
21-
route: { sessionKey: "" },
22-
baseSessionKey: "agent:main:discord:direct:base-only",
23-
messageChannelId: "channel-base",
24-
});
25-
const channelFallback = await createBaseDiscordMessageContext({
26-
route: { sessionKey: " " },
27-
baseSessionKey: " ",
28-
messageChannelId: "channel-fallback",
29-
});
30-
31-
expect(buildDiscordInboundJob(routed).queueKey).toBe("agent:main:discord:direct:routed");
32-
expect(buildDiscordInboundJob(baseOnly).queueKey).toBe("agent:main:discord:direct:base-only");
33-
expect(buildDiscordInboundJob(channelFallback).queueKey).toBe("channel-fallback");
34-
});
35-
3614
it("keeps live runtime references out of the payload", async () => {
3715
const ctx = await createBaseDiscordMessageContext({
3816
message: {

‎extensions/discord/src/monitor/inbound-job.ts‎

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ type DiscordInboundJobRuntime = Pick<DiscordMessagePreflightContext, DiscordInbo
2121
type DiscordInboundJobPayload = Omit<DiscordMessagePreflightContext, DiscordInboundJobRuntimeField>;
2222

2323
export type DiscordInboundJob = {
24-
queueKey: string;
2524
payload: DiscordInboundJobPayload;
2625
runtime: DiscordInboundJobRuntime;
2726
ingressSettlement?: {
@@ -30,20 +29,6 @@ export type DiscordInboundJob = {
3029
};
3130
};
3231

33-
function resolveDiscordInboundJobQueueKey(ctx: DiscordMessagePreflightContext): string {
34-
// Serialize work by the eventual session route so one conversation cannot
35-
// race itself when Discord channel and session identifiers differ.
36-
const sessionKey = ctx.route.sessionKey?.trim();
37-
if (sessionKey) {
38-
return sessionKey;
39-
}
40-
const baseSessionKey = ctx.baseSessionKey?.trim();
41-
if (baseSessionKey) {
42-
return baseSessionKey;
43-
}
44-
return ctx.messageChannelId;
45-
}
46-
4732
export function buildDiscordInboundJob(
4833
ctx: DiscordMessagePreflightContext,
4934
options?: { ingressSettlement?: DiscordInboundJob["ingressSettlement"] },
@@ -64,7 +49,6 @@ export function buildDiscordInboundJob(
6449

6550
const sanitizedMessage = sanitizeDiscordInboundMessage(message);
6651
return {
67-
queueKey: resolveDiscordInboundJobQueueKey(ctx),
6852
payload: {
6953
...payload,
7054
message: sanitizedMessage,

‎extensions/discord/src/monitor/message-handler.queue.test.ts‎

Lines changed: 37 additions & 119 deletions
Original file line numberDiff line numberDiff line change
@@ -112,16 +112,30 @@ function createPreflightContext(channelId = "ch-1") {
112112
};
113113
}
114114

115+
function createPreflightContextForMessage(data: { channel_id: string; message: { id: string } }) {
116+
const ctx = createPreflightContext(data.channel_id);
117+
return {
118+
...ctx,
119+
message: { ...ctx.message, id: data.message.id },
120+
data: {
121+
...ctx.data,
122+
message: { ...ctx.data.message, id: data.message.id },
123+
},
124+
};
125+
}
126+
115127
function createHandlerWithDefaultPreflight(overrides?: { setStatus?: SetStatusFn }) {
116-
preflightDiscordMessageMock.mockImplementation(async (params: { data: { channel_id: string } }) =>
117-
createPreflightContext(params.data.channel_id),
128+
preflightDiscordMessageMock.mockImplementation(
129+
async (params: { data: ReturnType<typeof createMessageData> }) =>
130+
createPreflightContextForMessage(params.data),
118131
);
119132
return createDiscordMessageHandler(createDiscordHandlerParams(overrides));
120133
}
121134

122135
function installDefaultDiscordPreflight() {
123-
preflightDiscordMessageMock.mockImplementation(async (params: { data: { channel_id: string } }) =>
124-
createPreflightContext(params.data.channel_id),
136+
preflightDiscordMessageMock.mockImplementation(
137+
async (params: { data: ReturnType<typeof createMessageData> }) =>
138+
createPreflightContextForMessage(params.data),
125139
);
126140
}
127141

@@ -177,7 +191,7 @@ describe("createDiscordMessageHandler queue behavior", () => {
177191
expectStatusPatch(setStatus, { activeRuns: 0, busy: false });
178192
});
179193

180-
it("returns immediately and tracks busy status while queued runs execute", async () => {
194+
it("starts a second same-session event while the first run is active", async () => {
181195
preflightDiscordMessageMock.mockReset();
182196
processDiscordMessageMock.mockReset();
183197

@@ -190,8 +204,12 @@ describe("createDiscordMessageHandler queue behavior", () => {
190204
.mockImplementationOnce(async () => {
191205
await secondRun.promise;
192206
});
207+
preflightDiscordMessageMock.mockImplementation(
208+
async (params: { data: ReturnType<typeof createMessageData> }) =>
209+
createPreflightContextForMessage(params.data),
210+
);
193211
const setStatus = vi.fn();
194-
const handler = createHandlerWithDefaultPreflight({ setStatus });
212+
const handler = createDiscordMessageHandler(createDiscordHandlerParams({ setStatus }));
195213

196214
await expect(handler(createMessageData("m-1") as never, {} as never)).resolves.toBeUndefined();
197215

@@ -203,17 +221,18 @@ describe("createDiscordMessageHandler queue behavior", () => {
203221

204222
await flushQueueWork();
205223
expect(preflightDiscordMessageMock).toHaveBeenCalledTimes(2);
206-
expect(processDiscordMessageMock).toHaveBeenCalledTimes(1);
207-
208-
firstRun.resolve();
209-
await firstRun.promise;
210-
211-
await flushQueueWork();
212224
expect(processDiscordMessageMock).toHaveBeenCalledTimes(2);
225+
expectStatusPatch(setStatus, { activeRuns: 2, busy: true });
213226

214227
secondRun.resolve();
215228
await secondRun.promise;
216229

230+
await flushQueueWork();
231+
expectStatusPatch(setStatus, { activeRuns: 1, busy: true });
232+
233+
firstRun.resolve();
234+
await firstRun.promise;
235+
217236
await flushQueueWork();
218237
const lastStatusPatch = statusPatches(setStatus).at(-1);
219238
expect(lastStatusPatch?.activeRuns).toBe(0);
@@ -375,7 +394,7 @@ describe("createDiscordMessageHandler queue behavior", () => {
375394
expect(stop).toHaveBeenCalledTimes(1);
376395
});
377396

378-
it("does not abort long queued runs with a Discord-owned channel timeout", async () => {
397+
it("does not abort concurrent runs with a Discord-owned channel timeout", async () => {
379398
vi.useFakeTimers();
380399
try {
381400
preflightDiscordMessageMock.mockReset();
@@ -407,27 +426,21 @@ describe("createDiscordMessageHandler queue behavior", () => {
407426
handler(createMessageData("m-2") as never, {} as never),
408427
).resolves.toBeUndefined();
409428
await flushQueueWork();
410-
expect(processDiscordMessageMock).toHaveBeenCalledTimes(1);
429+
expect(processDiscordMessageMock).toHaveBeenCalledTimes(2);
411430

412431
await vi.advanceTimersByTimeAsync(60_000);
413432
await flushQueueWork();
414433

415-
expect(processDiscordMessageMock).toHaveBeenCalledTimes(1);
416-
expect(capturedAbortSignals).toEqual([undefined]);
434+
expect(processDiscordMessageMock).toHaveBeenCalledTimes(2);
435+
expect(capturedAbortSignals).toEqual([undefined, undefined]);
417436
const runtimeError = params.runtime.error as unknown as MockCallSource;
418437
expect(
419438
mockCalls(runtimeError).some(([message]) => String(message).includes("timed out")),
420439
).toBe(false);
421440

422441
firstRun.resolve();
423-
await firstRun.promise;
424-
await flushQueueWork();
425-
426-
expect(processDiscordMessageMock).toHaveBeenCalledTimes(2);
427-
expect(capturedAbortSignals).toEqual([undefined, undefined]);
428-
429442
secondRun.resolve();
430-
await secondRun.promise;
443+
await Promise.all([firstRun.promise, secondRun.promise]);
431444
} finally {
432445
vi.useRealTimers();
433446
}
@@ -545,101 +558,6 @@ describe("createDiscordMessageHandler queue behavior", () => {
545558
expect(getEventListeners(abortController.signal, "abort")).toHaveLength(initialListenerCount);
546559
});
547560

548-
it("skips queued runs that have not started yet after deactivation", async () => {
549-
preflightDiscordMessageMock.mockReset();
550-
processDiscordMessageMock.mockReset();
551-
552-
const firstRun = createDeferred<void>();
553-
processDiscordMessageMock
554-
.mockImplementationOnce(async () => {
555-
await firstRun.promise;
556-
})
557-
.mockImplementationOnce(async () => undefined);
558-
preflightDiscordMessageMock.mockImplementation(
559-
async (params: { data: { channel_id: string } }) =>
560-
createPreflightContext(params.data.channel_id),
561-
);
562-
563-
const handler = createDiscordMessageHandler(createDiscordHandlerParams());
564-
await expect(handler(createMessageData("m-1") as never, {} as never)).resolves.toBeUndefined();
565-
await flushQueueWork();
566-
expect(processDiscordMessageMock).toHaveBeenCalledTimes(1);
567-
568-
await expect(handler(createMessageData("m-2") as never, {} as never)).resolves.toBeUndefined();
569-
const deactivation = handler.deactivate();
570-
571-
firstRun.resolve();
572-
await firstRun.promise;
573-
await deactivation;
574-
await Promise.resolve();
575-
576-
expect(processDiscordMessageMock).toHaveBeenCalledTimes(1);
577-
});
578-
579-
it("continues queued durable cleanup after an earlier settlement failure", async () => {
580-
preflightDiscordMessageMock.mockReset();
581-
processDiscordMessageMock.mockReset();
582-
583-
const firstRun = createDeferred<void>();
584-
processDiscordMessageMock.mockImplementation(async () => {
585-
await firstRun.promise;
586-
});
587-
preflightDiscordMessageMock.mockImplementation(
588-
async (params: {
589-
data: { channel_id: string };
590-
abortSignal?: AbortSignal;
591-
turnAdoptionLifecycle?: DiscordIngressLifecycle;
592-
}) => ({
593-
...createPreflightContext(params.data.channel_id),
594-
abortSignal: params.abortSignal,
595-
turnAdoptionLifecycle: params.turnAdoptionLifecycle,
596-
}),
597-
);
598-
599-
const handlerParams = createDiscordHandlerParams();
600-
const handler = createDiscordMessageHandler(handlerParams);
601-
const activeIngress = createIngressLifecycle();
602-
const failingQueuedIngress = createIngressLifecycle();
603-
const laterQueuedIngress = createIngressLifecycle();
604-
failingQueuedIngress.onAbandoned.mockRejectedValueOnce(
605-
new Error("simulated durable release failure"),
606-
);
607-
608-
await expect(
609-
handler(createMessageData("m-1") as never, {} as never, {
610-
turnAdoptionLifecycle: activeIngress,
611-
}),
612-
).resolves.toEqual({ kind: "deferred" });
613-
await flushQueueWork();
614-
expect(processDiscordMessageMock).toHaveBeenCalledTimes(1);
615-
616-
await expect(
617-
handler(createMessageData("m-2") as never, {} as never, {
618-
turnAdoptionLifecycle: failingQueuedIngress,
619-
}),
620-
).resolves.toEqual({ kind: "deferred" });
621-
await expect(
622-
handler(createMessageData("m-3") as never, {} as never, {
623-
turnAdoptionLifecycle: laterQueuedIngress,
624-
}),
625-
).resolves.toEqual({ kind: "deferred" });
626-
627-
const deactivation = handler.deactivate();
628-
await vi.waitFor(() => expect(failingQueuedIngress.onAbandoned).toHaveBeenCalledTimes(1));
629-
firstRun.resolve();
630-
631-
await expect(deactivation).resolves.toBeUndefined();
632-
expect(processDiscordMessageMock).toHaveBeenCalledTimes(1);
633-
expect(activeIngress.onAbandoned).toHaveBeenCalledTimes(1);
634-
expect(laterQueuedIngress.onAbandoned).toHaveBeenCalledTimes(1);
635-
const runtimeError = handlerParams.runtime.error as unknown as MockCallSource;
636-
expect(
637-
mockCalls(runtimeError).some(([message]) =>
638-
String(message).includes("discord queued message cleanup failed"),
639-
),
640-
).toBe(true);
641-
});
642-
643561
it("preserves non-debounced message ordering by awaiting debouncer enqueue", async () => {
644562
preflightDiscordMessageMock.mockReset();
645563
processDiscordMessageMock.mockReset();
@@ -684,7 +602,7 @@ describe("createDiscordMessageHandler queue behavior", () => {
684602
expect(processedMessageIds).toEqual(["m-1", "m-2"]);
685603
});
686604

687-
it("recovers queue progress after a run failure without leaving busy state stuck", async () => {
605+
it("reports a concurrent run failure without leaving busy state stuck", async () => {
688606
preflightDiscordMessageMock.mockReset();
689607
processDiscordMessageMock.mockReset();
690608

‎extensions/discord/src/monitor/message-run-queue.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,9 @@ export function createDiscordMessageRunQueue(
129129
return;
130130
}
131131
skippedCleanup.add(cleanupSkipped);
132-
runQueue.enqueue(job.queueKey, async ({ lifecycleSignal }) => {
132+
// Core reply admission owns session serialization. A transport event key
133+
// lets later Discord messages reach active-run steering while this run continues.
134+
runQueue.enqueue(job.payload.message.id, async ({ lifecycleSignal }) => {
133135
// Once the task starts, normal process/commit handling owns cleanup.
134136
// Leaving it in skippedCleanup would double-release replay state.
135137
skippedCleanup.delete(cleanupSkipped);

‎src/auto-reply/reply/agent-runner.runreplyagent.e2e.test.ts‎

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,11 @@ import {
3939
REPLY_OPERATION_RUN_STATE,
4040
type ReplyOperationRunState,
4141
} from "./reply-operation-run-state.js";
42-
import { createReplyOperation, type ReplyOperation } from "./reply-run-registry.js";
42+
import {
43+
createReplyOperation,
44+
type ReplyOperation,
45+
replyRunRegistry,
46+
} from "./reply-run-registry.js";
4347
import { testing as replyRunTesting } from "./reply-run-registry.test-support.js";
4448
import { bindReplyOperationTyping } from "./reply-run-typing.js";
4549
import { consumeReplyUsageState } from "./reply-usage-state.js";
@@ -558,6 +562,12 @@ describe("runReplyAgent active steering", () => {
558562

559563
it("injects a steer without claiming a new agent reply", async () => {
560564
const runState: ReplyOperationRunState = {};
565+
const active = createReplyOperation({
566+
sessionKey: "main",
567+
sessionId: "session",
568+
resetTriggered: false,
569+
});
570+
active.setPhase("running");
561571
state.beforeAgentReplyHasHooksMock.mockImplementation(
562572
(hookName) => hookName === "before_agent_reply",
563573
);
@@ -583,16 +593,22 @@ describe("runReplyAgent active steering", () => {
583593
},
584594
});
585595

586-
await expect(run()).resolves.toBeUndefined();
596+
try {
597+
await expect(run()).resolves.toBeUndefined();
587598

588-
expect(runState.admission).toEqual({ status: "accepted", mode: "steer" });
589-
expect(state.beforeAgentReplyRunMock).not.toHaveBeenCalled();
590-
expect(state.queueEmbeddedAgentMessageMock).toHaveBeenCalledOnce();
591-
expect(state.queueEmbeddedAgentMessageMock).toHaveBeenCalledWith(
592-
"session",
593-
"hello",
594-
expect.objectContaining({ steeringMode: "all" }),
595-
);
599+
expect(runState.admission).toEqual({ status: "accepted", mode: "steer" });
600+
expect(state.beforeAgentReplyRunMock).not.toHaveBeenCalled();
601+
expect(state.queueEmbeddedAgentMessageMock).toHaveBeenCalledOnce();
602+
expect(state.queueEmbeddedAgentMessageMock).toHaveBeenCalledWith(
603+
"session",
604+
"hello",
605+
expect.objectContaining({ steeringMode: "all" }),
606+
);
607+
expect(state.runEmbeddedAgentMock).not.toHaveBeenCalled();
608+
expect(replyRunRegistry.get("main")).toBe(active);
609+
} finally {
610+
active.complete();
611+
}
596612
});
597613

598614
it("does not let before_agent_reply claim an accepted steer", async () => {

0 commit comments

Comments
 (0)