File size: 8,833 Bytes
fc93158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
  clearInternalHooks,
  createInternalHookEvent,
  registerInternalHook,
  triggerInternalHook,
  type InternalHookEvent,
} from "./internal-hooks.js";

type ActionCase = {
  label: string;
  key: string;
  action: "received" | "transcribed" | "preprocessed" | "sent";
  context: Record<string, unknown>;
  assertContext: (context: Record<string, unknown>) => void;
};

const actionCases: ActionCase[] = [
  {
    label: "message:received",
    key: "message:received",
    action: "received",
    context: {
      from: "signal:+15551234567",
      to: "bot:+15559876543",
      content: "Test message",
      channelId: "signal",
      conversationId: "conv-abc",
      messageId: "msg-xyz",
      senderId: "sender-1",
      senderName: "Test User",
      senderUsername: "testuser",
      senderE164: "+15551234567",
      provider: "signal",
      surface: "signal",
      threadId: "thread-1",
      originatingChannel: "signal",
      originatingTo: "bot:+15559876543",
      timestamp: 1707600000,
    },
    assertContext: (context) => {
      expect(context.content).toBe("Test message");
      expect(context.channelId).toBe("signal");
      expect(context.senderE164).toBe("+15551234567");
      expect(context.threadId).toBe("thread-1");
    },
  },
  {
    label: "message:transcribed",
    key: "message:transcribed",
    action: "transcribed",
    context: {
      body: "🎤 [Audio]",
      bodyForAgent: "[Audio] Transcript: Hello from voice",
      transcript: "Hello from voice",
      channelId: "telegram",
      mediaType: "audio/ogg",
    },
    assertContext: (context) => {
      expect(context.body).toBe("🎤 [Audio]");
      expect(context.bodyForAgent).toContain("Transcript:");
      expect(context.transcript).toBe("Hello from voice");
      expect(context.mediaType).toBe("audio/ogg");
    },
  },
  {
    label: "message:preprocessed",
    key: "message:preprocessed",
    action: "preprocessed",
    context: {
      body: "🎤 [Audio]",
      bodyForAgent: "[Audio] Transcript: Check https://example.com\n[Link summary: Example site]",
      transcript: "Check https://example.com",
      channelId: "telegram",
      mediaType: "audio/ogg",
      isGroup: false,
    },
    assertContext: (context) => {
      expect(context.transcript).toBe("Check https://example.com");
      expect(String(context.bodyForAgent)).toContain("Link summary");
      expect(String(context.bodyForAgent)).toContain("Transcript:");
    },
  },
  {
    label: "message:sent",
    key: "message:sent",
    action: "sent",
    context: {
      from: "bot:456",
      to: "user:123",
      content: "Reply text",
      channelId: "discord",
      conversationId: "channel:C123",
      provider: "discord",
      surface: "discord",
      threadId: "thread-abc",
      originatingChannel: "discord",
      originatingTo: "channel:C123",
    },
    assertContext: (context) => {
      expect(context.content).toBe("Reply text");
      expect(context.channelId).toBe("discord");
      expect(context.conversationId).toBe("channel:C123");
      expect(context.threadId).toBe("thread-abc");
    },
  },
];

describe("message hooks", () => {
  beforeEach(() => {
    clearInternalHooks();
  });

  afterEach(() => {
    clearInternalHooks();
  });

  describe("action handlers", () => {
    for (const testCase of actionCases) {
      it(`triggers handler for ${testCase.label}`, async () => {
        const handler = vi.fn();
        registerInternalHook(testCase.key, handler);

        await triggerInternalHook(
          createInternalHookEvent("message", testCase.action, "session-1", testCase.context),
        );

        expect(handler).toHaveBeenCalledOnce();
        const event = handler.mock.calls[0][0] as InternalHookEvent;
        expect(event.type).toBe("message");
        expect(event.action).toBe(testCase.action);
        testCase.assertContext(event.context);
      });
    }

    it("does not trigger action-specific handlers for other actions", async () => {
      const sentHandler = vi.fn();
      registerInternalHook("message:sent", sentHandler);

      await triggerInternalHook(
        createInternalHookEvent("message", "received", "session-1", { content: "hello" }),
      );

      expect(sentHandler).not.toHaveBeenCalled();
    });
  });

  describe("general handler", () => {
    it("receives full message lifecycle in order", async () => {
      const events: InternalHookEvent[] = [];
      registerInternalHook("message", (event) => {
        events.push(event);
      });

      const lifecycleFixtures: Array<{
        action: "received" | "transcribed" | "preprocessed" | "sent";
        context: Record<string, unknown>;
      }> = [
        { action: "received", context: { content: "hi" } },
        { action: "transcribed", context: { transcript: "hello" } },
        { action: "preprocessed", context: { body: "hello", bodyForAgent: "hello" } },
        { action: "sent", context: { content: "reply" } },
      ];

      for (const fixture of lifecycleFixtures) {
        await triggerInternalHook(
          createInternalHookEvent("message", fixture.action, "s1", fixture.context),
        );
      }

      expect(events.map((event) => event.action)).toEqual([
        "received",
        "transcribed",
        "preprocessed",
        "sent",
      ]);
    });

    it("triggers both general and specific handlers", async () => {
      const generalHandler = vi.fn();
      const specificHandler = vi.fn();
      registerInternalHook("message", generalHandler);
      registerInternalHook("message:received", specificHandler);

      await triggerInternalHook(
        createInternalHookEvent("message", "received", "s1", { content: "test" }),
      );

      expect(generalHandler).toHaveBeenCalledOnce();
      expect(specificHandler).toHaveBeenCalledOnce();
    });
  });

  describe("error isolation", () => {
    it("does not propagate handler errors", async () => {
      const badHandler = vi.fn(() => {
        throw new Error("Hook exploded");
      });
      registerInternalHook("message:received", badHandler);

      await expect(
        triggerInternalHook(
          createInternalHookEvent("message", "received", "s1", { content: "test" }),
        ),
      ).resolves.not.toThrow();
      expect(badHandler).toHaveBeenCalledOnce();
    });

    it("continues with later handlers when one fails", async () => {
      const failHandler = vi.fn(() => {
        throw new Error("First handler fails");
      });
      const successHandler = vi.fn();
      registerInternalHook("message:received", failHandler);
      registerInternalHook("message:received", successHandler);

      await triggerInternalHook(
        createInternalHookEvent("message", "received", "s1", { content: "test" }),
      );

      expect(failHandler).toHaveBeenCalledOnce();
      expect(successHandler).toHaveBeenCalledOnce();
    });

    it("isolates async handler errors", async () => {
      const asyncFailHandler = vi.fn(async () => {
        throw new Error("Async hook failed");
      });
      registerInternalHook("message:sent", asyncFailHandler);

      await expect(
        triggerInternalHook(createInternalHookEvent("message", "sent", "s1", { content: "reply" })),
      ).resolves.not.toThrow();
      expect(asyncFailHandler).toHaveBeenCalledOnce();
    });
  });

  describe("event structure", () => {
    it("includes timestamps on message events", async () => {
      const handler = vi.fn();
      registerInternalHook("message", handler);

      const before = new Date();
      await triggerInternalHook(
        createInternalHookEvent("message", "received", "s1", { content: "hi" }),
      );
      const after = new Date();

      const event = handler.mock.calls[0][0] as InternalHookEvent;
      expect(event.timestamp).toBeInstanceOf(Date);
      expect(event.timestamp.getTime()).toBeGreaterThanOrEqual(before.getTime());
      expect(event.timestamp.getTime()).toBeLessThanOrEqual(after.getTime());
    });

    it("preserves mutable messages and sessionKey", async () => {
      const events: InternalHookEvent[] = [];
      registerInternalHook("message", (event) => {
        event.messages.push("Echo");
        events.push(event);
      });

      const sessionKey = "agent:main:telegram:abc";
      const received = createInternalHookEvent("message", "received", sessionKey, {
        content: "hi",
      });
      await triggerInternalHook(received);
      await triggerInternalHook(
        createInternalHookEvent("message", "sent", sessionKey, { content: "reply" }),
      );

      expect(received.messages).toContain("Echo");
      expect(events[0]?.sessionKey).toBe(sessionKey);
      expect(events[1]?.sessionKey).toBe(sessionKey);
    });
  });
});