summaryrefslogtreecommitdiffhomepage
path: root/app/packages/web/src/app.tsx
blob: 015d44c440dc990757116e3767d79ab4c494fd1b (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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import { createSignal, onCleanup, onMount, Show, For, createMemo } from "solid-js"
import { useParams } from "@solidjs/router"

type MessagePart = {
  type: string
  text?: string
  [key: string]: any
}

type MessageContent = {
  role?: string
  parts?: MessagePart[]
  metadata?: {
    time?: {
      created?: number
    }
  }
  [key: string]: any
}

type Message = {
  key: string
  content: string
}

type SessionInfo = {
  tokens?: {
    input?: number
    output?: number
    reasoning?: number
  }
}

export default function App() {
  const params = useParams<{ id: string }>()
  const [messages, setMessages] = createSignal<Message[]>([])
  const [connectionStatus, setConnectionStatus] = createSignal("Disconnected")
  const [sessionInfo, setSessionInfo] = createSignal<SessionInfo | null>(null)

  onMount(() => {
    // Get the API URL from environment
    const apiUrl = import.meta.env.VITE_API_URL
    const shareId = params.id

    console.log("Mounting Share component with ID:", shareId)
    console.log("API URL:", apiUrl)

    if (!shareId) {
      console.error("Share ID not found in environment variables")
      setConnectionStatus("Error: Share ID not found")
      return
    }

    if (!apiUrl) {
      console.error("API URL not found in environment variables")
      setConnectionStatus("Error: API URL not found")
      return
    }
    
    let reconnectTimer: number | undefined
    let socket: WebSocket | null = null

    // Function to create and set up WebSocket with auto-reconnect
    const setupWebSocket = () => {
      // Close any existing connection
      if (socket) {
        socket.close()
      }

      setConnectionStatus("Connecting...")

      // Always use secure WebSocket protocol (wss)
      const wsBaseUrl = apiUrl.replace(/^https?:\/\//, "wss://")
      const wsUrl = `${wsBaseUrl}/share_poll?shareID=${shareId}`
      console.log("Connecting to WebSocket URL:", wsUrl)

      // Create WebSocket connection
      socket = new WebSocket(wsUrl)

      // Handle connection opening
      socket.onopen = () => {
        setConnectionStatus("Connected")
        console.log("WebSocket connection established")
      }

      // Handle incoming messages
      socket.onmessage = (event) => {
        console.log("WebSocket message received")
        try {
          const data = JSON.parse(event.data) as Message
          
          // Check if this is a session info message
          if (data.key.startsWith("session/info/")) {
            try {
              const infoContent = JSON.parse(data.content) as SessionInfo;
              setSessionInfo(infoContent);
              console.log("Session info updated:", infoContent);
            } catch (e) {
              console.error("Error parsing session info:", e);
            }
          } else {
            // For all other messages
            setMessages((prev) => {
              // Check if message with this key already exists
              const existingIndex = prev.findIndex(msg => msg.key === data.key)
              
              if (existingIndex >= 0) {
                // Update existing message
                const updated = [...prev]
                updated[existingIndex] = data
                return updated
              } else {
                // Add new message
                return [...prev, data]
              }
            })
          }
        } catch (error) {
          console.error("Error parsing WebSocket message:", error)
        }
      }

      // Handle errors
      socket.onerror = (error) => {
        console.error("WebSocket error:", error)
        setConnectionStatus("Error: Connection failed")
      }

      // Handle connection close and reconnection
      socket.onclose = (event) => {
        console.log(`WebSocket closed: ${event.code} ${event.reason}`)
        setConnectionStatus("Disconnected, reconnecting...")

        // Try to reconnect after 2 seconds
        clearTimeout(reconnectTimer)
        reconnectTimer = window.setTimeout(
          setupWebSocket,
          2000,
        ) as unknown as number
      }
    }

    // Initial connection
    setupWebSocket()

    // Clean up on component unmount
    onCleanup(() => {
      console.log("Cleaning up WebSocket connection")
      if (socket) {
        socket.close()
      }
      clearTimeout(reconnectTimer)
    })
  })

  return (
    <main>
      <h1>Share: {params.id}</h1>

      <div style={{ margin: "2rem 0" }}>
        <h2>WebSocket Connection</h2>
        <p>
          Status: <strong>{connectionStatus()}</strong>
        </p>

        <h3>Live Updates</h3>
        
        <Show when={sessionInfo()}>
          <div 
            style={{
              backgroundColor: "#f8f9fa",
              padding: "1rem",
              borderRadius: "0.5rem",
              marginBottom: "1rem",
              border: "1px solid #dee2e6"
            }}
          >
            <h4 style={{ margin: "0 0 0.75rem 0" }}>Session Information</h4>
            <div style={{ display: "flex", gap: "1.5rem" }}>
              <div>
                <strong>Input Tokens:</strong> {sessionInfo()?.tokens?.input || 0}
              </div>
              <div>
                <strong>Output Tokens:</strong> {sessionInfo()?.tokens?.output || 0}
              </div>
              <div>
                <strong>Reasoning Tokens:</strong> {sessionInfo()?.tokens?.reasoning || 0}
              </div>
            </div>
          </div>
        </Show>
        
        <div
          style={{
            border: "1px solid #ccc",
            padding: "1rem",
            borderRadius: "0.5rem",
            maxHeight: "500px",
            overflowY: "auto",
          }}
        >
          <Show
            when={messages().length > 0}
            fallback={<p>Waiting for messages...</p>}
          >
            <ul style={{ listStyleType: "none", padding: 0 }}>
              <For each={messages()}>
                {(msg) => (
                  <li
                    style={{
                      padding: "0.75rem",
                      margin: "0.75rem 0",
                      backgroundColor: "#f5f5f5",
                      borderRadius: "0.5rem",
                      boxShadow: "0 1px 3px rgba(0,0,0,0.1)",
                    }}
                  >
                    <div>
                      <strong>Key:</strong> {msg.key}
                    </div>
                    
                    {(() => {
                      try {
                        const parsed = JSON.parse(msg.content) as MessageContent;
                        const createdTime = parsed.metadata?.time?.created 
                          ? new Date(parsed.metadata.time.created).toLocaleString() 
                          : 'Unknown time';
                        
                        return (
                          <>
                            <div style={{ marginTop: "0.5rem" }}>
                              <strong>Full Content:</strong>
                              <pre
                                style={{
                                  backgroundColor: "#f0f0f0",
                                  padding: "0.5rem",
                                  borderRadius: "0.25rem",
                                  overflow: "auto",
                                  maxHeight: "150px",
                                  whiteSpace: "pre-wrap",
                                  wordBreak: "break-word",
                                  fontSize: "0.85rem",
                                }}
                              >
                                {JSON.stringify(parsed, null, 2)}
                              </pre>
                            </div>
                            
                            {parsed.parts && parsed.parts.length > 0 && (
                              <div style={{ marginTop: "0.75rem" }}>
                                <div style={{ 
                                  display: "flex", 
                                  justifyContent: "space-between",
                                  alignItems: "center",
                                  padding: "0.25rem 0.5rem",
                                  backgroundColor: "#e9ecef",
                                  borderRadius: "0.25rem",
                                  marginBottom: "0.5rem"
                                }}>
                                  <strong>Role: {parsed.role || 'Unknown'}</strong>
                                  <span style={{ fontSize: "0.8rem", color: "#6c757d" }}>
                                    {createdTime}
                                  </span>
                                </div>
                                
                                <div style={{ 
                                  backgroundColor: "#fff", 
                                  padding: "0.75rem",
                                  borderRadius: "0.25rem",
                                  border: "1px solid #dee2e6"
                                }}>
                                  <For each={parsed.parts}>
                                    {(part, index) => (
                                      <div style={{ marginBottom: index() < parsed.parts!.length - 1 ? "0.75rem" : "0" }}>
                                        {part.type === "text" ? (
                                          <pre style={{ 
                                            whiteSpace: "pre-wrap", 
                                            wordBreak: "break-word",
                                            fontFamily: "inherit",
                                            margin: 0,
                                            padding: 0,
                                            backgroundColor: "transparent",
                                            border: "none",
                                            fontSize: "inherit",
                                            overflow: "visible"
                                          }}>
                                            {part.text}
                                          </pre>
                                        ) : (
                                          <div>
                                            <div style={{ 
                                              fontSize: "0.85rem", 
                                              fontWeight: "bold",
                                              marginBottom: "0.25rem",
                                              color: "#495057"
                                            }}>
                                              Part type: {part.type}
                                            </div>
                                            <pre
                                              style={{
                                                backgroundColor: "#f8f9fa",
                                                padding: "0.5rem",
                                                borderRadius: "0.25rem",
                                                overflow: "auto",
                                                maxHeight: "200px",
                                                whiteSpace: "pre-wrap",
                                                wordBreak: "break-word",
                                                fontSize: "0.85rem",
                                                margin: 0
                                              }}
                                            >
                                              {JSON.stringify(part, null, 2)}
                                            </pre>
                                          </div>
                                        )}
                                      </div>
                                    )}
                                  </For>
                                </div>
                              </div>
                            )}
                          </>
                        );
                      } catch (e) {
                        return (
                          <div>
                            <strong>Content:</strong>
                            <pre
                              style={{
                                backgroundColor: "#f0f0f0",
                                padding: "0.5rem",
                                borderRadius: "0.25rem",
                                overflow: "auto",
                                maxHeight: "200px",
                                whiteSpace: "pre-wrap",
                                wordBreak: "break-word",
                              }}
                            >
                              {msg.content}
                            </pre>
                          </div>
                        );
                      }
                    })()}
                  </li>
                )}
              </For>
            </ul>
          </Show>
        </div>
      </div>
    </main>
  )
}