@sveda-ai/svelte 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.
@@ -0,0 +1,29 @@
1
+ <script lang="ts">
2
+ import type { Snippet } from 'svelte';
3
+ import { untrack } from 'svelte';
4
+ import {
5
+ createSveda,
6
+ type SvedaContext,
7
+ type SvedaPluginOptions,
8
+ } from '../provider.js';
9
+ import { setSvedaContext } from '../context.js';
10
+
11
+ interface Props {
12
+ options?: SvedaPluginOptions;
13
+ sveda?: SvedaContext;
14
+ children?: Snippet;
15
+ }
16
+
17
+ let { options, sveda, children }: Props = $props();
18
+
19
+ // Context is fixed for the provider lifetime (mirrors Vue app.use(createSveda(...))).
20
+ const ctx = untrack(() => sveda ?? (options ? createSveda(options) : null));
21
+ if (!ctx) {
22
+ throw new Error('[sveda] SvedaProvider requires either `sveda` or `options`.');
23
+ }
24
+ setSvedaContext(ctx);
25
+ </script>
26
+
27
+ {#if children}
28
+ {@render children()}
29
+ {/if}
package/src/context.ts ADDED
@@ -0,0 +1,50 @@
1
+ import { getContext, setContext } from 'svelte';
2
+ import {
3
+ createSveda,
4
+ getDefaultSvedaConfig,
5
+ SVEDA_CONTEXT_KEY,
6
+ type SvedaConfig,
7
+ type SvedaContext,
8
+ type SvedaPluginOptions,
9
+ } from './provider.js';
10
+ import type { SvedaClient } from '@sveda-ai/core';
11
+
12
+ export function setSvedaContext(ctx: SvedaContext): SvedaContext {
13
+ setContext(SVEDA_CONTEXT_KEY, ctx);
14
+ return ctx;
15
+ }
16
+
17
+ export function createSvedaContext(options: SvedaPluginOptions): SvedaContext {
18
+ return setSvedaContext(createSveda(options));
19
+ }
20
+
21
+ export function useSvedaContext(): SvedaContext {
22
+ const ctx = getContext<SvedaContext | undefined>(SVEDA_CONTEXT_KEY);
23
+ if (!ctx) {
24
+ throw new Error(
25
+ '[sveda] Sveda context is missing. Wrap your tree in <SvedaProvider> or call setSvedaContext(createSveda(...)).',
26
+ );
27
+ }
28
+ return ctx;
29
+ }
30
+
31
+ export function useSvedaClient(): SvedaClient {
32
+ return useSvedaContext().client;
33
+ }
34
+
35
+ export function useSvedaConfig(): SvedaConfig {
36
+ try {
37
+ return useSvedaContext().config;
38
+ } catch {
39
+ return getDefaultSvedaConfig();
40
+ }
41
+ }
42
+
43
+ export function useSvedaT(): (key: string, params?: Record<string, unknown>) => string {
44
+ try {
45
+ const { i18n } = useSvedaContext();
46
+ return (key, params) => i18n.t(key, params);
47
+ } catch {
48
+ return (key) => key;
49
+ }
50
+ }
@@ -0,0 +1,120 @@
1
+ import {
2
+ getSvedaChatStore,
3
+ type SvedaChatHistory,
4
+ type SvedaChatState,
5
+ } from '@sveda-ai/chat';
6
+ import { SVEDA_EMBED_AUTH_EVENT, type SvedaContext } from '../provider.js';
7
+ import { useSvedaContext, useSvedaT } from '../context.js';
8
+
9
+ export type { SvedaChatHistory, SvedaChatState };
10
+
11
+ let initialized = false;
12
+ let subscribed = false;
13
+
14
+ const store = getSvedaChatStore({ embedAuthEvent: SVEDA_EMBED_AUTH_EVENT });
15
+
16
+ export function useSvedaChat(sveda?: SvedaContext) {
17
+ let ctx: SvedaContext | null = sveda ?? null;
18
+ try {
19
+ ctx = sveda ?? useSvedaContext();
20
+ } catch {
21
+ ctx = sveda ?? null;
22
+ }
23
+
24
+ const t = (() => {
25
+ try {
26
+ return useSvedaT();
27
+ } catch {
28
+ return (key: string) => key;
29
+ }
30
+ })();
31
+
32
+ if (ctx?.client) {
33
+ store.setClient(ctx.client);
34
+ }
35
+ store.setTranslate(t);
36
+
37
+ const initial = store.getState();
38
+
39
+ let chatState = $state<SvedaChatState>({ ...initial.chatState });
40
+ let currentChat = $state<SvedaChatHistory | null>(initial.currentChat);
41
+ let chatHistories = $state<SvedaChatHistory[]>(initial.chatHistories);
42
+ let storeRevision = $state(0);
43
+
44
+ const syncFromStore = () => {
45
+ const snapshot = store.getState();
46
+ chatState = { ...snapshot.chatState };
47
+ currentChat = snapshot.currentChat;
48
+ chatHistories = snapshot.chatHistories;
49
+ storeRevision += 1;
50
+ };
51
+
52
+ if (!subscribed) {
53
+ subscribed = true;
54
+ store.subscribe(syncFromStore);
55
+ }
56
+
57
+ if (!initialized) {
58
+ initialized = true;
59
+ store.initAuthListener();
60
+ void store.loadHistories();
61
+ }
62
+
63
+ return {
64
+ get chatState() {
65
+ return chatState;
66
+ },
67
+ get currentChat() {
68
+ return currentChat;
69
+ },
70
+ get chatHistories() {
71
+ return chatHistories;
72
+ },
73
+ get sortedHistories() {
74
+ void storeRevision;
75
+ return store.sortedHistories();
76
+ },
77
+ get openChatTabs() {
78
+ void storeRevision;
79
+ return store.openChatTabs();
80
+ },
81
+ get isOpen() {
82
+ return chatState.isOpen;
83
+ },
84
+ get isMinimized() {
85
+ return chatState.isMinimized;
86
+ },
87
+ get isLoading() {
88
+ return chatState.isLoading;
89
+ },
90
+ get isLoadingChatHistory() {
91
+ return chatState.isLoadingChatHistory;
92
+ },
93
+ get hasCurrentChat() {
94
+ return !!currentChat;
95
+ },
96
+ loadHistories: () => store.loadHistories(),
97
+ createNewChat: () => store.createNewChat(t),
98
+ setCurrentChat: (chatId: string) => store.setCurrentChat(chatId, t),
99
+ addMessage: store.addMessage.bind(store),
100
+ setChatTitle: store.setChatTitle.bind(store),
101
+ refreshChatTitleFromServer: store.refreshChatTitleFromServer.bind(store),
102
+ updateMessage: store.updateMessage.bind(store),
103
+ setChatMessages: store.setChatMessages.bind(store),
104
+ incrementChatTokens: store.incrementChatTokens.bind(store),
105
+ setChatContextWindowTokens: store.setChatContextWindowTokens.bind(store),
106
+ deleteChat: (chatId: string) => store.deleteChat(chatId, t),
107
+ renameChat: (chatId: string, title: string) => store.renameChat(chatId, title),
108
+ closeChatTab: (chatId: string) => store.closeChatTab(chatId, t),
109
+ openChat: () => store.openChat(t),
110
+ closeChat: () => store.closeChat(),
111
+ minimizeChat: () => store.minimizeChat(),
112
+ maximizeChat: () => store.maximizeChat(),
113
+ setLoading: (loading: boolean) => store.setLoading(loading),
114
+ };
115
+ }
116
+
117
+ /** Reset module init flags (tests only). */
118
+ export function __resetSvedaChatHookForTests(): void {
119
+ initialized = false;
120
+ }
@@ -0,0 +1,308 @@
1
+ import {
2
+ applyFixedLeftResize,
3
+ applyFloatingResize,
4
+ pointerScreenDelta,
5
+ SVEDA_CHAT_LAYOUT_MAX_HEIGHT,
6
+ SVEDA_CHAT_LAYOUT_MAX_WIDTH,
7
+ SVEDA_CHAT_LAYOUT_MIN_HEIGHT,
8
+ SVEDA_CHAT_LAYOUT_MIN_WIDTH,
9
+ } from '@sveda-ai/chat';
10
+
11
+ export type SvedaChatViewMode = 'floating' | 'fixed' | 'immersive';
12
+
13
+ const VIEW_MODE_STORAGE_KEY = 'sveda.chat-view-mode';
14
+ const FIXED_WIDTH_STORAGE_KEY = 'sveda.chat-fixed-width';
15
+ const CHAT_STORAGE_KEY = 'sveda.chat-dimensions';
16
+ const FIXED_MODE_BODY_CLASS = 'sveda-chat-fixed-mode';
17
+ const IMMERSIVE_BODY_CLASS = 'sveda-chat-immersive-mode';
18
+ const CHAT_WIDTH_CSS_VAR = '--sveda-chat-width';
19
+ const FIXED_RESIZE_BODY_CLASS = 'sveda-chat-fixed-resizing';
20
+ const DEFAULT_WIDTH = 384;
21
+ const DEFAULT_HEIGHT = 600;
22
+ const DEFAULT_FIXED_WIDTH = 400;
23
+ const MAIN_CONTENT_MIN_WIDTH = 768;
24
+
25
+ const clamp = (value: number, min: number, max: number) => Math.max(min, Math.min(max, value));
26
+
27
+ const readChatDimensions = (): { width: number; height: number } => {
28
+ if (typeof localStorage === 'undefined') {
29
+ return { width: DEFAULT_WIDTH, height: DEFAULT_HEIGHT };
30
+ }
31
+ try {
32
+ const saved = localStorage.getItem(CHAT_STORAGE_KEY);
33
+ if (!saved) {
34
+ return { width: DEFAULT_WIDTH, height: DEFAULT_HEIGHT };
35
+ }
36
+ const parsed = JSON.parse(saved) as { width?: number; height?: number };
37
+ return {
38
+ width: clamp(Number(parsed.width) || DEFAULT_WIDTH, SVEDA_CHAT_LAYOUT_MIN_WIDTH, SVEDA_CHAT_LAYOUT_MAX_WIDTH),
39
+ height: clamp(Number(parsed.height) || DEFAULT_HEIGHT, SVEDA_CHAT_LAYOUT_MIN_HEIGHT, SVEDA_CHAT_LAYOUT_MAX_HEIGHT),
40
+ };
41
+ } catch {
42
+ return { width: DEFAULT_WIDTH, height: DEFAULT_HEIGHT };
43
+ }
44
+ };
45
+
46
+ const readViewMode = (hostEmbed: boolean): SvedaChatViewMode => {
47
+ if (typeof localStorage === 'undefined') {
48
+ return hostEmbed ? 'floating' : 'fixed';
49
+ }
50
+ const stored = localStorage.getItem(VIEW_MODE_STORAGE_KEY);
51
+ if (stored === 'floating' || stored === 'fixed' || stored === 'immersive') {
52
+ return stored;
53
+ }
54
+ return hostEmbed ? 'floating' : 'fixed';
55
+ };
56
+
57
+ const readNumber = (key: string, fallback: number): number => {
58
+ if (typeof localStorage === 'undefined') {
59
+ return fallback;
60
+ }
61
+ const parsed = Number(localStorage.getItem(key));
62
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
63
+ };
64
+
65
+ export function useSvedaChatLayout(options: {
66
+ getIsMinimized: () => boolean;
67
+ hostEmbed: boolean;
68
+ fillHost: boolean;
69
+ }) {
70
+ const initialSize = readChatDimensions();
71
+ let viewMode = $state<SvedaChatViewMode>(readViewMode(options.hostEmbed));
72
+ let lastNonImmersiveViewMode = $state<SvedaChatViewMode>(options.hostEmbed ? 'floating' : 'fixed');
73
+ let isMobile = $state(false);
74
+ let chatWidth = $state(initialSize.width);
75
+ let chatHeight = $state(initialSize.height);
76
+ let fixedWidth = $state(readNumber(FIXED_WIDTH_STORAGE_KEY, DEFAULT_FIXED_WIDTH));
77
+
78
+ $effect(() => {
79
+ if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
80
+ return;
81
+ }
82
+ const media = window.matchMedia('(max-width: 768px)');
83
+ const apply = () => {
84
+ isMobile = options.hostEmbed ? false : media.matches;
85
+ };
86
+ apply();
87
+ media.addEventListener('change', apply);
88
+ return () => media.removeEventListener('change', apply);
89
+ });
90
+
91
+ $effect(() => {
92
+ if (typeof document === 'undefined') {
93
+ return;
94
+ }
95
+ const minimized = options.getIsMinimized();
96
+ const body = document.body;
97
+ body.classList.remove(FIXED_MODE_BODY_CLASS, IMMERSIVE_BODY_CLASS);
98
+ document.documentElement.style.removeProperty(CHAT_WIDTH_CSS_VAR);
99
+ body.style.removeProperty(CHAT_WIDTH_CSS_VAR);
100
+
101
+ if (!minimized && !isMobile && viewMode === 'fixed') {
102
+ body.classList.add(FIXED_MODE_BODY_CLASS);
103
+ body.style.setProperty(CHAT_WIDTH_CSS_VAR, `${fixedWidth}px`);
104
+ }
105
+ if (!minimized && !isMobile && viewMode === 'immersive') {
106
+ body.classList.add(IMMERSIVE_BODY_CLASS);
107
+ }
108
+
109
+ return () => {
110
+ body.classList.remove(FIXED_MODE_BODY_CLASS, IMMERSIVE_BODY_CLASS);
111
+ body.style.removeProperty(CHAT_WIDTH_CSS_VAR);
112
+ };
113
+ });
114
+
115
+ const saveViewMode = (mode: SvedaChatViewMode) => {
116
+ localStorage.setItem(VIEW_MODE_STORAGE_KEY, mode);
117
+ };
118
+
119
+ const toggleViewMode = () => {
120
+ if (viewMode === 'immersive') {
121
+ return;
122
+ }
123
+ const next: SvedaChatViewMode = viewMode === 'floating' ? 'fixed' : 'floating';
124
+ viewMode = next;
125
+ lastNonImmersiveViewMode = next;
126
+ saveViewMode(next);
127
+ };
128
+
129
+ const enterImmersiveMode = () => {
130
+ if (isMobile || viewMode === 'immersive') {
131
+ return;
132
+ }
133
+ lastNonImmersiveViewMode = viewMode;
134
+ viewMode = 'immersive';
135
+ saveViewMode('immersive');
136
+ };
137
+
138
+ const exitImmersiveMode = () => {
139
+ if (viewMode !== 'immersive') {
140
+ return;
141
+ }
142
+ const next = lastNonImmersiveViewMode === 'immersive' ? 'fixed' : lastNonImmersiveViewMode;
143
+ viewMode = next;
144
+ saveViewMode(next);
145
+ };
146
+
147
+ const startResize = (direction: string, event: PointerEvent) => {
148
+ event.preventDefault();
149
+ event.stopPropagation();
150
+ const handle = event.currentTarget;
151
+ if (!(handle instanceof HTMLElement)) {
152
+ return;
153
+ }
154
+ const pointerId = event.pointerId;
155
+ try {
156
+ handle.setPointerCapture(pointerId);
157
+ } catch {
158
+ // Capture is best-effort.
159
+ }
160
+
161
+ const startX = event.screenX;
162
+ const startY = event.screenY;
163
+ const mode = viewMode;
164
+ const startWidth = mode === 'fixed' ? fixedWidth : chatWidth;
165
+ const startHeight = chatHeight;
166
+ let latestWidth = startWidth;
167
+ let latestHeight = startHeight;
168
+ let finished = false;
169
+
170
+ const stop = () => {
171
+ window.removeEventListener('pointermove', onMove);
172
+ window.removeEventListener('pointerup', onUp);
173
+ window.removeEventListener('pointercancel', onUp);
174
+ try {
175
+ handle.releasePointerCapture(pointerId);
176
+ } catch {
177
+ // Already released.
178
+ }
179
+ };
180
+
181
+ const onUp = () => {
182
+ if (finished) {
183
+ return;
184
+ }
185
+ finished = true;
186
+ document.body.classList.remove(FIXED_RESIZE_BODY_CLASS);
187
+ if (mode === 'floating') {
188
+ localStorage.setItem(CHAT_STORAGE_KEY, JSON.stringify({ width: latestWidth, height: latestHeight }));
189
+ }
190
+ if (mode === 'fixed') {
191
+ localStorage.setItem(FIXED_WIDTH_STORAGE_KEY, String(latestWidth));
192
+ }
193
+ stop();
194
+ };
195
+
196
+ const onMove = (moveEvent: PointerEvent) => {
197
+ if (finished || moveEvent.pointerId !== pointerId) {
198
+ return;
199
+ }
200
+ const { deltaX, deltaY } = pointerScreenDelta(moveEvent, startX, startY);
201
+ if (mode === 'fixed' && direction === 'fixed-left') {
202
+ document.body.classList.add(FIXED_RESIZE_BODY_CLASS);
203
+ const maxChat = Math.max(SVEDA_CHAT_LAYOUT_MIN_WIDTH, window.innerWidth - MAIN_CONTENT_MIN_WIDTH);
204
+ const result = applyFixedLeftResize(startWidth, deltaX, maxChat);
205
+ latestWidth = result.width;
206
+ fixedWidth = result.width;
207
+ if (result.enterImmersive) {
208
+ lastNonImmersiveViewMode = 'fixed';
209
+ viewMode = 'immersive';
210
+ localStorage.setItem(VIEW_MODE_STORAGE_KEY, 'immersive');
211
+ localStorage.setItem(FIXED_WIDTH_STORAGE_KEY, String(result.width));
212
+ finished = true;
213
+ document.body.classList.remove(FIXED_RESIZE_BODY_CLASS);
214
+ stop();
215
+ }
216
+ return;
217
+ }
218
+ if (mode === 'floating') {
219
+ const next = applyFloatingResize(direction, startWidth, startHeight, deltaX, deltaY);
220
+ latestWidth = next.width;
221
+ latestHeight = next.height;
222
+ chatWidth = next.width;
223
+ chatHeight = next.height;
224
+ }
225
+ };
226
+
227
+ window.addEventListener('pointermove', onMove);
228
+ window.addEventListener('pointerup', onUp);
229
+ window.addEventListener('pointercancel', onUp);
230
+ };
231
+
232
+ return {
233
+ get isMobile() {
234
+ return isMobile;
235
+ },
236
+ get viewMode() {
237
+ return viewMode;
238
+ },
239
+ get chatWidth() {
240
+ return chatWidth;
241
+ },
242
+ get chatHeight() {
243
+ return chatHeight;
244
+ },
245
+ get isImmersiveDesktop() {
246
+ return !isMobile && !options.getIsMinimized() && viewMode === 'immersive';
247
+ },
248
+ get chatShellClass() {
249
+ const minimized = options.getIsMinimized();
250
+ return [
251
+ 'sveda-chat flex flex-col',
252
+ options.fillHost && !minimized ? 'relative h-full min-h-0 w-full overflow-hidden' : '',
253
+ !options.fillHost && minimized ? 'fixed bottom-0 right-0 z-50 min-[1872px]:bottom-4 min-[1872px]:right-4' : '',
254
+ !options.fillHost && !minimized && isMobile
255
+ ? 'sveda-chat-surface fixed inset-0 z-50 pb-[env(safe-area-inset-bottom)] pt-[env(safe-area-inset-top)]'
256
+ : '',
257
+ !options.fillHost && !minimized && !isMobile && viewMode === 'immersive'
258
+ ? 'sveda-chat-surface fixed right-0 top-0 z-50 h-[100dvh] pb-[env(safe-area-inset-bottom)] pt-[env(safe-area-inset-top)]'
259
+ : '',
260
+ !options.fillHost && !minimized && !isMobile && viewMode === 'fixed'
261
+ ? 'sveda-chat-surface fixed right-0 top-0 z-50 h-screen pt-[env(safe-area-inset-top)]'
262
+ : '',
263
+ !options.fillHost && !minimized && !isMobile && viewMode === 'floating' ? 'fixed bottom-4 right-4 z-50' : '',
264
+ options.fillHost || isMobile || viewMode === 'fixed' || viewMode === 'immersive' ? 'items-stretch' : 'items-end gap-2',
265
+ ]
266
+ .filter(Boolean)
267
+ .join(' ');
268
+ },
269
+ get chatShellStyle() {
270
+ const minimized = options.getIsMinimized();
271
+ if (options.fillHost && !minimized) {
272
+ return 'width: 100%; height: 100%;';
273
+ }
274
+ if (!isMobile && !minimized && viewMode === 'immersive') {
275
+ return 'width: 100vw; height: 100dvh;';
276
+ }
277
+ if (!isMobile && !minimized && viewMode === 'fixed') {
278
+ return 'width: var(--sveda-chat-width); height: 100dvh;';
279
+ }
280
+ return undefined;
281
+ },
282
+ get chatCardStyle() {
283
+ if (isMobile || options.fillHost) {
284
+ return 'width: 100%; height: 100%;';
285
+ }
286
+ if (viewMode === 'fixed') {
287
+ return 'width: var(--sveda-chat-width); height: 100%;';
288
+ }
289
+ if (viewMode === 'floating') {
290
+ return `width: ${chatWidth}px; height: ${chatHeight}px;`;
291
+ }
292
+ return 'width: 100%; height: 100%;';
293
+ },
294
+ get floatShellStyle() {
295
+ if (options.fillHost) {
296
+ return 'height: 100%; min-height: 0;';
297
+ }
298
+ if (isMobile || viewMode !== 'floating') {
299
+ return undefined;
300
+ }
301
+ return `height: ${chatHeight}px; min-height: 0;`;
302
+ },
303
+ toggleViewMode,
304
+ enterImmersiveMode,
305
+ exitImmersiveMode,
306
+ startResize,
307
+ };
308
+ }
@@ -0,0 +1,117 @@
1
+ import {
2
+ createSvedaStreaming,
3
+ type SvedaSendPayload,
4
+ type SvedaStreamingOptions as HeadlessStreamingOptions,
5
+ type SvedaStreamingStore as HeadlessStreamingStore,
6
+ } from '@sveda-ai/chat';
7
+ import type { SvedaClient, SvedaDisplayMessage, SvedaSendOptions } from '@sveda-ai/core';
8
+ import type { SvedaContextUsageEvent, SvedaToolProgressEvent } from '@sveda-ai/protocol';
9
+ import { onDestroy } from 'svelte';
10
+ import { useSvedaContext, useSvedaT } from '../context.js';
11
+
12
+ export interface SvedaStreamingStore {
13
+ getCurrentChat: () => {
14
+ id: string;
15
+ title?: string;
16
+ messages?: SvedaDisplayMessage[];
17
+ } | null;
18
+ setChatMessages: (chatId: string, messages: SvedaDisplayMessage[]) => void;
19
+ setChatTitle: (chatId: string, title: string) => void;
20
+ refreshChatTitleFromServer: (chatId: string) => Promise<string | null>;
21
+ incrementChatTokens: (chatId: string, tokens: number) => void;
22
+ setChatContextWindowTokens: (chatId: string, tokens: number) => void;
23
+ }
24
+
25
+ export interface SvedaStreamingOptions {
26
+ newChatLabel?: () => string;
27
+ resolveSendOptions?: () => Pick<SvedaSendOptions, 'model' | 'provider' | 'options'>;
28
+ onMaxStepsReached?: (chatId: string, data: { maxSteps: number }) => void;
29
+ onToolProgress?: (chatId: string, event: SvedaToolProgressEvent) => void;
30
+ onContextUsage?: (chatId: string, event: SvedaContextUsageEvent) => void;
31
+ onError?: (chatId: string, error: unknown) => void;
32
+ onDone?: (chatId: string) => void;
33
+ }
34
+
35
+ export type { SvedaSendPayload };
36
+
37
+ export function useSvedaStreaming(
38
+ store: SvedaStreamingStore,
39
+ scrollToBottom: (options?: { behavior?: string; onlyIfNearBottom?: boolean }) => void,
40
+ options: SvedaStreamingOptions = {},
41
+ ) {
42
+ const t = useSvedaT();
43
+ const ctx = useSvedaContext();
44
+ const client = ctx.client as SvedaClient;
45
+ const beforeSend = ctx.beforeSend;
46
+
47
+ let isThinking = $state(false);
48
+ let thinkingMessage = $state('');
49
+ let streamingChatIds = $state(new Set<string>());
50
+ let unreadChatIds = $state(new Set<string>());
51
+ let isStreaming = $state(false);
52
+
53
+ const headlessStore: HeadlessStreamingStore = {
54
+ getCurrentChat: () => store.getCurrentChat(),
55
+ setChatMessages: store.setChatMessages,
56
+ setChatTitle: store.setChatTitle,
57
+ refreshChatTitleFromServer: store.refreshChatTitleFromServer,
58
+ incrementChatTokens: store.incrementChatTokens,
59
+ setChatContextWindowTokens: store.setChatContextWindowTokens,
60
+ };
61
+
62
+ const headlessOptions: HeadlessStreamingOptions = {
63
+ ...options,
64
+ translate: t,
65
+ beforeSend,
66
+ };
67
+
68
+ const controller = createSvedaStreaming(client, headlessStore, scrollToBottom, headlessOptions);
69
+
70
+ const sync = () => {
71
+ const state = controller.getState();
72
+ isThinking = state.isThinking;
73
+ thinkingMessage = state.thinkingMessage;
74
+ streamingChatIds = state.streamingChatIds;
75
+ unreadChatIds = state.unreadChatIds;
76
+ isStreaming = controller.isStreamingFor(store.getCurrentChat()?.id);
77
+ };
78
+
79
+ const unsubscribe = controller.subscribe(sync);
80
+ sync();
81
+
82
+ const pollCurrentChat = controller.watchCurrentChatId(() => store.getCurrentChat()?.id);
83
+
84
+ const interval = setInterval(() => {
85
+ pollCurrentChat();
86
+ isStreaming = controller.isStreamingFor(store.getCurrentChat()?.id);
87
+ }, 250);
88
+
89
+ onDestroy(() => {
90
+ clearInterval(interval);
91
+ unsubscribe();
92
+ controller.dispose();
93
+ });
94
+
95
+ return {
96
+ sendMessage: controller.sendMessage,
97
+ continueAfterMaxSteps: controller.continueAfterMaxSteps,
98
+ resolveToolConfirmation: controller.resolveToolConfirmation,
99
+ get isStreaming() {
100
+ return isStreaming;
101
+ },
102
+ get isThinking() {
103
+ return isThinking;
104
+ },
105
+ get thinkingMessage() {
106
+ return thinkingMessage;
107
+ },
108
+ stopStreaming: controller.stopStreaming,
109
+ get streamingChatIds() {
110
+ return streamingChatIds;
111
+ },
112
+ get unreadChatIds() {
113
+ return unreadChatIds;
114
+ },
115
+ clearChatUnread: controller.clearChatUnread,
116
+ };
117
+ }
package/src/i18n.ts ADDED
@@ -0,0 +1,51 @@
1
+ export type SvedaMessages = Record<string, string>;
2
+
3
+ export interface SvedaI18n {
4
+ readonly locale: string;
5
+ t(key: string, params?: Record<string, unknown>): string;
6
+ setLocale(locale: string): void;
7
+ extend(locale: string, messages: SvedaMessages): void;
8
+ }
9
+
10
+ export interface SvedaI18nOptions {
11
+ locale?: string;
12
+ fallbackLocale?: string;
13
+ messages?: Record<string, SvedaMessages>;
14
+ }
15
+
16
+ export function createSvedaI18n(options: SvedaI18nOptions = {}): SvedaI18n {
17
+ let locale = options.locale ?? 'en';
18
+ const fallbackLocale = options.fallbackLocale ?? 'en';
19
+ const messages: Record<string, SvedaMessages> = { ...(options.messages ?? {}) };
20
+
21
+ const interpolate = (template: string, params?: Record<string, unknown>): string => {
22
+ if (!params) {
23
+ return template;
24
+ }
25
+
26
+ return template.replace(/\{(\w+)\}/g, (match, name: string) =>
27
+ params[name] === undefined || params[name] === null ? match : String(params[name])
28
+ );
29
+ };
30
+
31
+ return {
32
+ get locale() {
33
+ return locale;
34
+ },
35
+ t(key: string, params?: Record<string, unknown>): string {
36
+ const message = messages[locale]?.[key] ?? messages[fallbackLocale]?.[key];
37
+
38
+ if (message === undefined) {
39
+ return key;
40
+ }
41
+
42
+ return interpolate(message, params);
43
+ },
44
+ setLocale(next: string): void {
45
+ locale = next;
46
+ },
47
+ extend(nextLocale: string, localeMessages: SvedaMessages): void {
48
+ messages[nextLocale] = { ...(messages[nextLocale] ?? {}), ...localeMessages };
49
+ },
50
+ };
51
+ }