Skip to content

Commit 24c4637

Browse files
steipeteampagent
andauthored
improve(mattermost): speed up inbound direct-message replies (#128431)
* perf(mattermost): reuse inbound channel for replies * fix(mattermost): reject interaction route replacement --------- Co-authored-by: Amp <[email protected]>
1 parent b6798cb commit 24c4637

17 files changed

Lines changed: 143 additions & 359 deletions

‎extensions/mattermost/src/channel.send-loopback.test.ts‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import { createPluginRuntimeMock } from "openclaw/plugin-sdk/plugin-test-runtime
33
import { withServer } from "openclaw/plugin-sdk/test-env";
44
import { describe, expect, it, vi } from "vitest";
55
import { mattermostPlugin } from "./channel.js";
6+
import { deliverMattermostReplyPayload } from "./mattermost/reply-delivery.js";
7+
import { sendMessageMattermost } from "./mattermost/send.js";
68
import type { OpenClawConfig } from "./runtime-api.js";
79
import { setMattermostRuntime } from "./runtime.js";
810

@@ -17,6 +19,76 @@ vi.mock("./mattermost/runtime-api.js", async () => ({
1719
}));
1820

1921
describe("Mattermost send action loopback", () => {
22+
it("reuses the inbound provider channel when delivering a direct reply", async () => {
23+
const requests: Array<{ path: string; body?: unknown }> = [];
24+
25+
await withServer(
26+
(request, response) => {
27+
let body = "";
28+
request.setEncoding("utf8");
29+
request.on("data", (chunk) => {
30+
body += chunk;
31+
});
32+
request.on("end", () => {
33+
const path = request.url ?? "";
34+
requests.push({ path, ...(body ? { body: JSON.parse(body) as unknown } : {}) });
35+
response.writeHead(201, { "content-type": "application/json" });
36+
if (path === "/api/v4/users/me") {
37+
response.end(JSON.stringify({ id: "cccccccccccccccccccccccccc" }));
38+
return;
39+
}
40+
if (path === "/api/v4/channels/direct") {
41+
response.end(JSON.stringify({ id: CHANNEL_ID }));
42+
return;
43+
}
44+
response.end(
45+
JSON.stringify({
46+
id: "post-loopback",
47+
channel_id: CHANNEL_ID,
48+
message: "prepared direct reply",
49+
}),
50+
);
51+
});
52+
},
53+
async (baseUrl) => {
54+
const core = createPluginRuntimeMock();
55+
setMattermostRuntime(core);
56+
const cfg = {
57+
channels: {
58+
mattermost: {
59+
botToken: "prepared-inbound-loopback",
60+
baseUrl,
61+
network: { dangerouslyAllowPrivateNetwork: true },
62+
},
63+
},
64+
} as OpenClawConfig;
65+
66+
const result = await deliverMattermostReplyPayload({
67+
core,
68+
cfg,
69+
payload: { text: "prepared direct reply" },
70+
channelId: CHANNEL_ID,
71+
accountId: "default",
72+
textLimit: 4000,
73+
tableMode: "off",
74+
sendMessage: sendMessageMattermost,
75+
});
76+
77+
expect(result).toMatchObject({
78+
outcome: "text",
79+
messageIds: ["post-loopback"],
80+
visibleReplySent: true,
81+
});
82+
expect(requests).toEqual([
83+
{
84+
path: "/api/v4/posts",
85+
body: { channel_id: CHANNEL_ID, message: "prepared direct reply" },
86+
},
87+
]);
88+
},
89+
);
90+
});
91+
2092
it("sends text with blank attachment placeholders and rejects nonblank payloads", async () => {
2193
const requests: Array<{ path: string; body: unknown }> = [];
2294

‎extensions/mattermost/src/delivery-trace.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,7 @@ function setupMattermostTrace(recorder: WireRecorder) {
196196
core,
197197
cfg,
198198
payload: resolvedPayload,
199-
to: `channel:${CHANNEL_ID}`,
199+
channelId: CHANNEL_ID,
200200
accountId: ACCOUNT_ID,
201201
agentId: "agent",
202202
replyToId: resolveMattermostReplyRootId({

‎extensions/mattermost/src/mattermost/client.retry.test.ts‎

Lines changed: 1 addition & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,64 +1,7 @@
11
// Mattermost tests cover client.retry plugin behavior.
22
import { MAX_TIMER_TIMEOUT_MS } from "openclaw/plugin-sdk/number-runtime";
33
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4-
import {
5-
createMattermostClient,
6-
createMattermostDirectChannelWithRetry,
7-
resolveMattermostReplyDeliveryBarrierTimeoutMs,
8-
} from "./client.js";
9-
10-
describe("resolveMattermostReplyDeliveryBarrierTimeoutMs", () => {
11-
it("uses the default barrier for non-DM deliveries", () => {
12-
expect(
13-
resolveMattermostReplyDeliveryBarrierTimeoutMs({
14-
isDirect: false,
15-
queuedCounts: { tool: 1, block: 1, final: 1 },
16-
}),
17-
).toBeUndefined();
18-
});
19-
20-
it("uses the default barrier when no deliveries were queued", () => {
21-
expect(
22-
resolveMattermostReplyDeliveryBarrierTimeoutMs({
23-
isDirect: true,
24-
queuedCounts: { tool: 0, block: 0, final: 0 },
25-
}),
26-
).toBeUndefined();
27-
});
28-
29-
it("covers the default retry envelope plus scheduling slack", () => {
30-
expect(
31-
resolveMattermostReplyDeliveryBarrierTimeoutMs({
32-
isDirect: true,
33-
queuedCounts: { tool: 0, block: 0, final: 1 },
34-
}),
35-
).toBe(210_000);
36-
});
37-
38-
it("covers one maximum retry envelope per queued delivery", () => {
39-
expect(
40-
resolveMattermostReplyDeliveryBarrierTimeoutMs({
41-
isDirect: true,
42-
dmRetryOptions: {
43-
maxRetries: 10,
44-
maxDelayMs: 60_000,
45-
timeoutMs: 120_000,
46-
},
47-
queuedCounts: { tool: 1, block: 0, final: 1 },
48-
}),
49-
).toBe(3_960_000);
50-
});
51-
52-
it("includes the configured inter-block delay budget", () => {
53-
expect(
54-
resolveMattermostReplyDeliveryBarrierTimeoutMs({
55-
isDirect: true,
56-
queuedCounts: { tool: 0, block: 2, final: 0 },
57-
humanDelayBudgetMs: 180_000,
58-
}),
59-
).toBe(600_000);
60-
});
61-
});
4+
import { createMattermostClient, createMattermostDirectChannelWithRetry } from "./client.js";
625

636
describe("createMattermostDirectChannelWithRetry", () => {
647
const mockFetch = vi.fn<typeof fetch>();

‎extensions/mattermost/src/mattermost/client.ts‎

Lines changed: 2 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -393,35 +393,6 @@ export type CreateDmChannelRetryOptions = {
393393
onRetry?: (attempt: number, delayMs: number, error: Error) => void;
394394
};
395395

396-
const DM_REPLY_DELIVERY_BARRIER_SLACK_MS = 60_000;
397-
398-
/** Covers DM creation retries without extending channel-delivery stalls. */
399-
export function resolveMattermostReplyDeliveryBarrierTimeoutMs(params: {
400-
isDirect: boolean;
401-
dmRetryOptions?: CreateDmChannelRetryOptions;
402-
queuedCounts: Readonly<Record<"tool" | "block" | "final", number>>;
403-
humanDelayBudgetMs?: number;
404-
}): number | undefined {
405-
if (!params.isDirect) {
406-
return undefined;
407-
}
408-
const deliveryCount = Object.values(params.queuedCounts).reduce((sum, count) => sum + count, 0);
409-
if (deliveryCount === 0) {
410-
return undefined;
411-
}
412-
const maxRetries = params.dmRetryOptions?.maxRetries ?? 3;
413-
const maxDelayMs = params.dmRetryOptions?.maxDelayMs ?? 10_000;
414-
const timeoutMs = params.dmRetryOptions?.timeoutMs ?? 30_000;
415-
const perDeliveryTimeoutMs =
416-
(maxRetries + 1) * timeoutMs + maxRetries * maxDelayMs + DM_REPLY_DELIVERY_BARRIER_SLACK_MS;
417-
const totalTimeoutMs =
418-
perDeliveryTimeoutMs * deliveryCount + Math.max(0, params.humanDelayBudgetMs ?? 0);
419-
return resolveTimerTimeoutMs(
420-
Number.isFinite(totalTimeoutMs) ? totalTimeoutMs : Number.MAX_SAFE_INTEGER,
421-
perDeliveryTimeoutMs,
422-
);
423-
}
424-
425396
const RETRYABLE_NETWORK_ERROR_CODES = new Set([
426397
"ECONNRESET",
427398
"ECONNREFUSED",
@@ -500,8 +471,8 @@ export async function createMattermostDirectChannelWithRetry(
500471
attempts: maxRetries + 1,
501472
// Core retry raises maxDelayMs to the minDelayMs floor, but the schema
502473
// allows initialDelayMs above the (defaulted) maxDelayMs cap. The cap is
503-
// the documented contract here and the reply-delivery barrier budgets
504-
// with it, so clamp the base instead of letting the floor win.
474+
// the documented contract here, so clamp the base instead of letting
475+
// the floor win.
505476
minDelayMs: Math.min(initialDelayMs, maxDelayMs),
506477
maxDelayMs,
507478
// Full jitter (uniform [delay, 2*delay) with maxDelayMs applied after

‎extensions/mattermost/src/mattermost/monitor-event-plan.ts‎

Lines changed: 31 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import type { MattermostChannel } from "./client.js";
55
import { resolveMattermostTrustedChatKind } from "./monitor-auth.js";
66
import { resolveMattermostThreadSessionContext } from "./monitor-context.js";
77
import type { MattermostMonitorContext } from "./monitor-types.js";
8-
import { createMattermostReplyDeliveryBarrier } from "./reply-delivery.js";
98
import { logTypingFailure } from "./runtime-api.js";
109

1110
type MattermostEventPlanParams = {
@@ -101,46 +100,39 @@ export async function buildMattermostEventPlan(
101100
OriginatingChannel: "mattermost" as const,
102101
OriginatingTo: to,
103102
}),
104-
createReplyPlan: () => {
105-
const deliveryBarrier = createMattermostReplyDeliveryBarrier({
106-
isDirect: kind === "direct",
107-
dmRetryOptions: monitor.account.config.dmChannelRetry,
108-
});
109-
return {
110-
textLimit: monitor.core.channel.text.resolveTextChunkLimit(
111-
monitor.cfg,
112-
"mattermost",
113-
monitor.account.accountId,
114-
{ fallbackLimit: monitor.account.textChunkLimit ?? 4000 },
115-
),
116-
tableMode: monitor.core.channel.text.resolveMarkdownTableMode({
117-
cfg: monitor.cfg,
118-
channel: "mattermost",
119-
accountId: monitor.account.accountId,
120-
}),
121-
deliveryBarrier,
122-
replyPipeline: {
123-
typing: {
124-
start: () =>
125-
monitor.resources.sendTypingIndicator(params.channelId, thread.effectiveReplyToId),
126-
onStartError: (error: unknown) => {
127-
logTypingFailure({
128-
log: monitor.logDebugMessage,
129-
channel: "mattermost",
130-
target: params.channelId,
131-
error,
132-
});
133-
},
103+
createReplyPlan: () => ({
104+
textLimit: monitor.core.channel.text.resolveTextChunkLimit(
105+
monitor.cfg,
106+
"mattermost",
107+
monitor.account.accountId,
108+
{ fallbackLimit: monitor.account.textChunkLimit ?? 4000 },
109+
),
110+
tableMode: monitor.core.channel.text.resolveMarkdownTableMode({
111+
cfg: monitor.cfg,
112+
channel: "mattermost",
113+
accountId: monitor.account.accountId,
114+
}),
115+
replyPipeline: {
116+
typing: {
117+
start: () =>
118+
monitor.resources.sendTypingIndicator(params.channelId, thread.effectiveReplyToId),
119+
onStartError: (error: unknown) => {
120+
logTypingFailure({
121+
log: monitor.logDebugMessage,
122+
channel: "mattermost",
123+
target: params.channelId,
124+
error,
125+
});
134126
},
135127
},
136-
replyOptions: {
137-
disableBlockStreaming:
138-
typeof monitor.account.blockStreaming === "boolean"
139-
? !monitor.account.blockStreaming
140-
: undefined,
141-
},
142-
};
143-
},
128+
},
129+
replyOptions: {
130+
disableBlockStreaming:
131+
typeof monitor.account.blockStreaming === "boolean"
132+
? !monitor.account.blockStreaming
133+
: undefined,
134+
},
135+
}),
144136
};
145137
}
146138

‎extensions/mattermost/src/mattermost/monitor-interactions.ts‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ export function registerMattermostInteractions(params: {
9595
if (!eventPlan) {
9696
return;
9797
}
98-
const { channelDisplay, kind, route, thread, to } = eventPlan;
98+
const { channelDisplay, channelId, kind, route, thread, to } = eventPlan;
9999
const bodyText = `[Button click: user @${button.userName} selected "${button.actionName}"]`;
100100
const ctxPayload = eventPlan.finalizeContext({
101101
Body: bodyText,
@@ -109,8 +109,7 @@ export function registerMattermostInteractions(params: {
109109
WasMentioned: true,
110110
CommandAuthorized: false,
111111
});
112-
const { deliveryBarrier, replyOptions, replyPipeline, tableMode, textLimit } =
113-
eventPlan.createReplyPlan();
112+
const { replyOptions, replyPipeline, tableMode, textLimit } = eventPlan.createReplyPlan();
114113
await core.channel.inbound.dispatch({
115114
cfg,
116115
channel: "mattermost",
@@ -128,7 +127,7 @@ export function registerMattermostInteractions(params: {
128127
core,
129128
cfg,
130129
payload,
131-
to,
130+
channelId,
132131
accountId: account.accountId,
133132
agentId: route.agentId,
134133
replyToId: resolveMattermostInteractionReplyRootId({
@@ -141,7 +140,6 @@ export function registerMattermostInteractions(params: {
141140
textLimit,
142141
tableMode,
143142
sendMessage: sendMessageMattermost,
144-
onDmChannelResolution: deliveryBarrier.trackDmChannelResolution,
145143
});
146144
if (result.visibleReplySent) {
147145
runtime.log?.(`delivered button-click reply to ${to}`);
@@ -154,8 +152,6 @@ export function registerMattermostInteractions(params: {
154152
},
155153
replyPipeline,
156154
dispatcherOptions: {
157-
resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
158-
onDeliverySettled: deliveryBarrier.markDeliverySettled,
159155
humanDelay: resolveHumanDelayConfig(cfg, route.agentId),
160156
},
161157
replyOptions,
@@ -167,7 +163,6 @@ export function registerMattermostInteractions(params: {
167163
source: "mattermost-interactions",
168164
accountId: account.accountId,
169165
log: (message: string) => runtime.log?.(message),
170-
replaceExisting: true,
171166
throwOnFailure: true,
172167
});
173168
}

0 commit comments

Comments
 (0)