tui-session-event-relay.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // TUI 常驻会话事件中继。
  2. //
  3. // 单独成模块是为了让「换 app 时重挂」这条性质可被直接单测:若埋在 tui-prompt-handler
  4. // 的闭包里,只能靠一整套 app 工厂假件才能验,而漏挂的后果很安静——换 session 后 TUI 再也
  5. // 收不到出回合事件(dwf 进度、通知驱动回合),界面看起来完全正常。
  6. import type { SessionEvent } from "@zcode/contracts";
  7. /** 从 runtime 上读出订阅函数;读不到就返回 undefined(能力不在静态类型面上)。 */
  8. type SessionEventSubscriberReader = (
  9. runtime: unknown,
  10. ) => ((sink: { onSessionEvent: (event: SessionEvent) => void }) => () => void) | undefined;
  11. interface TuiSessionEventRelay {
  12. /** 注册一个 sink;返回退订。首个 sink 会触发实挂。 */
  13. addSink: (sink: (event: SessionEvent) => void) => () => void;
  14. /** 换 app 后重挂:先断旧的,再挂到当前 runtime 上。无 sink 时不挂。 */
  15. reattach: () => void;
  16. /** 拆掉当前订阅(不清空 sink 注册表)。 */
  17. detach: () => void;
  18. /** 当前是否挂着(测试与诊断用)。 */
  19. isAttached: () => boolean;
  20. }
  21. export function createTuiSessionEventRelay(input: {
  22. /** 每次重挂时读当前 app 的 runtime——闭包读取而不是传值,才能跟上 replaceApp。 */
  23. currentRuntime: () => unknown;
  24. readSubscriber: SessionEventSubscriberReader;
  25. }): TuiSessionEventRelay {
  26. const sinks = new Set<(event: SessionEvent) => void>();
  27. let detachCurrent: (() => void) | undefined;
  28. const detach = (): void => {
  29. detachCurrent?.();
  30. detachCurrent = undefined;
  31. };
  32. const reattach = (): void => {
  33. detach();
  34. if (sinks.size === 0) return;
  35. const subscribe = input.readSubscriber(input.currentRuntime());
  36. detachCurrent = subscribe?.({
  37. onSessionEvent: (event) => {
  38. // 直接遍历 Set:JS 的 Set 迭代对「遍历中删除」是安全的(已删未访问的条目会被跳过),
  39. // 所以 sink 在回调里退订不会破坏本次扇出,也不该再收到这一条。
  40. for (const sink of sinks) sink(event);
  41. },
  42. });
  43. };
  44. return {
  45. addSink: (sink) => {
  46. sinks.add(sink);
  47. if (sinks.size === 1) reattach();
  48. return () => {
  49. sinks.delete(sink);
  50. if (sinks.size === 0) detach();
  51. };
  52. },
  53. reattach,
  54. detach,
  55. isAttached: () => detachCurrent !== undefined,
  56. };
  57. }