-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat_controller.js
More file actions
339 lines (289 loc) · 10.7 KB
/
chat_controller.js
File metadata and controls
339 lines (289 loc) · 10.7 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
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
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["log", "input"]
static values = {
narrative: Array,
universeTime: String,
savedTextarea: String
}
connect() {
this.loadExistingMessages()
this.loadSavedInput()
this.saveDebounceTimeout = null
}
loadExistingMessages() {
if (this.narrativeValue && this.narrativeValue.length > 0) {
this.narrativeValue.forEach(message => {
const text = message.content[0].text
this.addMessage(message.role, text)
})
}
}
handleKeydown(event) {
if (event.key === "Enter") {
if (event.metaKey || event.ctrlKey) {
event.preventDefault()
this.send()
}
// Plain Enter allows multiline - textarea will expand naturally
} else if (event.key === "Escape") {
event.preventDefault()
this.inputTarget.blur()
}
}
handleInput(event) {
// Auto-expand textarea to fit content
const textarea = event.target
textarea.style.height = "auto"
textarea.style.height = textarea.scrollHeight + "px"
// Save input to localStorage immediately
this.saveInputToStorage(textarea.value)
// Debounced save to server (unless this is a programmatic event from loadSavedInput)
if (!event.skipServerSave) {
this.debouncedSaveToServer(textarea.value)
}
}
saveInputToStorage(value) {
const storageKey = `yours-input-${this.universeTimeValue || 'current'}`
localStorage.setItem(storageKey, value)
}
debouncedSaveToServer(value) {
// Clear existing timeout
if (this.saveDebounceTimeout) {
clearTimeout(this.saveDebounceTimeout)
}
// Set new timeout to save after 1.5 seconds of inactivity
this.saveDebounceTimeout = setTimeout(() => {
this.saveToServer(value)
}, 1500)
}
async saveToServer(value) {
try {
const response = await fetch("/textarea", {
method: "PUT",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": document.querySelector('meta[name="csrf-token"]').content
},
body: JSON.stringify({
textarea: value,
universe_time: this.universeTimeValue
})
})
if (response.status === 409) {
// Continuity divergence - this space moved forward elsewhere
const data = await response.json()
console.warn("Textarea save blocked: continuity divergence", data)
// Could show a subtle notice here if desired
} else if (!response.ok) {
console.error("Failed to save textarea:", response.status)
}
} catch (error) {
console.error("Error saving textarea:", error)
// Fail silently - localStorage still has it
}
}
loadSavedInput() {
// Prefer server-saved value over localStorage
const serverSaved = this.savedTextareaValue
const storageKey = `yours-input-${this.universeTimeValue || 'current'}`
const localSaved = localStorage.getItem(storageKey)
// Use whichever is longer (assumes the longer one is more recent)
// In practice, server value is canonical for cross-device sync
const savedInput = (serverSaved && serverSaved.length >= (localSaved || "").length)
? serverSaved
: localSaved
if (savedInput) {
this.inputTarget.value = savedInput
// Trigger input event to auto-expand (but don't re-trigger server save)
const event = new Event('input')
event.skipServerSave = true
this.inputTarget.dispatchEvent(event)
}
}
clearSavedInput() {
const storageKey = `yours-input-${this.universeTimeValue || 'current'}`
localStorage.removeItem(storageKey)
// Also clear on server
this.saveToServer("")
}
send() {
const text = this.inputTarget.value.trim()
if (!text) return
// Clear any visible flash messages
const flashMessages = document.querySelectorAll('[data-turbo-temporary]')
flashMessages.forEach(flash => flash.remove())
// Add user message to UI
this.addMessage("user", text)
// Clear input, reset height, and disable
this.inputTarget.value = ""
this.inputTarget.style.height = "auto"
this.inputTarget.disabled = true
this.clearSavedInput()
// Create message object in Lightward AI format
const message = {
role: "user",
content: [{ type: "text", text }]
}
// Stream response from backend
this.streamResponse(message)
}
async streamResponse(message) {
// Add pulsing assistant message placeholder with pink border
const assistantElement = this.addPulsingMessage("assistant")
let accumulatedText = ""
try {
const response = await fetch("/stream", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": document.querySelector('meta[name="csrf-token"]').content
},
body: JSON.stringify({
message,
universe_time: this.universeTimeValue
})
})
// Handle continuity divergence (409 Conflict)
if (response.status === 409) {
const data = await response.json()
this.handleContinuityDivergence(data)
this.inputTarget.disabled = false
this.inputTarget.focus()
assistantElement.remove()
return
}
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
// Read SSE stream
const reader = response.body.getReader()
const decoder = new TextDecoder()
let buffer = ""
while (true) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
// Process complete SSE events (separated by blank lines)
const events = buffer.split("\n\n")
buffer = events.pop() || "" // Keep incomplete event in buffer
for (const eventBlock of events) {
if (!eventBlock.trim()) continue
// Parse each event block for event: and data: fields
let eventType = null
let eventData = null
const eventLines = eventBlock.split("\n")
for (const line of eventLines) {
if (line.startsWith("event: ")) {
eventType = line.substring(7)
} else if (line.startsWith("data: ")) {
eventData = line.substring(6)
}
}
if (eventType) {
const data = eventData ? JSON.parse(eventData) : null
this.handleSSEEvent(eventType, data, assistantElement)
}
}
}
} catch (error) {
console.error("Stream error:", error)
assistantElement.textContent = `⚠️ Error: ${error.message}`
assistantElement.classList.remove("pulsing", "loading")
assistantElement.style.borderLeftColor = getComputedStyle(document.documentElement).getPropertyValue('--message-border').trim()
} finally {
// Re-enable input when done
this.inputTarget.disabled = false
this.inputTarget.focus()
}
}
handleSSEEvent(event, data, element) {
const messageBorder = getComputedStyle(document.documentElement).getPropertyValue('--message-border').trim()
switch (event) {
case "message_start":
element.classList.remove("pulsing")
element.style.animation = ""
break
case "content_block_delta":
if (data.delta?.type === "text_delta") {
element.classList.remove("pulsing", "loading")
element.style.animation = ""
element.textContent += data.delta.text
}
break
case "message_stop":
element.classList.remove("pulsing", "loading")
element.style.animation = ""
element.style.borderLeftColor = messageBorder
break
case "universe_time":
// Server sends updated universe_time after saving narrative
this.universeTimeValue = data.universe_time
break
case "end":
element.classList.remove("pulsing", "loading")
element.style.animation = ""
element.style.borderLeftColor = messageBorder
break
case "error":
element.textContent = `⚠️ ${data.error.message}`
element.classList.remove("pulsing", "loading")
element.style.animation = ""
element.style.borderLeftColor = messageBorder
break
}
}
addMessage(role, text) {
const messageElement = document.createElement("div")
messageElement.classList.add("chat-message", role)
messageElement.textContent = text
const userBg = getComputedStyle(document.documentElement).getPropertyValue('--user-message-bg').trim()
const assistantBg = getComputedStyle(document.documentElement).getPropertyValue('--assistant-message-bg').trim()
const messageBorder = getComputedStyle(document.documentElement).getPropertyValue('--message-border').trim()
const accent = getComputedStyle(document.documentElement).getPropertyValue('--accent').trim()
messageElement.style.cssText = `
padding: 1rem;
border-radius: 8px;
background: ${role === "user" ? userBg : assistantBg};
border-left: 3px solid ${role === "user" ? accent : messageBorder};
white-space: pre-wrap;
font-family: 'Lightward Favorit Mono', 'Courier New', monospace;
`
this.logTarget.appendChild(messageElement)
messageElement.scrollIntoView({ behavior: "smooth", block: "end" })
return messageElement
}
addPulsingMessage(role) {
const messageElement = this.addMessage(role, "")
messageElement.classList.add("pulsing")
const accentActive = getComputedStyle(document.documentElement).getPropertyValue('--accent-active').trim()
messageElement.style.cssText += `
min-height: 3rem;
animation: pulse 1.5s ease-in-out infinite;
border-left-color: ${accentActive};
`
return messageElement
}
handleContinuityDivergence(data) {
// Create a gentle notice that this space moved forward elsewhere
const noticeElement = document.createElement("div")
const accent = getComputedStyle(document.documentElement).getPropertyValue('--accent').trim()
const accentBg = getComputedStyle(document.documentElement).getPropertyValue('--user-message-bg').trim()
noticeElement.style.cssText = `
padding: 1.5rem;
border-radius: 8px;
background: ${accentBg};
border-left: 3px solid ${accent};
margin: 1rem 0;
font-family: 'Lightward Favorit Mono', 'Courier New', monospace;
`
noticeElement.innerHTML = `
<div style="margin-bottom: 1rem;">${data.message}</div>
<button onclick="window.location.reload()" style="cursor: pointer;">
Refresh to continue
</button>
`
this.logTarget.appendChild(noticeElement)
noticeElement.scrollIntoView({ behavior: "smooth", block: "end" })
}
}