llama-vscode.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { useEffect, useState } from 'react';
  2. import { MessageExtraContext } from './types';
  3. import { OptimizedTextareaValue } from '../components/ChatScreen';
  4. // Extra context when using llama.cpp WebUI from llama-vscode, inside an iframe
  5. // Ref: https://github.com/ggml-org/llama.cpp/pull/11940
  6. interface SetTextEvData {
  7. text: string;
  8. context: string;
  9. }
  10. /**
  11. * To test it:
  12. * window.postMessage({ command: 'setText', text: 'Spot the syntax error', context: 'def test()\n return 123' }, '*');
  13. */
  14. export const useVSCodeContext = (textarea: OptimizedTextareaValue) => {
  15. const [extraContext, setExtraContext] = useState<MessageExtraContext | null>(
  16. null
  17. );
  18. // Accept setText message from a parent window and set inputMsg and extraContext
  19. useEffect(() => {
  20. const handleMessage = (event: MessageEvent) => {
  21. if (event.data?.command === 'setText') {
  22. const data: SetTextEvData = event.data;
  23. textarea.setValue(data?.text);
  24. if (data?.context && data.context.length > 0) {
  25. setExtraContext({
  26. type: 'context',
  27. content: data.context,
  28. });
  29. }
  30. textarea.focus();
  31. }
  32. };
  33. window.addEventListener('message', handleMessage);
  34. return () => window.removeEventListener('message', handleMessage);
  35. }, [textarea]);
  36. // Add a keydown listener that sends the "escapePressed" message to the parent window
  37. useEffect(() => {
  38. const handleKeyDown = (event: KeyboardEvent) => {
  39. if (event.key === 'Escape') {
  40. window.parent.postMessage({ command: 'escapePressed' }, '*');
  41. }
  42. };
  43. window.addEventListener('keydown', handleKeyDown);
  44. return () => window.removeEventListener('keydown', handleKeyDown);
  45. }, []);
  46. return {
  47. extraContext,
  48. // call once the user message is sent, to clear the extra context
  49. clearExtraContext: () => setExtraContext(null),
  50. };
  51. };