Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 113 additions & 10 deletions packages/channels/dws/src/dws-channel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1101,6 +1101,32 @@ describe('DwsChannel', () => {
]);
});

it('lets polling recover a stale replayed direct message', async () => {
const client = new FakeDwsClient();
const channel = await readyChannel(client);
const replay = message(
'user_im_message_receive_o2o_all',
'replayed-direct',
'stale direct request',
{ eventTime: Date.now() - 60_000 },
);
client.directMessages = [replay];

await client.emit(1, replay);
await channel.poll();

expect(channel.inbound).toEqual([
expect.objectContaining({
chatId: 'cid-1',
messageId: 'replayed-direct',
text: 'stale direct request',
}),
]);

await channel.poll();
expect(channel.inbound).toHaveLength(1);
});

// R4-4: the pullback above only rescues the replay if the poll that was in
// flight when it happened does not finish by writing its own window's end
// back over it. `checkpoint.endTime` is always past the replay's `eventTime`,
Expand Down Expand Up @@ -1711,6 +1737,53 @@ describe('DwsChannel', () => {
]);
});

it('dispatches an ordinary direct message when the event stream misses it', async () => {
const client = new FakeDwsClient();
const channel = await readyChannel(client);
client.directMessages = [
message(
'user_im_message_receive_o2o_all',
'history-direct',
'recover this request',
),
];

await channel.poll();

expect(channel.inbound).toEqual([
expect.objectContaining({
chatId: 'cid-1',
messageId: 'history-direct',
text: 'recover this request',
isGroup: false,
}),
]);
});

it('applies sender pairing to a direct message recovered from history', async () => {
const client = new FakeDwsClient();
const { channel, bridge } = await readyPolicyChannel(
client,
makeConfig({ senderPolicy: 'pairing' }),
);
client.directMessages = [
message(
'user_im_message_receive_o2o_all',
'history-pairing',
'please help',
),
];

await channel.poll();

expect(bridge.prompt).not.toHaveBeenCalled();
expect(client.sendImMessage).toHaveBeenCalledWith(
{ kind: 'direct', openDingTalkId: 'open-alice' },
expect.stringContaining('pairing code'),
expect.any(String),
);
});

it('dispatches a group mention when the event stream misses it', async () => {
const client = new FakeDwsClient();
const channel = await readyChannel(client);
Expand Down Expand Up @@ -2826,7 +2899,7 @@ describe('DwsChannel', () => {
);

expect(bridge.prompt).toHaveBeenCalledOnce();
expect(client.replyToImMessage).toHaveBeenCalledOnce();
expect(client.sendImMessage).toHaveBeenCalledOnce();
});

it('removes a working reaction that finishes attaching after the task', async () => {
Expand Down Expand Up @@ -3739,10 +3812,9 @@ describe('DwsChannel', () => {
expect(channel.inboundAttempts).toBe(5);
});

// R12-1: a plain direct message whose turn throws had no redelivery path —
// the at-most-once event stream already consumed it, the DM history loop
// dispatches only document-mention notifications, and the pending queue
// parked only group sources. One transient failure lost it forever.
// R12-1: keep a local redelivery path when a direct-message turn throws.
// The event stream is at most once and remote history can be unavailable,
// so one transient failure must not lose the message forever.
it('replays a failed direct message on the next poll', async () => {
const client = new FakeDwsClient();
const channel = await readyChannel(client);
Expand Down Expand Up @@ -4055,23 +4127,54 @@ describe('DwsChannel', () => {
]);
});

it('uses the originating message for an idempotent final reply', async () => {
it('sends an idempotent ordinary message for a final direct response', async () => {
const client = new FakeDwsClient();
const channel = await readyChannel(client);
await client.emit(
1,
message('user_im_message_receive_o2o_all', 'message-1', 'hello'),
);
channel.responseMessageId = 'message-1';
channel.responseSenderId = 'open-alice';

await channel.respond('cid-1', 'final answer');
const firstKey = client.sendImMessage.mock.calls[0]?.[2];
await channel.respond('cid-1', 'final answer');

expect(client.replyToImMessage).toHaveBeenCalledWith(
'cid-1',
'message-1',
'open-alice',
expect(client.sendImMessage).toHaveBeenNthCalledWith(
1,
{ kind: 'direct', openDingTalkId: 'open-alice' },
'final answer',
expect.stringMatching(
/^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-8[0-9a-f]{3}-[0-9a-f]{12}$/,
),
);
expect(client.sendImMessage.mock.calls[1]?.[2]).toBe(firstKey);
expect(client.replyToImMessage).not.toHaveBeenCalled();
});

it('uses the originating message for a final group reply', async () => {
const client = new FakeDwsClient();
const channel = await readyChannel(client);
await client.emit(
0,
message('user_im_message_receive_at', 'message-1', '@Qwen hello', {
conversationId: 'group-1',
}),
);
channel.responseMessageId = 'message-1';
channel.responseSenderId = 'open-alice';

await channel.respond('group-1', 'final answer');

expect(client.replyToImMessage).toHaveBeenCalledWith(
'group-1',
'message-1',
'open-alice',
'final answer',
expect.any(String),
);
expect(client.sendImMessage).not.toHaveBeenCalled();
});

// R1-7: the unknown-outcome swallow decides whether a finished task is
Expand Down
31 changes: 20 additions & 11 deletions packages/channels/dws/src/dws-channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1044,12 +1044,19 @@ export class DwsChannel extends PollingChannelBase<DwsCursor> {
await this.sendMessage(chatId, text);
return;
}
const idempotencyKey = stableUuid(
`${this.name}\0${chatId}\0${messageId}\0${text}`,
);
if (this.findImTarget(chatId)?.kind === 'direct') {
await this.sendImText(chatId, text, idempotencyKey);
return;
}
await this.client.replyToImMessage(
chatId,
messageId,
senderId,
text,
stableUuid(`${this.name}\0${chatId}\0${messageId}\0${text}`),
idempotencyKey,
);
}

Expand Down Expand Up @@ -1130,11 +1137,14 @@ export class DwsChannel extends PollingChannelBase<DwsCursor> {
continue;
}
const notification = parseDocumentMentionNotification(message.content);
if (!notification) continue;
await this.processDocumentNotification(message, key, notification);
if (notification) {
await this.processDocumentNotification(message, key, notification);
} else {
await this.handleImMessage({ kind: 'direct' }, message, true);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deferred to the follow-up queue (recorded in this round's deferred findings so it survives merge). Verified on this commit: there is no SearchRightsDenied or repeated-history-failure handling anywhere in packages/channels/dws. Issue #10267 fix direction 4 — detecting a persistent identical history-fetch failure and emitting one clear operator warning instead of per-poll stderr lines — is operator diagnostics beyond this PR's delivery-recovery purpose, needs its own threshold/warning/reset design and tests, and the failure mode predates this PR for mention and document-notification history (this PR does not regress it). The deferred-findings record is the follow-up-issue option the finding proposed; a maintainer can schedule it from the queue. If it should instead land in this PR (since it claims "Fixes #10267"), say so and it will be implemented next round.

转入后续队列(已记录在本轮的 deferred findings 中,合并后不会丢失)。已在该提交上验证:packages/channels/dws 中任何地方都没有 SearchRightsDenied 或重复历史拉取失败的处理。issue #10267 的修复方向 4——检测持续出现的相同历史拉取失败,并发出一条清晰的运维告警取代每次轮询的 stderr 噪音——属于超出本 PR 投递恢复目的的运维诊断能力,需要独立的阈值/告警/重置设计与测试,且该失败模式在本 PR 之前就已存在于 @ 消息历史和文档通知历史(本 PR 没有使其退化)。deferred-findings 记录即该发现提出的"创建后续 issue"选项;维护者可从队列中安排。如果它应该改为在本 PR 中落地(因为本 PR 声明 "Fixes #10267"),请回复说明,下一轮将实现。

}
}
if (this.notificationWatermarkPulledBack) {
// R4-4: a stale document notification replayed while this window's
// R4-4: a stale direct message replayed while this window's
// fetch was in flight, and `handleImMessage` pulled the watermark back
// to cover it. That replay was left UNMARKED on purpose for history
// polling, so finishing this window normally would undo the rescue:
Expand Down Expand Up @@ -1458,13 +1468,13 @@ export class DwsChannel extends PollingChannelBase<DwsCursor> {
message.eventTime !== undefined &&
message.eventTime < this.connectionStartedAt - 5_000
) {
if (!parseDocumentMentionNotification(message.content)) {
if (source.kind !== 'direct') {
this.markProcessedMessage(messageKey(message));
this.saveCursor();
return;
}
// A replayed document notification is left UNMARKED on purpose, for
// history polling to pick up. That only works if polling will ever look
// A replayed direct message is left UNMARKED on purpose, for history
// polling to pick up. That only works if polling will ever look
// that far back: on a fresh cursor `notificationWatermark` starts at
// `connectionStartedAt` and the query window opens at `watermark − 5s`
// — exactly this branch's drop boundary — so every message this branch
Expand Down Expand Up @@ -1582,10 +1592,9 @@ export class DwsChannel extends PollingChannelBase<DwsCursor> {
} catch (error) {
if (source.kind !== 'at') {
// R12-1: park failed direct messages next to ambient group ones.
// The DM history loop dispatches document-mention notifications
// only, so nothing else ever re-drove a plain DM whose turn threw
// once. `at` messages need no parking: the pinned mention
// checkpoint re-fetches them.
// Direct-message history may be unavailable, and ambient group
// messages have no history fallback. `at` messages need no parking:
// the pinned mention checkpoint re-fetches them.
this.rememberPendingMessage(source, message);
}
// Under budget the throw propagates exactly as before, so redelivery
Expand Down
Loading