mirror of
https://github.com/hansjone/dsh-im-ops.git
synced 2026-10-09 04:13:17 +08:00
fix(feishu): make interactive card menus reliable
This commit is contained in:
parent
60a364118e
commit
0e62c69382
8 changed files with 232 additions and 71 deletions
82
lib/index.js
82
lib/index.js
File diff suppressed because one or more lines are too long
|
|
@ -131,7 +131,7 @@ export class FeishuHarnessBridge {
|
|||
#signal;
|
||||
/** Number-tappable menus: conversation key → menu state. */
|
||||
#menus = new Map();
|
||||
/** Interactive-card message id → { key, chatId } for button callbacks. */
|
||||
/** Interactive-card message id → route context for button callbacks. */
|
||||
#cardKeys = new Map();
|
||||
|
||||
constructor({
|
||||
|
|
@ -514,9 +514,15 @@ export class FeishuHarnessBridge {
|
|||
* session binding, workspace switches or other card actions.
|
||||
*/
|
||||
onCardAction(event) {
|
||||
const operatorOpenId = nonEmptyString(event?.operator?.operator_id?.open_id)
|
||||
const operatorOpenId = nonEmptyString(event?.operator?.open_id)
|
||||
?? nonEmptyString(event?.operator?.user_id)
|
||||
// Keep accepting the legacy nested shape while preferring the current
|
||||
// card.action.trigger v2 payload used by the official SDK.
|
||||
?? nonEmptyString(event?.operator?.operator_id?.open_id)
|
||||
?? nonEmptyString(event?.operator?.operator_id?.user_id);
|
||||
if (operatorOpenId === null || !this.#allowedSenderOpenIds.has(operatorOpenId)) {
|
||||
const operatorAllowed = operatorOpenId !== null
|
||||
&& (this.#allowedSenderOpenIds.has('*') || this.#allowedSenderOpenIds.has(operatorOpenId));
|
||||
if (!operatorAllowed) {
|
||||
this.#logger.warn?.('[dsh-feishu] ignoring card action from an unallowed sender');
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
|
@ -534,10 +540,10 @@ export class FeishuHarnessBridge {
|
|||
});
|
||||
}
|
||||
|
||||
async #handleCardAction(action, { chatId, key }) {
|
||||
async #handleCardAction(action, { chatId, key, sessionWorkspace = null }) {
|
||||
if (action === 'sessions' || /^sessions:\d+$/.test(action)) {
|
||||
const page = action === 'sessions' ? 0 : Number(action.slice('sessions:'.length));
|
||||
await this.#showSessions({ chatId, key }, null, page);
|
||||
await this.#showSessions({ chatId, key }, sessionWorkspace, page);
|
||||
return;
|
||||
}
|
||||
if (action === 'workspaces') {
|
||||
|
|
@ -635,7 +641,12 @@ export class FeishuHarnessBridge {
|
|||
kind: 'sessions',
|
||||
sessions: sessions.slice(safePage * MENU_PAGE_SIZE, (safePage + 1) * MENU_PAGE_SIZE),
|
||||
});
|
||||
await this.#sendCard(chatId, sessionListCard(workspace, sessions, safePage, sessions.length), { key });
|
||||
await this.#sendCard(chatId, sessionListCard(workspace, sessions, safePage, sessions.length), {
|
||||
key,
|
||||
// Keep the canonical selector result for later page callbacks. The
|
||||
// list response's workspace is display data and is not authoritative.
|
||||
sessionWorkspace: resolved.workspace,
|
||||
});
|
||||
} catch (error) {
|
||||
this.#logger.warn?.('[dsh-feishu] session list failed:', error.message);
|
||||
await this.#send(chatId, '暂时无法获取会话列表,请稍后重试。');
|
||||
|
|
@ -682,7 +693,13 @@ export class FeishuHarnessBridge {
|
|||
}
|
||||
const messageId = nonEmptyString(response?.data?.message_id);
|
||||
if (options.key && messageId) {
|
||||
this.#cardKeys.set(messageId, { key: options.key, chatId });
|
||||
this.#cardKeys.set(messageId, {
|
||||
key: options.key,
|
||||
chatId,
|
||||
sessionWorkspace: typeof options.sessionWorkspace === 'string' && options.sessionWorkspace
|
||||
? options.sessionWorkspace
|
||||
: null,
|
||||
});
|
||||
if (this.#cardKeys.size > 200) {
|
||||
const oldest = this.#cardKeys.keys().next().value;
|
||||
if (oldest !== undefined) this.#cardKeys.delete(oldest);
|
||||
|
|
|
|||
|
|
@ -2,13 +2,12 @@
|
|||
* Feishu interactive-card builders for the dsh-im menu / session-list /
|
||||
* workspace-list UX. All builders return the JSON string the
|
||||
* `im.message.create` API expects as `content` for `msg_type: interactive`
|
||||
* (card schema 2.0; buttons are plain body elements — the `action` container
|
||||
* is gone in V2).
|
||||
* (card schema 2.0; callback buttons live inside a column_set/column layout).
|
||||
*
|
||||
* Buttons carry a small `{ action }` value object that `card.action.trigger`
|
||||
* events echo back (when the app subscribes that event); every button also
|
||||
* carries a numeric label so the number-reply fallback stays usable without
|
||||
* button callbacks.
|
||||
* Buttons carry a small `{ action }` callback behavior that
|
||||
* `card.action.trigger` events echo back (when the app subscribes that
|
||||
* callback); every button also carries a numeric label so the number-reply
|
||||
* fallback stays usable without button callbacks.
|
||||
*/
|
||||
|
||||
export const MENU_PAGE_SIZE = 10;
|
||||
|
|
@ -23,10 +22,20 @@ function markdown(content) {
|
|||
|
||||
function button(content, actionValue) {
|
||||
return {
|
||||
tag: 'button',
|
||||
text: plainText(content),
|
||||
type: 'default',
|
||||
value: { action: actionValue },
|
||||
tag: 'column_set',
|
||||
flex_mode: 'none',
|
||||
columns: [{
|
||||
tag: 'column',
|
||||
width: 'weighted',
|
||||
weight: 1,
|
||||
elements: [{
|
||||
tag: 'button',
|
||||
text: plainText(content),
|
||||
type: 'default',
|
||||
width: 'fill',
|
||||
behaviors: [{ type: 'callback', value: { action: actionValue } }],
|
||||
}],
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -66,7 +75,7 @@ export function sessionListCard(workspace, sessions, page, total) {
|
|||
const elements = [
|
||||
{ tag: 'div', text: markdown(`**工作区**:\`${workspace}\`\n共 **${total}** 个会话${total > MENU_PAGE_SIZE ? `(第 ${page + 1}/${pageCount} 页)` : ''}`) },
|
||||
...slice.map((session, offset) => button(
|
||||
`${start + offset + 1}. ${safeTitle(session.title)}`,
|
||||
`${offset + 1}. ${safeTitle(session.title)}`,
|
||||
`use:${session.sessionId}`,
|
||||
)),
|
||||
];
|
||||
|
|
|
|||
|
|
@ -186,7 +186,8 @@ export class MultiBotDshFeishuController {
|
|||
addons: {
|
||||
preset: false,
|
||||
scopes: { tenant: [...REQUIRED_TENANT_SCOPES] },
|
||||
events: { items: { tenant: ['im.message.receive_v1', 'card.action.trigger'] } },
|
||||
events: { items: { tenant: ['im.message.receive_v1'] } },
|
||||
callbacks: { items: ['card.action.trigger'] },
|
||||
},
|
||||
});
|
||||
this.#touch();
|
||||
|
|
|
|||
|
|
@ -102,7 +102,8 @@ export class DshFeishuController {
|
|||
addons: {
|
||||
preset: false,
|
||||
scopes: { tenant: [...REQUIRED_TENANT_SCOPES] },
|
||||
events: { items: { tenant: ['im.message.receive_v1', 'card.action.trigger'] } },
|
||||
events: { items: { tenant: ['im.message.receive_v1'] } },
|
||||
callbacks: { items: ['card.action.trigger'] },
|
||||
},
|
||||
});
|
||||
return this.status();
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Readable } from 'node:stream';
|
||||
import { mkdirSync } from 'node:fs';
|
||||
import { mkdirSync, realpathSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { FeishuHarnessBridge } from '../../../src/channels/feishu/bridge.mjs';
|
||||
|
|
@ -1897,20 +1897,36 @@ function cardClient(onSend) {
|
|||
|
||||
function cardActionEvent(messageId, action, operatorOpenId) {
|
||||
return {
|
||||
operator: { operator_id: { open_id: operatorOpenId } },
|
||||
operator: { open_id: operatorOpenId },
|
||||
action: { value: { action } },
|
||||
context: { open_message_id: messageId },
|
||||
};
|
||||
}
|
||||
|
||||
function useActionsFromCard(content) {
|
||||
const values = [];
|
||||
for (const element of content.body.elements) {
|
||||
if (element.tag === 'button' && typeof element.value?.action === 'string' && element.value.action.startsWith('use:')) {
|
||||
values.push(element.value.action.slice('use:'.length));
|
||||
function buttonsFromCard(content) {
|
||||
const buttons = [];
|
||||
const visit = (value) => {
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) visit(item);
|
||||
return;
|
||||
}
|
||||
}
|
||||
return values;
|
||||
if (!value || typeof value !== 'object') return;
|
||||
if (value.tag === 'button') buttons.push(value);
|
||||
for (const child of Object.values(value)) visit(child);
|
||||
};
|
||||
visit(content.body?.elements);
|
||||
return buttons;
|
||||
}
|
||||
|
||||
function callbackAction(button) {
|
||||
return button.behaviors?.find((behavior) => behavior?.type === 'callback')?.value?.action;
|
||||
}
|
||||
|
||||
function useActionsFromCard(content) {
|
||||
return buttonsFromCard(content)
|
||||
.map(callbackAction)
|
||||
.filter((action) => typeof action === 'string' && action.startsWith('use:'))
|
||||
.map((action) => action.slice('use:'.length));
|
||||
}
|
||||
|
||||
function sessionsHarness(count) {
|
||||
|
|
@ -1953,6 +1969,13 @@ test('card buttons from an unallowed sender are ignored', async () => {
|
|||
await bridge.onCardAction(cardActionEvent('om_card_1', 'new', 'ou_evil'));
|
||||
await bridge.waitForIdle();
|
||||
assert.equal(fixture.sessions.size, 0, 'unallowed card operator must not act');
|
||||
|
||||
await bridge.onCardAction({
|
||||
action: { value: { action: 'new' } },
|
||||
context: { open_message_id: 'om_card_1' },
|
||||
});
|
||||
await bridge.waitForIdle();
|
||||
assert.equal(sent.length, 1, 'a card action without an operator must fail closed');
|
||||
});
|
||||
|
||||
test('card buttons from an allowed sender work', async () => {
|
||||
|
|
@ -1978,6 +2001,26 @@ test('card buttons from an allowed sender work', async () => {
|
|||
assert.equal(sent.length, 2, 'allowed operator click should send a reply');
|
||||
});
|
||||
|
||||
test('card buttons honor the wildcard sender allowlist', async () => {
|
||||
const fixture = stateFixture();
|
||||
const sent = [];
|
||||
const bridge = new FeishuHarnessBridge({
|
||||
client: cardClient(async (outgoing) => sent.push(outgoing)),
|
||||
channel: {},
|
||||
harness: sessionsHarness(3),
|
||||
state: fixture.state,
|
||||
status: bridgeStatus(),
|
||||
allowedSenderOpenIds: new Set(['*']),
|
||||
});
|
||||
|
||||
await bridge.accept(event('menu-open-wildcard', '/m', { senderOpenId: 'ou_any_user' }));
|
||||
await bridge.waitForIdle();
|
||||
await bridge.onCardAction(cardActionEvent('om_card_1', 'status', 'ou_another_user'));
|
||||
await bridge.waitForIdle();
|
||||
|
||||
assert.equal(sent.length, 2, 'wildcard access must apply to card callbacks too');
|
||||
});
|
||||
|
||||
function cards(messages) { return messages.filter((m) => m.msgType === 'interactive'); }
|
||||
|
||||
test('session list paginates by page number across 25 sessions', async () => {
|
||||
|
|
@ -1998,6 +2041,11 @@ test('session list paginates by page number across 25 sessions', async () => {
|
|||
await bridge.waitForIdle();
|
||||
assert.equal(cards(sent).length, 1);
|
||||
const page0 = cards(sent).at(-1).content;
|
||||
const firstLayout = page0.body.elements.find((element) => element.tag === 'column_set');
|
||||
const firstButton = firstLayout?.columns?.[0]?.elements?.[0];
|
||||
assert.equal(firstButton?.tag, 'button');
|
||||
assert.equal(Object.hasOwn(firstButton, 'value'), false, 'V2 buttons must not use the legacy value field');
|
||||
assert.equal(callbackAction(firstButton), 'use:session-01');
|
||||
assert.equal(useActionsFromCard(page0).length, 10);
|
||||
assert.equal(useActionsFromCard(page0)[0], 'session-01');
|
||||
|
||||
|
|
@ -2014,3 +2062,70 @@ test('session list paginates by page number across 25 sessions', async () => {
|
|||
assert.equal(useActionsFromCard(page1).length, 10);
|
||||
assert.equal(useActionsFromCard(page1)[0], 'session-11');
|
||||
});
|
||||
|
||||
test('number replies on a later session page use page-local labels', async () => {
|
||||
const fixture = stateFixture();
|
||||
const sent = [];
|
||||
const bridge = new FeishuHarnessBridge({
|
||||
client: cardClient(async (outgoing) => sent.push(outgoing)),
|
||||
channel: {},
|
||||
harness: sessionsHarness(25),
|
||||
state: fixture.state,
|
||||
status: bridgeStatus(),
|
||||
allowedSenderOpenIds: new Set(['ou_owner']),
|
||||
});
|
||||
|
||||
await bridge.accept(event('sessions-number-open', '/sessionlist', { senderOpenId: 'ou_owner' }));
|
||||
await bridge.waitForIdle();
|
||||
await bridge.onCardAction(cardActionEvent('om_card_1', 'sessions:2', 'ou_owner'));
|
||||
await bridge.waitForIdle();
|
||||
|
||||
const page2Buttons = buttonsFromCard(cards(sent).at(-1).content);
|
||||
assert.match(page2Buttons[0].text.content, /^1\. Session 21$/);
|
||||
|
||||
await bridge.accept(event('sessions-number-pick', '1', { senderOpenId: 'ou_owner' }));
|
||||
await bridge.waitForIdle();
|
||||
assert.match(JSON.parse(sent.at(-1).content).text, /ID:session-21/);
|
||||
});
|
||||
|
||||
test('session pagination preserves an explicitly selected workspace', async () => {
|
||||
const fixture = stateFixture();
|
||||
const sent = [];
|
||||
const workspaceARaw = join(tmpdir(), `dsh-im-card-current-${process.pid}`);
|
||||
const workspaceBRaw = join(tmpdir(), `dsh-im-card-selected-${process.pid}`);
|
||||
mkdirSync(workspaceARaw, { recursive: true });
|
||||
mkdirSync(workspaceBRaw, { recursive: true });
|
||||
const workspaceA = realpathSync(workspaceARaw);
|
||||
const workspaceB = realpathSync(workspaceBRaw);
|
||||
const sessionSet = (prefix) => Array.from({ length: 25 }, (_, index) => ({
|
||||
sessionId: `${prefix}-${String(index + 1).padStart(2, '0')}`,
|
||||
title: `${prefix} Session ${index + 1}`,
|
||||
}));
|
||||
const bridge = new FeishuHarnessBridge({
|
||||
client: cardClient(async (outgoing) => sent.push(outgoing)),
|
||||
channel: {},
|
||||
harness: {
|
||||
ensureRunning: async () => true,
|
||||
currentWorkspace: () => workspaceA,
|
||||
listWorkspaces: async () => [workspaceA, workspaceB],
|
||||
listWorkspaceSessions: async (workspace) => ({
|
||||
workspace,
|
||||
sessions: workspace === workspaceB ? sessionSet('selected') : sessionSet('current'),
|
||||
}),
|
||||
bindWorkspaceSession: async (_key, sessionId) => ({ sessionId, title: sessionId }),
|
||||
switchWorkspace: async (path) => path,
|
||||
},
|
||||
state: fixture.state,
|
||||
status: bridgeStatus(),
|
||||
allowedSenderOpenIds: new Set(['ou_owner']),
|
||||
});
|
||||
|
||||
await bridge.accept(event('selected-workspace-open', '/sessionlist 2', { senderOpenId: 'ou_owner' }));
|
||||
await bridge.waitForIdle();
|
||||
assert.equal(useActionsFromCard(cards(sent).at(-1).content)[0], 'selected-01');
|
||||
|
||||
await bridge.onCardAction(cardActionEvent('om_card_1', 'sessions:1', 'ou_owner'));
|
||||
await bridge.waitForIdle();
|
||||
assert.equal(useActionsFromCard(cards(sent).at(-1).content)[0], 'selected-11');
|
||||
assert.match(JSON.stringify(cards(sent).at(-1).content), new RegExp(workspaceB.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
|
||||
});
|
||||
|
|
|
|||
|
|
@ -148,6 +148,23 @@ async function completeScan(fx, result) {
|
|||
return fx.controller.registrationStatus(attemptId);
|
||||
}
|
||||
|
||||
test('QR registration separates events from card callbacks', async () => {
|
||||
const fx = fixture({ createBotIds: ['bot_callbacks'] });
|
||||
const started = fx.controller.startRegistration();
|
||||
const attemptId = started.registration.attempt;
|
||||
await waitFor(() => fx.registrationRuns.length === 1);
|
||||
const run = fx.registrationRuns.shift();
|
||||
assert.deepEqual(run.options.addons.events.items.tenant, ['im.message.receive_v1']);
|
||||
assert.deepEqual(run.options.addons.callbacks.items, ['card.action.trigger']);
|
||||
run.options.onQRCodeReady({ url: 'https://accounts.feishu.cn/callbacks', expireIn: 60 });
|
||||
run.resolve({
|
||||
client_id: 'cli_callbacks', client_secret: 'callbacks-secret',
|
||||
user_info: { open_id: 'ou_callbacks', tenant_brand: 'feishu' },
|
||||
});
|
||||
await waitFor(() => fx.controller.registrationStatus(attemptId).registration.state === 'succeeded');
|
||||
await fx.controller.close();
|
||||
});
|
||||
|
||||
test('manual Feishu credentials are verified, stored host-side, and use app visibility for access', async () => {
|
||||
const fx = fixture({ createBotIds: ['bot_manual'] });
|
||||
|
||||
|
|
|
|||
|
|
@ -79,7 +79,8 @@ test('QR success stores the secret off-config and becomes immediately chat-ready
|
|||
await flush();
|
||||
assert.equal(fx.getSdkOptions().createOnly, true);
|
||||
assert.equal(fx.getSdkOptions().addons.preset, false);
|
||||
assert.deepEqual(fx.getSdkOptions().addons.events.items.tenant, ['im.message.receive_v1', 'card.action.trigger']);
|
||||
assert.deepEqual(fx.getSdkOptions().addons.events.items.tenant, ['im.message.receive_v1']);
|
||||
assert.deepEqual(fx.getSdkOptions().addons.callbacks.items, ['card.action.trigger']);
|
||||
assert.ok(fx.getSdkOptions().addons.scopes.tenant.includes('im:message.p2p_msg:readonly'));
|
||||
assert.ok(fx.getSdkOptions().addons.scopes.tenant.includes('im:message:readonly'));
|
||||
assert.ok(fx.getSdkOptions().addons.scopes.tenant.includes('im:message:send_as_bot'));
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue