feat(ipc): merge consecutive send_message updates into one live message
Repeated send_message progress updates each posted a new Discord message, so a long run left a stack of separate status posts. While the role's previous send_message is still the newest message in the chat, append the new text to it by editing it (rendered like a fresh send). A message from anyone in between, a status verdict, an attachment, or the 2000-char limit starts a new message; a failed edit falls back to sending a new one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -22,6 +22,7 @@ import { sanitizeForOutbound } from '../router.js';
|
||||
import { hasReviewerLease } from '../service-routing.js';
|
||||
import type {
|
||||
DeleteRecentMessagesByContentOptions,
|
||||
EditMessageOptions,
|
||||
SendMessageOptions,
|
||||
SendMessageResult,
|
||||
} from '../types.js';
|
||||
@@ -169,6 +170,19 @@ export interface DiscordChannelOpts {
|
||||
roomBindings: () => Record<string, RegisteredGroup>;
|
||||
}
|
||||
|
||||
function finishDiscordOutboundText(cleanText: string): string {
|
||||
const cleaned = cleanText
|
||||
.replace(/^[ \t]*[•*-][ \t]*$/gm, '') // remove empty bullet lines
|
||||
.replace(/\n{3,}/g, '\n\n') // collapse excessive blank lines
|
||||
.trim()
|
||||
// Convert @username mentions to Discord mention format
|
||||
.replaceAll('@눈쟁이', '<@216851709744513024>');
|
||||
// Markdown escaping already happened in prepareDiscordOutbound (prose
|
||||
// escaped, structured output / fenced code preserved). Here we only
|
||||
// re-sanitize so we don't double-escape the delimiters.
|
||||
return sanitizeForOutbound(cleaned);
|
||||
}
|
||||
|
||||
export class DiscordChannel implements Channel {
|
||||
name = 'discord';
|
||||
|
||||
@@ -419,17 +433,7 @@ export class DiscordChannel implements Channel {
|
||||
);
|
||||
}
|
||||
|
||||
let cleaned = outbound.cleanText
|
||||
.replace(/^[ \t]*[•*-][ \t]*$/gm, '') // remove empty bullet lines
|
||||
.replace(/\n{3,}/g, '\n\n') // collapse excessive blank lines
|
||||
.trim();
|
||||
|
||||
// Convert @username mentions to Discord mention format
|
||||
cleaned = cleaned.replaceAll('@눈쟁이', '<@216851709744513024>');
|
||||
// Markdown escaping already happened in prepareDiscordOutbound (prose
|
||||
// escaped, structured output / fenced code preserved). Here we only
|
||||
// re-sanitize so we don't double-escape the delimiters.
|
||||
cleaned = sanitizeForOutbound(cleaned);
|
||||
let cleaned = finishDiscordOutboundText(outbound.cleanText);
|
||||
|
||||
// Surface rejected attachments in the visible message. The MEDIA:
|
||||
// directive was already stripped from the text, so without this the user
|
||||
@@ -806,14 +810,29 @@ export class DiscordChannel implements Channel {
|
||||
});
|
||||
}
|
||||
|
||||
isLatestMessage(jid: string, messageId: string): boolean {
|
||||
const channel = this.client?.channels.cache.get(jid.replace(/^dc:/, ''));
|
||||
return (
|
||||
!!channel &&
|
||||
'lastMessageId' in channel &&
|
||||
channel.lastMessageId === messageId
|
||||
);
|
||||
}
|
||||
|
||||
async editMessage(
|
||||
jid: string,
|
||||
messageId: string,
|
||||
text: string,
|
||||
rawText: string,
|
||||
options: EditMessageOptions = {},
|
||||
): Promise<void> {
|
||||
if (!this.client) {
|
||||
throw new Error('Discord client not initialized');
|
||||
}
|
||||
const text = options.formatAsOutbound
|
||||
? finishDiscordOutboundText(
|
||||
prepareDiscordOutbound(rawText, undefined).cleanText,
|
||||
)
|
||||
: rawText;
|
||||
try {
|
||||
const channelId = jid.replace(/^dc:/, '');
|
||||
const channel = await this.client.channels.fetch(channelId);
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { _initTestDatabase } from './db.js';
|
||||
|
||||
import {
|
||||
deliverCanonicalOutboundMessage,
|
||||
@@ -238,3 +240,126 @@ describe('deliverIpcOutboundMessage', () => {
|
||||
expect(deliverWorkItem).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('deliverIpcOutboundMessage live message merge', () => {
|
||||
beforeEach(() => {
|
||||
_initTestDatabase();
|
||||
});
|
||||
|
||||
function makeDiscordLikeChannel() {
|
||||
let nextId = 1;
|
||||
let lastMessageId: string | null = null;
|
||||
const sent: { id: string; text: string }[] = [];
|
||||
const edits: { id: string; text: string }[] = [];
|
||||
let failEdits = false;
|
||||
const channel: Channel = {
|
||||
name: 'discord',
|
||||
connect: async () => {},
|
||||
sendMessage: vi.fn(async (_jid: string, text: string) => {
|
||||
const id = `m${nextId++}`;
|
||||
sent.push({ id, text });
|
||||
lastMessageId = id;
|
||||
return { primaryMessageId: id, messageIds: [id], visible: true };
|
||||
}),
|
||||
editMessage: vi.fn(async (_jid: string, id: string, text: string) => {
|
||||
if (failEdits) throw new Error('Unknown Message');
|
||||
edits.push({ id, text });
|
||||
}),
|
||||
isLatestMessage: (_jid: string, id: string) => lastMessageId === id,
|
||||
isConnected: () => true,
|
||||
ownsJid: () => true,
|
||||
disconnect: async () => {},
|
||||
};
|
||||
return {
|
||||
channel,
|
||||
sent,
|
||||
edits,
|
||||
someoneElsePosted: () => {
|
||||
lastMessageId = `other${nextId++}`;
|
||||
},
|
||||
failEdits: () => {
|
||||
failEdits = true;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const send = (jid: string, channel: Channel, text: string, extra = {}) =>
|
||||
deliverIpcOutboundMessage(
|
||||
{ jid, text, senderRole: 'owner', ...extra },
|
||||
{
|
||||
channels: [channel],
|
||||
roomBindings: () => ({ [jid]: makeGroup() }),
|
||||
queue: {},
|
||||
},
|
||||
);
|
||||
|
||||
it('edits consecutive progress updates into one message', async () => {
|
||||
const d = makeDiscordLikeChannel();
|
||||
await send('dc:merge-1', d.channel, '첫 번째 진행 상황');
|
||||
await send('dc:merge-1', d.channel, '두 번째 진행 상황');
|
||||
await send('dc:merge-1', d.channel, '세 번째 진행 상황');
|
||||
|
||||
expect(d.sent).toHaveLength(1);
|
||||
expect(d.edits).toEqual([
|
||||
{ id: 'm1', text: '첫 번째 진행 상황\n\n두 번째 진행 상황' },
|
||||
{
|
||||
id: 'm1',
|
||||
text: '첫 번째 진행 상황\n\n두 번째 진행 상황\n\n세 번째 진행 상황',
|
||||
},
|
||||
]);
|
||||
expect(d.channel.editMessage).toHaveBeenCalledWith(
|
||||
'dc:merge-1',
|
||||
'm1',
|
||||
expect.any(String),
|
||||
{ formatAsOutbound: true },
|
||||
);
|
||||
});
|
||||
|
||||
it('starts a new message once someone else posted after it', async () => {
|
||||
const d = makeDiscordLikeChannel();
|
||||
await send('dc:merge-2', d.channel, '진행 1');
|
||||
d.someoneElsePosted();
|
||||
await send('dc:merge-2', d.channel, '진행 2');
|
||||
await send('dc:merge-2', d.channel, '진행 3');
|
||||
|
||||
expect(d.sent.map((m) => m.text)).toEqual(['진행 1', '진행 2']);
|
||||
expect(d.edits).toEqual([{ id: d.sent[1].id, text: '진행 2\n\n진행 3' }]);
|
||||
});
|
||||
|
||||
it('never merges status verdicts or attachments', async () => {
|
||||
const d = makeDiscordLikeChannel();
|
||||
await send('dc:merge-3', d.channel, '진행 1');
|
||||
await send('dc:merge-3', d.channel, 'TASK_DONE\n완료');
|
||||
await send('dc:merge-3', d.channel, '진행 2');
|
||||
await send('dc:merge-3', d.channel, '스크린샷', {
|
||||
attachments: [{ path: '/tmp/a.png' }],
|
||||
});
|
||||
|
||||
expect(d.sent.map((m) => m.text)).toEqual([
|
||||
'진행 1',
|
||||
'TASK_DONE\n완료',
|
||||
'진행 2',
|
||||
'스크린샷',
|
||||
]);
|
||||
expect(d.edits).toEqual([]);
|
||||
});
|
||||
|
||||
it('starts a new message when the merged text would be too long', async () => {
|
||||
const d = makeDiscordLikeChannel();
|
||||
await send('dc:merge-4', d.channel, 'a'.repeat(1000));
|
||||
await send('dc:merge-4', d.channel, 'b'.repeat(1000));
|
||||
|
||||
expect(d.sent).toHaveLength(2);
|
||||
expect(d.edits).toEqual([]);
|
||||
});
|
||||
|
||||
it('falls back to a new message with only the new text when the edit fails', async () => {
|
||||
const d = makeDiscordLikeChannel();
|
||||
await send('dc:merge-5', d.channel, '진행 1');
|
||||
d.failEdits();
|
||||
const result = await send('dc:merge-5', d.channel, '진행 2');
|
||||
|
||||
expect(result).toBe('delivered');
|
||||
expect(d.sent.map((m) => m.text)).toEqual(['진행 1', '진행 2']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createProducedWorkItem } from './db.js';
|
||||
import { createProducedWorkItem, markWorkItemDelivered } from './db.js';
|
||||
import type { WorkItem } from './db/work-items.js';
|
||||
import { resolveRuntimeAttachmentBaseDirs } from './attachment-base-dirs.js';
|
||||
import { deliverOpenWorkItem } from './message-runtime-delivery.js';
|
||||
@@ -50,6 +50,11 @@ export interface CanonicalOutboundDeliveryArgs {
|
||||
text: string;
|
||||
deliveryRole?: PairedRoomRole;
|
||||
attachments?: OutboundAttachment[];
|
||||
/**
|
||||
* Append to this role's previous message by editing it, as long as that
|
||||
* message is still the newest one in the chat, instead of posting a new one.
|
||||
*/
|
||||
mergeIntoLiveMessage?: boolean;
|
||||
}
|
||||
|
||||
export interface CanonicalOutboundDeliveryDeps {
|
||||
@@ -58,8 +63,23 @@ export interface CanonicalOutboundDeliveryDeps {
|
||||
log?: IpcDeliveryLog;
|
||||
createWorkItem?: typeof createProducedWorkItem;
|
||||
deliverWorkItem?: typeof deliverOpenWorkItem;
|
||||
markDelivered?: typeof markWorkItemDelivered;
|
||||
}
|
||||
|
||||
// Raw-text budget for a merged live message. Discord caps a message at 2000
|
||||
// characters and formatting can add escape characters, so keep headroom.
|
||||
const LIVE_MESSAGE_MAX_LENGTH = 1800;
|
||||
|
||||
interface LiveMessage {
|
||||
messageId: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
// Last mergeable message per chat + delivery role. Repeated send_message
|
||||
// progress updates edit this message instead of stacking new ones; a message
|
||||
// from anyone else in between ends the merge (see Channel.isLatestMessage).
|
||||
const liveMessages = new Map<string, LiveMessage>();
|
||||
|
||||
export type CanonicalOutboundDeliveryResult = 'delivered' | 'queued_retry';
|
||||
|
||||
export type IpcOutboundDeliveryResult =
|
||||
@@ -101,6 +121,24 @@ export async function deliverCanonicalOutboundMessage(
|
||||
'Routed outbound message to canonical work item delivery',
|
||||
);
|
||||
|
||||
const channel = route.channel;
|
||||
const liveKey = `${args.jid}|${args.deliveryRole ?? ''}`;
|
||||
const live = args.mergeIntoLiveMessage ? liveMessages.get(liveKey) : null;
|
||||
liveMessages.delete(liveKey);
|
||||
const mergeable =
|
||||
args.mergeIntoLiveMessage === true &&
|
||||
!args.attachments?.length &&
|
||||
!isTerminalStatusMessage(args.text) &&
|
||||
args.text.length <= LIVE_MESSAGE_MAX_LENGTH;
|
||||
const mergedText =
|
||||
mergeable && live ? `${live.text}\n\n${args.text}` : args.text;
|
||||
const canMerge =
|
||||
mergeable &&
|
||||
!!live &&
|
||||
mergedText.length <= LIVE_MESSAGE_MAX_LENGTH &&
|
||||
!!channel.editMessage &&
|
||||
channel.isLatestMessage?.(args.jid, live.messageId) === true;
|
||||
|
||||
const createWorkItem = deps.createWorkItem ?? createProducedWorkItem;
|
||||
const workItem = createWorkItem({
|
||||
group_folder: group.folder,
|
||||
@@ -113,14 +151,56 @@ export async function deliverCanonicalOutboundMessage(
|
||||
attachments: args.attachments,
|
||||
});
|
||||
|
||||
if (canMerge && live) {
|
||||
try {
|
||||
await channel.editMessage!(args.jid, live.messageId, mergedText, {
|
||||
formatAsOutbound: true,
|
||||
});
|
||||
(deps.markDelivered ?? markWorkItemDelivered)(
|
||||
workItem.id,
|
||||
live.messageId,
|
||||
);
|
||||
liveMessages.set(liveKey, {
|
||||
messageId: live.messageId,
|
||||
text: mergedText,
|
||||
});
|
||||
log.info(
|
||||
{
|
||||
transition: 'outbound:merge-live',
|
||||
chatJid: args.jid,
|
||||
deliveryRole: args.deliveryRole ?? null,
|
||||
messageId: live.messageId,
|
||||
workItemId: workItem.id,
|
||||
},
|
||||
'Appended outbound message to the live message by editing it',
|
||||
);
|
||||
return 'delivered';
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
{
|
||||
chatJid: args.jid,
|
||||
deliveryRole: args.deliveryRole ?? null,
|
||||
messageId: live.messageId,
|
||||
err,
|
||||
},
|
||||
'Failed to edit the live message; sending a new message instead',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const deliverWorkItem = deps.deliverWorkItem ?? deliverOpenWorkItem;
|
||||
const delivered = await deliverWorkItem({
|
||||
channel: route.channel,
|
||||
channel,
|
||||
item: workItem as WorkItem,
|
||||
log,
|
||||
attachmentBaseDirs: resolveRuntimeAttachmentBaseDirs(group),
|
||||
isDuplicateOfLastBotFinal: () => false,
|
||||
openContinuation: () => {},
|
||||
onSentAsNewMessage: (messageId) => {
|
||||
if (mergeable && messageId) {
|
||||
liveMessages.set(liveKey, { messageId, text: args.text });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return delivered ? 'delivered' : 'queued_retry';
|
||||
@@ -169,6 +249,7 @@ export async function deliverIpcOutboundMessage(
|
||||
text: args.text,
|
||||
deliveryRole,
|
||||
attachments: args.attachments,
|
||||
mergeIntoLiveMessage: true,
|
||||
},
|
||||
{
|
||||
channels: deps.channels,
|
||||
|
||||
@@ -32,6 +32,7 @@ export async function deliverOpenWorkItem(args: {
|
||||
replaceMessageId?: string | null;
|
||||
isDuplicateOfLastBotFinal: (chatJid: string, text: string) => boolean;
|
||||
openContinuation: (chatJid: string) => void;
|
||||
onSentAsNewMessage?: (messageId: string | null) => void;
|
||||
}): Promise<boolean> {
|
||||
const replaceMessageId = args.replaceMessageId ?? null;
|
||||
const attachments = args.item.attachments ?? [];
|
||||
@@ -116,6 +117,7 @@ export async function deliverOpenWorkItem(args: {
|
||||
args.item.result_payload,
|
||||
);
|
||||
markWorkItemDelivered(args.item.id, sendResult?.primaryMessageId ?? null);
|
||||
args.onSentAsNewMessage?.(sendResult?.primaryMessageId ?? null);
|
||||
args.openContinuation(args.item.chat_jid);
|
||||
args.log.info(
|
||||
buildDeliveryLogContext(args.channel, args.item, {
|
||||
|
||||
17
src/types.ts
17
src/types.ts
@@ -57,6 +57,14 @@ export interface SendMessageOptions {
|
||||
attachmentBaseDirs?: string[];
|
||||
}
|
||||
|
||||
export interface EditMessageOptions {
|
||||
/**
|
||||
* Render the text exactly like a fresh sendMessage would (markdown
|
||||
* neutralization, link/mention handling) instead of editing it in raw.
|
||||
*/
|
||||
formatAsOutbound?: boolean;
|
||||
}
|
||||
|
||||
export interface SendMessageResult {
|
||||
primaryMessageId: string | null;
|
||||
messageIds: string[];
|
||||
@@ -295,7 +303,14 @@ export interface Channel {
|
||||
// independent of setTyping(false) from message turns.
|
||||
setTypingHold?(jid: string, holdId: string, active: boolean): Promise<void>;
|
||||
// Optional: edit/delete messages (used by status dashboard and tracked progress cleanup).
|
||||
editMessage?(jid: string, messageId: string, text: string): Promise<void>;
|
||||
editMessage?(
|
||||
jid: string,
|
||||
messageId: string,
|
||||
text: string,
|
||||
options?: EditMessageOptions,
|
||||
): Promise<void>;
|
||||
// Optional: whether messageId is still the newest message in the chat.
|
||||
isLatestMessage?(jid: string, messageId: string): boolean;
|
||||
deleteMessage?(jid: string, messageId: string): Promise<void>;
|
||||
deleteRecentMessagesByContent?(
|
||||
jid: string,
|
||||
|
||||
Reference in New Issue
Block a user