vzcode 2.21.0 → 2.22.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 (40) hide show
  1. package/README.md +359 -0
  2. package/dist/assets/{index-D6-he0oi.js → index-CfDs-dAu.js} +99 -99
  3. package/dist/assets/{index-fYq6iaqF.css → index-fSroLVgi.css} +1 -1
  4. package/dist/index.html +2 -2
  5. package/dist/llm-streaming-server/aiEditing.js +58 -0
  6. package/dist/llm-streaming-server/chatOperations.js +494 -0
  7. package/dist/llm-streaming-server/errorHandling.js +49 -0
  8. package/dist/llm-streaming-server/index.js +20 -0
  9. package/dist/llm-streaming-server/llmStreaming.js +265 -0
  10. package/dist/llm-streaming-server/validation.js +19 -0
  11. package/dist/server/aiChatHandler/index.js +5 -5
  12. package/package.json +35 -35
  13. package/src/client/CodeEditor/getOrCreateEditor.tsx +20 -13
  14. package/src/client/CodeEditor/index.tsx +3 -3
  15. package/src/client/VZSidebar/AIChat/styles.scss +38 -0
  16. package/src/client/VZSidebar/FileTypeIcon.tsx +1 -0
  17. package/src/client/VZSidebar/index.tsx +1 -1
  18. package/src/llm-streaming-server/README.md +71 -0
  19. package/src/llm-streaming-server/aiEditing.ts +102 -0
  20. package/src/llm-streaming-server/chatOperations.ts +655 -0
  21. package/src/llm-streaming-server/errorHandling.ts +66 -0
  22. package/src/llm-streaming-server/index.ts +51 -0
  23. package/src/llm-streaming-server/llmStreaming.ts +403 -0
  24. package/src/llm-streaming-server/validation.ts +24 -0
  25. package/src/llm-streaming-ui/README.md +103 -0
  26. package/src/llm-streaming-ui/components/ChatInput.tsx +237 -0
  27. package/src/llm-streaming-ui/components/DiffView.scss +173 -0
  28. package/src/llm-streaming-ui/components/DiffView.tsx +236 -0
  29. package/src/llm-streaming-ui/components/FileEditingIndicator.tsx +89 -0
  30. package/src/llm-streaming-ui/components/IndividualFileDiff.tsx +86 -0
  31. package/src/llm-streaming-ui/components/JumpToLatestButton.tsx +64 -0
  32. package/src/llm-streaming-ui/components/Message.tsx +145 -0
  33. package/src/llm-streaming-ui/components/MessageList.tsx +241 -0
  34. package/src/llm-streaming-ui/components/ThinkingScratchpad.tsx +42 -0
  35. package/src/llm-streaming-ui/components/TypingIndicator.tsx +19 -0
  36. package/src/llm-streaming-ui/components/index.tsx +388 -0
  37. package/src/llm-streaming-ui/components/styles.scss +831 -0
  38. package/src/llm-streaming-ui/components/useSpeechRecognition.ts +116 -0
  39. package/src/llm-streaming-ui/index.ts +34 -0
  40. package/src/server/aiChatHandler/index.ts +5 -5
package/dist/index.html CHANGED
@@ -20,8 +20,8 @@
20
20
  href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap"
21
21
  rel="stylesheet"
22
22
  />
23
- <script type="module" crossorigin src="/assets/index-D6-he0oi.js"></script>
24
- <link rel="stylesheet" crossorigin href="/assets/index-fYq6iaqF.css">
23
+ <script type="module" crossorigin src="/assets/index-CfDs-dAu.js"></script>
24
+ <link rel="stylesheet" crossorigin href="/assets/index-fSroLVgi.css">
25
25
  </head>
26
26
  <body>
27
27
  <div id="root"></div>
@@ -0,0 +1,58 @@
1
+ import { assembleFullPrompt, prepareFilesForPrompt, } from 'editcodewithai';
2
+ import { formatMarkdownFiles } from 'llm-code-format';
3
+ import { createFilesSnapshot, generateFilesUnifiedDiff, } from '../utils/fileDiff.js';
4
+ // Dev flag for waiting 1 second before starting the LLM function.
5
+ // Useful for debugging and testing purposes, e.g. checking the typing indicator.
6
+ const delayStart = false;
7
+ /**
8
+ * Performs AI chat without editing - just generates a response
9
+ */
10
+ export const performAIChat = async ({ prompt, shareDBDoc, llmFunction, }) => {
11
+ const { files } = prepareFilesForPrompt(shareDBDoc.data.files);
12
+ const filesContext = formatMarkdownFiles(files);
13
+ // 2. Assemble the final prompt for Q&A mode
14
+ const fullPrompt = assembleFullPrompt({
15
+ filesContext,
16
+ prompt,
17
+ editFormat: 'whole',
18
+ });
19
+ if (delayStart) {
20
+ await new Promise((resolve) => setTimeout(resolve, 1000));
21
+ }
22
+ // Call the LLM function which will handle streaming but won't edit files
23
+ const result = await llmFunction(fullPrompt);
24
+ return {
25
+ content: result.content,
26
+ generationId: result.generationId,
27
+ diffData: {}, // No file changes in ask mode
28
+ };
29
+ };
30
+ /**
31
+ * Performs AI editing operations using streaming with incremental OT operations
32
+ */
33
+ export const performAIEditing = async ({ prompt, shareDBDoc, llmFunction, runCode, }) => {
34
+ // Capture the current state of files before editing
35
+ const beforeFiles = createFilesSnapshot(shareDBDoc.data.files);
36
+ const { files } = prepareFilesForPrompt(shareDBDoc.data.files);
37
+ const filesContext = formatMarkdownFiles(files);
38
+ // Assemble the final prompt
39
+ const fullPrompt = assembleFullPrompt({
40
+ filesContext,
41
+ prompt,
42
+ editFormat: 'whole',
43
+ });
44
+ if (delayStart) {
45
+ await new Promise((resolve) => setTimeout(resolve, 1000));
46
+ }
47
+ // Call the LLM function which will handle streaming, incremental file updates, and Prettier formatting
48
+ const result = await llmFunction(fullPrompt);
49
+ runCode();
50
+ // 4. Capture the state of files after editing and formatting, then generate diff
51
+ const afterFiles = createFilesSnapshot(shareDBDoc.data.files);
52
+ const diffData = generateFilesUnifiedDiff(beforeFiles, afterFiles);
53
+ return {
54
+ content: result.content,
55
+ generationId: result.generationId,
56
+ diffData,
57
+ };
58
+ };
@@ -0,0 +1,494 @@
1
+ import { dateToTimestamp } from '@vizhub/viz-utils';
2
+ import { randomId } from '../randomId.js';
3
+ import { diff } from '../ot.js';
4
+ /**
5
+ * Ensures the chats object exists in the ShareDB document
6
+ */
7
+ export const ensureChatsExist = (shareDBDoc) => {
8
+ if (!shareDBDoc.data.chats) {
9
+ const op = diff(shareDBDoc.data, {
10
+ ...shareDBDoc.data,
11
+ chats: {},
12
+ });
13
+ shareDBDoc.submitOp(op);
14
+ }
15
+ };
16
+ /**
17
+ * Ensures a specific chat exists in the ShareDB document
18
+ */
19
+ export const ensureChatExists = (shareDBDoc, chatId) => {
20
+ if (!shareDBDoc.data.chats[chatId]) {
21
+ const op = diff(shareDBDoc.data, {
22
+ ...shareDBDoc.data,
23
+ chats: {
24
+ ...shareDBDoc.data.chats,
25
+ [chatId]: {
26
+ id: chatId,
27
+ messages: [],
28
+ createdAt: dateToTimestamp(new Date()),
29
+ updatedAt: dateToTimestamp(new Date()),
30
+ },
31
+ },
32
+ });
33
+ shareDBDoc.submitOp(op);
34
+ }
35
+ };
36
+ /**
37
+ * Adds a user message to the chat
38
+ * Clears old messages to reflect that each prompt is a self-contained code transformation
39
+ */
40
+ export const addUserMessage = (shareDBDoc, chatId, content) => {
41
+ const userMessage = {
42
+ id: `user-${Date.now()}`,
43
+ role: 'user',
44
+ content: content,
45
+ timestamp: dateToTimestamp(new Date()),
46
+ };
47
+ const userMessageOp = diff(shareDBDoc.data, {
48
+ ...shareDBDoc.data,
49
+ chats: {
50
+ ...shareDBDoc.data.chats,
51
+ [chatId]: {
52
+ ...shareDBDoc.data.chats[chatId],
53
+ messages: [userMessage], // Replace old messages with just the new user message
54
+ updatedAt: dateToTimestamp(new Date()),
55
+ },
56
+ },
57
+ });
58
+ shareDBDoc.submitOp(userMessageOp);
59
+ return userMessage;
60
+ };
61
+ const DEBUG = false;
62
+ /**
63
+ * Updates AI status in the chat
64
+ */
65
+ export const updateAIStatus = (shareDBDoc, chatId, status) => {
66
+ DEBUG &&
67
+ console.log(`ChatOperations: updateAIStatus called with status: "${status}" for chatId: ${chatId}`);
68
+ const op = diff(shareDBDoc.data, {
69
+ ...shareDBDoc.data,
70
+ chats: {
71
+ ...shareDBDoc.data.chats,
72
+ [chatId]: {
73
+ ...shareDBDoc.data.chats[chatId],
74
+ aiStatus: status,
75
+ },
76
+ },
77
+ });
78
+ DEBUG &&
79
+ console.log(`ChatOperations: Submitting operation for status update:`, op);
80
+ shareDBDoc.submitOp(op);
81
+ DEBUG &&
82
+ console.log(`ChatOperations: Status update operation submitted successfully`);
83
+ };
84
+ /**
85
+ * Updates AI scratchpad content
86
+ */
87
+ export const updateAIScratchpad = (shareDBDoc, chatId, content) => {
88
+ const op = diff(shareDBDoc.data, {
89
+ ...shareDBDoc.data,
90
+ chats: {
91
+ ...shareDBDoc.data.chats,
92
+ [chatId]: {
93
+ ...shareDBDoc.data.chats[chatId],
94
+ aiScratchpad: content,
95
+ },
96
+ },
97
+ });
98
+ // op is `null` if there are no changes
99
+ // This can happen if the content is the same as before
100
+ // In that case, we don't need to submit an operation
101
+ if (op) {
102
+ shareDBDoc.submitOp(op);
103
+ }
104
+ };
105
+ /**
106
+ * Clears AI scratchpad and updates status
107
+ */
108
+ export const clearAIScratchpadAndStatus = (shareDBDoc, chatId, status) => {
109
+ const op = diff(shareDBDoc.data, {
110
+ ...shareDBDoc.data,
111
+ chats: {
112
+ ...shareDBDoc.data.chats,
113
+ [chatId]: {
114
+ ...shareDBDoc.data.chats[chatId],
115
+ aiScratchpad: undefined,
116
+ aiStatus: status,
117
+ },
118
+ },
119
+ });
120
+ shareDBDoc.submitOp(op);
121
+ };
122
+ /**
123
+ * Creates an initial empty AI message for streaming
124
+ */
125
+ export const createAIMessage = (shareDBDoc, chatId) => {
126
+ const aiMessage = {
127
+ id: `assistant-${Date.now()}`,
128
+ role: 'assistant',
129
+ content: '',
130
+ timestamp: dateToTimestamp(new Date()),
131
+ };
132
+ const messageOp = diff(shareDBDoc.data, {
133
+ ...shareDBDoc.data,
134
+ chats: {
135
+ ...shareDBDoc.data.chats,
136
+ [chatId]: {
137
+ ...shareDBDoc.data.chats[chatId],
138
+ messages: [
139
+ ...shareDBDoc.data.chats[chatId].messages,
140
+ aiMessage,
141
+ ],
142
+ updatedAt: dateToTimestamp(new Date()),
143
+ },
144
+ },
145
+ });
146
+ shareDBDoc.submitOp(messageOp);
147
+ return aiMessage.id;
148
+ };
149
+ /**
150
+ * Updates the content of an AI message during streaming
151
+ */
152
+ export const updateAIMessageContent = (shareDBDoc, chatId, messageId, content) => {
153
+ const chat = shareDBDoc.data.chats[chatId];
154
+ const messageIndex = chat.messages.findIndex((msg) => msg.id === messageId);
155
+ if (messageIndex === -1) {
156
+ console.warn(`AI message with id ${messageId} not found`);
157
+ return;
158
+ }
159
+ const updatedMessages = [...chat.messages];
160
+ updatedMessages[messageIndex] = {
161
+ ...updatedMessages[messageIndex],
162
+ content,
163
+ };
164
+ const messageOp = diff(shareDBDoc.data, {
165
+ ...shareDBDoc.data,
166
+ chats: {
167
+ ...shareDBDoc.data.chats,
168
+ [chatId]: {
169
+ ...chat,
170
+ messages: updatedMessages,
171
+ updatedAt: dateToTimestamp(new Date()),
172
+ },
173
+ },
174
+ });
175
+ shareDBDoc.submitOp(messageOp);
176
+ };
177
+ /**
178
+ * Sets the AI status for a chat
179
+ */
180
+ export const setAIStatus = (shareDBDoc, chatId, status) => {
181
+ const op = diff(shareDBDoc.data, {
182
+ ...shareDBDoc.data,
183
+ chats: {
184
+ ...shareDBDoc.data.chats,
185
+ [chatId]: {
186
+ ...shareDBDoc.data.chats[chatId],
187
+ aiStatus: status,
188
+ updatedAt: dateToTimestamp(new Date()),
189
+ },
190
+ },
191
+ });
192
+ shareDBDoc.submitOp(op);
193
+ };
194
+ /**
195
+ * Finalizes an AI message by clearing temporary fields
196
+ */
197
+ export const finalizeAIMessage = (shareDBDoc, chatId) => {
198
+ const op = diff(shareDBDoc.data, {
199
+ ...shareDBDoc.data,
200
+ chats: {
201
+ ...shareDBDoc.data.chats,
202
+ [chatId]: {
203
+ ...shareDBDoc.data.chats[chatId],
204
+ aiScratchpad: undefined,
205
+ aiStatus: undefined,
206
+ updatedAt: dateToTimestamp(new Date()),
207
+ },
208
+ },
209
+ });
210
+ shareDBDoc.submitOp(op);
211
+ };
212
+ /**
213
+ * Adds diff data to the most recent AI message
214
+ */
215
+ export const addDiffToAIMessage = (shareDBDoc, chatId, diffData, beforeCommitId) => {
216
+ const chat = shareDBDoc.data.chats[chatId];
217
+ const messages = [...chat.messages];
218
+ // Find the most recent AI message
219
+ const lastAIMessageIndex = messages.length - 1;
220
+ if (lastAIMessageIndex >= 0 &&
221
+ messages[lastAIMessageIndex].role === 'assistant') {
222
+ const newMessage = {
223
+ ...messages[lastAIMessageIndex],
224
+ diffData,
225
+ ...(beforeCommitId && { beforeCommitId }), // Add beforeCommitId for VizHub integration
226
+ };
227
+ // Use type assertion to extend the message with diffData
228
+ messages[lastAIMessageIndex] = newMessage;
229
+ const messageOp = diff(shareDBDoc.data, {
230
+ ...shareDBDoc.data,
231
+ chats: {
232
+ ...shareDBDoc.data.chats,
233
+ [chatId]: {
234
+ ...chat,
235
+ messages,
236
+ updatedAt: dateToTimestamp(new Date()),
237
+ },
238
+ },
239
+ });
240
+ shareDBDoc.submitOp(messageOp);
241
+ }
242
+ };
243
+ /**
244
+ * Adds an AI response message to the chat (legacy function, kept for compatibility)
245
+ */
246
+ export const addAIMessage = (shareDBDoc, chatId, content) => {
247
+ const aiResponse = {
248
+ id: Date.now() + 1,
249
+ role: 'assistant',
250
+ content: content || 'AI edit completed successfully.',
251
+ timestamp: dateToTimestamp(new Date()),
252
+ };
253
+ const messageOp = diff(shareDBDoc.data, {
254
+ ...shareDBDoc.data,
255
+ chats: {
256
+ ...shareDBDoc.data.chats,
257
+ [chatId]: {
258
+ ...shareDBDoc.data.chats[chatId],
259
+ messages: [
260
+ ...shareDBDoc.data.chats[chatId].messages,
261
+ aiResponse,
262
+ ],
263
+ updatedAt: dateToTimestamp(new Date()),
264
+ aiStatus: undefined,
265
+ },
266
+ },
267
+ });
268
+ shareDBDoc.submitOp(messageOp);
269
+ return aiResponse;
270
+ };
271
+ /**
272
+ * Updates files in the ShareDB document
273
+ */
274
+ export const updateFiles = (shareDBDoc, files) => {
275
+ const filesOp = diff(shareDBDoc.data, {
276
+ ...shareDBDoc.data,
277
+ files,
278
+ });
279
+ DEBUG && console.log('updateFiles op:');
280
+ DEBUG && console.log(JSON.stringify(filesOp, null, 2));
281
+ shareDBDoc.submitOp(filesOp);
282
+ return filesOp;
283
+ };
284
+ /**
285
+ * Finds a file ID by searching for a matching file name
286
+ */
287
+ export const resolveFileId = (fileName, shareDBDoc) => {
288
+ const files = shareDBDoc.data.files;
289
+ // Search through all files to find matching name
290
+ for (const [fileId, file] of Object.entries(files)) {
291
+ if (file.name === fileName) {
292
+ return fileId;
293
+ }
294
+ }
295
+ // If file doesn't exist, return null
296
+ return null;
297
+ };
298
+ /**
299
+ * Creates a new file with a random ID
300
+ */
301
+ export const createNewFile = (shareDBDoc, fileName) => {
302
+ // Generate a new random file ID
303
+ const newFileId = randomId();
304
+ const newState = {
305
+ ...shareDBDoc.data,
306
+ files: {
307
+ ...shareDBDoc.data.files,
308
+ [newFileId]: {
309
+ name: fileName,
310
+ text: '',
311
+ },
312
+ },
313
+ };
314
+ const op = diff(shareDBDoc.data, newState);
315
+ shareDBDoc.submitOp(op);
316
+ return newFileId;
317
+ };
318
+ // ============================================================================
319
+ // Streaming Chat Operations
320
+ // ============================================================================
321
+ /**
322
+ * Creates a streaming AI message with events array
323
+ */
324
+ export const createStreamingAIMessage = (shareDBDoc, chatId) => {
325
+ const aiMessage = {
326
+ id: `assistant-${Date.now()}`,
327
+ role: 'assistant',
328
+ content: '',
329
+ timestamp: dateToTimestamp(new Date()),
330
+ streamingEvents: [],
331
+ isProgressive: true,
332
+ };
333
+ const messageOp = diff(shareDBDoc.data, {
334
+ ...shareDBDoc.data,
335
+ chats: {
336
+ ...shareDBDoc.data.chats,
337
+ [chatId]: {
338
+ ...shareDBDoc.data.chats[chatId],
339
+ messages: [
340
+ ...shareDBDoc.data.chats[chatId].messages,
341
+ aiMessage,
342
+ ],
343
+ updatedAt: dateToTimestamp(new Date()),
344
+ isStreaming: true,
345
+ },
346
+ },
347
+ });
348
+ shareDBDoc.submitOp(messageOp);
349
+ return aiMessage.id;
350
+ };
351
+ /**
352
+ * Adds a streaming event to the most recent AI message
353
+ */
354
+ export const addStreamingEvent = (shareDBDoc, chatId, event) => {
355
+ DEBUG &&
356
+ console.log(`ChatOperations: Adding streaming event:`, event);
357
+ const chat = shareDBDoc.data.chats[chatId];
358
+ const messages = [...chat.messages];
359
+ const lastMessageIndex = messages.length - 1;
360
+ if (lastMessageIndex >= 0 &&
361
+ messages[lastMessageIndex].role === 'assistant') {
362
+ const lastMessage = messages[lastMessageIndex];
363
+ const updatedEvents = [
364
+ ...(lastMessage.streamingEvents || []),
365
+ event,
366
+ ];
367
+ messages[lastMessageIndex] = {
368
+ ...lastMessage,
369
+ streamingEvents: updatedEvents,
370
+ };
371
+ const messageOp = diff(shareDBDoc.data, {
372
+ ...shareDBDoc.data,
373
+ chats: {
374
+ ...shareDBDoc.data.chats,
375
+ [chatId]: {
376
+ ...chat,
377
+ messages,
378
+ updatedAt: dateToTimestamp(new Date()),
379
+ },
380
+ },
381
+ });
382
+ shareDBDoc.submitOp(messageOp);
383
+ }
384
+ };
385
+ /**
386
+ * Updates streaming status for a chat
387
+ */
388
+ export const updateStreamingStatus = (shareDBDoc, chatId, status, isStreaming = true) => {
389
+ DEBUG &&
390
+ console.log(`ChatOperations: Updating streaming status: "${status}"`);
391
+ const op = diff(shareDBDoc.data, {
392
+ ...shareDBDoc.data,
393
+ chats: {
394
+ ...shareDBDoc.data.chats,
395
+ [chatId]: {
396
+ ...shareDBDoc.data.chats[chatId],
397
+ currentStatus: status,
398
+ isStreaming,
399
+ updatedAt: dateToTimestamp(new Date()),
400
+ },
401
+ },
402
+ });
403
+ shareDBDoc.submitOp(op);
404
+ };
405
+ /**
406
+ * Finalizes streaming message and clears streaming state
407
+ */
408
+ export const finalizeStreamingMessage = (shareDBDoc, chatId) => {
409
+ DEBUG &&
410
+ console.log(`ChatOperations: Finalizing streaming message`);
411
+ const chat = shareDBDoc.data.chats[chatId];
412
+ const messages = [...chat.messages];
413
+ const lastMessageIndex = messages.length - 1;
414
+ if (lastMessageIndex >= 0 &&
415
+ messages[lastMessageIndex].role === 'assistant') {
416
+ const lastMessage = messages[lastMessageIndex];
417
+ messages[lastMessageIndex] = {
418
+ ...lastMessage,
419
+ isComplete: true,
420
+ };
421
+ const messageOp = diff(shareDBDoc.data, {
422
+ ...shareDBDoc.data,
423
+ chats: {
424
+ ...shareDBDoc.data.chats,
425
+ [chatId]: {
426
+ ...chat,
427
+ messages,
428
+ currentStatus: 'Done',
429
+ isStreaming: false,
430
+ updatedAt: dateToTimestamp(new Date()),
431
+ },
432
+ },
433
+ });
434
+ shareDBDoc.submitOp(messageOp);
435
+ }
436
+ };
437
+ // /**
438
+ // * Ensures a file exists, creating it if necessary
439
+ // */
440
+ // export const ensureFileExists = (shareDBDoc, fileName) => {
441
+ // let fileId = resolveFileId(fileName, shareDBDoc);
442
+ // if (!fileId) {
443
+ // // File doesn't exist, create it
444
+ // fileId = createNewFile(shareDBDoc, fileName);
445
+ // }
446
+ // return fileId;
447
+ // };
448
+ // /**
449
+ // * Clears the content of a file
450
+ // */
451
+ // export const clearFileContent = (
452
+ // shareDBDoc: ShareDBDoc<VizContent>,
453
+ // fileId: VizFileId,
454
+ // ) => {
455
+ // const currentFile = shareDBDoc.data.files[fileId];
456
+ // if (currentFile && currentFile.text) {
457
+ // // Clear the file content
458
+ // const newState = {
459
+ // ...shareDBDoc.data,
460
+ // files: {
461
+ // ...shareDBDoc.data.files,
462
+ // [fileId]: {
463
+ // ...currentFile,
464
+ // text: '',
465
+ // },
466
+ // },
467
+ // };
468
+ // const op = diff(shareDBDoc.data, newState);
469
+ // shareDBDoc.submitOp(op);
470
+ // }
471
+ // };
472
+ // /**
473
+ // * Appends a line to a file using OT operations
474
+ // */
475
+ // export const appendLineToFile = (
476
+ // shareDBDoc: ShareDBDoc<VizContent>,
477
+ // fileId: VizFileId,
478
+ // line: string,
479
+ // ) => {
480
+ // const currentFile = shareDBDoc.data.files[fileId];
481
+ // const currentContent = currentFile?.text || '';
482
+ // const newContent = currentContent + line + '\n';
483
+ // const newDocState = {
484
+ // ...shareDBDoc.data,
485
+ // files: {
486
+ // ...shareDBDoc.data.files,
487
+ // [fileId]: {
488
+ // ...currentFile,
489
+ // text: newContent,
490
+ // },
491
+ // },
492
+ // };
493
+ // shareDBDoc.submitOp(diff(shareDBDoc.data, newDocState));
494
+ // };
@@ -0,0 +1,49 @@
1
+ import { dateToTimestamp } from '@vizhub/viz-utils';
2
+ import { diff } from '../ot.js';
3
+ /**
4
+ * Handles errors by adding an error message to the chat and clearing AI state
5
+ */
6
+ export const handleError = (shareDBDoc, chatId, error, res) => {
7
+ console.error('[handleAIChatMessage] error:', error);
8
+ // Clear scratchpad and add error message on error
9
+ try {
10
+ const errorResponse = {
11
+ id: `error-${Date.now()}`,
12
+ role: 'assistant',
13
+ content: 'Sorry, I encountered an error while processing your message. Please try again.',
14
+ timestamp: dateToTimestamp(new Date()),
15
+ };
16
+ const errorOp = diff(shareDBDoc.data, {
17
+ ...shareDBDoc.data,
18
+ chats: {
19
+ ...shareDBDoc.data.chats,
20
+ [chatId]: {
21
+ ...shareDBDoc.data.chats[chatId],
22
+ messages: [
23
+ ...shareDBDoc.data.chats[chatId].messages,
24
+ errorResponse,
25
+ ],
26
+ aiScratchpad: undefined,
27
+ aiStatus: undefined,
28
+ updatedAt: dateToTimestamp(new Date()),
29
+ },
30
+ },
31
+ });
32
+ shareDBDoc.submitOp(errorOp);
33
+ }
34
+ catch (opError) {
35
+ console.error('[handleAIChatMessage] error handling error state:', opError);
36
+ }
37
+ if (res) {
38
+ res.status(500).json({
39
+ error: 'Internal server error',
40
+ message: error.message,
41
+ });
42
+ }
43
+ };
44
+ /**
45
+ * Handles errors in background processing (without HTTP response)
46
+ */
47
+ export const handleBackgroundError = (shareDBDoc, chatId, error) => {
48
+ handleError(shareDBDoc, chatId, error, null);
49
+ };
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @vizhub/llm-streaming-server
3
+ *
4
+ * Server-side library for streaming LLM responses with ShareDB integration.
5
+ * This module provides functionality for:
6
+ * - Creating and managing LLM streaming functions
7
+ * - Performing AI-assisted code editing
8
+ * - Managing chat operations with ShareDB
9
+ * - Validating requests and handling errors
10
+ */
11
+ // Core LLM streaming functionality
12
+ export { createLLMFunction } from './llmStreaming.js';
13
+ // AI editing operations
14
+ export { performAIChat, performAIEditing, } from './aiEditing.js';
15
+ // ShareDB chat operations
16
+ export { ensureChatsExist, ensureChatExists, addUserMessage, updateAIStatus, updateAIScratchpad, clearAIScratchpadAndStatus, createAIMessage, updateAIMessageContent, setAIStatus, finalizeAIMessage, addDiffToAIMessage, addAIMessage, updateFiles, resolveFileId, createNewFile, createStreamingAIMessage, addStreamingEvent, updateStreamingStatus, finalizeStreamingMessage, } from './chatOperations.js';
17
+ // Request validation
18
+ export { validateRequest } from './validation.js';
19
+ // Error handling
20
+ export { handleError, handleBackgroundError, } from './errorHandling.js';