File size: 11,433 Bytes
1f21206
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
/**
 * Unit tests for CronService, SearchService, and Scheduled Tasks API
 */

import { describe, it, expect, beforeEach, afterEach, spyOn } from 'bun:test'
import * as fs from 'fs/promises'
import * as path from 'path'
import * as os from 'os'
import { CronService } from '../services/cronService.js'
import { SearchService } from '../services/searchService.js'

// โ”€โ”€โ”€ Test helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

let tmpDir: string
const originalConfigDir = process.env.CLAUDE_CONFIG_DIR

async function createTmpDir(): Promise<string> {
  const dir = path.join(os.tmpdir(), `claude-test-${Date.now()}-${Math.random().toString(36).slice(2)}`)
  await fs.mkdir(dir, { recursive: true })
  return dir
}

async function cleanupTmpDir(dir: string): Promise<void> {
  try {
    await fs.rm(dir, { recursive: true, force: true })
  } catch {
    // ignore
  }
}

// โ”€โ”€โ”€ CronService tests โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

describe('CronService', () => {
  let service: CronService

  beforeEach(async () => {
    tmpDir = await createTmpDir()
    process.env.CLAUDE_CONFIG_DIR = tmpDir
    service = new CronService()
  })

  afterEach(async () => {
    if (originalConfigDir) {
      process.env.CLAUDE_CONFIG_DIR = originalConfigDir
    } else {
      delete process.env.CLAUDE_CONFIG_DIR
    }
    await cleanupTmpDir(tmpDir)
  })

  it('should return empty list when no tasks file exists', async () => {
    const tasks = await service.listTasks()
    expect(tasks).toEqual([])
  })

  it('should create a task with generated id and createdAt', async () => {
    const task = await service.createTask({
      cron: '0 9 * * *',
      prompt: 'Review commits',
      recurring: true,
    })

    expect(task.id).toBeDefined()
    expect(task.id).toHaveLength(8) // 4 bytes hex
    expect(task.cron).toBe('0 9 * * *')
    expect(task.prompt).toBe('Review commits')
    expect(task.recurring).toBe(true)
    expect(task.createdAt).toBeGreaterThan(0)
  })

  it('should persist tasks to file', async () => {
    await service.createTask({ cron: '0 9 * * *', prompt: 'Task 1' })
    await service.createTask({ cron: '30 18 * * 5', prompt: 'Task 2' })

    const tasks = await service.listTasks()
    expect(tasks).toHaveLength(2)
    expect(tasks[0].prompt).toBe('Task 1')
    expect(tasks[1].prompt).toBe('Task 2')
  })

  it('should update an existing task', async () => {
    const created = await service.createTask({
      cron: '0 9 * * *',
      prompt: 'Original prompt',
    })

    const updated = await service.updateTask(created.id, {
      prompt: 'Updated prompt',
      recurring: true,
    })

    expect(updated.id).toBe(created.id)
    expect(updated.prompt).toBe('Updated prompt')
    expect(updated.recurring).toBe(true)
    expect(updated.createdAt).toBe(created.createdAt)
  })

  it('should throw when updating a non-existent task', async () => {
    await expect(
      service.updateTask('nonexistent', { prompt: 'x' }),
    ).rejects.toThrow('Task not found')
  })

  it('should delete a task', async () => {
    const created = await service.createTask({
      cron: '0 9 * * *',
      prompt: 'To delete',
    })

    await service.deleteTask(created.id)
    const tasks = await service.listTasks()
    expect(tasks).toHaveLength(0)
  })

  it('should throw when deleting a non-existent task', async () => {
    await expect(service.deleteTask('nonexistent')).rejects.toThrow(
      'Task not found',
    )
  })

  it('should generate unique IDs', async () => {
    const ids = new Set<string>()
    for (let i = 0; i < 20; i++) {
      const task = await service.createTask({
        cron: '* * * * *',
        prompt: `Task ${i}`,
      })
      ids.add(task.id)
    }
    expect(ids.size).toBe(20)
  })

  it('should reject create when cron or prompt is missing', async () => {
    await expect(
      service.createTask({ cron: '', prompt: 'something' }),
    ).rejects.toThrow()

    await expect(
      service.createTask({ cron: '* * * * *', prompt: '' }),
    ).rejects.toThrow()
  })

  it('should retry the atomic write when rename returns ENOENT', async () => {
    const originalRename = fs.rename
    let renameCalls = 0

    const renameSpy = spyOn(fs, 'rename')
    renameSpy.mockImplementation(async (...args) => {
      renameCalls += 1

      if (renameCalls === 1) {
        const error = new Error(
          'ENOENT: no such file or directory, rename tmp -> scheduled_tasks.json',
        ) as NodeJS.ErrnoException
        error.code = 'ENOENT'
        throw error
      }

      return originalRename(...args)
    })

    try {
      const task = await service.createTask({
        cron: '0 9 * * *',
        prompt: 'Retry rename once',
      })

      const tasks = await service.listTasks()
      expect(task.id).toBeDefined()
      expect(tasks).toHaveLength(1)
      expect(tasks[0]?.prompt).toBe('Retry rename once')
      expect(renameCalls).toBe(2)
    } finally {
      renameSpy.mockRestore()
    }
  })
})

// โ”€โ”€โ”€ SearchService tests โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

describe('SearchService', () => {
  let service: SearchService
  let searchDir: string

  beforeEach(async () => {
    tmpDir = await createTmpDir()
    process.env.CLAUDE_CONFIG_DIR = tmpDir
    service = new SearchService()

    // ๅˆ›ๅปบๆœ็ดข็”จ็š„ไธดๆ—ถๆ–‡ไปถ
    searchDir = path.join(tmpDir, 'workspace')
    await fs.mkdir(searchDir, { recursive: true })
    await fs.writeFile(
      path.join(searchDir, 'hello.txt'),
      'Hello World\nThis is a test\nAnother line\n',
    )
    await fs.writeFile(
      path.join(searchDir, 'code.ts'),
      'function greet() {\n  return "hello"\n}\n',
    )
  })

  afterEach(async () => {
    if (originalConfigDir) {
      process.env.CLAUDE_CONFIG_DIR = originalConfigDir
    } else {
      delete process.env.CLAUDE_CONFIG_DIR
    }
    await cleanupTmpDir(tmpDir)
  })

  it('should find matches in workspace files', async () => {
    const results = await service.searchWorkspace('Hello', { cwd: searchDir })
    expect(results.length).toBeGreaterThan(0)
    expect(results[0].text).toContain('Hello')
  })

  it('should return empty results when nothing matches', async () => {
    const results = await service.searchWorkspace('ZZZZNONEXISTENT', {
      cwd: searchDir,
    })
    expect(results).toHaveLength(0)
  })

  it('should respect maxResults limit', async () => {
    // ๅ†™ๅ…ฅๅคš่กŒๅŒน้…
    const lines = Array.from({ length: 50 }, (_, i) => `match line ${i}`).join(
      '\n',
    )
    await fs.writeFile(path.join(searchDir, 'many.txt'), lines)

    const results = await service.searchWorkspace('match', {
      cwd: searchDir,
      maxResults: 5,
    })
    expect(results.length).toBeLessThanOrEqual(5)
  })

  it('should reject empty query', async () => {
    await expect(service.searchWorkspace('')).rejects.toThrow()
  })

  it('should return empty session results when no projects dir exists', async () => {
    const results = await service.searchSessions('test')
    expect(results).toEqual([])
  })
})

// โ”€โ”€โ”€ Scheduled Tasks API integration โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

describe('Scheduled Tasks API', () => {
  // ็›ดๆŽฅๆต‹่ฏ• handler ๅ‡ฝๆ•ฐ๏ผŒไธ้œ€่ฆๅฏๅŠจๅฎŒๆ•ดๆœๅŠกๅ™จ
  let handleScheduledTasksApi: (
    req: Request,
    url: URL,
    segments: string[],
  ) => Promise<Response>

  beforeEach(async () => {
    tmpDir = await createTmpDir()
    process.env.CLAUDE_CONFIG_DIR = tmpDir

    // ๅŠจๆ€ๅฏผๅ…ฅไปฅ่Žทๅ–ๆœ€ๆ–ฐ็š„็Žฏๅขƒๅ˜้‡
    const mod = await import('../api/scheduled-tasks.js')
    handleScheduledTasksApi = mod.handleScheduledTasksApi
  })

  afterEach(async () => {
    if (originalConfigDir) {
      process.env.CLAUDE_CONFIG_DIR = originalConfigDir
    } else {
      delete process.env.CLAUDE_CONFIG_DIR
    }
    await cleanupTmpDir(tmpDir)
  })

  it('should list empty tasks via GET', async () => {
    const req = new Request('http://localhost/api/scheduled-tasks', {
      method: 'GET',
    })
    const url = new URL(req.url)
    const resp = await handleScheduledTasksApi(req, url, [
      'api',
      'scheduled-tasks',
    ])
    const body = (await resp.json()) as { tasks: unknown[] }
    expect(resp.status).toBe(200)
    expect(body.tasks).toEqual([])
  })

  it('should create a task via POST', async () => {
    const req = new Request('http://localhost/api/scheduled-tasks', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        cron: '0 9 * * *',
        prompt: 'Daily review',
        recurring: true,
        model: 'provider-fast',
        providerId: 'provider-a',
      }),
    })
    const url = new URL(req.url)
    const resp = await handleScheduledTasksApi(req, url, [
      'api',
      'scheduled-tasks',
    ])
    const body = (await resp.json()) as {
      task: { id: string; prompt: string; model?: string; providerId?: string }
    }
    expect(resp.status).toBe(201)
    expect(body.task.id).toBeDefined()
    expect(body.task.prompt).toBe('Daily review')
    expect(body.task.model).toBe('provider-fast')
    expect(body.task.providerId).toBe('provider-a')
  })

  it('should CRUD a full lifecycle', async () => {
    // Create
    const createReq = new Request('http://localhost/api/scheduled-tasks', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ cron: '0 9 * * *', prompt: 'Test task' }),
    })
    const createResp = await handleScheduledTasksApi(
      createReq,
      new URL(createReq.url),
      ['api', 'scheduled-tasks'],
    )
    const { task } = (await createResp.json()) as {
      task: { id: string; prompt: string }
    }

    // Update
    const updateReq = new Request(
      `http://localhost/api/scheduled-tasks/${task.id}`,
      {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ prompt: 'Updated task' }),
      },
    )
    const updateResp = await handleScheduledTasksApi(
      updateReq,
      new URL(updateReq.url),
      ['api', 'scheduled-tasks', task.id],
    )
    const updated = (await updateResp.json()) as {
      task: { id: string; prompt: string }
    }
    expect(updated.task.prompt).toBe('Updated task')

    // Delete
    const deleteReq = new Request(
      `http://localhost/api/scheduled-tasks/${task.id}`,
      { method: 'DELETE' },
    )
    const deleteResp = await handleScheduledTasksApi(
      deleteReq,
      new URL(deleteReq.url),
      ['api', 'scheduled-tasks', task.id],
    )
    expect(deleteResp.status).toBe(200)

    // Verify empty
    const listReq = new Request('http://localhost/api/scheduled-tasks', {
      method: 'GET',
    })
    const listResp = await handleScheduledTasksApi(
      listReq,
      new URL(listReq.url),
      ['api', 'scheduled-tasks'],
    )
    const list = (await listResp.json()) as { tasks: unknown[] }
    expect(list.tasks).toHaveLength(0)
  })
})