Skip to content

Commit a154b4f

Browse files
authored
refactor: consolidate Teams and error helpers (#117907)
1 parent 83c6a51 commit a154b4f

17 files changed

Lines changed: 187 additions & 199 deletions

‎extensions/matrix/src/matrix/delivery-plan.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,17 @@ describe("Matrix durable delivery plans", () => {
202202
);
203203
});
204204

205+
it("preserves the unknown-error fallback for non-error send failures", async () => {
206+
await persist();
207+
client.sendMessage.mockRejectedValueOnce({ code: "M_UNKNOWN" });
208+
209+
await expect(reconcileMatrixUnknownSend(reconciliationContext())).resolves.toMatchObject({
210+
status: "unresolved",
211+
error: "unknown error",
212+
retryable: true,
213+
});
214+
});
215+
205216
it("preserves ordered typed receipt parts and the final event identity", async () => {
206217
const deliveryIdentity = identity("queue-multi-event");
207218
const plannedEvents = createMatrixPlannedEvents({

‎extensions/matrix/src/matrix/delivery-plan.ts‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type {
66
MessageReceipt,
77
MessageReceiptPartKind,
88
} from "openclaw/plugin-sdk/channel-outbound";
9+
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
910
import { getMatrixRuntime } from "../runtime.js";
1011
import type { MatrixClient } from "./sdk.js";
1112
import type { MatrixMessageWireDispatch } from "./sdk/client-base.js";
@@ -383,13 +384,6 @@ function createReconciledMatrixReceipt(params: {
383384
};
384385
}
385386

386-
function describeError(value: unknown): string {
387-
if (value instanceof Error) {
388-
return value.message;
389-
}
390-
return typeof value === "string" ? value : "unknown error";
391-
}
392-
393387
async function requireTransactionScope(client: MatrixClient): Promise<string> {
394388
const scope = (await client.getTransactionScopeId()).trim();
395389
if (!scope) {
@@ -488,13 +482,19 @@ export async function reconcileMatrixUnknownSend(
488482
cleanupError = cleanupFailure;
489483
}
490484
}
491-
const errorMessage = describeError(error);
485+
const errorMessage = formatErrorMessage(
486+
error instanceof Error || typeof error === "string" ? error : "unknown error",
487+
);
492488
return {
493489
status: "unresolved",
494490
error:
495491
cleanupError === undefined
496492
? errorMessage
497-
: `${errorMessage}; Matrix delivery-plan cleanup failed: ${describeError(cleanupError)}`,
493+
: `${errorMessage}; Matrix delivery-plan cleanup failed: ${formatErrorMessage(
494+
cleanupError instanceof Error || typeof cleanupError === "string"
495+
? cleanupError
496+
: "unknown error",
497+
)}`,
498498
retryable,
499499
};
500500
}

‎extensions/msteams/src/attachments/download.ts‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
isDownloadableAttachment,
1919
isRecord,
2020
isUrlAllowed,
21+
isRedirectStatus,
2122
type MSTeamsAttachmentDownloadLogger,
2223
type MSTeamsAttachmentFetchPolicy,
2324
type MSTeamsAttachmentResolveFn,
@@ -130,10 +131,6 @@ function scopeCandidatesForUrl(url: string): string[] {
130131
}
131132
}
132133

133-
function isRedirectStatus(status: number): boolean {
134-
return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
135-
}
136-
137134
async function resolveInlineDataImageMime(inline: {
138135
data: Buffer;
139136
contentType?: string;

‎extensions/msteams/src/attachments/shared.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -626,6 +626,10 @@ async function resolveAndValidateIP(
626626

627627
/** Maximum number of redirects to follow in safeFetch. */
628628
const MAX_SAFE_REDIRECTS = 5;
629+
export function isRedirectStatus(status: number): boolean {
630+
return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
631+
}
632+
629633
/**
630634
* Fetch a URL with redirect: "manual", validating each redirect target
631635
* against the hostname allowlist and optional DNS-resolved IP (anti-SSRF).
@@ -711,7 +715,7 @@ async function safeFetch(params: {
711715
redirect: "manual",
712716
});
713717

714-
if (![301, 302, 303, 307, 308].includes(res.status)) {
718+
if (!isRedirectStatus(res.status)) {
715719
return res;
716720
}
717721

‎extensions/msteams/src/graph-group-management.test.ts‎

Lines changed: 27 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,8 @@ import {
1010
const mockState = vi.hoisted(() => ({
1111
resolveGraphToken: vi.fn(),
1212
fetchGraphJson: vi.fn(),
13-
postGraphJson: vi.fn(),
13+
mutateGraphJson: vi.fn(),
1414
deleteGraphRequest: vi.fn(),
15-
patchGraphJson: vi.fn(),
1615
findPreferredDmByUserId: vi.fn(),
1716
}));
1817

@@ -22,9 +21,8 @@ vi.mock("./graph.js", async (importOriginal) => {
2221
...actual,
2322
resolveGraphToken: mockState.resolveGraphToken,
2423
fetchGraphJson: mockState.fetchGraphJson,
25-
postGraphJson: mockState.postGraphJson,
24+
mutateGraphJson: mockState.mutateGraphJson,
2625
deleteGraphRequest: mockState.deleteGraphRequest,
27-
patchGraphJson: mockState.patchGraphJson,
2826
};
2927
});
3028

@@ -39,7 +37,7 @@ const CHAT_ID = "19:[email protected]";
3937
const CHANNEL_TO = "team-id-1/channel-id-1";
4038

4139
function postGraphBodyAt(index: number): Record<string, unknown> {
42-
const call = mockState.postGraphJson.mock.calls[index];
40+
const call = mockState.mutateGraphJson.mock.calls[index];
4341
if (!call) {
4442
throw new Error(`expected Graph post call ${index}`);
4543
}
@@ -57,7 +55,7 @@ describe("addParticipantMSTeams", () => {
5755
});
5856

5957
it("maps the default chat member role to Graph owner", async () => {
60-
mockState.postGraphJson.mockResolvedValue({});
58+
mockState.mutateGraphJson.mockResolvedValue({});
6159

6260
const result = await addParticipantMSTeams({
6361
cfg: {} as OpenClawConfig,
@@ -66,9 +64,10 @@ describe("addParticipantMSTeams", () => {
6664
});
6765

6866
expect(result).toEqual({ added: { userId: "user-aad-id-1", chatId: CHAT_ID } });
69-
expect(mockState.postGraphJson).toHaveBeenCalledWith({
67+
expect(mockState.mutateGraphJson).toHaveBeenCalledWith({
7068
token: TOKEN,
7169
path: `/chats/${encodeURIComponent(CHAT_ID)}/members`,
70+
method: "POST",
7271
body: {
7372
"@odata.type": "#microsoft.graph.aadUserConversationMember",
7473
roles: ["owner"],
@@ -78,7 +77,7 @@ describe("addParticipantMSTeams", () => {
7877
});
7978

8079
it("adds member to a chat with owner role", async () => {
81-
mockState.postGraphJson.mockResolvedValue({});
80+
mockState.mutateGraphJson.mockResolvedValue({});
8281

8382
const result = await addParticipantMSTeams({
8483
cfg: {} as OpenClawConfig,
@@ -88,9 +87,10 @@ describe("addParticipantMSTeams", () => {
8887
});
8988

9089
expect(result).toEqual({ added: { userId: "user-aad-id-2", chatId: CHAT_ID } });
91-
expect(mockState.postGraphJson).toHaveBeenCalledWith({
90+
expect(mockState.mutateGraphJson).toHaveBeenCalledWith({
9291
token: TOKEN,
9392
path: `/chats/${encodeURIComponent(CHAT_ID)}/members`,
93+
method: "POST",
9494
body: {
9595
"@odata.type": "#microsoft.graph.aadUserConversationMember",
9696
roles: ["owner"],
@@ -100,7 +100,7 @@ describe("addParticipantMSTeams", () => {
100100
});
101101

102102
it("normalizes role casing and whitespace", async () => {
103-
mockState.postGraphJson.mockResolvedValue({});
103+
mockState.mutateGraphJson.mockResolvedValue({});
104104

105105
await addParticipantMSTeams({
106106
cfg: {} as OpenClawConfig,
@@ -109,9 +109,10 @@ describe("addParticipantMSTeams", () => {
109109
role: " OWNER ",
110110
});
111111

112-
expect(mockState.postGraphJson).toHaveBeenCalledWith({
112+
expect(mockState.mutateGraphJson).toHaveBeenCalledWith({
113113
token: TOKEN,
114114
path: `/chats/${encodeURIComponent(CHAT_ID)}/members`,
115+
method: "POST",
115116
body: {
116117
"@odata.type": "#microsoft.graph.aadUserConversationMember",
117118
roles: ["owner"],
@@ -130,11 +131,11 @@ describe("addParticipantMSTeams", () => {
130131
}),
131132
).rejects.toThrow('role must be "member" or "owner"');
132133

133-
expect(mockState.postGraphJson).not.toHaveBeenCalled();
134+
expect(mockState.mutateGraphJson).not.toHaveBeenCalled();
134135
});
135136

136137
it("constructs correct [email protected] URL", async () => {
137-
mockState.postGraphJson.mockResolvedValue({});
138+
mockState.mutateGraphJson.mockResolvedValue({});
138139

139140
await addParticipantMSTeams({
140141
cfg: {} as OpenClawConfig,
@@ -149,7 +150,7 @@ describe("addParticipantMSTeams", () => {
149150
});
150151

151152
it("escapes user ids before building the OData bind URL", async () => {
152-
mockState.postGraphJson.mockResolvedValue({});
153+
mockState.mutateGraphJson.mockResolvedValue({});
153154

154155
await addParticipantMSTeams({
155156
cfg: {} as OpenClawConfig,
@@ -164,7 +165,7 @@ describe("addParticipantMSTeams", () => {
164165
});
165166

166167
it("maps the default channel member role to an empty Graph role list", async () => {
167-
mockState.postGraphJson.mockResolvedValue({});
168+
mockState.mutateGraphJson.mockResolvedValue({});
168169

169170
const result = await addParticipantMSTeams({
170171
cfg: {} as OpenClawConfig,
@@ -173,9 +174,10 @@ describe("addParticipantMSTeams", () => {
173174
});
174175

175176
expect(result).toEqual({ added: { userId: "user-aad-id-3", chatId: CHANNEL_TO } });
176-
expect(mockState.postGraphJson).toHaveBeenCalledWith({
177+
expect(mockState.mutateGraphJson).toHaveBeenCalledWith({
177178
token: TOKEN,
178179
path: "/teams/team-id-1/channels/channel-id-1/members",
180+
method: "POST",
179181
body: {
180182
"@odata.type": "#microsoft.graph.aadUserConversationMember",
181183
roles: [],
@@ -185,7 +187,7 @@ describe("addParticipantMSTeams", () => {
185187
});
186188

187189
it("preserves the owner role for a channel", async () => {
188-
mockState.postGraphJson.mockResolvedValue({});
190+
mockState.mutateGraphJson.mockResolvedValue({});
189191

190192
await addParticipantMSTeams({
191193
cfg: {} as OpenClawConfig,
@@ -194,9 +196,10 @@ describe("addParticipantMSTeams", () => {
194196
role: "owner",
195197
});
196198

197-
expect(mockState.postGraphJson).toHaveBeenCalledWith({
199+
expect(mockState.mutateGraphJson).toHaveBeenCalledWith({
198200
token: TOKEN,
199201
path: "/teams/team-id-1/channels/channel-id-1/members",
202+
method: "POST",
200203
body: {
201204
"@odata.type": "#microsoft.graph.aadUserConversationMember",
202205
roles: ["owner"],
@@ -319,7 +322,7 @@ describe("renameGroupMSTeams", () => {
319322
});
320323

321324
it("renames a chat with topic", async () => {
322-
mockState.patchGraphJson.mockResolvedValue(undefined);
325+
mockState.mutateGraphJson.mockResolvedValue(undefined);
323326

324327
const result = await renameGroupMSTeams({
325328
cfg: {} as OpenClawConfig,
@@ -328,15 +331,16 @@ describe("renameGroupMSTeams", () => {
328331
});
329332

330333
expect(result).toEqual({ renamed: { chatId: CHAT_ID, newName: "New Chat Name" } });
331-
expect(mockState.patchGraphJson).toHaveBeenCalledWith({
334+
expect(mockState.mutateGraphJson).toHaveBeenCalledWith({
332335
token: TOKEN,
333336
path: `/chats/${encodeURIComponent(CHAT_ID)}`,
337+
method: "PATCH",
334338
body: { topic: "New Chat Name" },
335339
});
336340
});
337341

338342
it("renames a channel with displayName", async () => {
339-
mockState.patchGraphJson.mockResolvedValue(undefined);
343+
mockState.mutateGraphJson.mockResolvedValue(undefined);
340344

341345
const result = await renameGroupMSTeams({
342346
cfg: {} as OpenClawConfig,
@@ -345,9 +349,10 @@ describe("renameGroupMSTeams", () => {
345349
});
346350

347351
expect(result).toEqual({ renamed: { chatId: CHANNEL_TO, newName: "New Channel Name" } });
348-
expect(mockState.patchGraphJson).toHaveBeenCalledWith({
352+
expect(mockState.mutateGraphJson).toHaveBeenCalledWith({
349353
token: TOKEN,
350354
path: "/teams/team-id-1/channels/channel-id-1",
355+
method: "PATCH",
351356
body: { displayName: "New Channel Name" },
352357
});
353358
});

‎extensions/msteams/src/graph-group-management.ts‎

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,7 @@
22
import type { OpenClawConfig } from "../runtime-api.js";
33
import { findMSTeamsConversationMember } from "./graph-conversation-members.js";
44
import { resolveConversationPath, resolveGraphConversationId } from "./graph-messages.js";
5-
import {
6-
deleteGraphRequest,
7-
escapeOData,
8-
patchGraphJson,
9-
postGraphJson,
10-
resolveGraphToken,
11-
} from "./graph.js";
5+
import { deleteGraphRequest, escapeOData, mutateGraphJson, resolveGraphToken } from "./graph.js";
126

137
// ---------------------------------------------------------------------------
148
// Add Participant
@@ -67,9 +61,10 @@ export async function addParticipantMSTeams(
6761
"[email protected]": `https://graph.microsoft.com/v1.0/users('${escapeOData(params.userId)}')`,
6862
};
6963

70-
await postGraphJson<unknown>({
64+
await mutateGraphJson<unknown>({
7165
token,
7266
path: `${conv.basePath}/members`,
67+
method: "POST",
7368
body,
7469
});
7570

@@ -142,9 +137,10 @@ export async function renameGroupMSTeams(
142137

143138
const body = conv.kind === "chat" ? { topic: params.name } : { displayName: params.name };
144139

145-
await patchGraphJson<unknown>({
140+
await mutateGraphJson<unknown>({
146141
token,
147142
path: conv.basePath,
143+
method: "PATCH",
148144
body,
149145
});
150146

0 commit comments

Comments
 (0)