feat(discord): process edited user messages like new messages

Discord edits were dropped: only MessageCreate was handled, and re-storing
the same message id keeps its old seq, so the seq-based loop never re-reads
it. Handle MessageUpdate for cached human messages whose text changed and
store the edit as a new message (`<id>:edit:<editedAt ms>`, new seq) with a
"[메시지 수정됨] 원문/수정" prefix. It then follows the normal new-message
path (batched if pending, preempts a running turn, new request afterwards).
Bot edits, embed/link-preview updates (same text), uncached/partial
messages, unregistered rooms and outbound-only bots are ignored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Codex
2026-11-10 13:42:55 +09:00
parent c6afd7ccb8
commit 5c5942ae21
2 changed files with 196 additions and 0 deletions

View File

@@ -58,6 +58,7 @@ const loginShouldRejectRef = vi.hoisted(() => ({ value: false }));
vi.mock('discord.js', () => {
const Events = {
MessageCreate: 'messageCreate',
MessageUpdate: 'messageUpdate',
ClientReady: 'ready',
Error: 'error',
};
@@ -231,6 +232,25 @@ async function triggerMessage(message: any) {
for (const h of handlers) await h(message);
}
async function triggerMessageUpdate(oldMessage: any, newMessage: any) {
const handlers = currentClient().eventHandlers.get('messageUpdate') || [];
for (const h of handlers) await h(oldMessage, newMessage);
}
function createEditPair(
before: string,
after: string,
overrides: Parameters<typeof createMessage>[0] = {},
) {
const editedAt = new Date('2024-01-01T00:05:00.000Z');
const oldMessage = { ...createMessage({ ...overrides, content: before }) };
const newMessage = {
...createMessage({ ...overrides, content: after }),
editedAt,
};
return { oldMessage, newMessage, editedAt };
}
// --- Tests ---
beforeEach(() => {
@@ -1309,3 +1329,116 @@ describe('channel properties', () => {
expect(metadata.get('dc:222')?.name).toBe('second-chat');
});
});
// --- Message edits ---
describe('message edit handling', () => {
it('delivers a human edit as a new message with the original and edited text', async () => {
const opts = createTestOpts();
const channel = new DiscordChannel('test-token', opts);
await channel.connect();
const { oldMessage, newMessage, editedAt } = createEditPair(
'오늘 날씨 알려줘',
'내일 날씨 알려줘',
{ messageId: 'msg_042', memberDisplayName: '승한' },
);
await triggerMessageUpdate(oldMessage, newMessage);
expect(opts.onMessage).toHaveBeenCalledTimes(1);
expect(opts.onMessage).toHaveBeenCalledWith('dc:1234567890123456', {
id: `msg_042:edit:${editedAt.getTime()}`,
chat_jid: 'dc:1234567890123456',
sender: '55512345',
sender_name: '승한',
content:
'[메시지 수정됨] 사용자가 이전 메시지를 수정했습니다.\n원문: 오늘 날씨 알려줘\n수정: 내일 날씨 알려줘',
timestamp: editedAt.toISOString(),
is_from_me: false,
is_bot_message: false,
});
});
it('gives each successive edit of one message its own id', async () => {
const opts = createTestOpts();
const channel = new DiscordChannel('test-token', opts);
await channel.connect();
const first = createEditPair('a', 'b');
await triggerMessageUpdate(first.oldMessage, first.newMessage);
const second = createEditPair('b', 'c');
second.newMessage.editedAt = new Date('2024-01-01T00:06:00.000Z');
await triggerMessageUpdate(second.oldMessage, second.newMessage);
const ids = vi.mocked(opts.onMessage).mock.calls.map(([, msg]) => msg.id);
expect(ids).toHaveLength(2);
expect(new Set(ids).size).toBe(2);
});
it('ignores updates whose text did not change (link preview / embed)', async () => {
const opts = createTestOpts();
const channel = new DiscordChannel('test-token', opts);
await channel.connect();
const { oldMessage, newMessage } = createEditPair(
'https://example.com',
'https://example.com',
);
await triggerMessageUpdate(oldMessage, newMessage);
expect(opts.onMessage).not.toHaveBeenCalled();
});
it('ignores edits by bots, including its own messages', async () => {
const opts = createTestOpts();
const channel = new DiscordChannel('test-token', opts);
await channel.connect();
const own = createEditPair('진행 중', '완료', {
authorId: '999888777',
isBot: true,
});
await triggerMessageUpdate(own.oldMessage, own.newMessage);
hasReviewerLeaseMock.mockReturnValue(true);
const other = createEditPair('a', 'b', { authorId: '111', isBot: true });
await triggerMessageUpdate(other.oldMessage, other.newMessage);
expect(opts.onMessage).not.toHaveBeenCalled();
});
it('ignores uncached (partial) messages and unregistered channels', async () => {
const opts = createTestOpts();
const channel = new DiscordChannel('test-token', opts);
await channel.connect();
const partial = createEditPair('a', 'b');
await triggerMessageUpdate(
{ ...partial.oldMessage, partial: true, content: null },
partial.newMessage,
);
const unregistered = createEditPair('a', 'b', { channelId: '999' });
await triggerMessageUpdate(
unregistered.oldMessage,
unregistered.newMessage,
);
expect(opts.onMessage).not.toHaveBeenCalled();
});
it('does not deliver edits on outbound-only bots', async () => {
const opts = createTestOpts();
const channel = new DiscordChannel(
'test-token',
opts,
undefined,
'discord-review',
false,
);
await channel.connect();
const { oldMessage, newMessage } = createEditPair('a', 'b');
await triggerMessageUpdate(oldMessage, newMessage);
expect(opts.onMessage).not.toHaveBeenCalled();
});
});

View File

@@ -8,6 +8,7 @@ import {
GatewayIntentBits,
Message,
MessageFlags,
PartialMessage,
TextChannel,
} from 'discord.js';
@@ -170,6 +171,16 @@ export interface DiscordChannelOpts {
roomBindings: () => Record<string, RegisteredGroup>;
}
// An edited message is stored as a new message (own id, new seq) so it is
// processed exactly like a freshly sent one; the prefix tells the agent it
// replaces an earlier message rather than being a new request.
export function formatEditedMessageContent(
before: string,
after: string,
): string {
return `[메시지 수정됨] 사용자가 이전 메시지를 수정했습니다.\n원문: ${before || '(내용 없음)'}\n수정: ${after}`;
}
function finishDiscordOutboundText(cleanText: string): string {
const cleaned = cleanText
.replace(/^[ \t]*[•*-][ \t]*$/gm, '') // remove empty bullet lines
@@ -237,6 +248,10 @@ export class DiscordChannel implements Channel {
await this.handleMessageCreate(message);
});
this.client.on(Events.MessageUpdate, async (oldMessage, newMessage) => {
await this.handleMessageUpdate(oldMessage, newMessage);
});
// Handle errors gracefully
this.client.on(Events.Error, (err) => {
logger.error({ err: err.message }, 'Discord client error');
@@ -389,6 +404,54 @@ export class DiscordChannel implements Channel {
);
}
private async handleMessageUpdate(
oldMessage: Message | PartialMessage,
newMessage: Message | PartialMessage,
): Promise<void> {
if (!this.receivesInbound) return;
// Partial = not in the cache (e.g. sent before the bot started): the
// original text is unknown, so skip it.
if (oldMessage.partial || newMessage.partial) return;
// Human edits only: own/other bot edits (streaming progress, reviewer bot)
// are not user input.
if (newMessage.author.bot) return;
const before = oldMessage.content;
const after = newMessage.content;
// Same text = embed/link-preview update, not a user edit.
if (before === after) return;
const chatJid = `dc:${newMessage.channelId}`;
const group = this.opts.roomBindings()[chatJid];
if (!group) return;
if (
this.agentTypeFilter &&
(group.agentType || 'claude-code') !== this.agentTypeFilter
) {
return;
}
const editedAt = newMessage.editedAt ?? new Date();
const senderName =
newMessage.member?.displayName ||
newMessage.author.displayName ||
newMessage.author.username;
this.opts.onMessage(chatJid, {
id: `${newMessage.id}:edit:${editedAt.getTime()}`,
chat_jid: chatJid,
sender: newMessage.author.id,
sender_name: senderName,
content: formatEditedMessageContent(before, after),
timestamp: editedAt.toISOString(),
is_from_me: false,
is_bot_message: false,
});
logger.info(
{ chatJid, sender: senderName, messageId: newMessage.id },
'Discord message edit stored',
);
}
async sendMessage(
jid: string,
text: string,