summaryrefslogtreecommitdiff
path: root/makima/frontend/src/hooks/useFileSubscription.ts
blob: 7260b969ccfc6b9d14fdf0432e7d99baf59a7636 (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
import { useState, useCallback, useRef, useEffect } from "react";
import { FILE_SUBSCRIBE_ENDPOINT } from "../lib/api";

export interface FileUpdateEvent {
  fileId: string;
  version: number;
  updatedFields: string[];
  updatedBy: "user" | "llm" | "system";
}

interface UseFileSubscriptionOptions {
  fileId: string | null;
  onUpdate?: (event: FileUpdateEvent) => void;
  onError?: (error: string) => void;
}

export function useFileSubscription(options: UseFileSubscriptionOptions) {
  const { fileId, onUpdate, onError } = options;
  const [connected, setConnected] = useState(false);
  const wsRef = useRef<WebSocket | null>(null);
  const reconnectTimeoutRef = useRef<number | null>(null);
  const subscribedFileRef = useRef<string | null>(null);

  // Store callbacks in refs to avoid re-connecting when callbacks change
  const callbacksRef = useRef({ onUpdate, onError });
  useEffect(() => {
    callbacksRef.current = { onUpdate, onError };
  }, [onUpdate, onError]);

  const connect = useCallback(() => {
    if (wsRef.current?.readyState === WebSocket.OPEN) return;

    try {
      const ws = new WebSocket(FILE_SUBSCRIBE_ENDPOINT);
      wsRef.current = ws;

      ws.onopen = () => {
        setConnected(true);
        // Re-subscribe if we had a subscription
        if (subscribedFileRef.current) {
          ws.send(
            JSON.stringify({
              type: "subscribe",
              fileId: subscribedFileRef.current,
            })
          );
        }
      };

      ws.onmessage = (event) => {
        try {
          const message = JSON.parse(event.data);

          if (message.type === "fileUpdated") {
            callbacksRef.current.onUpdate?.({
              fileId: message.fileId,
              version: message.version,
              updatedFields: message.updatedFields,
              updatedBy: message.updatedBy,
            });
          } else if (message.type === "error") {
            callbacksRef.current.onError?.(message.message);
          }
        } catch (e) {
          console.error("Failed to parse file subscription message:", e);
        }
      };

      ws.onerror = () => {
        callbacksRef.current.onError?.("WebSocket connection error");
      };

      ws.onclose = () => {
        setConnected(false);
        wsRef.current = null;

        // Attempt reconnection after 3 seconds if we still have a subscription
        if (subscribedFileRef.current) {
          reconnectTimeoutRef.current = window.setTimeout(() => {
            connect();
          }, 3000);
        }
      };
    } catch (e) {
      callbacksRef.current.onError?.(
        e instanceof Error ? e.message : "Failed to connect"
      );
    }
  }, []);

  const subscribe = useCallback(
    (id: string) => {
      subscribedFileRef.current = id;

      if (wsRef.current?.readyState === WebSocket.OPEN) {
        wsRef.current.send(
          JSON.stringify({
            type: "subscribe",
            fileId: id,
          })
        );
      } else {
        connect();
      }
    },
    [connect]
  );

  const unsubscribe = useCallback(() => {
    if (
      subscribedFileRef.current &&
      wsRef.current?.readyState === WebSocket.OPEN
    ) {
      wsRef.current.send(
        JSON.stringify({
          type: "unsubscribe",
          fileId: subscribedFileRef.current,
        })
      );
    }
    subscribedFileRef.current = null;
  }, []);

  // Auto-subscribe when fileId changes
  useEffect(() => {
    if (fileId) {
      subscribe(fileId);
    } else {
      unsubscribe();
    }

    return () => {
      unsubscribe();
    };
  }, [fileId, subscribe, unsubscribe]);

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      if (reconnectTimeoutRef.current) {
        clearTimeout(reconnectTimeoutRef.current);
      }
      if (wsRef.current) {
        wsRef.current.close();
      }
    };
  }, []);

  return {
    connected,
    subscribe,
    unsubscribe,
  };
}