dispatch-check.ts 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { Message } from './api/models';
  2. /**
  3. * 派活有效性检查 —— 组长「表面上派了活」但组员根本没收到。
  4. *
  5. * ## 实测教训(2026-10-27)
  6. *
  7. * 组长在群里发了「派活消息已发到群里(event_id ...)」,
  8. * 但 40 分钟后交付物目录都不存在 —— 组员压根没开工。
  9. *
  10. * 查群消息发现:**整个群只有 1 条带 `m.mentions` 的消息**(用户发的),
  11. * 组长那条「派活」没带 mention 结构。
  12. *
  13. * 后果:`lj-test` 的 `MATRIX_REQUIRE_MENTION=true` 让它**不认为自己被叫**,
  14. * 于是不处理。组长的文字里写了 `@lj-test`,但那只是**纯文本**,不是 mention。
  15. *
  16. * ## 这个模块做什么
  17. *
  18. * 检查一条「派活消息」是否**真的能让对方收到**:
  19. * · 有 `m.mentions.user_ids` 且包含目标 → ✅ 有效
  20. * · 只有文本 `@名字` 但没 mention 结构 → ❌ **无效**(对方不会响应)
  21. */
  22. export type DispatchValidity = 'valid' | 'text-only' | 'no-mention';
  23. export interface DispatchCheck {
  24. validity: DispatchValidity;
  25. /** 给用户/组长看的说明 */
  26. detail: string;
  27. /** 是否需要提醒组长重发 */
  28. needsResend: boolean;
  29. }
  30. /**
  31. * 检查一条消息是否有效派活。
  32. *
  33. * @param msg 组长的派活消息
  34. * @param targetMxId 组员的 Matrix ID
  35. */
  36. export function checkDispatch(
  37. msg: Message | undefined,
  38. targetMxId: string,
  39. ): DispatchCheck {
  40. if (!msg) {
  41. return { validity: 'no-mention', detail: '没有找到派活消息', needsResend: true };
  42. }
  43. const mentions = msg.mentions ?? [];
  44. if (mentions.includes(targetMxId)) {
  45. return { validity: 'valid', detail: '派活消息带有正确的 @ 结构', needsResend: false };
  46. }
  47. // 文本里有 @名字 但没 mention 结构 —— 最常见的问题
  48. const text = msg.text ?? '';
  49. const local = targetMxId.replace(/^@/, '').split(':')[0];
  50. if (text.includes('@' + local) || text.includes(targetMxId)) {
  51. return {
  52. validity: 'text-only',
  53. detail:
  54. '派活消息只在文字里写了 @名字,没有真正的 mention 结构 —— ' +
  55. '对方不会认为被叫到,所以不会开工。需要带 m.mentions 重发。',
  56. needsResend: true,
  57. };
  58. }
  59. return { validity: 'no-mention', detail: '派活消息没有 @ 任何人', needsResend: true };
  60. }
  61. /**
  62. * 在群消息里找「组长最近一次派活」,并判断有效性。
  63. *
  64. * 用于:App 发现「组长说派了活但组员没动」时,判断是不是 mention 缺失。
  65. */
  66. export function findLastDispatch(
  67. messages: Message[],
  68. leaderMxId: string,
  69. targetMxId: string,
  70. ): { msg: Message | undefined; check: DispatchCheck } {
  71. for (let i = messages.length - 1; i >= 0; i--) {
  72. const m = messages[i];
  73. if (m.senderId !== leaderMxId) continue;
  74. const text = m.text ?? '';
  75. const local = targetMxId.replace(/^@/, '').split(':')[0];
  76. // 认「派活」的几种写法
  77. const looksLikeDispatch =
  78. /派活|分配|交给你|你来做|请做/.test(text) ||
  79. m.mentions?.includes(targetMxId) ||
  80. text.includes('@' + local);
  81. if (!looksLikeDispatch) continue;
  82. return { msg: m, check: checkDispatch(m, targetMxId) };
  83. }
  84. return { msg: undefined, check: checkDispatch(undefined, targetMxId) };
  85. }