bingocode 1.0.29 → 1.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/adapters/common/__tests__/chat-queue.test.ts +61 -0
  2. package/adapters/common/__tests__/format.test.ts +148 -0
  3. package/adapters/common/__tests__/http-client.test.ts +105 -0
  4. package/adapters/common/__tests__/message-buffer.test.ts +84 -0
  5. package/adapters/common/__tests__/message-dedup.test.ts +57 -0
  6. package/adapters/common/__tests__/session-store.test.ts +62 -0
  7. package/adapters/common/__tests__/ws-bridge.test.ts +177 -0
  8. package/adapters/common/attachment/__tests__/attachment-limits.test.ts +52 -0
  9. package/adapters/common/attachment/__tests__/attachment-store.test.ts +108 -0
  10. package/adapters/common/attachment/__tests__/image-block-watcher.test.ts +115 -0
  11. package/adapters/feishu/__tests__/card-errors.test.ts +194 -0
  12. package/adapters/feishu/__tests__/cardkit.test.ts +295 -0
  13. package/adapters/feishu/__tests__/extract-payload.test.ts +77 -0
  14. package/adapters/feishu/__tests__/feishu.test.ts +907 -0
  15. package/adapters/feishu/__tests__/flush-controller.test.ts +290 -0
  16. package/adapters/feishu/__tests__/markdown-style.test.ts +353 -0
  17. package/adapters/feishu/__tests__/media.test.ts +120 -0
  18. package/adapters/feishu/__tests__/streaming-card.test.ts +914 -0
  19. package/adapters/telegram/__tests__/media.test.ts +86 -0
  20. package/adapters/telegram/__tests__/telegram.test.ts +115 -0
  21. package/package.json +1 -1
  22. package/src/server/__tests__/conversation-service.test.ts +173 -0
  23. package/src/server/__tests__/conversations.test.ts +458 -0
  24. package/src/server/__tests__/cron-scheduler.test.ts +575 -0
  25. package/src/server/__tests__/e2e/business-flow.test.ts +841 -0
  26. package/src/server/__tests__/e2e/full-flow.test.ts +357 -0
  27. package/src/server/__tests__/fixtures/mock-sdk-cli.ts +123 -0
  28. package/src/server/__tests__/haha-oauth-api.test.ts +146 -0
  29. package/src/server/__tests__/haha-oauth-service.test.ts +185 -0
  30. package/src/server/__tests__/providers-real.test.ts +244 -0
  31. package/src/server/__tests__/providers.test.ts +579 -0
  32. package/src/server/__tests__/proxy-streaming.test.ts +317 -0
  33. package/src/server/__tests__/proxy-transform.test.ts +469 -0
  34. package/src/server/__tests__/real-llm-test.ts +526 -0
  35. package/src/server/__tests__/scheduled-tasks.test.ts +371 -0
  36. package/src/server/__tests__/sessions.test.ts +786 -0
  37. package/src/server/__tests__/settings.test.ts +376 -0
  38. package/src/server/__tests__/skills.test.ts +125 -0
  39. package/src/server/__tests__/tasks.test.ts +171 -0
  40. package/src/server/__tests__/team-watcher.test.ts +400 -0
  41. package/src/server/__tests__/teams.test.ts +627 -0
  42. package/src/server/middleware/cors.test.ts +27 -0
  43. package/src/utils/__tests__/cronFrequency.test.ts +153 -0
  44. package/src/utils/__tests__/cronTasks.test.ts +204 -0
  45. package/src/utils/computerUse/permissions.test.ts +44 -0
@@ -0,0 +1,458 @@
1
+ /**
2
+ * Tests for ConversationService and WebSocket chat integration
3
+ *
4
+ * ConversationService 管理 CLI 子进程的生命周期。
5
+ * WebSocket 集成测试验证消息从客户端经过服务端到达 CLI 的完整流转。
6
+ */
7
+
8
+ import { describe, it, expect, beforeAll, afterAll } from 'bun:test'
9
+ import * as fs from 'fs/promises'
10
+ import * as path from 'path'
11
+ import * as os from 'os'
12
+ import { fileURLToPath } from 'node:url'
13
+ import { ConversationService } from '../services/conversationService.js'
14
+
15
+ // ============================================================================
16
+ // ConversationService unit tests
17
+ // ============================================================================
18
+
19
+ describe('ConversationService', () => {
20
+ it('should report no session for unknown ID', () => {
21
+ const svc = new ConversationService()
22
+ const sid = crypto.randomUUID()
23
+ expect(svc.hasSession(sid)).toBe(false)
24
+ })
25
+
26
+ it('should track active sessions as empty initially', () => {
27
+ const svc = new ConversationService()
28
+ expect(svc.getActiveSessions()).toEqual([])
29
+ })
30
+
31
+ it('should return false when sending message to non-existent session', async () => {
32
+ const svc = new ConversationService()
33
+ const result = await svc.sendMessage('no-such-session', 'hello')
34
+ expect(result).toBe(false)
35
+ })
36
+
37
+ it('should return false when responding to permission for non-existent session', () => {
38
+ const svc = new ConversationService()
39
+ const result = svc.respondToPermission('no-such-session', 'req-1', true)
40
+ expect(result).toBe(false)
41
+ })
42
+
43
+ it('should forward suggested permission updates for allow-for-session decisions', () => {
44
+ const svc = new ConversationService()
45
+ const sent: unknown[] = []
46
+
47
+ ;(svc as any).sessions.set('session-1', {
48
+ proc: null,
49
+ outputCallbacks: [],
50
+ workDir: process.cwd(),
51
+ sdkToken: 'token',
52
+ sdkSocket: {
53
+ send(data: string) {
54
+ sent.push(JSON.parse(data))
55
+ },
56
+ },
57
+ pendingOutbound: [],
58
+ stderrLines: [],
59
+ sdkMessages: [],
60
+ pendingPermissionRequests: new Map([
61
+ ['req-1', {
62
+ toolName: 'Bash',
63
+ input: { command: 'ls src' },
64
+ permissionSuggestions: [
65
+ {
66
+ type: 'addRules',
67
+ rules: [{ toolName: 'Bash', ruleContent: 'ls src' }],
68
+ behavior: 'allow',
69
+ destination: 'localSettings',
70
+ },
71
+ ],
72
+ }],
73
+ ]),
74
+ })
75
+
76
+ const result = svc.respondToPermission('session-1', 'req-1', true, 'always')
77
+
78
+ expect(result).toBe(true)
79
+ expect(sent).toHaveLength(1)
80
+ expect(sent[0]).toMatchObject({
81
+ type: 'control_response',
82
+ response: {
83
+ response: {
84
+ behavior: 'allow',
85
+ updatedPermissions: [
86
+ {
87
+ type: 'addRules',
88
+ rules: [{ toolName: 'Bash', ruleContent: 'ls src' }],
89
+ behavior: 'allow',
90
+ destination: 'session',
91
+ },
92
+ ],
93
+ },
94
+ },
95
+ })
96
+ })
97
+
98
+ it('should send set_permission_mode requests to active sessions', () => {
99
+ const svc = new ConversationService()
100
+ const sent: unknown[] = []
101
+
102
+ ;(svc as any).sessions.set('session-2', {
103
+ proc: null,
104
+ outputCallbacks: [],
105
+ workDir: process.cwd(),
106
+ sdkToken: 'token',
107
+ sdkSocket: {
108
+ send(data: string) {
109
+ sent.push(JSON.parse(data))
110
+ },
111
+ },
112
+ pendingOutbound: [],
113
+ stderrLines: [],
114
+ sdkMessages: [],
115
+ pendingPermissionRequests: new Map(),
116
+ })
117
+
118
+ const result = svc.setPermissionMode('session-2', 'acceptEdits')
119
+
120
+ expect(result).toBe(true)
121
+ expect(sent).toHaveLength(1)
122
+ expect(sent[0]).toMatchObject({
123
+ type: 'control_request',
124
+ request: {
125
+ subtype: 'set_permission_mode',
126
+ mode: 'acceptEdits',
127
+ },
128
+ })
129
+ })
130
+
131
+ it('should not inject a desktop-specific ask override in default permission mode', () => {
132
+ const svc = new ConversationService()
133
+ expect((svc as any).getPermissionArgs('default', false)).toEqual([
134
+ '--permission-mode',
135
+ 'default',
136
+ ])
137
+ })
138
+
139
+ it('should return false when sending interrupt to non-existent session', () => {
140
+ const svc = new ConversationService()
141
+ const result = svc.sendInterrupt('no-such-session')
142
+ expect(result).toBe(false)
143
+ })
144
+
145
+ it('should not throw when stopping non-existent session', () => {
146
+ const svc = new ConversationService()
147
+ expect(() => svc.stopSession('no-such-session')).not.toThrow()
148
+ })
149
+
150
+ it('should not throw when registering callback for non-existent session', () => {
151
+ const svc = new ConversationService()
152
+ expect(() => svc.onOutput('no-such-session', () => {})).not.toThrow()
153
+ })
154
+ })
155
+
156
+ // ============================================================================
157
+ // WebSocket integration tests (with mock CLI using the SDK websocket protocol)
158
+ // ============================================================================
159
+
160
+ describe('WebSocket Chat Integration', () => {
161
+ let server: ReturnType<typeof Bun.serve>
162
+ let baseUrl: string
163
+ let wsUrl: string
164
+ let tmpDir: string
165
+
166
+ async function withMockInitMode<T>(
167
+ mode: string | undefined,
168
+ callback: () => Promise<T>,
169
+ ): Promise<T> {
170
+ const previousMode = process.env.MOCK_SDK_INIT_MODE
171
+
172
+ if (mode) {
173
+ process.env.MOCK_SDK_INIT_MODE = mode
174
+ } else {
175
+ delete process.env.MOCK_SDK_INIT_MODE
176
+ }
177
+
178
+ try {
179
+ return await callback()
180
+ } finally {
181
+ if (previousMode === undefined) {
182
+ delete process.env.MOCK_SDK_INIT_MODE
183
+ } else {
184
+ process.env.MOCK_SDK_INIT_MODE = previousMode
185
+ }
186
+ }
187
+ }
188
+
189
+ async function runTurn(sessionId: string, content: string): Promise<any[]> {
190
+ const messages: any[] = []
191
+ const ws = new WebSocket(`${wsUrl}/ws/${sessionId}`)
192
+
193
+ await new Promise<void>((resolve, reject) => {
194
+ const timeout = setTimeout(() => {
195
+ ws.close()
196
+ reject(new Error(`Timed out waiting for completion for session ${sessionId}`))
197
+ }, 30000)
198
+
199
+ ws.onmessage = (e) => {
200
+ const msg = JSON.parse(e.data as string)
201
+ messages.push(msg)
202
+ if (msg.type === 'connected') {
203
+ ws.send(JSON.stringify({ type: 'user_message', content }))
204
+ }
205
+ if (msg.type === 'error') {
206
+ clearTimeout(timeout)
207
+ ws.close()
208
+ reject(new Error(msg.message))
209
+ }
210
+ if (msg.type === 'message_complete') {
211
+ clearTimeout(timeout)
212
+ ws.close()
213
+ resolve()
214
+ }
215
+ }
216
+
217
+ ws.onerror = () => {
218
+ clearTimeout(timeout)
219
+ ws.close()
220
+ reject(new Error(`WebSocket error for session ${sessionId}`))
221
+ }
222
+ })
223
+
224
+ return messages
225
+ }
226
+ const originalCliPath = process.env.CLAUDE_CLI_PATH
227
+
228
+ beforeAll(async () => {
229
+ tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'claude-conv-'))
230
+ process.env.CLAUDE_CONFIG_DIR = tmpDir
231
+ process.env.CLAUDE_CLI_PATH = fileURLToPath(
232
+ new URL('./fixtures/mock-sdk-cli.ts', import.meta.url)
233
+ )
234
+ await fs.mkdir(path.join(tmpDir, 'projects'), { recursive: true })
235
+
236
+ const port = 15000 + Math.floor(Math.random() * 1000)
237
+ const { startServer } = await import('../index.js')
238
+ server = startServer(port, '127.0.0.1')
239
+ baseUrl = `http://127.0.0.1:${port}`
240
+ wsUrl = `ws://127.0.0.1:${port}`
241
+ })
242
+
243
+ afterAll(async () => {
244
+ server?.stop()
245
+ if (tmpDir) {
246
+ await fs.rm(tmpDir, { recursive: true, force: true })
247
+ }
248
+ if (originalCliPath) {
249
+ process.env.CLAUDE_CLI_PATH = originalCliPath
250
+ } else {
251
+ delete process.env.CLAUDE_CLI_PATH
252
+ }
253
+ delete process.env.CLAUDE_CONFIG_DIR
254
+ })
255
+
256
+ it('should connect and receive connected event', async () => {
257
+ const messages: any[] = []
258
+ const ws = new WebSocket(`${wsUrl}/ws/chat-test-1`)
259
+
260
+ await new Promise<void>((resolve) => {
261
+ ws.onmessage = (e) => {
262
+ messages.push(JSON.parse(e.data as string))
263
+ if (messages.length >= 1) {
264
+ ws.close()
265
+ resolve()
266
+ }
267
+ }
268
+ ws.onerror = () => {
269
+ ws.close()
270
+ resolve()
271
+ }
272
+ setTimeout(() => {
273
+ ws.close()
274
+ resolve()
275
+ }, 3000)
276
+ })
277
+
278
+ expect(messages[0].type).toBe('connected')
279
+ expect(messages[0].sessionId).toBe('chat-test-1')
280
+ })
281
+
282
+ it('should handle stop_generation and return idle status', async () => {
283
+ const messages: any[] = []
284
+ const ws = new WebSocket(`${wsUrl}/ws/chat-test-2`)
285
+
286
+ await new Promise<void>((resolve) => {
287
+ ws.onmessage = (e) => {
288
+ const msg = JSON.parse(e.data as string)
289
+ messages.push(msg)
290
+ if (msg.type === 'connected') {
291
+ ws.send(JSON.stringify({ type: 'stop_generation' }))
292
+ }
293
+ if (msg.type === 'status' && msg.state === 'idle') {
294
+ ws.close()
295
+ resolve()
296
+ }
297
+ }
298
+ ws.onerror = () => {
299
+ ws.close()
300
+ resolve()
301
+ }
302
+ setTimeout(() => {
303
+ ws.close()
304
+ resolve()
305
+ }, 3000)
306
+ })
307
+
308
+ expect(messages.some((m) => m.type === 'status' && m.state === 'idle')).toBe(true)
309
+ })
310
+
311
+ it('should send user_message and receive streamed SDK response', async () => {
312
+ const messages: any[] = []
313
+ const ws = new WebSocket(`${wsUrl}/ws/chat-test-3`)
314
+
315
+ await new Promise<void>((resolve) => {
316
+ ws.onmessage = (e) => {
317
+ const msg = JSON.parse(e.data as string)
318
+ messages.push(msg)
319
+ if (msg.type === 'connected') {
320
+ ws.send(
321
+ JSON.stringify({ type: 'user_message', content: 'Hello from test' })
322
+ )
323
+ }
324
+ // Wait until we receive completion after the streamed response
325
+ if (
326
+ msg.type === 'message_complete' &&
327
+ messages.some((entry) => entry.type === 'thinking')
328
+ ) {
329
+ ws.close()
330
+ resolve()
331
+ }
332
+ }
333
+ ws.onerror = () => {
334
+ ws.close()
335
+ resolve()
336
+ }
337
+ setTimeout(() => {
338
+ ws.close()
339
+ resolve()
340
+ }, 5000)
341
+ })
342
+
343
+ const types = messages.map((m) => m.type)
344
+ expect(types).toContain('connected')
345
+ expect(types).toContain('status')
346
+ // Mock SDK flow produces text streaming, thinking, and completion events.
347
+ expect(types).toContain('content_start')
348
+ expect(types).toContain('content_delta')
349
+ expect(types).toContain('thinking')
350
+ expect(types).toContain('message_complete')
351
+
352
+ // Verify thinking was first status
353
+ const statusMsgs = messages.filter((m) => m.type === 'status')
354
+ expect(statusMsgs[0].state).toBe('thinking')
355
+ })
356
+
357
+ it('should continue chat when SDK init arrives only after the first user turn', async () => {
358
+ const messages = await withMockInitMode('on_first_user', () =>
359
+ runTurn('chat-test-lazy-init', 'Hello after lazy init'),
360
+ )
361
+
362
+ expect(messages.some((m) => m.type === 'message_complete')).toBe(true)
363
+ expect(messages.some((m) => m.type === 'error')).toBe(false)
364
+ expect(
365
+ messages.some(
366
+ (m) => m.type === 'system_notification' && m.subtype === 'init',
367
+ ),
368
+ ).toBe(true)
369
+ })
370
+
371
+ it('should handle permission_response without error', async () => {
372
+ const messages: any[] = []
373
+ const ws = new WebSocket(`${wsUrl}/ws/chat-test-4`)
374
+
375
+ await new Promise<void>((resolve) => {
376
+ ws.onmessage = (e) => {
377
+ const msg = JSON.parse(e.data as string)
378
+ messages.push(msg)
379
+ if (msg.type === 'connected') {
380
+ // Send a permission response (no active session, should not crash)
381
+ ws.send(
382
+ JSON.stringify({
383
+ type: 'permission_response',
384
+ requestId: 'test-req-1',
385
+ allowed: true,
386
+ })
387
+ )
388
+ // Give a moment then close
389
+ setTimeout(() => {
390
+ ws.close()
391
+ resolve()
392
+ }, 500)
393
+ }
394
+ }
395
+ ws.onerror = () => {
396
+ ws.close()
397
+ resolve()
398
+ }
399
+ setTimeout(() => {
400
+ ws.close()
401
+ resolve()
402
+ }, 3000)
403
+ })
404
+
405
+ // Should have received connected and no error
406
+ expect(messages[0].type).toBe('connected')
407
+ expect(messages.some((m) => m.type === 'error')).toBe(false)
408
+ })
409
+
410
+ it('should handle ping/pong', async () => {
411
+ const messages: any[] = []
412
+ const ws = new WebSocket(`${wsUrl}/ws/chat-test-5`)
413
+
414
+ await new Promise<void>((resolve) => {
415
+ ws.onmessage = (e) => {
416
+ const msg = JSON.parse(e.data as string)
417
+ messages.push(msg)
418
+ if (msg.type === 'connected') {
419
+ ws.send(JSON.stringify({ type: 'ping' }))
420
+ }
421
+ if (msg.type === 'pong') {
422
+ ws.close()
423
+ resolve()
424
+ }
425
+ }
426
+ ws.onerror = () => {
427
+ ws.close()
428
+ resolve()
429
+ }
430
+ setTimeout(() => {
431
+ ws.close()
432
+ resolve()
433
+ }, 3000)
434
+ })
435
+
436
+ expect(messages.some((m) => m.type === 'pong')).toBe(true)
437
+ })
438
+
439
+ it('should start a placeholder REST session and continue it on a later reconnect', async () => {
440
+ const createRes = await fetch(`${baseUrl}/api/sessions`, {
441
+ method: 'POST',
442
+ headers: { 'Content-Type': 'application/json' },
443
+ body: JSON.stringify({ workDir: process.cwd() }),
444
+ })
445
+ expect(createRes.status).toBe(201)
446
+ const { sessionId } = await createRes.json() as { sessionId: string }
447
+
448
+ const firstTurn = await runTurn(sessionId, 'reply with first')
449
+ expect(firstTurn.some((m) => m.type === 'message_complete')).toBe(true)
450
+ expect(firstTurn.some((m) => m.type === 'error')).toBe(false)
451
+
452
+ await new Promise((resolve) => setTimeout(resolve, 1000))
453
+
454
+ const secondTurn = await runTurn(sessionId, 'reply with second')
455
+ expect(secondTurn.some((m) => m.type === 'message_complete')).toBe(true)
456
+ expect(secondTurn.some((m) => m.type === 'error')).toBe(false)
457
+ })
458
+ })