1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
|
@model Tango.Portal.Chat.Web.ViewModels.HomeViewVM
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
<div class="row align-items-center mb-5">
<div class="col-lg-7 text-center text-lg-start d-flex flex-column mx-auto">
<div>
<h1 style="color:white" class="display-1 fw-bold mb-4 heading">Twine AI</h1>
<p class="lead fs-4 fw-lighter">Twine AI can answer questions about architecture, user guides and live machines telemetry.</p>
</div>
</div>
<div class="col d-none d-lg-flex">
<img height="200" src="assets/img/twine-ai.png" />
</div>
</div>
</div>
<div class="container">
<div class="card">
<div id="chat" class="chat" aria-live="polite" aria-relevant="additions"></div>
<div class="composer">
<div class="row">
<textarea id="input" placeholder="Ask a question… (Enter to send, Shift+Enter for newline)"></textarea>
<button id="sendBtn" type="button">Send</button>
</div>
<div id="err" class="err"></div>
</div>
</div>
</div>
<!-- Markdown renderer -->
<script src="https://cdn.jsdelivr.net/npm/markdown-it@14.1.0/dist/markdown-it.min.js"></script>
<link href="https://cdn.datatables.net/2.3.3/css/dataTables.dataTables.css" rel="stylesheet">
<link href="https://cdn.datatables.net/buttons/3.2.4/css/buttons.dataTables.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script src="https://cdn.datatables.net/2.3.3/js/dataTables.js"></script>
<script src="https://cdn.datatables.net/buttons/3.2.4/js/dataTables.buttons.js"></script>
<script src="https://cdn.datatables.net/buttons/3.2.4/js/buttons.dataTables.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/3.2.4/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/3.2.4/js/buttons.print.min.js"></script>
<script src="https://cdn.plot.ly/plotly-3.1.0.min.js" charset="utf-8"></script>
<script>
function enhanceTable(el){
if (el.dataset.dtInitialized) return;
el.dataset.dtInitialized = '1';
new DataTable(el, {
layout: {
topStart: {
buttons: ['copy', 'csv', 'excel', 'pdf', 'print']
}
},
paging: true,
searching: false,
ordering: true,
info: false,
lengthChange: false,
// vertical scroll in v2:
scrollY: el.getAttribute('data-scroll') || 400,
scrollCollapse: !!el.getAttribute('data-scroll'),
responsive: true
});
}
document.querySelectorAll('table').forEach(enhanceTable);
new MutationObserver(muts=>{
for (const m of muts){
m.addedNodes.forEach(n=>{
if (n.nodeType!==1) return;
if (n.matches?.('table')) enhanceTable(n);
n.querySelectorAll?.('table').forEach(enhanceTable);
});
}
}).observe(document.documentElement, {childList:true, subtree:true});
</script>
<script>
// --- Plotly helper (parses string/object and renders as-is) ---
function renderPlotlyRaw(ploty, targetEl) {
// ploty can be a stringified JSON or an object
const plot =
typeof ploty === 'string' ? JSON.parse(ploty) :
(ploty && typeof ploty === 'object' ? ploty : {});
// Ensure structure for Plotly
plot.data = Array.isArray(plot.data) ? plot.data : [];
plot.layout = plot.layout || {};
// IMPORTANT: Do NOT inject msg.content into the plot title.
// The chart will use exactly what the server returned.
const config = { displayModeBar: true, responsive: true };
Plotly.newPlot(targetEl, plot.data, plot.layout, config);
// keep it responsive
window.addEventListener('resize', () => {
if (targetEl && targetEl.offsetParent !== null) {
Plotly.Plots.resize(targetEl);
}
}, { passive: true });
}
</script>
<script>
(() => {
// ---- Ephemeral session state (lost on refresh) ----
let threadId = null; // shared Assistants thread for this page session
const messages = []; // [{role, content, ts, usedKql?}]
// Elements
const chatEl = document.getElementById('chat');
const inputEl = document.getElementById('input');
const sendBtn = document.getElementById('sendBtn');
const errEl = document.getElementById('err');
// Markdown instance
const md = window.markdownit({ html: false, linkify: true, breaks: true });
function fmtTime(ts){
try { return new Date(ts).toLocaleTimeString([], {hour:'2-digit',minute:'2-digit'}); }
catch { return '' }
}
// Scroll the page (not the chat div) to the bottom
function scrollToBottom(){
window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
}
function enhanceLinks(container) {
container.querySelectorAll('a').forEach(a => {
a.target = '_blank';
a.rel = 'noopener noreferrer';
});
}
function renderMessage(msg){
const isUser = msg.role === 'user';
const wrap = document.createElement('div');
wrap.className = 'msg ' + (isUser ? 'user' : 'assistant');
const avatar = document.createElement('div');
avatar.className = 'avatar ' + (isUser ? 'user' : 'assistant');
avatar.textContent = isUser ? 'U' : 'A';
const body = document.createElement('div');
const bubble = document.createElement('div');
bubble.className = 'bubble';
// main content
const main = document.createElement('div');
if (isUser) {
main.textContent = msg.content;
} else {
main.className = 'md';
main.innerHTML = md.render(msg.content || '');
enhanceLinks(main);
}
bubble.appendChild(main);
// --- ADD: If the assistant returned a Plotly payload, render it below the markdown answer
if (!isUser && msg.ploty && String(msg.ploty).trim().length > 0) {
const chartDiv = document.createElement('div');
chartDiv.className = 'plotly-chart';
chartDiv.style.width = '100%';
chartDiv.style.height = '420px';
bubble.appendChild(chartDiv);
try {
renderPlotlyRaw(msg.ploty, chartDiv); // uses the helper from Step 2
} catch (err) {
const fallback = document.createElement('pre');
fallback.textContent = 'Failed to render chart. Raw ploty:\n' +
(typeof msg.ploty === 'string' ? msg.ploty : JSON.stringify(msg.ploty, null, 2));
bubble.appendChild(fallback);
}
}
// Expandable KQL when present
if (!isUser && msg.usedKql && msg.usedKql.trim().length > 0) {
const details = document.createElement('details');
details.style.marginTop = '.5rem';
const summary = document.createElement('summary');
summary.textContent = 'View KQL';
const pre = document.createElement('pre');
const code = document.createElement('code');
code.textContent = msg.usedKql;
pre.appendChild(code);
details.appendChild(summary);
details.appendChild(pre);
bubble.appendChild(details);
}
const meta = document.createElement('div');
meta.className = 'meta';
meta.textContent = fmtTime(msg.ts || Date.now());
body.appendChild(bubble);
body.appendChild(meta);
wrap.appendChild(avatar);
wrap.appendChild(body);
chatEl.appendChild(wrap);
scrollToBottom();
return wrap;
}
function renderThinking(){
const wrap = document.createElement('div');
wrap.className = 'msg assistant';
const avatar = document.createElement('div');
avatar.className = 'avatar';
avatar.textContent = 'A';
const body = document.createElement('div');
const bubble = document.createElement('div');
bubble.className = 'bubble';
bubble.innerHTML = `<span class="thinking">Thinking <span class="dots"><span></span><span></span><span></span></span></span>`;
const meta = document.createElement('div');
meta.className = 'meta';
meta.textContent = '…';
body.appendChild(bubble);
body.appendChild(meta);
wrap.appendChild(avatar);
wrap.appendChild(body);
chatEl.appendChild(wrap);
scrollToBottom();
return wrap;
}
function setBusy(busy){
sendBtn.disabled = busy;
inputEl.disabled = busy;
if (!busy) inputEl.focus();
}
function showErr(text){
errEl.style.display = text ? 'block' : 'none';
errEl.textContent = text || '';
}
async function sendQuestion() {
const text = (inputEl.value || '').trim();
if (!text) return;
showErr('');
setBusy(true);
// Append user message locally
const userMsg = { role:'user', content:text, ts: Date.now() };
messages.push(userMsg);
renderMessage(userMsg);
// Clear input
inputEl.value = '';
inputEl.style.height = 'auto'
// Show a temporary assistant "thinking" bubble
const thinkingEl = renderThinking();
try {
const res = await fetch('/api/chat/ask', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
question: text,
threadId: threadId,
// include short history to help routing follow-ups
history: messages.slice(-10).map(m => ({ role: m.role, content: m.content, usedKql: m.usedKql }))
})
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err?.message || err?.error || `${res.status} ${res.statusText}`);
}
const payload = await res.json();
// Store/keep the thread id for next turn
if (payload.threadId) threadId = payload.threadId;
// Replace "thinking" bubble with the real assistant answer
thinkingEl.remove();
const assistantMsg = {
role:'assistant',
content: (payload.answer || '').trim() || '(no answer)',
usedKql: (payload.usedKql || ''),
ploty: (payload.ploty || ''),
ts: Date.now()
};
messages.push(assistantMsg);
renderMessage(assistantMsg);
} catch (e) {
thinkingEl.remove();
showErr(e.message || 'Request failed.');
} finally {
setBusy(false);
}
}
// Auto-grow textarea; Shift+Enter = newline, Enter = send
inputEl.addEventListener('input', () => {
inputEl.style.height = 'auto';
inputEl.style.height = Math.min(inputEl.scrollHeight, 140) + 'px';
});
inputEl.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendQuestion();
}
});
sendBtn.addEventListener('click', sendQuestion);
// Optional greeting (visual only)
const hello = {
role:'assistant',
content:"Hi @Model.UserName I'm Twine AI assistant. Ask me anything!",
ts: Date.now()
};
messages.push(hello);
renderMessage(hello);
})();
</script>
|