Skip to content

Commit 7dd74db

Browse files
authored
fix: preserve completion delivery and truthful agent session state (#117119)
1 parent 45f274f commit 7dd74db

28 files changed

Lines changed: 654 additions & 161 deletions

‎extensions/discord/src/actions/handle-action.test.ts‎

Lines changed: 88 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -434,67 +434,93 @@ describe("handleDiscordMessageAction", () => {
434434
});
435435
});
436436

437-
it("notifies inbound event delivery after message sends", async () => {
438-
const markDelivered = vi.fn();
439-
const end = beginDiscordInboundEventDeliveryCorrelation(
440-
"agent:main:discord:channel:c1",
441-
{
442-
outboundTo: "channel:c1",
443-
outboundAccountId: "default",
444-
markInboundEventDelivered: markDelivered,
445-
},
446-
{ inboundEventKind: "room_event" },
447-
);
448-
449-
try {
450-
await handleDiscordMessageAction({
451-
action: "send",
452-
params: {
453-
to: "channel:c1",
454-
message: "hello",
455-
},
456-
cfg: discordConfig(),
457-
accountId: "default",
458-
sessionKey: "agent:main:discord:channel:c1",
459-
inboundEventKind: "room_event",
460-
});
461-
} finally {
462-
end();
463-
}
464-
465-
expect(markDelivered).toHaveBeenCalledTimes(1);
466-
});
467-
468-
it("notifies inbound event delivery after visible message actions", async () => {
469-
const markDelivered = vi.fn();
470-
const end = beginDiscordInboundEventDeliveryCorrelation(
471-
"agent:main:discord:channel:c1",
472-
{
473-
outboundTo: "channel:c1",
474-
outboundAccountId: "default",
475-
markInboundEventDelivered: markDelivered,
437+
it.each([
438+
{
439+
action: "send" as const,
440+
params: { to: "channel:c1", message: "hello" },
441+
},
442+
{
443+
action: "upload-file" as const,
444+
params: { to: "channel:c1", filePath: "/tmp/image.png" },
445+
},
446+
{
447+
action: "poll" as const,
448+
params: {
449+
to: "channel:c1",
450+
pollQuestion: "Which option?",
451+
pollOption: ["first", "second"],
476452
},
477-
{ inboundEventKind: "room_event" },
478-
);
479-
480-
try {
481-
await handleDiscordMessageAction({
482-
action: "upload-file",
483-
params: {
484-
to: "channel:c1",
485-
filePath: "/tmp/image.png",
486-
},
487-
cfg: discordConfig(),
488-
accountId: "default",
489-
sessionKey: "agent:main:discord:channel:c1",
490-
inboundEventKind: "room_event",
491-
});
492-
} finally {
493-
end();
494-
}
495-
496-
expect(markDelivered).toHaveBeenCalledTimes(1);
497-
});
453+
},
454+
{
455+
action: "sticker" as const,
456+
params: { to: "channel:c1", stickerId: ["sticker-1"] },
457+
},
458+
{
459+
action: "thread-reply" as const,
460+
params: { threadId: "c1", message: "thread update" },
461+
},
462+
{
463+
action: "thread-create" as const,
464+
params: { channelId: "c1", messageId: "message-1", threadName: "investigation" },
465+
},
466+
])(
467+
"records room-event delivery only after $action receives a positive receipt",
468+
async ({ action, params }) => {
469+
const sessionKey = "agent:main:discord:channel:c1";
470+
471+
for (const ok of [false, true]) {
472+
const markDelivered = vi.fn();
473+
const onThreadAdopted = vi.fn();
474+
const endDelivery = beginDiscordInboundEventDeliveryCorrelation(
475+
sessionKey,
476+
{
477+
outboundTo: "channel:c1",
478+
outboundAccountId: "default",
479+
markInboundEventDelivered: markDelivered,
480+
},
481+
{ inboundEventKind: "room_event" },
482+
);
483+
const endThreadRoute =
484+
action === "thread-create"
485+
? beginDiscordActiveTurnThreadRoute(sessionKey, {
486+
accountId: "default",
487+
sourceChannelId: "c1",
488+
sourceMessageId: "message-1",
489+
onThreadAdopted,
490+
})
491+
: () => {};
492+
493+
handleDiscordActionMock.mockResolvedValueOnce({
494+
content: [],
495+
details: {
496+
ok,
497+
...(ok ? {} : { error: "delivery failed" }),
498+
...(action === "thread-create" ? { thread: { id: "thread-1" } } : {}),
499+
},
500+
});
501+
502+
try {
503+
const result = await handleDiscordMessageAction({
504+
action,
505+
params,
506+
cfg: discordConfig({ threads: true, polls: true, stickers: true }),
507+
accountId: "default",
508+
sessionKey,
509+
inboundEventKind: "room_event",
510+
});
511+
512+
expect(result.details).toMatchObject({ ok });
513+
expect(markDelivered).toHaveBeenCalledTimes(ok ? 1 : 0);
514+
if (action === "thread-create") {
515+
expect(onThreadAdopted).toHaveBeenCalledTimes(ok ? 1 : 0);
516+
}
517+
} finally {
518+
endThreadRoute();
519+
endDelivery();
520+
}
521+
}
522+
},
523+
);
498524

499525
it("maps upload-file to Discord sendMessage with media read context", async () => {
500526
const mediaReadFile = vi.fn(async () => Buffer.from("image"));
@@ -644,7 +670,7 @@ describe("handleDiscordMessageAction", () => {
644670

645671
handleDiscordActionMock.mockResolvedValueOnce({
646672
content: [],
647-
details: { thread: { id: "thread-1" } },
673+
details: { ok: true, thread: { id: "thread-1" } },
648674
});
649675
await handleDiscordMessageAction({
650676
action: "thread-create",
@@ -766,7 +792,7 @@ describe("handleDiscordMessageAction", () => {
766792
try {
767793
const expectedResult = {
768794
content: [],
769-
details: { thread: { id: "thread-1" } },
795+
details: { ok: true, thread: { id: "thread-1" } },
770796
};
771797
handleDiscordActionMock.mockResolvedValueOnce(expectedResult);
772798

‎extensions/discord/src/actions/handle-action.ts‎

Lines changed: 32 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -104,13 +104,27 @@ export async function handleDiscordMessageAction(
104104
mediaReadFile: ctx.mediaReadFile,
105105
...readPolicyOptions,
106106
} as const;
107-
const notifyVisibleOutbound = (to: string, fallbackSessionKey?: string) =>
107+
const notifyVisibleOutbound = (
108+
result: AgentToolResult<unknown>,
109+
to: string,
110+
fallbackSessionKey?: string,
111+
) => {
112+
const details =
113+
result.details && typeof result.details === "object" && !Array.isArray(result.details)
114+
? (result.details as { ok?: unknown })
115+
: undefined;
116+
// Resolved failures are not delivery receipts; clearing room history would
117+
// otherwise permanently discard context without any visible reply.
118+
if (details?.ok !== true) {
119+
return;
120+
}
108121
notifyDiscordInboundEventOutboundSuccess({
109122
sessionKey: ctx.sessionKey ?? fallbackSessionKey ?? undefined,
110123
to,
111124
accountId,
112125
inboundEventKind: ctx.inboundEventKind,
113126
});
127+
};
114128
const withAdoptedThreadReplyRoute = (
115129
result: AgentToolResult<unknown>,
116130
to: string,
@@ -248,7 +262,7 @@ export async function handleDiscordMessageAction(
248262
cfg,
249263
actionOptions,
250264
);
251-
notifyVisibleOutbound(to, sessionKey);
265+
notifyVisibleOutbound(result, to, sessionKey);
252266
return withAdoptedThreadReplyRoute(result, to, sessionKey);
253267
}
254268

@@ -287,7 +301,7 @@ export async function handleDiscordMessageAction(
287301
cfg,
288302
actionOptions,
289303
);
290-
notifyVisibleOutbound(to, sessionKey);
304+
notifyVisibleOutbound(result, to, sessionKey);
291305
return withAdoptedThreadReplyRoute(result, to, sessionKey);
292306
}
293307

@@ -313,7 +327,7 @@ export async function handleDiscordMessageAction(
313327
cfg,
314328
actionOptions,
315329
);
316-
notifyVisibleOutbound(to);
330+
notifyVisibleOutbound(result, to);
317331
return result;
318332
}
319333

@@ -453,17 +467,19 @@ export async function handleDiscordMessageAction(
453467
);
454468
const details =
455469
result.details && typeof result.details === "object" && !Array.isArray(result.details)
456-
? (result.details as { thread?: { id?: unknown } })
470+
? (result.details as { ok?: unknown; thread?: { id?: unknown } })
457471
: undefined;
458-
const threadId = typeof details?.thread?.id === "string" ? details.thread.id : undefined;
459-
await notifyDiscordActiveTurnThreadCreated({
460-
sessionKey: ctx.sessionKey,
461-
accountId,
462-
sourceChannelId: resolveChannelId(),
463-
sourceMessageId: messageId,
464-
threadId,
465-
});
466-
notifyVisibleOutbound(resolveChannelId());
472+
if (details?.ok === true) {
473+
const threadId = typeof details.thread?.id === "string" ? details.thread.id : undefined;
474+
await notifyDiscordActiveTurnThreadCreated({
475+
sessionKey: ctx.sessionKey,
476+
accountId,
477+
sourceChannelId: resolveChannelId(),
478+
sourceMessageId: messageId,
479+
threadId,
480+
});
481+
}
482+
notifyVisibleOutbound(result, resolveChannelId());
467483
return result;
468484
}
469485

@@ -485,7 +501,7 @@ export async function handleDiscordMessageAction(
485501
cfg,
486502
actionOptions,
487503
);
488-
notifyVisibleOutbound(to);
504+
notifyVisibleOutbound(result, to);
489505
return result;
490506
}
491507

@@ -513,7 +529,7 @@ export async function handleDiscordMessageAction(
513529
if (adminResult !== undefined) {
514530
if (action === "thread-reply") {
515531
const threadId = readStringParam(params, "threadId") ?? readTarget();
516-
notifyVisibleOutbound(threadId);
532+
notifyVisibleOutbound(adminResult, threadId);
517533
return withAdoptedThreadReplyRoute(adminResult, threadId);
518534
}
519535
return adminResult;

‎extensions/qa-lab/src/providers/mock-openai/server.test.ts‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3309,7 +3309,7 @@ describe("qa mock openai server", () => {
33093309
expect(outputText(await final.json())).toBe("subagent-1: ok\nsubagent-2: ok");
33103310
});
33113311

3312-
it("completes subagent fanout from a continuation turn without tool output", async () => {
3312+
it("replays completed subagent fanout on requester-settle continuation turns", async () => {
33133313
const server = await startMockServer();
33143314

33153315
const prompt =
@@ -3354,6 +3354,43 @@ describe("qa mock openai server", () => {
33543354
});
33553355
expect(phaseOnlyFinal.status).toBe(200);
33563356
expect(outputText(await phaseOnlyFinal.json())).toBe("subagent-1: ok\nsubagent-2: ok");
3357+
3358+
const settledContinuation = await postResponses(server, {
3359+
stream: false,
3360+
tools: [SESSIONS_SPAWN_TOOL],
3361+
input: [
3362+
makeUserInput(prompt),
3363+
makeUserInput(
3364+
"[Inter-session message]\nALPHA-OK\nBETA-OK\nAll spawned subagents have settled. Resume the parent turn and report both results together.",
3365+
),
3366+
],
3367+
});
3368+
expect(settledContinuation.status).toBe(200);
3369+
const settledPayload = await settledContinuation.json();
3370+
expect(outputText(settledPayload)).toBe("subagent-1: ok\nsubagent-2: ok");
3371+
expect(outputItems(settledPayload)).not.toContainEqual(
3372+
expect.objectContaining({ type: "function_call", name: "sessions_spawn" }),
3373+
);
3374+
3375+
const unrelatedContinuation = await postResponses(server, {
3376+
stream: false,
3377+
tools: [SESSIONS_SPAWN_TOOL],
3378+
input: [makeUserInput("Continue with an unrelated conversation.")],
3379+
});
3380+
expect(unrelatedContinuation.status).toBe(200);
3381+
expect(outputText(await unrelatedContinuation.json())).not.toBe(
3382+
"subagent-1: ok\nsubagent-2: ok",
3383+
);
3384+
3385+
const restartedFanout = await postResponses(server, {
3386+
stream: false,
3387+
tools: [SESSIONS_SPAWN_TOOL],
3388+
input: [makeUserInput(prompt)],
3389+
});
3390+
expect(restartedFanout.status).toBe(200);
3391+
expect(
3392+
outputToolArgsFromItem(outputToolCall(await restartedFanout.json(), "sessions_spawn")),
3393+
).toEqual(expect.objectContaining({ label: "qa-fanout-alpha" }));
33573394
});
33583395

33593396
it("completes subagent fanout when beta completion arrives on a generic follow-up turn", async () => {

‎extensions/qa-lab/src/providers/mock-openai/server.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1477,6 +1477,10 @@ async function buildResponsesPayload(
14771477
scenarioState.subagentFanoutPhase = 0;
14781478
scenarioState.subagentFanoutCompletedWorkers.clear();
14791479
}
1480+
// A later requester-settle wake must replay the completed synthesis without spawning again.
1481+
if (isSubagentFanoutPrompt && scenarioState.subagentFanoutPhase === 3) {
1482+
return buildAssistantEvents("subagent-1: ok\nsubagent-2: ok");
1483+
}
14801484
if (canCallSessionsSpawn && isSubagentFanoutPrompt) {
14811485
if (!toolOutput && scenarioState.subagentFanoutPhase === 0) {
14821486
scenarioState.subagentFanoutPhase = 1;

‎src/agents/subagent-announce-delivery.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3906,6 +3906,50 @@ describe("deliverSubagentAnnouncement completion delivery", () => {
39063906
});
39073907
});
39083908

3909+
it("directly delivers settle synthesis even when a direct-message requester turn is active", async () => {
3910+
const callGateway = createGatewayMock();
3911+
const queueEmbeddedAgentMessageWithOutcome = createQueueOutcomeMock(true);
3912+
const origin = {
3913+
channel: "discord",
3914+
to: "dm:U123",
3915+
accountId: "acct-1",
3916+
};
3917+
testing.setDepsForTest({
3918+
callGateway,
3919+
getRequesterSessionActivity: () => ({
3920+
sessionId: "requester-session-dm",
3921+
isActive: true,
3922+
}),
3923+
getRuntimeConfig: () => ({}) as never,
3924+
queueEmbeddedAgentMessageWithOutcome,
3925+
});
3926+
3927+
const result = await deliverSubagentAnnouncement({
3928+
requesterSessionKey: "agent:main:discord:dm:U123",
3929+
targetRequesterSessionKey: "agent:main:discord:dm:U123",
3930+
triggerMessage: "all spawned subagents settled",
3931+
steerMessage: "all spawned subagents settled",
3932+
requesterOrigin: origin,
3933+
requesterSessionOrigin: origin,
3934+
directOrigin: origin,
3935+
requesterIsSubagent: false,
3936+
expectsCompletionMessage: false,
3937+
requireDirectDelivery: true,
3938+
directIdempotencyKey: "announce-requester-settle-direct",
3939+
sourceTool: "subagent_announce",
3940+
});
3941+
3942+
expectDeliveryPath(result, "direct");
3943+
expect(queueEmbeddedAgentMessageWithOutcome).not.toHaveBeenCalled();
3944+
const agentParams = expectGatewayAgentParams(callGateway, {
3945+
deliver: true,
3946+
channel: "discord",
3947+
accountId: "acct-1",
3948+
to: "dm:U123",
3949+
});
3950+
expect(agentParams.sourceReplyDeliveryMode).toBeUndefined();
3951+
});
3952+
39093953
it("does not retry session-file-changed failures with send evidence", async () => {
39103954
const sendErr = new OutboundDeliveryError("outbound delivery failed", {
39113955
cause: new Error("outbound delivery failed"),

0 commit comments

Comments
 (0)