Skip to content

Commit 07b7d64

Browse files
committed
fix(matrix): reconcile durable sends after response loss
1 parent f5a8cb0 commit 07b7d64

31 files changed

Lines changed: 1898 additions & 233 deletions

‎docs/docs_map.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7693,6 +7693,7 @@ Do not edit it by hand; run `pnpm docs:map:gen`.
76937693
- H2: Delivery Evidence
76947694
- H2: Existing outbound adapters
76957695
- H2: Durable sends
7696+
- H3: Automatic unknown-send reconciliation
76967697
- H2: Deferred delivery admission
76977698
- H2: Compatibility dispatch
76987699

‎docs/plugins/sdk-channel-outbound.md‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,37 @@ Use `payloadOutcomes` when a batch mixes sent, suppressed, and failed
201201
payloads. Do not infer hook cancellation from an empty legacy
202202
direct-delivery result.
203203

204+
### Automatic unknown-send reconciliation
205+
206+
Set `message.durableFinal.automaticUnknownSendReconciliation` only when the
207+
plugin can reconcile an ambiguous provider send from persisted, post-policy
208+
state without rerunning modifying hooks or regenerating provider payloads.
209+
Core considers this opt-in after hooks and cancellation, and only for exactly
210+
one accepted prepared payload. Multi-payload batches do not opt in
211+
automatically.
212+
213+
The adapter must also advertise `capabilities.reconcileUnknownSend: true` and
214+
provide `reconcileUnknownSend(...)`. Use `reconcileUnknownSendKinds` to name
215+
the concrete transport branches the plugin can prove, such as `text` or
216+
`media`. If the kind map is present, the selected branch must be `true`.
217+
Omitting the map means the callback claims every selected branch, so prefer an
218+
explicit map for new plugins.
219+
220+
The callback must use provider-owned idempotency or authoritative readback to
221+
return `sent` with the actual provider receipt, `not_sent` only when a fresh
222+
send is provably safe, or `unresolved` when neither outcome can be proven.
223+
When reconciliation is explicitly required, unsupported prepared shapes fail
224+
before provider I/O. During recovery, missing, incomplete, or mismatched
225+
provider proof must fail closed rather than replaying content that could
226+
already be visible.
227+
228+
If reconciliation needs provider-owned persisted evidence, implement
229+
`afterUnknownSendTerminal(...)`. Core calls it after the ambiguous queue row
230+
has authoritatively moved to failed, including retry-budget exhaustion. Use it
231+
to remove provider-owned plans or payloads that are no longer needed. Cleanup
232+
is best effort and must be idempotent; a failure is logged without making the
233+
terminal queue row replayable again.
234+
204235
## Deferred delivery admission
205236

206237
Use `message.durableFinal.admitDeferredDelivery(...)` when a resolved account

‎extensions/matrix/src/actions.ts‎

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -117,17 +117,22 @@ function buildMatrixProfileToolSchema(): NonNullable<ChannelMessageToolDiscovery
117117
};
118118
}
119119

120+
function resolveMatrixActionAccount(params: { cfg: CoreConfig; accountId?: string | null }) {
121+
if (!params.accountId && requiresExplicitMatrixDefaultAccount(params.cfg)) {
122+
return null;
123+
}
124+
const account = resolveMatrixAccount({
125+
cfg: params.cfg,
126+
accountId: params.accountId ?? resolveDefaultMatrixAccountId(params.cfg),
127+
});
128+
return account.enabled && account.configured ? account : null;
129+
}
130+
120131
export const matrixMessageActions: ChannelMessageActionAdapter = {
121132
describeMessageTool: ({ cfg, accountId, senderIsOwner }) => {
122133
const resolvedCfg = cfg as CoreConfig;
123-
if (!accountId && requiresExplicitMatrixDefaultAccount(resolvedCfg)) {
124-
return { actions: [], capabilities: [] };
125-
}
126-
const account = resolveMatrixAccount({
127-
cfg: resolvedCfg,
128-
accountId: accountId ?? resolveDefaultMatrixAccountId(resolvedCfg),
129-
});
130-
if (!account.enabled || !account.configured) {
134+
const account = resolveMatrixActionAccount({ cfg: resolvedCfg, accountId });
135+
if (!account) {
131136
return { actions: [], capabilities: [] };
132137
}
133138
const gate = createActionGate(account.config.actions);
@@ -150,6 +155,16 @@ export const matrixMessageActions: ChannelMessageActionAdapter = {
150155
extractToolSend: ({ args }) => {
151156
return extractToolSend(args, "sendMessage");
152157
},
158+
prepareSendPayload: ({ ctx, payload }) => {
159+
if (ctx.action !== "send") {
160+
return null;
161+
}
162+
const account = resolveMatrixActionAccount({
163+
cfg: ctx.cfg as CoreConfig,
164+
accountId: ctx.accountId,
165+
});
166+
return account && createActionGate(account.config.actions)("messages") ? payload : null;
167+
},
153168
handleAction: async (ctx: ChannelMessageActionContext) => {
154169
const { handleMatrixAction } = await import("./tool-actions.runtime.js");
155170
const { action, params, cfg, accountId, mediaLocalRoots } = ctx;
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import { createChannelMessageAdapterFromOutbound } from "openclaw/plugin-sdk/channel-outbound";
2+
import type { ChannelOutboundAdapter } from "openclaw/plugin-sdk/channel-send-result";
3+
import type { matrixChannelRuntime } from "./channel.runtime.js";
4+
5+
export function createMatrixMessageAdapter(params: {
6+
outbound: ChannelOutboundAdapter;
7+
getRuntime: () => Promise<typeof matrixChannelRuntime>;
8+
}) {
9+
const base = createChannelMessageAdapterFromOutbound({
10+
id: "matrix",
11+
outbound: params.outbound,
12+
live: {
13+
capabilities: {
14+
draftPreview: true,
15+
previewFinalization: true,
16+
progressUpdates: true,
17+
quietFinalization: true,
18+
},
19+
finalizer: {
20+
capabilities: {
21+
finalEdit: true,
22+
normalFallback: true,
23+
discardPending: true,
24+
previewReceipt: true,
25+
},
26+
},
27+
},
28+
});
29+
30+
return {
31+
...base,
32+
durableFinal: {
33+
...base.durableFinal,
34+
automaticUnknownSendReconciliation: true,
35+
capabilities: {
36+
...base.durableFinal?.capabilities,
37+
afterCommit: true,
38+
reconcileUnknownSend: true,
39+
},
40+
reconcileUnknownSendKinds: { text: true, media: true },
41+
reconcileUnknownSend: async (ctx) =>
42+
await (await params.getRuntime()).reconcileMatrixUnknownSend(ctx),
43+
afterUnknownSendTerminal: async (ctx) =>
44+
await (await params.getRuntime()).cleanupMatrixDeliveryPlans({ queueId: ctx.queueId }),
45+
},
46+
send: {
47+
...base.send,
48+
lifecycle: {
49+
afterCommit: async (ctx) => {
50+
if (!ctx.deliveryQueueId) {
51+
return;
52+
}
53+
await (
54+
await params.getRuntime()
55+
).cleanupMatrixDeliveryPlans({
56+
queueId: ctx.deliveryQueueId,
57+
});
58+
},
59+
},
60+
},
61+
} satisfies typeof base;
62+
}

‎extensions/matrix/src/channel.message-adapter.test.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ vi.mock("./matrix/send.js", () => ({
2121
}));
2222

2323
vi.mock("./runtime.js", () => ({
24+
getOptionalMatrixRuntime: () => undefined,
2425
getMatrixRuntime: () => ({
2526
channel: {
2627
text: {
@@ -35,6 +36,8 @@ import { matrixPlugin } from "./channel.js";
3536
const cfg = {
3637
channels: {
3738
matrix: {
39+
homeserver: "https://matrix.example.org",
40+
userId: "@bot:example.org",
3841
accessToken: "resolved-token",
3942
},
4043
},
@@ -68,6 +71,58 @@ describe("matrix channel message adapter", () => {
6871
expect(matrixPlugin.meta.markdownCapable).toBe(true);
6972
});
7073

74+
it("opts ordinary durable text and media sends into Matrix reconciliation", () => {
75+
expect(matrixPlugin.message?.durableFinal).toMatchObject({
76+
automaticUnknownSendReconciliation: true,
77+
capabilities: {
78+
text: true,
79+
media: true,
80+
afterCommit: true,
81+
reconcileUnknownSend: true,
82+
},
83+
reconcileUnknownSendKinds: { text: true, media: true },
84+
});
85+
expect(matrixPlugin.message?.durableFinal?.capabilities?.payload).not.toBe(true);
86+
expect(matrixPlugin.message?.durableFinal?.capabilities?.batch).not.toBe(true);
87+
});
88+
89+
it("forwards the exact durable part topology into Matrix sends", async () => {
90+
const sendText = matrixPlugin.message?.send?.text;
91+
if (!sendText) {
92+
throw new Error("Expected Matrix message adapter text sender");
93+
}
94+
await sendText({
95+
cfg,
96+
to: "room:!room:example",
97+
text: "durable",
98+
accountId: "default",
99+
deliveryQueueId: "queue-1",
100+
deliveryPartIndex: 2,
101+
deliveryPartCount: 3,
102+
});
103+
104+
expect(lastMatrixSendOptions()).toMatchObject({
105+
deliveryQueueId: "queue-1",
106+
deliveryPartIndex: 2,
107+
deliveryPartCount: 3,
108+
});
109+
});
110+
111+
it("routes the standard Matrix send action through canonical durable delivery", async () => {
112+
const prepareSendPayload = matrixPlugin.actions?.prepareSendPayload;
113+
if (!prepareSendPayload) {
114+
throw new Error("Expected Matrix prepared-send adapter");
115+
}
116+
const payload = { text: "durable tool send" };
117+
118+
expect(prepareSendPayload({ ctx: { action: "send", cfg } as never, payload } as never)).toBe(
119+
payload,
120+
);
121+
expect(
122+
prepareSendPayload({ ctx: { action: "edit", cfg } as never, payload } as never),
123+
).toBeNull();
124+
});
125+
71126
it.each([
72127
{
73128
name: "the current room with reply quoting disabled",
@@ -224,6 +279,13 @@ describe("matrix channel message adapter", () => {
224279
messageSendingHooks: () => {
225280
expect(adapter.send?.text).toBeTypeOf("function");
226281
},
282+
afterCommit: () => {
283+
expect(adapter.send?.lifecycle?.afterCommit).toBeTypeOf("function");
284+
},
285+
reconcileUnknownSend: () => {
286+
expect(adapter.durableFinal?.reconcileUnknownSend).toBeTypeOf("function");
287+
expect(adapter.durableFinal?.afterUnknownSendTerminal).toBeTypeOf("function");
288+
},
227289
},
228290
});
229291
});
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,21 @@
11
// Matrix plugin module implements channel behavior.
22
import { listMatrixDirectoryGroupsLive, listMatrixDirectoryPeersLive } from "./directory-live.js";
33
import { resolveMatrixAuth } from "./matrix/client.js";
4+
import { cleanupMatrixDeliveryPlans, reconcileMatrixUnknownSend } from "./matrix/delivery-plan.js";
45
import { probeMatrix } from "./matrix/probe.js";
56
import { sendMessageMatrix, sendTypingMatrix } from "./matrix/send.js";
67
import { matrixOutbound } from "./outbound.js";
78
import { resolveMatrixTargets } from "./resolve-targets.js";
89

910
export const matrixChannelRuntime = {
11+
cleanupMatrixDeliveryPlans,
1012
listMatrixDirectoryGroupsLive,
1113
listMatrixDirectoryPeersLive,
1214
matrixOutbound,
1315
probeMatrix,
1416
resolveMatrixAuth,
1517
resolveMatrixTargets,
18+
reconcileMatrixUnknownSend,
1619
sendMessageMatrix,
1720
sendTypingMatrix,
1821
};

‎extensions/matrix/src/channel.ts‎

Lines changed: 6 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,7 @@ import type {
88
ChannelThreadingToolContext,
99
} from "openclaw/plugin-sdk/channel-contract";
1010
import { createChatChannelPlugin, type ChannelPlugin } from "openclaw/plugin-sdk/channel-core";
11-
import {
12-
createChannelMessageAdapterFromOutbound,
13-
createRuntimeOutboundDelegates,
14-
} from "openclaw/plugin-sdk/channel-outbound";
11+
import { createRuntimeOutboundDelegates } from "openclaw/plugin-sdk/channel-outbound";
1512
import {
1613
createAllowlistProviderOpenWarningCollector,
1714
projectAccountConfigWarningCollector,
@@ -44,6 +41,7 @@ import {
4441
import { matrixMessageActions } from "./actions.js";
4542
import { matrixApprovalCapability } from "./approval-native.js";
4643
import { createMatrixPairingText, createMatrixProbeAccount } from "./channel-account-paths.js";
44+
import { createMatrixMessageAdapter } from "./channel-message-adapter.js";
4745
import { matrixPluginBase } from "./channel.setup.js";
4846
import { DEFAULT_ACCOUNT_ID } from "./config-adapter.js";
4947
import {
@@ -346,6 +344,8 @@ const matrixChannelOutbound: ChannelOutboundAdapter = {
346344
replyTo: true,
347345
thread: true,
348346
messageSendingHooks: true,
347+
afterCommit: true,
348+
reconcileUnknownSend: true,
349349
},
350350
},
351351
presentationCapabilities: {
@@ -392,25 +392,9 @@ const matrixChannelOutbound: ChannelOutboundAdapter = {
392392
}),
393393
};
394394

395-
const matrixMessageAdapter = createChannelMessageAdapterFromOutbound({
396-
id: "matrix",
395+
const matrixMessageAdapter = createMatrixMessageAdapter({
397396
outbound: matrixChannelOutbound,
398-
live: {
399-
capabilities: {
400-
draftPreview: true,
401-
previewFinalization: true,
402-
progressUpdates: true,
403-
quietFinalization: true,
404-
},
405-
finalizer: {
406-
capabilities: {
407-
finalEdit: true,
408-
normalFallback: true,
409-
discardPending: true,
410-
previewReceipt: true,
411-
},
412-
},
413-
},
397+
getRuntime: loadMatrixChannelRuntime,
414398
});
415399

416400
export const matrixPlugin: ChannelPlugin<ResolvedMatrixAccount, MatrixProbe> =

0 commit comments

Comments
 (0)