fix: support Harness interactions across IM channels

This commit is contained in:
xmanrui 2026-08-18 14:13:10 +08:00
parent 3e7e1dcdd7
commit cd8175d341
30 changed files with 5433 additions and 555 deletions

File diff suppressed because one or more lines are too long

View file

@ -238,6 +238,7 @@ export class DiscordRuntime {
status: this.#status,
logger: this.#logger,
replyTimeoutMs: this.#replyTimeoutMs,
signal: controller.signal,
});
let timer;
try {
@ -346,7 +347,16 @@ export class DiscordRuntime {
markReady();
} else if (packet.t === 'MESSAGE_CREATE') {
const message = normalizeDiscordMessage(packet.d, this.#config.platformId);
if (message) void this.#bridge?.accept(message);
const bridge = this.#bridge;
if (message && bridge) {
void bridge.accept(message).catch((error) => {
if (generation !== this.#generation || this.#stopped) return;
this.#logger.error?.(
`[dsh-im:discord] bot ${this.#config.botId} message handling failed:`,
error,
);
});
}
}
});
addSocketListener(socket, 'close', (event = {}) => {

View file

@ -1,3 +1,11 @@
import { HarnessClient } from '../weixin/harness-client.mjs';
import { HarnessClient } from '../shared/harness-client.mjs';
export class DiscordHarnessClient extends HarnessClient {}
export class DiscordHarnessClient extends HarnessClient {
constructor(options) {
super({
...options,
rpcIdPrefix: 'discord',
logPrefix: 'dsh-discord',
});
}
}

View file

@ -1,3 +1,11 @@
import { HarnessClient } from '../weixin/harness-client.mjs';
import { HarnessClient } from '../shared/harness-client.mjs';
export class QqHarnessClient extends HarnessClient {}
export class QqHarnessClient extends HarnessClient {
constructor(options) {
super({
...options,
rpcIdPrefix: 'qq',
logPrefix: 'dsh-qq',
});
}
}

View file

@ -1,6 +1,13 @@
import { runWorkspaceCommand } from '../shared/workspace-command.mjs';
import {
harnessAnswerForQuestion,
harnessQuestionText,
validHarnessQuestion,
} from '../shared/harness-question.mjs';
import { askInWorkspaceSession } from '../shared/workspace-session.mjs';
const INTERACTION_RESOLVED_TEXT = '这个问题已在其他客户端处理,无需再次回答。';
const HELP_TEXT = [
'QQ 机器人已连接 DeepSeek Harness。',
'',
@ -22,6 +29,17 @@ function safeText(message) {
return typeof message?.content === 'string' ? message.content.trim() : '';
}
function nonEmptyString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function canClaimInteractionReply(message, pending) {
return pending.questions[pending.index]
&& nonEmptyString(message?.senderId) === pending.actor
&& (message.kind !== 'group' || message.rawEventType === 'GROUP_AT_MESSAGE_CREATE')
&& nonEmptyString(safeText(message));
}
export function createQqBridgeStatus() {
return {
messagesReceived: 0,
@ -42,7 +60,11 @@ export class QqHarnessBridge {
#status;
#logger;
#replyTimeoutMs;
#signal;
#queues = new Map();
#pendingInteractions = new Map();
#interactionKeys = new Map();
#acceptedMessageIds = new Set();
constructor({
bot,
@ -52,6 +74,7 @@ export class QqHarnessBridge {
status = createQqBridgeStatus(),
logger = console,
replyTimeoutMs = 600_000,
signal,
}) {
if (!bot || typeof bot.sendText !== 'function') throw new TypeError('QQ bot client is required');
if (!ownerUserOpenid) throw new TypeError('QQ scanner identity is required');
@ -63,6 +86,7 @@ export class QqHarnessBridge {
this.#status = status;
this.#logger = logger;
this.#replyTimeoutMs = replyTimeoutMs;
this.#signal = signal;
}
get status() {
@ -70,12 +94,52 @@ export class QqHarnessBridge {
}
accept(message) {
if (this.#signal?.aborted) return Promise.resolve();
const messageId = nonEmptyString(message?.messageId);
const sender = nonEmptyString(message?.senderId);
if (!messageId || !sender || message?.senderIsBot === true
|| !['c2c', 'group'].includes(message?.kind)
|| this.#state.hasSeen(messageId)
|| this.#acceptedMessageIds.has(messageId)) return Promise.resolve();
const key = conversationKey(message);
this.#acceptedMessageIds.add(messageId);
const pending = this.#pendingInteractions.get(key);
if (pending && sender !== pending.actor) {
return this.#enqueueMessage(message, messageId, key);
}
if (pending?.submitting || pending?.claimedReplyMessageId) {
return this.#enqueueMessage(message, messageId, key);
}
if (pending) {
if (canClaimInteractionReply(message, pending)) {
pending.claimedReplyMessageId = messageId;
}
const previous = pending.queue ?? Promise.resolve();
const current = previous
.catch(() => undefined)
.then(() => this.#processInteractionReply(message, messageId, key, pending))
.catch((error) => this.#handleInteractionFailure(message, messageId, error))
.finally(() => {
this.#acceptedMessageIds.delete(messageId);
if (pending.claimedReplyMessageId === messageId) pending.claimedReplyMessageId = null;
if (pending.queue === current) pending.queue = null;
});
pending.queue = current;
return current;
}
return this.#enqueueMessage(message, messageId, key);
}
#enqueueMessage(message, messageId, key, {
releaseMessageId = true,
alreadyRecorded = false,
} = {}) {
const previous = this.#queues.get(key) ?? Promise.resolve();
const current = previous
.catch(() => undefined)
.then(() => this.#process(message))
.then(() => this.#process(message, key, { alreadyRecorded }))
.finally(() => {
if (releaseMessageId) this.#acceptedMessageIds.delete(messageId);
if (this.#queues.get(key) === current) this.#queues.delete(key);
});
this.#queues.set(key, current);
@ -83,17 +147,25 @@ export class QqHarnessBridge {
}
async waitForIdle() {
await Promise.allSettled([...this.#queues.values()]);
await Promise.allSettled([
...this.#queues.values(),
...[...this.#pendingInteractions.values()].flatMap((pending) => (
pending.queue ? [pending.queue] : []
)),
]);
}
async #process(message) {
const messageId = typeof message?.messageId === 'string' ? message.messageId : '';
const sender = typeof message?.senderId === 'string' ? message.senderId : '';
async #process(message, key, { alreadyRecorded = false } = {}) {
if (this.#signal?.aborted) return;
const messageId = nonEmptyString(message?.messageId);
const sender = nonEmptyString(message?.senderId);
if (!messageId || !sender || message.senderIsBot === true) return;
if (!['c2c', 'group'].includes(message.kind) || this.#state.hasSeen(messageId)) return;
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
if (!['c2c', 'group'].includes(message.kind)) return;
if (!alreadyRecorded) {
if (this.#state.hasSeen(messageId)) return;
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
}
if (this.#ownerUserOpenid !== '*' && sender !== this.#ownerUserOpenid) {
this.#status.messagesRejected += 1;
this.#status.lastRejectedAt = new Date().toISOString();
@ -116,12 +188,11 @@ export class QqHarnessBridge {
return;
}
if (command === '/status') {
await this.#harness.ensureRunning();
await this.#harness.ensureRunning({ signal: this.#signal });
await this.#bot.sendText(target, 'QQ 机器人与 DeepSeek Harness 连接正常。');
await this.#state.markSeen(messageId);
return;
}
const key = conversationKey(message);
if (command === '/new') {
await this.#state.clearSession(key);
await this.#bot.sendText(target, '已开启新会话。请发送你的问题。');
@ -146,23 +217,38 @@ export class QqHarnessBridge {
this.#logger.warn?.('[dsh-im:qq] unable to start a QQ stream; using a text reply:', error);
}
}
const { answer } = await askInWorkspaceSession({
harness: this.#harness,
state: this.#state,
key,
text,
askOptions: {
timeoutMs: this.#replyTimeoutMs,
onUpdate: stream ? async (update) => {
const progress = update.type === 'text'
? update.text
: update.type === 'tool'
? `正在使用${update.name}…`
: update.text;
if (progress) await stream.update(progress);
} : undefined,
},
});
let answer;
try {
({ answer } = await askInWorkspaceSession({
harness: this.#harness,
state: this.#state,
key,
text,
createOptions: { signal: this.#signal },
existsOptions: { signal: this.#signal },
askOptions: {
timeoutMs: this.#replyTimeoutMs,
signal: this.#signal,
onUpdate: stream ? async (update) => {
const progress = update.type === 'text'
? update.text
: update.type === 'tool'
? `正在使用${update.name}…`
: update.text;
if (progress) await stream.update(progress);
} : undefined,
onInteraction: (interaction) => this.#handleInteraction(interaction, {
key,
actor: sender,
target,
requiresMention: message.kind === 'group',
}),
onInteractionResolved: (resolution) => this.#handleInteractionResolved(resolution),
},
}));
} finally {
await this.#cancelPendingInteraction(key);
}
if (stream) {
try {
await stream.update(answer);
@ -179,6 +265,7 @@ export class QqHarnessBridge {
this.#status.lastReplyAt = new Date().toISOString();
this.#status.lastError = null;
} catch (error) {
if (this.#signal?.aborted) return;
this.#status.lastError = error?.message ?? String(error);
this.#logger.error?.('[dsh-im:qq] failed to process an inbound message:', error);
try {
@ -189,4 +276,269 @@ export class QqHarnessBridge {
}
}
}
async #processInteractionReply(message, messageId, key, expected) {
this.#signal?.throwIfAborted();
const current = this.#pendingInteractions.get(key);
const claimed = expected.claimedReplyMessageId === messageId;
if (!current || current !== expected || current.submitting) {
if (claimed && (!current || current !== expected)) {
return this.#discardResolvedInteractionReply(message, messageId);
}
return this.#enqueueMessage(message, messageId, key, { releaseMessageId: false });
}
if (this.#state.hasSeen(messageId)) return;
await this.#state.markSeen(messageId);
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
if (message.kind === 'group' && message.rawEventType !== 'GROUP_AT_MESSAGE_CREATE') return;
const text = nonEmptyString(safeText(message));
if (!text) {
await this.#bot.sendText(message.replyTarget, '请用文字回答当前问题。');
return;
}
const pending = this.#pendingInteractions.get(key);
if (!pending || pending !== expected || pending.submitting) {
if (claimed && (!pending || pending !== expected)) {
await this.#bot.sendText(message.replyTarget, INTERACTION_RESOLVED_TEXT);
return;
}
return this.#enqueueMessage(message, messageId, key, {
releaseMessageId: false,
alreadyRecorded: true,
});
}
pending.target = message.replyTarget;
if (pending.needsPresentation) {
try {
await this.#presentInteraction(pending);
} catch {
this.#status.lastError = 'QQ 交互问题发送失败。';
this.#logger.error?.('[dsh-im:qq] failed to retry an interaction question');
pending.interaction.reconnect?.();
return;
}
const presentedPending = this.#pendingInteractions.get(key);
if (!presentedPending || presentedPending !== expected || presentedPending.submitting) {
if (claimed && (!presentedPending || presentedPending !== expected)) {
await this.#bot.sendText(message.replyTarget, INTERACTION_RESOLVED_TEXT)
.catch(() => undefined);
return;
}
return this.#enqueueMessage(message, messageId, key, {
releaseMessageId: false,
alreadyRecorded: true,
});
}
}
const question = pending.questions[pending.index];
if (!question) return;
pending.answers.push(harnessAnswerForQuestion(question, text));
pending.index += 1;
if (pending.index < pending.questions.length) {
if (pending.claimedReplyMessageId === messageId) {
pending.claimedReplyMessageId = null;
}
pending.needsPresentation = true;
try {
await this.#presentInteraction(pending);
} catch {
this.#status.lastError = 'QQ 交互问题发送失败。';
this.#logger.error?.('[dsh-im:qq] failed to send the next interaction question');
pending.interaction.reconnect?.();
}
return;
}
pending.submitting = true;
try {
await pending.interaction.respond({
ok: true,
value: {
sessionId: pending.sessionId,
answer: { answers: pending.answers },
},
});
this.#clearPendingInteraction(key, pending.interactionId);
this.#status.lastError = null;
} catch (error) {
if (this.#signal?.aborted) return;
if (error?.code === 'interaction-not-pending') {
this.#clearPendingInteraction(key, pending.interactionId);
await this.#bot.sendText(pending.target, INTERACTION_RESOLVED_TEXT).catch(() => undefined);
return;
}
if (this.#pendingInteractions.get(key) !== pending) return;
pending.submitting = false;
pending.answers.pop();
pending.index -= 1;
this.#status.lastError = '回答提交失败。';
this.#logger.error?.('[dsh-im:qq] failed to answer a Harness interaction');
await this.#bot.sendText(pending.target, '回答提交失败,请重新发送当前问题的答案。')
.catch(() => undefined);
}
}
async #handleInteraction(interaction, {
key,
actor,
target,
requiresMention,
}) {
// Approval remains fail-closed until #5 adds an authenticated policy.
if (interaction?.kind !== 'question') return;
const questions = interaction?.payload?.questions;
const interactionId = typeof interaction?.interactionId === 'string'
? interaction.interactionId
: interaction?.rpcId;
if (typeof interaction?.rpcId !== 'string'
|| typeof interactionId !== 'string'
|| typeof interaction.sessionId !== 'string'
|| !Array.isArray(questions)
|| questions.length === 0
|| questions.some((question) => !validHarnessQuestion(question))) {
this.#logger.warn?.('[dsh-im:qq] ignored an invalid Harness question interaction');
return;
}
if (interaction.recovered === true) {
await interaction.respond({
ok: false,
error: {
code: 'cancelled',
message: 'QQ safely cancelled an interaction left by an earlier client.',
details: {},
},
});
await this.#bot.sendText(
target,
'检测到这个 Session 中遗留的待回答问题,已安全取消并继续处理你刚才的消息。',
).catch(() => undefined);
return;
}
const existing = this.#pendingInteractions.get(key);
if (existing?.interactionId === interactionId) {
existing.interaction = interaction;
if (existing.needsPresentation) await this.#presentInteraction(existing);
return;
}
if (this.#interactionKeys.has(interactionId)) return;
if (existing) {
await interaction.respond({
ok: false,
error: {
code: 'cancelled',
message: 'QQ is already handling another user interaction.',
details: {},
},
});
return;
}
const pending = {
kind: 'question',
interactionId,
sessionId: interaction.sessionId,
interaction,
actor,
requiresMention,
questions,
answers: [],
index: 0,
target,
queue: null,
claimedReplyMessageId: null,
presentationPromise: null,
submitting: false,
needsPresentation: true,
};
this.#pendingInteractions.set(key, pending);
this.#interactionKeys.set(interactionId, key);
await this.#presentInteraction(pending);
}
#handleInteractionResolved(resolution) {
const interactionId = resolution?.interactionId;
if (resolution?.kind !== 'question' || typeof interactionId !== 'string') return;
const key = this.#interactionKeys.get(interactionId);
if (!key) return;
this.#clearPendingInteraction(key, interactionId);
}
#presentInteraction(pending) {
if (!pending.needsPresentation) return Promise.resolve();
if (pending.presentationPromise) return pending.presentationPromise;
const question = pending.questions[pending.index];
if (!question) return Promise.resolve();
const presentation = this.#bot.sendText(
pending.target,
harnessQuestionText(
question,
pending.index,
pending.questions.length,
{ requiresMention: pending.requiresMention },
),
).then(() => {
pending.needsPresentation = false;
}).finally(() => {
if (pending.presentationPromise === presentation) pending.presentationPromise = null;
});
pending.presentationPromise = presentation;
return presentation;
}
async #discardResolvedInteractionReply(message, messageId) {
if (this.#state.hasSeen(messageId)) return;
await this.#state.markSeen(messageId);
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
await this.#bot.sendText(message.replyTarget, INTERACTION_RESOLVED_TEXT).catch(() => undefined);
}
#takePendingInteraction(key, interactionId) {
const pending = this.#pendingInteractions.get(key);
if (!pending
|| (interactionId !== undefined && pending.interactionId !== interactionId)) return null;
this.#pendingInteractions.delete(key);
this.#interactionKeys.delete(pending.interactionId);
return pending;
}
#clearPendingInteraction(key, interactionId) {
return this.#takePendingInteraction(key, interactionId) !== null;
}
async #cancelPendingInteraction(key) {
const pending = this.#takePendingInteraction(key);
if (!pending || pending.kind !== 'question') return;
try {
await pending.interaction.respond({
ok: false,
error: {
code: 'cancelled',
message: 'The QQ interaction ended before the user answered.',
details: {},
},
}, { signal: AbortSignal.timeout(5_000) });
} catch (error) {
if (error?.code !== 'interaction-not-pending') {
this.#logger.warn?.('[dsh-im:qq] failed to cancel a pending Harness interaction');
}
}
}
async #handleInteractionFailure(message, messageId, error) {
if (this.#signal?.aborted) return;
this.#status.lastError = error?.message ?? String(error);
this.#logger.error?.('[dsh-im:qq] failed to process an interaction reply:', error);
if (!this.#state.hasSeen(messageId)) {
await this.#state.markSeen(messageId).catch(() => undefined);
}
await this.#bot.sendText(message.replyTarget, '消息处理失败,请稍后重试。')
.catch(() => undefined);
}
}

View file

@ -101,6 +101,8 @@ export class QqRuntime {
if (!bot || typeof bot.start !== 'function' || typeof bot.stop !== 'function') {
throw new TypeError('QQ bot factory returned an invalid client');
}
const controller = new AbortController();
this.#abortController = controller;
this.#bot = bot;
this.#bridge = new QqHarnessBridge({
bot,
@ -110,6 +112,7 @@ export class QqRuntime {
status: this.#status,
logger: this.#logger,
replyTimeoutMs: this.#replyTimeoutMs,
signal: controller.signal,
});
bot.use?.(this.#typingMiddleware({
keepAlive: true,
@ -117,8 +120,6 @@ export class QqRuntime {
|| ctx?.message?.senderId === this.#config.ownerUserOpenid,
}));
const controller = new AbortController();
this.#abortController = controller;
let readyResolve;
let readyReject;
const ready = new Promise((resolve, reject) => {
@ -141,7 +142,17 @@ export class QqRuntime {
this.#logger.warn?.(`[dsh-im:qq] bot ${this.#config.botId} connection error:`, error);
}
};
const onMessage = (_ctx, message) => this.#bridge?.accept(message);
const onMessage = (_ctx, message) => {
const task = this.#bridge?.accept(message);
if (!task) return;
void task.catch((error) => {
if (controller.signal.aborted) return;
this.#logger.error?.(
`[dsh-im:qq] bot ${this.#config.botId} message handling failed:`,
error,
);
});
};
bot.on('ready', onReady);
bot.on('resumed', onReady);
bot.on('error', onError);

View file

@ -1,10 +1,23 @@
import { runWorkspaceCommand } from './workspace-command.mjs';
import { askInWorkspaceSession } from './workspace-session.mjs';
import {
harnessAnswerForQuestion,
harnessQuestionText,
validHarnessQuestion,
} from './harness-question.mjs';
const INTERACTION_RESOLVED_TEXT = '这个问题已在其他客户端处理,无需再次回答。';
function cleanText(value) {
return typeof value === 'string' ? value.trim() : '';
}
function canClaimInteractionReply(message, pending, senderId) {
return pending.actor === senderId
&& (message.kind !== 'group' || message.addressed === true)
&& Boolean(cleanText(message.content));
}
export function createTextBridgeStatus() {
return {
messagesReceived: 0,
@ -25,7 +38,11 @@ export class TextHarnessBridge {
#status;
#logger;
#replyTimeoutMs;
#signal;
#queues = new Map();
#pendingInteractions = new Map();
#interactionKeys = new Map();
#acceptedMessageIds = new Set();
constructor({
descriptor,
@ -35,6 +52,7 @@ export class TextHarnessBridge {
status = createTextBridgeStatus(),
logger = console,
replyTimeoutMs = 600_000,
signal,
}) {
if (!descriptor?.key || !descriptor?.label) throw new TypeError('A channel descriptor is required');
if (!bot || typeof bot.sendText !== 'function') throw new TypeError('A bot client is required');
@ -46,6 +64,7 @@ export class TextHarnessBridge {
this.#status = status;
this.#logger = logger;
this.#replyTimeoutMs = replyTimeoutMs;
this.#signal = signal;
}
get status() {
@ -53,14 +72,69 @@ export class TextHarnessBridge {
}
accept(message) {
if (this.#signal?.aborted) return Promise.resolve();
const conversationId = cleanText(message?.conversationId);
const kind = message?.kind === 'group' ? 'group' : 'direct';
const normalized = { ...message, kind, conversationId };
const messageId = cleanText(normalized.messageId);
const senderId = cleanText(normalized.senderId);
if (!messageId || !senderId || !conversationId || normalized.senderIsBot === true
|| this.#state.hasSeen(messageId) || this.#acceptedMessageIds.has(messageId)) {
return Promise.resolve();
}
this.#acceptedMessageIds.add(messageId);
const key = `${kind}:${conversationId}`;
const pending = this.#pendingInteractions.get(key);
if (pending && pending.actor !== senderId) {
return this.#enqueueMessage(normalized, messageId, senderId, key);
}
if (pending?.submitting || pending?.claimedReplyMessageId) {
return this.#enqueueMessage(normalized, messageId, senderId, key);
}
if (pending) {
if (canClaimInteractionReply(normalized, pending, senderId)) {
pending.claimedReplyMessageId = messageId;
}
const previous = pending.queue ?? Promise.resolve();
const current = previous
.catch(() => undefined)
.then(() => this.#processInteractionReply(
normalized,
messageId,
senderId,
key,
pending,
))
.finally(() => {
this.#acceptedMessageIds.delete(messageId);
if (pending.claimedReplyMessageId === messageId) {
pending.claimedReplyMessageId = null;
}
if (pending.queue === current) pending.queue = null;
});
pending.queue = current;
return current;
}
return this.#enqueueMessage(normalized, messageId, senderId, key);
}
#enqueueMessage(message, messageId, senderId, key, {
releaseMessageId = true,
alreadyRecorded = false,
} = {}) {
const previous = this.#queues.get(key) ?? Promise.resolve();
const current = previous
.catch(() => undefined)
.then(() => this.#process({ ...message, kind, conversationId }))
.then(() => this.#process(
message,
messageId,
senderId,
key,
{ alreadyRecorded },
))
.finally(() => {
if (releaseMessageId) this.#acceptedMessageIds.delete(messageId);
if (this.#queues.get(key) === current) this.#queues.delete(key);
});
this.#queues.set(key, current);
@ -68,29 +142,36 @@ export class TextHarnessBridge {
}
async waitForIdle() {
await Promise.allSettled([...this.#queues.values()]);
await Promise.allSettled([
...this.#queues.values(),
...[...this.#pendingInteractions.values()].flatMap((pending) => (
pending.queue ? [pending.queue] : []
)),
]);
}
async #process(message) {
const messageId = cleanText(message.messageId);
const senderId = cleanText(message.senderId);
if (!messageId || !senderId || !message.conversationId || message.senderIsBot === true) return;
if (this.#state.hasSeen(messageId)) return;
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
if (message.kind === 'group' && message.addressed !== true) {
this.#status.messagesRejected += 1;
this.#status.lastRejectedAt = new Date().toISOString();
return;
async #process(message, messageId, senderId, conversationKey, {
alreadyRecorded = false,
} = {}) {
if (!alreadyRecorded) {
if (this.#state.hasSeen(messageId)) return;
await this.#state.markSeen(messageId);
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
}
const target = message.replyTarget;
const text = cleanText(message.content);
let stream = null;
try {
this.#signal?.throwIfAborted();
if (message.kind === 'group' && message.addressed !== true) {
this.#status.messagesRejected += 1;
this.#status.lastRejectedAt = new Date().toISOString();
return;
}
if (!text) {
await this.#bot.sendText(target, '目前仅支持文字消息。');
await this.#state.markSeen(messageId);
return;
}
const command = text.toLowerCase();
@ -107,35 +188,29 @@ export class TextHarnessBridge {
'/status 检查连接状态',
'/help 显示本帮助',
].join('\n'));
await this.#state.markSeen(messageId);
return;
}
if (command === '/status') {
await this.#harness.ensureRunning();
await this.#harness.ensureRunning({ signal: this.#signal });
await this.#bot.sendText(target, `${this.#descriptor.label}机器人与 DeepSeek Harness 连接正常。`);
await this.#state.markSeen(messageId);
return;
}
const conversationKey = `${message.kind}:${message.conversationId}`;
const workspaceCommand = await runWorkspaceCommand(text, this.#harness, conversationKey);
if (workspaceCommand) {
for (const reply of workspaceCommand.messages ?? [workspaceCommand.message]) {
await this.#bot.sendText(target, reply);
}
await this.#state.markSeen(messageId);
return;
}
if (command === '/new') {
await this.#state.clearSession(conversationKey);
await this.#bot.sendText(target, '已开启新会话。请发送你的问题。');
await this.#state.markSeen(messageId);
return;
}
await this.#bot.sendTyping?.(target).catch((error) => {
this.#logger.warn?.(`[dsh-im:${this.#descriptor.key}] typing indicator failed:`, error);
});
let stream = null;
let streamFinished = false;
if (typeof this.#bot.openStream === 'function') {
try {
@ -152,13 +227,23 @@ export class TextHarnessBridge {
state: this.#state,
key: conversationKey,
text,
createOptions: this.#signal ? { signal: this.#signal } : undefined,
existsOptions: this.#signal ? { signal: this.#signal } : undefined,
askOptions: {
timeoutMs: this.#replyTimeoutMs,
signal: this.#signal,
onUpdate: stream ? async (update) => {
const progress = update.type === 'text' ? update.text
: update.type === 'tool' ? `正在使用${update.name}…` : update.text;
if (progress) await stream.update(progress);
} : undefined,
onInteraction: (interaction) => this.#handleInteraction(interaction, {
key: conversationKey,
actor: senderId,
target,
requiresMention: message.kind === 'group',
}),
onInteractionResolved: (resolution) => this.#handleInteractionResolved(resolution),
},
});
if (stream) {
@ -174,22 +259,349 @@ export class TextHarnessBridge {
}
}
if (!streamFinished) await this.#bot.sendText(target, answer);
await this.#state.markSeen(messageId);
this.#status.messagesReplied += 1;
this.#status.lastReplyAt = new Date().toISOString();
this.#status.lastError = null;
} catch (error) {
stream?.cancel?.();
if (this.#signal?.aborted) return;
this.#status.lastError = error?.message ?? String(error);
this.#logger.error?.(`[dsh-im:${this.#descriptor.key}] failed to process a message:`, error);
try {
await this.#bot.sendText(target, '消息处理失败,请稍后重试。');
await this.#state.markSeen(messageId);
} catch (sendError) {
this.#logger.error?.(
`[dsh-im:${this.#descriptor.key}] failed to send the safe error reply:`,
sendError,
);
}
} finally {
await this.#cancelPendingInteraction(conversationKey);
}
}
async #processInteractionReply(message, messageId, senderId, key, expected) {
if (this.#signal?.aborted) return;
const current = this.#pendingInteractions.get(key);
const claimed = expected.claimedReplyMessageId === messageId;
if (!current || current !== expected || current.submitting) {
if (claimed && (!current || current !== expected)) {
return this.#discardResolvedInteractionReply(message, messageId);
}
return this.#enqueueMessage(message, messageId, senderId, key, {
releaseMessageId: false,
});
}
if (this.#state.hasSeen(messageId)) return;
await this.#state.markSeen(messageId);
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
if (message.kind === 'group' && message.addressed !== true) {
this.#status.messagesRejected += 1;
this.#status.lastRejectedAt = new Date().toISOString();
return;
}
const target = message.replyTarget;
const text = cleanText(message.content);
if (!text) {
try {
await this.#bot.sendText(target, '请用文字回答当前问题。');
} catch (error) {
this.#logger.error?.(
`[dsh-im:${this.#descriptor.key}] failed to reject a non-text interaction reply:`,
error,
);
}
return;
}
const pending = this.#pendingInteractions.get(key);
if (!pending || pending !== expected || pending.submitting) {
if (claimed && (!pending || pending !== expected)) {
return this.#discardResolvedInteractionReply(message, messageId, {
alreadyRecorded: true,
});
}
return this.#enqueueMessage(message, messageId, senderId, key, {
releaseMessageId: false,
alreadyRecorded: true,
});
}
pending.target = target;
if (pending.needsPresentation) {
const presentationWasInFlight = pending.presentationTask !== null;
try {
await this.#presentInteraction(pending);
} catch (error) {
this.#status.lastError = `${this.#descriptor.label}交互问题发送失败。`;
this.#logger.error?.(
`[dsh-im:${this.#descriptor.key}] failed to retry an interaction question:`,
error,
);
pending.interaction.reconnect?.();
return;
}
const presented = this.#pendingInteractions.get(key);
if (!presented || presented !== expected || presented.submitting) {
if (claimed && (!presented || presented !== expected)) {
return this.#discardResolvedInteractionReply(message, messageId, {
alreadyRecorded: true,
});
}
return this.#enqueueMessage(message, messageId, senderId, key, {
releaseMessageId: false,
alreadyRecorded: true,
});
}
// A reply can arrive after the platform accepted the question message but
// before its send promise settles. In that case it is already a valid
// answer. A message which itself retried a failed presentation is not.
if (!presentationWasInFlight) return;
}
const question = pending.questions[pending.index];
if (!question) return;
pending.answers.push(harnessAnswerForQuestion(question, text));
pending.index += 1;
if (pending.index < pending.questions.length) {
if (pending.claimedReplyMessageId === messageId) {
pending.claimedReplyMessageId = null;
}
pending.needsPresentation = true;
try {
await this.#presentInteraction(pending);
} catch (error) {
this.#status.lastError = `${this.#descriptor.label}交互问题发送失败。`;
this.#logger.error?.(
`[dsh-im:${this.#descriptor.key}] failed to send the next interaction question:`,
error,
);
pending.interaction.reconnect?.();
}
return;
}
pending.submitting = true;
try {
await pending.interaction.respond({
ok: true,
value: {
sessionId: pending.sessionId,
answer: { answers: pending.answers },
},
});
this.#clearPendingInteraction(key, pending.interactionId);
this.#status.lastError = null;
} catch (error) {
if (error?.code === 'interaction-not-pending') {
this.#clearPendingInteraction(key, pending.interactionId);
if (this.#signal?.aborted) return;
try {
await this.#bot.sendText(target, INTERACTION_RESOLVED_TEXT);
} catch (sendError) {
this.#logger.error?.(
`[dsh-im:${this.#descriptor.key}] failed to send an expired interaction notice:`,
sendError,
);
}
return;
}
if (this.#signal?.aborted || this.#pendingInteractions.get(key) !== pending) return;
pending.submitting = false;
pending.answers.pop();
pending.index -= 1;
this.#status.lastError = '回答提交失败。';
this.#logger.error?.(
`[dsh-im:${this.#descriptor.key}] failed to answer a Harness interaction:`,
error,
);
try {
await this.#bot.sendText(target, '回答提交失败,请重新发送当前问题的答案。');
} catch (sendError) {
this.#logger.error?.(
`[dsh-im:${this.#descriptor.key}] failed to send an interaction retry notice:`,
sendError,
);
}
}
}
async #handleInteraction(interaction, {
key,
actor,
target,
requiresMention,
}) {
// Approval remains deliberately unanswered until #5 supplies a policy that
// can prove both the actor and the conversation allowed to decide it.
if (interaction?.kind !== 'question') return;
const questions = interaction?.payload?.questions;
const interactionId = cleanText(interaction?.interactionId) || cleanText(interaction?.rpcId);
if (!cleanText(interaction?.rpcId)
|| !interactionId
|| !cleanText(interaction?.sessionId)
|| !Array.isArray(questions)
|| questions.length === 0
|| questions.some((question) => !validHarnessQuestion(question))) {
this.#logger.warn?.(
`[dsh-im:${this.#descriptor.key}] ignored an invalid Harness question interaction`,
);
return;
}
if (interaction.recovered === true) {
await this.#respondCancellation(
interaction,
`${this.#descriptor.label} safely cancelled an interaction left by an earlier client.`,
);
try {
await this.#bot.sendText(
target,
'检测到这个 Session 中遗留的待回答问题,已安全取消并继续处理你刚才的消息。',
);
} catch (error) {
this.#logger.error?.(
`[dsh-im:${this.#descriptor.key}] failed to send an interaction recovery notice:`,
error,
);
}
return;
}
const existing = this.#pendingInteractions.get(key);
if (existing?.interactionId === interactionId) {
existing.interaction = interaction;
if (existing.needsPresentation) await this.#presentInteraction(existing);
return;
}
if (this.#interactionKeys.has(interactionId)) return;
if (existing) {
this.#logger.warn?.(
`[dsh-im:${this.#descriptor.key}] cancelled a second pending Harness question`,
);
await this.#respondCancellation(
interaction,
`${this.#descriptor.label} is already handling another user interaction.`,
);
return;
}
const pending = {
kind: 'question',
interactionId,
sessionId: interaction.sessionId,
interaction,
actor,
requiresMention,
questions,
answers: [],
index: 0,
target,
queue: null,
claimedReplyMessageId: null,
submitting: false,
needsPresentation: true,
presentationTask: null,
};
this.#pendingInteractions.set(key, pending);
this.#interactionKeys.set(interactionId, key);
await this.#presentInteraction(pending);
}
#handleInteractionResolved(resolution) {
const interactionId = cleanText(resolution?.interactionId);
if (resolution?.kind !== 'question' || !interactionId) return;
const key = this.#interactionKeys.get(interactionId);
if (!key) return;
this.#clearPendingInteraction(key, interactionId);
}
#presentInteraction(pending) {
if (pending.presentationTask) return pending.presentationTask;
const question = pending.questions[pending.index];
if (!question) return Promise.resolve();
const task = (async () => {
await this.#bot.sendText(
pending.target,
harnessQuestionText(
question,
pending.index,
pending.questions.length,
{ requiresMention: pending.requiresMention },
),
);
pending.needsPresentation = false;
})();
pending.presentationTask = task;
task.then(
() => {
if (pending.presentationTask === task) pending.presentationTask = null;
},
() => {
if (pending.presentationTask === task) pending.presentationTask = null;
},
);
return task;
}
async #discardResolvedInteractionReply(message, messageId, {
alreadyRecorded = false,
} = {}) {
if (!alreadyRecorded) {
if (this.#state.hasSeen(messageId)) return;
await this.#state.markSeen(messageId);
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
}
try {
await this.#bot.sendText(message.replyTarget, INTERACTION_RESOLVED_TEXT);
} catch (error) {
this.#logger.error?.(
`[dsh-im:${this.#descriptor.key}] failed to send an expired interaction notice:`,
error,
);
}
}
#takePendingInteraction(key, interactionId) {
const pending = this.#pendingInteractions.get(key);
if (!pending
|| (interactionId !== undefined && pending.interactionId !== interactionId)) return null;
this.#pendingInteractions.delete(key);
this.#interactionKeys.delete(pending.interactionId);
return pending;
}
#clearPendingInteraction(key, interactionId) {
return this.#takePendingInteraction(key, interactionId) !== null;
}
async #respondCancellation(interaction, message) {
try {
await interaction.respond({
ok: false,
error: { code: 'cancelled', message, details: {} },
}, { signal: AbortSignal.timeout(5_000) });
} catch (error) {
if (error?.code !== 'interaction-not-pending') throw error;
}
}
async #cancelPendingInteraction(key) {
const pending = this.#takePendingInteraction(key);
if (!pending || pending.kind !== 'question') return;
try {
await this.#respondCancellation(
pending.interaction,
`The ${this.#descriptor.label} interaction ended before the user answered.`,
);
} catch (error) {
this.#logger.warn?.(
`[dsh-im:${this.#descriptor.key}] failed to cancel a pending Harness interaction:`,
error,
);
}
}
}

View file

@ -1,3 +1,11 @@
import { HarnessClient } from '../weixin/harness-client.mjs';
import { HarnessClient } from '../shared/harness-client.mjs';
export class SlackHarnessClient extends HarnessClient {}
export class SlackHarnessClient extends HarnessClient {
constructor(options) {
super({
...options,
rpcIdPrefix: 'slack',
logPrefix: 'dsh-slack',
});
}
}

View file

@ -309,6 +309,7 @@ export class SlackRuntime {
status: this.#status,
logger: this.#logger,
replyTimeoutMs: this.#replyTimeoutMs,
signal: controller.signal,
});
let timer;
try {
@ -389,7 +390,16 @@ export class SlackRuntime {
if (this.#appId && packet.payload.api_app_id
&& packet.payload.api_app_id !== this.#appId) return;
const message = normalizeSlackEvent(packet.payload, this.#config.platformId.split(':')[1]);
if (message) void this.#bridge?.accept(message);
const bridge = this.#bridge;
if (message && bridge) {
void bridge.accept(message).catch((error) => {
if (generation !== this.#generation || this.#stopped) return;
this.#logger.error?.(
`[dsh-im:slack] bot ${this.#config.botId} message handling failed:`,
error,
);
});
}
});
addSocketListener(socket, 'close', (event = {}) => {

View file

@ -1,3 +1,11 @@
import { HarnessClient } from '../weixin/harness-client.mjs';
import { HarnessClient } from '../shared/harness-client.mjs';
export class TelegramHarnessClient extends HarnessClient {}
export class TelegramHarnessClient extends HarnessClient {
constructor(options) {
super({
...options,
rpcIdPrefix: 'telegram',
logPrefix: 'dsh-telegram',
});
}
}

View file

@ -34,19 +34,21 @@ export function normalizeTelegramUpdate(update, { botId, username }) {
const addressed = direct
|| String(message.reply_to_message?.from?.id ?? '') === String(botId)
|| mentionedUsername(message, username);
const messageThreadId = Number.isSafeInteger(message.message_thread_id)
? message.message_thread_id : undefined;
return {
messageId: String(update.update_id),
senderId: String(senderId),
senderIsBot: message.from?.is_bot === true,
kind: direct ? 'direct' : 'group',
conversationId: String(chatId),
conversationId: messageThreadId === undefined
? String(chatId) : `${chatId}:${messageThreadId}`,
content: withoutBotMention(message.text ?? message.caption ?? '', username),
addressed,
replyTarget: {
chatId,
replyToMessageId: messageId,
messageThreadId: Number.isSafeInteger(message.message_thread_id)
? message.message_thread_id : undefined,
messageThreadId,
},
};
}
@ -206,6 +208,7 @@ export class TelegramRuntime {
status: this.#status,
logger: this.#logger,
replyTimeoutMs: this.#replyTimeoutMs,
signal: controller.signal,
});
let cursor = this.#state.cursor();
@ -248,7 +251,15 @@ export class TelegramRuntime {
botId: this.#config.platformId,
username: this.#config.username,
});
if (message) await this.#bridge.accept(message);
if (message) {
void this.#bridge.accept(message).catch((error) => {
if (signal.aborted) return;
this.#logger.error?.(
`[dsh-im:telegram] bot ${this.#config.botId} message handling failed:`,
error,
);
});
}
cursor = update.update_id + 1;
await this.#state.setCursor(cursor);
}

View file

@ -1,3 +1,11 @@
import { HarnessClient } from '../weixin/harness-client.mjs';
import { HarnessClient } from '../shared/harness-client.mjs';
export class WecomHarnessClient extends HarnessClient {}
export class WecomHarnessClient extends HarnessClient {
constructor(options) {
super({
...options,
rpcIdPrefix: 'wecom',
logPrefix: 'dsh-wecom',
});
}
}

View file

@ -1,4 +1,9 @@
import { generateReqId } from '@wecom/aibot-node-sdk';
import {
harnessAnswerForQuestion,
harnessQuestionText,
validHarnessQuestion,
} from '../shared/harness-question.mjs';
import { runWorkspaceCommand } from '../shared/workspace-command.mjs';
import { askInWorkspaceSession } from '../shared/workspace-session.mjs';
@ -15,6 +20,11 @@ const HELP_TEXT = [
'/help 显示本帮助',
].join('\n');
const MAX_REPLY_BYTES = 18_000;
const INTERACTION_RESOLVED_TEXT = '这个问题已在其他客户端处理,无需再次回答。';
function nonEmptyString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function bodyOf(frame) {
return frame?.body && typeof frame.body === 'object' ? frame.body : {};
@ -27,16 +37,23 @@ function conversationKey(frame) {
function messageText(frame) {
const body = bodyOf(frame);
if (body.msgtype === 'text') return typeof body.text?.content === 'string' ? body.text.content.trim() : '';
if (body.msgtype === 'voice') return typeof body.voice?.content === 'string' ? body.voice.content.trim() : '';
if (body.msgtype === 'mixed' && Array.isArray(body.mixed?.msg_item)) {
return body.mixed.msg_item
let text = '';
if (body.msgtype === 'text') {
text = typeof body.text?.content === 'string' ? body.text.content.trim() : '';
} else if (body.msgtype === 'voice') {
text = typeof body.voice?.content === 'string' ? body.voice.content.trim() : '';
} else if (body.msgtype === 'mixed' && Array.isArray(body.mixed?.msg_item)) {
text = body.mixed.msg_item
.filter((item) => item?.msgtype === 'text' && typeof item.text?.content === 'string')
.map((item) => item.text.content)
.join('\n')
.trim();
}
return '';
// Group callbacks retain the leading @bot mention that caused delivery.
// It is routing metadata rather than part of the user's prompt or answer.
return body.chattype === 'group'
? text.replace(/^\s*@\S+(?:\s+|$)/u, '').trim()
: text;
}
function splitUtf8(text, maxBytes = MAX_REPLY_BYTES) {
@ -66,6 +83,12 @@ function progressText(update) {
return update?.text;
}
function canClaimInteractionReply(frame, pending) {
return pending.questions[pending.index]
&& nonEmptyString(bodyOf(frame).from?.userid) === pending.actor
&& nonEmptyString(messageText(frame));
}
export function createWecomBridgeStatus() {
return {
messagesReceived: 0,
@ -86,7 +109,11 @@ export class WecomHarnessBridge {
#logger;
#replyTimeoutMs;
#generateReqId;
#signal;
#queues = new Map();
#pendingInteractions = new Map();
#interactionKeys = new Map();
#acceptedMessageIds = new Set();
constructor({
client,
@ -96,6 +123,7 @@ export class WecomHarnessBridge {
logger = console,
replyTimeoutMs = 600_000,
generateStreamId = generateReqId,
signal,
}) {
if (!client || typeof client.replyStream !== 'function' || typeof client.sendMessage !== 'function') {
throw new TypeError('Enterprise WeChat client is required');
@ -108,6 +136,7 @@ export class WecomHarnessBridge {
this.#logger = logger;
this.#replyTimeoutMs = replyTimeoutMs;
this.#generateReqId = generateStreamId;
this.#signal = signal;
}
get status() {
@ -115,12 +144,65 @@ export class WecomHarnessBridge {
}
accept(frame) {
if (this.#signal?.aborted) return Promise.resolve();
const body = bodyOf(frame);
const messageId = nonEmptyString(body.msgid);
const senderId = nonEmptyString(body.from?.userid);
const chatId = body.chattype === 'group'
? nonEmptyString(body.chatid)
: senderId;
if (!messageId || !senderId || !chatId
|| !['single', 'group'].includes(body.chattype)
|| this.#state.hasSeen(messageId)
|| this.#acceptedMessageIds.has(messageId)) return Promise.resolve();
const key = conversationKey(frame);
this.#acceptedMessageIds.add(messageId);
const pending = this.#pendingInteractions.get(key);
if (pending && pending.actor !== senderId) {
return this.#enqueueMessage(frame, messageId, key);
}
if (pending?.submitting || pending?.claimedReplyMessageId) {
return this.#enqueueMessage(frame, messageId, key);
}
if (pending) {
if (canClaimInteractionReply(frame, pending)) {
pending.claimedReplyMessageId = messageId;
}
const previous = pending.queue ?? Promise.resolve();
const current = previous
.catch(() => undefined)
.then(() => this.#processInteractionReply(
frame,
messageId,
senderId,
chatId,
key,
pending,
))
.finally(() => {
this.#acceptedMessageIds.delete(messageId);
if (pending.claimedReplyMessageId === messageId) {
pending.claimedReplyMessageId = null;
}
if (pending.queue === current) pending.queue = null;
});
pending.queue = current;
return current;
}
return this.#enqueueMessage(frame, messageId, key);
}
#enqueueMessage(frame, messageId, key, {
releaseMessageId = true,
alreadyRecorded = false,
} = {}) {
const previous = this.#queues.get(key) ?? Promise.resolve();
const current = previous
.catch(() => undefined)
.then(() => this.#process(frame))
.then(() => this.#process(frame, { alreadyRecorded }))
.finally(() => {
if (releaseMessageId) this.#acceptedMessageIds.delete(messageId);
if (this.#queues.get(key) === current) this.#queues.delete(key);
});
this.#queues.set(key, current);
@ -128,16 +210,23 @@ export class WecomHarnessBridge {
}
async waitForIdle() {
await Promise.allSettled([...this.#queues.values()]);
await Promise.allSettled([
...this.#queues.values(),
...[...this.#pendingInteractions.values()].flatMap((pending) => (
pending.queue ? [pending.queue] : []
)),
]);
}
async #sendActive(chatId, text) {
for (const chunk of splitUtf8(text)) {
this.#signal?.throwIfAborted();
await this.#client.sendMessage(chatId, { msgtype: 'markdown', markdown: { content: chunk } });
}
}
async #sendImmediate(frame, chatId, text) {
this.#signal?.throwIfAborted();
const chunks = splitUtf8(text);
if (chunks.length === 0) return;
try {
@ -150,17 +239,20 @@ export class WecomHarnessBridge {
}
}
async #process(frame) {
async #process(frame, { alreadyRecorded = false } = {}) {
if (this.#signal?.aborted) return;
const body = bodyOf(frame);
const messageId = typeof body.msgid === 'string' ? body.msgid : '';
const senderId = typeof body.from?.userid === 'string' ? body.from.userid : '';
const chatId = body.chattype === 'group' ? body.chatid : senderId;
if (!messageId || !senderId || !chatId || !['single', 'group'].includes(body.chattype)) return;
if (this.#state.hasSeen(messageId)) return;
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
if (!alreadyRecorded) {
if (this.#state.hasSeen(messageId)) return;
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
}
const text = messageText(frame);
const key = conversationKey(frame);
let streamId = null;
let streamStarted = false;
try {
@ -176,12 +268,11 @@ export class WecomHarnessBridge {
return;
}
if (command === '/status') {
await this.#harness.ensureRunning();
await this.#harness.ensureRunning({ signal: this.#signal });
await this.#sendImmediate(frame, chatId, '企业微信机器人与 DeepSeek Harness 连接正常。');
await this.#state.markSeen(messageId);
return;
}
const key = conversationKey(frame);
if (command === '/new') {
await this.#state.clearSession(key);
await this.#sendImmediate(frame, chatId, '已开启新会话。请发送你的问题。');
@ -210,14 +301,24 @@ export class WecomHarnessBridge {
state: this.#state,
key,
text,
createOptions: { signal: this.#signal },
existsOptions: { signal: this.#signal },
askOptions: {
timeoutMs: this.#replyTimeoutMs,
signal: this.#signal,
onUpdate: streamStarted && typeof this.#client.replyStreamNonBlocking === 'function'
? async (update) => {
const progress = splitUtf8(progressText(update))[0];
if (progress) await this.#client.replyStreamNonBlocking(frame, streamId, progress, false);
}
: undefined,
onInteraction: (interaction) => this.#handleInteraction(interaction, {
key,
actor: senderId,
chatId,
requiresMention: body.chattype === 'group',
}),
onInteractionResolved: (resolution) => this.#handleInteractionResolved(resolution),
},
});
@ -240,6 +341,7 @@ export class WecomHarnessBridge {
this.#status.lastReplyAt = new Date().toISOString();
this.#status.lastError = null;
} catch (error) {
if (this.#signal?.aborted) return;
this.#status.lastError = error?.message ?? String(error);
this.#logger.error?.('[dsh-im:wecom] failed to process an inbound message');
try {
@ -252,6 +354,276 @@ export class WecomHarnessBridge {
} catch {
this.#logger.error?.('[dsh-im:wecom] failed to send the safe error reply');
}
} finally {
await this.#cancelPendingInteraction(key);
}
}
async #processInteractionReply(frame, messageId, senderId, chatId, key, expected) {
if (this.#signal?.aborted) return;
const current = this.#pendingInteractions.get(key);
const claimed = expected.claimedReplyMessageId === messageId;
if (!current || current !== expected || current.submitting) {
if (claimed && (!current || current !== expected)) {
return this.#discardResolvedInteractionReply(frame, messageId, chatId);
}
return this.#enqueueMessage(frame, messageId, key, { releaseMessageId: false });
}
if (this.#state.hasSeen(messageId)) return;
await this.#state.markSeen(messageId);
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
const text = nonEmptyString(messageText(frame));
if (!text) {
await this.#sendImmediate(frame, chatId, '请用文字或语音回答当前问题。')
.catch(() => undefined);
return;
}
const pending = this.#pendingInteractions.get(key);
if (!pending || pending !== expected || pending.submitting) {
if (claimed && (!pending || pending !== expected)) {
await this.#sendImmediate(frame, chatId, INTERACTION_RESOLVED_TEXT)
.catch(() => undefined);
return;
}
return this.#enqueueMessage(frame, messageId, key, {
releaseMessageId: false,
alreadyRecorded: true,
});
}
if (pending.actor !== senderId) {
return this.#enqueueMessage(frame, messageId, key, {
releaseMessageId: false,
alreadyRecorded: true,
});
}
pending.chatId = chatId;
if (pending.needsPresentation) {
try {
await this.#presentInteraction(pending);
} catch {
this.#status.lastError = '企业微信交互问题发送失败。';
this.#logger.error?.('[dsh-im:wecom] failed to retry an interaction question');
pending.interaction.reconnect?.();
return;
}
const presentedPending = this.#pendingInteractions.get(key);
if (!presentedPending || presentedPending !== expected || presentedPending.submitting) {
if (claimed && (!presentedPending || presentedPending !== expected)) {
await this.#sendImmediate(frame, chatId, INTERACTION_RESOLVED_TEXT)
.catch(() => undefined);
return;
}
return this.#enqueueMessage(frame, messageId, key, {
releaseMessageId: false,
alreadyRecorded: true,
});
}
}
const question = pending.questions[pending.index];
if (!question) return;
pending.answers.push(harnessAnswerForQuestion(question, text));
pending.index += 1;
if (pending.index < pending.questions.length) {
if (pending.claimedReplyMessageId === messageId) {
pending.claimedReplyMessageId = null;
}
pending.needsPresentation = true;
try {
await this.#presentInteraction(pending);
} catch {
this.#status.lastError = '企业微信交互问题发送失败。';
this.#logger.error?.('[dsh-im:wecom] failed to send the next interaction question');
pending.interaction.reconnect?.();
}
return;
}
pending.submitting = true;
try {
await pending.interaction.respond({
ok: true,
value: {
sessionId: pending.sessionId,
answer: { answers: pending.answers },
},
});
this.#clearPendingInteraction(key, pending.interactionId);
this.#status.lastError = null;
} catch (error) {
if (this.#signal?.aborted) return;
if (error?.code === 'interaction-not-pending') {
if (this.#pendingInteractions.get(key) === pending) {
this.#clearPendingInteraction(key, pending.interactionId);
}
await this.#sendImmediate(frame, chatId, INTERACTION_RESOLVED_TEXT)
.catch(() => undefined);
return;
}
if (this.#pendingInteractions.get(key) !== pending) return;
pending.submitting = false;
pending.answers.pop();
pending.index -= 1;
this.#status.lastError = '回答提交失败。';
this.#logger.error?.('[dsh-im:wecom] failed to answer a Harness interaction');
await this.#sendImmediate(frame, chatId, '回答提交失败,请重新发送当前问题的答案。')
.catch(() => undefined);
}
}
async #handleInteraction(interaction, {
key,
actor,
chatId,
requiresMention,
}) {
// Approval remains unanswered until #5 supplies an authenticated policy.
if (interaction?.kind !== 'question') return;
const questions = interaction?.payload?.questions;
const interactionId = typeof interaction?.interactionId === 'string'
? interaction.interactionId
: interaction?.rpcId;
if (typeof interaction?.rpcId !== 'string'
|| typeof interactionId !== 'string'
|| typeof interaction.sessionId !== 'string'
|| !Array.isArray(questions)
|| questions.length === 0
|| questions.some((question) => !validHarnessQuestion(question))) {
this.#logger.warn?.('[dsh-im:wecom] ignored an invalid Harness question interaction');
return;
}
if (interaction.recovered === true) {
await interaction.respond({
ok: false,
error: {
code: 'cancelled',
message: 'Enterprise WeChat safely cancelled an interaction left by an earlier client.',
details: {},
},
});
await this.#sendActive(
chatId,
'检测到这个 Session 中遗留的待回答问题,已安全取消并继续处理你刚才的消息。',
).catch(() => undefined);
return;
}
const existing = this.#pendingInteractions.get(key);
if (existing?.interactionId === interactionId) {
existing.interaction = interaction;
if (existing.needsPresentation) await this.#presentInteraction(existing);
return;
}
if (this.#interactionKeys.has(interactionId)) return;
if (existing) {
this.#logger.warn?.('[dsh-im:wecom] cancelled a second pending Harness question');
await interaction.respond({
ok: false,
error: {
code: 'cancelled',
message: 'Enterprise WeChat is already handling another user interaction.',
details: {},
},
});
return;
}
const pending = {
kind: 'question',
interactionId,
sessionId: interaction.sessionId,
interaction,
actor,
requiresMention,
questions,
answers: [],
index: 0,
chatId,
queue: null,
claimedReplyMessageId: null,
submitting: false,
needsPresentation: true,
presentationPromise: null,
};
this.#pendingInteractions.set(key, pending);
this.#interactionKeys.set(pending.interactionId, key);
await this.#presentInteraction(pending);
}
#handleInteractionResolved(resolution) {
const interactionId = resolution?.interactionId;
if (resolution?.kind !== 'question' || typeof interactionId !== 'string') return;
const key = this.#interactionKeys.get(interactionId);
if (!key) return;
this.#clearPendingInteraction(key, interactionId);
}
#presentInteraction(pending) {
if (!pending.needsPresentation) return Promise.resolve();
if (pending.presentationPromise) return pending.presentationPromise;
const question = pending.questions[pending.index];
if (!question) return Promise.resolve();
const presentation = this.#sendActive(
pending.chatId,
harnessQuestionText(
question,
pending.index,
pending.questions.length,
{ requiresMention: pending.requiresMention },
),
).then(() => {
pending.needsPresentation = false;
}).finally(() => {
if (pending.presentationPromise === presentation) {
pending.presentationPromise = null;
}
});
pending.presentationPromise = presentation;
return presentation;
}
async #discardResolvedInteractionReply(frame, messageId, chatId) {
if (this.#state.hasSeen(messageId)) return;
await this.#state.markSeen(messageId);
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
await this.#sendImmediate(frame, chatId, INTERACTION_RESOLVED_TEXT).catch(() => undefined);
}
#takePendingInteraction(key, interactionId) {
const pending = this.#pendingInteractions.get(key);
if (!pending
|| (interactionId !== undefined && pending.interactionId !== interactionId)) return null;
this.#pendingInteractions.delete(key);
this.#interactionKeys.delete(pending.interactionId);
return pending;
}
#clearPendingInteraction(key, interactionId) {
return this.#takePendingInteraction(key, interactionId) !== null;
}
async #cancelPendingInteraction(key) {
const pending = this.#takePendingInteraction(key);
if (!pending || pending.kind !== 'question') return;
try {
await pending.interaction.respond({
ok: false,
error: {
code: 'cancelled',
message: 'The Enterprise WeChat interaction ended before the user answered.',
details: {},
},
}, { signal: AbortSignal.timeout(5_000) });
} catch (error) {
if (error?.code !== 'interaction-not-pending') {
this.#logger.warn?.('[dsh-im:wecom] failed to cancel a pending Harness interaction');
}
}
}
}

View file

@ -36,6 +36,7 @@ export class WecomRuntime {
#bridge = null;
#starting = null;
#startController = null;
#runtimeController = null;
constructor({
config,
@ -69,8 +70,10 @@ export class WecomRuntime {
async start() {
if (this.#status.ready && this.#client) return this.status;
if (this.#starting) return this.#starting;
this.#runtimeController?.abort(new DOMException('Enterprise WeChat runtime replaced', 'AbortError'));
const controller = new AbortController();
this.#startController = controller;
this.#runtimeController = controller;
this.#starting = this.#start(controller.signal).finally(() => {
if (this.#startController === controller) this.#startController = null;
this.#starting = null;
@ -105,6 +108,7 @@ export class WecomRuntime {
status: this.#status,
logger: this.#logger,
replyTimeoutMs: this.#replyTimeoutMs,
signal,
});
let readyResolve;
@ -186,6 +190,8 @@ export class WecomRuntime {
async stop() {
const starting = this.#starting;
this.#startController?.abort(new DOMException('Enterprise WeChat runtime stopped', 'AbortError'));
this.#runtimeController?.abort(new DOMException('Enterprise WeChat runtime stopped', 'AbortError'));
this.#runtimeController = null;
await this.#stopActive();
await starting?.catch(() => undefined);
return this.status;

View file

@ -1,329 +1,19 @@
import { spawn } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { isAbsolute } from 'node:path';
import {
HarnessClient as SharedHarnessClient,
} from '../shared/harness-client.mjs';
import { adoptRegisteredWorkspaceSession } from '../shared/harness-session-binding.mjs';
export {
HarnessInteractionError,
HarnessReplyTracker,
HarnessRpcError,
} from '../shared/harness-client.mjs';
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function workspacePaths(value) {
if (!Array.isArray(value?.items)) return [];
return value.items.flatMap((item) => (
typeof item?.path === 'string' && isAbsolute(item.path) ? [item.path] : []
));
}
function workspaceFromList(workspacePath, workspaceList) {
if (!Array.isArray(workspaceList?.items)
|| !Array.isArray(workspaceList?.archivedSessionIds)) {
throw new Error('Harness returned an invalid response for workspace.list');
}
const workspace = workspaceList.items.find((item) => item?.path === workspacePath);
if (!workspace) return null;
if (!Array.isArray(workspace.sessionIds)
|| workspace.sessionIds.some((sessionId) => typeof sessionId !== 'string')) {
throw new Error('Harness returned invalid session IDs for workspace.list');
}
return workspace;
}
function workspaceSessions(workspace, archivedSessionIds, sessionList) {
if (!Array.isArray(sessionList?.items)) {
throw new Error('Harness returned an invalid response for session.list');
}
const archived = new Set(archivedSessionIds);
const summaries = new Map(sessionList.items.flatMap((item) => (
typeof item?.sessionId === 'string' ? [[item.sessionId, item]] : []
)));
return {
workspace: workspace.path,
sessions: workspace.sessionIds.map((sessionId) => {
const summary = summaries.get(sessionId);
const title = summary?.projections?.values?.title;
return {
sessionId,
title: typeof title === 'string' ? title : null,
archived: archived.has(sessionId),
blank: summary?.blank === true,
origin: summary?.origin === 'subagent' ? 'subagent' : null,
summaryAvailable: summary !== undefined,
};
}),
};
}
function assistantMessageText(event) {
return (event?.data?.message?.content ?? [])
.filter((part) => part.type === 'text' && typeof part.text === 'string')
.map((part) => part.text)
.join('\n')
.trim();
}
export class HarnessReplyTracker {
#promptRpcId;
#lastSeq;
#openTurn = null;
#targetTurn = null;
#stepText = new Map();
#latestText = '';
#finished = false;
#reason = null;
constructor({ promptRpcId, afterSeq = -1 }) {
this.#promptRpcId = promptRpcId;
this.#lastSeq = afterSeq;
}
get finished() {
return this.#finished;
}
get answer() {
return this.#latestText.trim();
}
get reason() {
return this.#reason;
}
consume(entries) {
let update = null;
const ordered = [...entries]
.map((entry) => entry?.event ?? entry)
.filter(Boolean)
.sort((left, right) => (left.seq ?? -1) - (right.seq ?? -1));
for (const event of ordered) {
const seq = event.seq ?? -1;
if (seq <= this.#lastSeq) continue;
this.#lastSeq = seq;
if (event.type === 'turn/start') this.#openTurn = event.data?.turn ?? null;
if (event.type === 'user/message' && event.data?.source?.rpcId === this.#promptRpcId) {
this.#targetTurn = this.#openTurn;
continue;
}
if (this.#targetTurn === null) continue;
if (event.type === 'turn/end') {
if (event.data?.turn !== this.#targetTurn) continue;
this.#finished = true;
this.#reason = event.data?.reason ?? null;
this.#openTurn = null;
continue;
}
if (event.data?.turn !== this.#targetTurn) continue;
if (event.type === 'assistant/chunk' && event.data?.chunk?.type === 'text-delta') {
const step = event.data?.step ?? 0;
const index = event.data.chunk.index ?? 0;
const key = `${step}:${index}`;
this.#stepText.set(key, (this.#stepText.get(key) ?? '') + event.data.chunk.text);
const prefix = `${step}:`;
const text = [...this.#stepText.entries()]
.filter(([partKey]) => partKey.startsWith(prefix))
.sort(([left], [right]) => Number(left.split(':')[1]) - Number(right.split(':')[1]))
.map(([, part]) => part)
.join('\n')
.trim();
if (text && text !== this.#latestText) {
this.#latestText = text;
update = { type: 'text', text };
}
continue;
}
if (event.type === 'assistant/message') {
const text = assistantMessageText(event);
if (text && text !== this.#latestText) {
this.#latestText = text;
update = { type: 'text', text };
}
continue;
}
if (event.type === 'tool/call') {
update = { type: 'tool', name: event.data?.name ?? '工具' };
} else if (event.type === 'tool/result') {
update = { type: 'status', text: '正在整理结果…' };
}
}
return update;
}
}
export class HarnessRpcError extends Error {
constructor(method, error) {
super(`${method}: ${error?.message ?? 'unknown Harness RPC error'}`);
this.name = 'HarnessRpcError';
this.method = method;
this.code = error?.code ?? 'internal';
this.details = error?.details ?? {};
}
}
export class HarnessClient {
#baseUrl;
#workspace;
#agentPreset;
#autostart;
#dshBin;
#managedProcess = null;
constructor({ baseUrl, workspace, agentPreset = 'standard', autostart = false, dshBin = 'dsh' }) {
this.#baseUrl = new URL(baseUrl);
this.#workspace = workspace;
this.#agentPreset = agentPreset;
this.#autostart = autostart;
this.#dshBin = dshBin;
}
async rpc(method, payload = {}, timeoutMs = 30_000, options = {}) {
const rpcId = options.rpcId ?? `weixin-${randomUUID()}`;
const response = await fetch(new URL(`/api/${method}`, this.#baseUrl), {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ type: 'client-request', rpcId, method, payload }),
signal: AbortSignal.timeout(timeoutMs),
export class HarnessClient extends SharedHarnessClient {
constructor(options) {
super({
...options,
rpcIdPrefix: 'weixin',
logPrefix: 'dsh-weixin',
});
if (!response.ok) throw new Error(`Harness transport ${method} failed: HTTP ${response.status}`);
const body = await response.json();
if (body?.type !== 'server-response' || body?.rpcId !== rpcId) {
throw new Error(`Harness returned an invalid response for ${method}`);
}
if (!body.result?.ok) throw new HarnessRpcError(method, body.result?.error);
return body.result.value;
}
async health() {
await this.rpc('host.describe', {}, 5_000);
return true;
}
async ensureRunning() {
try {
return await this.health();
} catch (firstError) {
if (!this.#autostart) throw firstError;
}
if (!this.#managedProcess || this.#managedProcess.exitCode !== null) {
const port = this.#baseUrl.port || (this.#baseUrl.protocol === 'https:' ? '443' : '80');
this.#managedProcess = spawn(this.#dshBin, [
'web', '--host', this.#baseUrl.hostname, '--port', port,
], {
cwd: this.#workspace,
env: process.env,
stdio: ['ignore', 'inherit', 'inherit'],
});
this.#managedProcess.on('error', (error) => {
console.error('[dsh-weixin] failed to start Harness:', error.message);
});
}
const deadline = Date.now() + 60_000;
let lastError;
while (Date.now() < deadline) {
await sleep(1_000);
try {
return await this.health();
} catch (error) {
lastError = error;
}
}
throw new Error(`Harness did not become ready: ${lastError?.message ?? 'timeout'}`);
}
async listWorkspaces(options = {}) {
await this.ensureRunning();
return workspacePaths(await this.rpc('workspace.list', {}, 30_000, options));
}
async listWorkspaceSessions(workspacePath, options = {}) {
await this.ensureRunning();
const workspaceList = await this.rpc('workspace.list', {}, 30_000, options);
const workspace = workspaceFromList(workspacePath, workspaceList);
if (!workspace) return { workspace: workspacePath, sessions: [] };
const sessionList = await this.rpc('session.list', {}, 30_000, options);
return workspaceSessions(workspace, workspaceList.archivedSessionIds, sessionList);
}
async adoptWorkspaceSession(value, options = {}) {
return adoptRegisteredWorkspaceSession(this, value, options);
}
async workspaceId(options = {}) {
const workspace = options.workspace ?? this.#workspace;
const { items } = await this.rpc('workspace.list', {});
const existing = items.find((item) => item.path === workspace);
if (existing) return existing.workspaceId;
const created = await this.rpc('workspace.create', { path: workspace });
return created.workspace.workspaceId;
}
async createSession(options = {}) {
await this.ensureRunning();
const workspaceId = await this.workspaceId(options);
const created = await this.rpc('session.create', {
workspaceId,
agentPreset: this.#agentPreset,
});
return created.sessionId;
}
async sessionExists(sessionId) {
try {
await this.rpc('session.history', { sessionId, maxMessages: 1 });
return true;
} catch (error) {
if (error instanceof HarnessRpcError && error.code === 'session-not-found') return false;
throw error;
}
}
async ask(sessionId, text, options = {}) {
if (typeof options === 'number') options = { timeoutMs: options };
const timeoutMs = options.timeoutMs ?? 600_000;
const onUpdate = typeof options.onUpdate === 'function' ? options.onUpdate : null;
await this.ensureRunning();
const before = await this.rpc('session.history', { sessionId, maxMessages: 1 });
const baselineSeq = Math.max(-1, ...(before.events ?? []).map(({ event }) => event.seq ?? -1));
const promptRpcId = `weixin-${randomUUID()}`;
const tracker = new HarnessReplyTracker({ promptRpcId, afterSeq: baselineSeq });
await this.rpc('session.prompt', {
sessionId,
mode: 'queue',
content: [{ type: 'text', text }],
clientTimeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
}, 30_000, { rpcId: promptRpcId });
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
await sleep(300);
const history = await this.rpc('session.history', { sessionId, maxMessages: 50 });
const update = tracker.consume(history.events ?? []);
if (update && onUpdate) {
try {
await onUpdate(update);
} catch (error) {
console.warn('[dsh-weixin] ignored a progress update failure:', error.message);
}
}
if (!tracker.finished) continue;
if (tracker.answer) return tracker.answer;
throw new Error(
`Harness turn ended without a text reply${tracker.reason ? ` (${JSON.stringify(tracker.reason)})` : ''}`,
);
}
throw new Error(`Harness reply timed out after ${Math.round(timeoutMs / 1_000)} seconds`);
}
stopManagedProcess() {
if (this.#managedProcess?.exitCode === null) this.#managedProcess.kill('SIGTERM');
}
}

View file

@ -3,9 +3,16 @@ import {
splitWeixinText,
weixinMessageId,
} from './weixin-api.mjs';
import {
harnessAnswerForQuestion,
harnessQuestionText,
validHarnessQuestion,
} from '../shared/harness-question.mjs';
import { runWorkspaceCommand } from '../shared/workspace-command.mjs';
import { askInWorkspaceSession } from '../shared/workspace-session.mjs';
const INTERACTION_RESOLVED_TEXT = '这个问题已在其他客户端处理,无需再次回答。';
const HELP_TEXT = [
'微信已连接 DeepSeek Harness。',
'',
@ -23,6 +30,16 @@ function conversationKey(userId) {
return `p2p:${userId}`;
}
function nonEmptyString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function canClaimInteractionReply(message, pending) {
return pending.questions[pending.index]
&& nonEmptyString(message?.from_user_id) === pending.actor
&& nonEmptyString(extractWeixinText(message));
}
export function createWeixinBridgeStatus() {
return {
messagesReceived: 0,
@ -46,7 +63,11 @@ export class WeixinHarnessBridge {
#logger;
#replyTimeoutMs;
#maxMessageChars;
#signal;
#queues = new Map();
#pendingInteractions = new Map();
#interactionKeys = new Map();
#acceptedMessageIds = new Set();
constructor({
api,
@ -59,6 +80,7 @@ export class WeixinHarnessBridge {
logger = console,
replyTimeoutMs = 600_000,
maxMessageChars = 4_000,
signal,
}) {
if (!api || typeof api.sendText !== 'function') throw new TypeError('Weixin API is required');
if (!baseUrl || !token || !ownerUserId) throw new TypeError('Weixin account credentials are required');
@ -73,6 +95,7 @@ export class WeixinHarnessBridge {
this.#logger = logger;
this.#replyTimeoutMs = replyTimeoutMs;
this.#maxMessageChars = maxMessageChars;
this.#signal = signal;
}
get status() {
@ -80,31 +103,73 @@ export class WeixinHarnessBridge {
}
accept(message) {
const sender = typeof message?.from_user_id === 'string' ? message.from_user_id : '';
const previous = this.#queues.get(sender) ?? Promise.resolve();
if (this.#signal?.aborted) return Promise.resolve();
if (message?.message_type === 2) return Promise.resolve();
const messageId = weixinMessageId(message);
const sender = nonEmptyString(message?.from_user_id);
if (!messageId || !sender || this.#state.hasSeen(messageId)
|| this.#acceptedMessageIds.has(messageId)) return Promise.resolve();
this.#acceptedMessageIds.add(messageId);
const key = conversationKey(sender);
const pending = this.#pendingInteractions.get(key);
if (pending?.submitting || pending?.claimedReplyMessageId) {
return this.#enqueueMessage(message, messageId, key);
}
if (pending) {
if (canClaimInteractionReply(message, pending)) {
pending.claimedReplyMessageId = messageId;
}
const previous = pending.queue ?? Promise.resolve();
const current = previous
.catch(() => undefined)
.then(() => this.#processInteractionReply(message, messageId, key, pending))
.catch((error) => this.#handleInteractionFailure(message, messageId, error))
.finally(() => {
this.#acceptedMessageIds.delete(messageId);
if (pending.claimedReplyMessageId === messageId) pending.claimedReplyMessageId = null;
if (pending.queue === current) pending.queue = null;
});
pending.queue = current;
return current;
}
return this.#enqueueMessage(message, messageId, key);
}
#enqueueMessage(message, messageId, key, {
releaseMessageId = true,
alreadyRecorded = false,
} = {}) {
const previous = this.#queues.get(key) ?? Promise.resolve();
const current = previous
.catch(() => undefined)
.then(() => this.#process(message))
.then(() => this.#process(message, key, { alreadyRecorded }))
.finally(() => {
if (this.#queues.get(sender) === current) this.#queues.delete(sender);
if (releaseMessageId) this.#acceptedMessageIds.delete(messageId);
if (this.#queues.get(key) === current) this.#queues.delete(key);
});
this.#queues.set(sender, current);
this.#queues.set(key, current);
return current;
}
async waitForIdle() {
await Promise.allSettled([...this.#queues.values()]);
await Promise.allSettled([
...this.#queues.values(),
...[...this.#pendingInteractions.values()].flatMap((pending) => (
pending.queue ? [pending.queue] : []
)),
]);
}
async #process(message) {
if (message?.message_type === 2) return;
async #process(message, key, { alreadyRecorded = false } = {}) {
this.#signal?.throwIfAborted();
const messageId = weixinMessageId(message);
const sender = typeof message?.from_user_id === 'string' ? message.from_user_id : '';
const sender = nonEmptyString(message?.from_user_id);
if (!messageId || !sender) return;
if (this.#state.hasSeen(messageId)) return;
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
if (!alreadyRecorded) {
if (this.#state.hasSeen(messageId)) return;
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
}
if (sender !== this.#ownerUserId) {
this.#status.messagesRejected += 1;
this.#status.lastRejectedAt = new Date().toISOString();
@ -122,14 +187,13 @@ export class WeixinHarnessBridge {
}
const command = text.trim().toLowerCase();
const key = conversationKey(sender);
if (command === '/help') {
await this.#send(sender, HELP_TEXT, contextToken, runId);
await this.#state.markSeen(messageId);
return;
}
if (command === '/status') {
await this.#harness.ensureRunning();
await this.#harness.ensureRunning({ signal: this.#signal });
await this.#send(sender, '微信与 DeepSeek Harness 连接正常。', contextToken, runId);
await this.#state.markSeen(messageId);
return;
@ -149,19 +213,37 @@ export class WeixinHarnessBridge {
return;
}
const { answer } = await askInWorkspaceSession({
harness: this.#harness,
state: this.#state,
key,
text,
askOptions: { timeoutMs: this.#replyTimeoutMs },
});
let answer;
try {
({ answer } = await askInWorkspaceSession({
harness: this.#harness,
state: this.#state,
key,
text,
createOptions: { signal: this.#signal },
existsOptions: { signal: this.#signal },
askOptions: {
timeoutMs: this.#replyTimeoutMs,
signal: this.#signal,
onInteraction: (interaction) => this.#handleInteraction(interaction, {
key,
actor: sender,
contextToken,
runId,
}),
onInteractionResolved: (resolution) => this.#handleInteractionResolved(resolution),
},
}));
} finally {
await this.#cancelPendingInteraction(key);
}
await this.#send(sender, answer, contextToken, runId);
await this.#state.markSeen(messageId);
this.#status.messagesReplied += 1;
this.#status.lastReplyAt = new Date().toISOString();
this.#status.lastError = null;
} catch (error) {
if (this.#signal?.aborted) return;
this.#status.lastError = error?.message ?? String(error);
this.#logger.error?.('[dsh-weixin] failed to process an inbound message:', error);
try {
@ -173,6 +255,304 @@ export class WeixinHarnessBridge {
}
}
async #processInteractionReply(message, messageId, key, expected) {
this.#signal?.throwIfAborted();
const current = this.#pendingInteractions.get(key);
const claimed = expected.claimedReplyMessageId === messageId;
if (!current || current !== expected || current.submitting) {
if (claimed && (!current || current !== expected)) {
return this.#discardResolvedInteractionReply(message, messageId);
}
return this.#enqueueMessage(message, messageId, key, { releaseMessageId: false });
}
if (this.#state.hasSeen(messageId)) return;
await this.#state.markSeen(messageId);
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
const text = nonEmptyString(extractWeixinText(message));
const contextToken = nonEmptyString(message?.context_token) ?? undefined;
const runId = nonEmptyString(message?.run_id) ?? undefined;
if (!text) {
await this.#send(
expected.actor,
'请用文字回答当前问题。',
contextToken,
runId,
);
return;
}
const pending = this.#pendingInteractions.get(key);
if (!pending || pending !== expected || pending.submitting) {
if (claimed && (!pending || pending !== expected)) {
await this.#send(
expected.actor,
INTERACTION_RESOLVED_TEXT,
contextToken,
runId,
);
return;
}
return this.#enqueueMessage(message, messageId, key, {
releaseMessageId: false,
alreadyRecorded: true,
});
}
pending.contextToken = contextToken;
pending.runId = runId;
if (pending.needsPresentation) {
try {
await this.#presentInteraction(pending);
} catch {
this.#status.lastError = '微信交互问题发送失败。';
this.#logger.error?.('[dsh-weixin] failed to retry an interaction question');
pending.interaction.reconnect?.();
return;
}
const presentedPending = this.#pendingInteractions.get(key);
if (!presentedPending || presentedPending !== expected || presentedPending.submitting) {
if (claimed && (!presentedPending || presentedPending !== expected)) {
await this.#send(
expected.actor,
INTERACTION_RESOLVED_TEXT,
contextToken,
runId,
).catch(() => undefined);
return;
}
return this.#enqueueMessage(message, messageId, key, {
releaseMessageId: false,
alreadyRecorded: true,
});
}
}
const question = pending.questions[pending.index];
if (!question) return;
pending.answers.push(harnessAnswerForQuestion(question, text));
pending.index += 1;
if (pending.index < pending.questions.length) {
if (pending.claimedReplyMessageId === messageId) {
pending.claimedReplyMessageId = null;
}
pending.needsPresentation = true;
try {
await this.#presentInteraction(pending);
} catch {
this.#status.lastError = '微信交互问题发送失败。';
this.#logger.error?.('[dsh-weixin] failed to send the next interaction question');
pending.interaction.reconnect?.();
}
return;
}
pending.submitting = true;
try {
await pending.interaction.respond({
ok: true,
value: {
sessionId: pending.sessionId,
answer: { answers: pending.answers },
},
});
this.#clearPendingInteraction(key, pending.interactionId);
this.#status.lastError = null;
} catch (error) {
if (this.#signal?.aborted) return;
if (error?.code === 'interaction-not-pending') {
this.#clearPendingInteraction(key, pending.interactionId);
await this.#send(
pending.actor,
INTERACTION_RESOLVED_TEXT,
pending.contextToken,
pending.runId,
).catch(() => undefined);
return;
}
if (this.#pendingInteractions.get(key) !== pending) return;
pending.submitting = false;
pending.answers.pop();
pending.index -= 1;
this.#status.lastError = '回答提交失败。';
this.#logger.error?.('[dsh-weixin] failed to answer a Harness interaction');
await this.#send(
pending.actor,
'回答提交失败,请重新发送当前问题的答案。',
pending.contextToken,
pending.runId,
).catch(() => undefined);
}
}
async #handleInteraction(interaction, {
key,
actor,
contextToken,
runId,
}) {
// Approval remains fail-closed until #5 adds an authenticated policy.
if (interaction?.kind !== 'question') return;
const questions = interaction?.payload?.questions;
const interactionId = typeof interaction?.interactionId === 'string'
? interaction.interactionId
: interaction?.rpcId;
if (typeof interaction?.rpcId !== 'string'
|| typeof interactionId !== 'string'
|| typeof interaction.sessionId !== 'string'
|| !Array.isArray(questions)
|| questions.length === 0
|| questions.some((question) => !validHarnessQuestion(question))) {
this.#logger.warn?.('[dsh-weixin] ignored an invalid Harness question interaction');
return;
}
if (interaction.recovered === true) {
await interaction.respond({
ok: false,
error: {
code: 'cancelled',
message: 'Weixin safely cancelled an interaction left by an earlier client.',
details: {},
},
});
await this.#send(
actor,
'检测到这个 Session 中遗留的待回答问题,已安全取消并继续处理你刚才的消息。',
contextToken,
runId,
).catch(() => undefined);
return;
}
const existing = this.#pendingInteractions.get(key);
if (existing?.interactionId === interactionId) {
existing.interaction = interaction;
if (existing.needsPresentation) await this.#presentInteraction(existing);
return;
}
if (this.#interactionKeys.has(interactionId)) return;
if (existing) {
await interaction.respond({
ok: false,
error: {
code: 'cancelled',
message: 'Weixin is already handling another user interaction.',
details: {},
},
});
return;
}
const pending = {
kind: 'question',
interactionId,
sessionId: interaction.sessionId,
interaction,
actor,
questions,
answers: [],
index: 0,
contextToken,
runId,
queue: null,
claimedReplyMessageId: null,
presentationPromise: null,
submitting: false,
needsPresentation: true,
};
this.#pendingInteractions.set(key, pending);
this.#interactionKeys.set(interactionId, key);
await this.#presentInteraction(pending);
}
#handleInteractionResolved(resolution) {
const interactionId = resolution?.interactionId;
if (resolution?.kind !== 'question' || typeof interactionId !== 'string') return;
const key = this.#interactionKeys.get(interactionId);
if (!key) return;
this.#clearPendingInteraction(key, interactionId);
}
#presentInteraction(pending) {
if (!pending.needsPresentation) return Promise.resolve();
if (pending.presentationPromise) return pending.presentationPromise;
const question = pending.questions[pending.index];
if (!question) return Promise.resolve();
const presentation = this.#send(
pending.actor,
harnessQuestionText(question, pending.index, pending.questions.length),
pending.contextToken,
pending.runId,
).then(() => {
pending.needsPresentation = false;
}).finally(() => {
if (pending.presentationPromise === presentation) pending.presentationPromise = null;
});
pending.presentationPromise = presentation;
return presentation;
}
async #discardResolvedInteractionReply(message, messageId) {
if (this.#state.hasSeen(messageId)) return;
await this.#state.markSeen(messageId);
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
await this.#send(
nonEmptyString(message?.from_user_id),
INTERACTION_RESOLVED_TEXT,
nonEmptyString(message?.context_token) ?? undefined,
nonEmptyString(message?.run_id) ?? undefined,
).catch(() => undefined);
}
#takePendingInteraction(key, interactionId) {
const pending = this.#pendingInteractions.get(key);
if (!pending
|| (interactionId !== undefined && pending.interactionId !== interactionId)) return null;
this.#pendingInteractions.delete(key);
this.#interactionKeys.delete(pending.interactionId);
return pending;
}
#clearPendingInteraction(key, interactionId) {
return this.#takePendingInteraction(key, interactionId) !== null;
}
async #cancelPendingInteraction(key) {
const pending = this.#takePendingInteraction(key);
if (!pending || pending.kind !== 'question') return;
try {
await pending.interaction.respond({
ok: false,
error: {
code: 'cancelled',
message: 'The Weixin interaction ended before the user answered.',
details: {},
},
}, { signal: AbortSignal.timeout(5_000) });
} catch (error) {
if (error?.code !== 'interaction-not-pending') {
this.#logger.warn?.('[dsh-weixin] failed to cancel a pending Harness interaction');
}
}
}
async #handleInteractionFailure(message, messageId, error) {
if (this.#signal?.aborted) return;
this.#status.lastError = error?.message ?? String(error);
this.#logger.error?.('[dsh-weixin] failed to process an interaction reply:', error);
if (!this.#state.hasSeen(messageId)) {
await this.#state.markSeen(messageId).catch(() => undefined);
}
await this.#send(
nonEmptyString(message?.from_user_id),
'消息处理失败,请稍后重试。',
nonEmptyString(message?.context_token) ?? undefined,
nonEmptyString(message?.run_id) ?? undefined,
).catch(() => undefined);
}
async #send(toUserId, text, contextToken, runId) {
for (const chunk of splitWeixinText(text, this.#maxMessageChars)) {
await this.#api.sendText({

View file

@ -116,6 +116,8 @@ export class WeixinRuntime {
await this.#harness.ensureRunning();
this.#status.harnessReachable = true;
await this.#notifyStart();
this.#abortController = new AbortController();
const signal = this.#abortController.signal;
this.#bridge = new WeixinHarnessBridge({
api: this.#api,
baseUrl: this.#config.baseUrl,
@ -127,12 +129,11 @@ export class WeixinRuntime {
logger: this.#logger,
replyTimeoutMs: this.#replyTimeoutMs,
maxMessageChars: this.#maxMessageChars,
signal,
});
this.#abortController = new AbortController();
this.#status.ready = true;
this.#status.weixinConnectionState = 'connected';
this.#status.lastCheckedAt = Date.now();
const signal = this.#abortController.signal;
this.#monitor = this.#runMonitor(signal).catch((error) => {
if (signal.aborted) return;
this.#status.ready = false;
@ -142,6 +143,9 @@ export class WeixinRuntime {
});
return this.status;
} catch (error) {
this.#abortController?.abort();
this.#abortController = null;
this.#bridge = null;
this.#status.ready = false;
this.#status.weixinConnectionState = 'failed';
this.#status.lastError = error?.message ?? String(error);
@ -195,7 +199,13 @@ export class WeixinRuntime {
this.#status.lastError = null;
for (const message of response?.msgs ?? []) {
await this.#bridge.accept(message);
void this.#bridge.accept(message).catch((error) => {
if (signal.aborted) return;
this.#logger.error?.(
`[dsh-weixin] account ${this.#config.botId} message handling failed:`,
error,
);
});
}
if (typeof response?.get_updates_buf === 'string' && response.get_updates_buf) {
await this.#state.setGetUpdatesBuf(response.get_updates_buf);

View file

@ -1,3 +1,11 @@
import { HarnessClient } from '../weixin/harness-client.mjs';
import { HarnessClient } from '../shared/harness-client.mjs';
export class WhatsappHarnessClient extends HarnessClient {}
export class WhatsappHarnessClient extends HarnessClient {
constructor(options) {
super({
...options,
rpcIdPrefix: 'whatsapp',
logPrefix: 'dsh-whatsapp',
});
}
}

View file

@ -256,6 +256,7 @@ export class WhatsappRuntime {
status: this.#status,
logger: this.#logger,
replyTimeoutMs: this.#replyTimeoutMs,
signal: controller.signal,
});
const now = Date.now();
this.#status.ready = true;

View file

@ -44,6 +44,25 @@ function credentials() {
};
}
function deferred() {
let resolve;
let reject;
const promise = new Promise((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
return { promise, resolve, reject };
}
async function eventually(predicate, timeoutMs = 1_000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (predicate()) return;
await new Promise((resolve) => setTimeout(resolve, 5));
}
assert.fail('condition was not met before timeout');
}
test('Discord API authenticates with a Bot header and validates the current bot', async () => {
assert.equal(validDiscordToken(TOKEN), true);
assert.equal(validDiscordToken('not-a-token'), false);
@ -233,6 +252,9 @@ class FakeSocket {
test('Discord runtime identifies on Gateway v10 and becomes ready', async () => {
let socket;
const abortMark = deferred();
let abortMarkStarted = false;
const errors = [];
const runtime = new DiscordRuntime({
config: {
botId: 'discord_test',
@ -246,7 +268,13 @@ test('Discord runtime identifies on Gateway v10 and becomes ready', async () =>
setSession: async () => {},
clearSession: async () => {},
hasSeen: () => false,
markSeen: async () => {},
markSeen: async (messageId) => {
if (messageId === '111111111111111199') {
abortMarkStarted = true;
return abortMark.promise;
}
throw new Error(`Discord state write failed for ${messageId}`);
},
},
createApi: () => ({
getCurrentUser: async () => ({ id: '1234567890123456789', bot: true }),
@ -260,6 +288,10 @@ test('Discord runtime identifies on Gateway v10 and becomes ready', async () =>
return socket;
},
random: () => 0.5,
logger: {
warn() {},
error(...args) { errors.push(args); },
},
});
await runtime.start();
assert.equal(runtime.status.ready, true);
@ -267,6 +299,46 @@ test('Discord runtime identifies on Gateway v10 and becomes ready', async () =>
assert.equal(identify.d.token, TOKEN);
assert.equal(identify.d.intents, 4_609);
assert.equal(identify.d.properties.browser, 'dsh-im');
await runtime.stop();
for (const [id, sequence] of [
['111111111111111190', 2],
['111111111111111191', 3],
]) {
socket.emit('message', {
data: JSON.stringify({
op: 0,
t: 'MESSAGE_CREATE',
s: sequence,
d: {
id,
channel_id: '222222222222222222',
author: { id: '333333333333333333', bot: false },
content: 'trigger state failure',
},
}),
});
}
await eventually(() => errors.length === 2);
assert.equal(errors.every((args) => args[0].includes('message handling failed')), true);
socket.emit('message', {
data: JSON.stringify({
op: 0,
t: 'MESSAGE_CREATE',
s: 4,
d: {
id: '111111111111111199',
channel_id: '222222222222222222',
author: { id: '333333333333333333', bot: false },
content: 'abort state write',
},
}),
});
await eventually(() => abortMarkStarted);
const stopping = runtime.stop();
abortMark.reject(new Error('Discord state write aborted'));
await stopping;
await new Promise((resolve) => setImmediate(resolve));
assert.equal(errors.length, 2);
assert.equal(runtime.status.ready, false);
});

View file

@ -3,6 +3,41 @@ import test from 'node:test';
import { QqHarnessBridge } from '../../../src/channels/qq/qq-bridge.mjs';
function deferred() {
let resolve;
let reject;
const promise = new Promise((promiseResolve, promiseReject) => {
resolve = promiseResolve;
reject = promiseReject;
});
return { promise, resolve, reject };
}
async function eventually(predicate, messageText = 'condition was not met') {
const deadline = Date.now() + 1_000;
while (Date.now() < deadline) {
if (predicate()) return;
await new Promise((resolve) => setTimeout(resolve, 5));
}
assert.fail(messageText);
}
function stateFixture(initialSessions = []) {
const sessions = new Map(initialSessions);
const seen = new Set();
return {
sessions,
seen,
state: {
hasSeen: (id) => seen.has(id),
markSeen: async (id) => seen.add(id),
sessionFor: (key) => sessions.get(key) ?? null,
setSession: async (key, sessionId) => sessions.set(key, sessionId),
clearSession: async (key) => sessions.delete(key),
},
};
}
function message(overrides = {}) {
return {
kind: 'c2c',
@ -101,3 +136,777 @@ test('QQ credential-bound bots accept senders within the platform visibility sco
assert.equal(asks, 1);
assert.equal(bridge.status.messagesRejected, 0);
});
test('QQ group questions require the initiating actor to mention the bot and preserve multi-question answers', async () => {
const fixture = stateFixture([['group:group-1', 'session-group']]);
const sent = [];
const asked = [];
const submitted = deferred();
const secondQuestionDelivered = deferred();
const releaseSecondQuestion = deferred();
const bridge = new QqHarnessBridge({
bot: {
sendText: async (target, text) => {
sent.push({ target, text });
if (text.includes('选择交付内容')) {
secondQuestionDelivered.resolve();
await releaseSecondQuestion.promise;
}
},
},
ownerUserOpenid: '*',
harness: {
sessionExists: async () => true,
createSession: async () => assert.fail('the existing session should be reused'),
ask: async (sessionId, text, options) => {
asked.push({ sessionId, text });
if (text === '旁观者的普通问题') return '旁观者问题已回答';
await options.onInteraction({
kind: 'question',
interactionId: 'qq-group-multi',
rpcId: 'qq-group-multi',
sessionId,
payload: {
type: 'question/requested',
sessionId,
questions: [
{
id: 'language',
question: '选择回答语言',
options: [{ label: '中文' }, { label: 'English' }],
},
{
id: 'deliverables',
question: '选择交付内容',
multiSelect: true,
options: [{ label: '测试' }, { label: '文档' }],
},
],
},
respond: async (result) => {
submitted.resolve(result);
return { accepted: true };
},
});
await submitted.promise;
return '发起者交互完成';
},
},
state: fixture.state,
});
const first = bridge.accept(message({
kind: 'group',
rawEventType: 'GROUP_AT_MESSAGE_CREATE',
senderId: 'initiator',
groupOpenid: 'group-1',
content: '启动群聊交互',
messageId: 'group-start',
replyTarget: { scope: 'group', targetId: 'group-1', msgId: 'group-start' },
}));
await eventually(() => sent.some(({ text }) => text.includes('选择回答语言')));
assert.equal(sent.find(({ text }) => text.includes('选择回答语言')).text
.includes('群聊中请 @机器人 后发送答案。'), true);
let submittedResult;
submitted.promise.then((result) => { submittedResult = result; });
const bystander = bridge.accept(message({
kind: 'group',
rawEventType: 'GROUP_AT_MESSAGE_CREATE',
senderId: 'bystander',
groupOpenid: 'group-1',
content: '旁观者的普通问题',
messageId: 'group-bystander',
replyTarget: { scope: 'group', targetId: 'group-1', msgId: 'group-bystander' },
}));
await bridge.accept(message({
kind: 'group',
rawEventType: 'GROUP_MESSAGE_CREATE',
senderId: 'initiator',
groupOpenid: 'group-1',
content: '未提及机器人的答案',
messageId: 'group-unmentioned',
replyTarget: { scope: 'group', targetId: 'group-1', msgId: 'group-unmentioned' },
}));
assert.equal(submittedResult, undefined);
const firstAnswer = bridge.accept(message({
kind: 'group',
rawEventType: 'GROUP_AT_MESSAGE_CREATE',
senderId: 'initiator',
groupOpenid: 'group-1',
content: '2',
messageId: 'group-language',
replyTarget: { scope: 'group', targetId: 'group-1', msgId: 'group-language' },
}));
await secondQuestionDelivered.promise;
const secondAnswer = bridge.accept(message({
kind: 'group',
rawEventType: 'GROUP_AT_MESSAGE_CREATE',
senderId: 'initiator',
groupOpenid: 'group-1',
content: '1,文档,发布说明',
messageId: 'group-deliverables',
replyTarget: { scope: 'group', targetId: 'group-1', msgId: 'group-deliverables' },
}));
releaseSecondQuestion.resolve();
await Promise.all([firstAnswer, secondAnswer]);
assert.deepEqual(await submitted.promise, {
ok: true,
value: {
sessionId: 'session-group',
answer: {
answers: [
{ id: 'language', selected: ['English'] },
{ id: 'deliverables', selected: ['测试', '文档'], custom: '发布说明' },
],
},
},
});
await Promise.all([first, bystander]);
assert.deepEqual(asked, [
{ sessionId: 'session-group', text: '启动群聊交互' },
{ sessionId: 'session-group', text: '旁观者的普通问题' },
]);
assert.equal(asked.some(({ text }) => [
'未提及机器人的答案',
'2',
'1,文档,发布说明',
].includes(text)), false);
assert.deepEqual(sent.slice(-2).map(({ text }) => text), ['发起者交互完成', '旁观者问题已回答']);
});
test('QQ pending questions stay isolated between private conversations', async () => {
const fixture = stateFixture([
['c2c:user-a', 'session-a'],
['c2c:user-b', 'session-b'],
]);
const sent = [];
const asked = [];
const answeredA = deferred();
const responseA = deferred();
const bridge = new QqHarnessBridge({
bot: { sendText: async (target, text) => sent.push({ target, text }) },
ownerUserOpenid: '*',
harness: {
sessionExists: async () => true,
createSession: async () => assert.fail('the existing sessions should be reused'),
ask: async (sessionId, text, options) => {
asked.push({ sessionId, text });
if (sessionId === 'session-b') return '乙会话的普通回答';
await options.onInteraction({
kind: 'question',
interactionId: 'qq-isolated-a',
rpcId: 'qq-isolated-a',
sessionId,
payload: {
type: 'question/requested',
sessionId,
questions: [{ id: 'answer-a', question: '甲会话的问题' }],
},
respond: async (result) => {
responseA.resolve(result);
answeredA.resolve();
return { accepted: true };
},
});
await answeredA.promise;
return '甲会话完成';
},
},
state: fixture.state,
});
const firstA = bridge.accept(message({
senderId: 'user-a',
content: '启动甲会话',
messageId: 'private-a-start',
replyTarget: { scope: 'c2c', targetId: 'user-a', msgId: 'private-a-start' },
}));
await eventually(() => sent.some(({ text }) => text.includes('甲会话的问题')));
await bridge.accept(message({
senderId: 'user-b',
content: '乙会话的消息',
messageId: 'private-b',
replyTarget: { scope: 'c2c', targetId: 'user-b', msgId: 'private-b' },
}));
assert.equal(sent.some(({ target, text }) => (
target.targetId === 'user-b' && text === '乙会话的普通回答'
)), true);
await bridge.accept(message({
senderId: 'user-a',
content: '甲的答案',
messageId: 'private-a-answer',
replyTarget: { scope: 'c2c', targetId: 'user-a', msgId: 'private-a-answer' },
}));
await firstA;
assert.deepEqual((await responseA.promise).value.answer.answers, [
{ id: 'answer-a', selected: [], custom: '甲的答案' },
]);
assert.deepEqual(asked, [
{ sessionId: 'session-a', text: '启动甲会话' },
{ sessionId: 'session-b', text: '乙会话的消息' },
]);
});
test('QQ deduplicates question replays, cancels orphan questions, and keeps approvals fail-closed', async () => {
const fixture = stateFixture();
const sent = [];
let approvalResponses = 0;
let parallelResponse;
let orphanResponse;
const bridge = new QqHarnessBridge({
bot: { sendText: async (target, text) => sent.push({ target, text }) },
ownerUserOpenid: 'owner-openid',
harness: {
sessionExists: async () => false,
createSession: async () => 'session-replay',
ask: async (sessionId, _text, options) => {
const replayedQuestion = {
kind: 'question',
interactionId: 'qq-replayed-question',
rpcId: 'qq-replayed-question',
sessionId,
payload: {
type: 'question/requested',
sessionId,
questions: [{ id: 'choice', question: '只应显示一次' }],
},
respond: async () => ({ accepted: true }),
};
await options.onInteraction(replayedQuestion);
await options.onInteraction(replayedQuestion);
await options.onInteraction({
kind: 'question',
interactionId: 'qq-parallel-question',
rpcId: 'qq-parallel-question',
sessionId,
payload: {
type: 'question/requested',
sessionId,
questions: [{ id: 'parallel', question: '不应展示的并行问题' }],
},
respond: async (result) => {
parallelResponse = result;
return { accepted: true };
},
});
await options.onInteraction({
kind: 'approval',
interactionId: 'qq-approval',
rpcId: 'qq-approval',
sessionId,
payload: {
type: 'approval/requested',
sessionId,
approvalId: 'qq-approval',
toolName: 'bash',
},
respond: async () => { approvalResponses += 1; },
});
await options.onInteractionResolved({
kind: 'question',
interactionId: 'qq-replayed-question',
sessionId,
outcome: 'cancelled',
});
await options.onInteraction({
kind: 'question',
interactionId: 'qq-orphan-question',
rpcId: 'qq-orphan-question',
sessionId,
recovered: true,
payload: {
type: 'question/requested',
sessionId,
questions: [{ id: 'secret', question: '旧会话中的敏感问题内容' }],
},
respond: async (result) => {
orphanResponse = result;
return { accepted: true };
},
});
return '交互恢复完成';
},
},
state: fixture.state,
logger: { warn() {}, error() {} },
});
await bridge.accept(message({ messageId: 'qq-replay', content: '测试交互重放' }));
assert.equal(sent.filter(({ text }) => text.includes('只应显示一次')).length, 1);
assert.deepEqual(parallelResponse, {
ok: false,
error: {
code: 'cancelled',
message: 'QQ is already handling another user interaction.',
details: {},
},
});
assert.equal(approvalResponses, 0);
assert.equal(sent.some(({ text }) => text.includes('approval')), false);
assert.deepEqual(orphanResponse, {
ok: false,
error: {
code: 'cancelled',
message: 'QQ safely cancelled an interaction left by an earlier client.',
details: {},
},
});
assert.equal(sent.some(({ text }) => text.includes('旧会话中的敏感问题内容')), false);
assert.equal(sent.some(({ text }) => text.includes('遗留的待回答问题')), true);
assert.equal(sent.at(-1).text, '交互恢复完成');
});
test('QQ keeps a queued prompt separate while a failed interaction answer is retried', async () => {
const fixture = stateFixture([['c2c:owner-openid', 'session-submit-retry']]);
const sent = [];
const asked = [];
const firstSubmitStarted = deferred();
const releaseFirstSubmit = deferred();
const answered = deferred();
const submittedAnswers = [];
let submitAttempts = 0;
const bridge = new QqHarnessBridge({
bot: { sendText: async (target, text) => sent.push({ target, text }) },
ownerUserOpenid: 'owner-openid',
harness: {
sessionExists: async () => true,
createSession: async () => assert.fail('the existing session should be reused'),
ask: async (sessionId, text, options) => {
asked.push(text);
if (text === '排队的下一个问题') return '第二轮完成';
await options.onInteraction({
kind: 'question',
interactionId: 'qq-submit-retry',
rpcId: 'qq-submit-retry',
sessionId,
payload: {
type: 'question/requested',
sessionId,
questions: [{ id: 'answer', question: '请回答后再继续' }],
},
respond: async (result) => {
submittedAnswers.push(result.value.answer.answers[0].custom);
submitAttempts += 1;
if (submitAttempts === 1) {
firstSubmitStarted.resolve();
await releaseFirstSubmit.promise;
throw new Error('temporary response failure');
}
answered.resolve();
return { accepted: true };
},
});
await answered.promise;
return '第一轮完成';
},
},
state: fixture.state,
logger: { warn() {}, error() {} },
});
const first = bridge.accept(message({ messageId: 'retry-start', content: '启动可重试交互' }));
await eventually(() => sent.some(({ text }) => text.includes('请回答后再继续')));
const firstAnswer = bridge.accept(message({
messageId: 'retry-first-answer',
content: '第一次答案',
replyTarget: { scope: 'c2c', targetId: 'owner-openid', msgId: 'retry-first-answer' },
}));
await firstSubmitStarted.promise;
let nextSettled = false;
const next = bridge.accept(message({
messageId: 'retry-next',
content: '排队的下一个问题',
replyTarget: { scope: 'c2c', targetId: 'owner-openid', msgId: 'retry-next' },
})).finally(() => { nextSettled = true; });
releaseFirstSubmit.resolve();
await firstAnswer;
await eventually(() => sent.some(({ text }) => text.includes('回答提交失败')));
assert.equal(nextSettled, false);
assert.deepEqual(asked, ['启动可重试交互']);
await Promise.all([
bridge.accept(message({
messageId: 'retry-second-answer',
content: '重试后的答案',
replyTarget: { scope: 'c2c', targetId: 'owner-openid', msgId: 'retry-second-answer' },
})),
first,
next,
]);
assert.deepEqual(submittedAnswers, ['第一次答案', '重试后的答案']);
assert.deepEqual(asked, ['启动可重试交互', '排队的下一个问题']);
assert.deepEqual(sent.slice(-2).map(({ text }) => text), ['第一轮完成', '第二轮完成']);
});
test('QQ discards an already-claimed answer when the interaction resolves elsewhere', async () => {
const fixture = stateFixture([['c2c:owner-openid', 'session-resolved-race']]);
const originalMarkSeen = fixture.state.markSeen;
const answerMarkStarted = deferred();
const releaseAnswerMark = deferred();
fixture.state.markSeen = async (id) => {
if (id === 'resolved-answer') {
answerMarkStarted.resolve();
await releaseAnswerMark.promise;
}
await originalMarkSeen(id);
};
const sent = [];
const asked = [];
const resolved = deferred();
let resolveInteraction;
const bridge = new QqHarnessBridge({
bot: { sendText: async (target, text) => sent.push({ target, text }) },
ownerUserOpenid: 'owner-openid',
harness: {
sessionExists: async () => true,
createSession: async () => assert.fail('the existing session should be reused'),
ask: async (sessionId, text, options) => {
asked.push(text);
if (text === '后来的普通问题') return '后来问题的回答';
await options.onInteraction({
kind: 'question',
interactionId: 'qq-resolved-race',
rpcId: 'qq-resolved-race',
sessionId,
payload: {
type: 'question/requested',
sessionId,
questions: [{ id: 'answer', question: '可能在其他客户端回答' }],
},
respond: async () => ({ accepted: true }),
});
resolveInteraction = async () => {
await options.onInteractionResolved({
kind: 'question',
interactionId: 'qq-resolved-race',
sessionId,
outcome: 'answered',
});
resolved.resolve();
};
await resolved.promise;
return '第一轮已由其他客户端完成';
},
},
state: fixture.state,
});
const first = bridge.accept(message({ messageId: 'resolved-start', content: '启动外部解决竞态' }));
await eventually(() => typeof resolveInteraction === 'function');
const answer = bridge.accept(message({
messageId: 'resolved-answer',
content: '原本的问题答案',
replyTarget: { scope: 'c2c', targetId: 'owner-openid', msgId: 'resolved-answer' },
}));
await answerMarkStarted.promise;
const later = bridge.accept(message({
messageId: 'resolved-later',
content: '后来的普通问题',
replyTarget: { scope: 'c2c', targetId: 'owner-openid', msgId: 'resolved-later' },
}));
await resolveInteraction();
releaseAnswerMark.resolve();
await Promise.all([answer, first, later]);
assert.deepEqual(asked, ['启动外部解决竞态', '后来的普通问题']);
assert.equal(asked.includes('原本的问题答案'), false);
assert.equal(sent.some(({ text }) => text.includes('已在其他客户端处理')), true);
});
test('QQ keeps an answer that arrives after the first question is delivered but before its send ACK', async () => {
const fixture = stateFixture([['c2c:owner-openid', 'session-first-delivery']]);
const questionDelivered = deferred();
const releaseQuestionAck = deferred();
const answered = deferred();
const sent = [];
const asked = [];
let submitted;
let questionSends = 0;
const bridge = new QqHarnessBridge({
bot: {
sendText: async (target, text) => {
sent.push({ target, text });
if (text.includes('首问 ACK 窗口')) {
questionSends += 1;
questionDelivered.resolve();
await releaseQuestionAck.promise;
}
},
},
ownerUserOpenid: 'owner-openid',
harness: {
sessionExists: async () => true,
ask: async (sessionId, text, options) => {
asked.push(text);
await options.onInteraction({
kind: 'question',
interactionId: 'qq-first-delivery',
rpcId: 'qq-first-delivery',
sessionId,
payload: {
type: 'question/requested',
sessionId,
questions: [{ id: 'answer', question: '首问 ACK 窗口' }],
},
respond: async (result) => {
submitted = result;
answered.resolve();
return { accepted: true };
},
});
await answered.promise;
return '首问已完成';
},
},
state: fixture.state,
});
const first = bridge.accept(message({
messageId: 'first-delivery-start',
content: '启动首问窗口',
}));
await questionDelivered.promise;
const answer = bridge.accept(message({
messageId: 'first-delivery-answer',
content: '窗口内答案',
replyTarget: { scope: 'c2c', targetId: 'owner-openid', msgId: 'first-delivery-answer' },
}));
await new Promise((resolve) => setImmediate(resolve));
assert.equal(submitted, undefined);
releaseQuestionAck.resolve();
await Promise.all([first, answer]);
assert.equal(questionSends, 1);
assert.deepEqual(asked, ['启动首问窗口']);
assert.deepEqual(submitted.value.answer.answers, [{
id: 'answer',
selected: [],
custom: '窗口内答案',
}]);
assert.equal(fixture.seen.has('first-delivery-answer'), true);
});
test('QQ tombstones a q2 answer accepted before its send ACK when the interaction resolves', async () => {
const fixture = stateFixture([['c2c:owner-openid', 'session-q2-resolved']]);
const secondQuestionDelivered = deferred();
const releaseSecondQuestionAck = deferred();
const turnResolved = deferred();
const sent = [];
const asked = [];
let resolveInteraction;
const bridge = new QqHarnessBridge({
bot: {
sendText: async (target, text) => {
sent.push({ target, text });
if (text.includes('会在 ACK 前 resolved 的第二问')) {
secondQuestionDelivered.resolve();
await releaseSecondQuestionAck.promise;
}
},
},
ownerUserOpenid: 'owner-openid',
harness: {
sessionExists: async () => true,
ask: async (sessionId, text, options) => {
asked.push(text);
await options.onInteraction({
kind: 'question',
interactionId: 'qq-q2-resolved',
rpcId: 'qq-q2-resolved',
sessionId,
payload: {
type: 'question/requested',
sessionId,
questions: [
{ id: 'first', question: '先回答第一问' },
{ id: 'second', question: '会在 ACK 前 resolved 的第二问' },
],
},
respond: async () => assert.fail('the externally resolved interaction must not be answered'),
});
resolveInteraction = () => {
options.onInteractionResolved({
kind: 'question',
interactionId: 'qq-q2-resolved',
sessionId,
outcome: 'answered',
});
turnResolved.resolve();
};
await turnResolved.promise;
return '已由其他客户端完成';
},
},
state: fixture.state,
});
const first = bridge.accept(message({
messageId: 'q2-resolved-start',
content: '启动 q2 resolved 窗口',
}));
await eventually(() => typeof resolveInteraction === 'function');
const firstAnswer = bridge.accept(message({
messageId: 'q2-resolved-first',
content: '第一问答案',
replyTarget: { scope: 'c2c', targetId: 'owner-openid', msgId: 'q2-resolved-first' },
}));
await secondQuestionDelivered.promise;
const secondAnswer = bridge.accept(message({
messageId: 'q2-resolved-second',
content: '第二问答案',
replyTarget: { scope: 'c2c', targetId: 'owner-openid', msgId: 'q2-resolved-second' },
}));
resolveInteraction();
releaseSecondQuestionAck.resolve();
await Promise.all([firstAnswer, secondAnswer, first]);
assert.deepEqual(asked, ['启动 q2 resolved 窗口']);
assert.equal(fixture.seen.has('q2-resolved-second'), true);
assert.equal(sent.some(({ text }) => text.includes('已在其他客户端处理')), true);
});
test('QQ reports resolved when an in-flight response becomes not-pending', async () => {
const fixture = stateFixture([['c2c:owner-openid', 'session-respond-resolved']]);
const responseStarted = deferred();
const releaseResponse = deferred();
const turnResolved = deferred();
const sent = [];
let resolveInteraction;
const bridge = new QqHarnessBridge({
bot: { sendText: async (target, text) => sent.push({ target, text }) },
ownerUserOpenid: 'owner-openid',
harness: {
sessionExists: async () => true,
ask: async (sessionId, _text, options) => {
await options.onInteraction({
kind: 'question',
interactionId: 'qq-respond-resolved',
rpcId: 'qq-respond-resolved',
sessionId,
payload: {
type: 'question/requested',
sessionId,
questions: [{ id: 'answer', question: '提交中会被外部解决' }],
},
respond: async () => {
responseStarted.resolve();
await releaseResponse.promise;
const error = new Error('already resolved');
error.code = 'interaction-not-pending';
throw error;
},
});
resolveInteraction = () => {
options.onInteractionResolved({
kind: 'question',
interactionId: 'qq-respond-resolved',
sessionId,
outcome: 'answered',
});
turnResolved.resolve();
};
await turnResolved.promise;
return '外部处理完成';
},
},
state: fixture.state,
});
const first = bridge.accept(message({
messageId: 'respond-resolved-start',
content: '启动提交竞态',
}));
await eventually(() => typeof resolveInteraction === 'function');
const answer = bridge.accept(message({
messageId: 'respond-resolved-answer',
content: '我的答案',
replyTarget: { scope: 'c2c', targetId: 'owner-openid', msgId: 'respond-resolved-answer' },
}));
await responseStarted.promise;
resolveInteraction();
releaseResponse.resolve();
await Promise.all([answer, first]);
assert.equal(sent.some(({ text, target }) => (
target.msgId === 'respond-resolved-answer'
&& text.includes('已在其他客户端处理')
)), true);
});
test('QQ propagates the stop signal and cancels its pending question on abort', async () => {
const fixture = stateFixture();
fixture.sessions.set('c2c:owner-openid', 'stale-session');
const controller = new AbortController();
const interactionReady = deferred();
let existsSignal;
let createSignal;
let askSignal;
let cancellation;
let cancellationSignal;
const bridge = new QqHarnessBridge({
bot: { sendText: async () => {} },
ownerUserOpenid: 'owner-openid',
signal: controller.signal,
harness: {
sessionExists: async (_sessionId, options) => {
existsSignal = options.signal;
return false;
},
createSession: async (options) => {
createSignal = options.signal;
return 'session-abort';
},
ask: async (sessionId, _text, options) => {
askSignal = options.signal;
await options.onInteraction({
kind: 'question',
interactionId: 'qq-abort-question',
rpcId: 'qq-abort-question',
sessionId,
payload: {
type: 'question/requested',
sessionId,
questions: [{ id: 'answer', question: '等待进程停止' }],
},
respond: async (result, respondOptions) => {
cancellation = result;
cancellationSignal = respondOptions.signal;
return { accepted: true };
},
});
interactionReady.resolve();
await new Promise((resolve, reject) => {
options.signal.addEventListener('abort', () => reject(options.signal.reason), { once: true });
});
},
},
state: fixture.state,
logger: { warn() {}, error() {} },
});
const turn = bridge.accept(message({ messageId: 'abort-start', content: '启动后停止' }));
await interactionReady.promise;
controller.abort(new Error('runtime stopped'));
await turn;
assert.equal(existsSignal, controller.signal);
assert.equal(createSignal, controller.signal);
assert.equal(askSignal, controller.signal);
assert.deepEqual(cancellation, {
ok: false,
error: {
code: 'cancelled',
message: 'The QQ interaction ended before the user answered.',
details: {},
},
});
assert.notEqual(cancellationSignal, controller.signal);
assert.equal(cancellationSignal.aborted, false);
});

View file

@ -4,6 +4,12 @@ import test from 'node:test';
import { QqRuntime } from '../../../src/channels/qq/qq-runtime.mjs';
function deferred() {
let resolve;
const promise = new Promise((done) => { resolve = done; });
return { promise, resolve };
}
class FakeBot extends EventEmitter {
middlewares = [];
stopped = false;
@ -70,3 +76,59 @@ test('QQ runtime never reports ready when the gateway does not emit ready', asyn
await assert.rejects(() => runtime.start(), /did not become ready/);
assert.equal(runtime.status.ready, false);
});
test('QQ runtime aborts an in-flight Harness interaction when stopped', async () => {
const bot = new FakeBot();
const askStarted = deferred();
let askSignal;
const runtime = new QqRuntime({
config: { botId: 'qq_bot', appId: 'app', ownerUserOpenid: 'owner' },
appSecret: 'secret',
harness: {
ensureRunning: async () => true,
sessionExists: async () => true,
ask: async (_sessionId, _text, options) => {
askSignal = options.signal;
askStarted.resolve();
await new Promise((_resolve, reject) => options.signal.addEventListener('abort', () => {
reject(options.signal.reason);
}, { once: true }));
},
},
state: {
hasSeen: () => false,
markSeen: async () => {},
sessionFor: () => 'session-existing',
setSession: async () => {},
clearSession: async () => {},
},
createBot: () => bot,
typingMiddleware: () => 'typing',
connectTimeoutMs: 100,
logger: { error() {}, warn() {}, info() {} },
});
await runtime.start();
bot.emit('message', {}, {
kind: 'c2c',
rawEventType: 'C2C_MESSAGE_CREATE',
senderId: 'owner',
senderIsBot: false,
content: '需要交互',
messageId: 'interaction-message',
replyTarget: { scope: 'c2c', targetId: 'owner', msgId: 'interaction-message' },
});
await askStarted.promise;
assert.equal(askSignal.aborted, false);
bot.emit('message', {}, {
kind: 'c2c',
rawEventType: 'C2C_MESSAGE_CREATE',
senderId: 'owner',
senderIsBot: false,
content: '排队中的下一条消息',
messageId: 'queued-message',
replyTarget: { scope: 'c2c', targetId: 'owner', msgId: 'queued-message' },
});
await runtime.stop();
assert.equal(askSignal.aborted, true);
});

View file

@ -0,0 +1,634 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { TextHarnessBridge } from '../../../src/channels/shared/text-harness-bridge.mjs';
function deferred() {
let resolve;
let reject;
const promise = new Promise((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
return { promise, resolve, reject };
}
async function eventually(predicate, timeoutMs = 1_000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (predicate()) return;
await new Promise((resolve) => setTimeout(resolve, 5));
}
assert.fail('condition was not met before timeout');
}
function stateFixture(initialSessions = {}) {
const sessions = new Map(Object.entries(initialSessions));
const seen = new Set();
return {
sessions,
seen,
state: {
sessionFor(key) { return sessions.get(key) ?? null; },
async setSession(key, sessionId) {
sessions.set(key, sessionId);
return true;
},
async clearSession(key) { sessions.delete(key); },
hasSeen(messageId) { return seen.has(messageId); },
async markSeen(messageId) { seen.add(messageId); },
},
};
}
function message(messageId, content, overrides = {}) {
return {
messageId,
senderId: 'actor-a',
senderIsBot: false,
kind: 'direct',
conversationId: 'chat-a',
content,
addressed: true,
replyTarget: { id: `target-${messageId}` },
...overrides,
};
}
function questionInteraction({
id = 'question-one',
sessionId = 'session-one',
questions = [{ id: 'answer', question: '请回答' }],
respond = async () => ({ accepted: true }),
...rest
} = {}) {
return {
kind: 'question',
interactionId: id,
rpcId: id,
sessionId,
payload: { type: 'question/requested', sessionId, questions },
respond,
...rest,
};
}
function createBridge({ harness, state, bot, signal, logger } = {}) {
return new TextHarnessBridge({
descriptor: { key: 'test', label: 'Test' },
bot,
harness,
state,
signal,
logger: logger ?? { warn() {}, error() {} },
});
}
test('answers a multi-question interaction on the fast lane with canonical values', async () => {
const fixture = stateFixture();
const sent = [];
const asked = [];
const submitted = deferred();
const bridge = createBridge({
state: fixture.state,
bot: { sendText: async (target, text) => sent.push({ target, text }) },
harness: {
createSession: async () => 'session-one',
ask: async (sessionId, text, options) => {
asked.push({ sessionId, text });
await options.onInteraction(questionInteraction({
sessionId,
questions: [
{
id: 'language',
question: '选择回答语言',
options: [{ label: '中文' }, { label: 'English' }],
},
{
id: 'deliverables',
question: '选择交付内容',
multiSelect: true,
options: [{ label: '测试' }, { label: '文档' }],
},
],
respond: async (result) => {
submitted.resolve(result);
return { accepted: true };
},
}));
await submitted.promise;
return '交互已完成';
},
},
});
const processing = bridge.accept(message('prompt', '请分步提问'));
await eventually(() => sent.some(({ text }) => text.includes('选择回答语言')));
await bridge.accept(message('language', '2'));
await eventually(() => sent.some(({ text }) => text.includes('选择交付内容')));
await bridge.accept(message('deliverables', '1,文档,发布说明'));
assert.deepEqual(await submitted.promise, {
ok: true,
value: {
sessionId: 'session-one',
answer: {
answers: [
{ id: 'language', selected: ['English'] },
{ id: 'deliverables', selected: ['测试', '文档'], custom: '发布说明' },
],
},
},
});
await processing;
assert.deepEqual(asked, [{ sessionId: 'session-one', text: '请分步提问' }]);
assert.equal(sent.at(-1).text, '交互已完成');
assert.deepEqual(sent[1].target, { id: 'target-language' });
});
test('isolates pending questions by normalized conversation key', async () => {
const fixture = stateFixture({
'direct:chat-a': 'session-a',
'direct:chat-b': 'session-b',
});
const sent = [];
const answeredA = deferred();
const asked = [];
const bridge = createBridge({
state: fixture.state,
bot: { sendText: async (target, text) => sent.push({ target, text }) },
harness: {
sessionExists: async () => true,
ask: async (sessionId, text, options) => {
asked.push({ sessionId, text });
if (sessionId === 'session-b') return '乙会话完成';
await options.onInteraction(questionInteraction({
id: 'question-a',
sessionId,
questions: [{ id: 'a', question: '甲会话的问题' }],
respond: async (result) => {
answeredA.resolve(result);
return { accepted: true };
},
}));
await answeredA.promise;
return '甲会话完成';
},
},
});
const first = bridge.accept(message('a-start', '启动甲'));
await eventually(() => sent.some(({ text }) => text.includes('甲会话的问题')));
await bridge.accept(message('b-normal', '乙的普通问题', {
senderId: 'actor-b',
conversationId: 'chat-b',
}));
assert.deepEqual(asked, [
{ sessionId: 'session-a', text: '启动甲' },
{ sessionId: 'session-b', text: '乙的普通问题' },
]);
await bridge.accept(message('a-answer', '甲的答案'));
assert.deepEqual((await answeredA.promise).value.answer.answers, [
{ id: 'a', selected: [], custom: '甲的答案' },
]);
await first;
});
test('a group question only accepts an addressed reply from the initiating actor', async () => {
const fixture = stateFixture({ 'group:room': 'session-group' });
const sent = [];
const submitted = deferred();
const asked = [];
let responseCalls = 0;
const bridge = createBridge({
state: fixture.state,
bot: { sendText: async (target, text) => sent.push({ target, text }) },
harness: {
sessionExists: async () => true,
ask: async (sessionId, text, options) => {
asked.push(text);
if (text !== '甲发起交互') return '普通群消息已处理';
await options.onInteraction(questionInteraction({
id: 'group-question',
sessionId,
questions: [{ id: 'actor', question: '只能由甲回答' }],
respond: async (result) => {
responseCalls += 1;
submitted.resolve(result);
return { accepted: true };
},
}));
await submitted.promise;
return '甲的交互完成';
},
},
});
const group = { kind: 'group', conversationId: 'room' };
const first = bridge.accept(message('group-start', '甲发起交互', { ...group }));
await eventually(() => sent.some(({ text }) => text.includes('只能由甲回答')));
assert.match(sent[0].text, /群聊中请 @机器人/);
await bridge.accept(message('group-unaddressed', '没有 @ 的回答', {
...group,
addressed: false,
}));
const intruder = bridge.accept(message('group-intruder', '乙试图代答', {
...group,
senderId: 'actor-b',
}));
await new Promise((resolve) => setTimeout(resolve, 20));
assert.equal(responseCalls, 0);
assert.deepEqual(asked, ['甲发起交互']);
await bridge.accept(message('group-answer', '甲的真正答案', { ...group }));
assert.deepEqual((await submitted.promise).value.answer.answers, [{
id: 'actor',
selected: [],
custom: '甲的真正答案',
}]);
await Promise.all([first, intruder]);
assert.deepEqual(asked, ['甲发起交互', '乙试图代答']);
assert.equal(bridge.status.messagesRejected, 1);
});
test('deduplicates replays, cancels parallel and recovered questions, and leaves approval pending', async () => {
const fixture = stateFixture();
const sent = [];
let parallelResponse;
let recoveredResponse;
let approvalResponses = 0;
const bridge = createBridge({
state: fixture.state,
bot: { sendText: async (target, text) => sent.push({ target, text }) },
harness: {
createSession: async () => 'session-one',
ask: async (sessionId, _text, options) => {
const current = questionInteraction({
id: 'replayed-question',
sessionId,
questions: [{ id: 'current', question: '只应显示一次' }],
});
await options.onInteraction(current);
await options.onInteraction(current);
await options.onInteraction(questionInteraction({
id: 'parallel-question',
sessionId,
questions: [{ id: 'parallel', question: '不应显示的并行问题' }],
respond: async (result) => { parallelResponse = result; },
}));
await options.onInteraction({
kind: 'approval',
interactionId: 'approval-one',
rpcId: 'approval-rpc',
sessionId,
payload: { type: 'approval/requested', approvalId: 'approval-one' },
respond: async () => { approvalResponses += 1; },
});
await options.onInteraction(questionInteraction({
id: 'orphan-question',
sessionId,
recovered: true,
questions: [{ id: 'secret', question: '旧会话中的敏感问题内容' }],
respond: async (result) => { recoveredResponse = result; },
}));
await options.onInteractionResolved({
kind: 'question',
interactionId: 'replayed-question',
sessionId,
outcome: 'cancelled',
});
return '已继续处理';
},
},
});
await bridge.accept(message('replay', '测试交互重放'));
assert.equal(sent.filter(({ text }) => text.includes('只应显示一次')).length, 1);
assert.equal(sent.some(({ text }) => text.includes('旧会话中的敏感问题内容')), false);
assert.equal(sent.some(({ text }) => text.includes('遗留的待回答问题')), true);
assert.deepEqual(parallelResponse?.error, {
code: 'cancelled',
message: 'Test is already handling another user interaction.',
details: {},
});
assert.deepEqual(recoveredResponse?.error, {
code: 'cancelled',
message: 'Test safely cancelled an interaction left by an earlier client.',
details: {},
});
assert.equal(approvalResponses, 0);
});
test('keeps a failed interaction response pending so the actor can retry', async () => {
const fixture = stateFixture();
const sent = [];
const completed = deferred();
const submittedAnswers = [];
const bridge = createBridge({
state: fixture.state,
bot: { sendText: async (target, text) => sent.push({ target, text }) },
harness: {
createSession: async () => 'session-one',
ask: async (sessionId, _text, options) => {
await options.onInteraction(questionInteraction({
id: 'retry-question',
sessionId,
respond: async (result) => {
submittedAnswers.push(result.value.answer.answers[0].custom);
if (submittedAnswers.length === 1) throw new Error('temporary failure');
completed.resolve();
return { accepted: true };
},
}));
await completed.promise;
return '重试成功';
},
},
});
const processing = bridge.accept(message('retry-start', '启动可重试交互'));
await eventually(() => sent.some(({ text }) => text.includes('请回答')));
await bridge.accept(message('retry-first', '第一次答案'));
assert.equal(sent.some(({ text }) => text.includes('回答提交失败')), true);
await bridge.accept(message('retry-second', '重试后的答案'));
await processing;
assert.deepEqual(submittedAnswers, ['第一次答案', '重试后的答案']);
assert.equal(sent.at(-1).text, '重试成功');
});
test('notifies the actor when an in-flight response resolves elsewhere before rejection', async () => {
const fixture = stateFixture();
const sent = [];
const responseStarted = deferred();
const asked = [];
const bridge = createBridge({
state: fixture.state,
bot: { sendText: async (target, text) => sent.push({ target, text }) },
harness: {
createSession: async () => 'session-one',
ask: async (sessionId, text, options) => {
asked.push(text);
await options.onInteraction(questionInteraction({
id: 'response-resolved-race',
sessionId,
respond: async () => {
options.onInteractionResolved({
kind: 'question',
interactionId: 'response-resolved-race',
sessionId,
outcome: 'answered',
});
responseStarted.resolve();
const error = new Error('interaction no longer pending');
error.code = 'interaction-not-pending';
throw error;
},
}));
await responseStarted.promise;
return '原会话已结束';
},
},
});
const processing = bridge.accept(message('response-race-start', '启动提交竞态'));
await eventually(() => sent.some(({ text }) => text.includes('请回答')));
await bridge.accept(message('response-race-answer', '已经收到的答案'));
await processing;
assert.deepEqual(asked, ['启动提交竞态']);
assert.equal(sent.some(({ text }) => text.includes('已在其他客户端处理')), true);
});
test('discards a claimed answer when the interaction resolves during message recording', async () => {
const fixture = stateFixture({ 'direct:chat-a': 'session-one' });
const originalMarkSeen = fixture.state.markSeen;
const answerMarkStarted = deferred();
const releaseAnswerMark = deferred();
fixture.state.markSeen = async (messageId) => {
if (messageId === 'racing-answer') {
answerMarkStarted.resolve();
await releaseAnswerMark.promise;
}
await originalMarkSeen(messageId);
};
const sent = [];
const asked = [];
const externallyResolved = deferred();
let resolveInteraction;
const bridge = createBridge({
state: fixture.state,
bot: { sendText: async (target, text) => sent.push({ target, text }) },
harness: {
sessionExists: async () => true,
ask: async (sessionId, text, options) => {
asked.push(text);
if (text === '后来的普通问题') return '后来问题的回答';
await options.onInteraction(questionInteraction({
id: 'resolved-race-question',
sessionId,
}));
resolveInteraction = () => {
options.onInteractionResolved({
kind: 'question',
interactionId: 'resolved-race-question',
sessionId,
outcome: 'answered',
});
externallyResolved.resolve();
};
await externallyResolved.promise;
return '第一轮已由其他客户端完成';
},
},
});
const processing = bridge.accept(message('race-start', '启动外部解决竞态'));
await eventually(() => typeof resolveInteraction === 'function');
const answer = bridge.accept(message('racing-answer', '原本的问题答案'));
await answerMarkStarted.promise;
resolveInteraction();
releaseAnswerMark.resolve();
await Promise.all([processing, answer]);
await bridge.accept(message('later-prompt', '后来的普通问题'));
assert.deepEqual(asked, ['启动外部解决竞态', '后来的普通问题']);
assert.equal(asked.includes('原本的问题答案'), false);
assert.equal(sent.some(({ text }) => text.includes('已在其他客户端处理')), true);
});
test('accepts a first answer received while its question presentation is still in flight', async () => {
const fixture = stateFixture();
const presentationStarted = deferred();
const releasePresentation = deferred();
const submitted = deferred();
const sent = [];
const asked = [];
let questionPresentations = 0;
const bridge = createBridge({
state: fixture.state,
bot: {
sendText: async (target, text) => {
sent.push({ target, text });
if (text.includes('发送仍在进行的问题')) {
questionPresentations += 1;
presentationStarted.resolve();
await releasePresentation.promise;
}
},
},
harness: {
createSession: async () => 'session-one',
ask: async (sessionId, text, options) => {
asked.push(text);
await options.onInteraction(questionInteraction({
id: 'first-presentation-race',
sessionId,
questions: [{ id: 'first', question: '发送仍在进行的问题' }],
respond: async (result) => {
submitted.resolve(result);
return { accepted: true };
},
}));
await submitted.promise;
return '首问已回答';
},
},
});
const processing = bridge.accept(message('presentation-start', '启动首问竞态'));
await presentationStarted.promise;
const answer = bridge.accept(message('presentation-answer', '首问答案'));
releasePresentation.resolve();
await Promise.all([processing, answer]);
assert.deepEqual((await submitted.promise).value.answer.answers, [{
id: 'first',
selected: [],
custom: '首问答案',
}]);
assert.deepEqual(asked, ['启动首问竞态']);
assert.equal(questionPresentations, 1);
assert.equal(sent.at(-1).text, '首问已回答');
});
test('discards an answer already received when a later question resolves during presentation', async () => {
const fixture = stateFixture();
const secondPresentationStarted = deferred();
const releaseSecondPresentation = deferred();
const externallyResolved = deferred();
const sent = [];
const asked = [];
let resolveInteraction;
const bridge = createBridge({
state: fixture.state,
bot: {
sendText: async (target, text) => {
sent.push({ target, text });
if (text.includes('仍在发送的第二问')) {
secondPresentationStarted.resolve();
await releaseSecondPresentation.promise;
}
},
},
harness: {
createSession: async () => 'session-one',
ask: async (sessionId, text, options) => {
asked.push(text);
if (text !== '启动第二问竞态') return '不应把第二问答案作为新 prompt';
await options.onInteraction(questionInteraction({
id: 'second-presentation-race',
sessionId,
questions: [
{ id: 'first', question: '第一问' },
{ id: 'second', question: '仍在发送的第二问' },
],
}));
resolveInteraction = () => {
options.onInteractionResolved({
kind: 'question',
interactionId: 'second-presentation-race',
sessionId,
outcome: 'answered',
});
externallyResolved.resolve();
};
await externallyResolved.promise;
return '已由其他客户端完成';
},
},
});
const processing = bridge.accept(message('second-race-start', '启动第二问竞态'));
await eventually(() => typeof resolveInteraction === 'function');
const firstAnswer = bridge.accept(message('second-race-first', '第一问答案'));
await secondPresentationStarted.promise;
const secondAnswer = bridge.accept(message('second-race-second', '第二问已收到的答案'));
resolveInteraction();
releaseSecondPresentation.resolve();
await Promise.all([processing, firstAnswer, secondAnswer]);
assert.deepEqual(asked, ['启动第二问竞态']);
assert.equal(asked.includes('第二问已收到的答案'), false);
assert.equal(sent.some(({ text }) => text.includes('已在其他客户端处理')), true);
});
test('passes the runtime signal to Harness and safely cancels a pending question on abort', async () => {
const controller = new AbortController();
const fixture = stateFixture({ 'direct:chat-a': 'stale-session' });
const sent = [];
const cancelled = deferred();
let existsSignal;
let createSignal;
let askSignal;
const bridge = createBridge({
state: fixture.state,
signal: controller.signal,
bot: { sendText: async (target, text) => sent.push({ target, text }) },
harness: {
sessionExists: async (_sessionId, options) => {
existsSignal = options?.signal;
return false;
},
createSession: async (options) => {
createSignal = options?.signal;
return 'session-one';
},
ask: async (sessionId, _text, options) => {
askSignal = options.signal;
await options.onInteraction(questionInteraction({
id: 'abort-question',
sessionId,
respond: async (result) => {
cancelled.resolve(result);
return { accepted: true };
},
}));
await new Promise((resolve, reject) => {
options.signal.addEventListener('abort', () => reject(options.signal.reason), {
once: true,
});
});
},
},
});
const processing = bridge.accept(message('abort-start', '启动后停止'));
await eventually(() => sent.some(({ text }) => text.includes('请回答')));
controller.abort(new DOMException('runtime stopped', 'AbortError'));
await processing;
assert.equal(existsSignal, controller.signal);
assert.equal(createSignal, controller.signal);
assert.equal(askSignal, controller.signal);
assert.deepEqual(await cancelled.promise, {
ok: false,
error: {
code: 'cancelled',
message: 'The Test interaction ended before the user answered.',
details: {},
},
});
});

View file

@ -46,6 +46,25 @@ function credentials() {
};
}
function deferred() {
let resolve;
let reject;
const promise = new Promise((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
return { promise, resolve, reject };
}
async function eventually(predicate, timeoutMs = 1_000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (predicate()) return;
await new Promise((resolve) => setTimeout(resolve, 5));
}
assert.fail('condition was not met before timeout');
}
test('Slack validates both tokens and inspects Bot and Socket Mode credentials', async () => {
assert.equal(validSlackBotToken(BOT_TOKEN), true);
assert.equal(validSlackAppToken(APP_TOKEN), true);
@ -269,6 +288,9 @@ class FakeSocket {
test('Slack runtime opens Socket Mode, acknowledges envelopes, and becomes ready', async () => {
let socket;
const abortMark = deferred();
let abortMarkStarted = false;
const errors = [];
const runtime = new SlackRuntime({
config: {
botId: 'slack_test',
@ -283,7 +305,13 @@ test('Slack runtime opens Socket Mode, acknowledges envelopes, and becomes ready
setSession: async () => {},
clearSession: async () => {},
hasSeen: () => false,
markSeen: async () => {},
markSeen: async (messageId) => {
if (messageId === 'Ev-abort') {
abortMarkStarted = true;
return abortMark.promise;
}
throw new Error(`Slack state write failed for ${messageId}`);
},
},
createApi: () => ({
authTest: async () => ({ team_id: 'T12345678', user_id: 'U12345678' }),
@ -299,6 +327,10 @@ test('Slack runtime opens Socket Mode, acknowledges envelopes, and becomes ready
}));
return socket;
},
logger: {
warn() {},
error(...args) { errors.push(args); },
},
});
await runtime.start();
assert.equal(runtime.status.ready, true);
@ -310,6 +342,55 @@ test('Slack runtime opens Socket Mode, acknowledges envelopes, and becomes ready
}),
});
assert.deepEqual(socket.sent.at(-1), { envelope_id: 'env-1' });
await runtime.stop();
for (const eventId of ['Ev-failed-first', 'Ev-failed-queued']) {
socket.emit('message', {
data: JSON.stringify({
envelope_id: `env-${eventId}`,
type: 'events_api',
payload: {
type: 'event_callback',
api_app_id: 'A12345678',
event_id: eventId,
event: {
type: 'message',
channel_type: 'im',
channel: 'D12345678',
user: 'U87654321',
ts: eventId === 'Ev-failed-first' ? '1700000000.010' : '1700000000.011',
text: 'trigger state failure',
},
},
}),
});
}
await eventually(() => errors.length === 2);
assert.equal(errors.every((args) => args[0].includes('message handling failed')), true);
socket.emit('message', {
data: JSON.stringify({
envelope_id: 'env-abort',
type: 'events_api',
payload: {
type: 'event_callback',
api_app_id: 'A12345678',
event_id: 'Ev-abort',
event: {
type: 'message',
channel_type: 'im',
channel: 'D12345678',
user: 'U87654321',
ts: '1700000000.012',
text: 'abort state write',
},
},
}),
});
await eventually(() => abortMarkStarted);
const stopping = runtime.stop();
abortMark.reject(new Error('Slack state write aborted'));
await stopping;
await new Promise((resolve) => setImmediate(resolve));
assert.equal(errors.length, 2);
assert.equal(runtime.status.ready, false);
});

View file

@ -58,6 +58,30 @@ function memoryState() {
};
}
function deferred() {
let resolve;
let reject;
const promise = new Promise((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
return { promise, resolve, reject };
}
async function bounded(promise, message, timeoutMs = 1_000) {
let timer;
try {
return await Promise.race([
promise,
new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(message)), timeoutMs);
}),
]);
} finally {
clearTimeout(timer);
}
}
test('Telegram API validates a Bot Token without exposing it in requests or errors', async () => {
assert.equal(validTelegramToken(TOKEN), true);
assert.equal(validTelegramToken('short'), false);
@ -198,6 +222,34 @@ test('Telegram normalizes private messages and requires an explicit group addres
assert.equal(groupMessage.kind, 'group');
assert.equal(groupMessage.addressed, true);
assert.equal(groupMessage.content, 'run this');
const topicOne = normalizeTelegramUpdate({
update_id: 12,
message: {
message_id: 6,
message_thread_id: 100,
chat: { id: -1001, type: 'supergroup' },
from: { id: 43, is_bot: false },
text: '@HarnessBot first topic',
entities: [{ type: 'mention', offset: 0, length: 11 }],
},
}, { botId: '123456789', username: 'HarnessBot' });
const topicTwo = normalizeTelegramUpdate({
update_id: 13,
message: {
message_id: 7,
message_thread_id: 200,
chat: { id: -1001, type: 'supergroup' },
from: { id: 43, is_bot: false },
text: '@HarnessBot second topic',
entities: [{ type: 'mention', offset: 0, length: 11 }],
},
}, { botId: '123456789', username: 'HarnessBot' });
assert.equal(topicOne.conversationId, '-1001:100');
assert.equal(topicTwo.conversationId, '-1001:200');
assert.notEqual(topicOne.conversationId, topicTwo.conversationId);
assert.equal(topicOne.replyTarget.messageThreadId, 100);
assert.equal(topicTwo.replyTarget.messageThreadId, 200);
});
test('Telegram bridge ignores unaddressed groups and streams direct replies', async () => {
@ -272,3 +324,171 @@ test('Telegram runtime validates webhook state and starts a cancellable long pol
assert.deepEqual(calls[0], { offset: -1, timeout: 0 });
await rm(directory, { recursive: true, force: true });
});
test('Telegram runtime keeps polling while a Harness question waits for its answer', async () => {
const directory = await mkdtemp(join(tmpdir(), 'dsh-im-telegram-interaction-'));
const state = await new TelegramStateStore(join(directory, 'state.json')).load();
const questionSent = deferred();
const secondPollStarted = deferred();
const answerSubmitted = deferred();
const releaseTurn = deferred();
const finalReplySent = deferred();
const pollOffsets = [];
const asked = [];
let answerUpdateDelivered = false;
let originalTurnEnded = false;
let nextOutboundMessageId = 500;
const promptUpdate = {
update_id: 10,
message: {
message_id: 100,
chat: { id: 42, type: 'private' },
from: { id: 7, is_bot: false },
text: '请先询问测试环境',
},
};
const answerUpdate = {
update_id: 11,
message: {
message_id: 101,
chat: { id: 42, type: 'private' },
from: { id: 7, is_bot: false },
text: '2',
},
};
const fakeApi = {
getMe: async () => ({ id: 123456789, is_bot: true }),
getWebhookInfo: async () => ({ url: '' }),
getUpdates: async ({ offset, timeout, signal }) => {
pollOffsets.push(offset);
if (timeout === 0) return [];
if (offset === 0) return [promptUpdate];
if (offset === 11) {
secondPollStarted.resolve(originalTurnEnded);
await questionSent.promise;
answerUpdateDelivered = true;
return [answerUpdate];
}
assert.equal(offset, 12);
return new Promise((resolve, reject) => {
if (signal.aborted) {
reject(signal.reason);
return;
}
signal.addEventListener('abort', () => reject(signal.reason), { once: true });
});
},
sendChatAction: async () => true,
sendMessage: async ({ text }) => {
const messageId = nextOutboundMessageId;
nextOutboundMessageId += 1;
if (text.includes('请选择测试环境')) questionSent.resolve();
return { message_id: messageId };
},
editMessageText: async ({ text }) => {
if (text === '已选择生产环境') finalReplySent.resolve();
return true;
},
};
const harness = {
ensureRunning: async () => true,
createSession: async () => 'session-runtime-interaction',
ask: async (sessionId, text, options) => {
asked.push({ sessionId, text });
if (text !== '请先询问测试环境') return '不应将答案当成新 prompt';
await options.onInteraction({
kind: 'question',
interactionId: 'telegram-runtime-question',
rpcId: 'telegram-runtime-question',
sessionId,
payload: {
type: 'question/requested',
sessionId,
questions: [{
id: 'environment',
question: '请选择测试环境',
options: [{ label: '测试环境' }, { label: '生产环境' }],
}],
},
respond: async (result) => {
assert.equal(answerUpdateDelivered, true);
assert.equal(originalTurnEnded, false);
answerSubmitted.resolve(result);
return { accepted: true };
},
});
await Promise.race([
answerSubmitted.promise,
new Promise((_, reject) => {
options.signal.addEventListener('abort', () => reject(options.signal.reason), {
once: true,
});
}),
]);
await releaseTurn.promise;
originalTurnEnded = true;
return '已选择生产环境';
},
};
const runtime = new TelegramRuntime({
config: {
botId: 'telegram_interaction',
platformId: '123456789',
username: 'HarnessBot',
},
token: TOKEN,
harness,
state,
createApi: () => fakeApi,
logger: { error() {}, warn() {} },
});
try {
await runtime.start();
assert.equal(await bounded(
secondPollStarted.promise,
'poller did not request the answer update while the first turn was active',
), false);
const submitted = await bounded(
answerSubmitted.promise,
'the Telegram answer was not submitted through the interaction fast path',
);
assert.deepEqual(submitted, {
ok: true,
value: {
sessionId: 'session-runtime-interaction',
answer: {
answers: [{ id: 'environment', selected: ['生产环境'] }],
},
},
});
assert.equal(originalTurnEnded, false);
assert.deepEqual(asked, [{
sessionId: 'session-runtime-interaction',
text: '请先询问测试环境',
}]);
await bounded((async () => {
while (state.cursor() !== 12) {
await new Promise((resolve) => setTimeout(resolve, 5));
}
})(), 'Telegram cursor did not advance past the answer update');
assert.deepEqual(pollOffsets.slice(0, 4), [-1, 0, 11, 12]);
assert.equal(state.hasSeen('10'), true);
assert.equal(state.hasSeen('11'), true);
releaseTurn.resolve();
await bounded(finalReplySent.promise, 'the original Harness turn did not finish');
await new Promise((resolve) => setTimeout(resolve, 20));
assert.equal(originalTurnEnded, true);
assert.deepEqual(asked, [{
sessionId: 'session-runtime-interaction',
text: '请先询问测试环境',
}]);
} finally {
releaseTurn.resolve();
await runtime.stop();
await rm(directory, { recursive: true, force: true });
}
});

View file

@ -30,6 +30,67 @@ function state() {
};
}
function deferred() {
let resolve;
let reject;
const promise = new Promise((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
return { promise, resolve, reject };
}
async function eventually(predicate, timeoutMs = 1_000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (predicate()) return;
await new Promise((resolve) => setTimeout(resolve, 1));
}
throw new Error('condition did not become true');
}
function testClient() {
const streamed = [];
const active = [];
return {
streamed,
active,
client: {
replyStream: async (source, streamId, content, finish) => {
streamed.push({ messageId: source.body.msgid, streamId, content, finish });
},
replyStreamNonBlocking: async (source, streamId, content, finish) => {
streamed.push({ messageId: source.body.msgid, streamId, content, finish });
},
sendMessage: async (chatId, body) => active.push({ chatId, body }),
},
};
}
function questionInteraction({
interactionId = 'question-1',
sessionId = 'session-existing',
questions = [{
id: 'environment',
question: '请选择测试环境',
options: [{ label: '测试环境' }, { label: '生产环境' }],
}],
recovered = false,
respond = async () => {},
reconnect = () => {},
} = {}) {
return {
kind: 'question',
interactionId,
rpcId: interactionId,
sessionId,
payload: { questions },
recovered,
respond,
reconnect,
};
}
test('Enterprise WeChat messages stream Harness progress and finalize once', async () => {
const replies = [];
const active = [];
@ -109,3 +170,625 @@ test('Enterprise WeChat finalizes an existing progress stream when Harness fails
]);
assert.equal(store.seen.has('msg-1'), true);
});
test('an Enterprise WeChat answer bypasses the original conversation queue', async () => {
const transport = testClient();
const answered = deferred();
const responses = [];
const bridge = new WecomHarnessBridge({
client: transport.client,
generateStreamId: (() => { let index = 0; return () => `stream-${++index}`; })(),
harness: {
sessionExists: async () => true,
ask: async (_sessionId, _text, options) => {
await options.onInteraction(questionInteraction({
respond: async (result) => {
responses.push(result);
answered.resolve();
},
}));
await answered.promise;
return '你选择了:测试环境';
},
},
state: state(),
});
const prompt = bridge.accept(frame({ msgid: 'question-start' }));
await eventually(() => transport.active.some(({ body }) => (
body.markdown.content.includes('请选择测试环境')
)));
const answer = bridge.accept(frame({
msgid: 'question-answer',
text: { content: '1' },
}));
await Promise.all([prompt, answer]);
assert.deepEqual(responses, [{
ok: true,
value: {
sessionId: 'session-existing',
answer: { answers: [{ id: 'environment', selected: ['测试环境'] }] },
},
}]);
assert.equal(transport.streamed.at(-1).content, '你选择了:测试环境');
assert.equal(transport.streamed.at(-1).finish, true);
});
test('an answer waits for the first Enterprise WeChat question delivery acknowledgement', async () => {
const questionSendStarted = deferred();
const questionAcknowledged = deferred();
const answered = deferred();
const streamed = [];
const active = [];
const prompts = [];
const responses = [];
const bridge = new WecomHarnessBridge({
client: {
replyStream: async (source, streamId, content, finish) => {
streamed.push({ messageId: source.body.msgid, streamId, content, finish });
},
sendMessage: async (chatId, body) => {
active.push({ chatId, body });
questionSendStarted.resolve();
await questionAcknowledged.promise;
},
},
generateStreamId: (() => { let index = 0; return () => `first-ack-${++index}`; })(),
harness: {
sessionExists: async () => true,
ask: async (_sessionId, text, options) => {
prompts.push(text);
await options.onInteraction(questionInteraction({
interactionId: 'first-ack-question',
respond: async (result) => {
responses.push(result);
answered.resolve();
},
}));
await answered.promise;
return '首问回答完成';
},
},
state: state(),
});
const prompt = bridge.accept(frame({ msgid: 'first-ack-start' }));
await questionSendStarted.promise;
let answerSettled = false;
const answer = bridge.accept(frame({
msgid: 'first-ack-answer',
text: { content: '1' },
}));
answer.then(
() => { answerSettled = true; },
() => { answerSettled = true; },
);
await new Promise((resolve) => setImmediate(resolve));
assert.equal(answerSettled, false);
assert.equal(active.length, 1);
assert.deepEqual(responses, []);
questionAcknowledged.resolve();
await eventually(() => responses.length === 1);
await Promise.all([prompt, answer]);
assert.deepEqual(prompts, ['请回答']);
assert.equal(active.length, 1);
assert.deepEqual(responses[0].value.answer.answers, [
{ id: 'environment', selected: ['测试环境'] },
]);
assert.equal(streamed.at(-1).content, '首问回答完成');
});
test('pending Enterprise WeChat questions stay isolated by conversation', async () => {
const transport = testClient();
const gates = new Map([
['ask-a', deferred()],
['ask-b', deferred()],
]);
const responses = [];
const bridge = new WecomHarnessBridge({
client: transport.client,
generateStreamId: (() => { let index = 0; return () => `isolation-${++index}`; })(),
harness: {
sessionExists: async () => true,
ask: async (_sessionId, text, options) => {
const gate = gates.get(text);
await options.onInteraction(questionInteraction({
interactionId: `question-${text}`,
respond: async (result) => {
responses.push({ text, result });
gate.resolve();
},
}));
await gate.promise;
return `done-${text}`;
},
},
state: state(),
});
const first = bridge.accept(frame({
msgid: 'isolation-a',
from: { userid: 'member-a' },
text: { content: 'ask-a' },
}));
const second = bridge.accept(frame({
msgid: 'isolation-b',
from: { userid: 'member-b' },
text: { content: 'ask-b' },
}));
await eventually(() => transport.active.filter(({ body }) => (
body.markdown.content.includes('请选择测试环境')
)).length === 2);
const answerA = bridge.accept(frame({
msgid: 'isolation-answer-a',
from: { userid: 'member-a' },
text: { content: '1' },
}));
await Promise.all([first, answerA]);
assert.deepEqual(responses.map(({ text }) => text), ['ask-a']);
const answerB = bridge.accept(frame({
msgid: 'isolation-answer-b',
from: { userid: 'member-b' },
text: { content: '2' },
}));
await Promise.all([second, answerB]);
assert.deepEqual(responses.map(({ text }) => text), ['ask-a', 'ask-b']);
assert.deepEqual(
responses[1].result.value.answer.answers,
[{ id: 'environment', selected: ['生产环境'] }],
);
});
test('question replays are deduplicated and approvals remain fail-closed', async () => {
const transport = testClient();
const answered = deferred();
let approvalResponses = 0;
let questionResponses = 0;
const bridge = new WecomHarnessBridge({
client: transport.client,
generateStreamId: () => 'replay-stream',
harness: {
sessionExists: async () => true,
ask: async (_sessionId, _text, options) => {
await options.onInteraction({
kind: 'approval',
interactionId: 'approval-1',
rpcId: 'approval-rpc-1',
sessionId: 'session-existing',
payload: { type: 'approval/requested', toolName: 'bash' },
respond: async () => { approvalResponses += 1; },
});
const interaction = questionInteraction({
interactionId: 'replayed-question',
respond: async () => {
questionResponses += 1;
answered.resolve();
},
});
await options.onInteraction(interaction);
await options.onInteraction({ ...interaction });
await answered.promise;
return 'done';
},
},
state: state(),
});
const prompt = bridge.accept(frame({ msgid: 'replay-start' }));
await eventually(() => transport.active.length === 1);
const answer = bridge.accept(frame({ msgid: 'replay-answer', text: { content: '1' } }));
await Promise.all([prompt, answer]);
assert.equal(transport.active.length, 1);
assert.equal(approvalResponses, 0);
assert.equal(questionResponses, 1);
});
test('a failed Enterprise WeChat interaction response can be retried', async () => {
const transport = testClient();
const answered = deferred();
const attempts = [];
const bridge = new WecomHarnessBridge({
client: transport.client,
generateStreamId: (() => { let index = 0; return () => `retry-${++index}`; })(),
harness: {
sessionExists: async () => true,
ask: async (_sessionId, _text, options) => {
await options.onInteraction(questionInteraction({
respond: async (result) => {
attempts.push(structuredClone(result.value.answer.answers));
if (attempts.length === 1) throw new Error('temporary response failure');
answered.resolve();
},
}));
await answered.promise;
return 'retry complete';
},
},
state: state(),
logger: { error() {} },
});
const prompt = bridge.accept(frame({ msgid: 'retry-start' }));
await eventually(() => transport.active.length === 1);
await bridge.accept(frame({ msgid: 'retry-first', text: { content: '1' } }));
assert.equal(transport.streamed.some(({ content }) => content.includes('回答提交失败')), true);
const second = bridge.accept(frame({ msgid: 'retry-second', text: { content: '2' } }));
await Promise.all([prompt, second]);
assert.deepEqual(attempts, [
[{ id: 'environment', selected: ['测试环境'] }],
[{ id: 'environment', selected: ['生产环境'] }],
]);
});
test('an externally resolved Enterprise WeChat answer is not submitted as a new prompt', async () => {
const transport = testClient();
const resolved = deferred();
let interactionOptions;
const prompts = [];
const bridge = new WecomHarnessBridge({
client: transport.client,
generateStreamId: (() => { let index = 0; return () => `resolved-${++index}`; })(),
harness: {
sessionExists: async () => true,
ask: async (_sessionId, text, options) => {
prompts.push(text);
interactionOptions = options;
await options.onInteraction(questionInteraction({ interactionId: 'resolved-question' }));
await resolved.promise;
return '外部客户端已处理';
},
},
state: state(),
});
const prompt = bridge.accept(frame({ msgid: 'resolved-start' }));
await eventually(() => transport.active.length === 1 && interactionOptions);
const lateAnswer = bridge.accept(frame({
msgid: 'resolved-answer',
text: { content: '1' },
}));
interactionOptions.onInteractionResolved({
kind: 'question',
interactionId: 'resolved-question',
});
resolved.resolve();
await Promise.all([prompt, lateAnswer]);
assert.deepEqual(prompts, ['请回答']);
assert.equal(transport.streamed.some(({ messageId, content }) => (
messageId === 'resolved-answer' && content === '这个问题已在其他客户端处理,无需再次回答。'
)), true);
});
test('an Enterprise WeChat answer reports resolution when respond loses an in-flight race', async () => {
const transport = testClient();
const responseStarted = deferred();
const releaseResponse = deferred();
const turnResolved = deferred();
const prompts = [];
let interactionOptions;
const bridge = new WecomHarnessBridge({
client: transport.client,
generateStreamId: (() => { let index = 0; return () => `respond-race-${++index}`; })(),
harness: {
sessionExists: async () => true,
ask: async (_sessionId, text, options) => {
prompts.push(text);
interactionOptions = options;
await options.onInteraction(questionInteraction({
interactionId: 'respond-race-question',
respond: async () => {
responseStarted.resolve();
await releaseResponse.promise;
const error = new Error('interaction resolved elsewhere');
error.code = 'interaction-not-pending';
throw error;
},
}));
await turnResolved.promise;
return '外部客户端已完成';
},
},
state: state(),
});
const prompt = bridge.accept(frame({ msgid: 'respond-race-start' }));
await eventually(() => transport.active.length === 1 && interactionOptions);
const answer = bridge.accept(frame({
msgid: 'respond-race-answer',
text: { content: '1' },
}));
await responseStarted.promise;
interactionOptions.onInteractionResolved({
kind: 'question',
interactionId: 'respond-race-question',
});
turnResolved.resolve();
releaseResponse.resolve();
await Promise.all([prompt, answer]);
assert.deepEqual(prompts, ['请回答']);
assert.equal(transport.streamed.filter(({ messageId, content }) => (
messageId === 'respond-race-answer'
&& content === '这个问题已在其他客户端处理,无需再次回答。'
)).length, 1);
});
test('a recovered orphan question is cancelled without exposing its content', async () => {
const transport = testClient();
const responses = [];
const bridge = new WecomHarnessBridge({
client: transport.client,
generateStreamId: () => 'orphan-stream',
harness: {
sessionExists: async () => true,
ask: async (_sessionId, _text, options) => {
await options.onInteraction(questionInteraction({
recovered: true,
questions: [{ id: 'secret', question: '不应显示的旧问题' }],
respond: async (result) => responses.push(result),
}));
return '新消息继续完成';
},
},
state: state(),
});
await bridge.accept(frame({ msgid: 'orphan-start' }));
assert.equal(responses[0].ok, false);
assert.equal(responses[0].error.code, 'cancelled');
assert.equal(transport.active.some(({ body }) => (
body.markdown.content.includes('不应显示的旧问题')
)), false);
assert.equal(transport.active.some(({ body }) => (
body.markdown.content.includes('遗留的待回答问题')
)), true);
});
test('multi-question Enterprise WeChat interactions preserve canonical answer order', async () => {
const transport = testClient();
const answered = deferred();
let submitted;
const questions = [
{
id: 'environment',
question: '请选择环境',
options: [{ label: '测试环境' }, { label: '生产环境' }],
},
{
id: 'features',
question: '请选择功能',
multiSelect: true,
options: [{ label: '日志' }, { label: '指标' }],
},
];
const bridge = new WecomHarnessBridge({
client: transport.client,
generateStreamId: (() => { let index = 0; return () => `batch-${++index}`; })(),
harness: {
sessionExists: async () => true,
ask: async (_sessionId, _text, options) => {
await options.onInteraction(questionInteraction({
interactionId: 'batch-question',
questions,
respond: async (result) => {
submitted = result;
answered.resolve();
},
}));
await answered.promise;
return 'batch complete';
},
},
state: state(),
});
const prompt = bridge.accept(frame({ msgid: 'batch-start' }));
await eventually(() => transport.active.length === 1);
await bridge.accept(frame({ msgid: 'batch-first', text: { content: '2' } }));
await eventually(() => transport.active.length === 2);
const second = bridge.accept(frame({
msgid: 'batch-second',
text: { content: '1, 指标, 自定义' },
}));
await Promise.all([prompt, second]);
assert.deepEqual(submitted.value.answer.answers, [
{ id: 'environment', selected: ['生产环境'] },
{ id: 'features', selected: ['日志', '指标'], custom: '自定义' },
]);
});
test('a second answer stays claimed while its Enterprise WeChat question awaits acknowledgement', async () => {
const secondQuestionStarted = deferred();
const secondQuestionAcknowledged = deferred();
const turnResolved = deferred();
const streamed = [];
const active = [];
const prompts = [];
let interactionOptions;
let responseCalls = 0;
const bridge = new WecomHarnessBridge({
client: {
replyStream: async (source, streamId, content, finish) => {
streamed.push({ messageId: source.body.msgid, streamId, content, finish });
},
sendMessage: async (chatId, body) => {
active.push({ chatId, body });
if (body.markdown.content.includes('请选择功能')) {
secondQuestionStarted.resolve();
await secondQuestionAcknowledged.promise;
}
},
},
generateStreamId: (() => { let index = 0; return () => `second-ack-${++index}`; })(),
harness: {
sessionExists: async () => true,
ask: async (_sessionId, text, options) => {
prompts.push(text);
interactionOptions = options;
await options.onInteraction(questionInteraction({
interactionId: 'second-ack-question',
questions: [
{
id: 'environment',
question: '请选择环境',
options: [{ label: '测试环境' }, { label: '生产环境' }],
},
{
id: 'features',
question: '请选择功能',
options: [{ label: '日志' }, { label: '指标' }],
},
],
respond: async () => { responseCalls += 1; },
}));
await turnResolved.promise;
return '外部客户端已处理多问';
},
},
state: state(),
});
const prompt = bridge.accept(frame({ msgid: 'second-ack-start' }));
await eventually(() => active.some(({ body }) => body.markdown.content.includes('请选择环境')));
const firstAnswer = bridge.accept(frame({
msgid: 'second-ack-first',
text: { content: '1' },
}));
await secondQuestionStarted.promise;
const secondAnswer = bridge.accept(frame({
msgid: 'second-ack-answer',
text: { content: '2' },
}));
interactionOptions.onInteractionResolved({
kind: 'question',
interactionId: 'second-ack-question',
});
turnResolved.resolve();
secondQuestionAcknowledged.resolve();
await Promise.all([prompt, firstAnswer, secondAnswer]);
assert.deepEqual(prompts, ['请回答']);
assert.equal(responseCalls, 0);
assert.equal(streamed.filter(({ messageId, content }) => (
messageId === 'second-ack-answer'
&& content === '这个问题已在其他客户端处理,无需再次回答。'
)).length, 1);
});
test('only the initiating actor can answer an Enterprise WeChat group question', async () => {
const transport = testClient();
const answered = deferred();
const order = [];
let groupResponse;
const bridge = new WecomHarnessBridge({
client: transport.client,
generateStreamId: (() => { let index = 0; return () => `group-${++index}`; })(),
harness: {
sessionExists: async () => true,
ask: async (_sessionId, text, options) => {
if (text !== '启动问题') {
order.push(`normal:${text}`);
return '普通消息完成';
}
await options.onInteraction(questionInteraction({
interactionId: 'group-question',
respond: async (result) => {
groupResponse = result;
order.push('answered');
answered.resolve();
},
}));
await answered.promise;
return '问题完成';
},
},
state: state(),
});
const prompt = bridge.accept(frame({
msgid: 'group-start',
chattype: 'group',
chatid: 'group-1',
from: { userid: 'member-a' },
text: { content: '@RobotA 启动问题' },
}));
await eventually(() => transport.active.some(({ chatId }) => chatId === 'group-1'));
assert.match(
transport.active.find(({ chatId }) => chatId === 'group-1').body.markdown.content,
/群聊中请 @机器人 后发送答案/,
);
const outsider = bridge.accept(frame({
msgid: 'group-outsider',
chattype: 'group',
chatid: 'group-1',
from: { userid: 'member-b' },
text: { content: '@RobotA 1' },
}));
await new Promise((resolve) => setImmediate(resolve));
assert.deepEqual(order, []);
const actor = bridge.accept(frame({
msgid: 'group-actor',
chattype: 'group',
chatid: 'group-1',
from: { userid: 'member-a' },
text: { content: '@RobotA 2' },
}));
await Promise.all([prompt, actor, outsider]);
assert.deepEqual(order, ['answered', 'normal:1']);
assert.deepEqual(groupResponse.value.answer.answers, [
{ id: 'environment', selected: ['生产环境'] },
]);
});
test('aborting Enterprise WeChat work cancels its pending question without a failure reply', async () => {
const transport = testClient();
const controller = new AbortController();
const cancellations = [];
const bridge = new WecomHarnessBridge({
client: transport.client,
generateStreamId: () => 'abort-stream',
signal: controller.signal,
harness: {
sessionExists: async () => true,
ask: async (_sessionId, _text, options) => {
assert.equal(options.signal, controller.signal);
await options.onInteraction(questionInteraction({
interactionId: 'abort-question',
respond: async (result, responseOptions) => {
cancellations.push({ result, responseOptions });
},
}));
await new Promise((resolve, reject) => {
if (options.signal.aborted) reject(options.signal.reason);
else options.signal.addEventListener('abort', () => reject(options.signal.reason), { once: true });
});
return 'unreachable';
},
},
state: state(),
});
const prompt = bridge.accept(frame({ msgid: 'abort-start' }));
await eventually(() => transport.active.length === 1);
controller.abort(new DOMException('runtime stopped', 'AbortError'));
await prompt;
assert.equal(cancellations.length, 1);
assert.equal(cancellations[0].result.ok, false);
assert.equal(cancellations[0].result.error.code, 'cancelled');
assert.equal(cancellations[0].responseOptions.signal.aborted, false);
assert.equal(transport.streamed.some(({ content }) => content === '消息处理失败,请稍后重试。'), false);
});

View file

@ -4,6 +4,12 @@ import test from 'node:test';
import { WecomRuntime } from '../../../src/channels/wecom/wecom-runtime.mjs';
function deferred() {
let resolve;
const promise = new Promise((done) => { resolve = done; });
return { promise, resolve };
}
class FakeClient extends EventEmitter {
disconnected = false;
connect() { queueMicrotask(() => this.emit('authenticated')); }
@ -78,3 +84,50 @@ test('Enterprise WeChat runtime stop cancels an in-flight authentication wait',
assert.equal(client.disconnected, true);
assert.equal(runtime.status.wecomConnectionState, 'idle');
});
test('Enterprise WeChat runtime aborts an in-flight Harness interaction when stopped', async () => {
const client = new FakeClient();
const askStarted = deferred();
let askSignal;
const runtime = new WecomRuntime({
config: { botId: 'wecom_bot', remoteBotId: 'remote-bot' },
secret: 'private-secret',
harness: {
ensureRunning: async () => true,
sessionExists: async () => true,
ask: async (_sessionId, _text, options) => {
askSignal = options.signal;
askStarted.resolve();
await new Promise((_resolve, reject) => options.signal.addEventListener('abort', () => {
reject(options.signal.reason);
}, { once: true }));
},
},
state: {
hasSeen: () => false,
markSeen: async () => {},
sessionFor: () => 'session-existing',
setSession: async () => {},
clearSession: async () => {},
},
createClient: () => client,
connectTimeoutMs: 100,
logger: { error() {}, warn() {} },
});
await runtime.start();
client.emit('message', {
headers: { req_id: 'req-interaction' },
body: {
msgid: 'msg-interaction',
chattype: 'single',
from: { userid: 'member-1' },
msgtype: 'text',
text: { content: '需要交互' },
},
});
await askStarted.promise;
assert.equal(askSignal.aborted, false);
await runtime.stop();
assert.equal(askSignal.aborted, true);
});

View file

@ -1,7 +1,49 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { DiscordHarnessClient } from '../../../src/channels/discord/harness-client.mjs';
import { QqHarnessClient } from '../../../src/channels/qq/harness-client.mjs';
import { SlackHarnessClient } from '../../../src/channels/slack/harness-client.mjs';
import { TelegramHarnessClient } from '../../../src/channels/telegram/harness-client.mjs';
import { WecomHarnessClient } from '../../../src/channels/wecom/harness-client.mjs';
import { HarnessClient, HarnessReplyTracker } from '../../../src/channels/weixin/harness-client.mjs';
import { WhatsappHarnessClient } from '../../../src/channels/whatsapp/harness-client.mjs';
test('all legacy channel clients now use the shared Harness RPC transport', async () => {
const channelClients = [
[HarnessClient, 'weixin'],
[WecomHarnessClient, 'wecom'],
[QqHarnessClient, 'qq'],
[SlackHarnessClient, 'slack'],
[DiscordHarnessClient, 'discord'],
[TelegramHarnessClient, 'telegram'],
[WhatsappHarnessClient, 'whatsapp'],
];
for (const [Client, prefix] of channelClients) {
let request;
const client = new Client({
baseUrl: 'http://127.0.0.1:3080',
workspace: '/tmp/default-workspace',
fetchImpl: async (url, options) => {
request = { url: String(url), ...options, body: JSON.parse(options.body) };
return {
ok: true,
json: async () => ({
type: 'server-response',
rpcId: request.body.rpcId,
result: { ok: true, value: { ready: true } },
}),
};
},
});
assert.deepEqual(await client.rpc('host.describe'), { ready: true });
assert.equal(request.url, 'http://127.0.0.1:3080/api/host.describe');
assert.match(request.body.rpcId, new RegExp(`^${prefix}-`));
assert.equal(request.body.type, 'client-request');
}
});
test('HarnessClient lists only absolute workspace paths', async () => {
const client = new HarnessClient({

View file

@ -3,6 +3,39 @@ import test from 'node:test';
import { createWeixinBridgeStatus, WeixinHarnessBridge } from '../../../src/channels/weixin/weixin-bridge.mjs';
function deferred() {
let resolve;
let reject;
const promise = new Promise((promiseResolve, promiseReject) => {
resolve = promiseResolve;
reject = promiseReject;
});
return { promise, resolve, reject };
}
async function eventually(predicate, messageText = 'condition was not met') {
const deadline = Date.now() + 1_000;
while (Date.now() < deadline) {
if (predicate()) return;
await new Promise((resolve) => setTimeout(resolve, 5));
}
assert.fail(messageText);
}
async function within(promise, milliseconds, messageText) {
let timer;
try {
return await Promise.race([
promise,
new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(messageText)), milliseconds);
}),
]);
} finally {
clearTimeout(timer);
}
}
function message(id, text, overrides = {}) {
return {
message_id: id,
@ -68,6 +101,698 @@ test('bridge maps the scanning Weixin user to one persistent Harness session and
assert.equal(status.messagesReplied, 2);
});
test('Weixin answers a multi-question interaction before the original turn queue', async () => {
const fixture = stateFixture();
fixture.sessions.set('p2p:owner-user', 'session-question');
const sent = [];
const asked = [];
const submitted = deferred();
const secondQuestionDelivered = deferred();
const releaseSecondQuestion = deferred();
const bridge = new WeixinHarnessBridge({
api: {
sendText: async (request) => {
sent.push(request);
if (request.text.includes('选择交付物')) {
secondQuestionDelivered.resolve();
await releaseSecondQuestion.promise;
}
},
},
baseUrl: 'https://ilinkai.weixin.qq.com/',
token: 'host-token',
ownerUserId: 'owner-user',
harness: {
sessionExists: async () => true,
createSession: async () => assert.fail('the existing session should be reused'),
ask: async (sessionId, text, options) => {
asked.push(text);
await options.onInteraction({
kind: 'question',
interactionId: 'weixin-multi',
rpcId: 'weixin-multi',
sessionId,
payload: {
type: 'question/requested',
sessionId,
questions: [
{
id: 'language',
question: '选择语言',
options: [{ label: '中文' }, { label: 'English' }],
},
{
id: 'deliverables',
question: '选择交付物',
multiSelect: true,
options: [{ label: '测试' }, { label: '文档' }],
},
],
},
respond: async (result) => {
submitted.resolve(result);
return { accepted: true };
},
});
await submitted.promise;
return '交互完成';
},
},
state: fixture.state,
});
const first = bridge.accept(message('multi-start', '请分步提问'));
await eventually(() => sent.some(({ text }) => text.includes('选择语言')));
const firstAnswer = bridge.accept(message('multi-language', '2'));
await secondQuestionDelivered.promise;
const secondAnswer = bridge.accept(message('multi-deliverables', '1,文档,发布说明'));
releaseSecondQuestion.resolve();
await within(
Promise.all([firstAnswer, secondAnswer]),
500,
'the second Weixin answer deadlocked behind delivery of the second question',
);
assert.deepEqual(await submitted.promise, {
ok: true,
value: {
sessionId: 'session-question',
answer: {
answers: [
{ id: 'language', selected: ['English'] },
{ id: 'deliverables', selected: ['测试', '文档'], custom: '发布说明' },
],
},
},
});
await first;
assert.deepEqual(asked, ['请分步提问']);
assert.equal(sent.at(-1).text, '交互完成');
assert.equal(sent.find(({ text }) => text.includes('选择交付物')).contextToken, 'context-multi-language');
});
test('Weixin deduplicates question replays, rejects parallel questions, and keeps approvals fail-closed', async () => {
const fixture = stateFixture();
const sent = [];
let approvalResponses = 0;
let parallelResponse;
let orphanResponse;
const bridge = new WeixinHarnessBridge({
api: { sendText: async (request) => sent.push(request) },
baseUrl: 'https://ilinkai.weixin.qq.com/',
token: 'host-token',
ownerUserId: 'owner-user',
harness: {
sessionExists: async () => false,
createSession: async () => 'session-replay',
ask: async (sessionId, _text, options) => {
const replayedQuestion = {
kind: 'question',
interactionId: 'weixin-replayed-question',
rpcId: 'weixin-replayed-question',
sessionId,
payload: {
type: 'question/requested',
sessionId,
questions: [{ id: 'choice', question: '只应显示一次' }],
},
respond: async () => ({ accepted: true }),
};
await options.onInteraction(replayedQuestion);
await options.onInteraction(replayedQuestion);
await options.onInteraction({
kind: 'question',
interactionId: 'weixin-parallel-question',
rpcId: 'weixin-parallel-question',
sessionId,
payload: {
type: 'question/requested',
sessionId,
questions: [{ id: 'parallel', question: '不应展示的并行问题' }],
},
respond: async (result) => {
parallelResponse = result;
return { accepted: true };
},
});
await options.onInteraction({
kind: 'approval',
interactionId: 'weixin-approval',
rpcId: 'weixin-approval',
sessionId,
payload: {
type: 'approval/requested',
sessionId,
approvalId: 'weixin-approval',
toolName: 'bash',
},
respond: async () => { approvalResponses += 1; },
});
await options.onInteractionResolved({
kind: 'question',
interactionId: 'weixin-replayed-question',
sessionId,
outcome: 'cancelled',
});
await options.onInteraction({
kind: 'question',
interactionId: 'weixin-orphan-question',
rpcId: 'weixin-orphan-question',
sessionId,
recovered: true,
payload: {
type: 'question/requested',
sessionId,
questions: [{ id: 'secret', question: '旧会话中的敏感问题内容' }],
},
respond: async (result) => {
orphanResponse = result;
return { accepted: true };
},
});
return '交互恢复完成';
},
},
state: fixture.state,
logger: { warn() {}, error() {} },
});
await bridge.accept(message('replay', '测试交互重放'));
assert.equal(sent.filter(({ text }) => text.includes('只应显示一次')).length, 1);
assert.deepEqual(parallelResponse, {
ok: false,
error: {
code: 'cancelled',
message: 'Weixin is already handling another user interaction.',
details: {},
},
});
assert.equal(approvalResponses, 0);
assert.equal(sent.some(({ text }) => text.includes('approval')), false);
assert.deepEqual(orphanResponse, {
ok: false,
error: {
code: 'cancelled',
message: 'Weixin safely cancelled an interaction left by an earlier client.',
details: {},
},
});
assert.equal(sent.some(({ text }) => text.includes('旧会话中的敏感问题内容')), false);
assert.equal(sent.some(({ text }) => text.includes('遗留的待回答问题')), true);
assert.equal(sent.at(-1).text, '交互恢复完成');
});
test('Weixin keeps a queued prompt separate while a failed interaction answer is retried', async () => {
const fixture = stateFixture();
fixture.sessions.set('p2p:owner-user', 'session-submit-retry');
const sent = [];
const asked = [];
const firstSubmitStarted = deferred();
const releaseFirstSubmit = deferred();
const answered = deferred();
const submittedAnswers = [];
let submitAttempts = 0;
const bridge = new WeixinHarnessBridge({
api: { sendText: async (request) => sent.push(request) },
baseUrl: 'https://ilinkai.weixin.qq.com/',
token: 'host-token',
ownerUserId: 'owner-user',
harness: {
sessionExists: async () => true,
createSession: async () => assert.fail('the existing session should be reused'),
ask: async (sessionId, text, options) => {
asked.push(text);
if (text === '排队的下一个问题') return '第二轮完成';
await options.onInteraction({
kind: 'question',
interactionId: 'weixin-submit-retry',
rpcId: 'weixin-submit-retry',
sessionId,
payload: {
type: 'question/requested',
sessionId,
questions: [{ id: 'answer', question: '请回答后再继续' }],
},
respond: async (result) => {
submittedAnswers.push(result.value.answer.answers[0].custom);
submitAttempts += 1;
if (submitAttempts === 1) {
firstSubmitStarted.resolve();
await releaseFirstSubmit.promise;
throw new Error('temporary response failure');
}
answered.resolve();
return { accepted: true };
},
});
await answered.promise;
return '第一轮完成';
},
},
state: fixture.state,
logger: { warn() {}, error() {} },
});
const first = bridge.accept(message('retry-start', '启动可重试交互'));
await eventually(() => sent.some(({ text }) => text.includes('请回答后再继续')));
const firstAnswer = bridge.accept(message('retry-first-answer', '第一次答案'));
await firstSubmitStarted.promise;
let nextSettled = false;
const next = bridge.accept(message('retry-next', '排队的下一个问题'))
.finally(() => { nextSettled = true; });
releaseFirstSubmit.resolve();
await firstAnswer;
await eventually(() => sent.some(({ text }) => text.includes('回答提交失败')));
assert.equal(nextSettled, false);
assert.deepEqual(asked, ['启动可重试交互']);
await Promise.all([
bridge.accept(message('retry-second-answer', '重试后的答案')),
first,
next,
]);
assert.deepEqual(submittedAnswers, ['第一次答案', '重试后的答案']);
assert.deepEqual(asked, ['启动可重试交互', '排队的下一个问题']);
assert.deepEqual(sent.slice(-2).map(({ text }) => text), ['第一轮完成', '第二轮完成']);
});
test('Weixin serializes an invalid pending reply before the following valid answer', async () => {
const fixture = stateFixture();
fixture.sessions.set('p2p:owner-user', 'session-invalid-answer');
const sent = [];
const invalidNoticeStarted = deferred();
const releaseInvalidNotice = deferred();
const answered = deferred();
let submitted;
const bridge = new WeixinHarnessBridge({
api: {
sendText: async (request) => {
if (request.text === '请用文字回答当前问题。') {
invalidNoticeStarted.resolve();
await releaseInvalidNotice.promise;
}
sent.push(request);
},
},
baseUrl: 'https://ilinkai.weixin.qq.com/',
token: 'host-token',
ownerUserId: 'owner-user',
harness: {
sessionExists: async () => true,
createSession: async () => assert.fail('the existing session should be reused'),
ask: async (sessionId, _text, options) => {
await options.onInteraction({
kind: 'question',
interactionId: 'weixin-invalid-answer',
rpcId: 'weixin-invalid-answer',
sessionId,
payload: {
type: 'question/requested',
sessionId,
questions: [{ id: 'answer', question: '请给出有效文字答案' }],
},
respond: async (result) => {
submitted = result;
answered.resolve();
return { accepted: true };
},
});
await answered.promise;
return '有效答案已收到';
},
},
state: fixture.state,
});
const first = bridge.accept(message('invalid-start', '启动交互'));
await eventually(() => sent.some(({ text }) => text.includes('请给出有效文字答案')));
const invalid = bridge.accept(message('invalid-image', '', {
message_type: 3,
item_list: [{ type: 2 }],
}));
await invalidNoticeStarted.promise;
const valid = bridge.accept(message('invalid-valid', '真正的答案'));
releaseInvalidNotice.resolve();
await Promise.all([invalid, valid, first]);
assert.deepEqual(submitted.value.answer.answers, [{
id: 'answer',
selected: [],
custom: '真正的答案',
}]);
assert.equal(sent.at(-1).text, '有效答案已收到');
});
test('Weixin discards an already-claimed answer when the interaction resolves elsewhere', async () => {
const fixture = stateFixture();
fixture.sessions.set('p2p:owner-user', 'session-resolved-race');
const originalMarkSeen = fixture.state.markSeen;
const answerMarkStarted = deferred();
const releaseAnswerMark = deferred();
fixture.state.markSeen = async (id) => {
if (id === 'resolved-answer') {
answerMarkStarted.resolve();
await releaseAnswerMark.promise;
}
await originalMarkSeen(id);
};
const sent = [];
const asked = [];
const resolved = deferred();
let resolveInteraction;
const bridge = new WeixinHarnessBridge({
api: { sendText: async (request) => sent.push(request) },
baseUrl: 'https://ilinkai.weixin.qq.com/',
token: 'host-token',
ownerUserId: 'owner-user',
harness: {
sessionExists: async () => true,
createSession: async () => assert.fail('the existing session should be reused'),
ask: async (sessionId, text, options) => {
asked.push(text);
if (text === '后来的普通问题') return '后来问题的回答';
await options.onInteraction({
kind: 'question',
interactionId: 'weixin-resolved-race',
rpcId: 'weixin-resolved-race',
sessionId,
payload: {
type: 'question/requested',
sessionId,
questions: [{ id: 'answer', question: '可能在其他客户端回答' }],
},
respond: async () => ({ accepted: true }),
});
resolveInteraction = async () => {
await options.onInteractionResolved({
kind: 'question',
interactionId: 'weixin-resolved-race',
sessionId,
outcome: 'answered',
});
resolved.resolve();
};
await resolved.promise;
return '第一轮已由其他客户端完成';
},
},
state: fixture.state,
});
const first = bridge.accept(message('resolved-start', '启动外部解决竞态'));
await eventually(() => typeof resolveInteraction === 'function');
const answer = bridge.accept(message('resolved-answer', '原本的问题答案'));
await answerMarkStarted.promise;
const later = bridge.accept(message('resolved-later', '后来的普通问题'));
await resolveInteraction();
releaseAnswerMark.resolve();
await Promise.all([answer, first, later]);
assert.deepEqual(asked, ['启动外部解决竞态', '后来的普通问题']);
assert.equal(asked.includes('原本的问题答案'), false);
assert.equal(sent.some(({ text }) => text.includes('已在其他客户端处理')), true);
});
test('Weixin keeps an answer that arrives after the first question is delivered but before its send ACK', async () => {
const fixture = stateFixture();
fixture.sessions.set('p2p:owner-user', 'session-first-delivery');
const questionDelivered = deferred();
const releaseQuestionAck = deferred();
const answered = deferred();
const sent = [];
const asked = [];
let submitted;
let questionSends = 0;
const bridge = new WeixinHarnessBridge({
api: {
sendText: async (request) => {
sent.push(request);
if (request.text.includes('首问 ACK 窗口')) {
questionSends += 1;
questionDelivered.resolve();
await releaseQuestionAck.promise;
}
},
},
baseUrl: 'https://ilinkai.weixin.qq.com/',
token: 'host-token',
ownerUserId: 'owner-user',
harness: {
sessionExists: async () => true,
ask: async (sessionId, text, options) => {
asked.push(text);
await options.onInteraction({
kind: 'question',
interactionId: 'weixin-first-delivery',
rpcId: 'weixin-first-delivery',
sessionId,
payload: {
type: 'question/requested',
sessionId,
questions: [{ id: 'answer', question: '首问 ACK 窗口' }],
},
respond: async (result) => {
submitted = result;
answered.resolve();
return { accepted: true };
},
});
await answered.promise;
return '首问已完成';
},
},
state: fixture.state,
});
const first = bridge.accept(message('first-delivery-start', '启动首问窗口'));
await questionDelivered.promise;
const answer = bridge.accept(message('first-delivery-answer', '窗口内答案'));
await new Promise((resolve) => setImmediate(resolve));
assert.equal(submitted, undefined);
releaseQuestionAck.resolve();
await Promise.all([first, answer]);
assert.equal(questionSends, 1);
assert.deepEqual(asked, ['启动首问窗口']);
assert.deepEqual(submitted.value.answer.answers, [{
id: 'answer',
selected: [],
custom: '窗口内答案',
}]);
assert.equal(fixture.seen.has('first-delivery-answer'), true);
});
test('Weixin tombstones a q2 answer accepted before its send ACK when the interaction resolves', async () => {
const fixture = stateFixture();
fixture.sessions.set('p2p:owner-user', 'session-q2-resolved');
const secondQuestionDelivered = deferred();
const releaseSecondQuestionAck = deferred();
const turnResolved = deferred();
const sent = [];
const asked = [];
let resolveInteraction;
const bridge = new WeixinHarnessBridge({
api: {
sendText: async (request) => {
sent.push(request);
if (request.text.includes('会在 ACK 前 resolved 的第二问')) {
secondQuestionDelivered.resolve();
await releaseSecondQuestionAck.promise;
}
},
},
baseUrl: 'https://ilinkai.weixin.qq.com/',
token: 'host-token',
ownerUserId: 'owner-user',
harness: {
sessionExists: async () => true,
ask: async (sessionId, text, options) => {
asked.push(text);
await options.onInteraction({
kind: 'question',
interactionId: 'weixin-q2-resolved',
rpcId: 'weixin-q2-resolved',
sessionId,
payload: {
type: 'question/requested',
sessionId,
questions: [
{ id: 'first', question: '先回答第一问' },
{ id: 'second', question: '会在 ACK 前 resolved 的第二问' },
],
},
respond: async () => assert.fail('the externally resolved interaction must not be answered'),
});
resolveInteraction = () => {
options.onInteractionResolved({
kind: 'question',
interactionId: 'weixin-q2-resolved',
sessionId,
outcome: 'answered',
});
turnResolved.resolve();
};
await turnResolved.promise;
return '已由其他客户端完成';
},
},
state: fixture.state,
});
const first = bridge.accept(message('q2-resolved-start', '启动 q2 resolved 窗口'));
await eventually(() => typeof resolveInteraction === 'function');
const firstAnswer = bridge.accept(message('q2-resolved-first', '第一问答案'));
await secondQuestionDelivered.promise;
const secondAnswer = bridge.accept(message('q2-resolved-second', '第二问答案'));
resolveInteraction();
releaseSecondQuestionAck.resolve();
await Promise.all([firstAnswer, secondAnswer, first]);
assert.deepEqual(asked, ['启动 q2 resolved 窗口']);
assert.equal(fixture.seen.has('q2-resolved-second'), true);
assert.equal(sent.some(({ text }) => text.includes('已在其他客户端处理')), true);
});
test('Weixin reports resolved when an in-flight response becomes not-pending', async () => {
const fixture = stateFixture();
fixture.sessions.set('p2p:owner-user', 'session-respond-resolved');
const responseStarted = deferred();
const releaseResponse = deferred();
const turnResolved = deferred();
const sent = [];
let resolveInteraction;
const bridge = new WeixinHarnessBridge({
api: { sendText: async (request) => sent.push(request) },
baseUrl: 'https://ilinkai.weixin.qq.com/',
token: 'host-token',
ownerUserId: 'owner-user',
harness: {
sessionExists: async () => true,
ask: async (sessionId, _text, options) => {
await options.onInteraction({
kind: 'question',
interactionId: 'weixin-respond-resolved',
rpcId: 'weixin-respond-resolved',
sessionId,
payload: {
type: 'question/requested',
sessionId,
questions: [{ id: 'answer', question: '提交中会被外部解决' }],
},
respond: async () => {
responseStarted.resolve();
await releaseResponse.promise;
const error = new Error('already resolved');
error.code = 'interaction-not-pending';
throw error;
},
});
resolveInteraction = () => {
options.onInteractionResolved({
kind: 'question',
interactionId: 'weixin-respond-resolved',
sessionId,
outcome: 'answered',
});
turnResolved.resolve();
};
await turnResolved.promise;
return '外部处理完成';
},
},
state: fixture.state,
});
const first = bridge.accept(message('respond-resolved-start', '启动提交竞态'));
await eventually(() => typeof resolveInteraction === 'function');
const answer = bridge.accept(message('respond-resolved-answer', '我的答案'));
await responseStarted.promise;
resolveInteraction();
releaseResponse.resolve();
await Promise.all([answer, first]);
assert.equal(sent.some(({ text, contextToken }) => (
contextToken === 'context-respond-resolved-answer'
&& text.includes('已在其他客户端处理')
)), true);
});
test('Weixin propagates the stop signal and cancels its pending question on abort', async () => {
const fixture = stateFixture();
fixture.sessions.set('p2p:owner-user', 'stale-session');
const controller = new AbortController();
const interactionReady = deferred();
let existsSignal;
let createSignal;
let askSignal;
let cancellation;
let cancellationSignal;
const bridge = new WeixinHarnessBridge({
api: { sendText: async () => {} },
baseUrl: 'https://ilinkai.weixin.qq.com/',
token: 'host-token',
ownerUserId: 'owner-user',
signal: controller.signal,
harness: {
sessionExists: async (_sessionId, options) => {
existsSignal = options.signal;
return false;
},
createSession: async (options) => {
createSignal = options.signal;
return 'session-abort';
},
ask: async (sessionId, _text, options) => {
askSignal = options.signal;
await options.onInteraction({
kind: 'question',
interactionId: 'weixin-abort-question',
rpcId: 'weixin-abort-question',
sessionId,
payload: {
type: 'question/requested',
sessionId,
questions: [{ id: 'answer', question: '等待进程停止' }],
},
respond: async (result, respondOptions) => {
cancellation = result;
cancellationSignal = respondOptions.signal;
return { accepted: true };
},
});
interactionReady.resolve();
await new Promise((resolve, reject) => {
options.signal.addEventListener('abort', () => reject(options.signal.reason), { once: true });
});
},
},
state: fixture.state,
logger: { warn() {}, error() {} },
});
const turn = bridge.accept(message('abort-start', '启动后停止'));
await interactionReady.promise;
controller.abort(new Error('runtime stopped'));
await turn;
assert.equal(existsSignal, controller.signal);
assert.equal(createSignal, controller.signal);
assert.equal(askSignal, controller.signal);
assert.deepEqual(cancellation, {
ok: false,
error: {
code: 'cancelled',
message: 'The Weixin interaction ended before the user answered.',
details: {},
},
});
assert.notEqual(cancellationSignal, controller.signal);
assert.equal(cancellationSignal.aborted, false);
});
test('bridge rejects every user except the account owner returned by QR login', async () => {
const fixture = stateFixture();
let asked = 0;

View file

@ -6,9 +6,54 @@ import { WeixinRuntime } from '../../../src/channels/weixin/weixin-runtime.mjs';
const flush = () => new Promise((resolve) => setImmediate(resolve));
function deferred() {
let resolve;
let reject;
const promise = new Promise((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
return { promise, resolve, reject };
}
async function eventually(predicate, message, timeoutMs = 1_000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (predicate()) return;
await new Promise((resolve) => setTimeout(resolve, 5));
}
assert.fail(message);
}
function abortable(promise, signal) {
return new Promise((resolve, reject) => {
const cleanup = () => signal?.removeEventListener('abort', onAbort);
const onAbort = () => {
cleanup();
reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
};
if (signal?.aborted) {
onAbort();
return;
}
signal?.addEventListener('abort', onAbort, { once: true });
promise.then(
(value) => {
cleanup();
resolve(value);
},
(error) => {
cleanup();
reject(error);
},
);
});
}
test('runtime verifies the token, consumes getUpdates, replies, persists cursor, and aborts on stop', async () => {
const calls = [];
let pollCount = 0;
let askSignal;
const stateData = { cursor: '', seen: new Set(), session: null };
const api = {
notifyStart: async (request) => calls.push(['start', request.token]),
@ -55,7 +100,10 @@ test('runtime verifies the token, consumes getUpdates, replies, persists cursor,
ensureRunning: async () => true,
sessionExists: async () => true,
createSession: async () => 'session-1',
ask: async () => '回答',
ask: async (_sessionId, _text, options) => {
askSignal = options.signal;
return '回答';
},
},
state,
logger: { warn() {}, error() {} },
@ -70,11 +118,149 @@ test('runtime verifies the token, consumes getUpdates, replies, persists cursor,
['start', 'bot-token'],
['send', '回答', 'context-7'],
]);
assert.equal(askSignal.aborted, false);
await runtime.stop();
assert.equal(askSignal.aborted, true);
assert.deepEqual(calls.at(-1), ['stop', 'bot-token']);
assert.equal(runtime.status.ready, false);
});
test('runtime keeps polling while a Harness interaction waits and consumes its answer in the open turn', async () => {
const questionPresented = deferred();
const answerSubmitted = deferred();
const sends = [];
const askTexts = [];
const interactionResponses = [];
const polledCursors = [];
const cursorWrites = [];
let pollCount = 0;
let turnFinished = false;
let secondPollStartedWhileTurnOpen = false;
let respondedWhileTurnOpen = false;
const stateData = { cursor: '', seen: new Set(), session: 'session-1' };
const api = {
notifyStart: async () => {},
notifyStop: async () => {},
sendText: async (request) => sends.push(request),
getUpdates: async ({ getUpdatesBuf, signal }) => {
pollCount += 1;
polledCursors.push(getUpdatesBuf);
if (pollCount === 1) {
return {
ret: 0,
get_updates_buf: 'cursor-question',
msgs: [{
message_id: 101,
message_type: 1,
from_user_id: 'owner',
context_token: 'context-question',
item_list: [{ type: 1, text_item: { text: '请调用 ask_user_question' } }],
}],
};
}
if (pollCount === 2) {
secondPollStartedWhileTurnOpen = !turnFinished;
await questionPresented.promise;
return {
ret: 0,
get_updates_buf: 'cursor-answer',
msgs: [{
message_id: 102,
message_type: 1,
from_user_id: 'owner',
context_token: 'context-answer',
item_list: [{ type: 1, text_item: { text: '1' } }],
}],
};
}
return new Promise((_resolve, reject) => {
const abort = () => reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
if (signal.aborted) abort();
else signal.addEventListener('abort', abort, { once: true });
});
},
};
const state = {
getUpdatesBuf: () => stateData.cursor,
setGetUpdatesBuf: async (value) => {
stateData.cursor = value;
cursorWrites.push(value);
},
hasSeen: (id) => stateData.seen.has(id),
markSeen: async (id) => stateData.seen.add(id),
sessionFor: () => stateData.session,
setSession: async (_key, value) => { stateData.session = value; },
clearSession: async () => { stateData.session = null; },
};
const runtime = new WeixinRuntime({
api,
config: {
botId: 'wx_interaction',
baseUrl: 'https://ilinkai.weixin.qq.com/',
ownerUserId: 'owner',
},
token: 'bot-token',
harness: {
ensureRunning: async () => true,
sessionExists: async () => true,
createSession: async () => 'session-1',
ask: async (sessionId, text, options) => {
askTexts.push(text);
await options.onInteraction({
kind: 'question',
rpcId: 'rpc-runtime-question',
interactionId: 'interaction-runtime-question',
sessionId,
payload: {
questions: [{
id: 'environment',
question: '请选择测试环境',
options: [{ label: '测试环境' }, { label: '生产环境' }],
}],
},
respond: async (response) => {
interactionResponses.push(response);
respondedWhileTurnOpen = !turnFinished;
answerSubmitted.resolve();
},
});
questionPresented.resolve();
await abortable(answerSubmitted.promise, options.signal);
turnFinished = true;
return '你选择了:测试环境';
},
},
state,
logger: { warn() {}, error() {} },
});
await runtime.start();
try {
await eventually(
() => turnFinished && stateData.seen.size === 2
&& sends.some((request) => request.text === '你选择了:测试环境'),
'the answer should resolve the original Harness turn',
);
assert.equal(secondPollStartedWhileTurnOpen, true);
assert.equal(respondedWhileTurnOpen, true);
assert.deepEqual(askTexts, ['请调用 ask_user_question']);
assert.deepEqual(interactionResponses, [{
ok: true,
value: {
sessionId: 'session-1',
answer: { answers: [{ id: 'environment', selected: ['测试环境'] }] },
},
}]);
assert.deepEqual(cursorWrites, ['cursor-question', 'cursor-answer']);
assert.deepEqual(polledCursors.slice(0, 3), ['', 'cursor-question', 'cursor-answer']);
assert.equal(stateData.cursor, 'cursor-answer');
} finally {
await runtime.stop();
}
});
test('runtime refuses to report ready when notifyStart rejects the stored token', async () => {
const runtime = new WeixinRuntime({
api: {