@sveda-ai/chat 0.3.1

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 (108) hide show
  1. package/LICENSE +557 -0
  2. package/README.md +18 -0
  3. package/dist/appearance.d.ts +54 -0
  4. package/dist/appearance.d.ts.map +1 -0
  5. package/dist/appearance.js +516 -0
  6. package/dist/appearance.js.map +1 -0
  7. package/dist/chatStore.d.ts +60 -0
  8. package/dist/chatStore.d.ts.map +1 -0
  9. package/dist/chatStore.js +518 -0
  10. package/dist/chatStore.js.map +1 -0
  11. package/dist/i18n/catalogs.d.ts +4 -0
  12. package/dist/i18n/catalogs.d.ts.map +1 -0
  13. package/dist/i18n/catalogs.js +3 -0
  14. package/dist/i18n/catalogs.js.map +1 -0
  15. package/dist/i18n/locales/en.d.ts +4 -0
  16. package/dist/i18n/locales/en.d.ts.map +1 -0
  17. package/dist/i18n/locales/en.js +59 -0
  18. package/dist/i18n/locales/en.js.map +1 -0
  19. package/dist/i18n/locales/ru.d.ts +4 -0
  20. package/dist/i18n/locales/ru.d.ts.map +1 -0
  21. package/dist/i18n/locales/ru.js +59 -0
  22. package/dist/i18n/locales/ru.js.map +1 -0
  23. package/dist/i18n/types.d.ts +2 -0
  24. package/dist/i18n/types.d.ts.map +1 -0
  25. package/dist/i18n/types.js +2 -0
  26. package/dist/i18n/types.js.map +1 -0
  27. package/dist/index.d.ts +27 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +19 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/lib/assistantMessage.d.ts +90 -0
  32. package/dist/lib/assistantMessage.d.ts.map +1 -0
  33. package/dist/lib/assistantMessage.js +311 -0
  34. package/dist/lib/assistantMessage.js.map +1 -0
  35. package/dist/lib/chatHistoryMerge.d.ts +20 -0
  36. package/dist/lib/chatHistoryMerge.d.ts.map +1 -0
  37. package/dist/lib/chatHistoryMerge.js +61 -0
  38. package/dist/lib/chatHistoryMerge.js.map +1 -0
  39. package/dist/lib/chatI18nKeys.d.ts +2 -0
  40. package/dist/lib/chatI18nKeys.d.ts.map +1 -0
  41. package/dist/lib/chatI18nKeys.js +63 -0
  42. package/dist/lib/chatI18nKeys.js.map +1 -0
  43. package/dist/lib/chatMessageVisibility.d.ts +6 -0
  44. package/dist/lib/chatMessageVisibility.d.ts.map +1 -0
  45. package/dist/lib/chatMessageVisibility.js +68 -0
  46. package/dist/lib/chatMessageVisibility.js.map +1 -0
  47. package/dist/lib/chatResize.d.ts +42 -0
  48. package/dist/lib/chatResize.d.ts.map +1 -0
  49. package/dist/lib/chatResize.js +71 -0
  50. package/dist/lib/chatResize.js.map +1 -0
  51. package/dist/lib/chatTabs.d.ts +9 -0
  52. package/dist/lib/chatTabs.d.ts.map +1 -0
  53. package/dist/lib/chatTabs.js +34 -0
  54. package/dist/lib/chatTabs.js.map +1 -0
  55. package/dist/lib/chatTitle.d.ts +3 -0
  56. package/dist/lib/chatTitle.d.ts.map +1 -0
  57. package/dist/lib/chatTitle.js +25 -0
  58. package/dist/lib/chatTitle.js.map +1 -0
  59. package/dist/lib/chatUiStorage.d.ts +6 -0
  60. package/dist/lib/chatUiStorage.d.ts.map +1 -0
  61. package/dist/lib/chatUiStorage.js +61 -0
  62. package/dist/lib/chatUiStorage.js.map +1 -0
  63. package/dist/lib/finalizeMessages.d.ts +21 -0
  64. package/dist/lib/finalizeMessages.d.ts.map +1 -0
  65. package/dist/lib/finalizeMessages.js +54 -0
  66. package/dist/lib/finalizeMessages.js.map +1 -0
  67. package/dist/lib/markdown.d.ts +8 -0
  68. package/dist/lib/markdown.d.ts.map +1 -0
  69. package/dist/lib/markdown.js +69 -0
  70. package/dist/lib/markdown.js.map +1 -0
  71. package/dist/lib/modelLabels.d.ts +3 -0
  72. package/dist/lib/modelLabels.d.ts.map +1 -0
  73. package/dist/lib/modelLabels.js +23 -0
  74. package/dist/lib/modelLabels.js.map +1 -0
  75. package/dist/lib/toolConfirmation.d.ts +11 -0
  76. package/dist/lib/toolConfirmation.d.ts.map +1 -0
  77. package/dist/lib/toolConfirmation.js +16 -0
  78. package/dist/lib/toolConfirmation.js.map +1 -0
  79. package/dist/lib/userMessage.d.ts +17 -0
  80. package/dist/lib/userMessage.d.ts.map +1 -0
  81. package/dist/lib/userMessage.js +33 -0
  82. package/dist/lib/userMessage.js.map +1 -0
  83. package/dist/streaming.d.ts +59 -0
  84. package/dist/streaming.d.ts.map +1 -0
  85. package/dist/streaming.js +375 -0
  86. package/dist/streaming.js.map +1 -0
  87. package/package.json +53 -0
  88. package/src/appearance.ts +654 -0
  89. package/src/chatStore.ts +696 -0
  90. package/src/i18n/catalogs.ts +3 -0
  91. package/src/i18n/locales/en.ts +64 -0
  92. package/src/i18n/locales/ru.ts +65 -0
  93. package/src/i18n/types.ts +1 -0
  94. package/src/index.ts +84 -0
  95. package/src/lib/assistantMessage.ts +439 -0
  96. package/src/lib/chatHistoryMerge.ts +93 -0
  97. package/src/lib/chatI18nKeys.ts +64 -0
  98. package/src/lib/chatMessageVisibility.ts +92 -0
  99. package/src/lib/chatResize.ts +123 -0
  100. package/src/lib/chatTabs.ts +54 -0
  101. package/src/lib/chatTitle.ts +30 -0
  102. package/src/lib/chatUiStorage.ts +69 -0
  103. package/src/lib/finalizeMessages.ts +81 -0
  104. package/src/lib/markdown.ts +90 -0
  105. package/src/lib/modelLabels.ts +24 -0
  106. package/src/lib/toolConfirmation.ts +31 -0
  107. package/src/lib/userMessage.ts +55 -0
  108. package/src/streaming.ts +514 -0
@@ -0,0 +1,93 @@
1
+ export type SvedaMergeableChatHistory<TMessage> = {
2
+ id: string;
3
+ title: string;
4
+ preview?: string;
5
+ messages: TMessage[];
6
+ tokensUsed: number;
7
+ contextWindowTokens: number;
8
+ createdAt: number;
9
+ updatedAt: number;
10
+ messagesLoaded: boolean;
11
+ };
12
+
13
+ export const mergeServerChatHistories = <T extends SvedaMergeableChatHistory<unknown>>(
14
+ serverHistories: T[],
15
+ currentChat: T | null
16
+ ): T[] => {
17
+ if (!currentChat) {
18
+ return serverHistories;
19
+ }
20
+
21
+ const index = serverHistories.findIndex(chat => chat.id === currentChat.id);
22
+ if (index === -1) {
23
+ return [currentChat, ...serverHistories];
24
+ }
25
+
26
+ if (currentChat.messagesLoaded && !serverHistories[index].messagesLoaded) {
27
+ const next = [...serverHistories];
28
+ next[index] = {
29
+ ...serverHistories[index],
30
+ messages: currentChat.messages,
31
+ messagesLoaded: true,
32
+ };
33
+ return next;
34
+ }
35
+
36
+ return serverHistories;
37
+ };
38
+
39
+ export const resolveMergedCurrentChat = <T extends { id: string }>(
40
+ histories: T[],
41
+ currentChat: T | null
42
+ ): T | null => {
43
+ if (!currentChat) {
44
+ return null;
45
+ }
46
+
47
+ return histories.find(chat => chat.id === currentChat.id) ?? currentChat;
48
+ };
49
+
50
+ export const upsertChatHistoryMessages = <T extends SvedaMergeableChatHistory<unknown>>(
51
+ histories: T[],
52
+ currentChat: T | null,
53
+ chatId: string,
54
+ messages: T['messages'],
55
+ now: number = Date.now()
56
+ ): { histories: T[]; current: T | null } => {
57
+ const index = histories.findIndex(chat => chat.id === chatId);
58
+ if (index !== -1) {
59
+ const next = [...histories];
60
+ next[index] = {
61
+ ...histories[index],
62
+ messages,
63
+ messagesLoaded: true,
64
+ updatedAt: now,
65
+ };
66
+
67
+ return {
68
+ histories: next,
69
+ current: currentChat?.id === chatId ? next[index] : currentChat,
70
+ };
71
+ }
72
+
73
+ const base = currentChat?.id === chatId ? currentChat : null;
74
+ const upserted = {
75
+ ...(base ?? {
76
+ id: chatId,
77
+ title: '',
78
+ preview: '',
79
+ tokensUsed: 0,
80
+ contextWindowTokens: 0,
81
+ createdAt: now,
82
+ }),
83
+ id: chatId,
84
+ messages,
85
+ messagesLoaded: true,
86
+ updatedAt: now,
87
+ } as T;
88
+
89
+ return {
90
+ histories: [upserted, ...histories],
91
+ current: currentChat === null || currentChat.id === chatId ? upserted : currentChat,
92
+ };
93
+ };
@@ -0,0 +1,64 @@
1
+ export const chatComponentI18nKeys: Record<string, Record<string, string>> = {
2
+ en: {
3
+ typeMessage: 'Ask AI to help you...',
4
+ chatAttachFiles: 'Attach files (PDF, Word, Excel, presentations, images…)',
5
+ chatRemoveFile: 'Remove file',
6
+ attachmentsLabel: 'Attachments',
7
+ attachmentOnlyPlaceholder: 'Documents: {names}',
8
+ chatHistory: 'Chat History',
9
+ searchChats: 'Search chats...',
10
+ noChatsFound: 'No chats found',
11
+ today: 'Today',
12
+ yesterday: 'Yesterday',
13
+ dayBeforeYesterday: 'Day before yesterday',
14
+ daysAgo: '{count} days ago',
15
+ renameChat: 'Rename chat',
16
+ cancel: 'Cancel',
17
+ delete: 'Delete',
18
+ pendingStatus: 'Processing your request...',
19
+ preparingReply: 'Preparing a reply…',
20
+ phaseToolCalling: 'Using tools…',
21
+ activityGroupSteps: '{label}: {count}',
22
+ voiceInputStart: 'Voice input',
23
+ voiceInputStop: 'Stop recording',
24
+ voiceInputUnsupported: 'Voice input is not supported in this browser.',
25
+ voiceInputError: 'Voice input',
26
+ voiceInputPermissionDenied: 'Microphone access was denied.',
27
+ voiceInputErrorGeneric: 'Something went wrong. Try again.',
28
+ voiceInputBrowserWarningTitle: 'Voice input in this browser',
29
+ voiceInputBrowserWarningDescription:
30
+ 'Speech recognition may be inaccurate or unstable. For best results, use Google Chrome or Microsoft Edge. You can still continue in your current browser.',
31
+ voiceInputBrowserWarningContinue: 'Continue anyway',
32
+ },
33
+ ru: {
34
+ typeMessage: 'Попросите AI помочь вам...',
35
+ chatAttachFiles: 'Прикрепить файлы (PDF, Word, Excel, презентации, изображения…)',
36
+ chatRemoveFile: 'Убрать файл',
37
+ attachmentsLabel: 'Вложения',
38
+ attachmentOnlyPlaceholder: 'Документы: {names}',
39
+ chatHistory: 'История чатов',
40
+ searchChats: 'Поиск по чатам...',
41
+ noChatsFound: 'Чаты не найдены',
42
+ today: 'Сегодня',
43
+ yesterday: 'Вчера',
44
+ dayBeforeYesterday: 'Позавчера',
45
+ daysAgo: '{count} дней назад',
46
+ renameChat: 'Переименовать чат',
47
+ cancel: 'Отмена',
48
+ delete: 'Удалить',
49
+ pendingStatus: 'Обрабатываем ваш запрос...',
50
+ preparingReply: 'Готовлю ответ…',
51
+ phaseToolCalling: 'Вызываю инструменты…',
52
+ activityGroupSteps: '{label}: {count}',
53
+ voiceInputStart: 'Голосовой ввод',
54
+ voiceInputStop: 'Остановить запись',
55
+ voiceInputUnsupported: 'Голосовой ввод не поддерживается в этом браузере.',
56
+ voiceInputError: 'Голосовой ввод',
57
+ voiceInputPermissionDenied: 'Доступ к микрофону запрещён.',
58
+ voiceInputErrorGeneric: 'Не получилось. Попробуйте ещё раз.',
59
+ voiceInputBrowserWarningTitle: 'Голосовой ввод в этом браузере',
60
+ voiceInputBrowserWarningDescription:
61
+ 'Распознавание речи может работать неточно или нестабильно. Для лучшего результата используйте Google Chrome или Microsoft Edge. Вы всё равно можете продолжить в текущем браузере.',
62
+ voiceInputBrowserWarningContinue: 'Всё равно продолжить',
63
+ },
64
+ };
@@ -0,0 +1,92 @@
1
+ import { isAssistantToolPart, type SvedaChatMessageLike } from './assistantMessage.js';
2
+
3
+ export function messageHasVisibleAssistantContent(
4
+ message: SvedaChatMessageLike | null | undefined
5
+ ): boolean {
6
+ if (!message || message.role !== 'assistant') {
7
+ return false;
8
+ }
9
+
10
+ if (Array.isArray(message.parts) && message.parts.length > 0) {
11
+ return message.parts.some(part => {
12
+ if (part.type === 'text' && part.text?.trim()) {
13
+ return true;
14
+ }
15
+ if (part.type === 'reasoning' && part.text?.trim()) {
16
+ return true;
17
+ }
18
+ if (part.type === 'tool-call' || part.type === 'tool-result') {
19
+ return true;
20
+ }
21
+ if (isAssistantToolPart(part)) {
22
+ return true;
23
+ }
24
+
25
+ return false;
26
+ });
27
+ }
28
+
29
+ return Boolean(message.content?.trim() || message.reasoningStream?.trim());
30
+ }
31
+
32
+ export function messageHasAssistantAnswerText(
33
+ message: SvedaChatMessageLike | null | undefined
34
+ ): boolean {
35
+ if (!message || message.role !== 'assistant') {
36
+ return false;
37
+ }
38
+
39
+ if (Array.isArray(message.parts) && message.parts.length > 0) {
40
+ return message.parts.some(part => part.type === 'text' && Boolean(part.text?.trim()));
41
+ }
42
+
43
+ return Boolean(message.content?.trim());
44
+ }
45
+
46
+ export function assistantHasActiveTools(message: SvedaChatMessageLike | null | undefined): boolean {
47
+ if (!message || message.role !== 'assistant' || !Array.isArray(message.parts)) {
48
+ return false;
49
+ }
50
+
51
+ const completed = new Set(
52
+ message.parts
53
+ .filter(part => part.type === 'tool-result' && part.toolCallId)
54
+ .map(part => part.toolCallId as string)
55
+ );
56
+
57
+ return message.parts.some(part => {
58
+ if (part.type === 'tool-call') {
59
+ return part.toolCallId ? !completed.has(part.toolCallId) : true;
60
+ }
61
+ if (isAssistantToolPart(part)) {
62
+ const state = part.state ?? '';
63
+ return (
64
+ state !== 'result' &&
65
+ state !== 'output-available' &&
66
+ state !== 'output-error' &&
67
+ state !== 'output-denied'
68
+ );
69
+ }
70
+ return false;
71
+ });
72
+ }
73
+
74
+ export function shouldShowChatPendingIndicator(
75
+ isThinking: boolean,
76
+ messages: SvedaChatMessageLike[]
77
+ ): boolean {
78
+ if (!isThinking) {
79
+ return false;
80
+ }
81
+
82
+ const lastMessage = messages[messages.length - 1];
83
+ if (!lastMessage) {
84
+ return true;
85
+ }
86
+
87
+ if (lastMessage.role === 'user') {
88
+ return true;
89
+ }
90
+
91
+ return !messageHasAssistantAnswerText(lastMessage);
92
+ }
@@ -0,0 +1,123 @@
1
+ export const SVEDA_CHAT_LAYOUT_MIN_WIDTH = 320;
2
+ export const SVEDA_CHAT_LAYOUT_MIN_HEIGHT = 400;
3
+ export const SVEDA_CHAT_LAYOUT_MAX_WIDTH = 800;
4
+ export const SVEDA_CHAT_LAYOUT_MAX_HEIGHT = 900;
5
+ export const SVEDA_HISTORY_SIDEBAR_WIDTH = 320;
6
+
7
+ export interface EmbedHostSize {
8
+ width: number;
9
+ height: number;
10
+ immersive: boolean;
11
+ fixed: boolean;
12
+ }
13
+
14
+ export const resolveEmbedHostSize = ({
15
+ chatWidth,
16
+ chatHeight,
17
+ fixedWidth,
18
+ historyOpen,
19
+ viewMode,
20
+ viewportWidth,
21
+ viewportHeight,
22
+ }: {
23
+ chatWidth: number;
24
+ chatHeight: number;
25
+ fixedWidth: number;
26
+ historyOpen: boolean;
27
+ viewMode: 'floating' | 'fixed' | 'immersive';
28
+ viewportWidth: number;
29
+ viewportHeight: number;
30
+ }): EmbedHostSize => {
31
+ if (viewMode === 'immersive') {
32
+ return {
33
+ width: viewportWidth,
34
+ height: viewportHeight,
35
+ immersive: true,
36
+ fixed: false,
37
+ };
38
+ }
39
+
40
+ if (viewMode === 'fixed') {
41
+ return {
42
+ width: fixedWidth + (historyOpen ? SVEDA_HISTORY_SIDEBAR_WIDTH : 0),
43
+ height: viewportHeight,
44
+ immersive: false,
45
+ fixed: true,
46
+ };
47
+ }
48
+
49
+ return {
50
+ width: chatWidth + (historyOpen ? SVEDA_HISTORY_SIDEBAR_WIDTH : 0),
51
+ height: chatHeight,
52
+ immersive: false,
53
+ fixed: false,
54
+ };
55
+ };
56
+
57
+ const clamp = (value: number, min: number, max: number): number =>
58
+ Math.max(min, Math.min(max, value));
59
+
60
+ export interface ChatBoxSize {
61
+ width: number;
62
+ height: number;
63
+ }
64
+
65
+ /**
66
+ * Pointer deltas for window resize must use screen coordinates.
67
+ *
68
+ * Inside an iframe, `clientX`/`clientY` are relative to the iframe viewport.
69
+ * Hosts pin the frame to the bottom-right, so growing the frame moves its origin
70
+ * and the next `clientX` snaps back — the window jitters. `screenX`/`screenY`
71
+ * stay stable across that origin shift (and still work for the in-page JS chat).
72
+ */
73
+ export const pointerScreenDelta = (
74
+ event: Pick<MouseEvent, 'screenX' | 'screenY'>,
75
+ startX: number,
76
+ startY: number
77
+ ): { deltaX: number; deltaY: number } => ({
78
+ deltaX: event.screenX - startX,
79
+ deltaY: event.screenY - startY,
80
+ });
81
+
82
+ export const applyFloatingResize = (
83
+ direction: string,
84
+ startWidth: number,
85
+ startHeight: number,
86
+ deltaX: number,
87
+ deltaY: number
88
+ ): ChatBoxSize => {
89
+ let width = startWidth;
90
+ let height = startHeight;
91
+
92
+ if (direction.includes('right')) {
93
+ width = clamp(startWidth + deltaX, SVEDA_CHAT_LAYOUT_MIN_WIDTH, SVEDA_CHAT_LAYOUT_MAX_WIDTH);
94
+ }
95
+ if (direction.includes('left')) {
96
+ width = clamp(startWidth - deltaX, SVEDA_CHAT_LAYOUT_MIN_WIDTH, SVEDA_CHAT_LAYOUT_MAX_WIDTH);
97
+ }
98
+ if (direction.includes('bottom')) {
99
+ height = clamp(startHeight + deltaY, SVEDA_CHAT_LAYOUT_MIN_HEIGHT, SVEDA_CHAT_LAYOUT_MAX_HEIGHT);
100
+ }
101
+ if (direction.includes('top')) {
102
+ height = clamp(startHeight - deltaY, SVEDA_CHAT_LAYOUT_MIN_HEIGHT, SVEDA_CHAT_LAYOUT_MAX_HEIGHT);
103
+ }
104
+
105
+ return { width, height };
106
+ };
107
+
108
+ export const applyFixedLeftResize = (
109
+ startWidth: number,
110
+ deltaX: number,
111
+ maxChat: number
112
+ ): { width: number; enterImmersive: boolean } => {
113
+ const next = startWidth - deltaX;
114
+ if (next > maxChat && maxChat >= SVEDA_CHAT_LAYOUT_MIN_WIDTH) {
115
+ return { width: maxChat, enterImmersive: true };
116
+ }
117
+
118
+ const upper = Math.max(SVEDA_CHAT_LAYOUT_MIN_WIDTH, maxChat);
119
+ return {
120
+ width: clamp(next, SVEDA_CHAT_LAYOUT_MIN_WIDTH, upper),
121
+ enterImmersive: false,
122
+ };
123
+ };
@@ -0,0 +1,54 @@
1
+ import { userMessageHasVisibleContent, type SvedaUserMessageLike } from './userMessage.js';
2
+
3
+ export type SvedaTabChat = {
4
+ id: string;
5
+ title?: string;
6
+ messages?: SvedaUserMessageLike[];
7
+ };
8
+
9
+ export const isNewChatPlaceholder = (chat: SvedaTabChat, newChatLabel: string): boolean => {
10
+ const messages = chat.messages || [];
11
+ if (messages.some(userMessageHasVisibleContent)) {
12
+ return false;
13
+ }
14
+
15
+ const title = (chat.title || '').trim();
16
+ if (!title || title === '__NEW_CHAT__' || title === 'New Chat') {
17
+ return true;
18
+ }
19
+
20
+ if (title === newChatLabel) {
21
+ return true;
22
+ }
23
+
24
+ if (title.startsWith(`${newChatLabel} `)) {
25
+ const suffix = title.slice(newChatLabel.length).trim();
26
+ return /^\d+$/.test(suffix);
27
+ }
28
+
29
+ return false;
30
+ };
31
+
32
+ export const buildChatTabTitleMap = (
33
+ tabs: SvedaTabChat[],
34
+ translate: (key: string, params?: Record<string, unknown>) => string
35
+ ): Map<string, string> => {
36
+ const newChatLabel = translate('newChat');
37
+ const placeholderTabs = tabs.filter(tab => isNewChatPlaceholder(tab, newChatLabel));
38
+ const titles = new Map<string, string>();
39
+
40
+ tabs.forEach(tab => {
41
+ if (!isNewChatPlaceholder(tab, newChatLabel)) {
42
+ titles.set(tab.id, (tab.title || '').trim() || newChatLabel);
43
+ return;
44
+ }
45
+
46
+ const index = placeholderTabs.findIndex(item => item.id === tab.id) + 1;
47
+ titles.set(
48
+ tab.id,
49
+ placeholderTabs.length > 1 ? translate('newChatNumbered', { number: index }) : newChatLabel
50
+ );
51
+ });
52
+
53
+ return titles;
54
+ };
@@ -0,0 +1,30 @@
1
+ export const isChatTitlePlaceholder = (title: string, newChatLabel: string): boolean => {
2
+ const normalized = (title || '').trim();
3
+ if (!normalized || normalized === '__NEW_CHAT__' || normalized === 'New Chat') {
4
+ return true;
5
+ }
6
+
7
+ if (normalized === newChatLabel) {
8
+ return true;
9
+ }
10
+
11
+ if (normalized.startsWith(`${newChatLabel} `)) {
12
+ const suffix = normalized.slice(newChatLabel.length).trim();
13
+ return /^\d+$/.test(suffix);
14
+ }
15
+
16
+ return false;
17
+ };
18
+
19
+ export const deriveProvisionalChatTitle = (userRequest: string): string => {
20
+ const text = userRequest.replace(/\s+/g, ' ').trim();
21
+ if (!text) {
22
+ return '';
23
+ }
24
+
25
+ if (text.length > 80) {
26
+ return text.slice(0, 80).trimEnd();
27
+ }
28
+
29
+ return text;
30
+ };
@@ -0,0 +1,69 @@
1
+ export const SVEDA_CHAT_MINIMIZED_STORAGE_KEY = 'sveda.chat-minimized';
2
+
3
+ const readFlag = (storage: Storage | undefined): boolean | null => {
4
+ if (!storage) {
5
+ return null;
6
+ }
7
+
8
+ try {
9
+ const saved = storage.getItem(SVEDA_CHAT_MINIMIZED_STORAGE_KEY);
10
+ if (saved === 'true') {
11
+ return true;
12
+ }
13
+ if (saved === 'false') {
14
+ return false;
15
+ }
16
+ } catch {
17
+ return null;
18
+ }
19
+
20
+ return null;
21
+ };
22
+
23
+ const storageOrNull = (read: () => Storage): Storage | undefined => {
24
+ if (typeof window === 'undefined') {
25
+ return undefined;
26
+ }
27
+
28
+ try {
29
+ return read();
30
+ } catch {
31
+ return undefined;
32
+ }
33
+ };
34
+
35
+ export const readPersistedMinimizedPreference = (): boolean | null => {
36
+ const session = readFlag(storageOrNull(() => sessionStorage));
37
+ if (session !== null) {
38
+ return session;
39
+ }
40
+
41
+ return readFlag(storageOrNull(() => localStorage));
42
+ };
43
+
44
+ export const readPersistedMinimized = (): boolean => {
45
+ return readPersistedMinimizedPreference() ?? true;
46
+ };
47
+
48
+ export const isPersistedSessionChatOpen = (): boolean => {
49
+ return readFlag(storageOrNull(() => sessionStorage)) === false;
50
+ };
51
+
52
+ export const writePersistedMinimized = (isMinimized: boolean): void => {
53
+ const value = isMinimized ? 'true' : 'false';
54
+
55
+ for (const storage of [
56
+ storageOrNull(() => sessionStorage),
57
+ storageOrNull(() => localStorage),
58
+ ]) {
59
+ if (!storage) {
60
+ continue;
61
+ }
62
+
63
+ try {
64
+ storage.setItem(SVEDA_CHAT_MINIMIZED_STORAGE_KEY, value);
65
+ } catch {
66
+ continue;
67
+ }
68
+ }
69
+ };
@@ -0,0 +1,81 @@
1
+ export type SvedaFinalizableMessage = {
2
+ parts?: Array<{
3
+ type?: string;
4
+ state?: string;
5
+ output?: unknown;
6
+ result?: unknown;
7
+ [key: string]: unknown;
8
+ }>;
9
+ streaming?: boolean;
10
+ activity?: {
11
+ phase?: string;
12
+ steps?: Array<{ status?: string; [key: string]: unknown }>;
13
+ [key: string]: unknown;
14
+ };
15
+ [key: string]: unknown;
16
+ };
17
+
18
+ const TERMINAL_ACTIVITY_PHASES = new Set(['done', 'error', 'stopped']);
19
+
20
+ const TOOL_COMPLETE_STATES = new Set([
21
+ 'result',
22
+ 'output-available',
23
+ 'output-error',
24
+ 'output-denied',
25
+ 'done',
26
+ ]);
27
+
28
+ const isToolPart = (part: { type?: string } | undefined): boolean =>
29
+ part?.type === 'dynamic-tool' ||
30
+ (typeof part?.type === 'string' && part.type.startsWith('tool-'));
31
+
32
+ function finalizeActivity<T extends SvedaFinalizableMessage>(message: T): T {
33
+ if (!message.activity) {
34
+ return message;
35
+ }
36
+
37
+ const activity = { ...message.activity };
38
+ if (activity.phase && !TERMINAL_ACTIVITY_PHASES.has(activity.phase)) {
39
+ activity.phase = 'done';
40
+ }
41
+
42
+ if (Array.isArray(activity.steps)) {
43
+ activity.steps = activity.steps.map(step => ({
44
+ ...step,
45
+ status: step.status === 'running' ? 'success' : step.status,
46
+ }));
47
+ }
48
+
49
+ return { ...message, activity };
50
+ }
51
+
52
+ function finalizeParts<T extends SvedaFinalizableMessage>(message: T): T {
53
+ if (!Array.isArray(message.parts)) {
54
+ if (message.streaming === true) {
55
+ return { ...message, streaming: false };
56
+ }
57
+ return message;
58
+ }
59
+
60
+ const parts = message.parts.map(part => {
61
+ if (part?.state === 'streaming') {
62
+ return { ...part, state: 'done' };
63
+ }
64
+ if (isToolPart(part) && part.state && !TOOL_COMPLETE_STATES.has(part.state)) {
65
+ if (part.output !== undefined || part.result !== undefined) {
66
+ return { ...part, state: 'output-available' };
67
+ }
68
+ }
69
+ return part;
70
+ });
71
+
72
+ return {
73
+ ...message,
74
+ parts,
75
+ streaming: false,
76
+ };
77
+ }
78
+
79
+ export function finalizeMessagesForDisplay<T extends SvedaFinalizableMessage>(messages: T[]): T[] {
80
+ return messages.map(message => finalizeActivity(finalizeParts(message)));
81
+ }
@@ -0,0 +1,90 @@
1
+ import DOMPurify from 'dompurify';
2
+ import hljs from 'highlight.js';
3
+ import { Marked, Renderer } from 'marked';
4
+ import type { SvedaResourceLink } from './assistantMessage.js';
5
+
6
+ const escapeHtml = (value: string): string =>
7
+ value
8
+ .replace(/&/g, '&amp;')
9
+ .replace(/</g, '&lt;')
10
+ .replace(/>/g, '&gt;')
11
+ .replace(/"/g, '&quot;');
12
+
13
+ const renderer = new Renderer();
14
+ renderer.code = ({ text, lang }): string => {
15
+ const language = lang && hljs.getLanguage(lang) ? lang : '';
16
+ const value = language ? hljs.highlight(text, { language }).value : escapeHtml(text);
17
+ const className = language ? ` class="hljs language-${language}"` : '';
18
+ return `<pre><code${className}>${value}</code></pre>`;
19
+ };
20
+
21
+ const markedInstance = new Marked({ gfm: true, breaks: true });
22
+ markedInstance.use({ renderer });
23
+
24
+ export function injectResourceLinks(html: string, resources: SvedaResourceLink[]): string {
25
+ if (!Array.isArray(resources) || resources.length === 0) {
26
+ return html;
27
+ }
28
+
29
+ const sorted = [...resources].sort((a, b) => b.label.length - a.label.length);
30
+
31
+ for (const resource of sorted) {
32
+ if (!resource.label || !resource.url) {
33
+ continue;
34
+ }
35
+ const escaped = resource.label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
36
+ const pattern = new RegExp(
37
+ `(?<=^|[^a-zA-Zа-яА-ЯёЁ])(«${escaped}»|„${escaped}"|"${escaped}"|«${escaped}|${escaped}»|${escaped})(?=$|[^a-zA-Zа-яА-ЯёЁ])`,
38
+ 'gu'
39
+ );
40
+ const safeLink = resource.url.replace(/"/g, '&quot;');
41
+ const icon =
42
+ '<svg class="resource-link-icon" xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 7h10v10"/><path d="M7 17 17 7"/></svg>';
43
+ html = html.replace(pattern, `<a href="${safeLink}" class="resource-inline-link">$1${icon}</a>`);
44
+ }
45
+
46
+ return html;
47
+ }
48
+
49
+ export interface SvedaMarkdownOptions {
50
+ resources?: SvedaResourceLink[];
51
+ injectResources?: boolean;
52
+ }
53
+
54
+ export function renderMarkdown(text: string, options: SvedaMarkdownOptions = {}): string {
55
+ const body = text || '';
56
+ if (!body.trim()) {
57
+ return '';
58
+ }
59
+
60
+ const raw = markedInstance.parse(body, { async: false });
61
+ let html = DOMPurify.sanitize(raw, {
62
+ ALLOWED_TAGS: [
63
+ 'p',
64
+ 'br',
65
+ 'strong',
66
+ 'em',
67
+ 'code',
68
+ 'pre',
69
+ 'ul',
70
+ 'ol',
71
+ 'li',
72
+ 'h1',
73
+ 'h2',
74
+ 'h3',
75
+ 'h4',
76
+ 'a',
77
+ 'blockquote',
78
+ 'hr',
79
+ 'span',
80
+ 'img',
81
+ ],
82
+ ALLOWED_ATTR: ['href', 'src', 'alt', 'title', 'class', 'target', 'rel', 'loading'],
83
+ });
84
+
85
+ if (options.injectResources && Array.isArray(options.resources) && options.resources.length > 0) {
86
+ html = injectResourceLinks(html, options.resources);
87
+ }
88
+
89
+ return html;
90
+ }