agentgui 1.0.828 → 1.0.830

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.
@@ -0,0 +1,132 @@
1
+ Object.assign(AgentGUIClient.prototype, {
2
+ renderCodeBlock(language, code) {
3
+ if (language.toLowerCase() === 'html') {
4
+ return `
5
+ <div class="message-code">
6
+ <div class="html-rendered-label">
7
+ Rendered HTML
8
+ </div>
9
+ <div class="html-content">
10
+ ${this.sanitizeHtml(code)}
11
+ </div>
12
+ </div>
13
+ `;
14
+ } else {
15
+ const lineCount = code.split('\n').length;
16
+ return `<div class="message-code"><details class="collapsible-code"><summary class="collapsible-code-summary">${this.escapeHtml(language)} - ${lineCount} line${lineCount !== 1 ? 's' : ''}</summary><pre style="margin:0;border-radius:0 0 0.375rem 0.375rem">${this.escapeHtml(code)}</pre></details></div>`;
17
+ }
18
+ },
19
+
20
+
21
+ renderMessageContent(content) {
22
+ if (typeof content === 'string') {
23
+ if (this.isHtmlContent(content)) {
24
+ return `<div class="message-text"><div class="html-content">${this.sanitizeHtml(content)}</div></div>`;
25
+ }
26
+ return `<div class="message-text">${this.escapeHtml(content)}</div>`;
27
+ } else if (content && typeof content === 'object' && content.type === 'claude_execution') {
28
+ let html = '<div class="message-blocks">';
29
+ if (content.blocks && Array.isArray(content.blocks)) {
30
+ let pendingToolUseClose = false;
31
+ let pendingHasInput = false;
32
+ content.blocks.forEach((block, blockIdx, blocks) => {
33
+ if (block.type !== 'tool_result' && pendingToolUseClose) {
34
+ if (pendingHasInput) html += '</div>';
35
+ html += '</details>';
36
+ pendingToolUseClose = false;
37
+ pendingHasInput = false;
38
+ }
39
+ if (block.type === 'text') {
40
+ const parts = this.parseMarkdownCodeBlocks(block.text);
41
+ parts.forEach(part => {
42
+ if (part.type === 'html') {
43
+ html += `<div class="message-text"><div class="html-content">${this.sanitizeHtml(part.content)}</div></div>`;
44
+ } else if (part.type === 'text') {
45
+ html += `<div class="message-text">${this.escapeHtml(part.content)}</div>`;
46
+ } else if (part.type === 'code') {
47
+ html += this.renderCodeBlock(part.language, part.code);
48
+ }
49
+ });
50
+ } else if (block.type === 'code_block') {
51
+ if (block.language === 'html') {
52
+ html += `
53
+ <div class="message-code">
54
+ <div class="html-rendered-label">
55
+ Rendered HTML
56
+ </div>
57
+ <div class="html-content">
58
+ ${this.sanitizeHtml(block.code)}
59
+ </div>
60
+ </div>
61
+ `;
62
+ } else {
63
+ const blkLineCount = block.code.split('\n').length;
64
+ html += `<div class="message-code"><details class="collapsible-code"><summary class="collapsible-code-summary">${this.escapeHtml(block.language || 'code')} - ${blkLineCount} line${blkLineCount !== 1 ? 's' : ''}</summary><pre style="margin:0;border-radius:0 0 0.375rem 0.375rem">${this.escapeHtml(block.code)}</pre></details></div>`;
65
+ }
66
+ } else if (block.type === 'tool_use') {
67
+ let inputContentHtml = '';
68
+ const hasInput = block.input && Object.keys(block.input).length > 0;
69
+ if (hasInput) {
70
+ const inputStr = JSON.stringify(block.input, null, 2);
71
+ inputContentHtml = `<pre class="tool-input-pre">${this.escapeHtml(inputStr)}</pre>`;
72
+ }
73
+ const tn = block.name || 'unknown';
74
+ const hasRenderer = typeof StreamingRenderer !== 'undefined';
75
+ const dName = hasRenderer ? StreamingRenderer.getToolDisplayName(tn) : tn;
76
+ const tTitle = hasRenderer && block.input ? StreamingRenderer.getToolTitle(tn, block.input) : '';
77
+ const iconHtml = hasRenderer && this.renderer ? `<span class="folded-tool-icon">${this.renderer.getToolIcon(tn)}</span>` : '';
78
+ const typeClass = hasRenderer && this.renderer ? this.renderer._getBlockTypeClass('tool_use') : 'block-type-tool_use';
79
+ const toolColorClass = hasRenderer && this.renderer ? this.renderer._getToolColorClass(tn) : 'tool-color-default';
80
+ const nextBlock = blocks[blockIdx + 1];
81
+ const resultClass = nextBlock?.type === 'tool_result' ? (nextBlock.is_error ? 'has-error tool-result-error' : 'has-success tool-result-success') : '';
82
+ const resultStatusIcon = nextBlock?.type === 'tool_result'
83
+ ? `<span class="folded-tool-status">${nextBlock.is_error
84
+ ? '<svg viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"/></svg>'
85
+ : '<svg viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/></svg>'
86
+ }</span>` : '';
87
+ if (hasInput) {
88
+ html += `<details class="block-tool-use folded-tool ${typeClass} ${toolColorClass} ${resultClass}"><summary class="folded-tool-bar">${iconHtml}<span class="folded-tool-name">${this.escapeHtml(dName)}</span>${tTitle ? `<span class="folded-tool-desc">${this.escapeHtml(tTitle)}</span>` : ''}${resultStatusIcon}</summary><div class="folded-tool-body">${inputContentHtml}`;
89
+ pendingHasInput = true;
90
+ } else {
91
+ html += `<details class="block-tool-use folded-tool ${typeClass} ${toolColorClass} ${resultClass}"><summary class="folded-tool-bar">${iconHtml}<span class="folded-tool-name">${this.escapeHtml(dName)}</span>${tTitle ? `<span class="folded-tool-desc">${this.escapeHtml(tTitle)}</span>` : ''}${resultStatusIcon}</summary>`;
92
+ pendingHasInput = false;
93
+ }
94
+ pendingToolUseClose = true;
95
+ } else if (block.type === 'tool_result') {
96
+ const content = typeof block.content === 'string' ? block.content : JSON.stringify(block.content);
97
+ const smartHtml = typeof StreamingRenderer !== 'undefined' ? StreamingRenderer.renderSmartContentHTML(content, this.escapeHtml.bind(this), true) : `<pre class="tool-result-pre">${this.escapeHtml(content.length > 2000 ? content.substring(0, 2000) + '\n... (truncated)' : content)}</pre>`;
98
+ const resultContentHtml = `<div class="folded-tool-result-content">${smartHtml}</div>`;
99
+ if (pendingToolUseClose) {
100
+ if (pendingHasInput) {
101
+ html += resultContentHtml + '</div></details>';
102
+ } else {
103
+ html += `<div class="folded-tool-body">${resultContentHtml}</div></details>`;
104
+ }
105
+ pendingToolUseClose = false;
106
+ } else {
107
+ html += resultContentHtml;
108
+ }
109
+ }
110
+ });
111
+ if (pendingToolUseClose) {
112
+ if (pendingHasInput) html += '</div>';
113
+ html += '</details>';
114
+ }
115
+ }
116
+ html += '</div>';
117
+ return html;
118
+ } else {
119
+ if (typeof content === 'object' && content !== null) {
120
+ const fieldsHtml = Object.entries(content)
121
+ .map(([key, value]) => {
122
+ let displayValue = typeof value === 'string' ? value : JSON.stringify(value);
123
+ if (displayValue.length > 150) displayValue = displayValue.substring(0, 150) + '...';
124
+ return `<div style="font-size:0.8rem;margin-bottom:0.375rem"><span style="font-weight:600">${this.escapeHtml(key)}:</span> <code style="background:var(--color-bg-secondary);padding:0.125rem 0.25rem;border-radius:0.25rem">${this.escapeHtml(displayValue)}</code></div>`;
125
+ }).join('');
126
+ return `<div class="message-text" style="background:var(--color-bg-secondary);padding:0.75rem;border-radius:0.375rem">${fieldsHtml}</div>`;
127
+ }
128
+ return `<div class="message-text">${this.escapeHtml(String(content))}</div>`;
129
+ }
130
+ }
131
+
132
+ });
@@ -0,0 +1,178 @@
1
+ Object.assign(AgentGUIClient.prototype, {
2
+ syncPromptState(conversationId) {
3
+ const conversation = this.state.currentConversation;
4
+ if (!conversation || conversation.id !== conversationId) return;
5
+
6
+ if (this.ui.messageInput) {
7
+ this.ui.messageInput.disabled = false;
8
+ }
9
+
10
+ this.updateBusyPromptArea(conversationId);
11
+ }
12
+
13
+
14
+ updateBusyPromptArea(conversationId) {
15
+ if (this.state.currentConversation?.id !== conversationId) return;
16
+ const isStreaming = this._convIsStreaming(conversationId);
17
+ const isConnected = this.wsManager?.isConnected;
18
+
19
+ const injectBtn = document.getElementById('injectBtn');
20
+ const queueBtn = document.getElementById('queueBtn');
21
+ const stopBtn = document.getElementById('stopBtn');
22
+
23
+ [injectBtn, queueBtn, stopBtn].forEach(btn => {
24
+ if (!btn) return;
25
+ btn.classList.toggle('visible', isStreaming);
26
+ btn.disabled = !isConnected;
27
+ });
28
+
29
+ if (this.ui.sendButton) this.ui.sendButton.style.display = isStreaming ? 'none' : '';
30
+ }
31
+
32
+
33
+ removeScrollUpDetection() {
34
+ const scrollContainer = document.getElementById(this.config.scrollContainerId);
35
+ if (scrollContainer && this._scrollUpHandler) {
36
+ scrollContainer.removeEventListener('scroll', this._scrollUpHandler);
37
+ this._scrollUpHandler = null;
38
+ }
39
+ }
40
+
41
+
42
+ setupScrollUpDetection(conversationId) {
43
+ const scrollContainer = document.getElementById(this.config.scrollContainerId);
44
+ if (!scrollContainer) return;
45
+
46
+ if (!this._scrollDetectionState) this._scrollDetectionState = {};
47
+
48
+ const detectionState = {
49
+ isLoading: false,
50
+ oldestTimestamp: Date.now(),
51
+ oldestMessageId: null,
52
+ conversation: conversationId
53
+ };
54
+
55
+ const handleScroll = async () => {
56
+ const scrollTop = scrollContainer.scrollTop;
57
+ const scrollHeight = scrollContainer.scrollHeight;
58
+ const clientHeight = scrollContainer.clientHeight;
59
+ const THRESHOLD = 300;
60
+
61
+ if (scrollTop < THRESHOLD && !detectionState.isLoading && scrollHeight > clientHeight) {
62
+ detectionState.isLoading = true;
63
+
64
+ try {
65
+ const messagesEl = document.querySelector('.conversation-messages');
66
+ if (!messagesEl) {
67
+ detectionState.isLoading = false;
68
+ return;
69
+ }
70
+
71
+ const firstMessageEl = messagesEl.querySelector('.message[data-msg-id]');
72
+ if (!firstMessageEl) {
73
+ const firstChunkEl = messagesEl.querySelector('[data-chunk-created]');
74
+ if (firstChunkEl) {
75
+ detectionState.oldestTimestamp = parseInt(firstChunkEl.getAttribute('data-chunk-created')) || 0;
76
+ }
77
+ } else {
78
+ detectionState.oldestMessageId = firstMessageEl.getAttribute('data-msg-id');
79
+ }
80
+
81
+ let result;
82
+ if (detectionState.oldestMessageId) {
83
+ try {
84
+ result = await window.wsClient.rpc('msg.ls.earlier', {
85
+ id: conversationId,
86
+ before: detectionState.oldestMessageId,
87
+ limit: 50
88
+ });
89
+ } catch (e) {
90
+ const base = window.__BASE_URL || '';
91
+ const r = await fetch(`${base}/api/conversations/${conversationId}/messages?limit=50`);
92
+ const d = await r.json();
93
+ result = { messages: d.messages || [] };
94
+ }
95
+ } else if (detectionState.oldestTimestamp > 0) {
96
+ try {
97
+ result = await window.wsClient.rpc('conv.chunks.earlier', {
98
+ id: conversationId,
99
+ before: detectionState.oldestTimestamp,
100
+ limit: 500
101
+ });
102
+ } catch (e) {
103
+ const base = window.__BASE_URL || '';
104
+ const r = await fetch(`${base}/api/conversations/${conversationId}/chunks`);
105
+ const d = await r.json();
106
+ result = { chunks: d.chunks || [] };
107
+ }
108
+ }
109
+
110
+ if (result && ((result.messages && result.messages.length > 0) || (result.chunks && result.chunks.length > 0))) {
111
+ const scrollHeightBefore = scrollContainer.scrollHeight;
112
+ const scrollTopBefore = scrollContainer.scrollTop;
113
+ const newContent = document.createDocumentFragment();
114
+
115
+ if (result.messages && result.messages.length > 0) {
116
+ result.messages.forEach(msg => {
117
+ const div = document.createElement('div');
118
+ div.className = `message message-${msg.role}`;
119
+ div.setAttribute('data-msg-id', msg.id);
120
+ div.innerHTML = `<div class="message-role">${msg.role.charAt(0).toUpperCase() + msg.role.slice(1)}</div>${this.renderMessageContent(msg.content)}<div class="message-timestamp">${new Date(msg.created_at).toLocaleString()}</div>`;
121
+ newContent.appendChild(div);
122
+ });
123
+ }
124
+
125
+ if (result.chunks && result.chunks.length > 0) {
126
+ result.chunks.forEach(chunk => {
127
+ const blockEl = this.renderer.renderBlock(chunk.data, {}, false);
128
+ if (blockEl) {
129
+ const wrapper = document.createElement('div');
130
+ wrapper.setAttribute('data-chunk-created', chunk.created_at);
131
+ wrapper.appendChild(blockEl);
132
+ newContent.appendChild(wrapper);
133
+ }
134
+ });
135
+ }
136
+
137
+ if (messagesEl.firstChild) {
138
+ messagesEl.insertBefore(newContent, messagesEl.firstChild);
139
+ } else {
140
+ messagesEl.appendChild(newContent);
141
+ }
142
+
143
+ const scrollHeightAfter = scrollContainer.scrollHeight;
144
+ scrollContainer.scrollTop = scrollTopBefore + (scrollHeightAfter - scrollHeightBefore);
145
+ }
146
+ } catch (error) {
147
+ console.error('Failed to load earlier messages:', error);
148
+ } finally {
149
+ detectionState.isLoading = false;
150
+ }
151
+ }
152
+ };
153
+
154
+ scrollContainer.removeEventListener('scroll', this._scrollUpHandler);
155
+ this._scrollUpHandler = handleScroll;
156
+ scrollContainer.addEventListener('scroll', this._scrollUpHandler, { passive: true });
157
+ }
158
+
159
+
160
+ renderMessagesFragment(messages) {
161
+ const frag = document.createDocumentFragment();
162
+ if (messages.length === 0) {
163
+ const p = document.createElement('p');
164
+ p.className = 'text-secondary';
165
+ p.textContent = 'No messages in this conversation yet';
166
+ frag.appendChild(p);
167
+ return frag;
168
+ }
169
+ for (const msg of messages) {
170
+ const div = document.createElement('div');
171
+ div.className = `message message-${msg.role}`;
172
+ div.innerHTML = `<div class="message-role">${msg.role.charAt(0).toUpperCase() + msg.role.slice(1)}</div>${this.renderMessageContent(msg.content)}<div class="message-timestamp">${new Date(msg.created_at).toLocaleString()}</div>`;
173
+ frag.appendChild(div);
174
+ }
175
+ return frag;
176
+ }
177
+
178
+ });
@@ -0,0 +1,167 @@
1
+ Object.assign(AgentGUIClient.prototype, {
2
+ _updateConnectionIndicator(quality) {
3
+ if (this._indicatorDebounce && !this._modelDownloadInProgress) return;
4
+ this._indicatorDebounce = true;
5
+ setTimeout(() => { this._indicatorDebounce = false; }, 1000);
6
+
7
+ let indicator = document.getElementById('connection-indicator');
8
+ if (!indicator) {
9
+ indicator = document.createElement('div');
10
+ indicator.id = 'connection-indicator';
11
+ indicator.className = 'connection-indicator';
12
+ indicator.innerHTML = '<span class="connection-dot"></span><span class="connection-label"></span>';
13
+ indicator.addEventListener('click', () => this._toggleConnectionTooltip());
14
+ const header = document.querySelector('.header-right') || document.querySelector('.app-header');
15
+ if (header) {
16
+ header.style.position = 'relative';
17
+ header.appendChild(indicator);
18
+ }
19
+ }
20
+
21
+ const dot = indicator.querySelector('.connection-dot');
22
+ const label = indicator.querySelector('.connection-label');
23
+ if (!dot || !label) return;
24
+
25
+ if (this._modelDownloadInProgress) {
26
+ dot.className = 'connection-dot downloading';
27
+ const progress = this._modelDownloadProgress;
28
+ if (progress && progress.totalBytes > 0) {
29
+ const pct = Math.round((progress.totalDownloaded / progress.totalBytes) * 100);
30
+ label.textContent = `Models ${pct}%`;
31
+ } else if (progress && progress.downloading) {
32
+ label.textContent = 'Downloading...';
33
+ } else {
34
+ label.textContent = 'Loading models...';
35
+ }
36
+ return;
37
+ }
38
+
39
+ dot.className = 'connection-dot';
40
+ if (quality === 'disconnected' || quality === 'reconnecting') {
41
+ dot.classList.add(quality);
42
+ label.textContent = quality === 'reconnecting' ? 'Reconnecting...' : 'Disconnected';
43
+ } else {
44
+ dot.classList.add(quality);
45
+ const latency = this.wsManager?.latency;
46
+ label.textContent = latency?.avg > 0 ? Math.round(latency.avg) + 'ms' : '';
47
+ }
48
+ },
49
+
50
+
51
+ _handleModelDownloadProgress(progress) {
52
+ this._modelDownloadProgress = progress;
53
+ if (progress.status === 'failed' || progress.error) {
54
+ this._modelDownloadInProgress = false;
55
+ console.error('[Models] Download error:', progress.error || progress.status);
56
+ this._updateConnectionIndicator(this.wsManager?.latency?.quality || 'unknown');
57
+ return;
58
+ }
59
+ if (progress.done || progress.status === 'completed') {
60
+ this._modelDownloadInProgress = false;
61
+ this._dbg('[Models] Download complete');
62
+ this._updateConnectionIndicator(this.wsManager?.latency?.quality || 'unknown');
63
+ return;
64
+ }
65
+ if (progress.started || progress.downloading || progress.status === 'downloading' || progress.status === 'connecting') {
66
+ this._modelDownloadInProgress = true;
67
+ this._updateConnectionIndicator(this.wsManager?.latency?.quality || 'unknown');
68
+ }
69
+ },
70
+
71
+
72
+ _handleTTSSetupProgress(data) {
73
+ if (data.step && data.status) {
74
+ this._dbg('[TTS Setup]', data.step, ':', data.status, data.message || '');
75
+ }
76
+ },
77
+
78
+
79
+ _toggleConnectionTooltip() {
80
+ let tooltip = document.getElementById('connection-tooltip');
81
+ if (tooltip) { tooltip.remove(); return; }
82
+
83
+ const indicator = document.getElementById('connection-indicator');
84
+ if (!indicator) return;
85
+
86
+ tooltip = document.createElement('div');
87
+ tooltip.id = 'connection-tooltip';
88
+ tooltip.className = 'connection-tooltip';
89
+
90
+ const latency = this.wsManager?.latency || {};
91
+ const stats = this.wsManager?.stats || {};
92
+ const state = this.wsManager?.connectionState || 'unknown';
93
+
94
+ tooltip.innerHTML = [
95
+ `<div>State: ${state}</div>`,
96
+ `<div>Latency: ${Math.round(latency.avg || 0)}ms</div>`,
97
+ `<div>Predicted: ${Math.round(latency.predicted || 0)}ms (Kalman)</div>`,
98
+ `<div>Trend: ${latency.trend || 'unknown'}</div>`,
99
+ `<div>Jitter: ${Math.round(latency.jitter || 0)}ms</div>`,
100
+ `<div>Quality: ${latency.quality || 'unknown'}</div>`,
101
+ `<div>Reconnects: ${stats.totalReconnects || 0}</div>`,
102
+ `<div>Uptime: ${stats.lastConnectedTime ? Math.round((Date.now() - stats.lastConnectedTime) / 1000) + 's' : 'N/A'}</div>`
103
+ ].join('');
104
+
105
+ indicator.appendChild(tooltip);
106
+ setTimeout(() => { if (tooltip.parentNode) tooltip.remove(); }, 5000);
107
+ },
108
+
109
+
110
+ updateMetrics(metrics) {
111
+ const metricsDisplay = document.querySelector('[data-metrics]');
112
+ if (metricsDisplay && metrics) {
113
+ metricsDisplay.textContent = `Batches: ${metrics.totalBatches} | Events: ${metrics.totalEvents} | Avg render: ${metrics.avgRenderTime.toFixed(2)}ms`;
114
+ }
115
+ },
116
+
117
+
118
+ disableControls() {
119
+ if (this.ui.sendButton) this.ui.sendButton.disabled = true;
120
+ if (window.promptMachineAPI) window.promptMachineAPI.send({ type: 'DISABLED' });
121
+ },
122
+
123
+
124
+ enableControls() {
125
+ if (this.ui.sendButton) {
126
+ this.ui.sendButton.disabled = !this.wsManager?.isConnected;
127
+ }
128
+ if (window.promptMachineAPI) window.promptMachineAPI.send({ type: 'READY' });
129
+ this.updateBusyPromptArea(this.state.currentConversation?.id);
130
+ },
131
+
132
+
133
+ toggleTheme() {
134
+ const isDark = document.documentElement.classList.toggle('dark');
135
+ localStorage.setItem('theme', isDark ? 'dark' : 'light');
136
+ },
137
+
138
+
139
+ async createNewConversation(workingDirectory, title) {
140
+ try {
141
+ const agentId = this.getEffectiveAgentId();
142
+ const model = this.ui.modelSelector?.value || null;
143
+ const convTitle = title || 'New Conversation';
144
+ const body = { agentId, title: convTitle };
145
+ if (workingDirectory) body.workingDirectory = workingDirectory;
146
+ if (model) body.model = model;
147
+
148
+ const { conversation } = await window.wsClient.rpc('conv.new', body);
149
+
150
+ await this.loadConversations();
151
+
152
+ if (window.conversationManager) {
153
+ await window.conversationManager.loadConversations();
154
+ window.conversationManager.select(conversation.id);
155
+ }
156
+
157
+ if (this.ui.messageInput) {
158
+ this.ui.messageInput.value = '';
159
+ this.ui.messageInput.focus();
160
+ }
161
+ } catch (error) {
162
+ console.error('Failed to create new conversation:', error);
163
+ this.showError(`Failed to create conversation: ${error.message}`);
164
+ }
165
+ }
166
+
167
+ });
@@ -0,0 +1,117 @@
1
+ Object.assign(AgentGUIClient.prototype, {
2
+ async handleStreamingStart(data) {
3
+ this._dbg('Streaming started:', data);
4
+ if (window.promptMachineAPI) window.promptMachineAPI.send({ type: 'STREAMING', conversationId: data.conversationId });
5
+ this._clearThinkingCountdown();
6
+ if (this._lastSendTime > 0) {
7
+ const actual = Date.now() - this._lastSendTime;
8
+ const predicted = this.wsManager?.latency?.predicted || 0;
9
+ const serverTime = Math.max(500, actual - predicted);
10
+ this._serverProcessingEstimate = 0.7 * this._serverProcessingEstimate + 0.3 * serverTime;
11
+ }
12
+
13
+ if (this.wsManager.isConnected) {
14
+ this.wsManager.subscribeToSession(data.sessionId);
15
+ if (!data.resumed) {
16
+ this.wsManager.sendMessage({ type: 'subscribe', conversationId: data.conversationId });
17
+ }
18
+ }
19
+
20
+ if (this.state.currentConversation?.id !== data.conversationId) {
21
+ this._dbg('Streaming started for non-active conversation:', data.conversationId);
22
+ this._setConvStreaming(data.conversationId, true, data.sessionId, data.agentId);
23
+ this._dbg('[SYNC] streaming_start - non-active conv:', { convId: data.conversationId, sessionId: data.sessionId, streamingCount: this.state.streamingConversations.size });
24
+ this.updateBusyPromptArea(data.conversationId);
25
+ this.emit('streaming:start', data);
26
+
27
+ if (!this.state.currentConversation && !this._isLoadingConversation) {
28
+ this._isLoadingConversation = true;
29
+ this.loadConversationMessages(data.conversationId).finally(() => {
30
+ this._isLoadingConversation = false;
31
+ });
32
+ }
33
+ return;
34
+ }
35
+
36
+ this._setConvStreaming(data.conversationId, true, data.sessionId, data.agentId);
37
+ this.updateBusyPromptArea(data.conversationId);
38
+ this.state.currentSession = {
39
+ id: data.sessionId,
40
+ conversationId: data.conversationId,
41
+ agentId: data.agentId,
42
+ startTime: Date.now()
43
+ };
44
+ this.state.sessionEvents = [];
45
+
46
+ this.updateUrlForConversation(data.conversationId, data.sessionId);
47
+
48
+ if (this.wsManager.isConnected) {
49
+ this.wsManager.subscribeToSession(data.sessionId);
50
+ }
51
+
52
+ const outputEl = document.getElementById('output');
53
+ if (outputEl) {
54
+ let messagesEl = outputEl.querySelector('.conversation-messages');
55
+ if (!messagesEl) {
56
+ const conv = this.state.currentConversation;
57
+ const wdInfo = conv?.workingDirectory ? `${this.escapeHtml(conv.workingDirectory)}` : '';
58
+ const timestamp = new Date(conv?.created_at || Date.now()).toLocaleDateString();
59
+ const metaParts = [timestamp];
60
+ if (conv?.agentType || conv?.agentId) metaParts.push(this.escapeHtml(conv.agentType || conv.agentId));
61
+ if (conv?.messageCount > 0) metaParts.push(`${conv.messageCount} msgs`);
62
+ if (wdInfo) metaParts.push(wdInfo);
63
+ outputEl.innerHTML = `
64
+ <div class="conversation-header">
65
+ <h2>${this.escapeHtml(conv?.title || 'Conversation')}</h2>
66
+ <p class="text-secondary">${metaParts.join(' - ')}</p>
67
+ </div>
68
+ <div class="conversation-messages"></div>
69
+ `;
70
+ messagesEl = outputEl.querySelector('.conversation-messages');
71
+ }
72
+ let streamingDiv = document.getElementById(`streaming-${data.sessionId}`);
73
+ if (!streamingDiv) {
74
+ streamingDiv = document.createElement('div');
75
+ streamingDiv.className = 'message message-assistant streaming-message';
76
+ streamingDiv.id = `streaming-${data.sessionId}`;
77
+ streamingDiv.innerHTML = `
78
+ <div class="message-role">Assistant</div>
79
+ <div class="message-blocks streaming-blocks"></div>
80
+ <div class="streaming-indicator" style="display:flex;align-items:center;gap:0.5rem;padding:0.5rem 0;color:var(--color-text-secondary);font-size:0.875rem;">
81
+ <span class="animate-spin" style="display:inline-block;width:1rem;height:1rem;border:2px solid var(--color-border);border-top-color:var(--color-primary);border-radius:50%;"></span>
82
+ <span class="streaming-indicator-label">Thinking...</span>
83
+ </div>
84
+ `;
85
+ messagesEl.appendChild(streamingDiv);
86
+ } else {
87
+ streamingDiv.classList.add('streaming-message');
88
+ streamingDiv.querySelectorAll('.streaming-indicator').forEach(ind => ind.remove());
89
+ const indDiv = document.createElement('div');
90
+ indDiv.className = 'streaming-indicator';
91
+ indDiv.style = 'display:flex;align-items:center;gap:0.5rem;padding:0.5rem 0;color:var(--color-text-secondary);font-size:0.875rem;';
92
+ indDiv.innerHTML = `<span class="animate-spin" style="display:inline-block;width:1rem;height:1rem;border:2px solid var(--color-border);border-top-color:var(--color-primary);border-radius:50%;"></span><span class="streaming-indicator-label">Thinking...</span>`;
93
+ streamingDiv.appendChild(indDiv);
94
+ }
95
+ this.scrollToBottom(true);
96
+ }
97
+
98
+ this._streamStartedAt = Date.now();
99
+ this._sessionCost = 0;
100
+ if (this._elapsedTimer) clearInterval(this._elapsedTimer);
101
+ this._elapsedTimer = setInterval(() => {
102
+ const label = streamingDiv?.querySelector('.streaming-indicator-label');
103
+ if (label) {
104
+ const sec = ((Date.now() - this._streamStartedAt) / 1000) | 0;
105
+ const time = sec < 60 ? sec + 's' : Math.floor(sec / 60) + 'm ' + (sec % 60) + 's';
106
+ label.textContent = this._sessionCost > 0 ? time + ' · $' + this._sessionCost.toFixed(4) : time;
107
+ }
108
+ }, 1000);
109
+
110
+ this._renderedSeqs[data.sessionId] = new Set();
111
+
112
+ this.showStreamingPromptButtons();
113
+
114
+ this.emit('streaming:start', data);
115
+ }
116
+
117
+ });