Skip to content

Commit 0b0a64e

Browse files
fix(line): a permanently refused message is replayed instead of settling (#131285)
* fix(line): report a provider rejection as a definitive non-dispatch * fix(line): keep a retried push ambiguous unless LINE refused every attempt * fix(line): preserve retryable and ambiguous rejection outcomes * fix(line): retain retry ambiguity through wrappers * fix(line): retain partial delivery evidence * test(line): split outbound delivery outcome coverage * test(line): align delivery recovery import order --------- Co-authored-by: Patrick Erichsen <[email protected]>
1 parent 59dad71 commit 0b0a64e

8 files changed

Lines changed: 361 additions & 110 deletions

‎extensions/line/src/auto-reply-delivery-recovery.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
LINE_TEST_CFG,
1111
type LineAutoReplyDeps,
1212
} from "./auto-reply-delivery.test-helpers.js";
13+
import { runLinePushWithRetries } from "./send-retry.js";
1314

1415
describe("deliverLineAutoReply HTTP recovery", () => {
1516
const createHttpError = (status: number) =>
@@ -315,6 +316,45 @@ describe("deliverLineAutoReply HTTP recovery", () => {
315316
expect(pushMessagesLine).toHaveBeenCalledTimes(1);
316317
});
317318

319+
it("does not recover text after an ambiguous push ends in a rejection", async () => {
320+
vi.useFakeTimers();
321+
let ambiguousFailure: unknown;
322+
try {
323+
let attempt = 0;
324+
const failurePromise = runLinePushWithRetries(async () => {
325+
attempt += 1;
326+
throw attempt === 1
327+
? Object.assign(new Error("socket hang up"), { code: "ECONNRESET" })
328+
: createHttpError(400);
329+
}, "line:push").catch((error: unknown) => error);
330+
await vi.runAllTimersAsync();
331+
ambiguousFailure = await failurePromise;
332+
} finally {
333+
vi.useRealTimers();
334+
}
335+
336+
const lineData = {
337+
flexMessage: { altText: "Card", contents: { type: "bubble" } },
338+
};
339+
const pushMessagesLine = vi.fn(async () => {
340+
throw ambiguousFailure;
341+
});
342+
const { deps } = createDeps({
343+
pushMessagesLine: pushMessagesLine as LineAutoReplyDeps["pushMessagesLine"],
344+
});
345+
346+
await expect(
347+
deliverLineAutoReply({
348+
...baseDeliveryParams,
349+
replyToken: undefined,
350+
payload: { text: "do not duplicate", channelData: { line: lineData } },
351+
lineData,
352+
deps,
353+
}),
354+
).rejects.toBe(ambiguousFailure);
355+
expect(pushMessagesLine).toHaveBeenCalledOnce();
356+
});
357+
318358
it("recovers quick replies from a rejected rich-only push", async () => {
319359
const lineData = {
320360
flexMessage: { altText: "Card", contents: { type: "bubble" } },

‎extensions/line/src/auto-reply-delivery.ts‎

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Line plugin module implements auto reply delivery behavior.
2-
import { HTTPFetchError, type messagingApi } from "@line/bot-sdk";
2+
import type { messagingApi } from "@line/bot-sdk";
33
import { isChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
44
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
55
import {
@@ -16,6 +16,7 @@ import type { FlexContainer } from "./flex-templates/types.js";
1616
import type { ProcessedLineMessage } from "./markdown-to-line.js";
1717
import { hasLineSpecificMediaOptions } from "./outbound-media.js";
1818
import { buildLineQuickReplyFallbackText } from "./quick-reply-fallback.js";
19+
import { findLineHttpError, resolveLineNonDispatchRetryable } from "./send-retry.js";
1920
import type { LineChannelData, LineTemplateMessagePayload } from "./types.js";
2021

2122
type LineAutoReplyDeps = {
@@ -58,14 +59,8 @@ function toLineDeliveryError(error: unknown): Error {
5859
return error instanceof Error ? error : new Error("LINE message send failed", { cause: error });
5960
}
6061

61-
function getLineHttpError(error: unknown): HTTPFetchError | undefined {
62-
return collectErrorGraphCandidates(error, (candidate) => [candidate.cause, candidate.error]).find(
63-
(candidate): candidate is HTTPFetchError => candidate instanceof HTTPFetchError,
64-
);
65-
}
66-
6762
function canFallbackAfterLineReplyFailure(error: unknown): boolean {
68-
const httpError = getLineHttpError(error);
63+
const httpError = findLineHttpError(error);
6964
if (httpError) {
7065
return httpError.status >= 400 && httpError.status < 500 && httpError.status !== 408;
7166
}
@@ -206,7 +201,7 @@ export async function deliverLineAutoReply(params: {
206201
// Only a definitive LINE 400 makes text recovery after a rejected push safe.
207202
await pushLineMessages(
208203
replyBatch,
209-
getLineHttpError(err)?.status === 400,
204+
findLineHttpError(err)?.status === 400,
210205
remaining.slice(replyBatch.length),
211206
);
212207
} finally {
@@ -342,7 +337,7 @@ export async function deliverLineAutoReply(params: {
342337
deliveryError ??= err;
343338
const failedSegment =
344339
typeof err === "object" && err !== null ? failedPushSegments.get(err) : undefined;
345-
const httpError = getLineHttpError(err);
340+
const httpError = findLineHttpError(err);
346341
const retryCandidates = failedSegment
347342
? [
348343
...(failedSegment.allowFailedBatchTextRecovery ? failedSegment.failedBatch : []),
@@ -367,7 +362,8 @@ export async function deliverLineAutoReply(params: {
367362
const canRetryTextOnly =
368363
retryMessages.length > 0 &&
369364
failedSegment?.failedBatch.some((message) => message.type !== "text") &&
370-
httpError?.status === 400;
365+
httpError?.status === 400 &&
366+
resolveLineNonDispatchRetryable(err) !== undefined;
371367
if (canRetryTextOnly) {
372368
// HTTPFetchError 400 is an actual LINE response: that request was rejected
373369
// atomically. Retry its text/actions plus the tail that was never attempted.
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { HTTPFetchError } from "@line/bot-sdk";
2+
import { createChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
3+
import { describe, expect, it } from "vitest";
4+
import type { OpenClawConfig } from "../api.js";
5+
import { createRuntime } from "./channel.sendPayload.test-support.js";
6+
import { lineOutboundAdapter } from "./outbound.js";
7+
import { setLineRuntime } from "./runtime.js";
8+
9+
describe("line outbound delivery outcomes", () => {
10+
it.each([
11+
{ status: 400, retryable: false },
12+
{ status: 429, retryable: true },
13+
])("reports an initial LINE $status as a non-dispatch", async ({ status, retryable }) => {
14+
const { runtime, mocks } = createRuntime();
15+
const rejection = new HTTPFetchError(`${status} - provider rejection`, {
16+
status,
17+
statusText: "provider rejection",
18+
headers: new Headers(),
19+
body: "provider rejection",
20+
});
21+
mocks.pushMessageLine.mockRejectedValueOnce(rejection);
22+
setLineRuntime(runtime);
23+
24+
await expect(
25+
lineOutboundAdapter.sendPayload!({
26+
to: "line:user:U123",
27+
text: "hello",
28+
payload: { text: "hello" },
29+
accountId: "default",
30+
cfg: { channels: { line: {} } } as OpenClawConfig,
31+
}),
32+
).rejects.toMatchObject({
33+
name: "PlatformMessageNotDispatchedError",
34+
retryable,
35+
cause: rejection,
36+
});
37+
});
38+
39+
it("preserves partial delivery evidence with a nested LINE rejection", async () => {
40+
const { runtime, mocks } = createRuntime();
41+
const rejection = new HTTPFetchError("400 - provider rejection", {
42+
status: 400,
43+
statusText: "provider rejection",
44+
headers: new Headers(),
45+
body: "provider rejection",
46+
});
47+
const partial = createChannelPartialDeliveryError(rejection, {
48+
messageIds: ["accepted-first"],
49+
visibleReplySent: true,
50+
});
51+
mocks.pushMessageLine.mockRejectedValueOnce(partial);
52+
setLineRuntime(runtime);
53+
54+
await expect(
55+
lineOutboundAdapter.sendPayload!({
56+
to: "line:user:U123",
57+
text: "hello",
58+
payload: { text: "hello" },
59+
accountId: "default",
60+
cfg: { channels: { line: {} } } as OpenClawConfig,
61+
}),
62+
).rejects.toBe(partial);
63+
});
64+
});
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
import { vi } from "vitest";
2+
import type { OpenClawConfig, PluginRuntime } from "../api.js";
3+
import { createLineSendReceipt } from "./send-receipt.js";
4+
5+
type LineRuntimeMocks = {
6+
pushMessageLine: ReturnType<typeof vi.fn>;
7+
pushMessagesLine: ReturnType<typeof vi.fn>;
8+
pushFlexMessage: ReturnType<typeof vi.fn>;
9+
pushTemplateMessage: ReturnType<typeof vi.fn>;
10+
pushLocationMessage: ReturnType<typeof vi.fn>;
11+
pushTextMessageWithQuickReplies: ReturnType<typeof vi.fn>;
12+
createQuickReplyItems: ReturnType<typeof vi.fn>;
13+
buildTemplateMessageFromPayload: ReturnType<typeof vi.fn>;
14+
sendMessageLine: ReturnType<typeof vi.fn>;
15+
chunkMarkdownText: ReturnType<typeof vi.fn>;
16+
resolveLineAccount: ReturnType<typeof vi.fn>;
17+
resolveTextChunkLimit: ReturnType<typeof vi.fn>;
18+
};
19+
20+
export function lineResult(messageId: string, chatId = "c1") {
21+
return {
22+
messageId,
23+
chatId,
24+
receipt: createLineSendReceipt({ messageId, chatId, kind: "text" }),
25+
};
26+
}
27+
28+
export function createRuntime(): { runtime: PluginRuntime; mocks: LineRuntimeMocks } {
29+
const pushMessageLine = vi.fn(async () => lineResult("m-text"));
30+
const pushMessagesLine = vi.fn(async () => lineResult("m-batch"));
31+
const pushFlexMessage = vi.fn(async () => lineResult("m-flex"));
32+
const pushTemplateMessage = vi.fn(async () => lineResult("m-template"));
33+
const pushLocationMessage = vi.fn(async () => lineResult("m-loc"));
34+
const pushTextMessageWithQuickReplies = vi.fn(async () => lineResult("m-quick"));
35+
const createQuickReplyItems = vi.fn((labels: string[]) => ({ items: labels }));
36+
const buildTemplateMessageFromPayload = vi.fn(() => ({ type: "buttons" }));
37+
const sendMessageLine = vi.fn(async () => lineResult("m-media"));
38+
const chunkMarkdownText = vi.fn((text: string) => [text]);
39+
const resolveTextChunkLimit = vi.fn(() => 123);
40+
const resolveLineAccount = vi.fn(
41+
({ cfg, accountId }: { cfg: OpenClawConfig; accountId?: string }) => {
42+
const resolved = accountId ?? "default";
43+
const lineConfig = (cfg.channels?.line ?? {}) as {
44+
accounts?: Record<string, Record<string, unknown>>;
45+
};
46+
const accountConfig = resolved !== "default" ? (lineConfig.accounts?.[resolved] ?? {}) : {};
47+
return {
48+
accountId: resolved,
49+
config: { ...lineConfig, ...accountConfig },
50+
};
51+
},
52+
);
53+
54+
const runtime = {
55+
channel: {
56+
line: {
57+
pushMessageLine,
58+
pushMessagesLine,
59+
pushFlexMessage,
60+
pushTemplateMessage,
61+
pushLocationMessage,
62+
pushTextMessageWithQuickReplies,
63+
createQuickReplyItems,
64+
buildTemplateMessageFromPayload,
65+
sendMessageLine,
66+
resolveLineAccount,
67+
},
68+
text: {
69+
chunkMarkdownText,
70+
resolveTextChunkLimit,
71+
},
72+
},
73+
} as unknown as PluginRuntime;
74+
75+
return {
76+
runtime,
77+
mocks: {
78+
pushMessageLine,
79+
pushMessagesLine,
80+
pushFlexMessage,
81+
pushTemplateMessage,
82+
pushLocationMessage,
83+
pushTextMessageWithQuickReplies,
84+
createQuickReplyItems,
85+
buildTemplateMessageFromPayload,
86+
sendMessageLine,
87+
chunkMarkdownText,
88+
resolveLineAccount,
89+
resolveTextChunkLimit,
90+
},
91+
};
92+
}

‎extensions/line/src/channel.sendPayload.test.ts‎

Lines changed: 2 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,9 @@ import {
77
} from "openclaw/plugin-sdk/channel-outbound";
88
import { chunkMarkdownText as chunkMarkdownTextForLine } from "openclaw/plugin-sdk/reply-runtime";
99
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
10-
import type { OpenClawConfig, PluginRuntime } from "../api.js";
10+
import type { OpenClawConfig } from "../api.js";
1111
import { linePlugin } from "./channel.js";
12+
import { createRuntime, lineResult } from "./channel.sendPayload.test-support.js";
1213
import { lineConfigAdapter } from "./config-adapter.js";
1314
import { resolveLineGroupRequireMention } from "./group-policy.js";
1415
import { lineOutboundAdapter } from "./outbound.js";
@@ -28,21 +29,6 @@ afterAll(() => {
2829
vi.resetModules();
2930
});
3031

31-
type LineRuntimeMocks = {
32-
pushMessageLine: ReturnType<typeof vi.fn>;
33-
pushMessagesLine: ReturnType<typeof vi.fn>;
34-
pushFlexMessage: ReturnType<typeof vi.fn>;
35-
pushTemplateMessage: ReturnType<typeof vi.fn>;
36-
pushLocationMessage: ReturnType<typeof vi.fn>;
37-
pushTextMessageWithQuickReplies: ReturnType<typeof vi.fn>;
38-
createQuickReplyItems: ReturnType<typeof vi.fn>;
39-
buildTemplateMessageFromPayload: ReturnType<typeof vi.fn>;
40-
sendMessageLine: ReturnType<typeof vi.fn>;
41-
chunkMarkdownText: ReturnType<typeof vi.fn>;
42-
resolveLineAccount: ReturnType<typeof vi.fn>;
43-
resolveTextChunkLimit: ReturnType<typeof vi.fn>;
44-
};
45-
4632
beforeEach(() => {
4733
vi.setSystemTime(1_800_000_000_000);
4834
ssrfMocks.resolvePinnedHostnameWithPolicy.mockReset();
@@ -57,14 +43,6 @@ afterEach(() => {
5743
vi.useRealTimers();
5844
});
5945

60-
function lineResult(messageId: string, chatId = "c1") {
61-
return {
62-
messageId,
63-
chatId,
64-
receipt: createLineSendReceipt({ messageId, chatId, kind: "text" }),
65-
};
66-
}
67-
6846
function createCredentialBearingHttpUrl(): string {
6947
const url = new URL("http://example.com/image.jpg");
7048
url.username = ["line", "user"].join("-");
@@ -73,72 +51,6 @@ function createCredentialBearingHttpUrl(): string {
7351
return url.href;
7452
}
7553

76-
function createRuntime(): { runtime: PluginRuntime; mocks: LineRuntimeMocks } {
77-
const pushMessageLine = vi.fn(async () => lineResult("m-text"));
78-
const pushMessagesLine = vi.fn(async () => lineResult("m-batch"));
79-
const pushFlexMessage = vi.fn(async () => lineResult("m-flex"));
80-
const pushTemplateMessage = vi.fn(async () => lineResult("m-template"));
81-
const pushLocationMessage = vi.fn(async () => lineResult("m-loc"));
82-
const pushTextMessageWithQuickReplies = vi.fn(async () => lineResult("m-quick"));
83-
const createQuickReplyItems = vi.fn((labels: string[]) => ({ items: labels }));
84-
const buildTemplateMessageFromPayload = vi.fn(() => ({ type: "buttons" }));
85-
const sendMessageLine = vi.fn(async () => lineResult("m-media"));
86-
const chunkMarkdownText = vi.fn((text: string) => [text]);
87-
const resolveTextChunkLimit = vi.fn(() => 123);
88-
const resolveLineAccount = vi.fn(
89-
({ cfg, accountId }: { cfg: OpenClawConfig; accountId?: string }) => {
90-
const resolved = accountId ?? "default";
91-
const lineConfig = (cfg.channels?.line ?? {}) as {
92-
accounts?: Record<string, Record<string, unknown>>;
93-
};
94-
const accountConfig = resolved !== "default" ? (lineConfig.accounts?.[resolved] ?? {}) : {};
95-
return {
96-
accountId: resolved,
97-
config: { ...lineConfig, ...accountConfig },
98-
};
99-
},
100-
);
101-
102-
const runtime = {
103-
channel: {
104-
line: {
105-
pushMessageLine,
106-
pushMessagesLine,
107-
pushFlexMessage,
108-
pushTemplateMessage,
109-
pushLocationMessage,
110-
pushTextMessageWithQuickReplies,
111-
createQuickReplyItems,
112-
buildTemplateMessageFromPayload,
113-
sendMessageLine,
114-
resolveLineAccount,
115-
},
116-
text: {
117-
chunkMarkdownText,
118-
resolveTextChunkLimit,
119-
},
120-
},
121-
} as unknown as PluginRuntime;
122-
123-
return {
124-
runtime,
125-
mocks: {
126-
pushMessageLine,
127-
pushMessagesLine,
128-
pushFlexMessage,
129-
pushTemplateMessage,
130-
pushLocationMessage,
131-
pushTextMessageWithQuickReplies,
132-
createQuickReplyItems,
133-
buildTemplateMessageFromPayload,
134-
sendMessageLine,
135-
chunkMarkdownText,
136-
resolveLineAccount,
137-
resolveTextChunkLimit,
138-
},
139-
};
140-
}
141-
14254
describe("line outbound sendPayload", () => {
14355
it.each([
14456
{ name: "without quick replies", quickReplies: [] as string[] },

0 commit comments

Comments
 (0)