Skip to content

Commit bea0e39

Browse files
sjf-oasjf
andauthored
fix(slack): expose channel reaction events to thread turns (#122363)
* test: cover routed Slack system events * fix: deliver route events to thread turns * style: format routed event test * fix: scope parent event routing to Slack * test: isolate routed event admission proof * fix(slack): keep reaction route handoff internal * fix(slack): preserve channel turn public types * fix(slack): hide reaction route carrier from sdk * style: keep channel lifecycle within lint budget * style: trim channel lifecycle carrier setup * test: preserve route events on busy admission * fix(reply): defer system event drain until admission * test: prove deferred system event drain --------- Co-authored-by: Sarah Fortune <[email protected]>
1 parent f525bee commit bea0e39

7 files changed

Lines changed: 211 additions & 23 deletions

File tree

‎extensions/slack/src/monitor/message-handler/prepare.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3947,6 +3947,8 @@ Second paragraph should still reach the agent after Slack's preview cutoff.`;
39473947
expect(root.ctxPayload.SessionKey).toBe(expectedSessionKey);
39483948
expect(followUp.ctxPayload.SessionKey).toBe(expectedSessionKey);
39493949
expect(new Set([root.ctxPayload.SessionKey, followUp.ctxPayload.SessionKey]).size).toBe(1);
3950+
expect(root.ctxPayload).not.toHaveProperty("SystemEventSessionKey");
3951+
expect(followUp.ctxPayload).not.toHaveProperty("SystemEventSessionKey");
39503952
if (expectedAgentId) {
39513953
expect(root.route.agentId).toBe(expectedAgentId);
39523954
}

‎extensions/slack/src/monitor/message-handler/prepare.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1670,7 +1670,8 @@ export async function prepareSlackMessage(params: {
16701670
agentId: route.agentId,
16711671
dmScope: route.dmScope,
16721672
accountId: route.accountId,
1673-
routeSessionKey: sessionKey,
1673+
routeSessionKey: route.sessionKey,
1674+
dispatchSessionKey: sessionKey,
16741675
parentSessionKey: threadKeys.parentSessionKey,
16751676
},
16761677
reply: {

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

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import {
4949
resolveRoutedDeliveryThreadId,
5050
} from "./routed-delivery-thread.js";
5151
import { drainFormattedSystemEvents } from "./session-system-events.js";
52+
import { getReplySystemEventSessionKey } from "./system-event-session-key.js";
5253

5354
export async function prepareReplyRunAdmission(context: PreparedReplyRunContext) {
5455
const {
@@ -130,20 +131,31 @@ export async function prepareReplyRunAdmission(context: PreparedReplyRunContext)
130131
? `[Thread starter - for context]\n${threadStarterBody}`
131132
: undefined;
132133
const drainedSystemEventBlocks: string[] = [];
133-
const rebuildPromptBodies = async () => {
134-
if (!useFastReplyRuntime) {
134+
const drainSystemEventBlocks = async () => {
135+
if (useFastReplyRuntime) {
136+
return;
137+
}
138+
const routeSystemEventSessionKey = normalizeOptionalString(getReplySystemEventSessionKey(opts));
139+
const systemEventSessionKeys =
140+
routeSystemEventSessionKey && routeSystemEventSessionKey !== sessionKey
141+
? [routeSystemEventSessionKey, sessionKey]
142+
: [sessionKey];
143+
for (const systemEventSessionKey of systemEventSessionKeys) {
144+
const isCurrentSession = systemEventSessionKey === sessionKey;
135145
const eventsBlock = await drainFormattedSystemEvents({
136146
cfg,
137147
agentId,
138-
sessionKey,
139-
isMainSession,
140-
isNewSession,
148+
sessionKey: systemEventSessionKey,
149+
isMainSession: isCurrentSession && isMainSession,
150+
isNewSession: isCurrentSession && isNewSession,
141151
suppressHeartbeatOwnedEvents: context.isHeartbeat,
142152
});
143153
if (eventsBlock) {
144154
drainedSystemEventBlocks.push(eventsBlock);
145155
}
146156
}
157+
};
158+
const rebuildPromptBodies = () => {
147159
const { activeGoalContext, inboundUserContext } = context.getInboundContext();
148160
return buildReplyPromptEnvelope({
149161
ctx,
@@ -566,6 +578,17 @@ export async function prepareReplyRunAdmission(context: PreparedReplyRunContext)
566578
return { kind: "reply", reply: queueState.reply } as const;
567579
}
568580
}
581+
if (activeRunQueueAction !== "drop") {
582+
await traceRunPhase("reply.drain_system_events", () => drainSystemEventBlocks());
583+
({
584+
prefixedCommandBody,
585+
queuedBody,
586+
transcriptBody,
587+
transcriptCommandBody,
588+
media: promptMedia,
589+
currentInboundContext,
590+
} = await traceRunPhase("reply.build_prompt_bodies", () => rebuildPromptBodies()));
591+
}
569592

570593
return {
571594
kind: "ready",

‎src/auto-reply/reply/get-reply-run.media-only.test.ts‎

Lines changed: 109 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ import {
4141
type SourceReplyDeliveryRuntimeOptions,
4242
} from "./source-reply-delivery-runtime.js";
4343
import { buildChannelSourceTurnId } from "./source-turn-id.js";
44+
import { withReplySystemEventSessionKey } from "./system-event-session-key.js";
4445
import { resolveTypingMode } from "./typing-mode.js";
4546

4647
vi.mock("../../agents/auth-profiles/session-override.js", () => ({
@@ -2469,12 +2470,73 @@ describe("runPreparedReply media-only handling", () => {
24692470

24702471
nextRun.complete();
24712472
});
2472-
it("re-drains system events after waiting behind an active run", async () => {
2473+
it("keeps route and dispatch system events queued when busy admission returns", async () => {
2474+
vi.useFakeTimers();
2475+
const actualSystemEvents = await vi.importActual<typeof import("./session-system-events.js")>(
2476+
"./session-system-events.js",
2477+
);
2478+
vi.mocked(drainFormattedSystemEvents).mockImplementation(
2479+
actualSystemEvents.drainFormattedSystemEvents,
2480+
);
24732481
const queueSettings = await import("./queue/settings-runtime.js");
24742482
vi.mocked(queueSettings.resolveQueueSettings).mockReturnValueOnce({ mode: "interrupt" });
2475-
vi.mocked(drainFormattedSystemEvents)
2476-
.mockResolvedValueOnce("System: [t] Initial event.")
2477-
.mockResolvedValueOnce("System: [t] Post-compaction context.");
2483+
const routeSessionKey = "agent:main:slack:channel:c123";
2484+
const dispatchSessionKey = `${routeSessionKey}:thread:123.456`;
2485+
enqueueSystemEvent("Slack reaction added: :eyes:", { sessionKey: routeSessionKey });
2486+
enqueueSystemEvent("Slack message in #claw-test from Alice", {
2487+
sessionKey: dispatchSessionKey,
2488+
});
2489+
const previousRun = createReplyOperation({
2490+
sessionId: "session-before-wait",
2491+
sessionKey: dispatchSessionKey,
2492+
resetTriggered: false,
2493+
});
2494+
previousRun.setPhase("running");
2495+
2496+
const runPromise = runPrepared({
2497+
isNewSession: false,
2498+
sessionId: "session-before-wait",
2499+
sessionKey: dispatchSessionKey,
2500+
opts: withReplySystemEventSessionKey({}, routeSessionKey),
2501+
provider: "",
2502+
model: "",
2503+
resolvedThinkLevel: "off",
2504+
});
2505+
2506+
await Promise.resolve();
2507+
previousRun.complete();
2508+
const nextRun = createReplyOperation({
2509+
sessionId: "session-after-wait",
2510+
sessionKey: dispatchSessionKey,
2511+
resetTriggered: false,
2512+
});
2513+
nextRun.setPhase("running");
2514+
2515+
const assertion = expect(runPromise).resolves.toEqual({
2516+
text: "⚠️ Previous run is still shutting down. Please try again in a moment.",
2517+
});
2518+
await vi.advanceTimersByTimeAsync(15_000);
2519+
await assertion;
2520+
expect(vi.mocked(runReplyAgent)).not.toHaveBeenCalled();
2521+
expect(peekSystemEventEntries(routeSessionKey).map((event) => event.text)).toEqual([
2522+
"Slack reaction added: :eyes:",
2523+
]);
2524+
expect(peekSystemEventEntries(dispatchSessionKey).map((event) => event.text)).toEqual([
2525+
"Slack message in #claw-test from Alice",
2526+
]);
2527+
2528+
nextRun.complete();
2529+
});
2530+
it("drains system events only after waiting behind an active run", async () => {
2531+
const actualSystemEvents = await vi.importActual<typeof import("./session-system-events.js")>(
2532+
"./session-system-events.js",
2533+
);
2534+
vi.mocked(drainFormattedSystemEvents).mockImplementation(
2535+
actualSystemEvents.drainFormattedSystemEvents,
2536+
);
2537+
const queueSettings = await import("./queue/settings-runtime.js");
2538+
vi.mocked(queueSettings.resolveQueueSettings).mockReturnValueOnce({ mode: "interrupt" });
2539+
enqueueSystemEvent("System event after active run", { sessionKey: "session-key" });
24782540

24792541
const previousRun = createReplyOperation({
24802542
sessionId: "session-events-after-wait",
@@ -2486,19 +2548,24 @@ describe("runPreparedReply media-only handling", () => {
24862548
const runPromise = runPrepared({
24872549
isNewSession: false,
24882550
sessionId: "session-events-after-wait",
2551+
provider: "",
2552+
model: "",
2553+
resolvedThinkLevel: "off",
24892554
});
24902555

24912556
await Promise.resolve();
2557+
expect(peekSystemEventEntries("session-key").map((event) => event.text)).toEqual([
2558+
"System event after active run",
2559+
]);
24922560
previousRun.complete();
24932561

24942562
await expect(runPromise).resolves.toEqual({ text: "ok" });
24952563
const call = requireLastRunReplyAgentCall();
2496-
expect(call?.commandBody).toContain("System: [t] Initial event.");
2497-
expect(call?.commandBody).not.toContain("System: [t] Post-compaction context.");
2498-
expect(call?.transcriptCommandBody).not.toContain("System: [t] Initial event.");
2499-
expect(call?.followupRun.prompt).toContain("System: [t] Initial event.");
2500-
expect(call?.followupRun.prompt).not.toContain("System: [t] Post-compaction context.");
2501-
expect(call?.followupRun.transcriptPrompt).not.toContain("System: [t] Initial event.");
2564+
expect(call?.commandBody).toContain("System event after active run");
2565+
expect(call?.transcriptCommandBody).not.toContain("System event after active run");
2566+
expect(call?.followupRun.prompt).toContain("System event after active run");
2567+
expect(call?.followupRun.transcriptPrompt).not.toContain("System event after active run");
2568+
expect(peekSystemEventEntries("session-key")).toStrictEqual([]);
25022569
});
25032570

25042571
it("threads inbound context as current-turn context without changing transcript text", async () => {
@@ -3777,6 +3844,38 @@ describe("runPreparedReply media-only handling", () => {
37773844
expect(call.followupRun.run.extraSystemPrompt ?? "").not.toContain("Runtime System Events");
37783845
});
37793846

3847+
it("includes route system events in a thread-scoped turn", async () => {
3848+
const actualSystemEvents = await vi.importActual<typeof import("./session-system-events.js")>(
3849+
"./session-system-events.js",
3850+
);
3851+
vi.mocked(drainFormattedSystemEvents).mockImplementation(
3852+
actualSystemEvents.drainFormattedSystemEvents,
3853+
);
3854+
enqueueSystemEvent("Slack reaction added: :eyes:", {
3855+
sessionKey: "agent:main:slack:channel:c123",
3856+
});
3857+
enqueueSystemEvent("Slack message in #claw-test from Alice", {
3858+
sessionKey: "agent:main:slack:channel:c123:thread:123.456",
3859+
});
3860+
3861+
await runPrepared({
3862+
ctx: createInboundBody("report queued reactions"),
3863+
opts: withReplySystemEventSessionKey({}, "agent:main:slack:channel:c123"),
3864+
provider: "",
3865+
model: "",
3866+
resolvedThinkLevel: "off",
3867+
sessionKey: "agent:main:slack:channel:c123:thread:123.456",
3868+
});
3869+
3870+
const prompt = requireRunReplyAgentCall().followupRun.prompt;
3871+
expect(prompt).toContain("Slack reaction added: :eyes:");
3872+
expect(prompt).toContain("Slack message in #claw-test from Alice");
3873+
expect(peekSystemEventEntries("agent:main:slack:channel:c123")).toStrictEqual([]);
3874+
expect(peekSystemEventEntries("agent:main:slack:channel:c123:thread:123.456")).toStrictEqual(
3875+
[],
3876+
);
3877+
});
3878+
37803879
it("keeps sender ownership when queued system events are prepended", async () => {
37813880
vi.mocked(drainFormattedSystemEvents).mockResolvedValueOnce(
37823881
"System: [t] External webhook payload.",
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const REPLY_SYSTEM_EVENT_SESSION_KEY = Symbol("openclaw.reply.systemEventSessionKey");
2+
3+
/** Attach route-owned system-event state without widening public reply option contracts. */
4+
export function withReplySystemEventSessionKey<T extends object>(
5+
options: T,
6+
sessionKey: string,
7+
): T {
8+
return {
9+
...options,
10+
[REPLY_SYSTEM_EVENT_SESSION_KEY]: sessionKey,
11+
};
12+
}
13+
14+
/** Read route-owned system-event state after it crosses internal reply-option spreads. */
15+
export function getReplySystemEventSessionKey(options: object | undefined): string | undefined {
16+
if (!options) {
17+
return undefined;
18+
}
19+
const value = (options as Record<PropertyKey, unknown>)[REPLY_SYSTEM_EVENT_SESSION_KEY];
20+
return typeof value === "string" ? value : undefined;
21+
}

‎src/channels/turn/lifecycle.ts‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { suppressPendingFinalDelivery } from "../../auto-reply/reply/dispatch-fr
44
import type { DispatchFromConfigResult } from "../../auto-reply/reply/dispatch-from-config.types.js";
55
import type { ReplyDispatchKind } from "../../auto-reply/reply/reply-dispatcher.types.js";
66
import { runWithSessionInitConflictRetry } from "../../auto-reply/reply/session-init-conflict-retry.js";
7+
import { withReplySystemEventSessionKey } from "../../auto-reply/reply/system-event-session-key.js";
78
import { resolveSessionStorePathCore } from "../../config/sessions/paths.js";
89
import {
910
deriveInboundMessageHookContext,
@@ -111,14 +112,17 @@ export function assembleResolvedChannelTurn<
111112
function resolveAssembledReplyPipeline(
112113
params: DispatchableChannelTurn,
113114
): Pick<AssembledChannelTurn, "dispatcherOptions" | "replyOptions"> {
114-
const turnAdoptionLifecycle =
115-
params.turnAdoptionLifecycle ?? params.replyOptions?.turnAdoptionLifecycle;
115+
const adoption = params.turnAdoptionLifecycle ?? params.replyOptions?.turnAdoptionLifecycle;
116+
let replyOptions = adoption
117+
? { ...params.replyOptions, turnAdoptionLifecycle: adoption }
118+
: params.replyOptions;
119+
if (params.routeSessionKey !== params.ctxPayload.SessionKey) {
120+
replyOptions = withReplySystemEventSessionKey(replyOptions ?? {}, params.routeSessionKey);
121+
}
116122
if (!params.replyPipeline) {
117123
return {
118124
dispatcherOptions: params.dispatcherOptions,
119-
replyOptions: turnAdoptionLifecycle
120-
? { ...params.replyOptions, turnAdoptionLifecycle }
121-
: params.replyOptions,
125+
replyOptions,
122126
};
123127
}
124128
const { onModelSelected, ...replyPipeline } = createChannelReplyPipeline({
@@ -135,8 +139,7 @@ function resolveAssembledReplyPipeline(
135139
},
136140
replyOptions: {
137141
onModelSelected,
138-
...params.replyOptions,
139-
...(turnAdoptionLifecycle ? { turnAdoptionLifecycle } : {}),
142+
...replyOptions,
140143
},
141144
};
142145
}

‎src/channels/turn/run-channel-turn.pipeline.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
33
import type { ReplyPayload } from "../../auto-reply/reply-payload.js";
44
import type { DispatchReplyWithBufferedBlockDispatcher } from "../../auto-reply/reply/provider-dispatcher.types.js";
55
import { createReplyDispatcher } from "../../auto-reply/reply/reply-dispatcher.js";
6+
import { getReplySystemEventSessionKey } from "../../auto-reply/reply/system-event-session-key.js";
67
import type { FinalizedMsgContext } from "../../auto-reply/templating.js";
78
import type { OpenClawConfig } from "../../config/types.openclaw.js";
89
import {
@@ -231,6 +232,44 @@ describe("channel turn pipeline", () => {
231232
expect(onDelivered).toHaveBeenCalledOnce();
232233
});
233234

235+
it.each([
236+
{
237+
channel: "slack",
238+
routeSessionKey: "agent:main:slack:channel:c1",
239+
dispatchSessionKey: "agent:main:slack:channel:c1:thread:123.456",
240+
},
241+
{
242+
channel: "discord",
243+
routeSessionKey: "agent:main:discord:channel:c1",
244+
dispatchSessionKey: "agent:main:discord:channel:c1:thread:t1",
245+
},
246+
])("carries $channel route system-event ownership privately into dispatch", async (scenario) => {
247+
const { channel, routeSessionKey, dispatchSessionKey } = scenario;
248+
const dispatchReplyWithBufferedBlockDispatcher = vi.fn(async (params) => {
249+
expect(params.ctx).not.toHaveProperty("SystemEventSessionKey");
250+
expect(getReplySystemEventSessionKey({ ...params.replyOptions })).toBe(routeSessionKey);
251+
await params.dispatcherOptions.deliver({ text: "reply" }, { kind: "final" });
252+
return { queuedFinal: true, counts: { tool: 0, block: 0, final: 1 } };
253+
}) as DispatchReplyWithBufferedBlockDispatcher;
254+
255+
await dispatchTestAssembledTurn({
256+
channel,
257+
routeSessionKey,
258+
ctxPayload: createCtx({
259+
SessionKey: dispatchSessionKey,
260+
Surface: channel,
261+
Provider: channel,
262+
}),
263+
recordInboundSession: createRecordInboundSession(),
264+
dispatchReplyWithBufferedBlockDispatcher,
265+
delivery: {
266+
deliver: async () => ({ visibleReplySent: true }),
267+
},
268+
});
269+
270+
expect(dispatchReplyWithBufferedBlockDispatcher).toHaveBeenCalledOnce();
271+
});
272+
234273
it("does not emit a second failure when a post-send observer throws", async () => {
235274
const observerError = new Error("observer failed");
236275
const onError = vi.fn();

0 commit comments

Comments
 (0)