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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
|
package api
import (
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/thepeterstone/claudomator/internal/storage"
)
// mockTaskLogStore implements taskLogStore for testing handleStreamTaskLogs.
type mockTaskLogStore struct {
getExecution func(id string) (*storage.Execution, error)
getLatestExecution func(taskID string) (*storage.Execution, error)
}
func (m *mockTaskLogStore) GetExecution(id string) (*storage.Execution, error) {
return m.getExecution(id)
}
func (m *mockTaskLogStore) GetLatestExecution(taskID string) (*storage.Execution, error) {
return m.getLatestExecution(taskID)
}
func taskLogsMux(srv *Server) *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("GET /api/tasks/{id}/logs/stream", srv.handleStreamTaskLogs)
return mux
}
// mockLogStore implements logStore for testing.
type mockLogStore struct {
fn func(id string) (*storage.Execution, error)
}
func (m *mockLogStore) GetExecution(id string) (*storage.Execution, error) {
return m.fn(id)
}
func logsMux(srv *Server) *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("GET /api/executions/{id}/logs", srv.handleStreamLogs)
return mux
}
// TestHandleStreamLogs_NotFound verifies that an unknown execution ID yields 404.
func TestHandleStreamLogs_NotFound(t *testing.T) {
srv := &Server{
logStore: &mockLogStore{fn: func(id string) (*storage.Execution, error) {
return nil, errors.New("not found")
}},
}
req := httptest.NewRequest("GET", "/api/executions/nonexistent/logs", nil)
w := httptest.NewRecorder()
logsMux(srv).ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Errorf("status: want 404, got %d; body: %s", w.Code, w.Body.String())
}
}
// TestHandleStreamLogs_TerminalState_EmitsEventsAndDone verifies that a COMPLETED
// execution with a populated stdout.log streams SSE events and terminates with a done event.
func TestHandleStreamLogs_TerminalState_EmitsEventsAndDone(t *testing.T) {
dir := t.TempDir()
logPath := filepath.Join(dir, "stdout.log")
lines := strings.Join([]string{
`{"type":"assistant","message":{"content":[{"type":"text","text":"Hello world"}]}}`,
`{"type":"assistant","message":{"content":[{"type":"tool_use","name":"Bash","input":{"command":"ls"}}]}}`,
`{"type":"result","cost_usd":0.0042}`,
}, "\n") + "\n"
if err := os.WriteFile(logPath, []byte(lines), 0600); err != nil {
t.Fatal(err)
}
exec := &storage.Execution{
ID: "exec-terminal-1",
TaskID: "task-terminal-1",
StartTime: time.Now(),
Status: "COMPLETED",
StdoutPath: logPath,
}
srv := &Server{
logStore: &mockLogStore{fn: func(id string) (*storage.Execution, error) {
return exec, nil
}},
}
req := httptest.NewRequest("GET", "/api/executions/exec-terminal-1/logs", nil)
w := httptest.NewRecorder()
logsMux(srv).ServeHTTP(w, req)
if ct := w.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/event-stream") {
t.Errorf("Content-Type: want text/event-stream, got %q", ct)
}
body := w.Body.String()
if !strings.Contains(body, "data: ") {
t.Error("expected at least one SSE 'data: ' event in body")
}
if !strings.Contains(body, "\n\n") {
t.Error("expected SSE double-newline event termination")
}
if !strings.HasSuffix(body, "event: done\ndata: {}\n\n") {
t.Errorf("body does not end with done event; got:\n%s", body)
}
}
// TestHandleStreamLogs_EmptyLog verifies that a COMPLETED execution with no stdout path
// responds with only the done sentinel event.
func TestHandleStreamLogs_EmptyLog(t *testing.T) {
exec := &storage.Execution{
ID: "exec-empty-1",
TaskID: "task-empty-1",
StartTime: time.Now(),
Status: "COMPLETED",
// StdoutPath intentionally empty
}
srv := &Server{
logStore: &mockLogStore{fn: func(id string) (*storage.Execution, error) {
return exec, nil
}},
}
req := httptest.NewRequest("GET", "/api/executions/exec-empty-1/logs", nil)
w := httptest.NewRecorder()
logsMux(srv).ServeHTTP(w, req)
body := w.Body.String()
if body != "event: done\ndata: {}\n\n" {
t.Errorf("want only done event, got:\n%s", body)
}
}
// TestHandleStreamLogs_RunningState_LiveTail verifies that a RUNNING execution streams
// initial log content and emits a done event once it transitions to a terminal state.
func TestHandleStreamLogs_RunningState_LiveTail(t *testing.T) {
dir := t.TempDir()
logPath := filepath.Join(dir, "stdout.log")
logLines := strings.Join([]string{
`{"type":"assistant","message":{"content":[{"type":"text","text":"Working..."}]}}`,
`{"type":"result","cost_usd":0.001}`,
}, "\n") + "\n"
if err := os.WriteFile(logPath, []byte(logLines), 0600); err != nil {
t.Fatal(err)
}
runningExec := &storage.Execution{
ID: "exec-running-1",
TaskID: "task-running-1",
StartTime: time.Now(),
Status: "RUNNING",
StdoutPath: logPath,
}
// callCount tracks how many times GetExecution has been called.
// Call 1: initial fetch in handleStreamLogs → RUNNING
// Call 2+: poll in tailRunningExecution → COMPLETED
var callCount atomic.Int32
mock := &mockLogStore{fn: func(id string) (*storage.Execution, error) {
n := callCount.Add(1)
if n <= 1 {
return runningExec, nil
}
completed := *runningExec
completed.Status = "COMPLETED"
return &completed, nil
}}
srv := &Server{logStore: mock}
req := httptest.NewRequest("GET", "/api/executions/exec-running-1/logs", nil)
w := httptest.NewRecorder()
logsMux(srv).ServeHTTP(w, req)
body := w.Body.String()
if !strings.Contains(body, `"Working..."`) {
t.Errorf("expected initial text event in body; got:\n%s", body)
}
if !strings.Contains(body, `"type":"cost"`) {
t.Errorf("expected cost event in body; got:\n%s", body)
}
if !strings.HasSuffix(body, "event: done\ndata: {}\n\n") {
t.Errorf("body does not end with done event; got:\n%s", body)
}
}
// --- Task-level SSE log streaming tests (handleStreamTaskLogs) ---
// TestHandleStreamTaskLogs_TaskNotFound verifies that a task with no executions yields 404.
func TestHandleStreamTaskLogs_TaskNotFound(t *testing.T) {
srv := &Server{
taskLogStore: &mockTaskLogStore{
getLatestExecution: func(taskID string) (*storage.Execution, error) {
return nil, errors.New("not found")
},
},
}
req := httptest.NewRequest("GET", "/api/tasks/nonexistent/logs/stream", nil)
w := httptest.NewRecorder()
taskLogsMux(srv).ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Errorf("status: want 404, got %d; body: %s", w.Code, w.Body.String())
}
}
// TestHandleStreamTaskLogs_NoStdoutPath_EmitsDone verifies that a completed execution with no
// stdout log path emits only the done sentinel event.
func TestHandleStreamTaskLogs_NoStdoutPath_EmitsDone(t *testing.T) {
exec := &storage.Execution{
ID: "exec-task-empty",
TaskID: "task-no-log",
StartTime: time.Now(),
Status: "COMPLETED",
// StdoutPath intentionally empty
}
srv := &Server{
taskLogStore: &mockTaskLogStore{
getLatestExecution: func(taskID string) (*storage.Execution, error) {
return exec, nil
},
getExecution: func(id string) (*storage.Execution, error) {
return exec, nil
},
},
}
req := httptest.NewRequest("GET", "/api/tasks/task-no-log/logs/stream", nil)
w := httptest.NewRecorder()
taskLogsMux(srv).ServeHTTP(w, req)
if ct := w.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/event-stream") {
t.Errorf("Content-Type: want text/event-stream, got %q", ct)
}
body := w.Body.String()
if body != "event: done\ndata: {}\n\n" {
t.Errorf("want only done event, got:\n%s", body)
}
}
// TestHandleStreamTaskLogs_TerminalExecution_EmitsEventsAndDone verifies that a COMPLETED
// execution streams SSE events and ends with a done event.
func TestHandleStreamTaskLogs_TerminalExecution_EmitsEventsAndDone(t *testing.T) {
dir := t.TempDir()
logPath := filepath.Join(dir, "stdout.log")
lines := strings.Join([]string{
`{"type":"assistant","message":{"content":[{"type":"text","text":"Task output here"}]}}`,
`{"type":"result","cost_usd":0.007}`,
}, "\n") + "\n"
if err := os.WriteFile(logPath, []byte(lines), 0600); err != nil {
t.Fatal(err)
}
exec := &storage.Execution{
ID: "exec-task-done",
TaskID: "task-done",
StartTime: time.Now(),
Status: "COMPLETED",
StdoutPath: logPath,
}
srv := &Server{
taskLogStore: &mockTaskLogStore{
getLatestExecution: func(taskID string) (*storage.Execution, error) {
return exec, nil
},
getExecution: func(id string) (*storage.Execution, error) {
return exec, nil
},
},
}
req := httptest.NewRequest("GET", "/api/tasks/task-done/logs/stream", nil)
w := httptest.NewRecorder()
taskLogsMux(srv).ServeHTTP(w, req)
body := w.Body.String()
if !strings.Contains(body, `"Task output here"`) {
t.Errorf("expected text event content in body; got:\n%s", body)
}
if !strings.Contains(body, `"type":"cost"`) {
t.Errorf("expected cost event in body; got:\n%s", body)
}
if !strings.HasSuffix(body, "event: done\ndata: {}\n\n") {
t.Errorf("body does not end with done event; got:\n%s", body)
}
}
// TestEmitLogLine_ToolUse_EmitsNameField verifies that emitLogLine emits a tool_use SSE event
// with a "name" field matching the tool name so the web UI can display it as "[ToolName]".
func TestEmitLogLine_ToolUse_EmitsNameField(t *testing.T) {
line := []byte(`{"type":"assistant","message":{"content":[{"type":"tool_use","name":"Bash","input":{"command":"ls -la"}}]}}`)
w := httptest.NewRecorder()
emitLogLine(w, w, line)
body := w.Body.String()
var found bool
for _, chunk := range strings.Split(body, "\n\n") {
chunk = strings.TrimSpace(chunk)
if !strings.HasPrefix(chunk, "data: ") {
continue
}
jsonStr := strings.TrimPrefix(chunk, "data: ")
var e map[string]interface{}
if err := json.Unmarshal([]byte(jsonStr), &e); err != nil {
continue
}
if e["type"] == "tool_use" {
if e["name"] != "Bash" {
t.Errorf("tool_use event name: want Bash, got %v", e["name"])
}
if e["input"] == nil {
t.Error("tool_use event input: expected non-nil")
}
found = true
}
}
if !found {
t.Errorf("no tool_use event found in SSE output:\n%s", body)
}
}
// TestEmitLogLine_Cost_EmitsTotalCostField verifies that emitLogLine emits a cost SSE event
// with a numeric "total_cost" field so the web UI can display it correctly.
func TestEmitLogLine_Cost_EmitsTotalCostField(t *testing.T) {
line := []byte(`{"type":"result","total_cost_usd":0.0042}`)
w := httptest.NewRecorder()
emitLogLine(w, w, line)
body := w.Body.String()
var found bool
for _, chunk := range strings.Split(body, "\n\n") {
chunk = strings.TrimSpace(chunk)
if !strings.HasPrefix(chunk, "data: ") {
continue
}
jsonStr := strings.TrimPrefix(chunk, "data: ")
var e map[string]interface{}
if err := json.Unmarshal([]byte(jsonStr), &e); err != nil {
continue
}
if e["type"] == "cost" {
if e["total_cost"] == nil {
t.Error("cost event total_cost: expected non-nil numeric field")
}
if v, ok := e["total_cost"].(float64); !ok || v != 0.0042 {
t.Errorf("cost event total_cost: want 0.0042, got %v", e["total_cost"])
}
found = true
}
}
if !found {
t.Errorf("no cost event found in SSE output:\n%s", body)
}
}
// TestHandleStreamTaskLogs_RunningExecution_LiveTails verifies that a RUNNING execution is
// live-tailed and a done event is emitted once it transitions to a terminal state.
func TestHandleStreamTaskLogs_RunningExecution_LiveTails(t *testing.T) {
dir := t.TempDir()
logPath := filepath.Join(dir, "stdout.log")
logLines := strings.Join([]string{
`{"type":"assistant","message":{"content":[{"type":"text","text":"Still running..."}]}}`,
`{"type":"result","cost_usd":0.003}`,
}, "\n") + "\n"
if err := os.WriteFile(logPath, []byte(logLines), 0600); err != nil {
t.Fatal(err)
}
runningExec := &storage.Execution{
ID: "exec-task-running",
TaskID: "task-running",
StartTime: time.Now(),
Status: "RUNNING",
StdoutPath: logPath,
}
// getLatestExecution is called once (initial lookup); getExecution polls for state change.
var pollCount atomic.Int32
srv := &Server{
taskLogStore: &mockTaskLogStore{
getLatestExecution: func(taskID string) (*storage.Execution, error) {
return runningExec, nil
},
getExecution: func(id string) (*storage.Execution, error) {
n := pollCount.Add(1)
if n <= 1 {
return runningExec, nil
}
completed := *runningExec
completed.Status = "COMPLETED"
return &completed, nil
},
},
}
req := httptest.NewRequest("GET", "/api/tasks/task-running/logs/stream", nil)
w := httptest.NewRecorder()
taskLogsMux(srv).ServeHTTP(w, req)
body := w.Body.String()
if !strings.Contains(body, `"Still running..."`) {
t.Errorf("expected live-tail text in body; got:\n%s", body)
}
if !strings.HasSuffix(body, "event: done\ndata: {}\n\n") {
t.Errorf("body does not end with done event; got:\n%s", body)
}
}
|