summaryrefslogtreecommitdiff
path: root/makima/frontend/src/hooks/useDirectives.ts
blob: 6e1654f02379ad4d08c9b7bc385402f3c0715160 (plain) (blame)
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
import { useState, useCallback, useEffect, useRef } from "react";
import {
  listDirectives,
  getDirective,
  createDirective,
  updateDirective,
  archiveDirective,
  startDirective,
  pauseDirective,
  resumeDirective,
  stopDirective,
  getDirectiveGraph,
  subscribeToDirectiveEvents,
  type DirectiveSummary,
  type DirectiveWithProgress,
  type DirectiveGraphResponse,
  type DirectiveStatus,
  type DirectiveEvent,
  type CreateDirectiveRequest,
  type UpdateDirectiveRequest,
  type StartDirectiveResponse,
} from "../lib/api";

interface UseDirectivesResult {
  directives: DirectiveSummary[];
  loading: boolean;
  error: string | null;
  refresh: () => Promise<void>;
  createNewDirective: (req: CreateDirectiveRequest) => Promise<DirectiveWithProgress | null>;
  updateExistingDirective: (
    directiveId: string,
    req: UpdateDirectiveRequest
  ) => Promise<DirectiveWithProgress | null>;
  archiveExistingDirective: (directiveId: string) => Promise<boolean>;
  getDirectiveById: (directiveId: string) => Promise<DirectiveWithProgress | null>;
  getGraph: (directiveId: string) => Promise<DirectiveGraphResponse | null>;
  start: (directiveId: string) => Promise<StartDirectiveResponse | null>;
  pause: (directiveId: string) => Promise<boolean>;
  resume: (directiveId: string) => Promise<boolean>;
  stop: (directiveId: string) => Promise<boolean>;
}

export function useDirectives(statusFilter?: DirectiveStatus): UseDirectivesResult {
  const [directives, setDirectives] = useState<DirectiveSummary[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchDirectives = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await listDirectives(statusFilter);
      setDirectives(response.directives);
    } catch (err) {
      console.error("Failed to fetch directives:", err);
      setError(err instanceof Error ? err.message : "Failed to fetch directives");
    } finally {
      setLoading(false);
    }
  }, [statusFilter]);

  useEffect(() => {
    fetchDirectives();
  }, [fetchDirectives]);

  const createNewDirective = useCallback(
    async (req: CreateDirectiveRequest): Promise<DirectiveWithProgress | null> => {
      try {
        const directive = await createDirective(req);
        // Refresh the list
        await fetchDirectives();
        // Return the full directive with progress
        return await getDirective(directive.id);
      } catch (err) {
        console.error("Failed to create directive:", err);
        setError(err instanceof Error ? err.message : "Failed to create directive");
        return null;
      }
    },
    [fetchDirectives]
  );

  const updateExistingDirective = useCallback(
    async (
      directiveId: string,
      req: UpdateDirectiveRequest
    ): Promise<DirectiveWithProgress | null> => {
      try {
        await updateDirective(directiveId, req);
        // Refresh the list
        await fetchDirectives();
        // Return the updated directive
        return await getDirective(directiveId);
      } catch (err) {
        console.error("Failed to update directive:", err);
        setError(err instanceof Error ? err.message : "Failed to update directive");
        return null;
      }
    },
    [fetchDirectives]
  );

  const archiveExistingDirective = useCallback(
    async (directiveId: string): Promise<boolean> => {
      try {
        await archiveDirective(directiveId);
        // Refresh the list
        await fetchDirectives();
        return true;
      } catch (err) {
        console.error("Failed to archive directive:", err);
        setError(err instanceof Error ? err.message : "Failed to archive directive");
        return false;
      }
    },
    [fetchDirectives]
  );

  const getDirectiveById = useCallback(
    async (directiveId: string): Promise<DirectiveWithProgress | null> => {
      try {
        return await getDirective(directiveId);
      } catch (err) {
        console.error("Failed to get directive:", err);
        setError(err instanceof Error ? err.message : "Failed to get directive");
        return null;
      }
    },
    []
  );

  const getGraph = useCallback(
    async (directiveId: string): Promise<DirectiveGraphResponse | null> => {
      try {
        return await getDirectiveGraph(directiveId);
      } catch (err) {
        console.error("Failed to get directive graph:", err);
        setError(err instanceof Error ? err.message : "Failed to get directive graph");
        return null;
      }
    },
    []
  );

  const start = useCallback(
    async (directiveId: string): Promise<StartDirectiveResponse | null> => {
      try {
        const response = await startDirective(directiveId);
        await fetchDirectives();
        return response;
      } catch (err) {
        console.error("Failed to start directive:", err);
        setError(err instanceof Error ? err.message : "Failed to start directive");
        return null;
      }
    },
    [fetchDirectives]
  );

  const pause = useCallback(
    async (directiveId: string): Promise<boolean> => {
      try {
        await pauseDirective(directiveId);
        await fetchDirectives();
        return true;
      } catch (err) {
        console.error("Failed to pause directive:", err);
        setError(err instanceof Error ? err.message : "Failed to pause directive");
        return false;
      }
    },
    [fetchDirectives]
  );

  const resume = useCallback(
    async (directiveId: string): Promise<boolean> => {
      try {
        await resumeDirective(directiveId);
        await fetchDirectives();
        return true;
      } catch (err) {
        console.error("Failed to resume directive:", err);
        setError(err instanceof Error ? err.message : "Failed to resume directive");
        return false;
      }
    },
    [fetchDirectives]
  );

  const stop = useCallback(
    async (directiveId: string): Promise<boolean> => {
      try {
        await stopDirective(directiveId);
        await fetchDirectives();
        return true;
      } catch (err) {
        console.error("Failed to stop directive:", err);
        setError(err instanceof Error ? err.message : "Failed to stop directive");
        return false;
      }
    },
    [fetchDirectives]
  );

  return {
    directives,
    loading,
    error,
    refresh: fetchDirectives,
    createNewDirective,
    updateExistingDirective,
    archiveExistingDirective,
    getDirectiveById,
    getGraph,
    start,
    pause,
    resume,
    stop,
  };
}

/** Hook for subscribing to real-time directive events via SSE */
export function useDirectiveEventSubscription(
  directiveId: string | null,
  onEvent?: (event: DirectiveEvent) => void
): {
  events: DirectiveEvent[];
  isConnected: boolean;
  error: string | null;
} {
  const [events, setEvents] = useState<DirectiveEvent[]>([]);
  const [isConnected, setIsConnected] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const cleanupRef = useRef<(() => void) | null>(null);

  useEffect(() => {
    // Clean up any existing subscription
    if (cleanupRef.current) {
      cleanupRef.current();
      cleanupRef.current = null;
    }

    if (!directiveId) {
      setIsConnected(false);
      setEvents([]);
      return;
    }

    // Subscribe to events
    let mounted = true;

    const setupSubscription = async () => {
      try {
        const cleanup = await subscribeToDirectiveEvents(
          directiveId,
          (event) => {
            if (mounted) {
              setEvents((prev) => [...prev, event]);
              onEvent?.(event);
            }
          },
          (err) => {
            if (mounted) {
              setError(err.message);
              setIsConnected(false);
            }
          }
        );

        if (mounted) {
          cleanupRef.current = cleanup;
          setIsConnected(true);
          setError(null);
        } else {
          // Component unmounted during setup, clean up immediately
          cleanup();
        }
      } catch (err) {
        if (mounted) {
          setError(err instanceof Error ? err.message : "Failed to subscribe to events");
          setIsConnected(false);
        }
      }
    };

    setupSubscription();

    return () => {
      mounted = false;
      if (cleanupRef.current) {
        cleanupRef.current();
        cleanupRef.current = null;
      }
    };
  }, [directiveId, onEvent]);

  return { events, isConnected, error };
}