-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathPrompt.tsx
More file actions
733 lines (687 loc) · 22.8 KB
/
Prompt.tsx
File metadata and controls
733 lines (687 loc) · 22.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
import { Map as ImmutableMap } from 'immutable';
import { dump as dumpYAML, load as loadYAML } from 'js-yaml';
import { cloneDeep, each, isMatch, omit, uniqueId } from 'lodash';
import * as React from 'react';
import { useTranslation } from 'react-i18next';
import { useDispatch, useSelector } from 'react-redux';
import {
consoleFetch,
consoleFetchJSON,
K8sResourceKind,
useK8sWatchResource,
} from '@openshift-console/dynamic-plugin-sdk';
import { MessageBar } from '@patternfly/chatbot';
import {
Alert,
AlertActionCloseButton,
DropdownItem,
DropdownList,
Label,
Spinner,
Title,
Tooltip,
} from '@patternfly/react-core';
import { FileCodeIcon, FileUploadIcon, InfoCircleIcon, TaskIcon } from '@patternfly/react-icons';
import { AttachmentTypes, toOLSAttachment } from '../attachments';
import { getApiUrl } from '../config';
import { getFetchErrorMessage } from '../error';
import { getRequestInitWithAuthHeader } from '../hooks/useAuth';
import { useBoolean } from '../hooks/useBoolean';
import { useLocationContext } from '../hooks/useLocationContext';
import { useAutoContextDescription } from '../hooks/useAutoContextDescription';
import {
attachmentDelete,
attachmentsClear,
attachmentSet,
chatHistoryPush,
chatHistoryUpdateByID,
chatHistoryUpdateTool,
setConversationID,
setQuery,
} from '../redux-actions';
import { State } from '../redux-reducers';
import { Attachment } from '../types';
import AttachEventsModal from './AttachEventsModal';
import AttachLogModal from './AttachLogModal';
import AttachmentLabel from './AttachmentLabel';
import AttachmentModal from './AttachmentModal';
import ResourceIcon from './ResourceIcon';
import ToolModal from './ResponseToolModal';
const ALERTS_ENDPOINT = '/api/prometheus/api/v1/rules?type=alert';
const QUERY_ENDPOINT = getApiUrl('/v1/streaming_query');
// Sanity check on the upload file size
const MAX_FILE_SIZE_MB = 1;
const INPUT_ELEMENT_ID = 'ols-plugin__prompt-input';
const SUBMIT_BUTTON_ELEMENT_CLASS = 'pf-chatbot__button--send';
const focusPromptInput = () => {
// We use getElementById instead of a ref because of problems with getting the ref forwarded to
// MessageBar's underlying textarea element
(document.getElementById(INPUT_ELEMENT_ID) as HTMLTextAreaElement).focus();
};
const FilteredYAMLInfo = () => {
const { t } = useTranslation('plugin__lightspeed-console-plugin');
return (
<Tooltip content={t('Kind, Metadata, and Status sections only')}>
<span className="ols-plugin__inline-icon">
<InfoCircleIcon />
</span>
</Tooltip>
);
};
// Managed clusters have an additional info object that lives in a namespace whose name matches the cluster name
const fetchManagedClusterInfo = async (clusterName: string): Promise<K8sResourceKind> => {
const endpoint = `/api/kubernetes/apis/internal.open-cluster-management.io/v1beta1/namespaces/${clusterName}/managedclusterinfos/${clusterName}`;
const response = await consoleFetchJSON(endpoint, 'get', getRequestInitWithAuthHeader());
return response;
};
type PromptProps = {
scrollIntoView: () => void;
};
const Prompt: React.FC<PromptProps> = ({ scrollIntoView }) => {
const { t } = useTranslation('plugin__lightspeed-console-plugin');
const dispatch = useDispatch();
const attachments = useSelector((s: State) => s.plugins?.ols?.get('attachments'));
const chatHistory = useSelector((s: State) => s.plugins?.ols?.get('chatHistory'));
const conversationID: string = useSelector((s: State) => s.plugins?.ols?.get('conversationID'));
const events = useSelector((s: State) => s.plugins?.ols?.get('contextEvents'));
const isEventsLoading = useSelector((s: State) => s.plugins?.ols?.get('isContextEventsLoading'));
const query: string = useSelector((s: State) => s.plugins?.ols?.get('query'));
const [error, setError] = React.useState<string>();
const [isEventsModalOpen, , openEventsModal, closeEventsModal] = useBoolean(false);
const [isLogModalOpen, , openLogModal, closeLogModal] = useBoolean(false);
const [isLoading, , setLoading, setLoaded] = useBoolean(false);
const [isOpen, setIsOpen] = React.useState<boolean>(false);
const [streamController, setStreamController] = React.useState(new AbortController());
const [validated, setValidated] = React.useState<'default' | 'error'>('default');
const fileInputRef = React.useRef<HTMLInputElement>(null);
const [kind, name, namespace] = useLocationContext();
const autoContextDescription = useAutoContextDescription();
const k8sContext = useK8sWatchResource<K8sResourceKind>(
kind && kind !== 'Alert' && name ? { isList: false, kind, name, namespace } : null,
);
const [context] = kind === 'Alert' && name ? [] : k8sContext;
const isStreaming = !!chatHistory.last()?.get('isStreaming');
// Focus the prompt input when the UI is first opened
React.useEffect(() => {
focusPromptInput();
}, []);
const handleFileUpload = React.useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) {
return;
}
if (file.size > MAX_FILE_SIZE_MB * 1024 * 1024) {
setError(
t('Uploaded file is too large. Max size is {{max}} MB.', { max: MAX_FILE_SIZE_MB }),
);
return;
}
setError(undefined);
const reader = new FileReader();
reader.onload = (event) => {
try {
const yaml = event.target?.result as string;
const content = loadYAML(yaml);
if (typeof content !== 'object') {
setError(t('Uploaded file is not valid YAML'));
return;
}
const fileName = content.metadata?.name;
dispatch(
attachmentSet(
AttachmentTypes.YAML,
content.kind || '?',
fileName ? `${fileName} (${file.name})` : file.name,
undefined,
content.metadata?.namespace,
yaml,
),
);
} catch {
setError(t('Uploaded file is not valid YAML'));
}
};
reader.readAsText(file);
},
[dispatch, setError, t],
);
const showEvents =
!!context &&
[
'CronJob',
'DaemonSet',
'Deployment',
'DeploymentConfig',
'HorizontalPodAutoscaler',
'Job',
'kubevirt.io~v1~VirtualMachine',
'kubevirt.io~v1~VirtualMachineInstance',
'Pod',
'PodDisruptionBudget',
'ReplicaSet',
'ReplicationController',
'StatefulSet',
].includes(kind);
const showLogs =
!!context &&
[
'CronJob',
'DaemonSet',
'Deployment',
'DeploymentConfig',
'HorizontalPodAutoscaler',
'Job',
'kubevirt.io~v1~VirtualMachine',
'kubevirt.io~v1~VirtualMachineInstance',
'Pod',
'PodDisruptionBudget',
'ReplicaSet',
'ReplicationController',
'StatefulSet',
].includes(kind);
const isResourceContext = !!context && !!kind && !!name;
const attachMenuItems = React.useMemo(
() => [
<DropdownList key="menu-list">
{isResourceContext && (
<>
<Title headingLevel="h5" key="currently-viewing-title">
{t('Currently viewing')}
</Title>
<div
key="currently-viewing-label"
style={{ marginBottom: 'var(--pf-t--global--spacer--md)' }}
>
<Label
className="ols-plugin__context-label"
textMaxWidth="10rem"
title={t('{{kind}} {{name}} in namespace {{namespace}}', {
kind,
name,
namespace,
})}
>
<ResourceIcon kind={kind} /> {name}
</Label>
</div>
</>
)}
{(isResourceContext || showEvents || showLogs) && (
<Title headingLevel="h5" key="attach-title">
{t('Attach')}
</Title>
)}
{isResourceContext &&
(kind === 'cluster.open-cluster-management.io~v1~ManagedCluster' ? (
<DropdownItem
icon={<TaskIcon />}
id="yaml-cluster"
key="yaml-cluster"
value={AttachmentTypes.YAML}
>
{t('Attach cluster info')} {isLoading && <Spinner size="md" />}
</DropdownItem>
) : (
<>
<DropdownItem
icon={<FileCodeIcon />}
id="yaml-full"
key="yaml-full"
value={AttachmentTypes.YAML}
>
{t('Full YAML file')} {isLoading && <Spinner size="md" />}
</DropdownItem>
<DropdownItem
icon={<FileCodeIcon />}
id="yaml-filtered"
key="yaml-filtered"
value={AttachmentTypes.YAMLFiltered}
>
{t('Filtered YAML')} <FilteredYAMLInfo />
</DropdownItem>
</>
))}
{kind === 'Alert' && (
<DropdownItem
icon={<FileCodeIcon />}
id="alert-yaml"
key="alert-yaml"
value={AttachmentTypes.YAML}
>
{t('Alert')} {isLoading && <Spinner size="md" />}
</DropdownItem>
)}
{showEvents && (
<DropdownItem
icon={<TaskIcon />}
id="events"
isDisabled={!isEventsLoading && events.length === 0}
key="events"
value={AttachmentTypes.Events}
>
{t('Events')}
</DropdownItem>
)}
{showLogs && (
<DropdownItem icon={<TaskIcon />} id="logs" key="logs" value={AttachmentTypes.Log}>
{t('Logs')}
</DropdownItem>
)}
<DropdownItem icon={<FileUploadIcon />} key="upload" value={AttachmentTypes.YAMLUpload}>
{t('Upload from computer')}
</DropdownItem>
</DropdownList>,
],
[
events.length,
isEventsLoading,
isLoading,
isResourceContext,
kind,
name,
namespace,
showEvents,
showLogs,
t,
],
);
const onAttachMenuSelect = React.useCallback(
(_ev: React.MouseEvent, attachmentType: string) => {
setIsOpen(false);
if (attachmentType === AttachmentTypes.Events) {
openEventsModal();
} else if (attachmentType === AttachmentTypes.Log) {
openLogModal();
} else if (attachmentType === AttachmentTypes.YAMLUpload) {
// Trigger file upload
fileInputRef.current?.click();
} else if (kind === 'Alert') {
setLoading();
const labels = Object.fromEntries(new URLSearchParams(location.search));
consoleFetchJSON(ALERTS_ENDPOINT, 'get', getRequestInitWithAuthHeader())
.then((response) => {
let alert;
each(response?.data?.groups, (group) => {
each(group.rules, (rule) => {
alert = rule.alerts?.find((a) => isMatch(labels, a.labels));
if (alert) {
return false;
}
});
if (alert) {
return false;
}
});
if (alert) {
try {
const yaml = dumpYAML(alert, { lineWidth: -1 }).trim();
dispatch(
attachmentSet(AttachmentTypes.YAML, kind, name, undefined, namespace, yaml),
);
} catch (e) {
setError(t('Error converting to YAML: {{e}}', { e }));
}
} else {
setError(t('Failed to find definition YAML for alert'));
}
setLoaded();
})
.catch((err) => {
setError(t('Error fetching alerting rules: {{err}}', { err }));
setLoaded();
});
} else if (
// Only show this attachment option when the object in play is a ManagedCluster
kind === 'cluster.open-cluster-management.io~v1~ManagedCluster' &&
attachmentType === AttachmentTypes.YAML
) {
setLoading();
// First attach the ManagedCluster object
if (context) {
const clusterData = cloneDeep(context);
delete clusterData.metadata.managedFields;
try {
const clusterYaml = dumpYAML(clusterData, { lineWidth: -1 }).trim();
dispatch(
attachmentSet(AttachmentTypes.YAML, kind, name, undefined, namespace, clusterYaml),
);
} catch (e) {
setError(t('Error converting ManagedCluster to YAML: {{e}}', { e }));
setLoaded();
return;
}
}
// Then fetch and attach the ManagedClusterInfo object
fetchManagedClusterInfo(name)
.then((clusterInfo) => {
const data = cloneDeep(clusterInfo);
delete data.metadata.managedFields;
try {
const yaml = dumpYAML(data, { lineWidth: -1 }).trim();
dispatch(
attachmentSet(
AttachmentTypes.YAML,
'ManagedClusterInfo',
name,
undefined,
name,
yaml,
),
);
close();
} catch (e) {
setError(t('Error converting ManagedClusterInfo to YAML: {{e}}', { e }));
}
setLoaded();
})
.catch((err) => {
setError(t('Error fetching cluster info: {{err}}', { err }));
setLoaded();
});
} else if (
context &&
(attachmentType === AttachmentTypes.YAML || attachmentType === AttachmentTypes.YAMLFiltered)
) {
const data = cloneDeep(
attachmentType === AttachmentTypes.YAMLFiltered
? { kind: context.kind, metadata: context.metadata, status: context.status }
: context,
);
// We ignore the managedFields section because it doesn't have much value
delete data.metadata.managedFields;
try {
const yaml = dumpYAML(data, { lineWidth: -1 }).trim();
dispatch(attachmentSet(attachmentType, kind, name, undefined, namespace, yaml));
} catch (e) {
setError(t('Error converting to YAML: {{e}}', { e }));
}
}
},
[
context,
dispatch,
kind,
name,
namespace,
openEventsModal,
openLogModal,
setIsOpen,
setLoaded,
setLoading,
t,
],
);
const onChange = React.useCallback(
(_e, value) => {
if (value.trim().length > 0) {
setValidated('default');
}
dispatch(setQuery(value));
},
[dispatch],
);
const onSubmit = React.useCallback(() => {
if (isStreaming) {
return;
}
if (!query || query.trim().length === 0) {
setValidated('error');
return;
}
dispatch(
chatHistoryPush({
attachments: attachments.map((a) => omit(a, 'originalValue')),
text: query,
who: 'user',
}),
);
const chatEntryID = uniqueId('ChatEntry_');
dispatch(
chatHistoryPush({
id: chatEntryID,
isCancelled: false,
isStreaming: true,
isTruncated: false,
references: [],
text: '',
tools: ImmutableMap(),
who: 'ai',
}),
);
scrollIntoView();
// Prepare attachments including hidden auto-context
const userAttachments = attachments.valueSeq().map(toOLSAttachment);
const allAttachments = autoContextDescription
? [
...userAttachments,
{
// eslint-disable-next-line camelcase
attachment_type: 'error message',
content: autoContextDescription,
// eslint-disable-next-line camelcase
content_type: 'text/plain',
},
]
: userAttachments;
const requestJSON = {
attachments: allAttachments,
// eslint-disable-next-line camelcase
conversation_id: conversationID,
// eslint-disable-next-line camelcase
media_type: 'application/json',
query,
};
const streamResponse = async () => {
const controller = new AbortController();
setStreamController(controller);
const response = await consoleFetch(QUERY_ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestJSON),
signal: controller.signal,
});
if (response.ok === false) {
dispatch(
chatHistoryUpdateByID(chatEntryID, {
error: getFetchErrorMessage({ response }, t),
isStreaming: false,
isTruncated: false,
who: 'ai',
}),
);
return;
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let responseText = '';
// eslint-disable-next-line no-constant-condition
while (true) {
const { value, done } = await reader.read();
if (done) {
break;
}
const text = decoder.decode(value);
text
.split('\n')
.filter((s) => s.startsWith('data: '))
.forEach((s) => {
const line = s.slice(5).trim();
let json;
try {
json = JSON.parse(line);
} catch (parseError) {
// eslint-disable-next-line no-console
console.error(`Failed to parse JSON string "${line}"`, parseError);
}
if (json && json.event && json.data) {
if (json.event === 'start') {
dispatch(setConversationID(json.data.conversation_id));
} else if (json.event === 'token') {
responseText += json.data.token;
dispatch(chatHistoryUpdateByID(chatEntryID, { text: responseText }));
} else if (json.event === 'end') {
dispatch(
chatHistoryUpdateByID(chatEntryID, {
isStreaming: false,
isTruncated: json.data.truncated === true,
references: json.data.referenced_documents,
}),
);
} else if (json.event === 'tool_call') {
const { args, id, name: toolName } = json.data;
dispatch(chatHistoryUpdateTool(chatEntryID, id, { name: toolName, args }));
} else if (json.event === 'tool_result') {
const { content, id, status } = json.data;
dispatch(chatHistoryUpdateTool(chatEntryID, id, { content, status }));
} else if (json.event === 'error') {
dispatch(
chatHistoryUpdateByID(chatEntryID, {
error: getFetchErrorMessage({ json: { detail: json.data } }, t),
isStreaming: false,
}),
);
} else {
// eslint-disable-next-line no-console
console.warn(`Unrecognized event in response stream:`, JSON.stringify(json));
}
}
});
}
};
streamResponse().catch((streamError) => {
if (streamError.name !== 'AbortError') {
dispatch(
chatHistoryUpdateByID(chatEntryID, {
error: getFetchErrorMessage(streamError, t),
isStreaming: false,
isTruncated: false,
who: 'ai',
}),
);
}
scrollIntoView();
});
// Clear prompt input and return focus to it
dispatch(setQuery(''));
dispatch(attachmentsClear());
focusPromptInput();
}, [
attachments,
autoContextDescription,
conversationID,
dispatch,
isStreaming,
query,
scrollIntoView,
t,
]);
const streamingResponseID: string = isStreaming
? (chatHistory.last()?.get('id') as string)
: undefined;
const onStreamCancel = React.useCallback(
(e) => {
e.preventDefault();
if (streamingResponseID) {
streamController.abort();
dispatch(
chatHistoryUpdateByID(streamingResponseID, {
isCancelled: true,
isStreaming: false,
}),
);
}
},
[dispatch, streamController, streamingResponseID],
);
const onKeyPress = React.useCallback((e) => {
// Enter key alone submits the prompt, Shift+Enter inserts a newline
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
(
document.getElementsByClassName(SUBMIT_BUTTON_ELEMENT_CLASS)[0] as HTMLButtonElement
)?.click();
}
}, []);
// Prevent default keyboard submit event so we can handle it with onKeyPress
const onKeyDown = React.useCallback(() => {}, []);
return (
<div>
{/* @ts-expect-error: TS2786 */}
<MessageBar
alwayShowSendButton
attachMenuProps={{
attachMenuItems,
isAttachMenuOpen: isOpen,
onAttachMenuInputChange: () => {},
onAttachMenuSelect,
onAttachMenuToggleClick: () => setIsOpen(!isOpen),
setIsAttachMenuOpen: setIsOpen,
}}
className="ols-plugin__prompt"
handleStopButton={() => {
onStreamCancel({ preventDefault: () => {} } as unknown as React.FormEvent);
}}
hasStopButton={isStreaming}
id={INPUT_ELEMENT_ID}
isSendButtonDisabled={!query || query.trim().length === 0}
onChange={(e) => onChange(e, e.target.value)}
onKeyDown={onKeyDown}
onKeyPress={onKeyPress}
onSendMessage={onSubmit}
placeholder={t('Send a message...')}
validated={validated}
value={query}
/>
<div className="ols-plugin__prompt-attachments">
{attachments.keySeq().map((id: string) => {
const attachment: Attachment = attachments.get(id);
return (
<AttachmentLabel
attachment={attachment}
isEditable
key={id}
onClose={() => dispatch(attachmentDelete(id))}
/>
);
})}
</div>
<AttachmentModal />
<ToolModal />
<input
accept=".yaml,.yml"
onChange={handleFileUpload}
ref={fileInputRef}
style={{ display: 'none' }}
type="file"
/>
{showEvents && context && context.metadata?.uid && (
<AttachEventsModal
isOpen={isEventsModalOpen}
kind={context.kind}
name={name}
namespace={namespace}
onClose={closeEventsModal}
uid={context.metadata?.uid}
/>
)}
{showLogs && (
<AttachLogModal isOpen={isLogModalOpen} onClose={closeLogModal} resource={context} />
)}
{error && (
<Alert
actionClose={<AlertActionCloseButton onClose={() => setError(undefined)} />}
className="ols-plugin__alert"
isInline
title={t('Failed to attach')}
variant="danger"
>
{error}
</Alert>
)}
</div>
);
};
export default Prompt;