summaryrefslogtreecommitdiff
path: root/internal/api/logs.go
blob: 1ba4b0045cd50b480d57e1aaf6eecd35bd1a9711 (plain)
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
package api

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"

	"github.com/thepeterstone/claudomator/internal/storage"
	"github.com/thepeterstone/claudomator/internal/task"
)

// logStore is the minimal storage interface needed by handleStreamLogs.
type logStore interface {
	GetExecution(id string) (*storage.Execution, error)
}

// taskLogStore is the minimal storage interface needed by handleStreamTaskLogs.
type taskLogStore interface {
	GetExecution(id string) (*storage.Execution, error)
	GetLatestExecution(taskID string) (*storage.Execution, error)
}

const maxTailDuration = 30 * time.Minute

var terminalStates = map[string]bool{
	string(task.StateCompleted):      true,
	string(task.StateFailed):         true,
	string(task.StateTimedOut):       true,
	string(task.StateCancelled):      true,
	string(task.StateBudgetExceeded): true,
}

type logStreamMsg struct {
	Type    string        `json:"type"`
	Message *logAssistMsg `json:"message,omitempty"`
	CostUSD float64       `json:"cost_usd,omitempty"`
}

type logAssistMsg struct {
	Content []logContentBlock `json:"content"`
}

type logContentBlock struct {
	Type  string          `json:"type"`
	Text  string          `json:"text,omitempty"`
	Name  string          `json:"name,omitempty"`
	Input json.RawMessage `json:"input,omitempty"`
}

// handleStreamTaskLogs streams the latest execution log for a task via SSE.
// GET /api/tasks/{id}/logs/stream
func (s *Server) handleStreamTaskLogs(w http.ResponseWriter, r *http.Request) {
	taskID := r.PathValue("id")
	exec, err := s.taskLogStore.GetLatestExecution(taskID)
	if err != nil {
		http.Error(w, "task not found", http.StatusNotFound)
		return
	}

	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("X-Accel-Buffering", "no")

	flusher, ok := w.(http.Flusher)
	if !ok {
		http.Error(w, "streaming not supported", http.StatusInternalServerError)
		return
	}

	ctx := r.Context()

	if terminalStates[exec.Status] {
		if exec.StdoutPath != "" {
			if f, err := os.Open(exec.StdoutPath); err == nil {
				defer f.Close()
				var offset int64
				for _, line := range readNewLines(f, &offset) {
					select {
					case <-ctx.Done():
						return
					default:
					}
					emitLogLine(w, flusher, line)
				}
			}
		}
	} else if exec.Status == string(task.StateRunning) {
		tailRunningExecution(ctx, w, flusher, s.taskLogStore, exec)
		return
	}

	fmt.Fprintf(w, "event: done\ndata: {}\n\n")
	flusher.Flush()
}

// handleStreamLogs streams parsed execution log content via SSE.
// GET /api/executions/{id}/logs/stream
func (s *Server) handleStreamLogs(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	exec, err := s.logStore.GetExecution(id)
	if err != nil {
		http.Error(w, "execution not found", http.StatusNotFound)
		return
	}

	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("X-Accel-Buffering", "no")

	flusher, ok := w.(http.Flusher)
	if !ok {
		http.Error(w, "streaming not supported", http.StatusInternalServerError)
		return
	}

	ctx := r.Context()

	if terminalStates[exec.Status] {
		if exec.StdoutPath != "" {
			if f, err := os.Open(exec.StdoutPath); err == nil {
				defer f.Close()
				var offset int64
				for _, line := range readNewLines(f, &offset) {
					select {
					case <-ctx.Done():
						return
					default:
					}
					emitLogLine(w, flusher, line)
				}
			}
		}
	} else if exec.Status == string(task.StateRunning) {
		tailRunningExecution(ctx, w, flusher, s.logStore, exec)
		return // tailRunningExecution sends the done event
	}

	fmt.Fprintf(w, "event: done\ndata: {}\n\n")
	flusher.Flush()
}

// tailRunningExecution live-tails the stdout log for a RUNNING execution, polling every 250ms.
// It returns when the execution transitions to a terminal state, the context is cancelled,
// or after maxTailDuration (safety guard against goroutine leaks).
func tailRunningExecution(ctx context.Context, w http.ResponseWriter, flusher http.Flusher, store logStore, exec *storage.Execution) {
	var (
		f      *os.File
		offset int64
	)

	// Emit any content already written to the log file.
	if exec.StdoutPath != "" {
		var err error
		f, err = os.Open(exec.StdoutPath)
		if err == nil {
			defer f.Close()
			for _, line := range readNewLines(f, &offset) {
				select {
				case <-ctx.Done():
					return
				default:
				}
				emitLogLine(w, flusher, line)
			}
		}
	}

	ticker := time.NewTicker(250 * time.Millisecond)
	defer ticker.Stop()
	deadline := time.NewTimer(maxTailDuration)
	defer deadline.Stop()

	for {
		select {
		case <-ctx.Done():
			return
		case <-deadline.C:
			fmt.Fprintf(w, "event: done\ndata: {}\n\n")
			flusher.Flush()
			return
		case <-ticker.C:
			// If the log file wasn't open yet, try now (may have been created since).
			if f == nil && exec.StdoutPath != "" {
				var err error
				f, err = os.Open(exec.StdoutPath)
				if err != nil {
					f = nil
				} else {
					defer f.Close()
				}
			}

			// Emit any new complete lines.
			if f != nil {
				for _, line := range readNewLines(f, &offset) {
					emitLogLine(w, flusher, line)
				}
			}

			// Re-fetch execution status from DB.
			updated, err := store.GetExecution(exec.ID)
			if err != nil {
				fmt.Fprintf(w, "event: done\ndata: {}\n\n")
				flusher.Flush()
				return
			}
			if terminalStates[updated.Status] {
				// Flush any remaining content written between the last read and now.
				if f != nil {
					for _, line := range readNewLines(f, &offset) {
						emitLogLine(w, flusher, line)
					}
				}
				fmt.Fprintf(w, "event: done\ndata: {}\n\n")
				flusher.Flush()
				return
			}
		}
	}
}

// readNewLines reads all complete lines from f starting at *offset.
// It advances *offset past the last newline so partial trailing lines
// are deferred to the next call (safe for live-tailing growing files).
func readNewLines(f *os.File, offset *int64) [][]byte {
	if _, err := f.Seek(*offset, io.SeekStart); err != nil {
		return nil
	}
	data, err := io.ReadAll(f)
	if err != nil || len(data) == 0 {
		return nil
	}
	lastNL := bytes.LastIndexByte(data, '\n')
	if lastNL < 0 {
		return nil // no complete line yet
	}
	*offset += int64(lastNL + 1)
	return bytes.Split(data[:lastNL], []byte("\n"))
}

// emitLogLine parses a single stream-json line and emits corresponding SSE events.
func emitLogLine(w http.ResponseWriter, flusher http.Flusher, line []byte) {
	if len(line) == 0 {
		return
	}
	var msg logStreamMsg
	if err := json.Unmarshal(line, &msg); err != nil {
		return
	}
	switch msg.Type {
	case "assistant":
		if msg.Message == nil {
			return
		}
		for _, block := range msg.Message.Content {
			var event map[string]string
			switch block.Type {
			case "text":
				event = map[string]string{"type": "text", "content": block.Text}
			case "tool_use":
				summary := string(block.Input)
				if len(summary) > 80 {
					summary = summary[:80]
				}
				event = map[string]string{"type": "tool_use", "content": fmt.Sprintf("%s(%s)", block.Name, summary)}
			default:
				continue
			}
			data, _ := json.Marshal(event)
			fmt.Fprintf(w, "data: %s\n\n", data)
			flusher.Flush()
		}
	case "result":
		event := map[string]string{
			"type":    "cost",
			"content": fmt.Sprintf("%g", msg.CostUSD),
		}
		data, _ := json.Marshal(event)
		fmt.Fprintf(w, "data: %s\n\n", data)
		flusher.Flush()
	}
}