vzcode 2.34.0 → 2.35.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.
package/dist/index.html CHANGED
@@ -20,7 +20,7 @@
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-nL6to42p.js"></script>
23
+ <script type="module" crossorigin src="/assets/index-rg2Zvfo_.js"></script>
24
24
  <link rel="stylesheet" crossorigin href="/assets/index-Dyt9tpmu.css">
25
25
  </head>
26
26
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vzcode",
3
- "version": "2.34.0",
3
+ "version": "2.35.0",
4
4
  "description": "Multiplayer code editor system",
5
5
  "main": "src/index.ts",
6
6
  "type": "module",
@@ -0,0 +1,17 @@
1
+ /** Pure AI chat behavior shared by the built-in session and unit tests. */
2
+ export const shouldReuseChatId = (
3
+ options?: Record<string, string>,
4
+ ): boolean =>
5
+ options?.isRetry === 'true' || options?.isUndo === 'true';
6
+
7
+ export const userMessageHistory = (
8
+ messages?: ReadonlyArray<{
9
+ role: string;
10
+ content: string;
11
+ }> | null,
12
+ ): string[] =>
13
+ messages
14
+ ? messages
15
+ .filter((message) => message.role === 'user')
16
+ .map((message) => message.content)
17
+ : [];
@@ -0,0 +1,325 @@
1
+ import {
2
+ useCallback,
3
+ useEffect,
4
+ useMemo,
5
+ useState,
6
+ } from 'react';
7
+ import { v4 as uuidv4 } from 'uuid';
8
+ import type { VZCodeProviderProps } from './types';
9
+ import {
10
+ shouldReuseChatId,
11
+ userMessageHistory,
12
+ } from './chatSessionHelpers';
13
+
14
+ type AIChatSessionOptions = Pick<
15
+ VZCodeProviderProps,
16
+ | 'content'
17
+ | 'submitOperation'
18
+ | 'aiChatEndpoint'
19
+ | 'aiChatOptions'
20
+ | 'autoForkAndRetryAI'
21
+ | 'handleChatError'
22
+ | 'onAIChatMessageSubmitted'
23
+ > & { aiChatMode: 'ask' | 'edit' };
24
+
25
+ /**
26
+ * Owns the built-in AI chat request, retry, history and draft lifecycle.
27
+ * The parent provider continues exposing the same VZCodeContextValue.
28
+ */
29
+ export function useAIChatSession({
30
+ content,
31
+ submitOperation,
32
+ aiChatMode,
33
+ aiChatEndpoint,
34
+ aiChatOptions,
35
+ autoForkAndRetryAI,
36
+ handleChatError,
37
+ onAIChatMessageSubmitted,
38
+ }: AIChatSessionOptions) {
39
+ const [aiChatMessage, setAIChatMessage] = useState('');
40
+
41
+ const DEBUG = false;
42
+
43
+ // Compute isLoading based on the current chat's aiStatus
44
+ // Chat ID changes with each new user message (but not for retry/undo)
45
+ const [currentChatId, setCurrentChatId] = useState(() =>
46
+ uuidv4(),
47
+ );
48
+ const [selectedChatId, setSelectedChatId] = useState<
49
+ string | null
50
+ >(null);
51
+
52
+ // Use selectedChatId if available, otherwise use currentChatId for backward compatibility
53
+ const activeChatId = selectedChatId || currentChatId;
54
+ const currentChat = content?.chats?.[activeChatId];
55
+
56
+ // Session-local navigation, derived from the current ShareDB chat.
57
+ const messageHistory = useMemo(
58
+ () => userMessageHistory(currentChat?.messages),
59
+ [currentChat?.messages],
60
+ );
61
+
62
+ const [historyIndex, setHistoryIndex] = useState(-1);
63
+ const [currentDraft, setCurrentDraft] = useState('');
64
+
65
+ const [aiErrorMessage, setAIErrorMessageState] = useState<
66
+ string | null
67
+ >(null);
68
+
69
+ // Create the combined setAIErrorMessage function that calls both state setter and external callback
70
+ const setAIErrorMessage = useCallback(
71
+ (error: string | null, message?: string) => {
72
+ setAIErrorMessageState(error);
73
+ if (error && handleChatError) {
74
+ handleChatError(error, message);
75
+ }
76
+ },
77
+ [handleChatError],
78
+ );
79
+
80
+ // Phase 5: Restore the prompt into the chat input when the server
81
+ // populates `currentChatDraft` (e.g. after Undo), then clear it so it
82
+ // is applied exactly once.
83
+ useEffect(() => {
84
+ const draft = (content as any)?.currentChatDraft;
85
+ if (typeof draft === 'string' && draft.trim()) {
86
+ setAIChatMessage(draft);
87
+ submitOperation((currentContent) => {
88
+ const next: any = { ...currentContent };
89
+ next.currentChatDraft = undefined;
90
+ return next;
91
+ });
92
+ }
93
+ // eslint-disable-next-line react-hooks/exhaustive-deps
94
+ }, [(content as any)?.currentChatDraft]);
95
+
96
+ // Message history navigation functions
97
+ const navigateMessageHistoryUp = useCallback(() => {
98
+ if (messageHistory.length === 0) return;
99
+
100
+ // If we're not navigating history, save current draft
101
+ if (historyIndex === -1) {
102
+ setCurrentDraft(aiChatMessage);
103
+ }
104
+
105
+ const newIndex =
106
+ historyIndex < messageHistory.length - 1
107
+ ? historyIndex + 1
108
+ : historyIndex;
109
+ setHistoryIndex(newIndex);
110
+ setAIChatMessage(
111
+ messageHistory[messageHistory.length - 1 - newIndex],
112
+ );
113
+ }, [messageHistory, historyIndex, aiChatMessage]);
114
+
115
+ const navigateMessageHistoryDown = useCallback(() => {
116
+ if (historyIndex === -1) return;
117
+
118
+ const newIndex = historyIndex - 1;
119
+ if (newIndex === -1) {
120
+ // Return to draft
121
+ setHistoryIndex(-1);
122
+ setAIChatMessage(currentDraft);
123
+ setCurrentDraft('');
124
+ } else {
125
+ setHistoryIndex(newIndex);
126
+ setAIChatMessage(
127
+ messageHistory[
128
+ messageHistory.length - 1 - newIndex
129
+ ],
130
+ );
131
+ }
132
+ }, [messageHistory, historyIndex, currentDraft]);
133
+
134
+ const resetMessageHistoryNavigation = useCallback(() => {
135
+ if (historyIndex !== -1) {
136
+ setHistoryIndex(-1);
137
+ setCurrentDraft('');
138
+ }
139
+ }, [historyIndex]);
140
+
141
+ const handleSendMessage = useCallback(
142
+ async (
143
+ messageToSend?: string,
144
+ options?: Record<string, string>,
145
+ ) => {
146
+ DEBUG &&
147
+ console.log(
148
+ 'AIChat: handleSendMessage called with:',
149
+ messageToSend,
150
+ 'aiChatMessage:',
151
+ aiChatMessage,
152
+ );
153
+ const messageContent = messageToSend || aiChatMessage;
154
+
155
+ if (
156
+ !messageContent ||
157
+ typeof messageContent !== 'string' ||
158
+ !messageContent.trim()
159
+ ) {
160
+ return;
161
+ }
162
+
163
+ const currentPrompt = aiChatMessage.trim();
164
+ setAIChatMessage('');
165
+
166
+ // Reset history navigation when sending a message
167
+ setHistoryIndex(-1);
168
+ setCurrentDraft('');
169
+
170
+ setAIErrorMessage(null); // Clear any previous errors
171
+
172
+ // Track AI chat message submission
173
+ const isRetry = options?.isRetry === 'true';
174
+ const isUndo = options?.isUndo === 'true';
175
+ if (
176
+ !DEBUG &&
177
+ onAIChatMessageSubmitted &&
178
+ aiChatOptions?.vizId
179
+ ) {
180
+ onAIChatMessageSubmitted({
181
+ messageLength: messageContent.trim().length,
182
+ isRetry,
183
+ isUndo,
184
+ });
185
+ }
186
+
187
+ // Generate new chat ID only for fresh user messages
188
+ // Keep existing chat ID for retries (Try Harder) and undos
189
+ const isRetryOrUndo = shouldReuseChatId(options);
190
+
191
+ let chatIdForRequest: string;
192
+ if (isRetryOrUndo) {
193
+ // Use existing chat ID for retry/undo operations
194
+ chatIdForRequest = activeChatId;
195
+ DEBUG &&
196
+ console.log(
197
+ 'Using existing chatId for retry/undo:',
198
+ chatIdForRequest,
199
+ );
200
+ } else {
201
+ // Generate NEW chat ID for fresh user message
202
+ const newChatId = uuidv4();
203
+ setCurrentChatId(newChatId);
204
+ setSelectedChatId(newChatId);
205
+ chatIdForRequest = newChatId;
206
+ DEBUG &&
207
+ console.log(
208
+ 'Generated new chatId for fresh message:',
209
+ chatIdForRequest,
210
+ );
211
+ }
212
+
213
+ // Call backend endpoint for AI response
214
+ try {
215
+ const response = await fetch(aiChatEndpoint, {
216
+ method: 'POST',
217
+ headers: {
218
+ 'Content-Type': 'application/json',
219
+ },
220
+ body: JSON.stringify({
221
+ ...aiChatOptions,
222
+ content: messageContent.trim(),
223
+ chatId: chatIdForRequest,
224
+ mode: aiChatMode,
225
+ ...options,
226
+ }),
227
+ });
228
+
229
+ if (!response.ok) {
230
+ throw new Error(
231
+ `HTTP error! status: ${response.status}`,
232
+ );
233
+ }
234
+
235
+ // Parse the response to check for errors
236
+ const responseData = await response.json();
237
+
238
+ // Check if the response contains a VizHub error
239
+ if (
240
+ responseData.outcome === 'failure' &&
241
+ responseData.error
242
+ ) {
243
+ const errorMessage = responseData.error.message;
244
+
245
+ // Check if this is the specific permission error that should trigger auto-fork
246
+ if (
247
+ errorMessage ===
248
+ 'You do not have permission to use AI chat on this visualization. Only users with edit access can use this feature. Fork the viz to edit it.'
249
+ ) {
250
+ // For authenticated users, trigger auto-fork
251
+ if (autoForkAndRetryAI) {
252
+ try {
253
+ await autoForkAndRetryAI(
254
+ currentPrompt,
255
+ aiChatMode,
256
+ );
257
+ // If we reach here, the fork was successful and redirect should happen
258
+ return;
259
+ } catch (forkError) {
260
+ console.error(
261
+ 'Auto-fork failed:',
262
+ forkError,
263
+ );
264
+ setAIErrorMessage(
265
+ 'Failed to fork visualization. Please try forking manually.',
266
+ );
267
+ return;
268
+ }
269
+ } else {
270
+ // For unauthenticated users, store the message and trigger login flow
271
+ // This will be handled by the external error handler
272
+ setAIErrorMessage(
273
+ errorMessage,
274
+ messageContent.trim(),
275
+ );
276
+ return;
277
+ }
278
+ }
279
+
280
+ // For other errors, show the error message
281
+ setAIErrorMessage(
282
+ errorMessage,
283
+ messageContent.trim(),
284
+ );
285
+ return;
286
+ }
287
+
288
+ // The backend handles all ShareDB operations for successful responses
289
+ // The loading state is now managed via ShareDB aiStatus
290
+ return responseData;
291
+ } catch (error) {
292
+ console.error('Error getting AI response:', error);
293
+ setAIErrorMessage(
294
+ 'Failed to send message. Please try again.',
295
+ messageContent.trim(),
296
+ );
297
+ }
298
+ },
299
+ [
300
+ aiChatMessage,
301
+ aiChatEndpoint,
302
+ aiChatOptions,
303
+ activeChatId,
304
+ aiChatMode,
305
+ autoForkAndRetryAI,
306
+ onAIChatMessageSubmitted,
307
+ DEBUG,
308
+ setAIErrorMessage,
309
+ ],
310
+ );
311
+
312
+ return {
313
+ aiChatMessage,
314
+ setAIChatMessage,
315
+ currentChatId,
316
+ selectedChatId,
317
+ setSelectedChatId,
318
+ aiErrorMessage,
319
+ setAIErrorMessage,
320
+ handleSendMessage,
321
+ navigateMessageHistoryUp,
322
+ navigateMessageHistoryDown,
323
+ resetMessageHistoryNavigation,
324
+ };
325
+ }
@@ -1,7 +1,6 @@
1
1
  import {
2
2
  useCallback,
3
3
  useEffect,
4
- useMemo,
5
4
  useReducer,
6
5
  useRef,
7
6
  useState,
@@ -22,7 +21,7 @@ import {
22
21
  } from '../vzReducer';
23
22
  import { findPane } from '../vzReducer/findPane';
24
23
  import { usePresenceAutoFollow } from '../usePresenceAutoFollow';
25
- import { v4 as uuidv4 } from 'uuid';
24
+ import { useAIChatSession } from './useAIChatSession';
26
25
  import {
27
26
  VZCodeContextValue,
28
27
  VZCodeProviderProps,
@@ -271,283 +270,28 @@ export const useVZCodeState = ({
271
270
  const [voiceChatModalOpen, setVoiceChatModalOpen] =
272
271
  useState(false);
273
272
 
274
- const [aiChatMessage, setAIChatMessage] = useState('');
275
-
276
- const DEBUG = false;
277
-
278
- // Compute isLoading based on the current chat's aiStatus
279
- // Chat ID changes with each new user message (but not for retry/undo)
280
- const [currentChatId, setCurrentChatId] = useState(() =>
281
- uuidv4(),
282
- );
283
- const [selectedChatId, setSelectedChatId] = useState<
284
- string | null
285
- >(null);
286
-
287
- // Use selectedChatId if available, otherwise use currentChatId for backward compatibility
288
- const activeChatId = selectedChatId || currentChatId;
289
- const currentChat = content?.chats?.[activeChatId];
290
-
291
- // Message history for up/down arrow navigation - using ShareDB document data
292
- const messageHistory = useMemo(() => {
293
- if (!currentChat?.messages) return [];
294
- // Extract user messages in chronological order for history navigation
295
- return currentChat.messages
296
- .filter((msg) => msg.role === 'user')
297
- .map((msg) => msg.content);
298
- }, [currentChat?.messages]);
299
-
300
- const [historyIndex, setHistoryIndex] = useState(-1);
301
- const [currentDraft, setCurrentDraft] = useState('');
302
-
303
- const [aiErrorMessage, setAIErrorMessageState] = useState<
304
- string | null
305
- >(null);
306
-
307
- // Create the combined setAIErrorMessage function that calls both state setter and external callback
308
- const setAIErrorMessage = useCallback(
309
- (error: string | null, message?: string) => {
310
- setAIErrorMessageState(error);
311
- if (error && handleChatError) {
312
- handleChatError(error, message);
313
- }
314
- },
315
- [handleChatError],
316
- );
317
-
318
- // Phase 5: Restore the prompt into the chat input when the server
319
- // populates `currentChatDraft` (e.g. after Undo), then clear it so it
320
- // is applied exactly once.
321
- useEffect(() => {
322
- const draft = (content as any)?.currentChatDraft;
323
- if (typeof draft === 'string' && draft.trim()) {
324
- setAIChatMessage(draft);
325
- submitOperation((currentContent) => {
326
- const next: any = { ...currentContent };
327
- next.currentChatDraft = undefined;
328
- return next;
329
- });
330
- }
331
- // eslint-disable-next-line react-hooks/exhaustive-deps
332
- }, [(content as any)?.currentChatDraft]);
333
-
334
- // Message history navigation functions
335
- const navigateMessageHistoryUp = useCallback(() => {
336
- if (messageHistory.length === 0) return;
337
-
338
- // If we're not navigating history, save current draft
339
- if (historyIndex === -1) {
340
- setCurrentDraft(aiChatMessage);
341
- }
342
-
343
- const newIndex =
344
- historyIndex < messageHistory.length - 1
345
- ? historyIndex + 1
346
- : historyIndex;
347
- setHistoryIndex(newIndex);
348
- setAIChatMessage(
349
- messageHistory[messageHistory.length - 1 - newIndex],
350
- );
351
- }, [messageHistory, historyIndex, aiChatMessage]);
352
-
353
- const navigateMessageHistoryDown = useCallback(() => {
354
- if (historyIndex === -1) return;
355
-
356
- const newIndex = historyIndex - 1;
357
- if (newIndex === -1) {
358
- // Return to draft
359
- setHistoryIndex(-1);
360
- setAIChatMessage(currentDraft);
361
- setCurrentDraft('');
362
- } else {
363
- setHistoryIndex(newIndex);
364
- setAIChatMessage(
365
- messageHistory[
366
- messageHistory.length - 1 - newIndex
367
- ],
368
- );
369
- }
370
- }, [messageHistory, historyIndex, currentDraft]);
371
-
372
- const resetMessageHistoryNavigation = useCallback(() => {
373
- if (historyIndex !== -1) {
374
- setHistoryIndex(-1);
375
- setCurrentDraft('');
376
- }
377
- }, [historyIndex]);
378
-
379
- const handleSendMessage = useCallback(
380
- async (
381
- messageToSend?: string,
382
- options?: Record<string, string>,
383
- ) => {
384
- DEBUG &&
385
- console.log(
386
- 'AIChat: handleSendMessage called with:',
387
- messageToSend,
388
- 'aiChatMessage:',
389
- aiChatMessage,
390
- );
391
- const messageContent = messageToSend || aiChatMessage;
392
-
393
- if (
394
- !messageContent ||
395
- typeof messageContent !== 'string' ||
396
- !messageContent.trim()
397
- ) {
398
- return;
399
- }
400
-
401
- const currentPrompt = aiChatMessage.trim();
402
- setAIChatMessage('');
403
-
404
- // Reset history navigation when sending a message
405
- setHistoryIndex(-1);
406
- setCurrentDraft('');
407
-
408
- setAIErrorMessage(null); // Clear any previous errors
409
-
410
- // Track AI chat message submission
411
- const isRetry = options?.isRetry === 'true';
412
- const isUndo = options?.isUndo === 'true';
413
- if (
414
- !DEBUG &&
415
- onAIChatMessageSubmitted &&
416
- aiChatOptions?.vizId
417
- ) {
418
- onAIChatMessageSubmitted({
419
- messageLength: messageContent.trim().length,
420
- isRetry,
421
- isUndo,
422
- });
423
- }
424
-
425
- // Generate new chat ID only for fresh user messages
426
- // Keep existing chat ID for retries (Try Harder) and undos
427
- const isRetryOrUndo =
428
- options?.isRetry === 'true' ||
429
- options?.isUndo === 'true';
430
-
431
- let chatIdForRequest: string;
432
- if (isRetryOrUndo) {
433
- // Use existing chat ID for retry/undo operations
434
- chatIdForRequest = activeChatId;
435
- DEBUG &&
436
- console.log(
437
- 'Using existing chatId for retry/undo:',
438
- chatIdForRequest,
439
- );
440
- } else {
441
- // Generate NEW chat ID for fresh user message
442
- const newChatId = uuidv4();
443
- setCurrentChatId(newChatId);
444
- setSelectedChatId(newChatId);
445
- chatIdForRequest = newChatId;
446
- DEBUG &&
447
- console.log(
448
- 'Generated new chatId for fresh message:',
449
- chatIdForRequest,
450
- );
451
- }
452
-
453
- // Call backend endpoint for AI response
454
- try {
455
- const response = await fetch(aiChatEndpoint, {
456
- method: 'POST',
457
- headers: {
458
- 'Content-Type': 'application/json',
459
- },
460
- body: JSON.stringify({
461
- ...aiChatOptions,
462
- content: messageContent.trim(),
463
- chatId: chatIdForRequest,
464
- mode: aiChatMode,
465
- ...options,
466
- }),
467
- });
468
-
469
- if (!response.ok) {
470
- throw new Error(
471
- `HTTP error! status: ${response.status}`,
472
- );
473
- }
474
-
475
- // Parse the response to check for errors
476
- const responseData = await response.json();
477
-
478
- // Check if the response contains a VizHub error
479
- if (
480
- responseData.outcome === 'failure' &&
481
- responseData.error
482
- ) {
483
- const errorMessage = responseData.error.message;
484
-
485
- // Check if this is the specific permission error that should trigger auto-fork
486
- if (
487
- errorMessage ===
488
- 'You do not have permission to use AI chat on this visualization. Only users with edit access can use this feature. Fork the viz to edit it.'
489
- ) {
490
- // For authenticated users, trigger auto-fork
491
- if (autoForkAndRetryAI) {
492
- try {
493
- await autoForkAndRetryAI(
494
- currentPrompt,
495
- aiChatMode,
496
- );
497
- // If we reach here, the fork was successful and redirect should happen
498
- return;
499
- } catch (forkError) {
500
- console.error(
501
- 'Auto-fork failed:',
502
- forkError,
503
- );
504
- setAIErrorMessage(
505
- 'Failed to fork visualization. Please try forking manually.',
506
- );
507
- return;
508
- }
509
- } else {
510
- // For unauthenticated users, store the message and trigger login flow
511
- // This will be handled by the external error handler
512
- setAIErrorMessage(
513
- errorMessage,
514
- messageContent.trim(),
515
- );
516
- return;
517
- }
518
- }
519
-
520
- // For other errors, show the error message
521
- setAIErrorMessage(
522
- errorMessage,
523
- messageContent.trim(),
524
- );
525
- return;
526
- }
527
-
528
- // The backend handles all ShareDB operations for successful responses
529
- // The loading state is now managed via ShareDB aiStatus
530
- return responseData;
531
- } catch (error) {
532
- console.error('Error getting AI response:', error);
533
- setAIErrorMessage(
534
- 'Failed to send message. Please try again.',
535
- messageContent.trim(),
536
- );
537
- }
538
- },
539
- [
540
- aiChatMessage,
541
- aiChatEndpoint,
542
- aiChatOptions,
543
- activeChatId,
544
- aiChatMode,
545
- autoForkAndRetryAI,
546
- onAIChatMessageSubmitted,
547
- DEBUG,
548
- setAIErrorMessage,
549
- ],
550
- );
273
+ const {
274
+ aiChatMessage,
275
+ setAIChatMessage,
276
+ currentChatId,
277
+ selectedChatId,
278
+ setSelectedChatId,
279
+ aiErrorMessage,
280
+ setAIErrorMessage,
281
+ handleSendMessage,
282
+ navigateMessageHistoryUp,
283
+ navigateMessageHistoryDown,
284
+ resetMessageHistoryNavigation,
285
+ } = useAIChatSession({
286
+ content,
287
+ submitOperation,
288
+ aiChatMode,
289
+ aiChatEndpoint,
290
+ aiChatOptions,
291
+ autoForkAndRetryAI,
292
+ handleChatError,
293
+ onAIChatMessageSubmitted,
294
+ });
551
295
 
552
296
  // Config.json change detection and iframe notification
553
297
  // This logic was moved from VisualEditor.tsx to ensure it runs