Skip to content

Commit d205216

Browse files
bdjbenBenjamin Badejojalehman
authored
fix(matrix): let follow-ups steer active turns (#128907)
* fix(matrix): let follow-ups reach active turns * fix(auto-reply): persist explicit steer turns * test(matrix): stabilize active steering admission * test: fix active steering type checks * fix(auto-reply): route steer to active embedded owner --------- Co-authored-by: Benjamin Badejo <[email protected]> Co-authored-by: Josh Lehman <[email protected]> Co-authored-by: Josh Lehman <[email protected]>
1 parent 7c116ba commit d205216

15 files changed

Lines changed: 726 additions & 178 deletions
Lines changed: 284 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,284 @@
1+
import path from "node:path";
2+
import {
3+
runChannelInboundEvent,
4+
type ChannelInboundEventRunnerParams,
5+
} from "openclaw/plugin-sdk/channel-inbound";
6+
import type { FinalizedMsgContext, GetReplyOptions } from "openclaw/plugin-sdk/reply-runtime";
7+
import { useAutoCleanupTempDirTracker } from "openclaw/plugin-sdk/test-env";
8+
import { afterEach, describe, expect, it, vi } from "vitest";
9+
import type { OpenClawConfig } from "../../runtime-api.js";
10+
import { installMatrixMonitorTestRuntime } from "../../test-runtime.js";
11+
import type { MatrixMonitorHandlerParams } from "./handler-types.js";
12+
import {
13+
createMatrixHandlerTestHarness,
14+
createMatrixTextMessageEvent,
15+
} from "./handler.test-helpers.js";
16+
import type { MatrixRawEvent } from "./types.js";
17+
18+
type MatrixInboundRun = MatrixMonitorHandlerParams["core"]["channel"]["inbound"]["run"];
19+
type MatrixInboundRunParams = Parameters<MatrixInboundRun>[0];
20+
type TurnAdoptionLifecycle = NonNullable<GetReplyOptions["turnAdoptionLifecycle"]>;
21+
22+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
23+
24+
function createDeferred() {
25+
let resolve!: () => void;
26+
const promise = new Promise<void>((settle) => {
27+
resolve = settle;
28+
});
29+
return { promise, resolve };
30+
}
31+
32+
function createClaimSpies() {
33+
return {
34+
commit: vi.fn(async () => true),
35+
release: vi.fn(),
36+
};
37+
}
38+
39+
function releaseSyntheticResolverAdmissionTicket(options: GetReplyOptions | undefined): void {
40+
if (!options) {
41+
throw new Error("expected reply options with an admission ticket");
42+
}
43+
const symbolOptions = options as GetReplyOptions & Record<symbol, unknown>;
44+
const tickets = Object.getOwnPropertySymbols(options)
45+
.map((key) => symbolOptions[key])
46+
.filter(
47+
(value): value is { wait: (signal?: AbortSignal) => Promise<boolean>; release: () => void } =>
48+
typeof value === "object" &&
49+
value !== null &&
50+
"wait" in value &&
51+
typeof value.wait === "function" &&
52+
"release" in value &&
53+
typeof value.release === "function",
54+
);
55+
const ticket = tickets.at(0);
56+
if (tickets.length !== 1 || !ticket) {
57+
throw new Error(`expected one reply admission ticket, received ${tickets.length}`);
58+
}
59+
// A real getReplyFromConfig run releases this ticket when runReplyAgent publishes
60+
// queue/run ownership. The synthetic resolver must model the same handoff.
61+
ticket.release();
62+
}
63+
64+
describe("Matrix active-turn steering admission", () => {
65+
it.each([
66+
{
67+
name: "configured steer mode",
68+
followupBody: "use the monochrome version instead",
69+
explicitSteer: false,
70+
},
71+
{
72+
name: "an explicit /steer command",
73+
followupBody: "/steer use the monochrome version instead",
74+
explicitSteer: true,
75+
},
76+
])(
77+
"lets $name reach queue policy while the prior Matrix turn is active",
78+
async ({ followupBody, explicitSteer }) => {
79+
installMatrixMonitorTestRuntime();
80+
const tempDir = tempDirs.make("openclaw-matrix-steer-");
81+
const storePath = path.join(tempDir, "sessions.json");
82+
const activeEventId = explicitSteer ? "$active-explicit-steer" : "$active-configured-steer";
83+
const followupEventId = explicitSteer ? "$explicit-steer" : "$configured-steer";
84+
const activeResolverStarted = createDeferred();
85+
const releaseActiveResolver = createDeferred();
86+
const followupTurnResolved = createDeferred();
87+
const claimsByEvent = new Map<string, ReturnType<typeof createClaimSpies>>();
88+
const inboundLifecycles = new Map<string, TurnAdoptionLifecycle | undefined>();
89+
let followupResolverLifecycle: TurnAdoptionLifecycle | undefined;
90+
let followupResolverContext: FinalizedMsgContext | undefined;
91+
92+
const cfg = {
93+
session: { store: storePath },
94+
messages: { queue: { mode: "steer" } },
95+
channels: { matrix: { dm: { allowFrom: ["*"] } } },
96+
} satisfies OpenClawConfig;
97+
const inboundDeduper: NonNullable<MatrixMonitorHandlerParams["inboundDeduper"]> = {
98+
claim: vi.fn(async ({ eventId }) => {
99+
const claim = createClaimSpies();
100+
claimsByEvent.set(eventId, claim);
101+
return {
102+
kind: "claimed" as const,
103+
handle: {
104+
keys: [eventId] as const,
105+
commit: claim.commit,
106+
release: claim.release,
107+
},
108+
};
109+
}),
110+
};
111+
const queuePolicyResolver = vi.fn(
112+
async (ctx: FinalizedMsgContext, options?: GetReplyOptions) => {
113+
releaseSyntheticResolverAdmissionTicket(options);
114+
const eventId = ctx.MessageSid;
115+
if (eventId === activeEventId) {
116+
await options?.turnAdoptionLifecycle?.onAdopted();
117+
activeResolverStarted.resolve();
118+
await releaseActiveResolver.promise;
119+
return undefined;
120+
}
121+
if (eventId === followupEventId) {
122+
followupResolverContext = ctx;
123+
followupResolverLifecycle = options?.turnAdoptionLifecycle;
124+
if (!followupResolverLifecycle?.onDeferred) {
125+
throw new Error("expected Matrix follow-up deferral ownership");
126+
}
127+
expect(followupResolverLifecycle.onDeferred()).not.toBe(false);
128+
await followupResolverLifecycle.onAdopted();
129+
}
130+
return undefined;
131+
},
132+
);
133+
const runWithQueuePolicyResolver = (async (params: MatrixInboundRunParams) => {
134+
const eventId = (params.raw as MatrixRawEvent).event_id;
135+
if (eventId) {
136+
inboundLifecycles.set(eventId, params.turnAdoptionLifecycle);
137+
}
138+
const adapter = params.adapter;
139+
return await runChannelInboundEvent({
140+
...params,
141+
adapter: {
142+
...adapter,
143+
resolveTurn: async (...args: Parameters<typeof adapter.resolveTurn>) => {
144+
const turn = await adapter.resolveTurn(...args);
145+
if (eventId === followupEventId) {
146+
followupTurnResolved.resolve();
147+
}
148+
if (!("route" in turn) || "runDispatch" in turn) {
149+
throw new Error("expected Matrix to resolve a routed channel turn");
150+
}
151+
return { ...turn, replyResolver: queuePolicyResolver as never };
152+
},
153+
},
154+
} as ChannelInboundEventRunnerParams<MatrixRawEvent>);
155+
}) as MatrixInboundRun;
156+
const runtime = { error: vi.fn() };
157+
const { handler } = createMatrixHandlerTestHarness({
158+
cfg,
159+
inboundDeduper,
160+
runtime: runtime as never,
161+
shouldHandleTextCommands: () => true,
162+
hasControlCommand: (text?: string) => text?.startsWith("/steer") === true,
163+
runChannelInboundEvent: runWithQueuePolicyResolver,
164+
});
165+
166+
let activeTurn: Promise<void> | undefined;
167+
let followupTurn: Promise<void> | undefined;
168+
try {
169+
activeTurn = handler(
170+
"!room:example.org",
171+
createMatrixTextMessageEvent({
172+
eventId: activeEventId,
173+
body: "keep this run active",
174+
}),
175+
);
176+
await vi.waitFor(() => expect(queuePolicyResolver).toHaveBeenCalledTimes(1), {
177+
// This suite imports the full Matrix extension graph. Keep the
178+
// active-turn admission assertion deterministic on saturated CI
179+
// workers without weakening the behavior being asserted.
180+
timeout: 10_000,
181+
interval: 10,
182+
});
183+
await activeResolverStarted.promise;
184+
185+
followupTurn = handler(
186+
"!room:example.org",
187+
createMatrixTextMessageEvent({
188+
eventId: followupEventId,
189+
body: followupBody,
190+
}),
191+
);
192+
await followupTurnResolved.promise;
193+
194+
// Before the fix, the second Matrix turn waits at reply-operation admission here;
195+
// queue policy cannot see either configured steer mode or the explicit command.
196+
await vi.waitFor(() => expect(queuePolicyResolver).toHaveBeenCalledTimes(2), {
197+
timeout: 500,
198+
interval: 10,
199+
});
200+
201+
expect(followupResolverContext?.CommandBody).toBe(followupBody);
202+
expect(inboundLifecycles.get(followupEventId)).toMatchObject({ admission: "exclusive" });
203+
// Core wraps the lifecycle to record adoption state; invoking that wrapper must still
204+
// settle the exact replay claim captured by the Matrix handler above.
205+
expect(followupResolverLifecycle).toMatchObject({ admission: "exclusive" });
206+
expect(claimsByEvent.get(followupEventId)?.commit).toHaveBeenCalledOnce();
207+
expect(claimsByEvent.get(followupEventId)?.release).not.toHaveBeenCalled();
208+
expect(runtime.error).not.toHaveBeenCalled();
209+
} finally {
210+
releaseActiveResolver.resolve();
211+
const turns = [activeTurn, followupTurn].filter(
212+
(turn): turn is Promise<void> => turn !== undefined,
213+
);
214+
await Promise.allSettled(turns);
215+
}
216+
},
217+
);
218+
219+
it.each([
220+
{
221+
name: "adoption commits it",
222+
eventId: "$adopted-followup",
223+
settlement: "onAdopted" as const,
224+
expectedCommits: 1,
225+
expectedReleases: 0,
226+
},
227+
{
228+
name: "abandonment releases it",
229+
eventId: "$abandoned-followup",
230+
settlement: "onAbandoned" as const,
231+
expectedCommits: 0,
232+
expectedReleases: 1,
233+
},
234+
])(
235+
"keeps a deferred replay claim past handler return until $name",
236+
async ({ eventId, settlement, expectedCommits, expectedReleases }) => {
237+
installMatrixMonitorTestRuntime();
238+
const claim = createClaimSpies();
239+
let deferredLifecycle: TurnAdoptionLifecycle | undefined;
240+
const inboundDeduper: NonNullable<MatrixMonitorHandlerParams["inboundDeduper"]> = {
241+
claim: vi.fn(async () => ({
242+
kind: "claimed" as const,
243+
handle: {
244+
keys: [eventId] as const,
245+
commit: claim.commit,
246+
release: claim.release,
247+
},
248+
})),
249+
};
250+
const runWithDeferredOwnership = (async (params: MatrixInboundRunParams) => {
251+
deferredLifecycle = params.turnAdoptionLifecycle;
252+
expect(deferredLifecycle?.onDeferred?.()).not.toBe(false);
253+
return {
254+
admission: { kind: "dispatch" as const },
255+
dispatched: true as const,
256+
ctxPayload: {} as FinalizedMsgContext,
257+
routeSessionKey: "agent:ops:main",
258+
dispatchResult: {
259+
queuedFinal: false,
260+
counts: { final: 0, block: 0, tool: 0 },
261+
},
262+
};
263+
}) as MatrixInboundRun;
264+
const { handler } = createMatrixHandlerTestHarness({
265+
inboundDeduper,
266+
runChannelInboundEvent: runWithDeferredOwnership,
267+
});
268+
269+
await handler(
270+
"!room:example.org",
271+
createMatrixTextMessageEvent({ eventId, body: "wait for the active turn" }),
272+
);
273+
274+
expect(deferredLifecycle).toMatchObject({ admission: "exclusive" });
275+
expect(claim.commit).not.toHaveBeenCalled();
276+
expect(claim.release).not.toHaveBeenCalled();
277+
278+
await deferredLifecycle?.[settlement]?.();
279+
280+
expect(claim.commit).toHaveBeenCalledTimes(expectedCommits);
281+
expect(claim.release).toHaveBeenCalledTimes(expectedReleases);
282+
},
283+
);
284+
});

‎extensions/matrix/src/matrix/monitor/handler.test-helpers.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ type MatrixHandlerTestHarnessOptions = {
106106
};
107107
resolveHumanDelayConfig?: () => undefined;
108108
dispatchInboundMessage?: MatrixDispatchInboundMessage;
109+
runChannelInboundEvent?: MatrixMonitorHandlerParams["core"]["channel"]["inbound"]["run"];
109110
runPrepared?: MatrixRunPreparedMock;
110111
inboundDeduper?: MatrixMonitorHandlerParams["inboundDeduper"];
111112
shouldAckReaction?: () => boolean;
@@ -218,7 +219,7 @@ export function createMatrixHandlerTestHarness(
218219
dispatchResult,
219220
};
220221
});
221-
const run = vi.fn(
222+
const defaultRun = vi.fn(
222223
async (
223224
params: Parameters<MatrixMonitorHandlerParams["core"]["channel"]["inbound"]["run"]>[0],
224225
) => {
@@ -266,6 +267,7 @@ export function createMatrixHandlerTestHarness(
266267
});
267268
},
268269
);
270+
const run = options.runChannelInboundEvent ?? defaultRun;
269271
const dmPolicy = options.dmPolicy ?? "open";
270272
const allowFrom = options.allowFrom ?? (dmPolicy === "open" ? ["*"] : []);
271273
const cfgForHandler =

‎extensions/matrix/src/matrix/monitor/handler.ts‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -155,11 +155,14 @@ export function createMatrixRoomMessageHandler(params: MatrixMonitorHandlerParam
155155
const eventTs = event.origin_server_ts;
156156
const eventAge = event.unsigned?.age;
157157
const commitInboundEventIfClaimed = async () => {
158-
if (!inboundReplayClaim) {
158+
const claim = inboundReplayClaim;
159+
if (!claim) {
159160
return;
160161
}
161-
await inboundReplayClaim.commit();
162-
inboundReplayClaim = undefined;
162+
await claim.commit();
163+
if (inboundReplayClaim === claim) {
164+
inboundReplayClaim = undefined;
165+
}
163166
};
164167
const readIngressPrefix = () =>
165168
readMatrixIngressPrefix({
@@ -450,11 +453,39 @@ export function createMatrixRoomMessageHandler(params: MatrixMonitorHandlerParam
450453
route: _route,
451454
sessionKey: _route.sessionKey,
452455
});
456+
const replayClaimAtDispatch = inboundReplayClaim;
457+
// Active-run deferral outlives this handler. Transfer the exact replay claim to the
458+
// reply lane so adoption commits it and abandonment reopens it for Matrix replay.
459+
const turnAdoptionLifecycle = replayClaimAtDispatch
460+
? {
461+
admission: "exclusive" as const,
462+
onDeferred: () => {
463+
if (inboundReplayClaim !== replayClaimAtDispatch) {
464+
return false;
465+
}
466+
inboundReplayClaim = undefined;
467+
return undefined;
468+
},
469+
onAdopted: async () => {
470+
if (inboundReplayClaim === replayClaimAtDispatch) {
471+
inboundReplayClaim = undefined;
472+
}
473+
await replayClaimAtDispatch.commit();
474+
},
475+
onAbandoned: () => {
476+
if (inboundReplayClaim === replayClaimAtDispatch) {
477+
inboundReplayClaim = undefined;
478+
}
479+
replayClaimAtDispatch.release();
480+
},
481+
}
482+
: undefined;
453483

454484
const turnResult = await core.channel.inbound.run({
455485
channel: "matrix",
456486
accountId: _route.accountId,
457487
raw: event,
488+
...(turnAdoptionLifecycle ? { turnAdoptionLifecycle } : {}),
458489
adapter: {
459490
ingest: () => ({
460491
id: messageId,

‎extensions/matrix/src/matrix/monitor/inbound-dedupe.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Matrix inbound replay protection: /sync replays events after an unclean
22
// shutdown and the decrypt bridge re-emits decrypted events, so each
3-
// (account, room, event) is claimed before handling and committed only after
4-
// reply dispatch succeeds; release on retryable failure reopens the event.
3+
// (account, room, event) is claimed before handling. Durable turn adoption or
4+
// terminal handling commits it; failure or abandonment before adoption releases it.
55
import {
66
createChannelReplayGuard,
77
resolvePersistentDedupePluginStateNamespace,

0 commit comments

Comments
 (0)