Repository navigation
Expand file tree
/
Copy pathuseTaskEvents.ts
More file actions
130 lines (111 loc) · 3.31 KB
/
Copy pathuseTaskEvents.ts
File metadata and controls
130 lines (111 loc) · 3.31 KB
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
import { useEffect, useRef, useState, useCallback } from "react";
export interface TaskEvent {
type: "progress" | "done" | "error";
stage?: string;
status?: string;
agent?: string;
summary?: string;
detail?: string;
/* done-specific fields */
run_id?: number;
findings_count?: number;
recommendations_count?: number;
error?: string | null;
message?: string;
}
interface UseTaskEventsOptions {
/** Called when the task finishes (status == done). */
onDone?: (event: TaskEvent) => void;
/** Enable/disable the connection. Defaults to true. */
enabled?: boolean;
}
/**
* Subscribe to real-time task progress via Server-Sent Events.
*
* Returns an array of received events and a boolean indicating whether
* the connection is still active.
*/
export function useTaskEvents(
taskId: string | null | undefined,
options: UseTaskEventsOptions = {},
) {
const { onDone, enabled = true } = options;
const [events, setEvents] = useState<TaskEvent[]>([]);
const [isStreaming, setIsStreaming] = useState(false);
const onDoneRef = useRef(onDone);
onDoneRef.current = onDone;
const reset = useCallback(() => {
setEvents([]);
setIsStreaming(false);
}, []);
useEffect(() => {
if (!taskId || !enabled) {
return;
}
const controller = new AbortController();
let cancelled = false;
setIsStreaming(true);
setEvents([]);
const handleMessage = (data: string) => {
try {
const event: TaskEvent = JSON.parse(data);
setEvents((prev) => [...prev, event]);
if (event.type === "done" || event.type === "error") {
setIsStreaming(false);
controller.abort();
onDoneRef.current?.(event);
}
} catch {
// Ignore malformed events
}
};
const readStream = async () => {
const headers = new Headers();
const token = localStorage.getItem("opencmo_token");
if (token) headers.set("Authorization", `Bearer ${token}`);
try {
const resp = await fetch(`/api/v1/tasks/${taskId}/events`, {
headers,
signal: controller.signal,
});
if (resp.status === 401) {
window.dispatchEvent(new CustomEvent("opencmo:unauthorized"));
}
if (!resp.ok || !resp.body) {
setIsStreaming(false);
return;
}
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (!cancelled) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const chunks = buffer.split("\n\n");
buffer = chunks.pop() ?? "";
for (const chunk of chunks) {
const data = chunk
.split("\n")
.filter((line) => line.startsWith("data:"))
.map((line) => line.slice(5).trimStart())
.join("\n");
if (data) handleMessage(data);
}
}
} catch {
if (!controller.signal.aborted) {
setIsStreaming(false);
}
return;
}
if (!cancelled) setIsStreaming(false);
};
void readStream();
return () => {
cancelled = true;
controller.abort();
};
}, [taskId, enabled]);
return { events, isStreaming, reset };
}