@rimori/react-client 0.1.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 (139) hide show
  1. package/.prettierignore +35 -0
  2. package/LICENSE +201 -0
  3. package/README copy.md +1216 -0
  4. package/README.md +1 -0
  5. package/dist/components/MarkdownEditor.d.ts +8 -0
  6. package/dist/components/MarkdownEditor.js +48 -0
  7. package/dist/components/Spinner.d.ts +8 -0
  8. package/dist/components/Spinner.js +4 -0
  9. package/dist/components/ai/Assistant.d.ts +9 -0
  10. package/dist/components/ai/Assistant.js +58 -0
  11. package/dist/components/ai/Avatar.d.ts +14 -0
  12. package/dist/components/ai/Avatar.js +59 -0
  13. package/dist/components/ai/EmbeddedAssistent/AudioInputField.d.ts +7 -0
  14. package/dist/components/ai/EmbeddedAssistent/AudioInputField.js +37 -0
  15. package/dist/components/ai/EmbeddedAssistent/CircleAudioAvatar.d.ts +8 -0
  16. package/dist/components/ai/EmbeddedAssistent/CircleAudioAvatar.js +79 -0
  17. package/dist/components/ai/EmbeddedAssistent/TTS/MessageSender.d.ts +19 -0
  18. package/dist/components/ai/EmbeddedAssistent/TTS/MessageSender.js +91 -0
  19. package/dist/components/ai/EmbeddedAssistent/TTS/Player.d.ts +27 -0
  20. package/dist/components/ai/EmbeddedAssistent/TTS/Player.js +185 -0
  21. package/dist/components/ai/EmbeddedAssistent/VoiceRecoder.d.ts +11 -0
  22. package/dist/components/ai/EmbeddedAssistent/VoiceRecoder.js +95 -0
  23. package/dist/components/ai/utils.d.ts +6 -0
  24. package/dist/components/ai/utils.js +13 -0
  25. package/dist/components/audio/Playbutton.d.ts +15 -0
  26. package/dist/components/audio/Playbutton.js +80 -0
  27. package/dist/components/components/ContextMenu.d.ts +10 -0
  28. package/dist/components/components/ContextMenu.js +135 -0
  29. package/dist/hooks/I18nHooks.d.ts +11 -0
  30. package/dist/hooks/I18nHooks.js +25 -0
  31. package/dist/hooks/UseChatHook.d.ts +10 -0
  32. package/dist/hooks/UseChatHook.js +29 -0
  33. package/dist/providers/PluginProvider.d.ts +11 -0
  34. package/dist/providers/PluginProvider.js +142 -0
  35. package/dist/react-client/plugin/ThemeSetter.d.ts +2 -0
  36. package/dist/react-client/plugin/ThemeSetter.js +19 -0
  37. package/dist/react-client/src/components/ContextMenu.d.ts +10 -0
  38. package/dist/react-client/src/components/ContextMenu.js +135 -0
  39. package/dist/react-client/src/components/MarkdownEditor.d.ts +8 -0
  40. package/dist/react-client/src/components/MarkdownEditor.js +48 -0
  41. package/dist/react-client/src/components/Spinner.d.ts +8 -0
  42. package/dist/react-client/src/components/Spinner.js +4 -0
  43. package/dist/react-client/src/components/ai/Assistant.d.ts +9 -0
  44. package/dist/react-client/src/components/ai/Assistant.js +58 -0
  45. package/dist/react-client/src/components/ai/Avatar.d.ts +14 -0
  46. package/dist/react-client/src/components/ai/Avatar.js +59 -0
  47. package/dist/react-client/src/components/ai/EmbeddedAssistent/AudioInputField.d.ts +7 -0
  48. package/dist/react-client/src/components/ai/EmbeddedAssistent/AudioInputField.js +37 -0
  49. package/dist/react-client/src/components/ai/EmbeddedAssistent/CircleAudioAvatar.d.ts +8 -0
  50. package/dist/react-client/src/components/ai/EmbeddedAssistent/CircleAudioAvatar.js +79 -0
  51. package/dist/react-client/src/components/ai/EmbeddedAssistent/TTS/MessageSender.d.ts +19 -0
  52. package/dist/react-client/src/components/ai/EmbeddedAssistent/TTS/MessageSender.js +91 -0
  53. package/dist/react-client/src/components/ai/EmbeddedAssistent/TTS/Player.d.ts +27 -0
  54. package/dist/react-client/src/components/ai/EmbeddedAssistent/TTS/Player.js +185 -0
  55. package/dist/react-client/src/components/ai/EmbeddedAssistent/VoiceRecoder.d.ts +11 -0
  56. package/dist/react-client/src/components/ai/EmbeddedAssistent/VoiceRecoder.js +95 -0
  57. package/dist/react-client/src/components/ai/utils.d.ts +6 -0
  58. package/dist/react-client/src/components/ai/utils.js +13 -0
  59. package/dist/react-client/src/components/audio/Playbutton.d.ts +15 -0
  60. package/dist/react-client/src/components/audio/Playbutton.js +82 -0
  61. package/dist/react-client/src/components/components/ContextMenu.d.ts +10 -0
  62. package/dist/react-client/src/components/components/ContextMenu.js +135 -0
  63. package/dist/react-client/src/hooks/I18nHooks.d.ts +11 -0
  64. package/dist/react-client/src/hooks/I18nHooks.js +25 -0
  65. package/dist/react-client/src/hooks/UseChatHook.d.ts +10 -0
  66. package/dist/react-client/src/hooks/UseChatHook.js +29 -0
  67. package/dist/react-client/src/plugin/ThemeSetter.d.ts +2 -0
  68. package/dist/react-client/src/plugin/ThemeSetter.js +19 -0
  69. package/dist/react-client/src/providers/PluginProvider.d.ts +12 -0
  70. package/dist/react-client/src/providers/PluginProvider.js +142 -0
  71. package/dist/react-client/src/utils/FullscreenUtils.d.ts +2 -0
  72. package/dist/react-client/src/utils/FullscreenUtils.js +23 -0
  73. package/dist/react-client/src/utils/PluginUtils.d.ts +2 -0
  74. package/dist/react-client/src/utils/PluginUtils.js +23 -0
  75. package/dist/rimori-client/src/cli/types/DatabaseTypes.d.ts +103 -0
  76. package/dist/rimori-client/src/cli/types/DatabaseTypes.js +2 -0
  77. package/dist/rimori-client/src/controller/AIController.d.ts +15 -0
  78. package/dist/rimori-client/src/controller/AIController.js +255 -0
  79. package/dist/rimori-client/src/controller/AccomplishmentController.d.ts +38 -0
  80. package/dist/rimori-client/src/controller/AccomplishmentController.js +112 -0
  81. package/dist/rimori-client/src/controller/AudioController.d.ts +37 -0
  82. package/dist/rimori-client/src/controller/AudioController.js +68 -0
  83. package/dist/rimori-client/src/controller/ExerciseController.d.ts +54 -0
  84. package/dist/rimori-client/src/controller/ExerciseController.js +74 -0
  85. package/dist/rimori-client/src/controller/ObjectController.d.ts +42 -0
  86. package/dist/rimori-client/src/controller/ObjectController.js +76 -0
  87. package/dist/rimori-client/src/controller/SettingsController.d.ts +79 -0
  88. package/dist/rimori-client/src/controller/SettingsController.js +118 -0
  89. package/dist/rimori-client/src/controller/SharedContentController.d.ts +106 -0
  90. package/dist/rimori-client/src/controller/SharedContentController.js +285 -0
  91. package/dist/rimori-client/src/controller/TranslationController.d.ts +38 -0
  92. package/dist/rimori-client/src/controller/TranslationController.js +106 -0
  93. package/dist/rimori-client/src/controller/VoiceController.d.ts +9 -0
  94. package/dist/rimori-client/src/controller/VoiceController.js +37 -0
  95. package/dist/rimori-client/src/fromRimori/EventBus.d.ts +101 -0
  96. package/dist/rimori-client/src/fromRimori/EventBus.js +263 -0
  97. package/dist/rimori-client/src/fromRimori/PluginTypes.d.ts +174 -0
  98. package/dist/rimori-client/src/fromRimori/PluginTypes.js +1 -0
  99. package/dist/rimori-client/src/index.d.ts +11 -0
  100. package/dist/rimori-client/src/index.js +10 -0
  101. package/dist/rimori-client/src/plugin/CommunicationHandler.d.ts +48 -0
  102. package/dist/rimori-client/src/plugin/CommunicationHandler.js +234 -0
  103. package/dist/rimori-client/src/plugin/Logger.d.ts +73 -0
  104. package/dist/rimori-client/src/plugin/Logger.js +308 -0
  105. package/dist/rimori-client/src/plugin/RimoriClient.d.ts +258 -0
  106. package/dist/rimori-client/src/plugin/RimoriClient.js +375 -0
  107. package/dist/rimori-client/src/plugin/StandaloneClient.d.ts +17 -0
  108. package/dist/rimori-client/src/plugin/StandaloneClient.js +115 -0
  109. package/dist/rimori-client/src/utils/difficultyConverter.d.ts +4 -0
  110. package/dist/rimori-client/src/utils/difficultyConverter.js +10 -0
  111. package/dist/rimori-client/src/utils/endpoint.d.ts +2 -0
  112. package/dist/rimori-client/src/utils/endpoint.js +2 -0
  113. package/dist/style.css +110 -0
  114. package/dist/style.css.map +1 -0
  115. package/dist/utils/PluginUtils.d.ts +2 -0
  116. package/dist/utils/PluginUtils.js +23 -0
  117. package/eslint.config.js +53 -0
  118. package/index.ts +6 -0
  119. package/package.json +47 -0
  120. package/prettier.config.js +8 -0
  121. package/src/components/ContextMenu.tsx +177 -0
  122. package/src/components/MarkdownEditor.tsx +144 -0
  123. package/src/components/Spinner.tsx +29 -0
  124. package/src/components/ai/Assistant.tsx +96 -0
  125. package/src/components/ai/Avatar.tsx +99 -0
  126. package/src/components/ai/EmbeddedAssistent/AudioInputField.tsx +73 -0
  127. package/src/components/ai/EmbeddedAssistent/CircleAudioAvatar.tsx +107 -0
  128. package/src/components/ai/EmbeddedAssistent/TTS/MessageSender.ts +96 -0
  129. package/src/components/ai/EmbeddedAssistent/TTS/Player.ts +197 -0
  130. package/src/components/ai/EmbeddedAssistent/VoiceRecoder.tsx +129 -0
  131. package/src/components/ai/utils.ts +21 -0
  132. package/src/components/audio/Playbutton.tsx +126 -0
  133. package/src/hooks/I18nHooks.ts +33 -0
  134. package/src/hooks/UseChatHook.ts +38 -0
  135. package/src/plugin/ThemeSetter.ts +23 -0
  136. package/src/providers/PluginProvider.tsx +197 -0
  137. package/src/style.scss +136 -0
  138. package/src/utils/FullscreenUtils.ts +22 -0
  139. package/tsconfig.json +23 -0
@@ -0,0 +1,144 @@
1
+ import { Markdown } from 'tiptap-markdown';
2
+ import StarterKit from '@tiptap/starter-kit';
3
+ import { PiCodeBlock } from 'react-icons/pi';
4
+ import { TbBlockquote } from 'react-icons/tb';
5
+ import { GoListOrdered } from 'react-icons/go';
6
+ import { AiOutlineUnorderedList } from 'react-icons/ai';
7
+ import { EditorProvider, useCurrentEditor } from '@tiptap/react';
8
+ import { LuHeading1, LuHeading2, LuHeading3 } from 'react-icons/lu';
9
+ import { FaBold, FaCode, FaItalic, FaParagraph, FaStrikethrough } from 'react-icons/fa';
10
+
11
+ // This inplementation is rooted in the Tiptap editor basic example https://codesandbox.io/p/devbox/editor-9x9dkd
12
+
13
+ interface EditorButtonProps {
14
+ action: string;
15
+ isActive?: boolean;
16
+ label: string | React.ReactNode;
17
+ disabled?: boolean;
18
+ }
19
+
20
+ const EditorButton = ({ action, isActive, label, disabled }: EditorButtonProps) => {
21
+ const { editor } = useCurrentEditor() as any;
22
+
23
+ if (!editor) {
24
+ return null;
25
+ }
26
+
27
+ if (action.includes('heading')) {
28
+ const level = parseInt(action[action.length - 1]);
29
+ return (
30
+ <button
31
+ onClick={() => editor.chain().focus().toggleHeading({ level: level }).run()}
32
+ className={`pl-2 ${isActive ? 'is-active' : ''}`}
33
+ >
34
+ {label}
35
+ </button>
36
+ );
37
+ }
38
+
39
+ return (
40
+ <button
41
+ onClick={() => editor.chain().focus()[action]().run()}
42
+ disabled={disabled ? !editor.can().chain().focus()[action]().run() : false}
43
+ className={`pl-2 ${isActive ? 'is-active' : ''}`}
44
+ >
45
+ {label}
46
+ </button>
47
+ );
48
+ };
49
+
50
+ const MenuBar = () => {
51
+ const { editor } = useCurrentEditor();
52
+
53
+ if (!editor) {
54
+ return null;
55
+ }
56
+
57
+ return (
58
+ <div className="bg-gray-400 dark:bg-gray-800 dark:text-white text-lg flex flex-row flex-wrap items-center p-1">
59
+ <EditorButton action="toggleBold" isActive={editor.isActive('bold')} label={<FaBold />} disabled />
60
+ <EditorButton action="toggleItalic" isActive={editor.isActive('italic')} label={<FaItalic />} disabled />
61
+ <EditorButton action="toggleStrike" isActive={editor.isActive('strike')} label={<FaStrikethrough />} disabled />
62
+ <EditorButton action="toggleCode" isActive={editor.isActive('code')} label={<FaCode />} disabled />
63
+ <EditorButton action="setParagraph" isActive={editor.isActive('paragraph')} label={<FaParagraph />} />
64
+ <EditorButton
65
+ action="setHeading1"
66
+ isActive={editor.isActive('heading', { level: 1 })}
67
+ label={<LuHeading1 size={'24px'} />}
68
+ />
69
+ <EditorButton
70
+ action="setHeading2"
71
+ isActive={editor.isActive('heading', { level: 2 })}
72
+ label={<LuHeading2 size={'24px'} />}
73
+ />
74
+ <EditorButton
75
+ action="setHeading3"
76
+ isActive={editor.isActive('heading', { level: 3 })}
77
+ label={<LuHeading3 size={'24px'} />}
78
+ />
79
+ <EditorButton
80
+ action="toggleBulletList"
81
+ isActive={editor.isActive('bulletList')}
82
+ label={<AiOutlineUnorderedList size={'24px'} />}
83
+ />
84
+ <EditorButton
85
+ action="toggleOrderedList"
86
+ isActive={editor.isActive('orderedList')}
87
+ label={<GoListOrdered size={'24px'} />}
88
+ />
89
+ <EditorButton
90
+ action="toggleCodeBlock"
91
+ isActive={editor.isActive('codeBlock')}
92
+ label={<PiCodeBlock size={'24px'} />}
93
+ />
94
+ <EditorButton
95
+ action="toggleBlockquote"
96
+ isActive={editor.isActive('blockquote')}
97
+ label={<TbBlockquote size={'24px'} />}
98
+ />
99
+ </div>
100
+ );
101
+ };
102
+
103
+ const extensions = [
104
+ StarterKit.configure({
105
+ bulletList: {
106
+ HTMLAttributes: {
107
+ class: 'list-disc list-inside dark:text-white p-1 mt-1 [&_li]:mb-1 [&_p]:inline m-0',
108
+ },
109
+ },
110
+ orderedList: {
111
+ HTMLAttributes: {
112
+ className: 'list-decimal list-inside dark:text-white p-1 mt-1 [&_li]:mb-1 [&_p]:inline m-0',
113
+ },
114
+ },
115
+ }),
116
+ Markdown,
117
+ ];
118
+
119
+ interface Props {
120
+ content?: string;
121
+ editable: boolean;
122
+ className?: string;
123
+ onUpdate?: (content: string) => void;
124
+ }
125
+
126
+ export const MarkdownEditor = (props: Props) => {
127
+ return (
128
+ <div
129
+ className={'text-md border border-gray-800 overflow-hidden ' + props.className}
130
+ style={{ borderWidth: props.editable ? 1 : 0 }}
131
+ >
132
+ <EditorProvider
133
+ key={(props.editable ? 'editable' : 'readonly') + props.content}
134
+ slotBefore={props.editable ? <MenuBar /> : null}
135
+ extensions={extensions}
136
+ content={props.content}
137
+ editable={props.editable}
138
+ onUpdate={(e) => {
139
+ props.onUpdate && props.onUpdate(e.editor.storage.markdown.getMarkdown());
140
+ }}
141
+ ></EditorProvider>
142
+ </div>
143
+ );
144
+ };
@@ -0,0 +1,29 @@
1
+ import React from 'react';
2
+
3
+ interface SpinnerProps {
4
+ text?: string;
5
+ size?: string;
6
+ className?: string;
7
+ }
8
+
9
+ export const Spinner: React.FC<SpinnerProps> = ({ text, className, size = '30px' }) => {
10
+ return (
11
+ <div className={'flex items-center space-x-2 ' + className}>
12
+ <svg
13
+ style={{ width: size, height: size }}
14
+ className="animate-spin -ml-1 mr-3 h-5 w-5 text-white"
15
+ xmlns="http://www.w3.org/2000/svg"
16
+ fill="none"
17
+ viewBox="0 0 24 24"
18
+ >
19
+ <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
20
+ <path
21
+ className="opacity-75"
22
+ fill="currentColor"
23
+ d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
24
+ ></path>
25
+ </svg>
26
+ {text && <span className="">{text}</span>}
27
+ </div>
28
+ );
29
+ };
@@ -0,0 +1,96 @@
1
+ import React, { useEffect, useMemo } from 'react';
2
+ import { CircleAudioAvatar } from './EmbeddedAssistent/CircleAudioAvatar';
3
+ import { AudioInputField } from './EmbeddedAssistent/AudioInputField';
4
+ import { MessageSender } from './EmbeddedAssistent/TTS/MessageSender';
5
+ import Markdown from 'react-markdown';
6
+ import { useChat } from '../../hooks/UseChatHook';
7
+ import { useRimori } from '../../providers/PluginProvider';
8
+ import { FirstMessages, getFirstMessages } from './utils';
9
+
10
+ interface Props {
11
+ voiceId: any;
12
+ avatarImageUrl: string;
13
+ onComplete: (result: any) => void;
14
+ autoStartConversation?: FirstMessages;
15
+ }
16
+
17
+ export function AssistantChat({ avatarImageUrl, voiceId, onComplete, autoStartConversation }: Props) {
18
+ const [oralCommunication, setOralCommunication] = React.useState(true);
19
+ const { ai: llm, event } = useRimori();
20
+ const sender = useMemo(() => new MessageSender(llm.getVoice, voiceId), []);
21
+ const { messages, append, isLoading, setMessages } = useChat();
22
+
23
+ const lastAssistantMessage = [...messages].filter((m) => m.role === 'assistant').pop()?.content;
24
+
25
+ useEffect(() => {
26
+ sender.setOnLoudnessChange((value: number) => event.emit('self.avatar.triggerLoudness', { loudness: value }));
27
+
28
+ if (!autoStartConversation) {
29
+ return;
30
+ }
31
+
32
+ setMessages(getFirstMessages(autoStartConversation));
33
+ // append([{ role: 'user', content: autoStartConversation.userMessage }]);
34
+
35
+ if (autoStartConversation.assistantMessage) {
36
+ // console.log("autostartmessages", { autoStartConversation, isLoading });
37
+ sender.handleNewText(autoStartConversation.assistantMessage, isLoading);
38
+ }
39
+ }, []);
40
+
41
+ useEffect(() => {
42
+ let message = lastAssistantMessage;
43
+ if (message !== messages[messages.length - 1]?.content) {
44
+ message = undefined;
45
+ }
46
+ sender.handleNewText(message, isLoading);
47
+ }, [messages, isLoading]);
48
+
49
+ const lastMessage = messages[messages.length - 1];
50
+
51
+ useEffect(() => {
52
+ console.log('lastMessage', lastMessage);
53
+ const toolInvocations = lastMessage?.toolCalls;
54
+ if (toolInvocations && toolInvocations.length > 0) {
55
+ console.log('toolInvocations', toolInvocations);
56
+ onComplete(toolInvocations[0].args);
57
+ }
58
+ }, [lastMessage]);
59
+
60
+ if (lastMessage?.toolCalls && lastMessage.toolCalls.length > 0) {
61
+ console.log('lastMessage test2', lastMessage);
62
+ const args = lastMessage.toolCalls[0].args;
63
+
64
+ const success = args.explanationUnderstood === 'TRUE' || args.studentKnowsTopic === 'TRUE';
65
+
66
+ return (
67
+ <div className="px-5 pt-5 overflow-y-auto text-center" style={{ height: '478px' }}>
68
+ <h1 className="text-center mt-5 mb-5">{success ? 'Great job!' : 'You failed'}</h1>
69
+ <p>{args.improvementHints}</p>
70
+ </div>
71
+ );
72
+ }
73
+
74
+ return (
75
+ <div>
76
+ {oralCommunication && <CircleAudioAvatar imageUrl={avatarImageUrl} className="mx-auto my-10" />}
77
+ <div className="w-full">
78
+ {lastAssistantMessage && (
79
+ <div className="px-5 pt-5 overflow-y-auto remirror-theme" style={{ height: '4k78px' }}>
80
+ <Markdown>{lastAssistantMessage}</Markdown>
81
+ </div>
82
+ )}
83
+ </div>
84
+ <AudioInputField
85
+ blockSubmission={isLoading}
86
+ onSubmit={(message) => {
87
+ append([{ role: 'user', content: message, id: messages.length.toString() }]);
88
+ }}
89
+ onAudioControl={(voice) => {
90
+ setOralCommunication(voice);
91
+ sender.setVolume(voice ? 1 : 0);
92
+ }}
93
+ />
94
+ </div>
95
+ );
96
+ }
@@ -0,0 +1,99 @@
1
+ import { useEffect, useMemo, useState } from 'react';
2
+ import { VoiceRecorder } from './EmbeddedAssistent/VoiceRecoder';
3
+ import { MessageSender } from './EmbeddedAssistent/TTS/MessageSender';
4
+ import { CircleAudioAvatar } from './EmbeddedAssistent/CircleAudioAvatar';
5
+ import { Tool } from '@rimori/client';
6
+ import { useChat } from '../../hooks/UseChatHook';
7
+ import { useRimori } from '../../providers/PluginProvider';
8
+ import { getFirstMessages } from './utils';
9
+ import { FirstMessages } from './utils';
10
+
11
+ interface Props {
12
+ voiceId: string;
13
+ agentTools: Tool[];
14
+ avatarImageUrl: string;
15
+ circleSize?: string;
16
+ isDarkTheme?: boolean;
17
+ children?: React.ReactNode;
18
+ autoStartConversation?: FirstMessages;
19
+ className?: string;
20
+ }
21
+
22
+ export function Avatar({
23
+ avatarImageUrl,
24
+ voiceId,
25
+ agentTools,
26
+ autoStartConversation,
27
+ children,
28
+ isDarkTheme = false,
29
+ circleSize = '300px',
30
+ className,
31
+ }: Props) {
32
+ const { ai, event } = useRimori();
33
+ const [agentReplying, setAgentReplying] = useState(false);
34
+ const [isProcessingMessage, setIsProcessingMessage] = useState(false);
35
+ const sender = useMemo(() => new MessageSender(ai.getVoice, voiceId), [voiceId]);
36
+ const { messages, append, isLoading, lastMessage, setMessages } = useChat(agentTools);
37
+
38
+ useEffect(() => {
39
+ console.log('messages', messages);
40
+ }, [messages]);
41
+
42
+ useEffect(() => {
43
+ if (!isLoading) setIsProcessingMessage(false);
44
+ }, [isLoading]);
45
+
46
+ useEffect(() => {
47
+ if (!voiceId) return; //at the beginning when being mounted the voiceId is undefined
48
+ sender.setOnLoudnessChange((value) => event.emit('self.avatar.triggerLoudness', { loudness: value }));
49
+ sender.setOnEndOfSpeech(() => setAgentReplying(false));
50
+
51
+ if (!autoStartConversation) return;
52
+
53
+ setMessages(getFirstMessages(autoStartConversation));
54
+ // append([{ role: 'user', content: autoStartConversation.userMessage }]);
55
+
56
+ if (autoStartConversation.assistantMessage) {
57
+ // console.log("autostartmessages", { autoStartConversation, isLoading });
58
+ sender.handleNewText(autoStartConversation.assistantMessage, isLoading);
59
+ } else if (autoStartConversation.userMessage) {
60
+ append([{ role: 'user', content: autoStartConversation.userMessage, id: messages.length.toString() }]);
61
+ }
62
+ }, [autoStartConversation, voiceId]);
63
+
64
+ useEffect(() => {
65
+ if (lastMessage?.role === 'assistant') {
66
+ sender.handleNewText(lastMessage.content, isLoading);
67
+ if (lastMessage.toolCalls) {
68
+ // console.log("unlocking mic", lastMessage)
69
+ setAgentReplying(false);
70
+ setIsProcessingMessage(false);
71
+ }
72
+ }
73
+ }, [lastMessage, isLoading]);
74
+
75
+ return (
76
+ <div className={`md:pb-8 ${className || ''}`}>
77
+ <CircleAudioAvatar width={circleSize} className="mx-auto" imageUrl={avatarImageUrl} isDarkTheme={isDarkTheme} />
78
+ {children}
79
+ <VoiceRecorder
80
+ iconSize="30"
81
+ className="w-16 h-16 shadow-lg rounded-full bg-gray-400 dark:bg-gray-800"
82
+ disabled={agentReplying}
83
+ loading={isProcessingMessage}
84
+ enablePushToTalk={true}
85
+ onVoiceRecorded={(message) => {
86
+ setAgentReplying(true);
87
+ append([
88
+ {
89
+ role: 'user',
90
+ content: 'Message(' + Math.floor((messages.length + 1) / 2) + '): ' + message,
91
+ id: messages.length.toString(),
92
+ },
93
+ ]);
94
+ }}
95
+ onRecordingStatusChange={(running) => !running && setIsProcessingMessage(true)}
96
+ />
97
+ </div>
98
+ );
99
+ }
@@ -0,0 +1,73 @@
1
+ import React, { useState } from 'react';
2
+ import { VoiceRecorder } from './VoiceRecoder';
3
+ import { BiSolidRightArrow } from 'react-icons/bi';
4
+ import { HiMiniSpeakerXMark, HiMiniSpeakerWave } from 'react-icons/hi2';
5
+
6
+ interface AudioInputFieldProps {
7
+ onSubmit: (text: string) => void;
8
+ onAudioControl?: (voice: boolean) => void;
9
+ blockSubmission?: boolean;
10
+ }
11
+
12
+ export function AudioInputField({ onSubmit, onAudioControl, blockSubmission = false }: AudioInputFieldProps) {
13
+ const [text, setText] = useState('');
14
+ const [audioEnabled, setAudioEnabled] = useState(true);
15
+
16
+ const handleSubmit = (manualText?: string) => {
17
+ if (blockSubmission) return;
18
+ const sendableText = manualText || text;
19
+ if (sendableText.trim()) {
20
+ onSubmit(sendableText);
21
+ setTimeout(() => {
22
+ setText('');
23
+ }, 100);
24
+ }
25
+ };
26
+
27
+ const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
28
+ if (blockSubmission) return;
29
+ if (e.key === 'Enter' && e.ctrlKey) {
30
+ setText(text + '\n');
31
+ } else if (e.key === 'Enter') {
32
+ handleSubmit();
33
+ }
34
+ };
35
+
36
+ return (
37
+ <div className="flex items-center bg-gray-600 pt-2 pb-2 p-2">
38
+ {onAudioControl && (
39
+ <button
40
+ onClick={() => {
41
+ onAudioControl(!audioEnabled);
42
+ setAudioEnabled(!audioEnabled);
43
+ }}
44
+ className="cursor-default"
45
+ >
46
+ {audioEnabled ? (
47
+ <HiMiniSpeakerWave className="w-9 h-9 cursor-pointer" />
48
+ ) : (
49
+ <HiMiniSpeakerXMark className="w-9 h-9 cursor-pointer" />
50
+ )}
51
+ </button>
52
+ )}
53
+ <VoiceRecorder
54
+ onRecordingStatusChange={() => {}}
55
+ onVoiceRecorded={(m: string) => {
56
+ console.log('onVoiceRecorded', m);
57
+ handleSubmit(m);
58
+ }}
59
+ />
60
+ <textarea
61
+ value={text}
62
+ onChange={(e) => setText(e.target.value)}
63
+ onKeyDown={handleKeyDown}
64
+ className="flex-1 border-none rounded-lg p-2 text-gray-800 focus::outline-none"
65
+ placeholder="Type a message..."
66
+ disabled={blockSubmission}
67
+ />
68
+ <button onClick={() => handleSubmit()} className="cursor-default" disabled={blockSubmission}>
69
+ <BiSolidRightArrow className="w-9 h-10 cursor-pointer" />
70
+ </button>
71
+ </div>
72
+ );
73
+ }
@@ -0,0 +1,107 @@
1
+ import { useEffect, useRef } from 'react';
2
+ import { EventBus, EventBusMessage } from '@rimori/client';
3
+
4
+ interface CircleAudioAvatarProps {
5
+ width?: string;
6
+ imageUrl: string;
7
+ className?: string;
8
+ isDarkTheme?: boolean;
9
+ }
10
+
11
+ export function CircleAudioAvatar({
12
+ imageUrl,
13
+ className,
14
+ isDarkTheme = false,
15
+ width = '150px',
16
+ }: CircleAudioAvatarProps) {
17
+ const canvasRef = useRef<HTMLCanvasElement>(null);
18
+ const currentLoudnessRef = useRef(0);
19
+ const targetLoudnessRef = useRef(0);
20
+ const animationFrameRef = useRef<number | null>(null);
21
+
22
+ useEffect(() => {
23
+ const canvas = canvasRef.current;
24
+ if (canvas) {
25
+ const ctx = canvas.getContext('2d');
26
+ if (ctx) {
27
+ const image = new Image();
28
+ image.src = imageUrl;
29
+ let isMounted = true;
30
+
31
+ image.onload = () => {
32
+ if (!isMounted) return;
33
+ draw(ctx, canvas, image, 0);
34
+ const animate = () => {
35
+ const decayRate = 0.06;
36
+ if (currentLoudnessRef.current > targetLoudnessRef.current) {
37
+ currentLoudnessRef.current = Math.max(
38
+ targetLoudnessRef.current,
39
+ currentLoudnessRef.current - decayRate * currentLoudnessRef.current,
40
+ );
41
+ } else {
42
+ currentLoudnessRef.current = targetLoudnessRef.current;
43
+ }
44
+ draw(ctx, canvas, image, currentLoudnessRef.current);
45
+ animationFrameRef.current = requestAnimationFrame(animate);
46
+ };
47
+ animationFrameRef.current = requestAnimationFrame(animate);
48
+ };
49
+
50
+ const handleLoudness = ({ data }: EventBusMessage) => {
51
+ const newLoudness = data.loudness;
52
+ if (newLoudness > currentLoudnessRef.current) {
53
+ currentLoudnessRef.current = newLoudness;
54
+ }
55
+ targetLoudnessRef.current = newLoudness;
56
+ };
57
+
58
+ const listener = EventBus.on('self.avatar.triggerLoudness', handleLoudness);
59
+
60
+ return () => {
61
+ isMounted = false;
62
+ listener.off();
63
+ if (animationFrameRef.current) {
64
+ cancelAnimationFrame(animationFrameRef.current);
65
+ }
66
+ };
67
+ }
68
+ }
69
+ }, [imageUrl]);
70
+
71
+ const draw = (
72
+ ctx: CanvasRenderingContext2D,
73
+ canvas: HTMLCanvasElement,
74
+ image: HTMLImageElement,
75
+ loudness: number,
76
+ ) => {
77
+ if (canvas && ctx) {
78
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
79
+
80
+ const radius = Math.min(canvas.width, canvas.height) / 3;
81
+ const centerX = canvas.width / 2;
82
+ const centerY = canvas.height / 2;
83
+ const pulseRadius = radius + loudness / 2.5;
84
+ ctx.beginPath();
85
+ ctx.arc(centerX, centerY, pulseRadius, 0, Math.PI * 2, true);
86
+ ctx.strokeStyle = isDarkTheme ? 'rgba(255, 255, 255, 0.5)' : 'rgba(0, 0, 0, 0.5)';
87
+ ctx.lineWidth = 5;
88
+ ctx.stroke();
89
+
90
+ ctx.save();
91
+ ctx.beginPath();
92
+ ctx.arc(centerX, centerY, radius, 0, Math.PI * 2, true);
93
+ ctx.closePath();
94
+ ctx.clip();
95
+ ctx.drawImage(image, centerX - radius, centerY - radius, radius * 2, radius * 2);
96
+ ctx.restore();
97
+
98
+ ctx.beginPath();
99
+ ctx.arc(centerX, centerY, radius, 0, Math.PI * 2, true);
100
+ ctx.strokeStyle = isDarkTheme ? 'rgba(255, 255, 255, 0.9)' : 'rgba(0, 0, 0, 0.9)';
101
+ ctx.lineWidth = 5;
102
+ ctx.stroke();
103
+ }
104
+ };
105
+
106
+ return <canvas ref={canvasRef} className={className} width={500} height={500} style={{ width }} />;
107
+ }
@@ -0,0 +1,96 @@
1
+ import { ChunkedAudioPlayer } from './Player';
2
+
3
+ type VoiceBackend = (text: string, voice?: string, speed?: number) => Promise<Blob>;
4
+
5
+ export class MessageSender {
6
+ private player = new ChunkedAudioPlayer();
7
+ private fetchedSentences = new Set<string>();
8
+ private lastLoading = false;
9
+ private voice: string;
10
+ private voiceBackend: VoiceBackend;
11
+
12
+ constructor(voiceBackend: VoiceBackend, voice: string) {
13
+ if (voice?.split('_').length !== 2) {
14
+ throw new Error("Invalid voice id format '" + voice + "'. Voice id needs to look like <provider>_<voice_id>");
15
+ }
16
+ this.voiceBackend = voiceBackend;
17
+ this.voice = voice;
18
+ }
19
+
20
+ private getCompletedSentences(currentText: string, isLoading: boolean): string[] {
21
+ // Split the text based on the following characters: .?!
22
+ // Only split on : when followed by a space
23
+ const pattern = /(.+?[.?!]|.+?:\s+|.+?\n+)/g;
24
+ const result: string[] = [];
25
+ let match;
26
+ while ((match = pattern.exec(currentText)) !== null) {
27
+ const sentence = match[0].trim();
28
+ if (sentence.length > 0) {
29
+ result.push(sentence);
30
+ }
31
+ }
32
+ if (!isLoading) {
33
+ const lastFullSentence = result[result.length - 1];
34
+ const leftoverIndex = currentText.lastIndexOf(lastFullSentence) + lastFullSentence.length;
35
+ if (leftoverIndex < currentText.length) {
36
+ result.push(currentText.slice(leftoverIndex).trim());
37
+ }
38
+ }
39
+ return result;
40
+ }
41
+
42
+ public async handleNewText(currentText: string | undefined, isLoading: boolean) {
43
+ if (!this.lastLoading && isLoading) {
44
+ this.reset();
45
+ }
46
+ this.lastLoading = isLoading;
47
+
48
+ if (!currentText) {
49
+ return;
50
+ }
51
+
52
+ const sentences = this.getCompletedSentences(currentText, isLoading);
53
+
54
+ for (let i = 0; i < sentences.length; i++) {
55
+ const sentence = sentences[i];
56
+ if (!this.fetchedSentences.has(sentence)) {
57
+ this.fetchedSentences.add(sentence);
58
+ const audioData = await this.generateSpeech(sentence);
59
+ await this.player.addChunk(audioData, i);
60
+ }
61
+ }
62
+ }
63
+
64
+ private async generateSpeech(sentence: string): Promise<ArrayBuffer> {
65
+ const blob = await this.voiceBackend(sentence, this.voice, 1.0);
66
+ return await blob.arrayBuffer();
67
+ }
68
+
69
+ public play() {
70
+ this.player.playAgain();
71
+ }
72
+
73
+ public stop() {
74
+ this.player.stopPlayback();
75
+ }
76
+
77
+ private reset() {
78
+ this.stop();
79
+ this.fetchedSentences.clear();
80
+ this.player.reset();
81
+ }
82
+
83
+ public setVolume(volume: number) {
84
+ this.player.setVolume(volume);
85
+ }
86
+
87
+ public setOnLoudnessChange(callback: (value: number) => void) {
88
+ this.player.setOnLoudnessChange((loudness) => {
89
+ callback(loudness);
90
+ });
91
+ }
92
+
93
+ public setOnEndOfSpeech(callback: () => void) {
94
+ this.player.setOnEndOfSpeech(callback);
95
+ }
96
+ }