topicPreparationState.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import type { BotInboundMessage } from "@zcode/shared";
  2. export type TopicPreparationStatus = "preparing" | "waitingStop" | "failed";
  3. /** 仅保留未提交材料;对外投影不包含文件二进制,重试仍由入站授权链处理。 */
  4. export function createTopicPreparationState() {
  5. const waitingStop = new Set<string>();
  6. const topics = new Map<
  7. string,
  8. Map<
  9. string,
  10. {
  11. message: BotInboundMessage;
  12. status: TopicPreparationStatus;
  13. error?: string;
  14. }
  15. >
  16. >();
  17. return {
  18. add(key: string, message: BotInboundMessage) {
  19. const id = message.actor.providerMessageId;
  20. if (!id) throw new Error("Topic message identity is missing");
  21. let entries = topics.get(key);
  22. if (!entries) {
  23. entries = new Map();
  24. topics.set(key, entries);
  25. }
  26. entries.set(id, { message, status: waitingStop.has(key) ? "waitingStop" : "preparing" });
  27. },
  28. setWaitingStop(key: string, waiting: boolean) {
  29. // 停止确认可能先于材料授权完成;保存话题阶段,让稍后加入的消息继承等待状态。
  30. if (waiting) waitingStop.add(key);
  31. else waitingStop.delete(key);
  32. for (const entry of topics.get(key)?.values() ?? []) {
  33. if (entry.status !== "failed") entry.status = waiting ? "waitingStop" : "preparing";
  34. }
  35. },
  36. update(key: string, ids: string[], status: TopicPreparationStatus, error?: string) {
  37. for (const id of ids) {
  38. const entry = topics.get(key)?.get(id);
  39. if (entry) {
  40. entry.status = status;
  41. entry.error = error;
  42. }
  43. }
  44. },
  45. snapshot(key: string) {
  46. return [...(topics.get(key)?.entries() ?? [])].map(([messageId, entry]) => ({
  47. messageId,
  48. senderName: entry.message.actor.displayName ?? entry.message.actor.providerUserId,
  49. text: entry.message.text,
  50. contentParts: entry.message.contentParts,
  51. status: entry.status,
  52. ...(entry.error ? { error: entry.error } : {}),
  53. }));
  54. },
  55. retry(key: string, id: string) {
  56. const entry = topics.get(key)?.get(id);
  57. return entry?.status === "failed" ? entry.message : undefined;
  58. },
  59. remove(key: string, ids: string[]) {
  60. const entries = topics.get(key);
  61. for (const id of ids) entries?.delete(id);
  62. if (!entries?.size) topics.delete(key);
  63. },
  64. clear(key?: string) {
  65. if (key) {
  66. topics.delete(key);
  67. waitingStop.delete(key);
  68. } else {
  69. topics.clear();
  70. waitingStop.clear();
  71. }
  72. },
  73. };
  74. }