Stijnus commited on
Commit
9230ef3
·
unverified ·
2 Parent(s): 8f3f37a e196442

Merge branch 'stackblitz-labs:main' into FEAT_BoltDYI_NEW_SETTINGS_UI

Browse files
app/components/chat/BaseChat.tsx CHANGED
@@ -3,13 +3,13 @@
3
  * Preventing TS checks with files presented in the video for a better presentation.
4
  */
5
  import type { Message } from 'ai';
6
- import React, { type RefCallback, useCallback, useEffect, useState } from 'react';
7
  import { ClientOnly } from 'remix-utils/client-only';
8
  import { Menu } from '~/components/sidebar/Menu.client';
9
  import { IconButton } from '~/components/ui/IconButton';
10
  import { Workbench } from '~/components/workbench/Workbench.client';
11
  import { classNames } from '~/utils/classNames';
12
- import { MODEL_LIST, PROVIDER_LIST, initializeModelList } from '~/utils/constants';
13
  import { Messages } from './Messages.client';
14
  import { SendButton } from './SendButton.client';
15
  import { APIKeyManager, getApiKeysFromCookies } from './APIKeyManager';
@@ -25,13 +25,13 @@ import GitCloneButton from './GitCloneButton';
25
  import FilePreview from './FilePreview';
26
  import { ModelSelector } from '~/components/chat/ModelSelector';
27
  import { SpeechRecognitionButton } from '~/components/chat/SpeechRecognition';
28
- import type { IProviderSetting, ProviderInfo } from '~/types/model';
29
  import { ScreenshotStateManager } from './ScreenshotStateManager';
30
  import { toast } from 'react-toastify';
31
  import StarterTemplates from './StarterTemplates';
32
  import type { ActionAlert } from '~/types/actions';
33
  import ChatAlert from './ChatAlert';
34
- import { LLMManager } from '~/lib/modules/llm/manager';
35
 
36
  const TEXTAREA_MIN_HEIGHT = 76;
37
 
@@ -102,35 +102,13 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
102
  ) => {
103
  const TEXTAREA_MAX_HEIGHT = chatStarted ? 400 : 200;
104
  const [apiKeys, setApiKeys] = useState<Record<string, string>>(getApiKeysFromCookies());
105
- const [modelList, setModelList] = useState(MODEL_LIST);
106
  const [isModelSettingsCollapsed, setIsModelSettingsCollapsed] = useState(false);
107
  const [isListening, setIsListening] = useState(false);
108
  const [recognition, setRecognition] = useState<SpeechRecognition | null>(null);
109
  const [transcript, setTranscript] = useState('');
110
  const [isModelLoading, setIsModelLoading] = useState<string | undefined>('all');
111
 
112
- const getProviderSettings = useCallback(() => {
113
- let providerSettings: Record<string, IProviderSetting> | undefined = undefined;
114
-
115
- try {
116
- const savedProviderSettings = Cookies.get('providers');
117
-
118
- if (savedProviderSettings) {
119
- const parsedProviderSettings = JSON.parse(savedProviderSettings);
120
-
121
- if (typeof parsedProviderSettings === 'object' && parsedProviderSettings !== null) {
122
- providerSettings = parsedProviderSettings;
123
- }
124
- }
125
- } catch (error) {
126
- console.error('Error loading Provider Settings from cookies:', error);
127
-
128
- // Clear invalid cookie data
129
- Cookies.remove('providers');
130
- }
131
-
132
- return providerSettings;
133
- }, []);
134
  useEffect(() => {
135
  console.log(transcript);
136
  }, [transcript]);
@@ -169,7 +147,6 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
169
 
170
  useEffect(() => {
171
  if (typeof window !== 'undefined') {
172
- const providerSettings = getProviderSettings();
173
  let parsedApiKeys: Record<string, string> | undefined = {};
174
 
175
  try {
@@ -177,17 +154,18 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
177
  setApiKeys(parsedApiKeys);
178
  } catch (error) {
179
  console.error('Error loading API keys from cookies:', error);
180
-
181
- // Clear invalid cookie data
182
  Cookies.remove('apiKeys');
183
  }
 
184
  setIsModelLoading('all');
185
- initializeModelList({ apiKeys: parsedApiKeys, providerSettings })
186
- .then((modelList) => {
187
- setModelList(modelList);
 
 
188
  })
189
  .catch((error) => {
190
- console.error('Error initializing model list:', error);
191
  })
192
  .finally(() => {
193
  setIsModelLoading(undefined);
@@ -200,29 +178,24 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
200
  setApiKeys(newApiKeys);
201
  Cookies.set('apiKeys', JSON.stringify(newApiKeys));
202
 
203
- const provider = LLMManager.getInstance(import.meta.env || process.env || {}).getProvider(providerName);
204
 
205
- if (provider && provider.getDynamicModels) {
206
- setIsModelLoading(providerName);
207
 
208
- try {
209
- const providerSettings = getProviderSettings();
210
- const staticModels = provider.staticModels;
211
- const dynamicModels = await provider.getDynamicModels(
212
- newApiKeys,
213
- providerSettings,
214
- import.meta.env || process.env || {},
215
- );
216
-
217
- setModelList((preModels) => {
218
- const filteredOutPreModels = preModels.filter((x) => x.provider !== providerName);
219
- return [...filteredOutPreModels, ...staticModels, ...dynamicModels];
220
- });
221
- } catch (error) {
222
- console.error('Error loading dynamic models:', error);
223
- }
224
- setIsModelLoading(undefined);
225
  }
 
 
 
 
 
 
 
226
  };
227
 
228
  const startListening = () => {
 
3
  * Preventing TS checks with files presented in the video for a better presentation.
4
  */
5
  import type { Message } from 'ai';
6
+ import React, { type RefCallback, useEffect, useState } from 'react';
7
  import { ClientOnly } from 'remix-utils/client-only';
8
  import { Menu } from '~/components/sidebar/Menu.client';
9
  import { IconButton } from '~/components/ui/IconButton';
10
  import { Workbench } from '~/components/workbench/Workbench.client';
11
  import { classNames } from '~/utils/classNames';
12
+ import { PROVIDER_LIST } from '~/utils/constants';
13
  import { Messages } from './Messages.client';
14
  import { SendButton } from './SendButton.client';
15
  import { APIKeyManager, getApiKeysFromCookies } from './APIKeyManager';
 
25
  import FilePreview from './FilePreview';
26
  import { ModelSelector } from '~/components/chat/ModelSelector';
27
  import { SpeechRecognitionButton } from '~/components/chat/SpeechRecognition';
28
+ import type { ProviderInfo } from '~/types/model';
29
  import { ScreenshotStateManager } from './ScreenshotStateManager';
30
  import { toast } from 'react-toastify';
31
  import StarterTemplates from './StarterTemplates';
32
  import type { ActionAlert } from '~/types/actions';
33
  import ChatAlert from './ChatAlert';
34
+ import type { ModelInfo } from '~/lib/modules/llm/types';
35
 
36
  const TEXTAREA_MIN_HEIGHT = 76;
37
 
 
102
  ) => {
103
  const TEXTAREA_MAX_HEIGHT = chatStarted ? 400 : 200;
104
  const [apiKeys, setApiKeys] = useState<Record<string, string>>(getApiKeysFromCookies());
105
+ const [modelList, setModelList] = useState<ModelInfo[]>([]);
106
  const [isModelSettingsCollapsed, setIsModelSettingsCollapsed] = useState(false);
107
  const [isListening, setIsListening] = useState(false);
108
  const [recognition, setRecognition] = useState<SpeechRecognition | null>(null);
109
  const [transcript, setTranscript] = useState('');
110
  const [isModelLoading, setIsModelLoading] = useState<string | undefined>('all');
111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  useEffect(() => {
113
  console.log(transcript);
114
  }, [transcript]);
 
147
 
148
  useEffect(() => {
149
  if (typeof window !== 'undefined') {
 
150
  let parsedApiKeys: Record<string, string> | undefined = {};
151
 
152
  try {
 
154
  setApiKeys(parsedApiKeys);
155
  } catch (error) {
156
  console.error('Error loading API keys from cookies:', error);
 
 
157
  Cookies.remove('apiKeys');
158
  }
159
+
160
  setIsModelLoading('all');
161
+ fetch('/api/models')
162
+ .then((response) => response.json())
163
+ .then((data) => {
164
+ const typedData = data as { modelList: ModelInfo[] };
165
+ setModelList(typedData.modelList);
166
  })
167
  .catch((error) => {
168
+ console.error('Error fetching model list:', error);
169
  })
170
  .finally(() => {
171
  setIsModelLoading(undefined);
 
178
  setApiKeys(newApiKeys);
179
  Cookies.set('apiKeys', JSON.stringify(newApiKeys));
180
 
181
+ setIsModelLoading(providerName);
182
 
183
+ let providerModels: ModelInfo[] = [];
 
184
 
185
+ try {
186
+ const response = await fetch(`/api/models/${encodeURIComponent(providerName)}`);
187
+ const data = await response.json();
188
+ providerModels = (data as { modelList: ModelInfo[] }).modelList;
189
+ } catch (error) {
190
+ console.error('Error loading dynamic models for:', providerName, error);
 
 
 
 
 
 
 
 
 
 
 
191
  }
192
+
193
+ // Only update models for the specific provider
194
+ setModelList((prevModels) => {
195
+ const otherModels = prevModels.filter((model) => model.provider !== providerName);
196
+ return [...otherModels, ...providerModels];
197
+ });
198
+ setIsModelLoading(undefined);
199
  };
200
 
201
  const startListening = () => {
app/components/workbench/Preview.tsx CHANGED
@@ -1,5 +1,5 @@
1
- import { useStore } from '@nanostores/react';
2
  import { memo, useCallback, useEffect, useRef, useState } from 'react';
 
3
  import { IconButton } from '~/components/ui/IconButton';
4
  import { workbenchStore } from '~/lib/stores/workbench';
5
  import { PortDropdown } from './PortDropdown';
@@ -7,6 +7,19 @@ import { ScreenshotSelector } from './ScreenshotSelector';
7
 
8
  type ResizeSide = 'left' | 'right' | null;
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  export const Preview = memo(() => {
11
  const iframeRef = useRef<HTMLIFrameElement>(null);
12
  const containerRef = useRef<HTMLDivElement>(null);
@@ -15,6 +28,7 @@ export const Preview = memo(() => {
15
  const [activePreviewIndex, setActivePreviewIndex] = useState(0);
16
  const [isPortDropdownOpen, setIsPortDropdownOpen] = useState(false);
17
  const [isFullscreen, setIsFullscreen] = useState(false);
 
18
  const hasSelectedPreview = useRef(false);
19
  const previews = useStore(workbenchStore.previews);
20
  const activePreview = previews[activePreviewIndex];
@@ -27,7 +41,7 @@ export const Preview = memo(() => {
27
  const [isDeviceModeOn, setIsDeviceModeOn] = useState(false);
28
 
29
  // Use percentage for width
30
- const [widthPercent, setWidthPercent] = useState<number>(37.5); // 375px assuming 1000px window width initially
31
 
32
  const resizingState = useRef({
33
  isResizing: false,
@@ -37,8 +51,10 @@ export const Preview = memo(() => {
37
  windowWidth: window.innerWidth,
38
  });
39
 
40
- // Define the scaling factor
41
- const SCALING_FACTOR = 2; // Adjust this value to increase/decrease sensitivity
 
 
42
 
43
  useEffect(() => {
44
  if (!activePreview) {
@@ -79,7 +95,6 @@ export const Preview = memo(() => {
79
  [],
80
  );
81
 
82
- // When previews change, display the lowest port if user hasn't selected a preview
83
  useEffect(() => {
84
  if (previews.length > 1 && !hasSelectedPreview.current) {
85
  const minPortIndex = previews.reduce(findMinPortIndex, 0);
@@ -122,7 +137,6 @@ export const Preview = memo(() => {
122
  return;
123
  }
124
 
125
- // Prevent text selection
126
  document.body.style.userSelect = 'none';
127
 
128
  resizingState.current.isResizing = true;
@@ -134,7 +148,7 @@ export const Preview = memo(() => {
134
  document.addEventListener('mousemove', onMouseMove);
135
  document.addEventListener('mouseup', onMouseUp);
136
 
137
- e.preventDefault(); // Prevent any text selection on mousedown
138
  };
139
 
140
  const onMouseMove = (e: MouseEvent) => {
@@ -145,7 +159,6 @@ export const Preview = memo(() => {
145
  const dx = e.clientX - resizingState.current.startX;
146
  const windowWidth = resizingState.current.windowWidth;
147
 
148
- // Apply scaling factor to increase sensitivity
149
  const dxPercent = (dx / windowWidth) * 100 * SCALING_FACTOR;
150
 
151
  let newWidthPercent = resizingState.current.startWidthPercent;
@@ -156,7 +169,6 @@ export const Preview = memo(() => {
156
  newWidthPercent = resizingState.current.startWidthPercent - dxPercent;
157
  }
158
 
159
- // Clamp the width between 10% and 90%
160
  newWidthPercent = Math.max(10, Math.min(newWidthPercent, 90));
161
 
162
  setWidthPercent(newWidthPercent);
@@ -168,17 +180,12 @@ export const Preview = memo(() => {
168
  document.removeEventListener('mousemove', onMouseMove);
169
  document.removeEventListener('mouseup', onMouseUp);
170
 
171
- // Restore text selection
172
  document.body.style.userSelect = '';
173
  };
174
 
175
- // Handle window resize to ensure widthPercent remains valid
176
  useEffect(() => {
177
  const handleWindowResize = () => {
178
- /*
179
- * Optional: Adjust widthPercent if necessary
180
- * For now, since widthPercent is relative, no action is needed
181
- */
182
  };
183
 
184
  window.addEventListener('resize', handleWindowResize);
@@ -188,7 +195,6 @@ export const Preview = memo(() => {
188
  };
189
  }, []);
190
 
191
- // A small helper component for the handle's "grip" icon
192
  const GripIcon = () => (
193
  <div
194
  style={{
@@ -213,8 +219,33 @@ export const Preview = memo(() => {
213
  </div>
214
  );
215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
  return (
217
- <div ref={containerRef} className="w-full h-full flex flex-col relative">
 
 
 
218
  {isPortDropdownOpen && (
219
  <div className="z-iframe-overlay w-full h-full absolute" onClick={() => setIsPortDropdownOpen(false)} />
220
  )}
@@ -225,10 +256,7 @@ export const Preview = memo(() => {
225
  onClick={() => setIsSelectionMode(!isSelectionMode)}
226
  className={isSelectionMode ? 'bg-bolt-elements-background-depth-3' : ''}
227
  />
228
- <div
229
- className="flex items-center gap-1 flex-grow bg-bolt-elements-preview-addressBar-background border border-bolt-elements-borderColor text-bolt-elements-preview-addressBar-text rounded-full px-3 py-1 text-sm hover:bg-bolt-elements-preview-addressBar-backgroundHover hover:focus-within:bg-bolt-elements-preview-addressBar-backgroundActive focus-within:bg-bolt-elements-preview-addressBar-backgroundActive
230
- focus-within-border-bolt-elements-borderColorActive focus-within:text-bolt-elements-preview-addressBar-textActive"
231
- >
232
  <input
233
  title="URL"
234
  ref={inputRef}
@@ -261,26 +289,65 @@ export const Preview = memo(() => {
261
  />
262
  )}
263
 
264
- {/* Device mode toggle button */}
265
  <IconButton
266
  icon="i-ph:devices"
267
  onClick={toggleDeviceMode}
268
  title={isDeviceModeOn ? 'Switch to Responsive Mode' : 'Switch to Device Mode'}
269
  />
270
 
271
- {/* Fullscreen toggle button */}
 
 
 
 
 
272
  <IconButton
273
  icon={isFullscreen ? 'i-ph:arrows-in' : 'i-ph:arrows-out'}
274
  onClick={toggleFullscreen}
275
  title={isFullscreen ? 'Exit Full Screen' : 'Full Screen'}
276
  />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
  </div>
278
 
279
  <div className="flex-1 border-t border-bolt-elements-borderColor flex justify-center items-center overflow-auto">
280
  <div
281
  style={{
282
  width: isDeviceModeOn ? `${widthPercent}%` : '100%',
283
- height: '100%', // Always full height
284
  overflow: 'visible',
285
  background: '#fff',
286
  position: 'relative',
@@ -294,7 +361,8 @@ export const Preview = memo(() => {
294
  title="preview"
295
  className="border-none w-full h-full bg-white"
296
  src={iframeUrl}
297
- allowFullScreen
 
298
  />
299
  <ScreenshotSelector
300
  isSelectionMode={isSelectionMode}
@@ -308,7 +376,6 @@ export const Preview = memo(() => {
308
 
309
  {isDeviceModeOn && (
310
  <>
311
- {/* Left handle */}
312
  <div
313
  onMouseDown={(e) => startResizing(e, 'left')}
314
  style={{
@@ -333,7 +400,6 @@ export const Preview = memo(() => {
333
  <GripIcon />
334
  </div>
335
 
336
- {/* Right handle */}
337
  <div
338
  onMouseDown={(e) => startResizing(e, 'right')}
339
  style={{
 
 
1
  import { memo, useCallback, useEffect, useRef, useState } from 'react';
2
+ import { useStore } from '@nanostores/react';
3
  import { IconButton } from '~/components/ui/IconButton';
4
  import { workbenchStore } from '~/lib/stores/workbench';
5
  import { PortDropdown } from './PortDropdown';
 
7
 
8
  type ResizeSide = 'left' | 'right' | null;
9
 
10
+ interface WindowSize {
11
+ name: string;
12
+ width: number;
13
+ height: number;
14
+ }
15
+
16
+ const WINDOW_SIZES: WindowSize[] = [
17
+ { name: 'Mobile (375x667)', width: 375, height: 667 },
18
+ { name: 'Tablet (768x1024)', width: 768, height: 1024 },
19
+ { name: 'Laptop (1366x768)', width: 1366, height: 768 },
20
+ { name: 'Desktop (1920x1080)', width: 1920, height: 1080 },
21
+ ];
22
+
23
  export const Preview = memo(() => {
24
  const iframeRef = useRef<HTMLIFrameElement>(null);
25
  const containerRef = useRef<HTMLDivElement>(null);
 
28
  const [activePreviewIndex, setActivePreviewIndex] = useState(0);
29
  const [isPortDropdownOpen, setIsPortDropdownOpen] = useState(false);
30
  const [isFullscreen, setIsFullscreen] = useState(false);
31
+ const [isPreviewOnly, setIsPreviewOnly] = useState(false);
32
  const hasSelectedPreview = useRef(false);
33
  const previews = useStore(workbenchStore.previews);
34
  const activePreview = previews[activePreviewIndex];
 
41
  const [isDeviceModeOn, setIsDeviceModeOn] = useState(false);
42
 
43
  // Use percentage for width
44
+ const [widthPercent, setWidthPercent] = useState<number>(37.5);
45
 
46
  const resizingState = useRef({
47
  isResizing: false,
 
51
  windowWidth: window.innerWidth,
52
  });
53
 
54
+ const SCALING_FACTOR = 2;
55
+
56
+ const [isWindowSizeDropdownOpen, setIsWindowSizeDropdownOpen] = useState(false);
57
+ const [selectedWindowSize, setSelectedWindowSize] = useState<WindowSize>(WINDOW_SIZES[0]);
58
 
59
  useEffect(() => {
60
  if (!activePreview) {
 
95
  [],
96
  );
97
 
 
98
  useEffect(() => {
99
  if (previews.length > 1 && !hasSelectedPreview.current) {
100
  const minPortIndex = previews.reduce(findMinPortIndex, 0);
 
137
  return;
138
  }
139
 
 
140
  document.body.style.userSelect = 'none';
141
 
142
  resizingState.current.isResizing = true;
 
148
  document.addEventListener('mousemove', onMouseMove);
149
  document.addEventListener('mouseup', onMouseUp);
150
 
151
+ e.preventDefault();
152
  };
153
 
154
  const onMouseMove = (e: MouseEvent) => {
 
159
  const dx = e.clientX - resizingState.current.startX;
160
  const windowWidth = resizingState.current.windowWidth;
161
 
 
162
  const dxPercent = (dx / windowWidth) * 100 * SCALING_FACTOR;
163
 
164
  let newWidthPercent = resizingState.current.startWidthPercent;
 
169
  newWidthPercent = resizingState.current.startWidthPercent - dxPercent;
170
  }
171
 
 
172
  newWidthPercent = Math.max(10, Math.min(newWidthPercent, 90));
173
 
174
  setWidthPercent(newWidthPercent);
 
180
  document.removeEventListener('mousemove', onMouseMove);
181
  document.removeEventListener('mouseup', onMouseUp);
182
 
 
183
  document.body.style.userSelect = '';
184
  };
185
 
 
186
  useEffect(() => {
187
  const handleWindowResize = () => {
188
+ // Optional: Adjust widthPercent if necessary
 
 
 
189
  };
190
 
191
  window.addEventListener('resize', handleWindowResize);
 
195
  };
196
  }, []);
197
 
 
198
  const GripIcon = () => (
199
  <div
200
  style={{
 
219
  </div>
220
  );
221
 
222
+ const openInNewWindow = (size: WindowSize) => {
223
+ if (activePreview?.baseUrl) {
224
+ const match = activePreview.baseUrl.match(/^https?:\/\/([^.]+)\.local-credentialless\.webcontainer-api\.io/);
225
+
226
+ if (match) {
227
+ const previewId = match[1];
228
+ const previewUrl = `/webcontainer/preview/${previewId}`;
229
+ const newWindow = window.open(
230
+ previewUrl,
231
+ '_blank',
232
+ `noopener,noreferrer,width=${size.width},height=${size.height},menubar=no,toolbar=no,location=no,status=no`,
233
+ );
234
+
235
+ if (newWindow) {
236
+ newWindow.focus();
237
+ }
238
+ } else {
239
+ console.warn('[Preview] Invalid WebContainer URL:', activePreview.baseUrl);
240
+ }
241
+ }
242
+ };
243
+
244
  return (
245
+ <div
246
+ ref={containerRef}
247
+ className={`w-full h-full flex flex-col relative ${isPreviewOnly ? 'fixed inset-0 z-50 bg-white' : ''}`}
248
+ >
249
  {isPortDropdownOpen && (
250
  <div className="z-iframe-overlay w-full h-full absolute" onClick={() => setIsPortDropdownOpen(false)} />
251
  )}
 
256
  onClick={() => setIsSelectionMode(!isSelectionMode)}
257
  className={isSelectionMode ? 'bg-bolt-elements-background-depth-3' : ''}
258
  />
259
+ <div className="flex items-center gap-1 flex-grow bg-bolt-elements-preview-addressBar-background border border-bolt-elements-borderColor text-bolt-elements-preview-addressBar-text rounded-full px-3 py-1 text-sm hover:bg-bolt-elements-preview-addressBar-backgroundHover hover:focus-within:bg-bolt-elements-preview-addressBar-backgroundActive focus-within:bg-bolt-elements-preview-addressBar-backgroundActive focus-within-border-bolt-elements-borderColorActive focus-within:text-bolt-elements-preview-addressBar-textActive">
 
 
 
260
  <input
261
  title="URL"
262
  ref={inputRef}
 
289
  />
290
  )}
291
 
 
292
  <IconButton
293
  icon="i-ph:devices"
294
  onClick={toggleDeviceMode}
295
  title={isDeviceModeOn ? 'Switch to Responsive Mode' : 'Switch to Device Mode'}
296
  />
297
 
298
+ <IconButton
299
+ icon="i-ph:layout-light"
300
+ onClick={() => setIsPreviewOnly(!isPreviewOnly)}
301
+ title={isPreviewOnly ? 'Show Full Interface' : 'Show Preview Only'}
302
+ />
303
+
304
  <IconButton
305
  icon={isFullscreen ? 'i-ph:arrows-in' : 'i-ph:arrows-out'}
306
  onClick={toggleFullscreen}
307
  title={isFullscreen ? 'Exit Full Screen' : 'Full Screen'}
308
  />
309
+
310
+ <div className="relative">
311
+ <IconButton
312
+ icon="i-ph:arrow-square-out"
313
+ onClick={() => openInNewWindow(selectedWindowSize)}
314
+ title={`Open Preview in ${selectedWindowSize.name} Window`}
315
+ />
316
+ <IconButton
317
+ icon="i-ph:caret-down"
318
+ onClick={() => setIsWindowSizeDropdownOpen(!isWindowSizeDropdownOpen)}
319
+ className="ml-1"
320
+ title="Select Window Size"
321
+ />
322
+
323
+ {isWindowSizeDropdownOpen && (
324
+ <>
325
+ <div className="fixed inset-0 z-50" onClick={() => setIsWindowSizeDropdownOpen(false)} />
326
+ <div className="absolute right-0 top-full mt-1 z-50 bg-bolt-elements-background-depth-2 rounded-lg shadow-lg border border-bolt-elements-borderColor overflow-hidden">
327
+ {WINDOW_SIZES.map((size) => (
328
+ <button
329
+ key={size.name}
330
+ className="w-full px-4 py-2 text-left hover:bg-bolt-elements-background-depth-3 text-sm whitespace-nowrap"
331
+ onClick={() => {
332
+ setSelectedWindowSize(size);
333
+ setIsWindowSizeDropdownOpen(false);
334
+ openInNewWindow(size);
335
+ }}
336
+ >
337
+ {size.name}
338
+ </button>
339
+ ))}
340
+ </div>
341
+ </>
342
+ )}
343
+ </div>
344
  </div>
345
 
346
  <div className="flex-1 border-t border-bolt-elements-borderColor flex justify-center items-center overflow-auto">
347
  <div
348
  style={{
349
  width: isDeviceModeOn ? `${widthPercent}%` : '100%',
350
+ height: '100%',
351
  overflow: 'visible',
352
  background: '#fff',
353
  position: 'relative',
 
361
  title="preview"
362
  className="border-none w-full h-full bg-white"
363
  src={iframeUrl}
364
+ sandbox="allow-scripts allow-forms allow-popups allow-modals allow-storage-access-by-user-activation allow-same-origin"
365
+ allow="cross-origin-isolated"
366
  />
367
  <ScreenshotSelector
368
  isSelectionMode={isSelectionMode}
 
376
 
377
  {isDeviceModeOn && (
378
  <>
 
379
  <div
380
  onMouseDown={(e) => startResizing(e, 'left')}
381
  style={{
 
400
  <GripIcon />
401
  </div>
402
 
 
403
  <div
404
  onMouseDown={(e) => startResizing(e, 'right')}
405
  style={{
app/lib/api/cookies.ts ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export function parseCookies(cookieHeader: string | null) {
2
+ const cookies: Record<string, string> = {};
3
+
4
+ if (!cookieHeader) {
5
+ return cookies;
6
+ }
7
+
8
+ // Split the cookie string by semicolons and spaces
9
+ const items = cookieHeader.split(';').map((cookie) => cookie.trim());
10
+
11
+ items.forEach((item) => {
12
+ const [name, ...rest] = item.split('=');
13
+
14
+ if (name && rest.length > 0) {
15
+ // Decode the name and value, and join value parts in case it contains '='
16
+ const decodedName = decodeURIComponent(name.trim());
17
+ const decodedValue = decodeURIComponent(rest.join('=').trim());
18
+ cookies[decodedName] = decodedValue;
19
+ }
20
+ });
21
+
22
+ return cookies;
23
+ }
24
+
25
+ export function getApiKeysFromCookie(cookieHeader: string | null): Record<string, string> {
26
+ const cookies = parseCookies(cookieHeader);
27
+ return cookies.apiKeys ? JSON.parse(cookies.apiKeys) : {};
28
+ }
29
+
30
+ export function getProviderSettingsFromCookie(cookieHeader: string | null): Record<string, any> {
31
+ const cookies = parseCookies(cookieHeader);
32
+ return cookies.providers ? JSON.parse(cookies.providers) : {};
33
+ }
app/lib/modules/llm/manager.ts CHANGED
@@ -83,7 +83,7 @@ export class LLMManager {
83
 
84
  let enabledProviders = Array.from(this._providers.values()).map((p) => p.name);
85
 
86
- if (providerSettings) {
87
  enabledProviders = enabledProviders.filter((p) => providerSettings[p].enabled);
88
  }
89
 
 
83
 
84
  let enabledProviders = Array.from(this._providers.values()).map((p) => p.name);
85
 
86
+ if (providerSettings && Object.keys(providerSettings).length > 0) {
87
  enabledProviders = enabledProviders.filter((p) => providerSettings[p].enabled);
88
  }
89
 
app/lib/modules/llm/providers/github.ts ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { BaseProvider } from '~/lib/modules/llm/base-provider';
2
+ import type { ModelInfo } from '~/lib/modules/llm/types';
3
+ import type { IProviderSetting } from '~/types/model';
4
+ import type { LanguageModelV1 } from 'ai';
5
+ import { createOpenAI } from '@ai-sdk/openai';
6
+
7
+ export default class GithubProvider extends BaseProvider {
8
+ name = 'Github';
9
+ getApiKeyLink = 'https://github.com/settings/personal-access-tokens';
10
+
11
+ config = {
12
+ apiTokenKey: 'GITHUB_API_KEY',
13
+ };
14
+ // find more in https://github.com/marketplace?type=models
15
+ staticModels: ModelInfo[] = [
16
+ { name: 'gpt-4o', label: 'GPT-4o', provider: 'Github', maxTokenAllowed: 8000 },
17
+ { name: 'o1', label: 'o1-preview', provider: 'Github', maxTokenAllowed: 100000 },
18
+ { name: 'o1-mini', label: 'o1-mini', provider: 'Github', maxTokenAllowed: 8000 },
19
+ { name: 'gpt-4o-mini', label: 'GPT-4o Mini', provider: 'Github', maxTokenAllowed: 8000 },
20
+ { name: 'gpt-4-turbo', label: 'GPT-4 Turbo', provider: 'Github', maxTokenAllowed: 8000 },
21
+ { name: 'gpt-4', label: 'GPT-4', provider: 'Github', maxTokenAllowed: 8000 },
22
+ { name: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo', provider: 'Github', maxTokenAllowed: 8000 },
23
+ ];
24
+
25
+ getModelInstance(options: {
26
+ model: string;
27
+ serverEnv: Env;
28
+ apiKeys?: Record<string, string>;
29
+ providerSettings?: Record<string, IProviderSetting>;
30
+ }): LanguageModelV1 {
31
+ const { model, serverEnv, apiKeys, providerSettings } = options;
32
+
33
+ const { apiKey } = this.getProviderBaseUrlAndKey({
34
+ apiKeys,
35
+ providerSettings: providerSettings?.[this.name],
36
+ serverEnv: serverEnv as any,
37
+ defaultBaseUrlKey: '',
38
+ defaultApiTokenKey: 'GITHUB_API_KEY',
39
+ });
40
+
41
+ if (!apiKey) {
42
+ throw new Error(`Missing API key for ${this.name} provider`);
43
+ }
44
+
45
+ const openai = createOpenAI({
46
+ baseURL: 'https://models.inference.ai.azure.com',
47
+ apiKey,
48
+ });
49
+
50
+ return openai(model);
51
+ }
52
+ }
app/lib/modules/llm/registry.ts CHANGED
@@ -15,6 +15,7 @@ import TogetherProvider from './providers/together';
15
  import XAIProvider from './providers/xai';
16
  import HyperbolicProvider from './providers/hyperbolic';
17
  import AmazonBedrockProvider from './providers/amazon-bedrock';
 
18
 
19
  export {
20
  AnthropicProvider,
@@ -34,4 +35,5 @@ export {
34
  TogetherProvider,
35
  LMStudioProvider,
36
  AmazonBedrockProvider,
 
37
  };
 
15
  import XAIProvider from './providers/xai';
16
  import HyperbolicProvider from './providers/hyperbolic';
17
  import AmazonBedrockProvider from './providers/amazon-bedrock';
18
+ import GithubProvider from './providers/github';
19
 
20
  export {
21
  AnthropicProvider,
 
35
  TogetherProvider,
36
  LMStudioProvider,
37
  AmazonBedrockProvider,
38
+ GithubProvider,
39
  };
app/lib/stores/previews.ts CHANGED
@@ -1,27 +1,192 @@
1
  import type { WebContainer } from '@webcontainer/api';
2
  import { atom } from 'nanostores';
3
 
 
 
 
 
 
 
 
4
  export interface PreviewInfo {
5
  port: number;
6
  ready: boolean;
7
  baseUrl: string;
8
  }
9
 
 
 
 
10
  export class PreviewsStore {
11
  #availablePreviews = new Map<number, PreviewInfo>();
12
  #webcontainer: Promise<WebContainer>;
 
 
 
 
 
 
13
 
14
  previews = atom<PreviewInfo[]>([]);
15
 
16
  constructor(webcontainerPromise: Promise<WebContainer>) {
17
  this.#webcontainer = webcontainerPromise;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
  this.#init();
20
  }
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  async #init() {
23
  const webcontainer = await this.#webcontainer;
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  webcontainer.on('port', (port, type, url) => {
26
  let previewInfo = this.#availablePreviews.get(port);
27
 
@@ -44,6 +209,101 @@ export class PreviewsStore {
44
  previewInfo.baseUrl = url;
45
 
46
  this.previews.set([...previews]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  });
48
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  }
 
1
  import type { WebContainer } from '@webcontainer/api';
2
  import { atom } from 'nanostores';
3
 
4
+ // Extend Window interface to include our custom property
5
+ declare global {
6
+ interface Window {
7
+ _tabId?: string;
8
+ }
9
+ }
10
+
11
  export interface PreviewInfo {
12
  port: number;
13
  ready: boolean;
14
  baseUrl: string;
15
  }
16
 
17
+ // Create a broadcast channel for preview updates
18
+ const PREVIEW_CHANNEL = 'preview-updates';
19
+
20
  export class PreviewsStore {
21
  #availablePreviews = new Map<number, PreviewInfo>();
22
  #webcontainer: Promise<WebContainer>;
23
+ #broadcastChannel: BroadcastChannel;
24
+ #lastUpdate = new Map<string, number>();
25
+ #watchedFiles = new Set<string>();
26
+ #refreshTimeouts = new Map<string, NodeJS.Timeout>();
27
+ #REFRESH_DELAY = 300;
28
+ #storageChannel: BroadcastChannel;
29
 
30
  previews = atom<PreviewInfo[]>([]);
31
 
32
  constructor(webcontainerPromise: Promise<WebContainer>) {
33
  this.#webcontainer = webcontainerPromise;
34
+ this.#broadcastChannel = new BroadcastChannel(PREVIEW_CHANNEL);
35
+ this.#storageChannel = new BroadcastChannel('storage-sync-channel');
36
+
37
+ // Listen for preview updates from other tabs
38
+ this.#broadcastChannel.onmessage = (event) => {
39
+ const { type, previewId } = event.data;
40
+
41
+ if (type === 'file-change') {
42
+ const timestamp = event.data.timestamp;
43
+ const lastUpdate = this.#lastUpdate.get(previewId) || 0;
44
+
45
+ if (timestamp > lastUpdate) {
46
+ this.#lastUpdate.set(previewId, timestamp);
47
+ this.refreshPreview(previewId);
48
+ }
49
+ }
50
+ };
51
+
52
+ // Listen for storage sync messages
53
+ this.#storageChannel.onmessage = (event) => {
54
+ const { storage, source } = event.data;
55
+
56
+ if (storage && source !== this._getTabId()) {
57
+ this._syncStorage(storage);
58
+ }
59
+ };
60
+
61
+ // Override localStorage setItem to catch all changes
62
+ if (typeof window !== 'undefined') {
63
+ const originalSetItem = localStorage.setItem;
64
+
65
+ localStorage.setItem = (...args) => {
66
+ originalSetItem.apply(localStorage, args);
67
+ this._broadcastStorageSync();
68
+ };
69
+ }
70
 
71
  this.#init();
72
  }
73
 
74
+ // Generate a unique ID for this tab
75
+ private _getTabId(): string {
76
+ if (typeof window !== 'undefined') {
77
+ if (!window._tabId) {
78
+ window._tabId = Math.random().toString(36).substring(2, 15);
79
+ }
80
+
81
+ return window._tabId;
82
+ }
83
+
84
+ return '';
85
+ }
86
+
87
+ // Sync storage data between tabs
88
+ private _syncStorage(storage: Record<string, string>) {
89
+ if (typeof window !== 'undefined') {
90
+ Object.entries(storage).forEach(([key, value]) => {
91
+ try {
92
+ const originalSetItem = Object.getPrototypeOf(localStorage).setItem;
93
+ originalSetItem.call(localStorage, key, value);
94
+ } catch (error) {
95
+ console.error('[Preview] Error syncing storage:', error);
96
+ }
97
+ });
98
+
99
+ // Force a refresh after syncing storage
100
+ const previews = this.previews.get();
101
+ previews.forEach((preview) => {
102
+ const previewId = this.getPreviewId(preview.baseUrl);
103
+
104
+ if (previewId) {
105
+ this.refreshPreview(previewId);
106
+ }
107
+ });
108
+
109
+ // Reload the page content
110
+ if (typeof window !== 'undefined' && window.location) {
111
+ const iframe = document.querySelector('iframe');
112
+
113
+ if (iframe) {
114
+ iframe.src = iframe.src;
115
+ }
116
+ }
117
+ }
118
+ }
119
+
120
+ // Broadcast storage state to other tabs
121
+ private _broadcastStorageSync() {
122
+ if (typeof window !== 'undefined') {
123
+ const storage: Record<string, string> = {};
124
+
125
+ for (let i = 0; i < localStorage.length; i++) {
126
+ const key = localStorage.key(i);
127
+
128
+ if (key) {
129
+ storage[key] = localStorage.getItem(key) || '';
130
+ }
131
+ }
132
+
133
+ this.#storageChannel.postMessage({
134
+ type: 'storage-sync',
135
+ storage,
136
+ source: this._getTabId(),
137
+ timestamp: Date.now(),
138
+ });
139
+ }
140
+ }
141
+
142
  async #init() {
143
  const webcontainer = await this.#webcontainer;
144
 
145
+ // Listen for server ready events
146
+ webcontainer.on('server-ready', (port, url) => {
147
+ console.log('[Preview] Server ready on port:', port, url);
148
+ this.broadcastUpdate(url);
149
+
150
+ // Initial storage sync when preview is ready
151
+ this._broadcastStorageSync();
152
+ });
153
+
154
+ try {
155
+ // Watch for file changes
156
+ const watcher = await webcontainer.fs.watch('**/*', { persistent: true });
157
+
158
+ // Use the native watch events
159
+ (watcher as any).addEventListener('change', async () => {
160
+ const previews = this.previews.get();
161
+
162
+ for (const preview of previews) {
163
+ const previewId = this.getPreviewId(preview.baseUrl);
164
+
165
+ if (previewId) {
166
+ this.broadcastFileChange(previewId);
167
+ }
168
+ }
169
+ });
170
+
171
+ // Watch for DOM changes that might affect storage
172
+ if (typeof window !== 'undefined') {
173
+ const observer = new MutationObserver((_mutations) => {
174
+ // Broadcast storage changes when DOM changes
175
+ this._broadcastStorageSync();
176
+ });
177
+
178
+ observer.observe(document.body, {
179
+ childList: true,
180
+ subtree: true,
181
+ characterData: true,
182
+ attributes: true,
183
+ });
184
+ }
185
+ } catch (error) {
186
+ console.error('[Preview] Error setting up watchers:', error);
187
+ }
188
+
189
+ // Listen for port events
190
  webcontainer.on('port', (port, type, url) => {
191
  let previewInfo = this.#availablePreviews.get(port);
192
 
 
209
  previewInfo.baseUrl = url;
210
 
211
  this.previews.set([...previews]);
212
+
213
+ if (type === 'open') {
214
+ this.broadcastUpdate(url);
215
+ }
216
+ });
217
+ }
218
+
219
+ // Helper to extract preview ID from URL
220
+ getPreviewId(url: string): string | null {
221
+ const match = url.match(/^https?:\/\/([^.]+)\.local-credentialless\.webcontainer-api\.io/);
222
+ return match ? match[1] : null;
223
+ }
224
+
225
+ // Broadcast state change to all tabs
226
+ broadcastStateChange(previewId: string) {
227
+ const timestamp = Date.now();
228
+ this.#lastUpdate.set(previewId, timestamp);
229
+
230
+ this.#broadcastChannel.postMessage({
231
+ type: 'state-change',
232
+ previewId,
233
+ timestamp,
234
  });
235
  }
236
+
237
+ // Broadcast file change to all tabs
238
+ broadcastFileChange(previewId: string) {
239
+ const timestamp = Date.now();
240
+ this.#lastUpdate.set(previewId, timestamp);
241
+
242
+ this.#broadcastChannel.postMessage({
243
+ type: 'file-change',
244
+ previewId,
245
+ timestamp,
246
+ });
247
+ }
248
+
249
+ // Broadcast update to all tabs
250
+ broadcastUpdate(url: string) {
251
+ const previewId = this.getPreviewId(url);
252
+
253
+ if (previewId) {
254
+ const timestamp = Date.now();
255
+ this.#lastUpdate.set(previewId, timestamp);
256
+
257
+ this.#broadcastChannel.postMessage({
258
+ type: 'file-change',
259
+ previewId,
260
+ timestamp,
261
+ });
262
+ }
263
+ }
264
+
265
+ // Method to refresh a specific preview
266
+ refreshPreview(previewId: string) {
267
+ // Clear any pending refresh for this preview
268
+ const existingTimeout = this.#refreshTimeouts.get(previewId);
269
+
270
+ if (existingTimeout) {
271
+ clearTimeout(existingTimeout);
272
+ }
273
+
274
+ // Set a new timeout for this refresh
275
+ const timeout = setTimeout(() => {
276
+ const previews = this.previews.get();
277
+ const preview = previews.find((p) => this.getPreviewId(p.baseUrl) === previewId);
278
+
279
+ if (preview) {
280
+ preview.ready = false;
281
+ this.previews.set([...previews]);
282
+
283
+ requestAnimationFrame(() => {
284
+ preview.ready = true;
285
+ this.previews.set([...previews]);
286
+ });
287
+ }
288
+
289
+ this.#refreshTimeouts.delete(previewId);
290
+ }, this.#REFRESH_DELAY);
291
+
292
+ this.#refreshTimeouts.set(previewId, timeout);
293
+ }
294
+ }
295
+
296
+ // Create a singleton instance
297
+ let previewsStore: PreviewsStore | null = null;
298
+
299
+ export function usePreviewStore() {
300
+ if (!previewsStore) {
301
+ /*
302
+ * Initialize with a Promise that resolves to WebContainer
303
+ * This should match how you're initializing WebContainer elsewhere
304
+ */
305
+ previewsStore = new PreviewsStore(Promise.resolve({} as WebContainer));
306
+ }
307
+
308
+ return previewsStore;
309
  }
app/routes/api.enhancer.ts CHANGED
@@ -1,34 +1,13 @@
1
  import { type ActionFunctionArgs } from '@remix-run/cloudflare';
2
-
3
- //import { StreamingTextResponse, parseStreamPart } from 'ai';
4
  import { streamText } from '~/lib/.server/llm/stream-text';
5
  import { stripIndents } from '~/utils/stripIndent';
6
- import type { IProviderSetting, ProviderInfo } from '~/types/model';
 
7
 
8
  export async function action(args: ActionFunctionArgs) {
9
  return enhancerAction(args);
10
  }
11
 
12
- function parseCookies(cookieHeader: string) {
13
- const cookies: any = {};
14
-
15
- // Split the cookie string by semicolons and spaces
16
- const items = cookieHeader.split(';').map((cookie) => cookie.trim());
17
-
18
- items.forEach((item) => {
19
- const [name, ...rest] = item.split('=');
20
-
21
- if (name && rest) {
22
- // Decode the name and value, and join value parts in case it contains '='
23
- const decodedName = decodeURIComponent(name.trim());
24
- const decodedValue = decodeURIComponent(rest.join('=').trim());
25
- cookies[decodedName] = decodedValue;
26
- }
27
- });
28
-
29
- return cookies;
30
- }
31
-
32
  async function enhancerAction({ context, request }: ActionFunctionArgs) {
33
  const { message, model, provider } = await request.json<{
34
  message: string;
@@ -55,12 +34,8 @@ async function enhancerAction({ context, request }: ActionFunctionArgs) {
55
  }
56
 
57
  const cookieHeader = request.headers.get('Cookie');
58
-
59
- // Parse the cookie's value (returns an object or null if no cookie exists)
60
- const apiKeys = JSON.parse(parseCookies(cookieHeader || '').apiKeys || '{}');
61
- const providerSettings: Record<string, IProviderSetting> = JSON.parse(
62
- parseCookies(cookieHeader || '').providers || '{}',
63
- );
64
 
65
  try {
66
  const result = await streamText({
 
1
  import { type ActionFunctionArgs } from '@remix-run/cloudflare';
 
 
2
  import { streamText } from '~/lib/.server/llm/stream-text';
3
  import { stripIndents } from '~/utils/stripIndent';
4
+ import type { ProviderInfo } from '~/types/model';
5
+ import { getApiKeysFromCookie, getProviderSettingsFromCookie } from '~/lib/api/cookies';
6
 
7
  export async function action(args: ActionFunctionArgs) {
8
  return enhancerAction(args);
9
  }
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  async function enhancerAction({ context, request }: ActionFunctionArgs) {
12
  const { message, model, provider } = await request.json<{
13
  message: string;
 
34
  }
35
 
36
  const cookieHeader = request.headers.get('Cookie');
37
+ const apiKeys = getApiKeysFromCookie(cookieHeader);
38
+ const providerSettings = getProviderSettingsFromCookie(cookieHeader);
 
 
 
 
39
 
40
  try {
41
  const result = await streamText({
app/routes/api.llmcall.ts CHANGED
@@ -1,34 +1,24 @@
1
  import { type ActionFunctionArgs } from '@remix-run/cloudflare';
2
-
3
- //import { StreamingTextResponse, parseStreamPart } from 'ai';
4
  import { streamText } from '~/lib/.server/llm/stream-text';
5
  import type { IProviderSetting, ProviderInfo } from '~/types/model';
6
  import { generateText } from 'ai';
7
- import { getModelList, PROVIDER_LIST } from '~/utils/constants';
8
  import { MAX_TOKENS } from '~/lib/.server/llm/constants';
 
 
 
9
 
10
  export async function action(args: ActionFunctionArgs) {
11
  return llmCallAction(args);
12
  }
13
 
14
- function parseCookies(cookieHeader: string) {
15
- const cookies: any = {};
16
-
17
- // Split the cookie string by semicolons and spaces
18
- const items = cookieHeader.split(';').map((cookie) => cookie.trim());
19
-
20
- items.forEach((item) => {
21
- const [name, ...rest] = item.split('=');
22
-
23
- if (name && rest) {
24
- // Decode the name and value, and join value parts in case it contains '='
25
- const decodedName = decodeURIComponent(name.trim());
26
- const decodedValue = decodeURIComponent(rest.join('=').trim());
27
- cookies[decodedName] = decodedValue;
28
- }
29
- });
30
-
31
- return cookies;
32
  }
33
 
34
  async function llmCallAction({ context, request }: ActionFunctionArgs) {
@@ -58,12 +48,8 @@ async function llmCallAction({ context, request }: ActionFunctionArgs) {
58
  }
59
 
60
  const cookieHeader = request.headers.get('Cookie');
61
-
62
- // Parse the cookie's value (returns an object or null if no cookie exists)
63
- const apiKeys = JSON.parse(parseCookies(cookieHeader || '').apiKeys || '{}');
64
- const providerSettings: Record<string, IProviderSetting> = JSON.parse(
65
- parseCookies(cookieHeader || '').providers || '{}',
66
- );
67
 
68
  if (streamOutput) {
69
  try {
@@ -105,8 +91,8 @@ async function llmCallAction({ context, request }: ActionFunctionArgs) {
105
  }
106
  } else {
107
  try {
108
- const MODEL_LIST = await getModelList({ apiKeys, providerSettings, serverEnv: context.cloudflare.env as any });
109
- const modelDetails = MODEL_LIST.find((m) => m.name === model);
110
 
111
  if (!modelDetails) {
112
  throw new Error('Model not found');
 
1
  import { type ActionFunctionArgs } from '@remix-run/cloudflare';
 
 
2
  import { streamText } from '~/lib/.server/llm/stream-text';
3
  import type { IProviderSetting, ProviderInfo } from '~/types/model';
4
  import { generateText } from 'ai';
5
+ import { PROVIDER_LIST } from '~/utils/constants';
6
  import { MAX_TOKENS } from '~/lib/.server/llm/constants';
7
+ import { LLMManager } from '~/lib/modules/llm/manager';
8
+ import type { ModelInfo } from '~/lib/modules/llm/types';
9
+ import { getApiKeysFromCookie, getProviderSettingsFromCookie } from '~/lib/api/cookies';
10
 
11
  export async function action(args: ActionFunctionArgs) {
12
  return llmCallAction(args);
13
  }
14
 
15
+ async function getModelList(options: {
16
+ apiKeys?: Record<string, string>;
17
+ providerSettings?: Record<string, IProviderSetting>;
18
+ serverEnv?: Record<string, string>;
19
+ }) {
20
+ const llmManager = LLMManager.getInstance(import.meta.env);
21
+ return llmManager.updateModelList(options);
 
 
 
 
 
 
 
 
 
 
 
22
  }
23
 
24
  async function llmCallAction({ context, request }: ActionFunctionArgs) {
 
48
  }
49
 
50
  const cookieHeader = request.headers.get('Cookie');
51
+ const apiKeys = getApiKeysFromCookie(cookieHeader);
52
+ const providerSettings = getProviderSettingsFromCookie(cookieHeader);
 
 
 
 
53
 
54
  if (streamOutput) {
55
  try {
 
91
  }
92
  } else {
93
  try {
94
+ const models = await getModelList({ apiKeys, providerSettings, serverEnv: context.cloudflare.env as any });
95
+ const modelDetails = models.find((m: ModelInfo) => m.name === model);
96
 
97
  if (!modelDetails) {
98
  throw new Error('Model not found');
app/routes/api.models.$provider.ts ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ import { loader } from './api.models';
2
+ export { loader };
app/routes/api.models.ts CHANGED
@@ -1,6 +1,84 @@
1
  import { json } from '@remix-run/cloudflare';
2
- import { MODEL_LIST } from '~/utils/constants';
 
 
 
3
 
4
- export async function loader() {
5
- return json(MODEL_LIST);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  }
 
1
  import { json } from '@remix-run/cloudflare';
2
+ import { LLMManager } from '~/lib/modules/llm/manager';
3
+ import type { ModelInfo } from '~/lib/modules/llm/types';
4
+ import type { ProviderInfo } from '~/types/model';
5
+ import { getApiKeysFromCookie, getProviderSettingsFromCookie } from '~/lib/api/cookies';
6
 
7
+ interface ModelsResponse {
8
+ modelList: ModelInfo[];
9
+ providers: ProviderInfo[];
10
+ defaultProvider: ProviderInfo;
11
+ }
12
+
13
+ let cachedProviders: ProviderInfo[] | null = null;
14
+ let cachedDefaultProvider: ProviderInfo | null = null;
15
+
16
+ function getProviderInfo(llmManager: LLMManager) {
17
+ if (!cachedProviders) {
18
+ cachedProviders = llmManager.getAllProviders().map((provider) => ({
19
+ name: provider.name,
20
+ staticModels: provider.staticModels,
21
+ getApiKeyLink: provider.getApiKeyLink,
22
+ labelForGetApiKey: provider.labelForGetApiKey,
23
+ icon: provider.icon,
24
+ }));
25
+ }
26
+
27
+ if (!cachedDefaultProvider) {
28
+ const defaultProvider = llmManager.getDefaultProvider();
29
+ cachedDefaultProvider = {
30
+ name: defaultProvider.name,
31
+ staticModels: defaultProvider.staticModels,
32
+ getApiKeyLink: defaultProvider.getApiKeyLink,
33
+ labelForGetApiKey: defaultProvider.labelForGetApiKey,
34
+ icon: defaultProvider.icon,
35
+ };
36
+ }
37
+
38
+ return { providers: cachedProviders, defaultProvider: cachedDefaultProvider };
39
+ }
40
+
41
+ export async function loader({
42
+ request,
43
+ params,
44
+ }: {
45
+ request: Request;
46
+ params: { provider?: string };
47
+ }): Promise<Response> {
48
+ const llmManager = LLMManager.getInstance(import.meta.env);
49
+
50
+ // Get client side maintained API keys and provider settings from cookies
51
+ const cookieHeader = request.headers.get('Cookie');
52
+ const apiKeys = getApiKeysFromCookie(cookieHeader);
53
+ const providerSettings = getProviderSettingsFromCookie(cookieHeader);
54
+
55
+ const { providers, defaultProvider } = getProviderInfo(llmManager);
56
+
57
+ let modelList: ModelInfo[] = [];
58
+
59
+ if (params.provider) {
60
+ // Only update models for the specific provider
61
+ const provider = llmManager.getProvider(params.provider);
62
+
63
+ if (provider) {
64
+ const staticModels = provider.staticModels;
65
+ const dynamicModels = provider.getDynamicModels
66
+ ? await provider.getDynamicModels(apiKeys, providerSettings, import.meta.env)
67
+ : [];
68
+ modelList = [...staticModels, ...dynamicModels];
69
+ }
70
+ } else {
71
+ // Update all models
72
+ modelList = await llmManager.updateModelList({
73
+ apiKeys,
74
+ providerSettings,
75
+ serverEnv: import.meta.env,
76
+ });
77
+ }
78
+
79
+ return json<ModelsResponse>({
80
+ modelList,
81
+ providers,
82
+ defaultProvider,
83
+ });
84
  }
app/routes/webcontainer.preview.$id.tsx ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { json, type LoaderFunctionArgs } from '@remix-run/cloudflare';
2
+ import { useLoaderData } from '@remix-run/react';
3
+ import { useCallback, useEffect, useRef, useState } from 'react';
4
+
5
+ const PREVIEW_CHANNEL = 'preview-updates';
6
+
7
+ export async function loader({ params }: LoaderFunctionArgs) {
8
+ const previewId = params.id;
9
+
10
+ if (!previewId) {
11
+ throw new Response('Preview ID is required', { status: 400 });
12
+ }
13
+
14
+ return json({ previewId });
15
+ }
16
+
17
+ export default function WebContainerPreview() {
18
+ const { previewId } = useLoaderData<typeof loader>();
19
+ const iframeRef = useRef<HTMLIFrameElement>(null);
20
+ const broadcastChannelRef = useRef<BroadcastChannel>();
21
+ const [previewUrl, setPreviewUrl] = useState('');
22
+
23
+ // Handle preview refresh
24
+ const handleRefresh = useCallback(() => {
25
+ if (iframeRef.current && previewUrl) {
26
+ // Force a clean reload
27
+ iframeRef.current.src = '';
28
+ requestAnimationFrame(() => {
29
+ if (iframeRef.current) {
30
+ iframeRef.current.src = previewUrl;
31
+ }
32
+ });
33
+ }
34
+ }, [previewUrl]);
35
+
36
+ // Notify other tabs that this preview is ready
37
+ const notifyPreviewReady = useCallback(() => {
38
+ if (broadcastChannelRef.current && previewUrl) {
39
+ broadcastChannelRef.current.postMessage({
40
+ type: 'preview-ready',
41
+ previewId,
42
+ url: previewUrl,
43
+ timestamp: Date.now(),
44
+ });
45
+ }
46
+ }, [previewId, previewUrl]);
47
+
48
+ useEffect(() => {
49
+ // Initialize broadcast channel
50
+ broadcastChannelRef.current = new BroadcastChannel(PREVIEW_CHANNEL);
51
+
52
+ // Listen for preview updates
53
+ broadcastChannelRef.current.onmessage = (event) => {
54
+ if (event.data.previewId === previewId) {
55
+ if (event.data.type === 'refresh-preview' || event.data.type === 'file-change') {
56
+ handleRefresh();
57
+ }
58
+ }
59
+ };
60
+
61
+ // Construct the WebContainer preview URL
62
+ const url = `https://${previewId}.local-credentialless.webcontainer-api.io`;
63
+ setPreviewUrl(url);
64
+
65
+ // Set the iframe src
66
+ if (iframeRef.current) {
67
+ iframeRef.current.src = url;
68
+ }
69
+
70
+ // Notify other tabs that this preview is ready
71
+ notifyPreviewReady();
72
+
73
+ // Cleanup
74
+ return () => {
75
+ broadcastChannelRef.current?.close();
76
+ };
77
+ }, [previewId, handleRefresh, notifyPreviewReady]);
78
+
79
+ return (
80
+ <div className="w-full h-full">
81
+ <iframe
82
+ ref={iframeRef}
83
+ title="WebContainer Preview"
84
+ className="w-full h-full border-none"
85
+ sandbox="allow-scripts allow-forms allow-popups allow-modals allow-storage-access-by-user-activation allow-same-origin"
86
+ allow="cross-origin-isolated"
87
+ loading="eager"
88
+ onLoad={notifyPreviewReady}
89
+ />
90
+ </div>
91
+ );
92
+ }
app/utils/constants.ts CHANGED
@@ -1,7 +1,4 @@
1
- import type { IProviderSetting } from '~/types/model';
2
-
3
  import { LLMManager } from '~/lib/modules/llm/manager';
4
- import type { ModelInfo } from '~/lib/modules/llm/types';
5
  import type { Template } from '~/types/template';
6
 
7
  export const WORK_DIR_NAME = 'project';
@@ -17,9 +14,7 @@ const llmManager = LLMManager.getInstance(import.meta.env);
17
  export const PROVIDER_LIST = llmManager.getAllProviders();
18
  export const DEFAULT_PROVIDER = llmManager.getDefaultProvider();
19
 
20
- let MODEL_LIST = llmManager.getModelList();
21
-
22
- const providerBaseUrlEnvKeys: Record<string, { baseUrlKey?: string; apiTokenKey?: string }> = {};
23
  PROVIDER_LIST.forEach((provider) => {
24
  providerBaseUrlEnvKeys[provider.name] = {
25
  baseUrlKey: provider.config.baseUrlKey,
@@ -27,34 +22,6 @@ PROVIDER_LIST.forEach((provider) => {
27
  };
28
  });
29
 
30
- // Export the getModelList function using the manager
31
- export async function getModelList(options: {
32
- apiKeys?: Record<string, string>;
33
- providerSettings?: Record<string, IProviderSetting>;
34
- serverEnv?: Record<string, string>;
35
- }) {
36
- return await llmManager.updateModelList(options);
37
- }
38
-
39
- async function initializeModelList(options: {
40
- env?: Record<string, string>;
41
- providerSettings?: Record<string, IProviderSetting>;
42
- apiKeys?: Record<string, string>;
43
- }): Promise<ModelInfo[]> {
44
- const { providerSettings, apiKeys, env } = options;
45
- const list = await getModelList({
46
- apiKeys,
47
- providerSettings,
48
- serverEnv: env,
49
- });
50
- MODEL_LIST = list || MODEL_LIST;
51
-
52
- return list;
53
- }
54
-
55
- // initializeModelList({})
56
- export { initializeModelList, providerBaseUrlEnvKeys, MODEL_LIST };
57
-
58
  // starter Templates
59
 
60
  export const STARTER_TEMPLATES: Template[] = [
 
 
 
1
  import { LLMManager } from '~/lib/modules/llm/manager';
 
2
  import type { Template } from '~/types/template';
3
 
4
  export const WORK_DIR_NAME = 'project';
 
14
  export const PROVIDER_LIST = llmManager.getAllProviders();
15
  export const DEFAULT_PROVIDER = llmManager.getDefaultProvider();
16
 
17
+ export const providerBaseUrlEnvKeys: Record<string, { baseUrlKey?: string; apiTokenKey?: string }> = {};
 
 
18
  PROVIDER_LIST.forEach((provider) => {
19
  providerBaseUrlEnvKeys[provider.name] = {
20
  baseUrlKey: provider.config.baseUrlKey,
 
22
  };
23
  });
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  // starter Templates
26
 
27
  export const STARTER_TEMPLATES: Template[] = [