vzcode 2.18.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 (57) hide show
  1. package/README.md +359 -0
  2. package/dist/assets/index-CfDs-dAu.js +476 -0
  3. package/dist/assets/{index-BvGPtSrr.css → index-fSroLVgi.css} +1 -1
  4. package/dist/assets/{worker-y5jhqCTR.js → worker-Cm3I3tnR.js} +57 -57
  5. package/dist/assets/{worker-ClF0pBYr.js → worker-KiuLM-X4.js} +71 -71
  6. package/dist/index.html +2 -2
  7. package/dist/llm-streaming-server/aiEditing.js +58 -0
  8. package/dist/llm-streaming-server/chatOperations.js +494 -0
  9. package/dist/llm-streaming-server/errorHandling.js +49 -0
  10. package/dist/llm-streaming-server/index.js +20 -0
  11. package/dist/llm-streaming-server/llmStreaming.js +265 -0
  12. package/dist/llm-streaming-server/validation.js +19 -0
  13. package/dist/server/aiChatHandler/chatOperations.js +3 -4
  14. package/dist/server/aiChatHandler/index.js +5 -5
  15. package/dist/server/aiChatHandler/llmStreaming.js +57 -4
  16. package/dist/server/prettier.js +18 -16
  17. package/dist/utils/fileDiff.js +25 -1
  18. package/package.json +45 -45
  19. package/src/client/CodeEditor/getOrCreateEditor.tsx +272 -258
  20. package/src/client/CodeEditor/index.tsx +3 -3
  21. package/src/client/VZRight.tsx +4 -0
  22. package/src/client/VZSidebar/AIChat/ChatInput.tsx +1 -1
  23. package/src/client/VZSidebar/AIChat/DiffView.scss +37 -1
  24. package/src/client/VZSidebar/AIChat/DiffView.tsx +55 -16
  25. package/src/client/VZSidebar/AIChat/styles.scss +38 -0
  26. package/src/client/VZSidebar/FileTypeIcon.tsx +1 -0
  27. package/src/client/VZSidebar/index.tsx +1 -1
  28. package/src/client/featureFlags.ts +7 -0
  29. package/src/llm-streaming-server/README.md +71 -0
  30. package/src/llm-streaming-server/aiEditing.ts +102 -0
  31. package/src/llm-streaming-server/chatOperations.ts +655 -0
  32. package/src/llm-streaming-server/errorHandling.ts +66 -0
  33. package/src/llm-streaming-server/index.ts +51 -0
  34. package/src/llm-streaming-server/llmStreaming.ts +403 -0
  35. package/src/llm-streaming-server/validation.ts +24 -0
  36. package/src/llm-streaming-ui/README.md +103 -0
  37. package/src/llm-streaming-ui/components/ChatInput.tsx +237 -0
  38. package/src/llm-streaming-ui/components/DiffView.scss +173 -0
  39. package/src/llm-streaming-ui/components/DiffView.tsx +236 -0
  40. package/src/llm-streaming-ui/components/FileEditingIndicator.tsx +89 -0
  41. package/src/llm-streaming-ui/components/IndividualFileDiff.tsx +86 -0
  42. package/src/llm-streaming-ui/components/JumpToLatestButton.tsx +64 -0
  43. package/src/llm-streaming-ui/components/Message.tsx +145 -0
  44. package/src/llm-streaming-ui/components/MessageList.tsx +241 -0
  45. package/src/llm-streaming-ui/components/ThinkingScratchpad.tsx +42 -0
  46. package/src/llm-streaming-ui/components/TypingIndicator.tsx +19 -0
  47. package/src/llm-streaming-ui/components/index.tsx +388 -0
  48. package/src/llm-streaming-ui/components/styles.scss +831 -0
  49. package/src/llm-streaming-ui/components/useSpeechRecognition.ts +116 -0
  50. package/src/llm-streaming-ui/index.ts +34 -0
  51. package/src/server/aiChatHandler/chatOperations.ts +3 -4
  52. package/src/server/aiChatHandler/index.ts +5 -5
  53. package/src/server/aiChatHandler/llmStreaming.ts +87 -4
  54. package/src/server/prettier.ts +30 -31
  55. package/src/types.ts +5 -0
  56. package/src/utils/fileDiff.ts +36 -2
  57. package/dist/assets/index-DuDXdJWC.js +0 -477
@@ -0,0 +1,265 @@
1
+ import OpenAI from 'openai';
2
+ import { parseMarkdownFiles, StreamingMarkdownParser, } from 'llm-code-format';
3
+ import { mergeFileChanges } from 'editcodewithai';
4
+ import { updateFiles, updateAIScratchpad, createStreamingAIMessage, addStreamingEvent, updateStreamingStatus, finalizeStreamingMessage, } from './chatOperations.js';
5
+ import { formatFiles } from '../server/prettier.js';
6
+ // Verbose logs
7
+ const DEBUG = false;
8
+ // Useful for testing/debugging the streaming behavior
9
+ const slowMode = false;
10
+ // If the `EMIT_FIXTURES` variable is true,
11
+ // then an output file in the `test/fixtures` folder
12
+ // with the before and after file states for testing purposes.
13
+ // This feeds into tests in codemirror-ot.
14
+ const EMIT_FIXTURES = false;
15
+ /**
16
+ * Creates and configures the LLM function for streaming with reasoning tokens
17
+ */
18
+ export const createLLMFunction = ({ shareDBDoc, chatId,
19
+ // Feature flag to enable/disable reasoning tokens.
20
+ // When false, reasoning tokens are not requested from the API
21
+ // and reasoning content is not processed in the streaming response.
22
+ enableReasoningTokens = false, model, aiRequestOptions, }) => {
23
+ return async (fullPrompt) => {
24
+ // Create OpenRouter client for reasoning token support
25
+ const openRouterClient = new OpenAI({
26
+ apiKey: process.env.VZCODE_EDIT_WITH_AI_API_KEY,
27
+ baseURL: process.env.VZCODE_EDIT_WITH_AI_BASE_URL ||
28
+ 'https://openrouter.ai/api/v1',
29
+ defaultHeaders: {
30
+ 'HTTP-Referer': 'https://vizhub.com',
31
+ 'X-Title': 'VizHub',
32
+ },
33
+ });
34
+ let fullContent = '';
35
+ let generationId = '';
36
+ let currentEditingFileName = null;
37
+ let accumulatedTextChunk = '';
38
+ let currentFileContent = '';
39
+ // Create streaming AI message
40
+ createStreamingAIMessage(shareDBDoc, chatId);
41
+ // Set initial content generation status
42
+ updateStreamingStatus(shareDBDoc, chatId, 'Formulating a plan...');
43
+ // Helper to get original file content
44
+ const getOriginalFileContent = (fileName) => {
45
+ const files = shareDBDoc.data.files;
46
+ for (const file of Object.values(files)) {
47
+ if (file.name === fileName) {
48
+ return file.text || '';
49
+ }
50
+ }
51
+ return '';
52
+ };
53
+ // Helper to emit text chunk when accumulated
54
+ const emitTextChunk = async () => {
55
+ if (accumulatedTextChunk.trim()) {
56
+ DEBUG &&
57
+ console.log('LLMStreaming: Emitting text chunk:', accumulatedTextChunk.substring(0, 100) + '...');
58
+ await addStreamingEvent(shareDBDoc, chatId, {
59
+ type: 'text_chunk',
60
+ content: accumulatedTextChunk,
61
+ timestamp: Date.now(),
62
+ });
63
+ accumulatedTextChunk = '';
64
+ }
65
+ };
66
+ // Helper to complete file editing
67
+ const completeFileEditing = async (fileName) => {
68
+ if (fileName) {
69
+ DEBUG &&
70
+ console.log(`LLMStreaming: Completing file editing for ${fileName}`);
71
+ await addStreamingEvent(shareDBDoc, chatId, {
72
+ type: 'file_complete',
73
+ fileName,
74
+ beforeContent: getOriginalFileContent(fileName),
75
+ afterContent: currentFileContent,
76
+ timestamp: Date.now(),
77
+ });
78
+ currentFileContent = '';
79
+ }
80
+ };
81
+ // Define callbacks for streaming parser
82
+ const callbacks = {
83
+ onFileNameChange: async (fileName, format) => {
84
+ DEBUG &&
85
+ console.log(`LLMStreaming: File changed to: ${fileName} (${format})`);
86
+ // Emit any accumulated text chunk first
87
+ await emitTextChunk();
88
+ // Complete previous file if any
89
+ if (currentEditingFileName) {
90
+ await completeFileEditing(currentEditingFileName);
91
+ }
92
+ // Start new file
93
+ currentEditingFileName = fileName;
94
+ currentFileContent = '';
95
+ // Emit file start event
96
+ await addStreamingEvent(shareDBDoc, chatId, {
97
+ type: 'file_start',
98
+ fileName,
99
+ timestamp: Date.now(),
100
+ });
101
+ // Update status
102
+ updateStreamingStatus(shareDBDoc, chatId, `Editing ${fileName}...`);
103
+ },
104
+ onCodeLine: async (line) => {
105
+ DEBUG && console.log(`Code line: ${line}`);
106
+ // Accumulate code content for the current file
107
+ currentFileContent += line + '\n';
108
+ },
109
+ onNonCodeLine: async (line) => {
110
+ DEBUG && console.log(`Non-code line: ${line}`);
111
+ // Accumulate non-code content as text chunk
112
+ if (line.trim() !== '') {
113
+ accumulatedTextChunk += line + '\n';
114
+ // Update status for subsequent non-code chunks
115
+ if (firstNonCodeChunkProcessed) {
116
+ updateStreamingStatus(shareDBDoc, chatId, 'Describing changes...');
117
+ }
118
+ else {
119
+ firstNonCodeChunkProcessed = true;
120
+ }
121
+ }
122
+ },
123
+ onFileDelete: async (fileName) => {
124
+ DEBUG &&
125
+ console.log(`LLMStreaming: File marked for deletion: ${fileName}`);
126
+ // Emit any accumulated text chunk first
127
+ await emitTextChunk();
128
+ // Complete previous file if any
129
+ if (currentEditingFileName) {
130
+ await completeFileEditing(currentEditingFileName);
131
+ }
132
+ // Reset current editing state
133
+ currentEditingFileName = null;
134
+ currentFileContent = '';
135
+ // Emit file delete event
136
+ await addStreamingEvent(shareDBDoc, chatId, {
137
+ type: 'file_delete',
138
+ fileName,
139
+ timestamp: Date.now(),
140
+ });
141
+ // Update status
142
+ updateStreamingStatus(shareDBDoc, chatId, `Deleting ${fileName}...`);
143
+ },
144
+ };
145
+ const parser = new StreamingMarkdownParser(callbacks);
146
+ const chunks = [];
147
+ let reasoningContent = '';
148
+ // Stream the response with reasoning tokens
149
+ const modelName = model ||
150
+ process.env.VZCODE_EDIT_WITH_AI_MODEL_NAME ||
151
+ 'anthropic/claude-3.5-sonnet';
152
+ // Configure reasoning tokens based on enableReasoningTokens flag
153
+ const requestConfig = {
154
+ model: modelName,
155
+ messages: [{ role: 'user', content: fullPrompt }],
156
+ usage: { include: true },
157
+ stream: true,
158
+ ...aiRequestOptions,
159
+ };
160
+ // Only include reasoning configuration if reasoning tokens are enabled
161
+ if (enableReasoningTokens) {
162
+ requestConfig.reasoning = {
163
+ effort: 'low',
164
+ exclude: false,
165
+ };
166
+ }
167
+ const stream = await openRouterClient.chat.completions.create(requestConfig);
168
+ let reasoningStarted = false;
169
+ let contentStarted = false;
170
+ let firstNonCodeChunkProcessed = false;
171
+ for await (const chunk of stream) {
172
+ if (slowMode) {
173
+ await new Promise((resolve) => setTimeout(resolve, 500));
174
+ }
175
+ const delta = chunk.choices[0]?.delta; // Type assertion for OpenRouter-specific reasoning fields
176
+ if (delta?.reasoning && enableReasoningTokens) {
177
+ // Handle reasoning tokens (thinking) - only if enabled
178
+ if (!reasoningStarted) {
179
+ reasoningStarted = true;
180
+ updateStreamingStatus(shareDBDoc, chatId, 'Thinking...');
181
+ }
182
+ reasoningContent += delta.reasoning;
183
+ updateAIScratchpad(shareDBDoc, chatId, reasoningContent);
184
+ }
185
+ else if (delta?.content) {
186
+ // Handle regular content tokens
187
+ if (!contentStarted) {
188
+ contentStarted = true;
189
+ if (reasoningStarted) {
190
+ // Clear reasoning when content starts
191
+ updateAIScratchpad(shareDBDoc, chatId, '');
192
+ }
193
+ // // Set initial content generation status
194
+ // updateStreamingStatus(
195
+ // shareDBDoc,
196
+ // chatId,
197
+ // 'Formulating a plan...',
198
+ // );
199
+ }
200
+ const chunkContent = delta.content;
201
+ chunks.push(chunkContent);
202
+ await parser.processChunk(chunkContent);
203
+ fullContent += chunkContent;
204
+ }
205
+ else if (chunk.usage) {
206
+ // Handle usage information
207
+ DEBUG && console.log('Usage:', chunk.usage);
208
+ }
209
+ if (!generationId && chunk.id) {
210
+ generationId = chunk.id;
211
+ }
212
+ }
213
+ await parser.flushRemaining();
214
+ // Emit any remaining text chunk
215
+ await emitTextChunk();
216
+ // Complete final file if any
217
+ if (currentEditingFileName) {
218
+ await completeFileEditing(currentEditingFileName);
219
+ }
220
+ // // Capture the current state of files before applying changes
221
+ // const beforeFiles = createFilesSnapshot(
222
+ // shareDBDoc.data.files,
223
+ // );
224
+ // Parse the full content to extract file changes
225
+ // export type FileCollection = Record<string, string>;
226
+ const newFilesUnformatted = parseMarkdownFiles(fullContent, 'bold').files;
227
+ // Run Prettier on `newFiles` before applying them,
228
+ // preserving empty files as empty
229
+ // since that is the cue to delete a file.
230
+ const newFilesFormatted = await formatFiles(newFilesUnformatted);
231
+ // Capture the current state of files before applying changes
232
+ let vizFilesBefore;
233
+ if (EMIT_FIXTURES) {
234
+ vizFilesBefore = JSON.parse(JSON.stringify(shareDBDoc.data.files));
235
+ }
236
+ // Apply all the edits at once
237
+ const vizFilesAfter = mergeFileChanges(shareDBDoc.data.files, newFilesFormatted);
238
+ const filesOp = updateFiles(shareDBDoc, vizFilesAfter);
239
+ if (EMIT_FIXTURES) {
240
+ const fs = await import('fs');
241
+ const path = await import('path');
242
+ const testCasesDir = path.resolve(process.cwd(), '../', 'fixtures');
243
+ if (!fs.existsSync(testCasesDir)) {
244
+ fs.mkdirSync(testCasesDir, { recursive: true });
245
+ }
246
+ const timestamp = new Date()
247
+ .toISOString()
248
+ .replace(/[:.]/g, '-');
249
+ const testCasePath = path.join(testCasesDir, `ai-chat-${timestamp}.json`);
250
+ const testCaseData = {
251
+ vizFilesBefore,
252
+ vizFilesAfter,
253
+ filesOp,
254
+ };
255
+ fs.writeFileSync(testCasePath, JSON.stringify(testCaseData, null, 2));
256
+ console.log(`AI chat test case written to ${testCasePath}`);
257
+ }
258
+ // Finalize streaming message
259
+ finalizeStreamingMessage(shareDBDoc, chatId);
260
+ return {
261
+ content: fullContent,
262
+ generationId: generationId,
263
+ };
264
+ };
265
+ };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Validates incoming request data for AI chat messages
3
+ */
4
+ export const validateRequest = (req, res) => {
5
+ const { content, chatId } = req.body;
6
+ if (!content || typeof content !== 'string') {
7
+ res.status(400).json({
8
+ error: 'Invalid request: content is required and must be a string',
9
+ });
10
+ return false;
11
+ }
12
+ if (!chatId || typeof chatId !== 'string') {
13
+ res.status(400).json({
14
+ error: 'Invalid request: chatId is required and must be a string',
15
+ });
16
+ return false;
17
+ }
18
+ return true;
19
+ };
@@ -35,6 +35,7 @@ export const ensureChatExists = (shareDBDoc, chatId) => {
35
35
  };
36
36
  /**
37
37
  * Adds a user message to the chat
38
+ * Clears old messages to reflect that each prompt is a self-contained code transformation
38
39
  */
39
40
  export const addUserMessage = (shareDBDoc, chatId, content) => {
40
41
  const userMessage = {
@@ -49,10 +50,7 @@ export const addUserMessage = (shareDBDoc, chatId, content) => {
49
50
  ...shareDBDoc.data.chats,
50
51
  [chatId]: {
51
52
  ...shareDBDoc.data.chats[chatId],
52
- messages: [
53
- ...shareDBDoc.data.chats[chatId].messages,
54
- userMessage,
55
- ],
53
+ messages: [userMessage], // Replace old messages with just the new user message
56
54
  updatedAt: dateToTimestamp(new Date()),
57
55
  },
58
56
  },
@@ -281,6 +279,7 @@ export const updateFiles = (shareDBDoc, files) => {
281
279
  DEBUG && console.log('updateFiles op:');
282
280
  DEBUG && console.log(JSON.stringify(filesOp, null, 2));
283
281
  shareDBDoc.submitOp(filesOp);
282
+ return filesOp;
284
283
  };
285
284
  /**
286
285
  * Finds a file ID by searching for a matching file name
@@ -1,8 +1,8 @@
1
- import { validateRequest } from './validation.js';
2
- import { ensureChatsExist, ensureChatExists, addUserMessage, setAIStatus, } from './chatOperations.js';
3
- import { createLLMFunction } from './llmStreaming.js';
4
- import { performAIEditing } from './aiEditing.js';
5
- import { handleError, handleBackgroundError, } from './errorHandling.js';
1
+ import { validateRequest } from '../../llm-streaming-server/validation.js';
2
+ import { ensureChatsExist, ensureChatExists, addUserMessage, setAIStatus, } from '../../llm-streaming-server/chatOperations.js';
3
+ import { createLLMFunction } from '../../llm-streaming-server/llmStreaming.js';
4
+ import { performAIEditing } from '../../llm-streaming-server/aiEditing.js';
5
+ import { handleError, handleBackgroundError, } from '../../llm-streaming-server/errorHandling.js';
6
6
  import { createRunCodeFunction } from '../../runCode.js';
7
7
  import { createSubmitOperation } from '../../submitOperation.js';
8
8
  import { getGenerationMetadata } from 'editcodewithai';
@@ -3,9 +3,15 @@ import { parseMarkdownFiles, StreamingMarkdownParser, } from 'llm-code-format';
3
3
  import { mergeFileChanges } from 'editcodewithai';
4
4
  import { updateFiles, updateAIScratchpad, createStreamingAIMessage, addStreamingEvent, updateStreamingStatus, finalizeStreamingMessage, } from './chatOperations.js';
5
5
  import { formatFiles } from '../prettier.js';
6
+ // Verbose logs
6
7
  const DEBUG = false;
7
8
  // Useful for testing/debugging the streaming behavior
8
9
  const slowMode = false;
10
+ // If the `EMIT_FIXTURES` variable is true,
11
+ // then an output file in the `test/fixtures` folder
12
+ // with the before and after file states for testing purposes.
13
+ // This feeds into tests in codemirror-ot.
14
+ const EMIT_FIXTURES = false;
9
15
  /**
10
16
  * Creates and configures the LLM function for streaming with reasoning tokens
11
17
  */
@@ -59,7 +65,7 @@ enableReasoningTokens = false, model, aiRequestOptions, }) => {
59
65
  };
60
66
  // Helper to complete file editing
61
67
  const completeFileEditing = async (fileName) => {
62
- if (fileName && currentFileContent) {
68
+ if (fileName) {
63
69
  DEBUG &&
64
70
  console.log(`LLMStreaming: Completing file editing for ${fileName}`);
65
71
  await addStreamingEvent(shareDBDoc, chatId, {
@@ -114,6 +120,27 @@ enableReasoningTokens = false, model, aiRequestOptions, }) => {
114
120
  }
115
121
  }
116
122
  },
123
+ onFileDelete: async (fileName) => {
124
+ DEBUG &&
125
+ console.log(`LLMStreaming: File marked for deletion: ${fileName}`);
126
+ // Emit any accumulated text chunk first
127
+ await emitTextChunk();
128
+ // Complete previous file if any
129
+ if (currentEditingFileName) {
130
+ await completeFileEditing(currentEditingFileName);
131
+ }
132
+ // Reset current editing state
133
+ currentEditingFileName = null;
134
+ currentFileContent = '';
135
+ // Emit file delete event
136
+ await addStreamingEvent(shareDBDoc, chatId, {
137
+ type: 'file_delete',
138
+ fileName,
139
+ timestamp: Date.now(),
140
+ });
141
+ // Update status
142
+ updateStreamingStatus(shareDBDoc, chatId, `Deleting ${fileName}...`);
143
+ },
117
144
  };
118
145
  const parser = new StreamingMarkdownParser(callbacks);
119
146
  const chunks = [];
@@ -197,11 +224,37 @@ enableReasoningTokens = false, model, aiRequestOptions, }) => {
197
224
  // Parse the full content to extract file changes
198
225
  // export type FileCollection = Record<string, string>;
199
226
  const newFilesUnformatted = parseMarkdownFiles(fullContent, 'bold').files;
200
- // Run Prettier on `newFiles` before applying them
227
+ // Run Prettier on `newFiles` before applying them,
228
+ // preserving empty files as empty
229
+ // since that is the cue to delete a file.
201
230
  const newFilesFormatted = await formatFiles(newFilesUnformatted);
231
+ // Capture the current state of files before applying changes
232
+ let vizFilesBefore;
233
+ if (EMIT_FIXTURES) {
234
+ vizFilesBefore = JSON.parse(JSON.stringify(shareDBDoc.data.files));
235
+ }
202
236
  // Apply all the edits at once
203
- const mergedChanges = mergeFileChanges(shareDBDoc.data.files, newFilesFormatted);
204
- updateFiles(shareDBDoc, mergedChanges);
237
+ const vizFilesAfter = mergeFileChanges(shareDBDoc.data.files, newFilesFormatted);
238
+ const filesOp = updateFiles(shareDBDoc, vizFilesAfter);
239
+ if (EMIT_FIXTURES) {
240
+ const fs = await import('fs');
241
+ const path = await import('path');
242
+ const testCasesDir = path.resolve(process.cwd(), '../', 'fixtures');
243
+ if (!fs.existsSync(testCasesDir)) {
244
+ fs.mkdirSync(testCasesDir, { recursive: true });
245
+ }
246
+ const timestamp = new Date()
247
+ .toISOString()
248
+ .replace(/[:.]/g, '-');
249
+ const testCasePath = path.join(testCasesDir, `ai-chat-${timestamp}.json`);
250
+ const testCaseData = {
251
+ vizFilesBefore,
252
+ vizFilesAfter,
253
+ filesOp,
254
+ };
255
+ fs.writeFileSync(testCasePath, JSON.stringify(testCaseData, null, 2));
256
+ console.log(`AI chat test case written to ${testCasePath}`);
257
+ }
205
258
  // Finalize streaming message
206
259
  finalizeStreamingMessage(shareDBDoc, chatId);
207
260
  return {
@@ -67,6 +67,8 @@ export const formatFile = async (fileText, fileName) => {
67
67
  return null;
68
68
  }
69
69
  };
70
+ // Keys are file names, values are file text contents
71
+ //export type FileCollection = Record<string, string>;
70
72
  /**
71
73
  * Formats multiple files using Prettier
72
74
  * Only formats files that have supported extensions
@@ -74,24 +76,24 @@ export const formatFile = async (fileText, fileName) => {
74
76
  */
75
77
  export const formatFiles = async (fileCollection) => {
76
78
  const results = {};
77
- const targetFileIds = Object.keys(fileCollection);
79
+ const targetFileNames = Object.keys(fileCollection);
78
80
  // Process files in parallel for better performance
79
- const formatPromises = targetFileIds.map(async (fileId) => {
80
- const fileData = fileCollection[fileId];
81
- if (!fileData)
81
+ const formatPromises = targetFileNames.map(async (fileName) => {
82
+ const fileText = fileCollection[fileName];
83
+ results[fileName] = fileText;
84
+ // Preserve empty files as empty,
85
+ // since this is the cue to delete a file.
86
+ if (!fileText || fileText.trim() === '') {
82
87
  return;
83
- // Handle both FileCollection format and test format
84
- const fileName = typeof fileData === 'string'
85
- ? fileId
86
- : fileData.name;
87
- const fileText = typeof fileData === 'string'
88
- ? fileData
89
- : fileData.text;
90
- if (!fileText)
91
- return;
92
- const formatted = await formatFile(fileText, fileName);
93
- if (formatted !== null && formatted !== fileText) {
94
- results[fileId] = formatted;
88
+ }
89
+ try {
90
+ const formatted = await formatFile(fileText, fileName);
91
+ if (formatted !== null && formatted !== fileText) {
92
+ results[fileName] = formatted;
93
+ }
94
+ }
95
+ catch (error) {
96
+ console.error(`Error formatting ${fileName}:`, error);
95
97
  }
96
98
  });
97
99
  await Promise.all(formatPromises);
@@ -1,4 +1,21 @@
1
1
  import { createTwoFilesPatch } from 'diff';
2
+ // Special marker to indicate a file deletion
3
+ export const FILE_DELETION_MARKER = '__FILE_DELETED__';
4
+ /**
5
+ * Check if a diff string represents a file deletion
6
+ */
7
+ export function isFileDeletion(diffString) {
8
+ return diffString.startsWith(FILE_DELETION_MARKER);
9
+ }
10
+ /**
11
+ * Extract file name from a deletion marker
12
+ */
13
+ export function getDeletedFileName(diffString) {
14
+ if (!isFileDeletion(diffString)) {
15
+ return '';
16
+ }
17
+ return diffString.substring(FILE_DELETION_MARKER.length + 1);
18
+ }
2
19
  /**
3
20
  * Generate a unified diff for a single file using the diff library
4
21
  */
@@ -7,6 +24,10 @@ export function generateFileUnifiedDiff(fileId, fileName, beforeContent, afterCo
7
24
  if (beforeContent === afterContent) {
8
25
  return '';
9
26
  }
27
+ // Handle file deletion case - when file existed before but is now empty/deleted
28
+ if (beforeContent && !afterContent) {
29
+ return `${FILE_DELETION_MARKER}:${fileName}`;
30
+ }
10
31
  // Use the diff library's createTwoFilesPatch function to generate unified diff
11
32
  const unifiedDiff = createTwoFilesPatch(fileName, fileName, beforeContent, afterContent, '', '', { context: 3 });
12
33
  return unifiedDiff;
@@ -60,7 +81,10 @@ export function parseUnifiedDiffStats(unifiedDiff) {
60
81
  }
61
82
  /**
62
83
  * Combine multiple unified diffs into a single diff string
84
+ * Note: File deletion markers are excluded from combination
63
85
  */
64
86
  export function combineUnifiedDiffs(unifiedDiffs) {
65
- return Object.values(unifiedDiffs).join('\n');
87
+ return Object.values(unifiedDiffs)
88
+ .filter((diff) => !isFileDeletion(diff))
89
+ .join('\n');
66
90
  }