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.
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-BfDRE_ou.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,10 +1,12 @@
1
1
  {
2
2
  "name": "vzcode",
3
- "version": "2.31.0",
3
+ "version": "2.35.0",
4
4
  "description": "Multiplayer code editor system",
5
5
  "main": "src/index.ts",
6
6
  "type": "module",
7
- "bin": "dist/cli.js",
7
+ "bin": {
8
+ "vzcode": "dist/cli.js"
9
+ },
8
10
  "files": [
9
11
  "dist/**",
10
12
  "src/**"
@@ -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
+ : [];
@@ -1,4 +1,6 @@
1
1
  import {
2
+ VZInitialSidebarView,
3
+ VisualEditorEmptyReason,
2
4
  ItemId,
3
5
  LeafPane,
4
6
  Pane,
@@ -91,6 +93,10 @@ export type VZCodeContextValue = {
91
93
  setIsSearchOpen: (isSearchOpen: boolean) => void;
92
94
  setSearch: (pattern: string) => void;
93
95
 
96
+ /** Host-provided replacement for the built-in visual-editor empty states. */
97
+ renderVisualEditorEmptyState?: (
98
+ reason: VisualEditorEmptyReason,
99
+ ) => React.ReactNode;
94
100
  isVisualEditorOpen: boolean;
95
101
  setIsVisualEditorOpen: (
96
102
  isVisualEditorOpen: boolean,
@@ -226,6 +232,12 @@ export interface VZCodeProviderProps {
226
232
  docPresence: any;
227
233
  prettierWorker: Worker;
228
234
  initialUsername: Username;
235
+ /** Initial sidebar selection; defaults to VZCode's historical AI chat. */
236
+ initialSidebarView?: VZInitialSidebarView;
237
+ /** Optional host UI for a missing/invalid/unconfigured visual editor. */
238
+ renderVisualEditorEmptyState?: (
239
+ reason: VisualEditorEmptyReason,
240
+ ) => React.ReactNode;
229
241
  children: React.ReactNode;
230
242
  codeError?: string | null;
231
243
  connected?: boolean;
@@ -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
+ }