vzcode 2.31.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.
@@ -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,
@@ -37,6 +36,8 @@ export const useVZCodeState = ({
37
36
  docPresence,
38
37
  prettierWorker,
39
38
  initialUsername,
39
+ initialSidebarView,
40
+ renderVisualEditorEmptyState,
40
41
  codeError = null,
41
42
  connected,
42
43
  pending,
@@ -101,7 +102,7 @@ export const useVZCodeState = ({
101
102
  // See https://react.dev/reference/react/useReducer
102
103
  const [state, dispatch] = useReducer(
103
104
  vzReducer,
104
- { defaultTheme, initialUsername },
105
+ { defaultTheme, initialUsername, initialSidebarView },
105
106
  createInitialState,
106
107
  );
107
108
 
@@ -269,283 +270,28 @@ export const useVZCodeState = ({
269
270
  const [voiceChatModalOpen, setVoiceChatModalOpen] =
270
271
  useState(false);
271
272
 
272
- const [aiChatMessage, setAIChatMessage] = useState('');
273
-
274
- const DEBUG = false;
275
-
276
- // Compute isLoading based on the current chat's aiStatus
277
- // Chat ID changes with each new user message (but not for retry/undo)
278
- const [currentChatId, setCurrentChatId] = useState(() =>
279
- uuidv4(),
280
- );
281
- const [selectedChatId, setSelectedChatId] = useState<
282
- string | null
283
- >(null);
284
-
285
- // Use selectedChatId if available, otherwise use currentChatId for backward compatibility
286
- const activeChatId = selectedChatId || currentChatId;
287
- const currentChat = content?.chats?.[activeChatId];
288
-
289
- // Message history for up/down arrow navigation - using ShareDB document data
290
- const messageHistory = useMemo(() => {
291
- if (!currentChat?.messages) return [];
292
- // Extract user messages in chronological order for history navigation
293
- return currentChat.messages
294
- .filter((msg) => msg.role === 'user')
295
- .map((msg) => msg.content);
296
- }, [currentChat?.messages]);
297
-
298
- const [historyIndex, setHistoryIndex] = useState(-1);
299
- const [currentDraft, setCurrentDraft] = useState('');
300
-
301
- const [aiErrorMessage, setAIErrorMessageState] = useState<
302
- string | null
303
- >(null);
304
-
305
- // Create the combined setAIErrorMessage function that calls both state setter and external callback
306
- const setAIErrorMessage = useCallback(
307
- (error: string | null, message?: string) => {
308
- setAIErrorMessageState(error);
309
- if (error && handleChatError) {
310
- handleChatError(error, message);
311
- }
312
- },
313
- [handleChatError],
314
- );
315
-
316
- // Phase 5: Restore the prompt into the chat input when the server
317
- // populates `currentChatDraft` (e.g. after Undo), then clear it so it
318
- // is applied exactly once.
319
- useEffect(() => {
320
- const draft = (content as any)?.currentChatDraft;
321
- if (typeof draft === 'string' && draft.trim()) {
322
- setAIChatMessage(draft);
323
- submitOperation((currentContent) => {
324
- const next: any = { ...currentContent };
325
- next.currentChatDraft = undefined;
326
- return next;
327
- });
328
- }
329
- // eslint-disable-next-line react-hooks/exhaustive-deps
330
- }, [(content as any)?.currentChatDraft]);
331
-
332
- // Message history navigation functions
333
- const navigateMessageHistoryUp = useCallback(() => {
334
- if (messageHistory.length === 0) return;
335
-
336
- // If we're not navigating history, save current draft
337
- if (historyIndex === -1) {
338
- setCurrentDraft(aiChatMessage);
339
- }
340
-
341
- const newIndex =
342
- historyIndex < messageHistory.length - 1
343
- ? historyIndex + 1
344
- : historyIndex;
345
- setHistoryIndex(newIndex);
346
- setAIChatMessage(
347
- messageHistory[messageHistory.length - 1 - newIndex],
348
- );
349
- }, [messageHistory, historyIndex, aiChatMessage]);
350
-
351
- const navigateMessageHistoryDown = useCallback(() => {
352
- if (historyIndex === -1) return;
353
-
354
- const newIndex = historyIndex - 1;
355
- if (newIndex === -1) {
356
- // Return to draft
357
- setHistoryIndex(-1);
358
- setAIChatMessage(currentDraft);
359
- setCurrentDraft('');
360
- } else {
361
- setHistoryIndex(newIndex);
362
- setAIChatMessage(
363
- messageHistory[
364
- messageHistory.length - 1 - newIndex
365
- ],
366
- );
367
- }
368
- }, [messageHistory, historyIndex, currentDraft]);
369
-
370
- const resetMessageHistoryNavigation = useCallback(() => {
371
- if (historyIndex !== -1) {
372
- setHistoryIndex(-1);
373
- setCurrentDraft('');
374
- }
375
- }, [historyIndex]);
376
-
377
- const handleSendMessage = useCallback(
378
- async (
379
- messageToSend?: string,
380
- options?: Record<string, string>,
381
- ) => {
382
- DEBUG &&
383
- console.log(
384
- 'AIChat: handleSendMessage called with:',
385
- messageToSend,
386
- 'aiChatMessage:',
387
- aiChatMessage,
388
- );
389
- const messageContent = messageToSend || aiChatMessage;
390
-
391
- if (
392
- !messageContent ||
393
- typeof messageContent !== 'string' ||
394
- !messageContent.trim()
395
- ) {
396
- return;
397
- }
398
-
399
- const currentPrompt = aiChatMessage.trim();
400
- setAIChatMessage('');
401
-
402
- // Reset history navigation when sending a message
403
- setHistoryIndex(-1);
404
- setCurrentDraft('');
405
-
406
- setAIErrorMessage(null); // Clear any previous errors
407
-
408
- // Track AI chat message submission
409
- const isRetry = options?.isRetry === 'true';
410
- const isUndo = options?.isUndo === 'true';
411
- if (
412
- !DEBUG &&
413
- onAIChatMessageSubmitted &&
414
- aiChatOptions?.vizId
415
- ) {
416
- onAIChatMessageSubmitted({
417
- messageLength: messageContent.trim().length,
418
- isRetry,
419
- isUndo,
420
- });
421
- }
422
-
423
- // Generate new chat ID only for fresh user messages
424
- // Keep existing chat ID for retries (Try Harder) and undos
425
- const isRetryOrUndo =
426
- options?.isRetry === 'true' ||
427
- options?.isUndo === 'true';
428
-
429
- let chatIdForRequest: string;
430
- if (isRetryOrUndo) {
431
- // Use existing chat ID for retry/undo operations
432
- chatIdForRequest = activeChatId;
433
- DEBUG &&
434
- console.log(
435
- 'Using existing chatId for retry/undo:',
436
- chatIdForRequest,
437
- );
438
- } else {
439
- // Generate NEW chat ID for fresh user message
440
- const newChatId = uuidv4();
441
- setCurrentChatId(newChatId);
442
- setSelectedChatId(newChatId);
443
- chatIdForRequest = newChatId;
444
- DEBUG &&
445
- console.log(
446
- 'Generated new chatId for fresh message:',
447
- chatIdForRequest,
448
- );
449
- }
450
-
451
- // Call backend endpoint for AI response
452
- try {
453
- const response = await fetch(aiChatEndpoint, {
454
- method: 'POST',
455
- headers: {
456
- 'Content-Type': 'application/json',
457
- },
458
- body: JSON.stringify({
459
- ...aiChatOptions,
460
- content: messageContent.trim(),
461
- chatId: chatIdForRequest,
462
- mode: aiChatMode,
463
- ...options,
464
- }),
465
- });
466
-
467
- if (!response.ok) {
468
- throw new Error(
469
- `HTTP error! status: ${response.status}`,
470
- );
471
- }
472
-
473
- // Parse the response to check for errors
474
- const responseData = await response.json();
475
-
476
- // Check if the response contains a VizHub error
477
- if (
478
- responseData.outcome === 'failure' &&
479
- responseData.error
480
- ) {
481
- const errorMessage = responseData.error.message;
482
-
483
- // Check if this is the specific permission error that should trigger auto-fork
484
- if (
485
- errorMessage ===
486
- '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.'
487
- ) {
488
- // For authenticated users, trigger auto-fork
489
- if (autoForkAndRetryAI) {
490
- try {
491
- await autoForkAndRetryAI(
492
- currentPrompt,
493
- aiChatMode,
494
- );
495
- // If we reach here, the fork was successful and redirect should happen
496
- return;
497
- } catch (forkError) {
498
- console.error(
499
- 'Auto-fork failed:',
500
- forkError,
501
- );
502
- setAIErrorMessage(
503
- 'Failed to fork visualization. Please try forking manually.',
504
- );
505
- return;
506
- }
507
- } else {
508
- // For unauthenticated users, store the message and trigger login flow
509
- // This will be handled by the external error handler
510
- setAIErrorMessage(
511
- errorMessage,
512
- messageContent.trim(),
513
- );
514
- return;
515
- }
516
- }
517
-
518
- // For other errors, show the error message
519
- setAIErrorMessage(
520
- errorMessage,
521
- messageContent.trim(),
522
- );
523
- return;
524
- }
525
-
526
- // The backend handles all ShareDB operations for successful responses
527
- // The loading state is now managed via ShareDB aiStatus
528
- return responseData;
529
- } catch (error) {
530
- console.error('Error getting AI response:', error);
531
- setAIErrorMessage(
532
- 'Failed to send message. Please try again.',
533
- messageContent.trim(),
534
- );
535
- }
536
- },
537
- [
538
- aiChatMessage,
539
- aiChatEndpoint,
540
- aiChatOptions,
541
- activeChatId,
542
- aiChatMode,
543
- autoForkAndRetryAI,
544
- onAIChatMessageSubmitted,
545
- DEBUG,
546
- setAIErrorMessage,
547
- ],
548
- );
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
+ });
549
295
 
550
296
  // Config.json change detection and iframe notification
551
297
  // This logic was moved from VisualEditor.tsx to ensure it runs
@@ -670,6 +416,7 @@ export const useVZCodeState = ({
670
416
  setSearchFocusedIndex,
671
417
  toggleSearchFocused,
672
418
 
419
+ renderVisualEditorEmptyState,
673
420
  isVisualEditorOpen,
674
421
  setIsVisualEditorOpen,
675
422