Skip to content

Commit ffdc7aa

Browse files
fix(slack): route DM thread replies to main session instead of thread-scoped session (#82418)
* fix(slack): route DM thread replies to main session instead of thread-scoped session DM thread replies (user replies inside a thread under a bot message in a DM) were routed to a thread-specific session key instead of the user's main DM session. This caused the agent to never receive the inbound on the expected session, making the bot appear unresponsive. The root cause was in prepare-routing.ts: canonicalThreadId for isDirectMessage was set to threadTs when isThreadReply was true, creating a session key like agent:main:slack:direct:u3:thread:<ts>. DM threads are a UI affordance — not a session boundary — so all DM messages should route to the main DM session regardless of thread_ts. Also adds a diagnostic logVerbose warning when assistant_app_thread message_changed events fail sender resolution (Case 2 of #82390), which was previously completely silent. Fixes #82390 * chore(slack): polish DM thread routing PR * test(slack): update DM thread routing contract * test(slack): flatten non-main DM thread expectations * fix(slack): preserve bound DM thread routes * test(slack): align DM thread session fixtures * fix(slack): keep flattened DM thread metadata scoped * fix(slack): preserve DM thread delivery routes --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent cc22c2a commit ffdc7aa

24 files changed

Lines changed: 551 additions & 36 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ Docs: https://docs.openclaw.ai
3232
- Plugins/doctor: migrate legacy top-level plugin `tools` declarations into `contracts.tools`, so `openclaw doctor --fix` repairs local plugins for the manifest tool contract. (#81112) Thanks @100yenadmin.
3333
- Slack: guide agents to use stable `<@USER_ID>` mention tokens from context instead of plain `@name` text, so user mentions link and notify correctly. Fixes #82090. (#82152) Thanks @neeravmakwana.
3434
- Auth: serialize provider login writes through the auth-profile lock for OpenAI Codex, Anthropic, Cloudflare AI Gateway, GitHub Copilot, and z.ai, preserving upsert semantics so a live Gateway cannot overwrite freshly refreshed OAuth credentials with an expired in-memory snapshot.
35+
- Slack: keep DM thread replies on the main direct-message session instead of routing them to invisible thread-scoped sessions. Refs #82390. (#82418) Thanks @kagura-agent.
3536
- Codex app-server: release raw assistant completions when `turn/completed` is missing while keeping commentary/status items as progress, preventing completed Codex runs from hanging until timeout. Fixes #82343. (#82403) Thanks @IWhatsskill.
3637
- Agents/sessions: remove the transient `*.bak-<pid>-<ts>` backup written by `repairSessionFileIfNeeded` once the atomic replace succeeds, so a stuck session with a persistently malformed JSONL line no longer accumulates one snapshot per repair invocation. Fixes #80960. (#80969) Thanks @100yenadmin. Co-authored by @tynamite.
3738
- CLI/status: show plain empty-state messages instead of empty Channels and Sessions tables when no channels or sessions exist.

‎extensions/slack/src/monitor.tool-result.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -820,7 +820,7 @@ describe("monitorSlackProvider tool results", () => {
820820

821821
expect(replyMock).toHaveBeenCalledTimes(1);
822822
const ctx = getFirstReplySessionCtx();
823-
expect(ctx.SessionKey).toBe("agent:main:main:thread:123");
823+
expect(ctx.SessionKey).toBe("agent:main:main");
824824
expect(ctx.ParentSessionKey).toBeUndefined();
825825
});
826826

‎extensions/slack/src/monitor/events/messages.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { SlackEventMiddlewareArgs } from "@slack/bolt";
22
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
3-
import { danger } from "openclaw/plugin-sdk/runtime-env";
3+
import { danger, logVerbose, shouldLogVerbose } from "openclaw/plugin-sdk/runtime-env";
44
import { enqueueSystemEvent } from "openclaw/plugin-sdk/system-event-runtime";
55
import type { SlackAppMentionEvent, SlackMessageEvent } from "../../types.js";
66
import { normalizeSlackChannelType } from "../channel-type.js";
@@ -107,6 +107,11 @@ function resolveAssistantMessageChangedInbound(params: {
107107
botUserId: params.ctx.botUserId,
108108
});
109109
if (!senderId) {
110+
if (shouldLogVerbose()) {
111+
logVerbose(
112+
`slack: assistant_app_thread message_changed in DM channel=${changed.channel} dropped: no sender resolved from metadata`,
113+
);
114+
}
110115
return undefined;
111116
}
112117
return {

‎extensions/slack/src/monitor/message-handler/dispatch.preview-fallback.test.ts‎

Lines changed: 48 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -946,7 +946,7 @@ describe("dispatchPreparedSlackMessage preview fallback", () => {
946946
expect(deliverRepliesMock).toHaveBeenCalledTimes(1);
947947
});
948948

949-
it("updates non-main DM last-route metadata on the prepared thread session", async () => {
949+
it("updates non-main DM last-route metadata on the prepared direct session", async () => {
950950
await dispatchPreparedSlackMessage(
951951
createPreparedSlackMessage({
952952
cfg: { session: { dmScope: "per-channel-peer" } },
@@ -965,14 +965,14 @@ describe("dispatchPreparedSlackMessage preview fallback", () => {
965965
},
966966
ctxPayload: {
967967
MessageThreadId: "500.000",
968-
SessionKey: "agent:main:slack:direct:u1:thread:500.000",
968+
SessionKey: "agent:main:slack:direct:u1",
969969
},
970970
}),
971971
);
972972

973973
expect(updateLastRouteMock).toHaveBeenCalledWith({
974974
storePath: "/tmp/openclaw-store.json",
975-
sessionKey: "agent:main:slack:direct:u1:thread:500.000",
975+
sessionKey: "agent:main:slack:direct:u1",
976976
deliveryContext: {
977977
channel: "slack",
978978
to: "user:U1",
@@ -981,7 +981,49 @@ describe("dispatchPreparedSlackMessage preview fallback", () => {
981981
},
982982
ctx: {
983983
MessageThreadId: "500.000",
984-
SessionKey: "agent:main:slack:direct:u1:thread:500.000",
984+
SessionKey: "agent:main:slack:direct:u1",
985+
},
986+
});
987+
});
988+
989+
it("uses DM transport thread metadata for last-route updates", async () => {
990+
await dispatchPreparedSlackMessage(
991+
createPreparedSlackMessage({
992+
isDirectMessage: true,
993+
message: {
994+
channel: "D123",
995+
user: "U1",
996+
ts: "701.000",
997+
thread_ts: "701.000",
998+
},
999+
route: {
1000+
agentId: "main",
1001+
mainSessionKey: "agent:main:main",
1002+
sessionKey: "agent:main:main",
1003+
lastRoutePolicy: "main",
1004+
},
1005+
ctxPayload: {
1006+
MessageThreadId: undefined,
1007+
ReplyToId: "701.000",
1008+
TransportThreadId: "701.000",
1009+
SessionKey: "agent:main:main",
1010+
},
1011+
}),
1012+
);
1013+
1014+
expect(updateLastRouteMock).toHaveBeenCalledWith({
1015+
storePath: "/tmp/openclaw-store.json",
1016+
sessionKey: "agent:main:main",
1017+
deliveryContext: {
1018+
channel: "slack",
1019+
to: "user:U1",
1020+
accountId: "default",
1021+
threadId: "701.000",
1022+
},
1023+
ctx: {
1024+
ReplyToId: "701.000",
1025+
TransportThreadId: "701.000",
1026+
SessionKey: "agent:main:main",
9851027
},
9861028
});
9871029
});
@@ -1004,7 +1046,7 @@ describe("dispatchPreparedSlackMessage preview fallback", () => {
10041046
},
10051047
ctxPayload: {
10061048
MessageThreadId: "600.000",
1007-
SessionKey: "agent:main:main:thread:600.000",
1049+
SessionKey: "agent:main:main",
10081050
},
10091051
}),
10101052
);
@@ -1020,7 +1062,7 @@ describe("dispatchPreparedSlackMessage preview fallback", () => {
10201062
},
10211063
ctx: {
10221064
MessageThreadId: "600.000",
1023-
SessionKey: "agent:main:main:thread:600.000",
1065+
SessionKey: "agent:main:main",
10241066
},
10251067
});
10261068
});

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -385,7 +385,7 @@ export async function dispatchPreparedSlackMessage(prepared: PreparedSlackMessag
385385
channel: "slack",
386386
to: `user:${message.user}`,
387387
accountId: route.accountId,
388-
threadId: prepared.ctxPayload.MessageThreadId,
388+
threadId: prepared.ctxPayload.MessageThreadId ?? prepared.ctxPayload.TransportThreadId,
389389
},
390390
ctx: prepared.ctxPayload,
391391
});

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

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -203,24 +203,27 @@ export function resolveSlackRoutingContext(params: {
203203
? seedCandidateThreadId
204204
: undefined;
205205
const roomThreadId = isThreadReply && threadTs ? threadTs : undefined;
206+
// DM threads are a UI affordance, not a session boundary. Route all DM
207+
// messages, including thread replies, to the user's main DM session so
208+
// the agent sees them as part of the existing conversation.
206209
const canonicalThreadId = isDirectMessage
207-
? isThreadReply
208-
? threadTs
209-
: undefined
210+
? undefined
210211
: isRoomish
211212
? roomThreadId
212213
: isThreadReply
213214
? threadTs
214215
: autoThreadId;
215216
const routedThreadId = canonicalThreadId ?? (isRoomish ? seededRoomThreadId : undefined);
216217
const baseConversationId = resolveSlackBaseConversationId({ message, isDirectMessage });
217-
const boundThreadRoute = routedThreadId
218+
const runtimeBindingThreadId =
219+
routedThreadId ?? (isDirectMessage && isThreadReply ? threadTs : undefined);
220+
const boundThreadRoute = runtimeBindingThreadId
218221
? resolveRuntimeConversationBindingRoute({
219222
route,
220223
conversation: {
221224
channel: "slack",
222225
accountId: account.accountId,
223-
conversationId: routedThreadId,
226+
conversationId: runtimeBindingThreadId,
224227
parentConversationId: baseConversationId,
225228
},
226229
})

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ export async function resolveSlackThreadContextData(params: {
103103
roomLabel: string;
104104
storePath: string;
105105
sessionKey: string;
106+
forceInitialHistory?: boolean;
106107
allowFromLower: string[];
107108
allowNameMatching: boolean;
108109
contextVisibilityMode: ContextVisibilityMode;
@@ -213,7 +214,10 @@ export async function resolveSlackThreadContextData(params: {
213214

214215
const threadInitialHistoryLimit = params.account.config?.thread?.initialHistoryLimit ?? 20;
215216

216-
if (threadInitialHistoryLimit > 0 && !threadSessionPreviousTimestamp) {
217+
if (
218+
threadInitialHistoryLimit > 0 &&
219+
(!threadSessionPreviousTimestamp || params.forceInitialHistory)
220+
) {
217221
const currentBotRootTs = starter?.ts ?? params.threadTs;
218222
const threadHistory = await resolveSlackThreadHistory({
219223
channelId: params.message.channel,

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

Lines changed: 108 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -292,9 +292,14 @@ describe("slack prepareSlackMessage inbound contract", () => {
292292
replies: ReturnType<typeof vi.fn>,
293293
starterText: string,
294294
followUpText: string,
295+
options?: { expectStarterBody?: boolean },
295296
) {
296297
assertPrepared(prepared);
297-
expect(prepared.ctxPayload.ThreadStarterBody).toBe(starterText);
298+
if (options?.expectStarterBody === false) {
299+
expect(prepared.ctxPayload.ThreadStarterBody).toBeUndefined();
300+
} else {
301+
expect(prepared.ctxPayload.ThreadStarterBody).toBe(starterText);
302+
}
298303
expect(prepared.ctxPayload.ThreadHistoryBody).toContain(starterText);
299304
expect(prepared.ctxPayload.ThreadHistoryBody).toContain(followUpText);
300305
expect(prepared.ctxPayload.ThreadHistoryBody).not.toContain("assistant reply");
@@ -1345,6 +1350,7 @@ Second paragraph should still reach the agent after Slack's preview cutoff.`;
13451350
replies,
13461351
"starter from open dm",
13471352
"dm follow-up",
1353+
{ expectStarterBody: false },
13481354
);
13491355
});
13501356

@@ -1502,7 +1508,7 @@ Second paragraph should still reach the agent after Slack's preview cutoff.`;
15021508
expect(prepared.ctxPayload.MessageThreadId).toBe("500.000");
15031509
});
15041510

1505-
it("records non-main DM last-route metadata on the prepared thread session", async () => {
1511+
it("records non-main DM thread replies on the prepared direct session", async () => {
15061512
const { storePath } = storeFixture.makeTmpStorePath();
15071513
const slackCtx = createInboundSlackCtx({
15081514
cfg: {
@@ -1525,7 +1531,13 @@ Second paragraph should still reach the agent after Slack's preview cutoff.`;
15251531

15261532
assertPrepared(prepared);
15271533
expect(prepared.route.sessionKey).toBe("agent:main:slack:direct:u1");
1528-
expect(prepared.ctxPayload.SessionKey).toBe("agent:main:slack:direct:u1:thread:500.000");
1534+
expect(prepared.ctxPayload.SessionKey).toBe("agent:main:slack:direct:u1");
1535+
expect(prepared.ctxPayload.ParentSessionKey).toBeUndefined();
1536+
expect(prepared.ctxPayload.MessageThreadId).toBeUndefined();
1537+
expect(prepared.ctxPayload.ThreadLabel).toBeUndefined();
1538+
expect(prepared.ctxPayload.IsFirstThreadTurn).toBeUndefined();
1539+
expect(prepared.ctxPayload.ReplyToId).toBe("500.000");
1540+
expect(prepared.ctxPayload.TransportThreadId).toBe("500.000");
15291541
expect(
15301542
(prepared.turn.record as { updateLastRoute?: { sessionKey?: string } }).updateLastRoute,
15311543
).toEqual({
@@ -1538,7 +1550,7 @@ Second paragraph should still reach the agent after Slack's preview cutoff.`;
15381550
});
15391551
});
15401552

1541-
it("keeps default main-scope DM last-route metadata on the main session", async () => {
1553+
it("keeps default main-scope DM thread replies on the main session", async () => {
15421554
const slackCtx = createInboundSlackCtx({
15431555
cfg: {
15441556
channels: { slack: { enabled: true, replyToMode: "all" } },
@@ -1558,7 +1570,13 @@ Second paragraph should still reach the agent after Slack's preview cutoff.`;
15581570
);
15591571

15601572
assertPrepared(prepared);
1561-
expect(prepared.ctxPayload.SessionKey).toBe("agent:main:main:thread:600.000");
1573+
expect(prepared.ctxPayload.SessionKey).toBe("agent:main:main");
1574+
expect(prepared.ctxPayload.ParentSessionKey).toBeUndefined();
1575+
expect(prepared.ctxPayload.MessageThreadId).toBeUndefined();
1576+
expect(prepared.ctxPayload.ThreadLabel).toBeUndefined();
1577+
expect(prepared.ctxPayload.IsFirstThreadTurn).toBeUndefined();
1578+
expect(prepared.ctxPayload.ReplyToId).toBe("600.000");
1579+
expect(prepared.ctxPayload.TransportThreadId).toBe("600.000");
15621580
expect(
15631581
(prepared.turn.record as { updateLastRoute?: { sessionKey?: string } }).updateLastRoute,
15641582
).toEqual({
@@ -1571,6 +1589,91 @@ Second paragraph should still reach the agent after Slack's preview cutoff.`;
15711589
});
15721590
});
15731591

1592+
it("preserves Slack thread history when an existing DM session receives a thread reply", async () => {
1593+
const { storePath } = storeFixture.makeTmpStorePath();
1594+
fs.writeFileSync(
1595+
storePath,
1596+
JSON.stringify(
1597+
{
1598+
"agent:main:main": { updatedAt: Date.now() },
1599+
"agent:main:main:thread:650.000": { updatedAt: Date.now() },
1600+
},
1601+
null,
1602+
2,
1603+
),
1604+
);
1605+
const replies = vi
1606+
.fn()
1607+
.mockResolvedValueOnce({
1608+
messages: [{ text: "starter topic", user: "U1", ts: "650.000" }],
1609+
})
1610+
.mockResolvedValueOnce({
1611+
messages: [
1612+
{ text: "starter topic", user: "U1", ts: "650.000" },
1613+
{ text: "assistant reply", bot_id: "B1", ts: "650.500" },
1614+
{ text: "user follow-up", user: "U1", ts: "650.800" },
1615+
{ text: "current message", user: "U1", ts: "651.000" },
1616+
],
1617+
response_metadata: { next_cursor: "" },
1618+
});
1619+
const slackCtx = createInboundSlackCtx({
1620+
cfg: {
1621+
session: { store: storePath },
1622+
channels: { slack: { enabled: true, replyToMode: "all" } },
1623+
} as OpenClawConfig,
1624+
appClient: { conversations: { replies } } as unknown as App["client"],
1625+
replyToMode: "all",
1626+
});
1627+
slackCtx.resolveUserName = async () => ({ name: "Alice" }) as any;
1628+
1629+
const prepared = await prepareMessageWith(
1630+
slackCtx,
1631+
createSlackAccount({ replyToMode: "all", thread: { initialHistoryLimit: 20 } }),
1632+
createSlackMessage({
1633+
text: "current message",
1634+
ts: "651.000",
1635+
thread_ts: "650.000",
1636+
}),
1637+
);
1638+
1639+
assertPrepared(prepared);
1640+
expect(prepared.ctxPayload.SessionKey).toBe("agent:main:main");
1641+
expect(prepared.ctxPayload.MessageThreadId).toBeUndefined();
1642+
expect(prepared.ctxPayload.ThreadStarterBody).toBeUndefined();
1643+
expect(prepared.ctxPayload.ThreadHistoryBody).toContain("starter topic");
1644+
expect(prepared.ctxPayload.ThreadHistoryBody).toContain("user follow-up");
1645+
expect(prepared.ctxPayload.ThreadHistoryBody).not.toContain("assistant reply");
1646+
expect(prepared.ctxPayload.ThreadHistoryBody).not.toContain("current message");
1647+
expect(replies).toHaveBeenCalledTimes(2);
1648+
});
1649+
1650+
it("keeps transport thread metadata for DM parent_user_id replies with self thread_ts", async () => {
1651+
const slackCtx = createInboundSlackCtx({
1652+
cfg: {
1653+
channels: { slack: { enabled: true, replyToMode: "all" } },
1654+
} as OpenClawConfig,
1655+
replyToMode: "all",
1656+
});
1657+
slackCtx.resolveUserName = async () => ({ name: "Alice" }) as any;
1658+
1659+
const prepared = await prepareMessageWith(
1660+
slackCtx,
1661+
createSlackAccount({ replyToMode: "all" }),
1662+
createSlackMessage({
1663+
text: "thread reply",
1664+
ts: "701.000",
1665+
thread_ts: "701.000",
1666+
parent_user_id: "B1",
1667+
}),
1668+
);
1669+
1670+
assertPrepared(prepared);
1671+
expect(prepared.ctxPayload.SessionKey).toBe("agent:main:main");
1672+
expect(prepared.ctxPayload.MessageThreadId).toBeUndefined();
1673+
expect(prepared.ctxPayload.ReplyToId).toBe("701.000");
1674+
expect(prepared.ctxPayload.TransportThreadId).toBe("701.000");
1675+
});
1676+
15741677
it("routes Slack thread replies through runtime conversation bindings", async () => {
15751678
const targetSessionKey = "agent:review:acp:session-67739";
15761679
const binding: SessionBindingRecord = {

0 commit comments

Comments
 (0)