Matthias Nott
2026-03-07 281834df3070cfbdfc28314ab2a2e84d321ca5df
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
import React, {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useRef,
  useState,
} from "react";
import * as SecureStore from "expo-secure-store";
import {
  ConnectionStatus,
  ServerConfig,
  WsIncoming,
  WsOutgoing,
} from "../types";
import { wsClient } from "../services/websocket";
import { sendWol, isValidMac } from "../services/wol";
const SECURE_STORE_KEY = "pailot_server_config";
interface ConnectionContextValue {
  serverConfig: ServerConfig | null;
  status: ConnectionStatus;
  connect: (config?: ServerConfig) => void;
  disconnect: () => void;
  sendTextMessage: (text: string) => boolean;
  sendVoiceMessage: (audioBase64: string, transcript?: string, messageId?: string) => boolean;
  sendImageMessage: (imageBase64: string, caption: string, mimeType: string) => boolean;
  sendCommand: (command: string, args?: Record<string, unknown>) => boolean;
  saveServerConfig: (config: ServerConfig) => Promise<void>;
  onMessageReceived: React.MutableRefObject<
    ((data: WsIncoming) => void) | null
  >;
}
const ConnectionContext = createContext<ConnectionContextValue | null>(null);
export function ConnectionProvider({
  children,
}: {
  children: React.ReactNode;
}) {
  const [serverConfig, setServerConfig] = useState<ServerConfig | null>(null);
  const [status, setStatus] = useState<ConnectionStatus>("disconnected");
  const onMessageReceived = useRef<((data: WsIncoming) => void) | null>(null);
  useEffect(() => {
    loadConfig();
  }, []);
  useEffect(() => {
    wsClient.setCallbacks({
      onOpen: () => setStatus("connected"),
      onClose: () => setStatus("disconnected"),
      onError: () => setStatus("disconnected"),
      onMessage: (data) => {
        const msg = data as unknown as WsIncoming;
        // Handle server-side status changes (compaction indicator)
        if (msg.type === "status") {
          if (msg.status === "compacting") setStatus("compacting");
          else if (msg.status === "online") setStatus("connected");
          return;
        }
        onMessageReceived.current?.(msg);
      },
    });
  }, []);
  async function loadConfig() {
    try {
      const stored = await SecureStore.getItemAsync(SECURE_STORE_KEY);
      if (stored) {
        const config = JSON.parse(stored) as ServerConfig;
        setServerConfig(config);
        connectToServer(config);
      }
    } catch {
      // No stored config
    }
  }
  async function connectToServer(config: ServerConfig) {
    setStatus("connecting");
    // Fire-and-forget WoL — never block the WebSocket connection
    if (config.macAddress && isValidMac(config.macAddress)) {
      sendWol(config.macAddress, config.host).catch(() => {});
    }
    // Build URL list: local first (preferred), then remote
    const urls: string[] = [];
    if (config.localHost) {
      urls.push(`ws://${config.localHost}:${config.port}`);
    }
    urls.push(`ws://${config.host}:${config.port}`);
    wsClient.connect(urls);
  }
  const connect = useCallback(
    (config?: ServerConfig) => {
      const target = config ?? serverConfig;
      if (!target) return;
      connectToServer(target);
    },
    [serverConfig]
  );
  const disconnect = useCallback(() => {
    wsClient.disconnect();
    setStatus("disconnected");
  }, []);
  const saveServerConfig = useCallback(async (config: ServerConfig) => {
    await SecureStore.setItemAsync(SECURE_STORE_KEY, JSON.stringify(config));
    setServerConfig(config);
  }, []);
  const sendTextMessage = useCallback((text: string): boolean => {
    return wsClient.send({ type: "text", content: text });
  }, []);
  const sendVoiceMessage = useCallback(
    (audioBase64: string, transcript: string = "", messageId?: string): boolean => {
      return wsClient.send({
        type: "voice",
        content: transcript,
        audioBase64,
        messageId,
      });
    },
    []
  );
  const sendImageMessage = useCallback(
    (imageBase64: string, caption: string = "", mimeType: string = "image/jpeg"): boolean => {
      return wsClient.send({ type: "image", imageBase64, caption, mimeType });
    },
    []
  );
  const sendCommand = useCallback(
    (command: string, args?: Record<string, unknown>): boolean => {
      const msg: WsOutgoing = { type: "command", command, args };
      return wsClient.send(msg as any);
    },
    []
  );
  return (
    <ConnectionContext.Provider
      value={{
        serverConfig,
        status,
        connect,
        disconnect,
        sendTextMessage,
        sendVoiceMessage,
        sendImageMessage,
        sendCommand,
        saveServerConfig,
        onMessageReceived,
      }}
    >
      {children}
    </ConnectionContext.Provider>
  );
}
export function useConnection() {
  const ctx = useContext(ConnectionContext);
  if (!ctx) throw new Error("useConnection must be used within ConnectionProvider");
  return ctx;
}