|
| 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 | +}); |
0 commit comments