vzcode 2.35.0 → 2.36.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 (44) hide show
  1. package/dist/assets/buildWorker-BZlya278.js +687 -0
  2. package/dist/assets/index-Cj-ERpBu.css +1 -0
  3. package/dist/assets/index-DD7vzp4U.js +364 -0
  4. package/dist/assets/{worker-D8p1JlHW.js → worker-1oQYaz-F.js} +251 -251
  5. package/dist/assets/worker-BfgPD8zR.js +125 -0
  6. package/dist/assets/{worker-k7HZ3t-V.js → worker-CoJaqtpi.js} +12 -12
  7. package/dist/index.html +2 -2
  8. package/dist/ot.js +180 -2
  9. package/dist/server/createServer.js +281 -0
  10. package/dist/server/index.js +6 -269
  11. package/package.json +14 -3
  12. package/src/client/CodeEditor/getOrCreateEditor.tsx +0 -14
  13. package/src/client/VZSidebar/AIChatWrapper.tsx +85 -0
  14. package/src/client/VZSidebar/VisualEditor/VisualEditor.tsx +13 -9
  15. package/src/client/VZSidebar/VisualEditor/colorUtils.ts +14 -0
  16. package/src/client/VZSidebar/index.tsx +2 -2
  17. package/src/client/useOpenDirectories.ts +0 -1
  18. package/src/llm-streaming-server/README.md +5 -3
  19. package/src/llm-streaming-ui/README.md +44 -42
  20. package/src/llm-streaming-ui/components/ChatInput.tsx +6 -19
  21. package/src/llm-streaming-ui/components/DiffView.tsx +6 -24
  22. package/src/llm-streaming-ui/components/FileEditingIndicator.tsx +1 -1
  23. package/src/llm-streaming-ui/components/Message.tsx +11 -27
  24. package/src/llm-streaming-ui/components/MessageList.tsx +15 -29
  25. package/src/llm-streaming-ui/components/Spinner.scss +37 -0
  26. package/src/llm-streaming-ui/components/Spinner.tsx +59 -0
  27. package/src/llm-streaming-ui/components/bootstrap.ts +16 -0
  28. package/src/llm-streaming-ui/components/icons.tsx +68 -0
  29. package/src/llm-streaming-ui/components/index.tsx +34 -30
  30. package/src/llm-streaming-ui/index.ts +13 -0
  31. package/src/llm-streaming-ui/props.ts +137 -0
  32. package/src/ot.ts +221 -4
  33. package/src/server/createServer.ts +413 -0
  34. package/src/server/index.ts +8 -333
  35. package/dist/assets/buildWorker-DylWm2VX.js +0 -687
  36. package/dist/assets/index-Dyt9tpmu.css +0 -1
  37. package/dist/assets/index-rg2Zvfo_.js +0 -364
  38. package/dist/assets/worker-b9bkZkXK.js +0 -116
  39. package/src/client/AIAssist/AIAssistCodeMirrorKeyMap.ts +0 -42
  40. package/src/client/AIAssist/generateFilesContext.ts +0 -25
  41. package/src/client/AIAssist/index.ts +0 -2
  42. package/src/client/CodeEditor/InteractiveWidgets/highlightWidgets.ts +0 -79
  43. /package/src/{client → llm-streaming-ui}/hooks/useAutoScroll.ts +0 -0
  44. /package/src/{client → llm-streaming-ui}/utils/scrollUtils.ts +0 -0
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-rg2Zvfo_.js"></script>
24
- <link rel="stylesheet" crossorigin href="/assets/index-Dyt9tpmu.css">
23
+ <script type="module" crossorigin src="/assets/index-DD7vzp4U.js"></script>
24
+ <link rel="stylesheet" crossorigin href="/assets/index-Cj-ERpBu.css">
25
25
  </head>
26
26
  <body>
27
27
  <div id="root"></div>
package/dist/ot.js CHANGED
@@ -8,10 +8,188 @@ import { diff_match_patch as DiffMatchPatch, DIFF_DELETE, DIFF_INSERT, DIFF_EQUA
8
8
  DiffMatchPatch.DIFF_DELETE = DIFF_DELETE;
9
9
  DiffMatchPatch.DIFF_INSERT = DIFF_INSERT;
10
10
  DiffMatchPatch.DIFF_EQUAL = DIFF_EQUAL;
11
- const diffMatchPatch = DiffMatchPatch;
12
11
  export const { json1Presence, textUnicode } = OTJSON1Presence;
13
12
  // The OT type used throughout the codebase.
14
13
  export const otType = json1Presence.type;
15
14
  // Applies an OT op to an object.
16
15
  export const apply = otType.apply;
17
- export const diff = (a, b) => jsondiff(a, b, diffMatchPatch, json1Presence, textUnicode);
16
+ // ---------------------------------------------------------------------------
17
+ // Unicode-safe text diffing
18
+ // ---------------------------------------------------------------------------
19
+ //
20
+ // `json0-ot-diff` asks diff-match-patch for text patches and converts the
21
+ // resulting offsets into `textUnicode` (ot-text-unicode) operations. This is
22
+ // incorrect for text containing astral-plane characters (emoji, etc.):
23
+ //
24
+ // 1. diff-match-patch measures offsets in UTF-16 code units, while
25
+ // ot-text-unicode measures them in Unicode code points.
26
+ // 2. diff-match-patch can split a surrogate pair across diffs (it may treat
27
+ // the high and low halves of an emoji as independent characters).
28
+ //
29
+ // Both produce operations that either fail to apply ("The op is too long for
30
+ // this document", "Invalid offset - splits unicode bytes") or apply
31
+ // incorrectly.
32
+ //
33
+ // The fix: when either string contains astral characters, encode each astral
34
+ // code point as a single unused BMP placeholder before diffing. One UTF-16
35
+ // unit then equals one code point and surrogate pairs can never be split. The
36
+ // generated text operation is decoded back to the original characters.
37
+ // Strings without astral characters keep using the original (correct and
38
+ // faster) code path.
39
+ const hasSurrogates = (value) => /[\uD800-\uDFFF]/.test(value);
40
+ const textDiffMatchPatch = new DiffMatchPatch();
41
+ // State describing the string currently being diffed by json0-ot-diff.
42
+ let currentOldValue = '';
43
+ let currentNewValue = '';
44
+ let pendingTextEdit = false;
45
+ let needsUnicodeSafeDiff = false;
46
+ // `for...of` over a string iterates code points; an astral code point is
47
+ // represented as two UTF-16 code units (i.e. `char.length === 2`).
48
+ const encodeAstralCharacters = (oldValue, newValue) => {
49
+ if (!hasSurrogates(oldValue) &&
50
+ !hasSurrogates(newValue)) {
51
+ return null;
52
+ }
53
+ // BMP characters already used by the input, so placeholders never collide.
54
+ const used = new Set();
55
+ for (const char of oldValue)
56
+ used.add(char);
57
+ for (const char of newValue)
58
+ used.add(char);
59
+ const astralCharacters = new Set();
60
+ for (const char of oldValue) {
61
+ if (char.length === 2)
62
+ astralCharacters.add(char);
63
+ }
64
+ for (const char of newValue) {
65
+ if (char.length === 2)
66
+ astralCharacters.add(char);
67
+ }
68
+ const astralToPlaceholder = new Map();
69
+ const placeholderToAstral = new Map();
70
+ // Assign each distinct astral code point an unused, non-surrogate BMP code
71
+ // point. The BMP has ~63k usable code points, far more than the number of
72
+ // distinct astral characters found in practice.
73
+ let candidate = 0xe000;
74
+ const nextPlaceholder = () => {
75
+ for (let attempts = 0; attempts < 0x10000; attempts++) {
76
+ if (candidate > 0xffff)
77
+ candidate = 0x0020;
78
+ const placeholder = String.fromCharCode(candidate++);
79
+ if (!used.has(placeholder))
80
+ return placeholder;
81
+ }
82
+ throw new Error('Unable to encode astral characters for diffing');
83
+ };
84
+ for (const astral of astralCharacters) {
85
+ const placeholder = nextPlaceholder();
86
+ astralToPlaceholder.set(astral, placeholder);
87
+ placeholderToAstral.set(placeholder, astral);
88
+ }
89
+ const encode = (value) => {
90
+ let encoded = '';
91
+ for (const char of value) {
92
+ encoded +=
93
+ char.length === 2
94
+ ? astralToPlaceholder.get(char)
95
+ : char;
96
+ }
97
+ return encoded;
98
+ };
99
+ const decode = (value) => {
100
+ let decoded = '';
101
+ for (const char of value) {
102
+ decoded += placeholderToAstral.get(char) ?? char;
103
+ }
104
+ return decoded;
105
+ };
106
+ return {
107
+ encodedOldValue: encode(oldValue),
108
+ encodedNewValue: encode(newValue),
109
+ decode,
110
+ };
111
+ };
112
+ // Builds an ot-text-unicode operation from diff-match-patch's diffs. Skips are
113
+ // counted in code points, which (after encoding) equal UTF-16 units.
114
+ const buildTextOp = (oldValue, newValue) => {
115
+ const encoding = encodeAstralCharacters(oldValue, newValue);
116
+ const oldText = encoding
117
+ ? encoding.encodedOldValue
118
+ : oldValue;
119
+ const newText = encoding
120
+ ? encoding.encodedNewValue
121
+ : newValue;
122
+ const decode = encoding
123
+ ? encoding.decode
124
+ : (value) => value;
125
+ const diffs = textDiffMatchPatch.diff_main(oldText, newText);
126
+ const components = [];
127
+ for (const [operation, text] of diffs) {
128
+ if (text.length === 0)
129
+ continue;
130
+ if (operation === DIFF_EQUAL) {
131
+ components.push(text.length);
132
+ }
133
+ else if (operation === DIFF_DELETE) {
134
+ components.push({ d: decode(text) });
135
+ }
136
+ else if (operation === DIFF_INSERT) {
137
+ components.push(decode(text));
138
+ }
139
+ }
140
+ // Canonicalize: merge adjacent skips and drop a trailing skip, as required
141
+ // by ot-text-unicode's op validation.
142
+ const op = [];
143
+ for (const component of components) {
144
+ if (typeof component === 'number') {
145
+ if (component <= 0)
146
+ continue;
147
+ const last = op[op.length - 1];
148
+ if (typeof last === 'number') {
149
+ op[op.length - 1] = last + component;
150
+ }
151
+ else {
152
+ op.push(component);
153
+ }
154
+ }
155
+ else {
156
+ op.push(component);
157
+ }
158
+ }
159
+ while (op.length > 0 &&
160
+ typeof op[op.length - 1] === 'number') {
161
+ op.pop();
162
+ }
163
+ return op;
164
+ };
165
+ class UnicodeSafeDiffMatchPatch extends DiffMatchPatch {
166
+ patch_make(a, b) {
167
+ currentOldValue = a;
168
+ currentNewValue = b;
169
+ pendingTextEdit = true;
170
+ needsUnicodeSafeDiff =
171
+ hasSurrogates(a) || hasSurrogates(b);
172
+ return b === undefined
173
+ ? super.patch_make(a)
174
+ : super.patch_make(a, b);
175
+ }
176
+ }
177
+ // Wrap the json1 type so text edits for strings containing astral characters
178
+ // are built by the unicode-safe routine above. All other operations (and text
179
+ // without astral characters) delegate unchanged.
180
+ const unicodeSafeJson1 = {
181
+ ...json1Presence,
182
+ editOp: (path, type, op) => {
183
+ if (type === textUnicode.type && needsUnicodeSafeDiff) {
184
+ if (pendingTextEdit) {
185
+ pendingTextEdit = false;
186
+ return json1Presence.editOp(path, type, buildTextOp(currentOldValue, currentNewValue));
187
+ }
188
+ // The full text op was already emitted for this string; the
189
+ // remaining edits reported by json0-ot-diff are redundant.
190
+ return json1Presence.editOp(path, type, []);
191
+ }
192
+ return json1Presence.editOp(path, type, op);
193
+ },
194
+ };
195
+ export const diff = (a, b) => jsondiff(a, b, UnicodeSafeDiffMatchPatch, unicodeSafeJson1, textUnicode);
@@ -0,0 +1,281 @@
1
+ import WebSocketJSONStream from '@teamwork/websocket-json-stream';
2
+ import bodyParser from 'body-parser';
3
+ import express from 'express';
4
+ import fs from 'fs';
5
+ import http from 'http';
6
+ import path from 'path';
7
+ import ShareDB from 'sharedb';
8
+ import { fileURLToPath } from 'url';
9
+ import { WebSocketServer } from 'ws';
10
+ import { json1Presence } from '../ot.js';
11
+ import { computeInitialDocument } from './computeInitialDocument.js';
12
+ import { handleAIAssist } from './handleAIAssist.js';
13
+ import { handleAICopilot } from './handleAICopilot.js';
14
+ import { handleAIChatMessage } from './handleAIChatMessage.js';
15
+ import { isDirectory } from './isDirectory.js';
16
+ import { createToken } from './livekit.js';
17
+ import './setupEnv.js';
18
+ // The time in milliseconds by which auto-saving is debounced.
19
+ const autoSaveDebounceTimeMS = 800;
20
+ // The time in milliseconds by which auto-saving is throttled
21
+ // when the user is interacting with the widgets in the editor.
22
+ const throttleTimeMS = 100;
23
+ // The image file utility used when writing files to disk.
24
+ const isImageFile = (fileName) => {
25
+ return (fileName.match(/\.(png|jpg|jpeg|gif|bmp|svg|webp)$/i) !== null);
26
+ };
27
+ /**
28
+ * Creates a VZCode server instance without starting it.
29
+ *
30
+ * Splitting construction from `listen`/`open` makes the server testable
31
+ * in-process (see `test/serverE2E.test.ts`). The production entry point
32
+ * `src/server/index.ts` is a thin wrapper around this factory.
33
+ */
34
+ export const createVZCodeServer = (options = {}) => {
35
+ const cwd = options.cwd ?? process.cwd();
36
+ const autoSave = options.autoSave ?? true;
37
+ // Resolve file names from the ShareDB document against the workspace
38
+ // root, so the server can operate on a directory other than the
39
+ // process's current working directory.
40
+ const resolvePath = (name) => path.resolve(cwd, name);
41
+ const serveStaticDir = options.serveStaticDir === undefined
42
+ ? path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'dist')
43
+ : options.serveStaticDir;
44
+ const initialDocument = computeInitialDocument({
45
+ fullPath: cwd,
46
+ });
47
+ // Register our custom OT type,
48
+ // because it does not ship with ShareDB.
49
+ ShareDB.types.register(json1Presence.type);
50
+ const app = express();
51
+ // Use ShareDB over WebSocket
52
+ const shareDBBackend = new ShareDB({
53
+ // Enable presence
54
+ presence: true,
55
+ doNotForwardSendPresenceErrorsToClient: true,
56
+ });
57
+ const httpServer = http.createServer(app);
58
+ const wss = new WebSocketServer({ server: httpServer });
59
+ wss.on('connection', (ws) => {
60
+ const clientStream = new WebSocketJSONStream(ws);
61
+ shareDBBackend.listen(clientStream);
62
+ // Prevent server crashes on errors.
63
+ clientStream.on('error', (error) => {
64
+ console.log('clientStream error: ' + error.message);
65
+ });
66
+ // Handle errors
67
+ ws.on('error', (error) => {
68
+ console.log('ws error: ' + error.message);
69
+ });
70
+ // Handle disconnections
71
+ ws.on('close', () => {
72
+ clientStream.end();
73
+ });
74
+ });
75
+ // Serve static files
76
+ if (serveStaticDir) {
77
+ app.use(express.static(serveStaticDir));
78
+ }
79
+ // Create the initial "document",
80
+ // which is a representation of files on disk.
81
+ const shareDBConnection = shareDBBackend.connect();
82
+ const shareDBDoc = shareDBConnection.get('documents', '1');
83
+ // The state of the document when files were last auto-saved.
84
+ let previousDocument = initialDocument;
85
+ // Saves the files that changed.
86
+ const save = () => {
87
+ const currentDocument = shareDBDoc.data;
88
+ // Take a look at each file (key) previously and currently.
89
+ const allKeys = Object.keys({
90
+ ...currentDocument.files,
91
+ ...previousDocument.files,
92
+ });
93
+ const directoriesToDelete = [];
94
+ for (const key of allKeys) {
95
+ const previous = previousDocument.files[key];
96
+ const current = currentDocument.files[key];
97
+ // If this file was neither created nor deleted...
98
+ if (previous && current) {
99
+ // Handle changing of text content.
100
+ if (previous.text !== current.text) {
101
+ if (isImageFile(current.name)) {
102
+ // Write image files as binary from base64
103
+ const buffer = Buffer.from(current.text, 'base64');
104
+ fs.writeFileSync(resolvePath(current.name), buffer);
105
+ }
106
+ else {
107
+ // Write non-image files as text
108
+ fs.writeFileSync(resolvePath(current.name), current.text);
109
+ }
110
+ }
111
+ // Handle renaming files.
112
+ if (previous.name !== current.name) {
113
+ if (isDirectory(previous.name)) {
114
+ // If the directory itself is being renamed,
115
+ // Phase I: Ignore it, and get the files moved
116
+ // Phase II: Keep track of these, and delete them after
117
+ // all the files moved.
118
+ directoriesToDelete.push(previous.name);
119
+ }
120
+ else {
121
+ const newDir = path.dirname(current.name);
122
+ // Check if the new directory exists, if not, create it
123
+ if (!fs.existsSync(resolvePath(newDir))) {
124
+ fs.mkdirSync(resolvePath(newDir), {
125
+ recursive: true,
126
+ });
127
+ }
128
+ // Move the file to the new directory
129
+ fs.renameSync(resolvePath(previous.name), resolvePath(current.name));
130
+ }
131
+ }
132
+ }
133
+ // handle deleting files and directories.
134
+ if (previous && !current) {
135
+ const stats = fs.statSync(resolvePath(previous.name));
136
+ //Check if the file path we are trying to delete is a directory
137
+ if (!stats.isDirectory()) {
138
+ fs.unlinkSync(resolvePath(previous.name));
139
+ }
140
+ else {
141
+ //Performs directory deletion.
142
+ fs.rm(resolvePath(previous.name), {
143
+ recursive: true, //Makes sure that all files in directory are deleted.
144
+ }, (error) => {
145
+ if (error) {
146
+ console.log(error);
147
+ }
148
+ });
149
+ }
150
+ }
151
+ // Handle creating files and Directories.
152
+ if (!previous && current) {
153
+ //File Creation
154
+ if (!isDirectory(current.name)) {
155
+ if (isImageFile(current.name)) {
156
+ // Write image files as binary from base64
157
+ const buffer = Buffer.from(current.text, 'base64');
158
+ fs.writeFileSync(resolvePath(current.name), buffer);
159
+ }
160
+ else {
161
+ // Write non-image files as text
162
+ fs.writeFileSync(resolvePath(current.name), current.text);
163
+ }
164
+ }
165
+ else {
166
+ fs.mkdirSync(resolvePath(current.name), {
167
+ recursive: true,
168
+ });
169
+ }
170
+ }
171
+ }
172
+ // TODO deleted all directories under directoriesToDelete
173
+ for (const dir of directoriesToDelete) {
174
+ //Performs directory deletion.
175
+ fs.rm(resolvePath(dir), {
176
+ recursive: true, //Makes sure that all files in directory are deleted.
177
+ }, (error) => {
178
+ if (error) {
179
+ console.log(error);
180
+ }
181
+ });
182
+ }
183
+ previousDocument = currentDocument;
184
+ };
185
+ let lastExecutedTime = Date.now();
186
+ let lastChangeTimeout; // This timeout ensures the last change is saved
187
+ // Function to throttle the saving
188
+ function throttleSave() {
189
+ const now = Date.now();
190
+ const timeSinceLastExecution = now - lastExecutedTime;
191
+ if (timeSinceLastExecution > throttleTimeMS) {
192
+ save();
193
+ lastExecutedTime = now;
194
+ }
195
+ else {
196
+ // Clear the previous timeout and set a new one to save the last change
197
+ clearTimeout(lastChangeTimeout);
198
+ lastChangeTimeout = setTimeout(() => {
199
+ save();
200
+ lastExecutedTime = now;
201
+ }, throttleTimeMS - timeSinceLastExecution);
202
+ }
203
+ }
204
+ // Function to debounce the saving
205
+ let debounceTimeout;
206
+ function debounceSave() {
207
+ clearTimeout(debounceTimeout);
208
+ debounceTimeout = setTimeout(save, autoSaveDebounceTimeMS);
209
+ }
210
+ // Create the document, then subscribe so that the server-side doc
211
+ // receives ops from connected clients.
212
+ const ready = new Promise((resolve, reject) => {
213
+ shareDBDoc.create(initialDocument, json1Presence.type.uri, (createError) => {
214
+ if (createError)
215
+ return reject(createError);
216
+ shareDBDoc.subscribe((subscribeError) => {
217
+ if (subscribeError)
218
+ return reject(subscribeError);
219
+ if (autoSave) {
220
+ // Subscribe to listen for modifications
221
+ shareDBDoc.on('op', () => {
222
+ if (shareDBDoc.data.isInteracting) {
223
+ throttleSave();
224
+ }
225
+ else {
226
+ debounceSave();
227
+ }
228
+ });
229
+ }
230
+ resolve();
231
+ });
232
+ });
233
+ });
234
+ // Handle AI Assist requests.
235
+ app.post('/ai-assist', bodyParser.json(), handleAIAssist(shareDBDoc));
236
+ // Handle AI Copilot requests.
237
+ app.post('/ai-copilot', bodyParser.json(), handleAICopilot());
238
+ // Handle AI Chat Message requests.
239
+ app.post('/ai-chat-message', bodyParser.json(), handleAIChatMessage({
240
+ shareDBDoc,
241
+ onCreditDeduction: undefined,
242
+ }));
243
+ // Livekit Token Generator
244
+ app.get('/livekit-token', async (req, res) => {
245
+ const { room, username } = req.query;
246
+ res.send(await createToken(room, username));
247
+ });
248
+ const listen = (port) => new Promise((resolve, reject) => {
249
+ const onError = (error) => reject(error);
250
+ httpServer.once('error', onError);
251
+ httpServer.listen(port, () => {
252
+ httpServer.removeListener('error', onError);
253
+ const address = httpServer.address();
254
+ const actualPort = address && typeof address === 'object'
255
+ ? address.port
256
+ : port;
257
+ resolve(actualPort);
258
+ });
259
+ });
260
+ const close = () => new Promise((resolve, reject) => {
261
+ clearTimeout(lastChangeTimeout);
262
+ clearTimeout(debounceTimeout);
263
+ wss.close(() => {
264
+ httpServer.close((error) => {
265
+ if (error)
266
+ return reject(error);
267
+ shareDBBackend.close(() => resolve());
268
+ });
269
+ });
270
+ });
271
+ return {
272
+ app,
273
+ httpServer,
274
+ shareDBBackend,
275
+ shareDBDoc,
276
+ ready,
277
+ save,
278
+ listen,
279
+ close,
280
+ };
281
+ };