vzcode 3.2.0 → 3.4.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 (67) hide show
  1. package/README.md +185 -40
  2. package/dist/assets/App-BSFvLn9Z.js +387 -0
  3. package/dist/assets/App-DbKY-mb6.css +1 -0
  4. package/dist/assets/bindings_wasm_bg-IWNG_AjZ.wasm +0 -0
  5. package/dist/assets/buildWorker-N5tFTOqM.js +794 -0
  6. package/dist/assets/index-Acvr-XWK.js +43 -0
  7. package/dist/assets/index-CZT-v4sH.css +1 -0
  8. package/dist/assets/rolldown-runtime-COiEfhsA.js +1 -0
  9. package/dist/assets/worker-BpV7Ustv.js +223 -0
  10. package/dist/assets/worker-CLeezw6h.js +458 -0
  11. package/dist/assets/worker-DaSIYBQX.js +327 -0
  12. package/dist/cli.js +170 -99
  13. package/dist/index.html +3 -2
  14. package/dist/server/accessControl.js +104 -0
  15. package/dist/server/computeInitialDocument.js +4 -1
  16. package/dist/server/createServer.js +356 -104
  17. package/dist/server/index.js +4 -3
  18. package/dist/server/workspaceSecurity.js +115 -0
  19. package/dist/server/workspaceSync.js +141 -0
  20. package/package.json +74 -72
  21. package/src/cli.ts +203 -182
  22. package/src/client/App/index.tsx +2 -0
  23. package/src/client/App/usePending.ts +3 -1
  24. package/src/client/RunCodeWidget/index.tsx +1 -0
  25. package/src/client/SplitPaneResizeContext.tsx +94 -11
  26. package/src/client/VZCodeContext/types.ts +6 -0
  27. package/src/client/VZCodeContext/useVZCodeState.ts +2 -0
  28. package/src/client/VZResizer/index.tsx +25 -0
  29. package/src/client/VZSidebar/AIChatWrapper.tsx +2 -0
  30. package/src/client/VZSidebar/VisualEditor/CheckboxWidget.tsx +22 -30
  31. package/src/client/VZSidebar/VisualEditor/ColorWidget.tsx +198 -126
  32. package/src/client/VZSidebar/VisualEditor/DropdownWidget.tsx +25 -67
  33. package/src/client/VZSidebar/VisualEditor/PropertySection.tsx +41 -0
  34. package/src/client/VZSidebar/VisualEditor/SegmentedWidget.tsx +34 -0
  35. package/src/client/VZSidebar/VisualEditor/SliderWidget.tsx +60 -12
  36. package/src/client/VZSidebar/VisualEditor/VisualEditor.tsx +31 -393
  37. package/src/client/VZSidebar/VisualEditor/VisualEditorControls.tsx +478 -0
  38. package/src/client/VZSidebar/VisualEditor/colorUtils.ts +12 -0
  39. package/src/client/VZSidebar/VisualEditor/status.ts +47 -0
  40. package/src/client/VZSidebar/VisualEditor/updateConfig.ts +51 -24
  41. package/src/client/VZSidebar/VisualEditor/utils.ts +1 -1
  42. package/src/client/VZSidebar/styles.scss +424 -0
  43. package/src/client/WorkspaceConflictBanner.tsx +120 -0
  44. package/src/client/index.ts +2 -0
  45. package/src/client/main.jsx +54 -12
  46. package/src/llm-streaming-server/README.md +4 -16
  47. package/src/llm-streaming-ui/README.md +41 -2
  48. package/src/llm-streaming-ui/components/ChatInput.tsx +65 -13
  49. package/src/llm-streaming-ui/components/index.tsx +2 -0
  50. package/src/llm-streaming-ui/components/styles.scss +14 -0
  51. package/src/llm-streaming-ui/hooks/useAutoScroll.ts +1 -1
  52. package/src/llm-streaming-ui/index.ts +1 -0
  53. package/src/llm-streaming-ui/props.ts +26 -2
  54. package/src/server/accessControl.ts +151 -0
  55. package/src/server/computeInitialDocument.ts +6 -2
  56. package/src/server/createServer.ts +487 -138
  57. package/src/server/index.ts +4 -5
  58. package/src/server/workspaceSecurity.ts +160 -0
  59. package/src/server/workspaceSync.ts +203 -0
  60. package/src/types.ts +29 -27
  61. package/dist/assets/bindings_wasm_bg-9w8E-TmY.wasm +0 -0
  62. package/dist/assets/buildWorker-BZlya278.js +0 -687
  63. package/dist/assets/index-B7NRhsN6.js +0 -356
  64. package/dist/assets/index-D1V1AKed.css +0 -1
  65. package/dist/assets/worker-1oQYaz-F.js +0 -342
  66. package/dist/assets/worker-BfgPD8zR.js +0 -125
  67. package/dist/assets/worker-CoJaqtpi.js +0 -436
@@ -4,6 +4,8 @@ import express from 'express';
4
4
  import fs from 'fs';
5
5
  import http from 'http';
6
6
  import path from 'path';
7
+ import { createAccessControl } from './accessControl.js';
8
+ import { createWorkspacePathResolver } from './workspaceSecurity.js';
7
9
  import ShareDB from 'sharedb';
8
10
  import { fileURLToPath } from 'url';
9
11
  import { WebSocketServer } from 'ws';
@@ -15,6 +17,8 @@ import { handleAIChatMessage } from './handleAIChatMessage.js';
15
17
  import { isDirectory } from './isDirectory.js';
16
18
  import { createToken } from './livekit.js';
17
19
  import './setupEnv.js';
20
+ import { diff } from '../ot.js';
21
+ import { copyFiles, diskMatchesBaseline, readWorkspaceDisk, reconcileDisk, } from './workspaceSync.js';
18
22
  // The time in milliseconds by which auto-saving is debounced.
19
23
  const autoSaveDebounceTimeMS = 800;
20
24
  // The time in milliseconds by which auto-saving is throttled
@@ -34,28 +38,69 @@ const isImageFile = (fileName) => {
34
38
  export const createVZCodeServer = (options = {}) => {
35
39
  const cwd = options.cwd ?? process.cwd();
36
40
  const autoSave = options.autoSave ?? true;
41
+ const watchFiles = options.watchFiles ?? autoSave;
42
+ const scanIntervalMS = options.scanIntervalMS ?? 1500;
43
+ const workspace = createWorkspacePathResolver(cwd);
44
+ const access = createAccessControl(options.accessToken);
37
45
  // Resolve file names from the ShareDB document against the workspace
38
46
  // root, so the server can operate on a directory other than the
39
47
  // process's current working directory.
40
- const resolvePath = (name) => path.resolve(cwd, name);
48
+ const resolvePath = workspace.resolve;
41
49
  const serveStaticDir = options.serveStaticDir === undefined
42
50
  ? path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'dist')
43
51
  : options.serveStaticDir;
44
- const initialDocument = computeInitialDocument({
45
- fullPath: cwd,
46
- });
52
+ const initialDocument = {
53
+ ...computeInitialDocument({
54
+ fullPath: workspace.root,
55
+ }),
56
+ workspaceConflicts: [],
57
+ };
58
+ workspace.validateFiles(initialDocument.files);
47
59
  // Register our custom OT type,
48
60
  // because it does not ship with ShareDB.
49
61
  ShareDB.types.register(json1Presence.type);
50
62
  const app = express();
63
+ access.install(app);
51
64
  // Use ShareDB over WebSocket
52
65
  const shareDBBackend = new ShareDB({
53
66
  // Enable presence
54
67
  presence: true,
55
68
  doNotForwardSendPresenceErrorsToClient: true,
56
69
  });
70
+ // Validate the committed post-operation snapshot, not merely the
71
+ // operation payload. A rejected submission must never reach autosave.
72
+ shareDBBackend.use('commit', (context, next) => {
73
+ try {
74
+ if (context.collection !== 'documents' ||
75
+ context.id !== '1') {
76
+ throw new Error('Unauthorized ShareDB document');
77
+ }
78
+ workspace.validateFiles(context.snapshot?.data?.files);
79
+ next();
80
+ }
81
+ catch (error) {
82
+ next(error);
83
+ }
84
+ });
57
85
  const httpServer = http.createServer(app);
58
- const wss = new WebSocketServer({ server: httpServer });
86
+ // Authentication is enforced before ShareDB attaches to the socket.
87
+ const wss = new WebSocketServer({ noServer: true });
88
+ httpServer.on('upgrade', (req, socket, head) => {
89
+ const pathname = (req.url || '').split('?')[0];
90
+ if (pathname !== '/ws') {
91
+ socket.write('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n');
92
+ socket.destroy();
93
+ return;
94
+ }
95
+ if (!access.authorized(req)) {
96
+ socket.write('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n');
97
+ socket.destroy();
98
+ return;
99
+ }
100
+ wss.handleUpgrade(req, socket, head, (ws) => {
101
+ wss.emit('connection', ws, req);
102
+ });
103
+ });
59
104
  wss.on('connection', (ws) => {
60
105
  const clientStream = new WebSocketJSONStream(ws);
61
106
  shareDBBackend.listen(clientStream);
@@ -81,106 +126,256 @@ export const createVZCodeServer = (options = {}) => {
81
126
  const shareDBConnection = shareDBBackend.connect();
82
127
  const shareDBDoc = shareDBConnection.get('documents', '1');
83
128
  // The state of the document when files were last auto-saved.
84
- let previousDocument = initialDocument;
129
+ let previousDocument = {
130
+ ...initialDocument,
131
+ files: copyFiles(initialDocument.files),
132
+ };
133
+ let identities = {};
134
+ const initialDisk = readWorkspaceDisk(workspace.root);
135
+ for (const [id, file] of Object.entries(previousDocument.files)) {
136
+ identities[id] = initialDisk.get(file.name)?.identity;
137
+ }
138
+ let conflictNames = [];
139
+ let runningSync = null;
140
+ let closing = false;
141
+ let watcher;
142
+ let interval;
143
+ let changeTimer;
85
144
  // Saves the files that changed.
86
145
  const save = () => {
87
146
  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
- }
147
+ if (conflictNames.length) {
148
+ throw new Error('Workspace conflicts require resolution: ' +
149
+ conflictNames.join(', '));
150
+ }
151
+ // Do not write a single byte if the disk has changed since the
152
+ // last successful save/import. This also protects against events
153
+ // arriving before a filesystem watch callback is delivered.
154
+ if (!diskMatchesBaseline(previousDocument.files, readWorkspaceDisk(workspace.root))) {
155
+ void syncFromDisk().catch((error) => console.error('VZCode disk reconciliation failed:', error));
156
+ throw new Error('External filesystem change detected; save deferred');
157
+ }
158
+ // Fail closed before the first write in this batch. Repeat checks
159
+ // at each filesystem call to reject newly created symlinks.
160
+ workspace.validateFiles(previousDocument.files);
161
+ workspace.validateFiles(currentDocument.files);
162
+ const before = previousDocument.files;
163
+ const after = currentDocument.files;
164
+ const oldEntries = Object.entries(before);
165
+ const newEntries = Object.entries(after);
166
+ const depth = (name) => name.split('/').length;
167
+ const removed = oldEntries.filter(([id]) => !after[id]);
168
+ const changed = newEntries.filter(([id]) => !!before[id]);
169
+ const created = newEntries.filter(([id]) => !before[id]);
170
+ // Create destination directories first, including renamed folders.
171
+ for (const [, file] of newEntries
172
+ .filter(([, file]) => isDirectory(file.name))
173
+ .sort((a, b) => depth(a[1].name) - depth(b[1].name))) {
174
+ if (!fs.existsSync(resolvePath(file.name))) {
175
+ fs.mkdirSync(resolvePath(file.name), {
176
+ recursive: true,
177
+ });
132
178
  }
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
- }
179
+ }
180
+ // Delete removed files before moving another file into their path.
181
+ for (const [, file] of removed.filter(([, file]) => !isDirectory(file.name))) {
182
+ fs.unlinkSync(resolvePath(file.name));
183
+ }
184
+ // Move surviving files before writing their updated contents. Moving
185
+ // only the leaf (not directories) preserves file IDs across folder
186
+ // renames and avoids writing to the old location.
187
+ for (const [id, current] of changed) {
188
+ const previous = before[id];
189
+ if (previous.name !== current.name &&
190
+ !isDirectory(current.name)) {
191
+ const destinationDir = path.dirname(current.name);
192
+ if (destinationDir !== '.') {
193
+ fs.mkdirSync(resolvePath(destinationDir), {
194
+ recursive: true,
148
195
  });
149
196
  }
197
+ fs.renameSync(resolvePath(previous.name), resolvePath(current.name));
150
198
  }
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), {
199
+ }
200
+ // Apply edited contents and new files, including binary images.
201
+ for (const [id, current] of [...changed, ...created]) {
202
+ if (isDirectory(current.name))
203
+ continue;
204
+ if (!before[id] || before[id].text !== current.text) {
205
+ const parent = path.dirname(current.name);
206
+ if (parent !== '.') {
207
+ fs.mkdirSync(resolvePath(parent), {
167
208
  recursive: true,
168
209
  });
169
210
  }
211
+ const data = isImageFile(current.name)
212
+ ? Buffer.from(current.text, 'base64')
213
+ : current.text;
214
+ workspace.writeFile(current.name, data);
170
215
  }
171
216
  }
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
- }
217
+ // Remove obsolete directories after moving or removing children.
218
+ const obsoleteDirs = [
219
+ ...removed
220
+ .filter(([, file]) => isDirectory(file.name))
221
+ .map(([, file]) => file.name),
222
+ ...changed
223
+ .filter(([id, file]) => isDirectory(before[id].name) &&
224
+ before[id].name !== file.name)
225
+ .map(([id]) => before[id].name),
226
+ ];
227
+ for (const name of [...new Set(obsoleteDirs)].sort((a, b) => depth(b) - depth(a))) {
228
+ const full = resolvePath(name);
229
+ if (fs.existsSync(full)) {
230
+ fs.rmSync(full, { recursive: true });
231
+ }
232
+ }
233
+ previousDocument = {
234
+ ...currentDocument,
235
+ files: copyFiles(currentDocument.files),
236
+ };
237
+ const disk = readWorkspaceDisk(workspace.root);
238
+ identities = Object.fromEntries(Object.entries(previousDocument.files).map(([id, file]) => [id, disk.get(file.name)?.identity]));
239
+ };
240
+ const publishDiskUpdate = (files, conflicts) => {
241
+ const current = shareDBDoc.data;
242
+ const next = {
243
+ ...current,
244
+ files,
245
+ workspaceConflicts: conflicts,
246
+ };
247
+ const operation = diff(current, next);
248
+ if (!operation ||
249
+ (Array.isArray(operation) && !operation.length)) {
250
+ return Promise.resolve();
251
+ }
252
+ return new Promise((resolve, reject) => {
253
+ shareDBDoc.submitOp(operation, { source: 'filesystem' }, (error) => {
254
+ if (error)
255
+ reject(error);
256
+ else
257
+ resolve();
258
+ });
259
+ });
260
+ };
261
+ /** Serialized rescans avoid overlapping external imports. */
262
+ const syncFromDisk = () => {
263
+ if (runningSync)
264
+ return runningSync;
265
+ if (closing)
266
+ return Promise.resolve();
267
+ const scan = async () => {
268
+ const disk = readWorkspaceDisk(workspace.root);
269
+ if (!conflictNames.length &&
270
+ diskMatchesBaseline(previousDocument.files, disk)) {
271
+ identities = Object.fromEntries(Object.entries(previousDocument.files).map(([id, file]) => [
272
+ id,
273
+ disk.get(file.name)?.identity,
274
+ ]));
275
+ return;
276
+ }
277
+ const plan = reconcileDisk({
278
+ baseline: previousDocument.files,
279
+ current: shareDBDoc.data.files,
280
+ disk,
281
+ identities,
181
282
  });
283
+ await publishDiskUpdate(plan.files, plan.conflicts);
284
+ previousDocument = {
285
+ ...previousDocument,
286
+ files: plan.baseline,
287
+ };
288
+ identities = plan.identities;
289
+ conflictNames = plan.conflicts;
290
+ // A local edit may have been pending while an unrelated external
291
+ // change was imported. Resume its save after the OT is committed.
292
+ if (autoSave &&
293
+ !conflictNames.length &&
294
+ !diskMatchesBaseline(plan.files, disk)) {
295
+ debounceSave();
296
+ }
297
+ };
298
+ runningSync = scan().finally(() => {
299
+ runningSync = null;
300
+ });
301
+ return runningSync;
302
+ };
303
+ const resolveConflict = async (name, choice) => {
304
+ await syncFromDisk();
305
+ if (!conflictNames.includes(name)) {
306
+ throw new Error('Unknown or already resolved conflict');
307
+ }
308
+ const disk = readWorkspaceDisk(workspace.root);
309
+ const nextFiles = copyFiles(shareDBDoc.data.files);
310
+ const nextBaseline = copyFiles(previousDocument.files);
311
+ const id = Object.keys(nextBaseline).find((key) => nextBaseline[key].name === name) ??
312
+ Object.keys(nextFiles).find((key) => nextFiles[key].name === name);
313
+ if (!id)
314
+ throw new Error('Conflict entry disappeared');
315
+ let observed = disk.get(name);
316
+ // External renames may have changed the path but preserved the inode.
317
+ if (!observed && identities[id]) {
318
+ const candidates = Array.from(disk.values()).filter((file) => file.identity === identities[id]);
319
+ if (candidates.length === 1)
320
+ observed = candidates[0];
321
+ }
322
+ if (choice === 'disk') {
323
+ if (observed) {
324
+ nextFiles[id] = {
325
+ name: observed.name,
326
+ text: observed.text,
327
+ };
328
+ }
329
+ else {
330
+ delete nextFiles[id];
331
+ }
332
+ }
333
+ if (observed) {
334
+ nextBaseline[id] = {
335
+ name: observed.name,
336
+ text: observed.text,
337
+ };
338
+ identities[id] = observed.identity;
339
+ }
340
+ else {
341
+ delete nextBaseline[id];
342
+ delete identities[id];
343
+ }
344
+ const remaining = conflictNames.filter((conflict) => conflict !== name);
345
+ // All other tracked files must still match disk before allowing an
346
+ // editor-wins write. A new disk change requires another reconciliation.
347
+ if (choice === 'editor' &&
348
+ !remaining.length &&
349
+ !diskMatchesBaseline(nextBaseline, disk)) {
350
+ throw new Error('Disk changed again; retry after reconciling');
351
+ }
352
+ await publishDiskUpdate(nextFiles, remaining);
353
+ previousDocument = {
354
+ ...previousDocument,
355
+ files: nextBaseline,
356
+ };
357
+ conflictNames = remaining;
358
+ if (autoSave && !remaining.length) {
359
+ debounceSave();
360
+ }
361
+ };
362
+ const scheduleSync = () => {
363
+ if (closing)
364
+ return;
365
+ clearTimeout(changeTimer);
366
+ changeTimer = setTimeout(() => {
367
+ void syncFromDisk().catch((error) => console.error('VZCode disk watcher failed:', error));
368
+ }, 80);
369
+ };
370
+ // Invalid paths or external filesystem changes must not crash the
371
+ // process from a delayed timer. Expose errors in logs for operators.
372
+ const autoSaveSafely = () => {
373
+ try {
374
+ save();
375
+ }
376
+ catch (error) {
377
+ console.error('VZCode autosave refused:', error);
182
378
  }
183
- previousDocument = currentDocument;
184
379
  };
185
380
  let lastExecutedTime = Date.now();
186
381
  let lastChangeTimeout; // This timeout ensures the last change is saved
@@ -189,14 +384,14 @@ export const createVZCodeServer = (options = {}) => {
189
384
  const now = Date.now();
190
385
  const timeSinceLastExecution = now - lastExecutedTime;
191
386
  if (timeSinceLastExecution > throttleTimeMS) {
192
- save();
387
+ autoSaveSafely();
193
388
  lastExecutedTime = now;
194
389
  }
195
390
  else {
196
391
  // Clear the previous timeout and set a new one to save the last change
197
392
  clearTimeout(lastChangeTimeout);
198
393
  lastChangeTimeout = setTimeout(() => {
199
- save();
394
+ autoSaveSafely();
200
395
  lastExecutedTime = now;
201
396
  }, throttleTimeMS - timeSinceLastExecution);
202
397
  }
@@ -205,7 +400,7 @@ export const createVZCodeServer = (options = {}) => {
205
400
  let debounceTimeout;
206
401
  function debounceSave() {
207
402
  clearTimeout(debounceTimeout);
208
- debounceTimeout = setTimeout(save, autoSaveDebounceTimeMS);
403
+ debounceTimeout = setTimeout(autoSaveSafely, autoSaveDebounceTimeMS);
209
404
  }
210
405
  // Create the document, then subscribe so that the server-side doc
211
406
  // receives ops from connected clients.
@@ -217,8 +412,10 @@ export const createVZCodeServer = (options = {}) => {
217
412
  if (subscribeError)
218
413
  return reject(subscribeError);
219
414
  if (autoSave) {
220
- // Subscribe to listen for modifications
221
- shareDBDoc.on('op', () => {
415
+ // Filesystem imports must not trigger a write-back loop.
416
+ shareDBDoc.on('op', (_op, source) => {
417
+ if (source === 'filesystem')
418
+ return;
222
419
  if (shareDBDoc.data.isInteracting) {
223
420
  throttleSave();
224
421
  }
@@ -227,39 +424,91 @@ export const createVZCodeServer = (options = {}) => {
227
424
  }
228
425
  });
229
426
  }
427
+ if (watchFiles) {
428
+ // Root watcher gives low-latency notifications. The periodic
429
+ // recursive scan handles nested files and lost/coalesced events.
430
+ try {
431
+ watcher = fs.watch(workspace.root, scheduleSync);
432
+ watcher.on('error', (error) => {
433
+ console.error('VZCode watcher error:', error);
434
+ });
435
+ }
436
+ catch (error) {
437
+ // Some filesystems do not offer watch notifications.
438
+ console.warn('VZCode using polling-only filesystem monitoring:', error);
439
+ }
440
+ interval = setInterval(scheduleSync, scanIntervalMS);
441
+ interval.unref();
442
+ }
230
443
  resolve();
231
444
  });
232
445
  });
233
446
  });
447
+ // Conflict decisions are explicit, authenticated user actions.
448
+ app.post('/workspace-conflicts/resolve', access.requireAuth, bodyParser.json(), async (req, res) => {
449
+ const { name, choice } = req.body || {};
450
+ if (typeof name !== 'string' ||
451
+ (choice !== 'disk' && choice !== 'editor')) {
452
+ res
453
+ .status(400)
454
+ .json({ error: 'Invalid conflict resolution' });
455
+ return;
456
+ }
457
+ try {
458
+ await resolveConflict(name, choice);
459
+ res.sendStatus(204);
460
+ }
461
+ catch (error) {
462
+ res.status(409).json({ error: error.message });
463
+ }
464
+ });
234
465
  // Handle AI Assist requests.
235
- app.post('/ai-assist', bodyParser.json(), handleAIAssist(shareDBDoc));
466
+ app.post('/ai-assist', access.requireAuth, bodyParser.json(), handleAIAssist(shareDBDoc));
236
467
  // Handle AI Copilot requests.
237
- app.post('/ai-copilot', bodyParser.json(), handleAICopilot());
468
+ app.post('/ai-copilot', access.requireAuth, bodyParser.json(), handleAICopilot());
238
469
  // Handle AI Chat Message requests.
239
- app.post('/ai-chat-message', bodyParser.json(), handleAIChatMessage({
470
+ app.post('/ai-chat-message', access.requireAuth, bodyParser.json(), handleAIChatMessage({
240
471
  shareDBDoc,
241
472
  onCreditDeduction: undefined,
242
473
  }));
243
474
  // Livekit Token Generator
244
- app.get('/livekit-token', async (req, res) => {
475
+ app.get('/livekit-token', access.requireAuth, async (req, res) => {
245
476
  const { room, username } = req.query;
246
477
  res.send(await createToken(room, username));
247
478
  });
248
- const listen = (port) => new Promise((resolve, reject) => {
249
- const onError = (error) => reject(error);
479
+ const listen = (port, host) => new Promise((resolve, reject) => {
480
+ const onError = (error) => {
481
+ httpServer.removeListener('error', onError);
482
+ reject(error);
483
+ };
250
484
  httpServer.once('error', onError);
251
- httpServer.listen(port, () => {
485
+ const onListening = () => {
252
486
  httpServer.removeListener('error', onError);
253
487
  const address = httpServer.address();
254
488
  const actualPort = address && typeof address === 'object'
255
489
  ? address.port
256
490
  : port;
257
491
  resolve(actualPort);
258
- });
492
+ };
493
+ if (host) {
494
+ httpServer.listen(port, host, onListening);
495
+ }
496
+ else {
497
+ httpServer.listen(port, onListening);
498
+ }
259
499
  });
260
500
  const close = () => new Promise((resolve, reject) => {
501
+ closing = true;
502
+ watcher?.close();
503
+ clearInterval(interval);
504
+ clearTimeout(changeTimer);
261
505
  clearTimeout(lastChangeTimeout);
262
506
  clearTimeout(debounceTimeout);
507
+ access.close();
508
+ // An upgraded WebSocket otherwise prevents CLI shutdown.
509
+ for (const client of wss.clients) {
510
+ client.terminate();
511
+ }
263
512
  wss.close(() => {
264
513
  httpServer.close((error) => {
265
514
  if (error)
@@ -273,8 +522,11 @@ export const createVZCodeServer = (options = {}) => {
273
522
  httpServer,
274
523
  shareDBBackend,
275
524
  shareDBDoc,
525
+ accessToken: access.token,
276
526
  ready,
277
527
  save,
528
+ syncFromDisk,
529
+ resolveConflict,
278
530
  listen,
279
531
  close,
280
532
  };
@@ -11,7 +11,7 @@ function getPortFromArgs(defaultPort = 3030) {
11
11
  }
12
12
  // Server port.
13
13
  const port = getPortFromArgs();
14
- const { ready, listen } = createVZCodeServer();
14
+ const { ready, listen, accessToken } = createVZCodeServer();
15
15
  ready.catch((error) => {
16
16
  console.error('Failed to initialize ShareDB document:', error);
17
17
  });
@@ -20,6 +20,7 @@ listen(port).then((actualPort) => {
20
20
  // variable (for development) or the default port.
21
21
  const livePort = process.env.EDITOR_PORT || actualPort;
22
22
  console.log(`EDITOR_PORT: ${process.env.EDITOR_PORT}`);
23
- console.log(`Editor is live at http://localhost:${livePort}`);
24
- open(`http://localhost:${livePort}`);
23
+ const accessUrl = `http://localhost:${livePort}/#vzcode-token=${accessToken}`;
24
+ console.log(`Editor is live at ${accessUrl}`);
25
+ open(accessUrl);
25
26
  });