Skip to content

Commit f18d619

Browse files
steipetePeter Steinberger
andauthored
fix(channels): preserve preview and presentation delivery (#116884)
Co-authored-by: Peter Steinberger <[email protected]>
1 parent 50771ab commit f18d619

10 files changed

Lines changed: 409 additions & 70 deletions

File tree

‎extensions/mattermost/src/mattermost/monitor-draft-delivery.test.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,57 @@ describe("deliverMattermostReplyWithDraftPreview", () => {
459459
});
460460
});
461461

462+
it("retries an explicitly unsent TTS supplement through normal delivery", async () => {
463+
const draftStream = createDraftStreamMock();
464+
let deliveryAttempt = 0;
465+
const deliverFinal = vi.fn(async (payload: { text?: string }) => {
466+
deliveryAttempt += 1;
467+
if (deliveryAttempt === 1) {
468+
return {
469+
outcome: "empty" as const,
470+
visibleReplySent: false,
471+
suppression: { reason: "no_visible_result" as const },
472+
};
473+
}
474+
return {
475+
outcome: "text" as const,
476+
messageIds: ["supplement-post-1"],
477+
receipt: createMessageReceiptFromOutboundResults({
478+
results: [{ channel: "mattermost", messageId: "supplement-post-1" }],
479+
kind: "media",
480+
}),
481+
visibleReplySent: true,
482+
content: payload.text ?? "",
483+
};
484+
});
485+
486+
const result = await deliverMattermostReplyWithDraftPreview({
487+
payload: {
488+
mediaUrl: "https://example.com/tts.mp3",
489+
audioAsVoice: true,
490+
spokenText: "Spoken answer",
491+
ttsSupplement: { spokenText: "Spoken answer" },
492+
} as never,
493+
info: { kind: "final" },
494+
kind: "channel",
495+
client: createMattermostClientMock(),
496+
draftStream,
497+
effectiveReplyToId: "thread-root-1",
498+
resolvePreviewFinalText,
499+
previewState: { finalizedViaPreviewPost: false },
500+
logVerboseMessage: vi.fn(),
501+
deliverPayload: deliverFinal,
502+
});
503+
504+
expect(deliverFinal).toHaveBeenCalledTimes(2);
505+
expect(deliverFinal.mock.calls[1]?.[0]).not.toHaveProperty("text");
506+
expect(result).toMatchObject({
507+
messageIds: ["patched", "supplement-post-1"],
508+
visibleReplySent: true,
509+
content: "Spoken answer",
510+
});
511+
});
512+
462513
it("preserves the finalized preview receipt when its supplement fails after sending", async () => {
463514
const draftStream = createDraftStreamMock();
464515
const mediaReceipt = createMessageReceiptFromOutboundResults({

‎extensions/mattermost/src/mattermost/monitor-draft-delivery.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,8 @@ export async function deliverMattermostReplyWithDraftPreview(
161161
resolveFinalizedId: (previewPostId) => finalizedPreviewPost?.id ?? previewPostId,
162162
onPreviewFinalized: (_previewPostId, receipt) => {
163163
params.previewState.finalizedViaPreviewPost = true;
164+
// Supplemental retries must not repost text already committed by the preview edit.
165+
previewFinalTextAlreadyDelivered = true;
164166
previewDeliveryResult = {
165167
outcome: "text",
166168
messageIds: listMessageReceiptPlatformIds(receipt),
@@ -237,6 +239,8 @@ export async function deliverMattermostReplyWithDraftPreview(
237239
confirmedPreviewDelivery,
238240
previewDeliveryResult,
239241
supplementalDeliveryResult,
242+
// Supplemental retries use the normal sender; retain its durable receipt too.
243+
normalDeliveryResult,
240244
]) ?? previewDeliveryResult
241245
);
242246
} catch (error: unknown) {

‎src/channels/message/lifecycle.test.ts‎

Lines changed: 77 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ import {
99
} from "./live.js";
1010
import { createMessageReceiveContext } from "./receive.js";
1111

12+
type LivePreviewMediaPayload = { text?: string; mediaUrl: string };
13+
type LivePreviewMediaEdit = { text?: string };
14+
1215
function requireMockCall(
1316
mock: { mock: { calls: unknown[][] } },
1417
callIndex: number,
@@ -92,9 +95,9 @@ describe("message lifecycle primitives", () => {
9295
const deliverSupplemental = vi.fn(async () => true);
9396

9497
const result = await deliverFinalizableLivePreview<
95-
{ text?: string; mediaUrl: string },
98+
LivePreviewMediaPayload,
9699
string,
97-
{ text?: string }
100+
LivePreviewMediaEdit
98101
>({
99102
kind: "final",
100103
payload: { text: "done", mediaUrl: "file:///tmp/reply.mp3" },
@@ -117,6 +120,78 @@ describe("message lifecycle primitives", () => {
117120
expect(deliverSupplemental).toHaveBeenCalledWith({ mediaUrl: "file:///tmp/reply.mp3" });
118121
});
119122

123+
it("falls back to normal supplemental delivery when its dedicated sender reports no send", async () => {
124+
const deliverNormally = vi.fn(async () => true);
125+
const deliverSupplemental = vi.fn(async () => false);
126+
127+
const result = await deliverFinalizableLivePreview<
128+
LivePreviewMediaPayload,
129+
string,
130+
LivePreviewMediaEdit
131+
>({
132+
kind: "final",
133+
payload: { text: "done", mediaUrl: "file:///tmp/reply.mp3" },
134+
draft: {
135+
flush: vi.fn(async () => undefined),
136+
id: () => "preview-supplement-fallback",
137+
clear: vi.fn(async () => undefined),
138+
},
139+
buildFinalEdit: (payload) => ({ text: payload.text }),
140+
editFinal: vi.fn(async () => undefined),
141+
buildSupplementalPayload: (payload) => ({ mediaUrl: payload.mediaUrl }),
142+
deliverSupplemental,
143+
deliverNormally,
144+
});
145+
146+
expect(result.kind).toBe("preview-finalized");
147+
expect(deliverSupplemental).toHaveBeenCalledWith({ mediaUrl: "file:///tmp/reply.mp3" });
148+
expect(deliverNormally).toHaveBeenCalledWith({ mediaUrl: "file:///tmp/reply.mp3" });
149+
});
150+
151+
it("uses normal delivery when a finalized preview has no supplemental sender", async () => {
152+
const deliverNormally = vi.fn(async () => true);
153+
154+
const result = await deliverFinalizableLivePreview<
155+
LivePreviewMediaPayload,
156+
string,
157+
LivePreviewMediaEdit
158+
>({
159+
kind: "final",
160+
payload: { text: "done", mediaUrl: "file:///tmp/reply.mp3" },
161+
draft: {
162+
flush: vi.fn(async () => undefined),
163+
id: () => "preview-no-supplement-sender",
164+
clear: vi.fn(async () => undefined),
165+
},
166+
buildFinalEdit: (payload) => ({ text: payload.text }),
167+
editFinal: vi.fn(async () => undefined),
168+
buildSupplementalPayload: (payload) => ({ mediaUrl: payload.mediaUrl }),
169+
deliverNormally,
170+
});
171+
172+
expect(result.kind).toBe("preview-finalized");
173+
expect(deliverNormally).toHaveBeenCalledWith({ mediaUrl: "file:///tmp/reply.mp3" });
174+
});
175+
176+
it("surfaces supplemental delivery failure after both sender paths report no send", async () => {
177+
await expect(
178+
deliverFinalizableLivePreview<LivePreviewMediaPayload, string, LivePreviewMediaEdit>({
179+
kind: "final",
180+
payload: { text: "done", mediaUrl: "file:///tmp/reply.mp3" },
181+
draft: {
182+
flush: vi.fn(async () => undefined),
183+
id: () => "preview-supplement-unsent",
184+
clear: vi.fn(async () => undefined),
185+
},
186+
buildFinalEdit: (payload) => ({ text: payload.text }),
187+
editFinal: vi.fn(async () => undefined),
188+
buildSupplementalPayload: (payload) => ({ mediaUrl: payload.mediaUrl }),
189+
deliverSupplemental: vi.fn(async () => false),
190+
deliverNormally: vi.fn(async () => false),
191+
}),
192+
).rejects.toThrow("Live preview supplemental payload was not delivered");
193+
});
194+
120195
it("treats live preview fallback delivery as terminal state", async () => {
121196
const discardPending = vi.fn(async () => undefined);
122197
const clear = vi.fn(async () => undefined);

‎src/channels/message/live.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,14 @@ export async function deliverFinalizableLivePreview<TPayload, TId, TEdit>(params
198198
await params.onPreviewFinalized?.(finalizedId, receipt, liveState);
199199
const supplementalPayload = params.buildSupplementalPayload?.(params.payload);
200200
if (supplementalPayload !== undefined) {
201-
await params.deliverSupplemental?.(supplementalPayload);
201+
const supplementalDelivered = await params.deliverSupplemental?.(supplementalPayload);
202+
if (!params.deliverSupplemental || supplementalDelivered === false) {
203+
// A finalized text preview must not silently acknowledge media that never became visible.
204+
const fallbackDelivered = await params.deliverNormally(supplementalPayload);
205+
if (fallbackDelivered === false) {
206+
throw new Error("Live preview supplemental payload was not delivered");
207+
}
208+
}
202209
}
203210
return { kind: "preview-finalized", liveState };
204211
}

‎src/channels/plugins/outbound/interactive.test.ts‎

Lines changed: 87 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
// Interactive outbound tests cover channel outbound interactive payload construction.
22
import { describe, expect, it } from "vitest";
3-
import { renderMessagePresentationChartFallbackText } from "../../../interactive/payload.js";
3+
import {
4+
renderMessagePresentationChartFallbackText,
5+
renderMessagePresentationFallbackText,
6+
} from "../../../interactive/payload.js";
47
import {
58
adaptMessagePresentationForChannel,
69
applyPresentationActionLimits,
@@ -355,7 +358,7 @@ describe("presentation capability limits", () => {
355358
placeholder: "Enviro",
356359
options: [{ label: "Canary", value: "canary" }],
357360
},
358-
{ type: "context", text: "Environment target:\n- Produc" },
361+
{ type: "context", text: "Environment target:\n- Production cluster" },
359362
],
360363
});
361364
});
@@ -396,8 +399,8 @@ describe("presentation capability limits", () => {
396399
});
397400

398401
expect(presentation.blocks).toEqual([
399-
{ type: "context", text: "Actions:\n- Approve\n- Rollback" },
400-
{ type: "context", text: "Environment:\n- Canary\n- Product" },
402+
{ type: "context", text: "Actions:\n- Approve deployment\n- Rollback deployment" },
403+
{ type: "context", text: "Environment:\n- Canary cluster\n- Production cluster" },
401404
]);
402405
});
403406

@@ -536,7 +539,7 @@ describe("presentation capability limits", () => {
536539
});
537540

538541
expect(presentation.blocks).toEqual([
539-
{ type: "text", text: "Actions:\n- Appr" },
542+
{ type: "text", text: "Actions:\n- Approve" },
540543
{ type: "text", text: "Target:\n- Canary" },
541544
{ type: "text", text: "Muted details" },
542545
]);
@@ -577,6 +580,82 @@ describe("presentation capability limits", () => {
577580
]);
578581
});
579582

583+
it("splits unsupported button fallbacks without losing action labels", () => {
584+
const labels = ["Approve production", "Rollback release", "Show audit trail"];
585+
const maxLength = 24;
586+
const presentation = adaptMessagePresentationForChannel({
587+
presentation: {
588+
blocks: [
589+
{
590+
type: "buttons",
591+
buttons: labels.map((label, index) => ({ label, value: `action-${index}` })),
592+
},
593+
],
594+
},
595+
capabilities: {
596+
buttons: false,
597+
context: false,
598+
limits: {
599+
actions: { maxLabelLength: 4 },
600+
text: { maxLength, encoding: "characters" },
601+
},
602+
},
603+
});
604+
605+
const fallback = presentation.blocks.map((block) => {
606+
expect(block.type).toBe("text");
607+
return block.type === "text" ? block.text : "";
608+
});
609+
expect(fallback.length).toBeGreaterThan(1);
610+
expect(fallback.every((value) => Array.from(value).length <= maxLength)).toBe(true);
611+
expect(fallback.join("")).toBe(`Actions:\n${labels.map((label) => `- ${label}`).join("\n")}`);
612+
expect(renderMessagePresentationFallbackText({ presentation })).toBe(
613+
`Actions:\n${labels.map((label) => `- ${label}`).join("\n")}`,
614+
);
615+
});
616+
617+
it("splits overflow select fallbacks without losing unavailable options", () => {
618+
const maxLength = 18;
619+
const presentation = adaptMessagePresentationForChannel({
620+
presentation: {
621+
blocks: [
622+
{
623+
type: "select",
624+
placeholder: "Deployment target",
625+
options: [
626+
{ label: "Canary", value: "canary" },
627+
{ label: "Production cluster", value: "production" },
628+
{ label: "Rollback environment", value: "rollback" },
629+
],
630+
},
631+
],
632+
},
633+
capabilities: {
634+
limits: {
635+
selects: { maxOptions: 1, maxLabelLength: 4 },
636+
text: { maxLength, encoding: "characters" },
637+
},
638+
},
639+
});
640+
641+
expect(presentation.blocks[0]).toMatchObject({
642+
type: "select",
643+
options: [{ label: "Cana", value: "canary" }],
644+
});
645+
const fallback = presentation.blocks.slice(1).map((block) => {
646+
expect(block.type).toBe("context");
647+
return block.type === "context" ? block.text : "";
648+
});
649+
expect(fallback.length).toBeGreaterThan(1);
650+
expect(fallback.every((value) => Array.from(value).length <= maxLength)).toBe(true);
651+
expect(fallback.join("")).toBe(
652+
"Deployment target:\n- Production cluster\n- Rollback environment",
653+
);
654+
expect(renderMessagePresentationFallbackText({ presentation })).toBe(
655+
"Depl:\n- Cana\n\nDeployment target:\n- Production cluster\n- Rollback environment",
656+
);
657+
});
658+
580659
it("applies advertised text limits to titles, text, context, and generated fallback", () => {
581660
const presentation = adaptMessagePresentationForChannel({
582661
presentation: {
@@ -609,6 +688,9 @@ describe("presentation capability limits", () => {
609688
{ type: "text", text: "hello" },
610689
{ type: "context", text: "abcde" },
611690
{ type: "context", text: "Actio" },
691+
{ type: "context", text: "ns:\n" },
692+
{ type: "context", text: "- Dep" },
693+
{ type: "context", text: "loy" },
612694
],
613695
});
614696
});

0 commit comments

Comments
 (0)