@jungjaehoon/mama-os 0.32.3 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/README.md +15 -17
  2. package/dist/agent/os-agent-capabilities.md +2 -2
  3. package/dist/api/graph-api.d.ts +4 -4
  4. package/dist/api/graph-api.d.ts.map +1 -1
  5. package/dist/api/graph-api.js +47 -78
  6. package/dist/api/graph-api.js.map +1 -1
  7. package/dist/api/index.d.ts +10 -0
  8. package/dist/api/index.d.ts.map +1 -1
  9. package/dist/api/index.js +9 -2
  10. package/dist/api/index.js.map +1 -1
  11. package/dist/api/operator-handler.d.ts +1 -1
  12. package/dist/api/operator-handler.js +1 -1
  13. package/dist/api/runtime-status-handler.d.ts +41 -0
  14. package/dist/api/runtime-status-handler.d.ts.map +1 -0
  15. package/dist/api/runtime-status-handler.js +55 -0
  16. package/dist/api/runtime-status-handler.js.map +1 -0
  17. package/dist/cli/commands/start.d.ts.map +1 -1
  18. package/dist/cli/commands/start.js +58 -23
  19. package/dist/cli/commands/start.js.map +1 -1
  20. package/dist/cli/runtime/api-routes-init.d.ts +2 -0
  21. package/dist/cli/runtime/api-routes-init.d.ts.map +1 -1
  22. package/dist/cli/runtime/api-routes-init.js +62 -1
  23. package/dist/cli/runtime/api-routes-init.js.map +1 -1
  24. package/dist/cli/runtime/api-server-init.d.ts +12 -1
  25. package/dist/cli/runtime/api-server-init.d.ts.map +1 -1
  26. package/dist/cli/runtime/api-server-init.js +54 -0
  27. package/dist/cli/runtime/api-server-init.js.map +1 -1
  28. package/dist/cli/runtime/utilities.d.ts +1 -1
  29. package/dist/cli/runtime/utilities.d.ts.map +1 -1
  30. package/dist/cli/runtime/utilities.js +3 -1
  31. package/dist/cli/runtime/utilities.js.map +1 -1
  32. package/dist/gateways/message-router.d.ts +4 -0
  33. package/dist/gateways/message-router.d.ts.map +1 -1
  34. package/dist/gateways/message-router.js +62 -13
  35. package/dist/gateways/message-router.js.map +1 -1
  36. package/dist/gateways/owner-report-inbox.d.ts +40 -0
  37. package/dist/gateways/owner-report-inbox.d.ts.map +1 -0
  38. package/dist/gateways/owner-report-inbox.js +128 -0
  39. package/dist/gateways/owner-report-inbox.js.map +1 -0
  40. package/dist/gateways/report-projection-v1.d.ts +41 -0
  41. package/dist/gateways/report-projection-v1.d.ts.map +1 -0
  42. package/dist/gateways/report-projection-v1.js +160 -0
  43. package/dist/gateways/report-projection-v1.js.map +1 -0
  44. package/dist/gateways/session-store.d.ts +22 -0
  45. package/dist/gateways/session-store.d.ts.map +1 -1
  46. package/dist/gateways/session-store.js +76 -3
  47. package/dist/gateways/session-store.js.map +1 -1
  48. package/dist/gateways/telegram-message-ledger.d.ts +10 -0
  49. package/dist/gateways/telegram-message-ledger.d.ts.map +1 -1
  50. package/dist/gateways/telegram-message-ledger.js +23 -2
  51. package/dist/gateways/telegram-message-ledger.js.map +1 -1
  52. package/dist/gateways/telegram-report-context-store.d.ts +193 -0
  53. package/dist/gateways/telegram-report-context-store.d.ts.map +1 -0
  54. package/dist/gateways/telegram-report-context-store.js +612 -0
  55. package/dist/gateways/telegram-report-context-store.js.map +1 -0
  56. package/dist/gateways/telegram.d.ts +9 -0
  57. package/dist/gateways/telegram.d.ts.map +1 -1
  58. package/dist/gateways/telegram.js +100 -0
  59. package/dist/gateways/telegram.js.map +1 -1
  60. package/dist/gateways/types.d.ts +12 -0
  61. package/dist/gateways/types.d.ts.map +1 -1
  62. package/dist/multi-agent/dashboard-agent-persona.js +2 -2
  63. package/dist/operator/board-slot-instructions.d.ts +1 -1
  64. package/dist/operator/board-slot-instructions.js +1 -1
  65. package/dist/operator/operator-trigger-loop.d.ts +17 -1
  66. package/dist/operator/operator-trigger-loop.d.ts.map +1 -1
  67. package/dist/operator/operator-trigger-loop.js +87 -23
  68. package/dist/operator/operator-trigger-loop.js.map +1 -1
  69. package/dist/operator/report-delivery-coordinator.d.ts +82 -0
  70. package/dist/operator/report-delivery-coordinator.d.ts.map +1 -0
  71. package/dist/operator/report-delivery-coordinator.js +123 -0
  72. package/dist/operator/report-delivery-coordinator.js.map +1 -0
  73. package/dist/operator/situation-report.d.ts +7 -0
  74. package/dist/operator/situation-report.d.ts.map +1 -1
  75. package/dist/operator/situation-report.js +12 -0
  76. package/dist/operator/situation-report.js.map +1 -1
  77. package/package.json +1 -2
  78. package/public/viewer/js/modules/system.js +183 -0
  79. package/public/viewer/js/utils/ui-commands.js +4 -9
  80. package/public/viewer/log-viewer.html +2 -192
  81. package/public/viewer/operator/operator.css +1 -0
  82. package/public/viewer/operator/operator.js +14830 -0
  83. package/public/viewer/src/modules/system.ts +242 -0
  84. package/public/viewer/src/utils/ui-commands.ts +4 -8
  85. package/public/viewer/sw.js +44 -10
  86. package/public/viewer/viewer.css +338 -331
  87. package/public/viewer/viewer.html +388 -1472
  88. package/public/ui/assets/index-BDXDGEV6.js +0 -62
  89. package/public/ui/assets/index-po2tN0xq.css +0 -1
  90. package/public/ui/index.html +0 -14
  91. package/public/ui/theme-init.js +0 -20
  92. package/public/viewer/js/modules/agents.js +0 -1153
  93. package/public/viewer/js/modules/chat.js +0 -1993
  94. package/public/viewer/js/modules/connector-feed.js +0 -352
  95. package/public/viewer/js/modules/dashboard.js +0 -456
  96. package/public/viewer/js/modules/entity-audit.js +0 -106
  97. package/public/viewer/js/modules/entity-review.js +0 -66
  98. package/public/viewer/js/modules/settings.js +0 -1257
  99. package/public/viewer/src/modules/agents.ts +0 -1302
  100. package/public/viewer/src/modules/chat.ts +0 -2426
  101. package/public/viewer/src/modules/connector-feed.ts +0 -391
  102. package/public/viewer/src/modules/dashboard.ts +0 -498
  103. package/public/viewer/src/modules/entity-audit.ts +0 -154
  104. package/public/viewer/src/modules/entity-review.ts +0 -175
  105. package/public/viewer/src/modules/settings.ts +0 -1547
@@ -1,1993 +0,0 @@
1
- /**
2
- * Chat Module - Mobile Chat with Voice Input
3
- * @module modules/chat
4
- * @version 1.0.0
5
- *
6
- * Handles Chat tab functionality including:
7
- * - WebSocket chat with Claude Code CLI
8
- * - Voice input (Web Speech API)
9
- * - Conversation history management
10
- * - Real-time streaming responses
11
- */
12
- /* eslint-env browser */
13
- import { escapeHtml, escapeAttr, showToast, scrollToBottom, autoResizeTextarea, getElementByIdOrNull, getErrorMessage, } from '../utils/dom.js';
14
- import { formatMessageTime, formatAssistantMessage } from '../utils/format.js';
15
- import { API } from '../utils/api.js';
16
- import { DebugLogger } from '../utils/debug-logger.js';
17
- const logger = new DebugLogger('Chat');
18
- /**
19
- * Chat Module Class
20
- */
21
- export class ChatModule {
22
- memoryModule = null;
23
- ws = null;
24
- sessionId = null;
25
- reconnectAttempts = 0;
26
- maxReconnectDelay = 30000;
27
- speechRecognition = null;
28
- isRecording = false;
29
- silenceTimeout = null;
30
- silenceDelay = 2500;
31
- accumulatedTranscript = '';
32
- speechSynthesis = window.speechSynthesis;
33
- isSpeaking = false;
34
- ttsEnabled = false;
35
- handsFreeMode = false;
36
- ttsVoice = null;
37
- ttsRate = 1.8;
38
- ttsPitch = 1.0;
39
- currentStreamEl = null;
40
- currentStreamText = '';
41
- streamBuffer = '';
42
- rafPending = false;
43
- history = [];
44
- historyPrefix = 'mama_chat_history_';
45
- get historyStorageKey() {
46
- return this.historyPrefix + 'viewer_mama_os_main';
47
- }
48
- maxHistoryMessages = 200;
49
- maxDomMessages = 100; // Limit DOM elements for performance
50
- historyExpiryMs = 24 * 60 * 60 * 1000;
51
- checkpointCooldown = false;
52
- COOLDOWN_MS = 60 * 1000;
53
- idleTimer = null;
54
- IDLE_TIMEOUT = 5 * 60 * 1000;
55
- _onDragMouseMove = null;
56
- _onDragMouseUp = null;
57
- _onDragTouchMove = null;
58
- _onDragTouchEnd = null;
59
- _onResizeMouseMove = null;
60
- _onResizeMouseUp = null;
61
- _onResizeTouchMove = null;
62
- _onResizeTouchEnd = null;
63
- _onEscapeKey = null;
64
- /** Active tool-status group element (single line, in-place updates) */
65
- toolStatusGroup = null;
66
- /** Completed tool names in current group */
67
- toolStatusCompleted = [];
68
- /** Currently running tool name */
69
- toolStatusCurrentName = null;
70
- /** Current tool detail string (for rendering) */
71
- toolStatusCurrentDetail = '';
72
- constructor(memoryModule = null) {
73
- // External dependencies
74
- this.memoryModule = memoryModule;
75
- // Initialize
76
- this.initChatInput();
77
- this.initLongPressCopy();
78
- this.initSpeechRecognition();
79
- this.initSpeechSynthesis();
80
- }
81
- // =============================================
82
- // Idle Auto-Checkpoint
83
- // =============================================
84
- resetIdleTimer() {
85
- if (this.idleTimer) {
86
- clearTimeout(this.idleTimer);
87
- }
88
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
89
- this.idleTimer = setTimeout(() => {
90
- this.autoCheckpoint();
91
- }, this.IDLE_TIMEOUT);
92
- }
93
- }
94
- async autoCheckpoint() {
95
- // DISABLED: Auto-checkpoint was saving raw conversation history to MAMA memory.
96
- // Checkpoints should only be saved manually via /checkpoint command with proper summaries.
97
- // The viewer chat uses localStorage for session persistence instead.
98
- logger.info('Auto-checkpoint disabled (use /checkpoint for manual saves)');
99
- return;
100
- }
101
- // =============================================
102
- // Session Management
103
- // =============================================
104
- /**
105
- * Initialize chat session
106
- */
107
- async initSession() {
108
- // Check for resumable session first
109
- await this.checkForResumableSession();
110
- // Always try to get the last active viewer session from server
111
- // Use it regardless of isAlive — server history is the source of truth
112
- const lastActiveSession = await API.getLastActiveSession().catch(() => null);
113
- if (lastActiveSession && lastActiveSession.id) {
114
- logger.info('Using server session:', lastActiveSession.id);
115
- localStorage.setItem('mama_chat_session_id', lastActiveSession.id);
116
- this.initWebSocket(lastActiveSession.id);
117
- return;
118
- }
119
- const savedSessionId = localStorage.getItem('mama_chat_session_id');
120
- if (savedSessionId) {
121
- logger.info('Trying saved session:', savedSessionId);
122
- this.addSystemMessage('Connecting to session...');
123
- this.initWebSocket(savedSessionId);
124
- }
125
- else {
126
- try {
127
- this.addSystemMessage('Creating new session...');
128
- const data = await API.createSession('.');
129
- const sessionId = data.sessionId;
130
- logger.info('Created new session:', sessionId);
131
- localStorage.setItem('mama_chat_session_id', sessionId);
132
- this.initWebSocket(sessionId);
133
- }
134
- catch (error) {
135
- logger.error('Failed to create session:', error);
136
- const message = getErrorMessage(error);
137
- this.addSystemMessage(`Failed to create session: ${message}`, 'error');
138
- }
139
- }
140
- }
141
- /**
142
- * Connect to session (public method)
143
- */
144
- connectToSession(sessionId) {
145
- this.initWebSocket(sessionId);
146
- }
147
- /**
148
- * Disconnect from session (public method)
149
- */
150
- disconnect() {
151
- if (this.ws) {
152
- this.sessionId = null; // Prevent auto-reconnect
153
- this.ws.close();
154
- this.ws = null;
155
- }
156
- this.updateStatus('disconnected');
157
- this.enableInput(false);
158
- }
159
- // =============================================
160
- // WebSocket Management
161
- // =============================================
162
- /**
163
- * Initialize WebSocket connection
164
- */
165
- initWebSocket(sessionId) {
166
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
167
- logger.info('Already connected');
168
- return;
169
- }
170
- this.sessionId = sessionId;
171
- this.restoreHistory(sessionId);
172
- const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
173
- const wsUrl = `${protocol}//${window.location.host}/ws?sessionId=${sessionId}`;
174
- logger.info('Connecting to:', wsUrl);
175
- this.ws = new WebSocket(wsUrl);
176
- this.ws.onopen = () => {
177
- logger.info('Connected');
178
- this.reconnectAttempts = 0;
179
- this.updateStatus('connected');
180
- this.enableInput(true);
181
- this.ws.send(JSON.stringify({
182
- type: 'attach',
183
- sessionId: sessionId,
184
- osAgentMode: true, // Enable OS Agent capabilities (Viewer-only)
185
- language: navigator.language || 'en', // Browser language for greeting
186
- }));
187
- };
188
- this.ws.onmessage = (event) => {
189
- try {
190
- const data = JSON.parse(event.data);
191
- this.handleMessage(data);
192
- }
193
- catch (e) {
194
- logger.error('Parse error:', e);
195
- }
196
- };
197
- this.ws.onclose = (event) => {
198
- logger.info('Disconnected:', event.code, event.reason);
199
- this.updateStatus('disconnected');
200
- this.enableInput(false);
201
- if (this.sessionId) {
202
- this.scheduleReconnect();
203
- }
204
- };
205
- this.ws.onerror = (error) => {
206
- logger.error('WebSocket error:', error);
207
- this.updateStatus('disconnected');
208
- };
209
- }
210
- /**
211
- * Handle incoming WebSocket message
212
- */
213
- handleMessage(data) {
214
- switch (data.type) {
215
- case 'attached':
216
- logger.info('Attached to session:', data.sessionId);
217
- this.addSystemMessage('Connected to session');
218
- break;
219
- case 'history':
220
- // Display conversation history from server
221
- if (data.messages && data.messages.length > 0) {
222
- logger.info('Received history:', data.messages.length, 'messages');
223
- this.displayHistory(data.messages);
224
- }
225
- break;
226
- case 'output':
227
- case 'stream':
228
- if (data.content) {
229
- this.hideTypingIndicator();
230
- this.enableSend(true);
231
- this.appendStreamChunk(data.content);
232
- }
233
- break;
234
- case 'stream_end':
235
- this.hideTypingIndicator();
236
- this.finalizeStreamMessage();
237
- this.resetToolStatusGroup();
238
- break;
239
- case 'error':
240
- if (data.error === 'session_not_found') {
241
- logger.info('Session not found, creating new one...');
242
- localStorage.removeItem('mama_chat_session_id');
243
- this.addSystemMessage('Session expired. Creating new session...');
244
- if (this.ws) {
245
- this.ws.close();
246
- this.ws = null;
247
- }
248
- setTimeout(() => this.initSession(), 500);
249
- }
250
- else {
251
- this.addSystemMessage(`Error: ${data.message || data.error}`, 'error');
252
- this.enableSend(true);
253
- }
254
- break;
255
- case 'tool_use':
256
- this.addToolCard(data.tool || 'tool', data.toolId || '', data.input && typeof data.input === 'object' ? data.input : null);
257
- break;
258
- case 'tool_complete':
259
- if (typeof data.index === 'number') {
260
- this.completeToolCard(data.index);
261
- }
262
- break;
263
- case 'typing':
264
- this.showTypingIndicator(data.elapsed ?? 0);
265
- break;
266
- case 'pong':
267
- break;
268
- case 'connected':
269
- logger.info('WebSocket connected:', data.clientId);
270
- break;
271
- default:
272
- logger.warn('Unknown message type:', data.type);
273
- }
274
- }
275
- /**
276
- * Schedule reconnection with exponential backoff
277
- */
278
- scheduleReconnect() {
279
- const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), this.maxReconnectDelay);
280
- this.reconnectAttempts++;
281
- logger.info(`Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`);
282
- this.addSystemMessage(`Connection lost. Reconnecting in ${Math.round(delay / 1000)}s...`, 'warning');
283
- setTimeout(() => {
284
- if (this.sessionId) {
285
- this.initWebSocket(this.sessionId);
286
- }
287
- }, delay);
288
- }
289
- // =============================================
290
- // Message Handling
291
- // =============================================
292
- /**
293
- * Send chat message
294
- */
295
- send() {
296
- const input = getElementByIdOrNull('chat-input');
297
- if (!input) {
298
- return;
299
- }
300
- const message = input.value.trim();
301
- if (!message) {
302
- return;
303
- }
304
- // Handle slash commands
305
- if (message.startsWith('/')) {
306
- this.handleCommand(message);
307
- input.value = '';
308
- autoResizeTextarea(input);
309
- return;
310
- }
311
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
312
- this.addSystemMessage('Not connected. Please connect to a session first.', 'error');
313
- return;
314
- }
315
- this.addUserMessage(message);
316
- this.enableSend(false);
317
- // Include current viewer tab context (SmartStore ChatPanel pattern)
318
- const tabIndicator = document.getElementById('chat-tab-indicator');
319
- const viewerContext = {
320
- currentTab: tabIndicator?.textContent?.toLowerCase() || 'unknown',
321
- };
322
- this.ws.send(JSON.stringify({
323
- type: 'send',
324
- sessionId: this.sessionId,
325
- content: message,
326
- viewerContext,
327
- }));
328
- // Search for related MAMA decisions
329
- if (this.memoryModule) {
330
- this.memoryModule.showRelatedForMessage(message);
331
- }
332
- input.value = '';
333
- autoResizeTextarea(input);
334
- logger.info('Sent:', message);
335
- this.resetIdleTimer();
336
- }
337
- /**
338
- * Send quiz choice (A, B, C, D)
339
- */
340
- sendQuizChoice(choice) {
341
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
342
- this.addSystemMessage('Not connected.', 'error');
343
- return;
344
- }
345
- // Display choice as user message
346
- this.addUserMessage(choice);
347
- this.enableSend(false);
348
- // Send to server
349
- this.ws.send(JSON.stringify({
350
- type: 'send',
351
- sessionId: this.sessionId,
352
- content: choice,
353
- }));
354
- logger.info('Quiz choice sent:', choice);
355
- this.resetIdleTimer();
356
- }
357
- /**
358
- * Handle slash commands
359
- */
360
- handleCommand(message) {
361
- const parts = message.slice(1).split(' ');
362
- const command = parts[0].toLowerCase();
363
- const args = parts.slice(1).join(' ');
364
- logger.info('Command:', command, 'Args:', args);
365
- switch (command) {
366
- case 'save':
367
- this.commandSave(args);
368
- break;
369
- case 'search':
370
- this.commandSearch(args);
371
- break;
372
- case 'checkpoint':
373
- this.commandCheckpoint();
374
- break;
375
- case 'resume':
376
- this.commandResume();
377
- break;
378
- case 'help':
379
- this.commandHelp();
380
- break;
381
- default:
382
- // Forward unrecognized commands to agent as regular messages
383
- this.sendRaw(message);
384
- }
385
- }
386
- /**
387
- * Send a message directly to the agent (bypass command parsing)
388
- * Rewrites /command to avoid Claude CLI slash command interception
389
- */
390
- sendRaw(message) {
391
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
392
- this.addSystemMessage('Not connected. Please connect to a session first.', 'error');
393
- return;
394
- }
395
- this.addUserMessage(message);
396
- this.enableSend(false);
397
- // Rewrite /command → natural language to avoid Claude CLI interception
398
- // Must be explicit enough to override built-in skills (BMAD, etc.)
399
- let agentMessage = message;
400
- if (message.startsWith('/')) {
401
- const parts = message.slice(1).split(' ');
402
- const cmd = parts[0];
403
- const args = parts.slice(1).join(' ');
404
- agentMessage = [
405
- `[INSTALLED PLUGIN COMMAND — DO NOT USE SKILL TOOL]`,
406
- `Look in your system prompt under "Installed Skills (PRIORITY)" for the "commands/${cmd}.md" section.`,
407
- `Execute ONLY the instructions from that installed plugin command file.`,
408
- `DO NOT invoke the Skill tool. DO NOT match to bmad or any other built-in skill.`,
409
- `This command comes from a user-installed Cowork/OpenClaw plugin, not a system skill.`,
410
- args ? `User arguments: <user_args>${args}</user_args>` : '',
411
- ]
412
- .filter(Boolean)
413
- .join(' ');
414
- }
415
- this.ws.send(JSON.stringify({
416
- type: 'send',
417
- sessionId: this.sessionId,
418
- content: agentMessage,
419
- }));
420
- if (this.memoryModule) {
421
- this.memoryModule.showRelatedForMessage(message);
422
- }
423
- logger.info('Forwarded to agent:', agentMessage);
424
- this.resetIdleTimer();
425
- }
426
- /**
427
- * /save <text> - Open Memory form with text
428
- */
429
- commandSave(text) {
430
- if (!this.memoryModule) {
431
- this.addSystemMessage('Memory module not available', 'error');
432
- return;
433
- }
434
- if (!text) {
435
- this.addSystemMessage('Usage: /save <decision text>', 'error');
436
- return;
437
- }
438
- // Switch to Memory tab and open form with text
439
- window.switchTab?.('memory');
440
- this.memoryModule.showSaveFormWithText(text);
441
- this.addSystemMessage(`💾 Opening save form with: "${text.substring(0, 50)}..."`);
442
- }
443
- /**
444
- * /search <query> - Search in Memory tab
445
- */
446
- commandSearch(query) {
447
- if (!this.memoryModule) {
448
- this.addSystemMessage('Memory module not available', 'error');
449
- return;
450
- }
451
- if (!query) {
452
- this.addSystemMessage('Usage: /search <query>', 'error');
453
- return;
454
- }
455
- // Switch to Memory tab and execute search
456
- window.switchTab?.('memory');
457
- this.memoryModule.searchWithQuery(query);
458
- this.addSystemMessage(`🔍 Searching for: "${query}"`);
459
- }
460
- /**
461
- * /checkpoint - Save current session as checkpoint
462
- */
463
- async commandCheckpoint() {
464
- try {
465
- const summary = this.generateCheckpointSummary();
466
- await this.saveCheckpoint(summary);
467
- this.addSystemMessage('✅ Checkpoint saved successfully');
468
- }
469
- catch (error) {
470
- logger.error('Checkpoint save failed:', error);
471
- const message = getErrorMessage(error);
472
- this.addSystemMessage(`Failed to save checkpoint: ${message}`, 'error');
473
- }
474
- }
475
- /**
476
- * /resume - Load last checkpoint
477
- */
478
- async commandResume() {
479
- try {
480
- const checkpoint = await this.loadCheckpoint();
481
- if (checkpoint) {
482
- this.addSystemMessage(`📖 Last checkpoint (${new Date(checkpoint.timestamp).toLocaleString()}):`);
483
- this.addSystemMessage(checkpoint.summary);
484
- }
485
- else {
486
- this.addSystemMessage('No checkpoint found', 'error');
487
- }
488
- }
489
- catch (error) {
490
- logger.error('Checkpoint load failed:', error);
491
- const message = getErrorMessage(error);
492
- this.addSystemMessage(`Failed to load checkpoint: ${message}`, 'error');
493
- }
494
- }
495
- /**
496
- * /help - Show available commands
497
- */
498
- commandHelp() {
499
- const helpText = `
500
- **Available Commands:**
501
-
502
- **/save <text>** - Save a decision to Memory
503
- **/search <query>** - Search decisions in Memory
504
- **/checkpoint** - Save current session
505
- **/resume** - Load last checkpoint
506
- **/help** - Show this help message
507
-
508
- **Keyboard Shortcuts:**
509
- - **Enter** - Send message
510
- - **Shift+Enter** - New line
511
- - **Long press message** - Copy to clipboard
512
- `.trim();
513
- this.addSystemMessage(helpText);
514
- }
515
- /**
516
- * Add user message to chat
517
- */
518
- addUserMessage(text) {
519
- const container = getElementByIdOrNull('chat-messages');
520
- if (!container) {
521
- return;
522
- }
523
- this.removePlaceholder();
524
- const timestamp = new Date();
525
- const msgEl = document.createElement('div');
526
- msgEl.className = 'chat-message user';
527
- msgEl.innerHTML = `
528
- <div class="message-content">${escapeHtml(text)}</div>
529
- <div class="message-time">${formatMessageTime(timestamp)}</div>
530
- `;
531
- container.appendChild(msgEl);
532
- scrollToBottom(container);
533
- this.saveToHistory('user', text, timestamp);
534
- }
535
- addUserMessageWithAttachment(text, attachment) {
536
- const container = getElementByIdOrNull('chat-messages');
537
- if (!container) {
538
- return;
539
- }
540
- this.removePlaceholder();
541
- const timestamp = new Date();
542
- const msgEl = document.createElement('div');
543
- msgEl.className = 'chat-message user';
544
- let attachHtml = '';
545
- if (attachment.isImage) {
546
- const safeUrl = escapeAttr(attachment.mediaUrl);
547
- const safeAlt = escapeAttr(attachment.originalName);
548
- attachHtml = `<img src="${safeUrl}" class="max-w-[200px] rounded-lg mt-1 cursor-pointer" alt="${safeAlt}" data-lightbox="${safeUrl}" />`;
549
- }
550
- else {
551
- const safeName = encodeURIComponent(attachment.filename);
552
- attachHtml = `<a href="/api/media/download/${safeName}" target="_blank" class="flex items-center gap-2 mt-1 px-3 py-2 bg-white/50 rounded-lg border border-gray-200 text-sm hover:bg-white/80 transition-colors"><span class="text-lg">\u{1F4CE}</span><span class="truncate max-w-[180px]">${escapeHtml(attachment.originalName)}</span></a>`;
553
- }
554
- msgEl.innerHTML = `
555
- <div class="message-content">${escapeHtml(text)}${attachHtml}</div>
556
- <div class="message-time">${formatMessageTime(timestamp)}</div>
557
- `;
558
- container.appendChild(msgEl);
559
- scrollToBottom(container);
560
- this.saveToHistory('user', text, timestamp, attachment);
561
- }
562
- /**
563
- * Add assistant message to chat
564
- */
565
- addAssistantMessage(text) {
566
- const container = getElementByIdOrNull('chat-messages');
567
- if (!container) {
568
- return;
569
- }
570
- this.removePlaceholder();
571
- this.enableSend(true);
572
- const timestamp = new Date();
573
- const msgEl = document.createElement('div');
574
- msgEl.className = 'chat-message assistant';
575
- msgEl.innerHTML = `
576
- <div class="message-content">${formatAssistantMessage(text)}</div>
577
- <div class="message-time">${formatMessageTime(timestamp)}</div>
578
- `;
579
- container.appendChild(msgEl);
580
- scrollToBottom(container);
581
- this.saveToHistory('assistant', text, timestamp);
582
- // Show unread badge if floating panel is closed
583
- this.showUnreadBadge();
584
- // Auto-play TTS if enabled
585
- if (this.ttsEnabled && text) {
586
- logger.info('Auto-play enabled, speaking assistant message');
587
- this.speak(text);
588
- }
589
- }
590
- /**
591
- * Add system message to chat
592
- */
593
- addSystemMessage(text, type = 'info') {
594
- const container = getElementByIdOrNull('chat-messages');
595
- if (!container) {
596
- return;
597
- }
598
- this.removePlaceholder();
599
- const msgEl = document.createElement('div');
600
- msgEl.className = `chat-message system ${type}`;
601
- msgEl.innerHTML = `
602
- <div class="message-content">${escapeHtml(text)}</div>
603
- `;
604
- container.appendChild(msgEl);
605
- scrollToBottom(container);
606
- }
607
- /**
608
- * Get tool icon by name
609
- */
610
- getToolIcon(toolName) {
611
- const iconMap = {
612
- Read: '📄',
613
- Write: '✏️',
614
- Bash: '💻',
615
- Edit: '🔧',
616
- Grep: '🔍',
617
- Glob: '📂',
618
- Task: '🤖',
619
- WebFetch: '🌐',
620
- WebSearch: '🔎',
621
- };
622
- return iconMap[toolName] || '🔧';
623
- }
624
- /**
625
- * Get short detail label for a tool invocation
626
- */
627
- getToolDetail(toolName, input) {
628
- if (toolName === 'Read' && input?.file_path) {
629
- return `(${escapeHtml(input.file_path.split('/').pop() ?? '')})`;
630
- }
631
- if (toolName === 'Bash' && input?.command) {
632
- const cmd = String(input.command);
633
- return `(${escapeHtml(cmd.substring(0, 40))}${cmd.length > 40 ? '…' : ''})`;
634
- }
635
- return '';
636
- }
637
- /**
638
- * Render the tool-status group HTML in-place
639
- */
640
- renderToolStatusGroup() {
641
- if (!this.toolStatusGroup) {
642
- return;
643
- }
644
- const parts = [];
645
- // Completed tools: ✓ icon name
646
- for (const name of this.toolStatusCompleted) {
647
- parts.push(`<span style="color:#4caf50">✓</span> ${this.getToolIcon(name)} ${escapeHtml(name)}`);
648
- }
649
- // Current running tool: ⏳ icon name(detail)
650
- if (this.toolStatusCurrentName) {
651
- parts.push(`<span class="tool-status-spinner">⏳</span> ${this.getToolIcon(this.toolStatusCurrentName)} <b>${escapeHtml(this.toolStatusCurrentName)}</b>${this.toolStatusCurrentDetail}`);
652
- }
653
- this.toolStatusGroup.innerHTML = parts.join(' &nbsp; ');
654
- }
655
- /**
656
- * Reset tool status group (call when assistant turn ends)
657
- */
658
- resetToolStatusGroup() {
659
- this.toolStatusGroup = null;
660
- this.toolStatusCompleted = [];
661
- this.toolStatusCurrentName = null;
662
- this.toolStatusCurrentDetail = '';
663
- }
664
- /**
665
- * Add tool usage — single in-place status line
666
- */
667
- addToolCard(toolName, _toolId, input) {
668
- const container = getElementByIdOrNull('chat-messages');
669
- if (!container) {
670
- return;
671
- }
672
- this.removePlaceholder();
673
- // Create group element on first tool call
674
- if (!this.toolStatusGroup) {
675
- const groupEl = document.createElement('div');
676
- groupEl.className = 'tool-status-group';
677
- groupEl.style.cssText =
678
- 'padding:4px 12px;margin:2px 0;font-size:0.85em;color:#aaa;line-height:1.8;white-space:normal;word-wrap:break-word;';
679
- container.appendChild(groupEl);
680
- this.toolStatusGroup = groupEl;
681
- this.toolStatusCompleted = [];
682
- }
683
- // Move previous current tool to completed
684
- if (this.toolStatusCurrentName) {
685
- this.toolStatusCompleted.push(this.toolStatusCurrentName);
686
- }
687
- // Set new current tool
688
- this.toolStatusCurrentName = toolName;
689
- this.toolStatusCurrentDetail = this.getToolDetail(toolName, input);
690
- this.renderToolStatusGroup();
691
- scrollToBottom(container);
692
- }
693
- /**
694
- * Complete tool card (mark current as finished)
695
- */
696
- completeToolCard(_index) {
697
- if (!this.toolStatusCurrentName) {
698
- return;
699
- }
700
- this.toolStatusCompleted.push(this.toolStatusCurrentName);
701
- this.toolStatusCurrentName = null;
702
- this.toolStatusCurrentDetail = '';
703
- this.renderToolStatusGroup();
704
- }
705
- /**
706
- * Remove placeholder
707
- */
708
- removePlaceholder() {
709
- const placeholder = document.querySelector('.chat-placeholder');
710
- if (placeholder) {
711
- placeholder.remove();
712
- }
713
- }
714
- // =============================================
715
- // Streaming Message Handling
716
- // =============================================
717
- /**
718
- * Append streaming chunk with RAF batching
719
- */
720
- appendStreamChunk(content) {
721
- const container = getElementByIdOrNull('chat-messages');
722
- if (!container) {
723
- return;
724
- }
725
- if (!this.currentStreamEl) {
726
- this.removePlaceholder();
727
- this.currentStreamEl = document.createElement('div');
728
- this.currentStreamEl.className = 'chat-message assistant streaming';
729
- this.currentStreamEl.innerHTML = `
730
- <div class="message-content"></div>
731
- <div class="message-time">${formatMessageTime(new Date())}</div>
732
- `;
733
- container.appendChild(this.currentStreamEl);
734
- this.currentStreamText = '';
735
- this.streamBuffer = '';
736
- }
737
- this.streamBuffer += content;
738
- if (!this.rafPending) {
739
- this.rafPending = true;
740
- requestAnimationFrame(() => {
741
- if (this.streamBuffer) {
742
- this.currentStreamText += this.streamBuffer;
743
- this.streamBuffer = '';
744
- const contentEl = this.currentStreamEl?.querySelector('.message-content');
745
- if (contentEl) {
746
- contentEl.innerHTML = formatAssistantMessage(this.currentStreamText);
747
- }
748
- container.scrollTo({
749
- top: container.scrollHeight,
750
- behavior: 'auto',
751
- });
752
- }
753
- this.rafPending = false;
754
- });
755
- }
756
- }
757
- /**
758
- * Finalize streaming message
759
- */
760
- finalizeStreamMessage() {
761
- if (this.streamBuffer && this.currentStreamEl) {
762
- this.currentStreamText += this.streamBuffer;
763
- const contentEl = this.currentStreamEl.querySelector('.message-content');
764
- if (contentEl) {
765
- contentEl.innerHTML = formatAssistantMessage(this.currentStreamText);
766
- }
767
- }
768
- if (this.currentStreamText) {
769
- this.saveToHistory('assistant', this.currentStreamText);
770
- // Auto-play TTS for streamed responses
771
- if (this.ttsEnabled) {
772
- this.speak(this.currentStreamText);
773
- }
774
- }
775
- // Show unread badge if floating panel is closed
776
- this.showUnreadBadge();
777
- if (this.currentStreamEl) {
778
- this.currentStreamEl.classList.remove('streaming');
779
- this.currentStreamEl = null;
780
- this.currentStreamText = '';
781
- this.streamBuffer = '';
782
- }
783
- this.rafPending = false;
784
- this.enableSend(true);
785
- }
786
- /**
787
- * Show typing indicator while agent is processing
788
- */
789
- showTypingIndicator(elapsed) {
790
- const container = getElementByIdOrNull('chat-messages');
791
- if (!container) {
792
- return;
793
- }
794
- let indicator = container.querySelector('.chat-typing-indicator');
795
- if (!indicator) {
796
- indicator = document.createElement('div');
797
- indicator.className = 'chat-typing-indicator';
798
- indicator.innerHTML = `
799
- <div class="typing-dots">
800
- <span></span><span></span><span></span>
801
- </div>
802
- <span class="typing-label">thinking...</span>`;
803
- container.appendChild(indicator);
804
- scrollToBottom(container);
805
- }
806
- if (elapsed) {
807
- const label = indicator.querySelector('.typing-label');
808
- if (label) {
809
- label.textContent = `thinking... (${elapsed}s)`;
810
- }
811
- }
812
- }
813
- /**
814
- * Hide typing indicator
815
- */
816
- hideTypingIndicator() {
817
- const container = getElementByIdOrNull('chat-messages');
818
- if (!container) {
819
- return;
820
- }
821
- const indicator = container.querySelector('.chat-typing-indicator');
822
- if (indicator) {
823
- indicator.remove();
824
- }
825
- }
826
- // =============================================
827
- // UI Control
828
- // =============================================
829
- /**
830
- * Update chat status
831
- */
832
- updateStatus(status) {
833
- const statusEl = getElementByIdOrNull('chat-status');
834
- if (!statusEl) {
835
- logger.warn('Status element not found');
836
- return;
837
- }
838
- // #chat-status IS the indicator element (not a wrapper with children)
839
- statusEl.className = 'status-indicator w-1.5 h-1.5 rounded-full flex-shrink-0 ' + status;
840
- switch (status) {
841
- case 'connected':
842
- statusEl.title = 'Connected';
843
- break;
844
- case 'disconnected':
845
- statusEl.title = 'Disconnected';
846
- break;
847
- case 'connecting':
848
- statusEl.title = 'Connecting...';
849
- break;
850
- default:
851
- statusEl.title = status;
852
- }
853
- }
854
- /**
855
- * Enable/disable chat input
856
- */
857
- enableInput(enabled) {
858
- const input = getElementByIdOrNull('chat-input');
859
- const sendBtn = getElementByIdOrNull('chat-send');
860
- if (!input || !sendBtn) {
861
- return;
862
- }
863
- input.disabled = !enabled;
864
- sendBtn.disabled = !enabled;
865
- if (enabled) {
866
- input.placeholder = 'Type your message...';
867
- }
868
- else {
869
- input.placeholder = 'Connect to a session to chat';
870
- }
871
- }
872
- /**
873
- * Enable/disable send button
874
- */
875
- enableSend(enabled) {
876
- const sendBtn = getElementByIdOrNull('chat-send');
877
- if (!sendBtn) {
878
- return;
879
- }
880
- sendBtn.disabled = !enabled;
881
- if (enabled) {
882
- sendBtn.textContent = 'Send';
883
- sendBtn.classList.remove('loading');
884
- }
885
- else {
886
- sendBtn.textContent = 'Sending...';
887
- sendBtn.classList.add('loading');
888
- }
889
- }
890
- /**
891
- * Enable/disable mic button
892
- */
893
- enableMic(enabled) {
894
- const micBtn = getElementByIdOrNull('chat-mic');
895
- if (micBtn) {
896
- micBtn.disabled = !enabled;
897
- }
898
- }
899
- // =============================================
900
- // Input Handlers
901
- // =============================================
902
- /**
903
- * Handle chat input keydown
904
- */
905
- handleInputKeydown(event) {
906
- if (event.key === 'Enter' && !event.shiftKey) {
907
- event.preventDefault();
908
- // Use sendChatMessage which handles file attachments
909
- if (typeof window.sendChatMessage === 'function') {
910
- window.sendChatMessage();
911
- }
912
- else {
913
- this.send();
914
- }
915
- }
916
- }
917
- /**
918
- * Initialize chat input handlers
919
- */
920
- initChatInput() {
921
- const input = getElementByIdOrNull('chat-input');
922
- if (!input) {
923
- return;
924
- }
925
- const messagesContainer = getElementByIdOrNull('chat-messages');
926
- input.addEventListener('input', () => {
927
- autoResizeTextarea(input);
928
- });
929
- if (messagesContainer) {
930
- messagesContainer.addEventListener('click', (event) => {
931
- const target = event.target?.closest('.quiz-choice-btn');
932
- if (!target) {
933
- return;
934
- }
935
- const choice = target.dataset.choice;
936
- if (!choice) {
937
- return;
938
- }
939
- event.preventDefault();
940
- this.sendQuizChoice(choice);
941
- });
942
- }
943
- input.addEventListener('keydown', (event) => {
944
- this.handleInputKeydown(event);
945
- });
946
- }
947
- /**
948
- * Initialize long press to copy message functionality
949
- * Supports both touch (mobile) and mouse (desktop) events
950
- */
951
- initLongPressCopy() {
952
- const messagesContainer = getElementByIdOrNull('chat-messages');
953
- if (!messagesContainer) {
954
- return;
955
- }
956
- let pressTimer = null;
957
- const PRESS_DURATION = 750; // milliseconds
958
- // Touch events (mobile)
959
- messagesContainer.addEventListener('touchstart', (e) => {
960
- const target = e.target;
961
- const message = target?.closest('.chat-message');
962
- if (!message || message.classList.contains('system')) {
963
- return;
964
- }
965
- pressTimer = setTimeout(() => {
966
- copyMessageText(message);
967
- }, PRESS_DURATION);
968
- });
969
- messagesContainer.addEventListener('touchend', () => {
970
- if (pressTimer) {
971
- clearTimeout(pressTimer);
972
- pressTimer = null;
973
- }
974
- });
975
- messagesContainer.addEventListener('touchmove', () => {
976
- if (pressTimer) {
977
- clearTimeout(pressTimer);
978
- pressTimer = null;
979
- }
980
- });
981
- // Mouse events (desktop)
982
- messagesContainer.addEventListener('mousedown', (e) => {
983
- const target = e.target;
984
- const message = target?.closest('.chat-message');
985
- if (!message || message.classList.contains('system')) {
986
- return;
987
- }
988
- pressTimer = setTimeout(() => {
989
- copyMessageText(message);
990
- }, PRESS_DURATION);
991
- });
992
- messagesContainer.addEventListener('mouseup', () => {
993
- if (pressTimer) {
994
- clearTimeout(pressTimer);
995
- pressTimer = null;
996
- }
997
- });
998
- messagesContainer.addEventListener('mouseleave', () => {
999
- if (pressTimer) {
1000
- clearTimeout(pressTimer);
1001
- pressTimer = null;
1002
- }
1003
- });
1004
- /**
1005
- * Copy message text to clipboard
1006
- */
1007
- async function copyMessageText(messageEl) {
1008
- const textContent = messageEl.querySelector('.message-content');
1009
- if (!textContent) {
1010
- return;
1011
- }
1012
- const text = textContent.textContent || '';
1013
- try {
1014
- await navigator.clipboard.writeText(text);
1015
- showToast('📋 Copied to clipboard');
1016
- // Visual feedback
1017
- messageEl.style.opacity = '0.5';
1018
- setTimeout(() => {
1019
- messageEl.style.opacity = '1';
1020
- }, 300);
1021
- }
1022
- catch (err) {
1023
- logger.error('Copy failed:', err);
1024
- showToast('Failed to copy');
1025
- }
1026
- }
1027
- }
1028
- // =============================================
1029
- // Voice Input (Web Speech API)
1030
- // =============================================
1031
- /**
1032
- * Initialize speech recognition
1033
- */
1034
- initSpeechRecognition() {
1035
- const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
1036
- if (!SpeechRecognition) {
1037
- logger.warn('SpeechRecognition not supported');
1038
- const micBtn = getElementByIdOrNull('chat-mic');
1039
- if (micBtn) {
1040
- micBtn.style.display = 'none';
1041
- }
1042
- return;
1043
- }
1044
- this.speechRecognition = new SpeechRecognition();
1045
- const recognition = this.speechRecognition;
1046
- recognition.lang = navigator.language || 'ko-KR';
1047
- recognition.continuous = true;
1048
- recognition.interimResults = true;
1049
- recognition.maxAlternatives = 3;
1050
- recognition.onresult = (event) => {
1051
- const input = getElementByIdOrNull('chat-input');
1052
- if (!input) {
1053
- return;
1054
- }
1055
- let interimTranscript = '';
1056
- let finalTranscript = '';
1057
- // Build transcript from NEW results only (use resultIndex)
1058
- logger.debug('onresult fired, resultIndex:', event.resultIndex, 'total results:', event.results.length);
1059
- for (let i = event.resultIndex; i < event.results.length; i++) {
1060
- const result = event.results[i];
1061
- const transcript = result[0].transcript;
1062
- if (result.isFinal) {
1063
- finalTranscript += transcript;
1064
- logger.debug('Final result [' + i + ']:', transcript, 'Confidence:', result[0].confidence);
1065
- }
1066
- else {
1067
- interimTranscript += transcript;
1068
- logger.debug('Interim result [' + i + ']:', transcript);
1069
- }
1070
- }
1071
- // Handle final transcripts - accumulate them
1072
- if (finalTranscript) {
1073
- // Add space before appending if there's already text
1074
- if (this.accumulatedTranscript) {
1075
- this.accumulatedTranscript += ' ' + finalTranscript;
1076
- }
1077
- else {
1078
- this.accumulatedTranscript = finalTranscript;
1079
- }
1080
- input.value = this.accumulatedTranscript;
1081
- input.classList.remove('voice-active');
1082
- logger.debug('Accumulated transcript:', this.accumulatedTranscript);
1083
- }
1084
- // Handle interim transcripts - show temporarily with accumulated text
1085
- if (interimTranscript) {
1086
- const displayText = this.accumulatedTranscript
1087
- ? this.accumulatedTranscript + ' ' + interimTranscript
1088
- : interimTranscript;
1089
- input.value = displayText;
1090
- input.classList.add('voice-active');
1091
- logger.debug('Showing interim (temp):', displayText);
1092
- }
1093
- autoResizeTextarea(input);
1094
- // Reset silence timer on each result
1095
- if (this.silenceTimeout) {
1096
- clearTimeout(this.silenceTimeout);
1097
- }
1098
- this.silenceTimeout = setTimeout(() => {
1099
- if (this.isRecording) {
1100
- logger.info('Silence detected, stopping...');
1101
- this.stopVoice();
1102
- }
1103
- }, this.silenceDelay);
1104
- };
1105
- recognition.onend = () => {
1106
- logger.info('Recognition ended');
1107
- this.stopVoice();
1108
- };
1109
- recognition.onerror = (event) => {
1110
- logger.error('Error:', event.error);
1111
- this.stopVoice();
1112
- let errorMessage = '';
1113
- switch (event.error) {
1114
- case 'not-allowed':
1115
- errorMessage = '마이크 권한이 거부되었습니다. 브라우저 설정에서 마이크를 허용해주세요.';
1116
- break;
1117
- case 'no-speech':
1118
- errorMessage = '음성이 감지되지 않았습니다. 다시 시도해주세요.';
1119
- break;
1120
- case 'network':
1121
- errorMessage = '네트워크 오류가 발생했습니다.';
1122
- break;
1123
- default:
1124
- errorMessage = `음성 인식 오류: ${event.error}`;
1125
- }
1126
- this.addSystemMessage(errorMessage, 'error');
1127
- };
1128
- logger.info('SpeechRecognition initialized (lang:', recognition.lang + ')');
1129
- }
1130
- /**
1131
- * Toggle voice input
1132
- */
1133
- toggleVoice() {
1134
- if (this.isRecording) {
1135
- this.stopVoice();
1136
- }
1137
- else {
1138
- this.startVoice();
1139
- }
1140
- }
1141
- /**
1142
- * Start voice recording
1143
- */
1144
- startVoice() {
1145
- if (!this.speechRecognition) {
1146
- this.addSystemMessage('이 브라우저에서는 음성 인식이 지원되지 않습니다.', 'error');
1147
- return;
1148
- }
1149
- try {
1150
- const micBtn = getElementByIdOrNull('chat-mic');
1151
- const input = getElementByIdOrNull('chat-input');
1152
- if (!micBtn || !input) {
1153
- return;
1154
- }
1155
- // Clear input and accumulated transcript for new recording
1156
- input.value = '';
1157
- this.accumulatedTranscript = '';
1158
- this.speechRecognition.start();
1159
- this.isRecording = true;
1160
- micBtn.classList.add('recording');
1161
- input.classList.add('voice-active');
1162
- input.placeholder = '말씀해주세요... (계속 말하면 이어서 인식됩니다)';
1163
- logger.info('Recording started (continuous mode)');
1164
- logger.debug('Settings:', {
1165
- lang: this.speechRecognition.lang,
1166
- continuous: this.speechRecognition.continuous,
1167
- interimResults: this.speechRecognition.interimResults,
1168
- maxAlternatives: this.speechRecognition.maxAlternatives,
1169
- });
1170
- this.silenceTimeout = setTimeout(() => {
1171
- if (this.isRecording) {
1172
- this.stopVoice();
1173
- }
1174
- }, this.silenceDelay);
1175
- }
1176
- catch (err) {
1177
- logger.error('Failed to start:', err);
1178
- this.addSystemMessage('음성 인식을 시작할 수 없습니다.', 'error');
1179
- }
1180
- }
1181
- /**
1182
- * Stop voice recording
1183
- */
1184
- stopVoice() {
1185
- if (!this.isRecording) {
1186
- return;
1187
- }
1188
- if (this.silenceTimeout) {
1189
- clearTimeout(this.silenceTimeout);
1190
- }
1191
- try {
1192
- if (this.speechRecognition) {
1193
- this.speechRecognition.stop();
1194
- }
1195
- }
1196
- catch {
1197
- // Ignore errors
1198
- }
1199
- this.isRecording = false;
1200
- const micBtn = getElementByIdOrNull('chat-mic');
1201
- const input = getElementByIdOrNull('chat-input');
1202
- if (!micBtn || !input) {
1203
- return;
1204
- }
1205
- micBtn.classList.remove('recording');
1206
- input.classList.remove('voice-active');
1207
- input.placeholder = 'Type your message...';
1208
- logger.info('Recording stopped');
1209
- this.resetIdleTimer();
1210
- }
1211
- // =============================================
1212
- // Text-to-Speech (TTS)
1213
- // =============================================
1214
- /**
1215
- * Initialize Speech Synthesis
1216
- */
1217
- initSpeechSynthesis() {
1218
- if (!this.speechSynthesis) {
1219
- logger.warn('SpeechSynthesis not supported');
1220
- return;
1221
- }
1222
- // Wait for voices to load
1223
- const loadVoices = () => {
1224
- const voices = this.speechSynthesis.getVoices();
1225
- // Find Korean voice
1226
- this.ttsVoice =
1227
- voices.find((v) => v.lang === 'ko-KR') ||
1228
- voices.find((v) => v.lang.startsWith('ko')) ||
1229
- voices[0];
1230
- if (this.ttsVoice) {
1231
- logger.info('Korean voice selected:', this.ttsVoice.name, this.ttsVoice.lang);
1232
- }
1233
- else {
1234
- logger.warn('No Korean voice found, using default');
1235
- }
1236
- };
1237
- // Voices might not be loaded immediately
1238
- if (this.speechSynthesis.getVoices().length > 0) {
1239
- loadVoices();
1240
- }
1241
- else {
1242
- this.speechSynthesis.onvoiceschanged = loadVoices;
1243
- }
1244
- logger.info('SpeechSynthesis initialized');
1245
- }
1246
- /**
1247
- * Toggle TTS auto-play
1248
- */
1249
- toggleTTS() {
1250
- this.ttsEnabled = !this.ttsEnabled;
1251
- if (!this.ttsEnabled) {
1252
- this.stopSpeaking();
1253
- }
1254
- const btn = getElementByIdOrNull('chat-tts-toggle');
1255
- if (btn) {
1256
- btn.classList.toggle('active', this.ttsEnabled);
1257
- btn.title = this.ttsEnabled
1258
- ? 'TTS 활성화됨 (클릭하여 끄기)'
1259
- : 'TTS 비활성화됨 (클릭하여 켜기)';
1260
- }
1261
- logger.info('Auto-play:', this.ttsEnabled ? 'ON' : 'OFF');
1262
- showToast(this.ttsEnabled ? '🔊 TTS 활성화' : '🔇 TTS 비활성화');
1263
- }
1264
- /**
1265
- * Toggle hands-free mode
1266
- */
1267
- toggleHandsFree() {
1268
- this.handsFreeMode = !this.handsFreeMode;
1269
- const btn = getElementByIdOrNull('chat-handsfree-toggle');
1270
- if (btn) {
1271
- btn.classList.toggle('active', this.handsFreeMode);
1272
- btn.title = this.handsFreeMode ? '핸즈프리 활성화됨' : '핸즈프리 비활성화됨';
1273
- }
1274
- logger.info('Hands-free mode:', this.handsFreeMode ? 'ON' : 'OFF');
1275
- showToast(this.handsFreeMode ? '🎙️ 핸즈프리 모드 활성화' : '🎙️ 핸즈프리 모드 비활성화');
1276
- // Enable TTS automatically when hands-free is enabled
1277
- if (this.handsFreeMode && !this.ttsEnabled) {
1278
- this.toggleTTS();
1279
- }
1280
- }
1281
- /**
1282
- * Speak text using TTS
1283
- */
1284
- stripMarkdownForTTS(text) {
1285
- return text
1286
- .replace(/```[\s\S]*?```/g, '') // code blocks
1287
- .replace(/`([^`]+)`/g, '$1') // inline code
1288
- .replace(/\*\*([^*]+)\*\*/g, '$1') // bold
1289
- .replace(/\*([^*]+)\*/g, '$1') // italic
1290
- .replace(/~~([^~]+)~~/g, '$1') // strikethrough
1291
- .replace(/#{1,6}\s(.+)/g, '$1') // headers
1292
- .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') // links
1293
- .replace(/^[-*]\s/gm, '') // list markers
1294
- .replace(/!\[([^\]]*)\]\([^)]+\)/g, '$1') // images
1295
- .replace(/~\/.mama\/workspace\/media\/[^\s]+/g, '') // media paths
1296
- .replace(/[\u{1F600}-\u{1F9FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}\u{1F300}-\u{1F5FF}\u{1F680}-\u{1F6FF}\u{1FA00}-\u{1FAFF}]/gu, '') // emoji
1297
- .replace(/\n{2,}/g, '. ')
1298
- .trim();
1299
- }
1300
- speak(text) {
1301
- if (!this.speechSynthesis || !text) {
1302
- return;
1303
- }
1304
- text = this.stripMarkdownForTTS(text);
1305
- if (!text) {
1306
- return;
1307
- }
1308
- // Stop any ongoing speech
1309
- this.stopSpeaking();
1310
- const utterance = new SpeechSynthesisUtterance(text);
1311
- utterance.voice = this.ttsVoice;
1312
- utterance.rate = this.ttsRate;
1313
- utterance.pitch = this.ttsPitch;
1314
- utterance.lang = this.ttsVoice?.lang || navigator.language || 'ko-KR';
1315
- utterance.onstart = () => {
1316
- this.isSpeaking = true;
1317
- logger.debug('Speaking started');
1318
- };
1319
- utterance.onend = () => {
1320
- this.isSpeaking = false;
1321
- logger.debug('Speaking ended');
1322
- // If hands-free mode, start listening after TTS finishes
1323
- if (this.handsFreeMode && !this.isRecording) {
1324
- logger.info('Hands-free mode: auto-starting voice input');
1325
- setTimeout(() => {
1326
- this.startVoice();
1327
- }, 500); // Small delay for smooth transition
1328
- }
1329
- };
1330
- utterance.onerror = (event) => {
1331
- this.isSpeaking = false;
1332
- logger.error('Error:', event.error);
1333
- };
1334
- this.speechSynthesis.speak(utterance);
1335
- logger.debug('Speaking:', text.substring(0, 50) + '...');
1336
- }
1337
- /**
1338
- * Stop speaking
1339
- */
1340
- stopSpeaking() {
1341
- if (this.speechSynthesis && this.isSpeaking) {
1342
- this.speechSynthesis.cancel();
1343
- this.isSpeaking = false;
1344
- logger.debug('Speaking stopped');
1345
- }
1346
- }
1347
- /**
1348
- * Set TTS rate (0.5 - 2.0)
1349
- */
1350
- setTTSRate(rate) {
1351
- this.ttsRate = Math.max(0.5, Math.min(2.0, rate));
1352
- logger.info('Rate set to:', this.ttsRate);
1353
- }
1354
- // =============================================
1355
- // History Management
1356
- // =============================================
1357
- /**
1358
- * Save message to history
1359
- */
1360
- saveToHistory(role, content, timestamp = new Date(), attachment = null) {
1361
- if (!this.sessionId) {
1362
- return;
1363
- }
1364
- const entry = {
1365
- role,
1366
- content,
1367
- timestamp: timestamp.toISOString(),
1368
- ...(attachment ? { attachment } : {}),
1369
- };
1370
- this.history.push(entry);
1371
- if (this.history.length > this.maxHistoryMessages) {
1372
- this.history = this.history.slice(-this.maxHistoryMessages);
1373
- }
1374
- try {
1375
- const storageKey = this.historyStorageKey;
1376
- const storageData = {
1377
- history: this.history,
1378
- savedAt: Date.now(),
1379
- };
1380
- localStorage.setItem(storageKey, JSON.stringify(storageData));
1381
- }
1382
- catch (e) {
1383
- logger.warn('Failed to save history:', e);
1384
- }
1385
- }
1386
- /**
1387
- * Load history from localStorage
1388
- */
1389
- loadHistory(_sessionId) {
1390
- try {
1391
- const storageKey = this.historyStorageKey;
1392
- const stored = localStorage.getItem(storageKey);
1393
- if (!stored) {
1394
- return null;
1395
- }
1396
- const data = JSON.parse(stored);
1397
- if (Date.now() - data.savedAt > this.historyExpiryMs) {
1398
- localStorage.removeItem(storageKey);
1399
- return null;
1400
- }
1401
- return data.history || [];
1402
- }
1403
- catch (e) {
1404
- logger.warn('Failed to load history:', e);
1405
- return null;
1406
- }
1407
- }
1408
- /**
1409
- * Restore chat history (optimized with DocumentFragment)
1410
- */
1411
- restoreHistory(sessionId) {
1412
- const history = this.loadHistory(sessionId);
1413
- if (!history || history.length === 0) {
1414
- return false;
1415
- }
1416
- this.history = history;
1417
- const container = getElementByIdOrNull('chat-messages');
1418
- if (!container) {
1419
- return false;
1420
- }
1421
- this.removePlaceholder();
1422
- // Use DocumentFragment for batch DOM insertion
1423
- const fragment = document.createDocumentFragment();
1424
- // Limit to last N messages for DOM performance
1425
- const messagesToRender = history.slice(-this.maxDomMessages);
1426
- messagesToRender.forEach((msg) => {
1427
- const msgEl = document.createElement('div');
1428
- msgEl.className = `chat-message ${msg.role}`;
1429
- if (msg.role === 'user') {
1430
- let attachHtml = '';
1431
- if (msg.attachment) {
1432
- const att = msg.attachment;
1433
- if (att.isImage) {
1434
- const safeUrl = escapeAttr(att.mediaUrl);
1435
- const safeAlt = escapeAttr(att.originalName || '');
1436
- attachHtml = `<img src="${safeUrl}" class="max-w-[200px] rounded-lg mt-1 cursor-pointer" alt="${safeAlt}" data-lightbox="${safeUrl}" />`;
1437
- }
1438
- else {
1439
- const safeName = encodeURIComponent(att.filename);
1440
- attachHtml = `<a href="/api/media/download/${safeName}" target="_blank" class="flex items-center gap-2 mt-1 px-3 py-2 bg-white/50 rounded-lg border border-gray-200 text-sm hover:bg-white/80 transition-colors"><span class="text-lg">\u{1F4CE}</span><span class="truncate max-w-[180px]">${escapeHtml(att.originalName || att.filename)}</span></a>`;
1441
- }
1442
- }
1443
- msgEl.innerHTML = `
1444
- <div class="message-content">${escapeHtml(msg.content)}${attachHtml}</div>
1445
- <div class="message-time">${formatMessageTime(new Date(msg.timestamp))}</div>
1446
- `;
1447
- }
1448
- else if (msg.role === 'assistant') {
1449
- msgEl.innerHTML = `
1450
- <div class="message-content">${formatAssistantMessage(msg.content)}</div>
1451
- <div class="message-time">${formatMessageTime(new Date(msg.timestamp))}</div>
1452
- `;
1453
- }
1454
- else if (msg.role === 'system') {
1455
- msgEl.innerHTML = `
1456
- <div class="message-content">${escapeHtml(msg.content)}</div>
1457
- `;
1458
- }
1459
- fragment.appendChild(msgEl);
1460
- });
1461
- container.appendChild(fragment);
1462
- scrollToBottom(container);
1463
- showToast('Previous conversation restored');
1464
- return true;
1465
- }
1466
- /**
1467
- * Display history received from server (optimized with DocumentFragment)
1468
- */
1469
- displayHistory(messages) {
1470
- const container = getElementByIdOrNull('chat-messages');
1471
- if (!container) {
1472
- return;
1473
- }
1474
- // Server history is authoritative — always use it when available
1475
- if (messages.length === 0 && this.history.length > 0) {
1476
- logger.info(`Server sent empty history, keeping local (${this.history.length})`);
1477
- return;
1478
- }
1479
- // Merge: use server messages as base, append any local-only messages
1480
- // that are newer than the last server message
1481
- const serverTimestamp = messages.length > 0 ? new Date(messages[messages.length - 1].timestamp || 0).getTime() : 0;
1482
- const localOnlyMessages = this.history.filter((msg) => {
1483
- const msgTime = new Date(msg.timestamp).getTime();
1484
- return msgTime > serverTimestamp && msg.role !== 'system';
1485
- });
1486
- const merged = [...messages, ...localOnlyMessages];
1487
- const boundedHistory = merged.slice(-this.maxHistoryMessages);
1488
- container.innerHTML = '';
1489
- this.history = boundedHistory;
1490
- // Use DocumentFragment for batch DOM insertion
1491
- const fragment = document.createDocumentFragment();
1492
- const messagesToRender = boundedHistory.slice(-this.maxDomMessages);
1493
- messagesToRender.forEach((msg) => {
1494
- const msgEl = document.createElement('div');
1495
- msgEl.className = `chat-message ${msg.role}`;
1496
- const timestamp = msg.timestamp ? new Date(msg.timestamp) : new Date();
1497
- if (msg.role === 'user') {
1498
- msgEl.innerHTML = `
1499
- <div class="message-content">${escapeHtml(msg.content)}</div>
1500
- <div class="message-time">${formatMessageTime(timestamp)}</div>
1501
- `;
1502
- }
1503
- else if (msg.role === 'assistant') {
1504
- msgEl.innerHTML = `
1505
- <div class="message-content">${formatAssistantMessage(msg.content)}</div>
1506
- <div class="message-time">${formatMessageTime(timestamp)}</div>
1507
- `;
1508
- }
1509
- else if (msg.role === 'system') {
1510
- msgEl.innerHTML = `
1511
- <div class="message-content">${escapeHtml(msg.content)}</div>
1512
- `;
1513
- }
1514
- fragment.appendChild(msgEl);
1515
- });
1516
- container.appendChild(fragment);
1517
- scrollToBottom(container);
1518
- // Save merged history to localStorage
1519
- this.saveCurrentHistory();
1520
- logger.info('Displayed', messagesToRender.length, 'messages (server:', messages.length, '+ local:', localOnlyMessages.length, ')');
1521
- }
1522
- saveCurrentHistory() {
1523
- if (!this.sessionId) {
1524
- return;
1525
- }
1526
- try {
1527
- const storageKey = this.historyStorageKey;
1528
- const storageData = {
1529
- history: this.history,
1530
- savedAt: Date.now(),
1531
- };
1532
- localStorage.setItem(storageKey, JSON.stringify(storageData));
1533
- }
1534
- catch (e) {
1535
- logger.warn('Failed to save history:', e);
1536
- }
1537
- }
1538
- /**
1539
- * Clear chat history
1540
- */
1541
- clearHistory(_sessionId = null) {
1542
- try {
1543
- const storageKey = this.historyStorageKey;
1544
- localStorage.removeItem(storageKey);
1545
- this.history = [];
1546
- }
1547
- catch (e) {
1548
- logger.warn('Failed to clear history:', e);
1549
- }
1550
- }
1551
- /**
1552
- * Clean up expired histories
1553
- */
1554
- cleanupExpiredHistories() {
1555
- try {
1556
- const keys = Object.keys(localStorage);
1557
- const now = Date.now();
1558
- keys.forEach((key) => {
1559
- if (key.startsWith(this.historyPrefix)) {
1560
- try {
1561
- const data = JSON.parse(localStorage.getItem(key) ?? 'null');
1562
- if (data && data.savedAt && now - data.savedAt > this.historyExpiryMs) {
1563
- localStorage.removeItem(key);
1564
- logger.info('Cleaned up expired history:', key);
1565
- }
1566
- }
1567
- catch {
1568
- // Invalid data, remove it
1569
- localStorage.removeItem(key);
1570
- }
1571
- }
1572
- });
1573
- }
1574
- catch (e) {
1575
- logger.warn('Failed to cleanup histories:', e);
1576
- }
1577
- }
1578
- // =============================================
1579
- // Checkpoint Management
1580
- // =============================================
1581
- /**
1582
- * Generate checkpoint summary from current session (for manual /checkpoint command)
1583
- */
1584
- generateCheckpointSummary() {
1585
- const summary = {
1586
- sessionId: this.sessionId,
1587
- messageCount: this.history.length,
1588
- lastActivity: new Date().toISOString(),
1589
- messages: this.history.slice(-10).map((msg) => ({
1590
- role: msg.role,
1591
- preview: msg.content.substring(0, 100),
1592
- timestamp: msg.timestamp,
1593
- })),
1594
- };
1595
- return JSON.stringify(summary, null, 2);
1596
- }
1597
- /**
1598
- * Save checkpoint via API
1599
- */
1600
- async saveCheckpoint(summary) {
1601
- return await API.post('/api/checkpoint/save', { summary });
1602
- }
1603
- /**
1604
- * Load last checkpoint via API
1605
- */
1606
- async loadCheckpoint() {
1607
- try {
1608
- return await API.get('/api/checkpoint/load');
1609
- }
1610
- catch (error) {
1611
- if (error instanceof Error && error.message.includes('HTTP 404')) {
1612
- return null;
1613
- }
1614
- throw error;
1615
- }
1616
- }
1617
- /**
1618
- * Check for resumable session on init
1619
- */
1620
- async checkForResumableSession() {
1621
- try {
1622
- const checkpoint = await this.loadCheckpoint();
1623
- if (checkpoint) {
1624
- // Show resume banner
1625
- const banner = getElementByIdOrNull('session-resume-banner');
1626
- if (banner) {
1627
- banner.style.display = 'flex';
1628
- logger.info('Resume banner shown');
1629
- }
1630
- }
1631
- }
1632
- catch {
1633
- // Silent fail - no checkpoint is okay
1634
- logger.info('No resumable session');
1635
- }
1636
- }
1637
- // =============================================
1638
- // Floating Chat
1639
- // =============================================
1640
- /**
1641
- * Initialize floating chat panel bindings
1642
- */
1643
- initFloating() {
1644
- const bubble = getElementByIdOrNull('chat-bubble');
1645
- const closeBtn = getElementByIdOrNull('chat-close');
1646
- const resizeHandle = getElementByIdOrNull('chat-resize-handle');
1647
- const panel = getElementByIdOrNull('chat-panel');
1648
- const header = getElementByIdOrNull('chat-header');
1649
- // Right panel mode: no bubble, auto-init session
1650
- const isRightPanel = !bubble && !!document.getElementById('chat-panel-wrapper');
1651
- if (isRightPanel && !this.ws) {
1652
- this.initSession();
1653
- }
1654
- if (bubble) {
1655
- bubble.addEventListener('click', () => this.togglePanel());
1656
- }
1657
- if (closeBtn) {
1658
- closeBtn.addEventListener('click', () => this.togglePanel(false));
1659
- }
1660
- // Right panel mode: skip drag/resize handlers (handled by viewer.html inline JS)
1661
- if (isRightPanel)
1662
- return;
1663
- if (panel && header) {
1664
- let dragging = false;
1665
- let startX = 0;
1666
- let startY = 0;
1667
- let startLeft = 0;
1668
- let startTop = 0;
1669
- const startDrag = (clientX, clientY) => {
1670
- dragging = true;
1671
- const rect = panel.getBoundingClientRect();
1672
- startX = clientX;
1673
- startY = clientY;
1674
- startLeft = rect.left;
1675
- startTop = rect.top;
1676
- panel.classList.add('chat-panel-draggable');
1677
- document.body.style.userSelect = 'none';
1678
- };
1679
- const doDrag = (clientX, clientY) => {
1680
- if (!dragging) {
1681
- return;
1682
- }
1683
- const dx = clientX - startX;
1684
- const dy = clientY - startY;
1685
- const nextLeft = Math.max(8, Math.min(window.innerWidth - 80, startLeft + dx));
1686
- const nextTop = Math.max(8, Math.min(window.innerHeight - 80, startTop + dy));
1687
- panel.style.left = `${nextLeft}px`;
1688
- panel.style.top = `${nextTop}px`;
1689
- };
1690
- const endDrag = () => {
1691
- if (!dragging) {
1692
- return;
1693
- }
1694
- dragging = false;
1695
- document.body.style.userSelect = '';
1696
- document.body.classList.remove('no-scroll');
1697
- this.savePanelState(panel);
1698
- };
1699
- header.addEventListener('mousedown', (e) => {
1700
- const target = e.target;
1701
- if (target?.closest('button, a, input, select')) {
1702
- return;
1703
- }
1704
- e.preventDefault();
1705
- startDrag(e.clientX, e.clientY);
1706
- });
1707
- this._onDragMouseMove = (e) => doDrag(e.clientX, e.clientY);
1708
- this._onDragMouseUp = endDrag;
1709
- window.addEventListener('mousemove', this._onDragMouseMove);
1710
- window.addEventListener('mouseup', this._onDragMouseUp);
1711
- this._onDragTouchMove = (e) => {
1712
- const touch = e.touches[0];
1713
- if (!touch) {
1714
- return;
1715
- }
1716
- if (!dragging) {
1717
- return;
1718
- }
1719
- e.preventDefault();
1720
- doDrag(touch.clientX, touch.clientY);
1721
- };
1722
- this._onDragTouchEnd = endDrag;
1723
- header.addEventListener('touchstart', (e) => {
1724
- const target = e.target;
1725
- if (target?.closest('button, a, input, select')) {
1726
- return;
1727
- }
1728
- const touch = e.touches[0];
1729
- if (!touch) {
1730
- return;
1731
- }
1732
- e.preventDefault();
1733
- startDrag(touch.clientX, touch.clientY);
1734
- document.body.classList.add('no-scroll');
1735
- }, { passive: false });
1736
- window.addEventListener('touchmove', this._onDragTouchMove, { passive: false });
1737
- window.addEventListener('touchend', this._onDragTouchEnd);
1738
- }
1739
- if (resizeHandle && panel) {
1740
- let resizing = false;
1741
- let startX = 0;
1742
- let startY = 0;
1743
- let startW = 0;
1744
- let startH = 0;
1745
- const startResize = (clientX, clientY) => {
1746
- resizing = true;
1747
- const rect = panel.getBoundingClientRect();
1748
- startX = clientX;
1749
- startY = clientY;
1750
- startW = rect.width;
1751
- startH = rect.height;
1752
- document.body.style.userSelect = 'none';
1753
- };
1754
- const doResize = (clientX, clientY) => {
1755
- if (!resizing) {
1756
- return;
1757
- }
1758
- const dx = clientX - startX;
1759
- const dy = clientY - startY;
1760
- const minW = 280;
1761
- const minH = 320;
1762
- const maxW = Math.min(window.innerWidth * 0.96, 800);
1763
- const maxH = Math.min(window.innerHeight * 0.85, 900);
1764
- const nextW = Math.max(minW, Math.min(maxW, startW + dx));
1765
- const nextH = Math.max(minH, Math.min(maxH, startH + dy));
1766
- panel.style.width = `${nextW}px`;
1767
- panel.style.height = `${nextH}px`;
1768
- };
1769
- const endResize = () => {
1770
- if (!resizing) {
1771
- return;
1772
- }
1773
- resizing = false;
1774
- document.body.style.userSelect = '';
1775
- document.body.classList.remove('no-scroll');
1776
- this.savePanelState(panel);
1777
- };
1778
- resizeHandle.addEventListener('mousedown', (e) => {
1779
- e.preventDefault();
1780
- startResize(e.clientX, e.clientY);
1781
- });
1782
- this._onResizeMouseMove = (e) => doResize(e.clientX, e.clientY);
1783
- this._onResizeMouseUp = endResize;
1784
- window.addEventListener('mousemove', this._onResizeMouseMove);
1785
- window.addEventListener('mouseup', this._onResizeMouseUp);
1786
- this._onResizeTouchMove = (e) => {
1787
- const touch = e.touches[0];
1788
- if (!touch) {
1789
- return;
1790
- }
1791
- if (!resizing) {
1792
- return;
1793
- }
1794
- e.preventDefault();
1795
- doResize(touch.clientX, touch.clientY);
1796
- };
1797
- this._onResizeTouchEnd = endResize;
1798
- resizeHandle.addEventListener('touchstart', (e) => {
1799
- const touch = e.touches[0];
1800
- if (!touch) {
1801
- return;
1802
- }
1803
- e.preventDefault();
1804
- startResize(touch.clientX, touch.clientY);
1805
- document.body.classList.add('no-scroll');
1806
- }, { passive: false });
1807
- window.addEventListener('touchmove', this._onResizeTouchMove, { passive: false });
1808
- window.addEventListener('touchend', this._onResizeTouchEnd);
1809
- }
1810
- this._onEscapeKey = (e) => {
1811
- if (e.key === 'Escape' && this.isFloatingOpen()) {
1812
- this.togglePanel(false);
1813
- }
1814
- };
1815
- document.addEventListener('keydown', this._onEscapeKey);
1816
- logger.info('Floating mode initialized');
1817
- }
1818
- /**
1819
- * Toggle floating chat panel open/close
1820
- * @param {boolean} [forceState] - Force open (true) or close (false)
1821
- */
1822
- togglePanel(forceState) {
1823
- const panel = getElementByIdOrNull('chat-panel');
1824
- const bubble = getElementByIdOrNull('chat-bubble');
1825
- const badge = getElementByIdOrNull('chat-badge');
1826
- if (!panel) {
1827
- return;
1828
- }
1829
- const isClosed = panel.classList.contains('chat-panel-closed');
1830
- const shouldOpen = forceState !== undefined ? forceState : isClosed;
1831
- if (shouldOpen) {
1832
- // Lazy session init on first open
1833
- if (!this.ws) {
1834
- this.initSession();
1835
- }
1836
- panel.classList.remove('chat-panel-closed');
1837
- panel.classList.add('chat-panel-open', 'animate-slide-up');
1838
- this.restorePanelState(panel);
1839
- if (bubble) {
1840
- bubble.classList.add('scale-0');
1841
- }
1842
- if (badge) {
1843
- badge.classList.add('hidden');
1844
- }
1845
- const input = getElementByIdOrNull('chat-input');
1846
- if (input) {
1847
- setTimeout(() => input.focus(), 100);
1848
- }
1849
- const messages = getElementByIdOrNull('chat-messages');
1850
- if (messages) {
1851
- messages.scrollTop = messages.scrollHeight;
1852
- }
1853
- }
1854
- else {
1855
- panel.classList.add('chat-panel-closed');
1856
- panel.classList.remove('chat-panel-open', 'animate-slide-up');
1857
- if (bubble) {
1858
- bubble.classList.remove('scale-0');
1859
- }
1860
- }
1861
- }
1862
- /**
1863
- * Persist panel size + position
1864
- */
1865
- savePanelState(panel) {
1866
- try {
1867
- const rect = panel.getBoundingClientRect();
1868
- const state = {
1869
- width: rect.width,
1870
- height: rect.height,
1871
- left: rect.left,
1872
- top: rect.top,
1873
- };
1874
- localStorage.setItem('mama_chat_panel_state', JSON.stringify(state));
1875
- }
1876
- catch {
1877
- // ignore storage errors
1878
- }
1879
- }
1880
- /**
1881
- * Restore panel size + position
1882
- */
1883
- restorePanelState(panel) {
1884
- try {
1885
- const raw = localStorage.getItem('mama_chat_panel_state');
1886
- if (!raw) {
1887
- return;
1888
- }
1889
- const state = JSON.parse(raw);
1890
- if (state.width) {
1891
- panel.style.width = `${state.width}px`;
1892
- }
1893
- if (state.height) {
1894
- panel.style.height = `${state.height}px`;
1895
- }
1896
- if (state.left !== undefined && state.top !== undefined) {
1897
- panel.classList.add('chat-panel-draggable');
1898
- panel.style.left = `${state.left}px`;
1899
- panel.style.top = `${state.top}px`;
1900
- }
1901
- }
1902
- catch {
1903
- // ignore storage errors
1904
- }
1905
- }
1906
- /**
1907
- * Check if floating panel is open
1908
- */
1909
- isFloatingOpen() {
1910
- const panel = getElementByIdOrNull('chat-panel');
1911
- return Boolean(panel && panel.classList.contains('chat-panel-open'));
1912
- }
1913
- /**
1914
- * Show unread badge on bubble when panel is closed
1915
- */
1916
- showUnreadBadge() {
1917
- if (this.isFloatingOpen()) {
1918
- return;
1919
- }
1920
- const badge = getElementByIdOrNull('chat-badge');
1921
- if (badge) {
1922
- badge.classList.remove('hidden');
1923
- }
1924
- }
1925
- /**
1926
- * Cleanup resources when module is destroyed
1927
- * Prevents memory leaks by cleaning up timers, connections, and APIs
1928
- */
1929
- cleanup() {
1930
- // Clean up WebSocket
1931
- if (this.ws) {
1932
- this.ws.close();
1933
- this.ws = null;
1934
- }
1935
- // Clean up timers
1936
- if (this.silenceTimeout) {
1937
- clearTimeout(this.silenceTimeout);
1938
- this.silenceTimeout = null;
1939
- }
1940
- if (this.idleTimer) {
1941
- clearTimeout(this.idleTimer);
1942
- this.idleTimer = null;
1943
- }
1944
- // Clean up Speech Recognition
1945
- if (this.speechRecognition) {
1946
- this.speechRecognition.stop();
1947
- this.speechRecognition = null;
1948
- }
1949
- // Clean up Speech Synthesis
1950
- if (this.isSpeaking) {
1951
- this.speechSynthesis.cancel();
1952
- this.isSpeaking = false;
1953
- }
1954
- // Clean up window/document event listeners
1955
- if (this._onDragMouseMove) {
1956
- window.removeEventListener('mousemove', this._onDragMouseMove);
1957
- this._onDragMouseMove = null;
1958
- }
1959
- if (this._onDragMouseUp) {
1960
- window.removeEventListener('mouseup', this._onDragMouseUp);
1961
- this._onDragMouseUp = null;
1962
- }
1963
- if (this._onDragTouchMove) {
1964
- window.removeEventListener('touchmove', this._onDragTouchMove);
1965
- this._onDragTouchMove = null;
1966
- }
1967
- if (this._onDragTouchEnd) {
1968
- window.removeEventListener('touchend', this._onDragTouchEnd);
1969
- this._onDragTouchEnd = null;
1970
- }
1971
- if (this._onResizeMouseMove) {
1972
- window.removeEventListener('mousemove', this._onResizeMouseMove);
1973
- this._onResizeMouseMove = null;
1974
- }
1975
- if (this._onResizeMouseUp) {
1976
- window.removeEventListener('mouseup', this._onResizeMouseUp);
1977
- this._onResizeMouseUp = null;
1978
- }
1979
- if (this._onResizeTouchMove) {
1980
- window.removeEventListener('touchmove', this._onResizeTouchMove);
1981
- this._onResizeTouchMove = null;
1982
- }
1983
- if (this._onResizeTouchEnd) {
1984
- window.removeEventListener('touchend', this._onResizeTouchEnd);
1985
- this._onResizeTouchEnd = null;
1986
- }
1987
- if (this._onEscapeKey) {
1988
- document.removeEventListener('keydown', this._onEscapeKey);
1989
- this._onEscapeKey = null;
1990
- }
1991
- logger.info('Cleanup completed');
1992
- }
1993
- }