@widgetic/creator 0.4.2 → 0.4.3

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/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # Widget Creator – Local Development Notes
2
2
 
3
+ > **Internal building block.** This package is part of Widgetic's own apps and is not a supported integration surface. Partners: use [`@widgetic/ui-sdk`](https://www.npmjs.com/package/@widgetic/ui-sdk) instead.
4
+
3
5
  ## Environment variables
4
6
 
5
7
  `.env.example` tracks the full variable inventory — copy it to `.env.local` and
@@ -161,6 +161,7 @@
161
161
  shouldUseTusForChatUpload,
162
162
  uploadChatFileToWidgeticApi
163
163
  } from './utils/widgeticChatUpload.js';
164
+ import { tryPartnerMediaUpload, uploadFromMediaLibrary } from './utils/partnerMediaUpload.js';
164
165
  import { persistWidgetThumbnail } from './utils/persistWidgetThumbnail.js';
165
166
  import { nativeScrollbarPadding } from './utils/nativeScrollbarPadding.js';
166
167
  import { pinScrollToBottom } from './utils/pinScrollToBottom.js';
@@ -232,6 +233,7 @@
232
233
  export let initialCompositionId: CreatorAppProps['initialCompositionId'] = null;
233
234
  export let initialStep: CreatorAppProps['initialStep'] = null;
234
235
  export let forceCreateNewWidget: CreatorAppProps['forceCreateNewWidget'] = false;
236
+ export let initialSketchName: CreatorAppProps['initialSketchName'] = null;
235
237
  export let apiUrl: CreatorAppProps['apiUrl'] = null;
236
238
  export let widgetBuilderUrl: CreatorAppProps['widgetBuilderUrl'] = null;
237
239
  export let initialDebugMode: CreatorAppProps['initialDebugMode'] = undefined;
@@ -258,8 +260,17 @@
258
260
  export let onCanvasUnavailable: CreatorAppProps['onCanvasUnavailable'] = undefined;
259
261
  export let onCanvasChanged: CreatorAppProps['onCanvasChanged'] = undefined;
260
262
  export let onReady: CreatorAppProps['onReady'] = undefined;
261
- /** The page's own media library for the editor's file pickers (see `CreatorAppProps.mediaLibrary`). */
263
+ /** Partner library for chat/canvas uploads (see `CreatorAppProps.mediaLibrary`). */
262
264
  export let mediaLibrary: CreatorAppProps['mediaLibrary'] = undefined;
265
+ /** Optional override for PropsEditor file fields (`purpose: 'field'`). */
266
+ export let mediaLibraryForFields: CreatorAppProps['mediaLibraryForFields'] = undefined;
267
+ /** Opens the partner's file picker instead of the built-in File Browser (see `CreatorAppProps.pickFile`). */
268
+ export let pickFile: CreatorAppProps['pickFile'] = undefined;
269
+ /** Resolves the url stored with a picked file (see `CreatorAppProps.storeFileUrl`). */
270
+ export let storeFileUrl: CreatorAppProps['storeFileUrl'] = undefined;
271
+ /** One console.warn per mount when `mediaLibrary.upload` fails and the creator falls back to Widgetic uploads. */
272
+ const partnerUploadWarnings = { mediaLibraryUpload: false as boolean | undefined };
273
+ let mountUploadAbortController: AbortController | null = null;
263
274
  /**
264
275
  * The language of everything the creator shows (see `CreatorAppProps.locale` and `CreatorAppProps.messages`). The one flat
265
276
  * `messages` object is split between the creator's own words and the parts it draws: the editor (with its file
@@ -526,7 +537,7 @@
526
537
  import { PropsEditor, provideEditorLanguage, setFileBrowserUploadConfig, setGoogleFontsApiKey } from '@widgetic/editor';
527
538
 
528
539
  // API root: embedded hosts pass apiUrl; standalone uses VITE_API_URL / PUBLIC_API_URL.
529
- // If unset, @widgetic/api-sdk falls back to BASE_PATH = dev-api.widgetic.com (OpenAPI default).
540
+ // If unset, @widgetic/api-sdk falls back to its own BASE_PATH, https://api.widgetic.com/v1 (the production API).
530
541
  function resolveApiRoot(): string | undefined {
531
542
  const raw =
532
543
  apiUrl ||
@@ -944,6 +955,7 @@
944
955
 
945
956
  // Canvas component resolves eagerly; WidgetDetails loads on demand when panels are opened
946
957
  onMount(async () => {
958
+ mountUploadAbortController = new AbortController();
947
959
  if (canvasModulePromise) {
948
960
  const canvasModule = await canvasModulePromise;
949
961
  // Installed before the canvas mounts so the first save already externalizes
@@ -1042,6 +1054,11 @@
1042
1054
  let userCanvases: CanvasListEntry[] = [];
1043
1055
  let showCanvasDropdown = false; // kept for existing code that sets it to false on switchToCanvas etc.
1044
1056
  let activeCanvasName = 'Loading...';
1057
+ let appliedSketchName = false;
1058
+ $: if (!appliedSketchName && typeof initialSketchName === 'string' && initialSketchName.trim()) {
1059
+ appliedSketchName = true;
1060
+ activeCanvasName = initialSketchName.trim();
1061
+ }
1045
1062
  let canvasNameEditing = false; // kept for existing startCanvasNameEdit/commitCanvasNameEdit
1046
1063
  let canvasNameInputEl: HTMLInputElement | null = null;
1047
1064
 
@@ -1302,6 +1319,9 @@
1302
1319
  * `window`: nothing else reads it, and a partner's page is not a place to leave globals.
1303
1320
  */
1304
1321
  let codegenActiveCount = 0;
1322
+ // Canvas autosave stringifies every shape 15s after the last edit. That
1323
+ // lines up with the stall, so the save waits until this generation ends.
1324
+ $: suspendCanvasAutosave = codegenActiveCount > 0 || isGeneratingCode || Object.keys(generatingWidgetIds).some((id) => generatingWidgetIds[id]);
1305
1325
  function noteCodegenActive(active: boolean): void {
1306
1326
  codegenActiveCount = Math.max(0, codegenActiveCount + (active ? 1 : -1));
1307
1327
  }
@@ -1504,7 +1524,12 @@
1504
1524
 
1505
1525
  async function handleChatUploadFile(
1506
1526
  file: File,
1507
- options?: { onProgress?: (percentage: number) => void; source?: string; widgetId?: string },
1527
+ options?: {
1528
+ onProgress?: (percentage: number) => void;
1529
+ source?: string;
1530
+ widgetId?: string;
1531
+ abortSignal?: AbortSignal;
1532
+ },
1508
1533
  ) {
1509
1534
  if (!authenticatedClientsToken) {
1510
1535
  throw new Error('Upload client not initialized');
@@ -1528,6 +1553,40 @@
1528
1553
  if (partnerMode && shouldUseTusForChatUpload(uploadFile)) {
1529
1554
  throw new Error('This file is too large to attach here (the limit is 10 MB).');
1530
1555
  }
1556
+ const uploadAbortSignal = options?.abortSignal ?? mountUploadAbortController?.signal ?? undefined;
1557
+ let partnerFile: Awaited<ReturnType<typeof tryPartnerMediaUpload>> = null;
1558
+ try {
1559
+ partnerFile = await tryPartnerMediaUpload(
1560
+ mediaLibrary,
1561
+ {
1562
+ file: uploadFile,
1563
+ purpose: 'chat',
1564
+ onProgress: options?.onProgress,
1565
+ signal: uploadAbortSignal,
1566
+ },
1567
+ { storeFileUrl, warnings: partnerUploadWarnings },
1568
+ );
1569
+ } catch (error) {
1570
+ if (
1571
+ uploadAbortSignal?.aborted ||
1572
+ (error instanceof DOMException && error.name === 'AbortError')
1573
+ ) {
1574
+ throw new Error('Upload cancelled.');
1575
+ }
1576
+ throw error;
1577
+ }
1578
+ if (partnerFile) {
1579
+ return {
1580
+ id: partnerFile.id,
1581
+ url: partnerFile.url,
1582
+ fileType: partnerFile.mimeType || uploadFile.type,
1583
+ fileName: partnerFile.name || uploadFile.name,
1584
+ fileSize: partnerFile.size ?? uploadFile.size,
1585
+ };
1586
+ }
1587
+ if (uploadAbortSignal?.aborted) {
1588
+ throw new Error('Upload cancelled.');
1589
+ }
1531
1590
  let result: Awaited<ReturnType<typeof uploadChatFileToWidgeticApi>>;
1532
1591
  try {
1533
1592
  result = await uploadChatFileToWidgeticApi(
@@ -1543,7 +1602,7 @@
1543
1602
  ? currentChatConversationId
1544
1603
  : undefined,
1545
1604
  },
1546
- { onProgress: options?.onProgress },
1605
+ { onProgress: options?.onProgress, abortSignal: uploadAbortSignal },
1547
1606
  );
1548
1607
  } catch (error) {
1549
1608
  // This upload does not go through the API clients, so their middleware did not see the refusal: a full storage
@@ -3308,10 +3367,20 @@
3308
3367
  return Math.max(CHAT_MIN_HEIGHT, Math.min(CHAT_MAX_HEIGHT, stored));
3309
3368
  }
3310
3369
 
3370
+ const chatResizeHits: Record<string, number[]> = {};
3311
3371
  function handleChatMessagesResize(widgetId: string, deltaPx: number): void {
3312
3372
  // Sub-pixel footer jitter was rewriting the chat height every frame and
3313
3373
  // re-rendering the whole creator while code generation streamed.
3374
+ if (generatingWidgetIds[widgetId]) return;
3314
3375
  if (!Number.isFinite(deltaPx) || Math.abs(deltaPx) < 2) return;
3376
+ const now = Date.now();
3377
+ const hits = (chatResizeHits[widgetId] || []).filter((time) => now - time < 2000);
3378
+ hits.push(now);
3379
+ chatResizeHits[widgetId] = hits;
3380
+ if (hits.length > 6) {
3381
+ if (hits.length === 7) console.warn('[CreatorApp] Stopped a chat-height resize loop', widgetId.substring(0, 8));
3382
+ return;
3383
+ }
3315
3384
  const measured = document
3316
3385
  .querySelector(`[data-widget-chat-height="${widgetId}"]`)
3317
3386
  ?.getBoundingClientRect().height;
@@ -6735,18 +6804,43 @@
6735
6804
  const untitledCanvasBaseName = 'Untitled Widget';
6736
6805
 
6737
6806
  function nextUntitledCanvasName(existingNames: string[]): string {
6738
- const names = new Set(existingNames.map((name) => (name || '').trim()).filter(Boolean));
6739
- if (!names.has(untitledCanvasBaseName)) return untitledCanvasBaseName;
6740
- let highest = 1;
6741
- for (const name of names) {
6742
- const match = name.match(/^Untitled Widget (\d+)$/);
6807
+ let highest = 0;
6808
+ for (const rawName of existingNames) {
6809
+ const name = (rawName || '').trim();
6810
+ const match = name.match(/^Untitled (?:Widget|Image)(?: (\d+))?$/);
6743
6811
  if (!match) continue;
6744
- const value = Number(match[1]);
6745
- if (Number.isFinite(value) && value > highest) highest = value;
6812
+ const value = match[1] ? Number(match[1]) : 1;
6813
+ if (value > highest) highest = value;
6746
6814
  }
6747
6815
  return `${untitledCanvasBaseName} ${highest + 1}`;
6748
6816
  }
6749
6817
 
6818
+ function sketchNameFromHost(): string {
6819
+ return typeof initialSketchName === 'string' ? initialSketchName.trim() : '';
6820
+ }
6821
+
6822
+ async function canvasNamesForNewSketch(): Promise<string[]> {
6823
+ const known = userCanvases.map((canvas) => canvas.name || '');
6824
+ if (!canvasesClient) return known;
6825
+ try {
6826
+ const response = await canvasesClient.getAllCanvases({
6827
+ page: 1,
6828
+ size: 100,
6829
+ sort: 'id:desc'
6830
+ });
6831
+ const rows: any[] = Array.isArray(response)
6832
+ ? response
6833
+ : Array.isArray((response as any)?.data)
6834
+ ? (response as any).data
6835
+ : [];
6836
+ if (rows.length === 0) return known;
6837
+ return rows.map((canvas) => canvas.persistenceKey || canvas.persistence_key || canvas.name || '');
6838
+ } catch (error) {
6839
+ console.warn('[CreatorApp] Could not list canvases before naming a sketch', error);
6840
+ return known;
6841
+ }
6842
+ }
6843
+
6750
6844
  function canvasCreateRequest(persistenceKey: string) {
6751
6845
  const trimmedProjectId = typeof projectId === 'string' ? projectId.trim() : '';
6752
6846
  return {
@@ -6765,7 +6859,7 @@
6765
6859
  return null;
6766
6860
  }
6767
6861
  try {
6768
- const newName = nextUntitledCanvasName(userCanvases.map((c) => c.name || ''));
6862
+ const newName = sketchNameFromHost() || nextUntitledCanvasName(await canvasNamesForNewSketch());
6769
6863
  const createdRaw = await canvasesClient.createCanvas({
6770
6864
  createCanvasRequest: canvasCreateRequest(newName)
6771
6865
  });
@@ -6807,7 +6901,7 @@
6807
6901
  }
6808
6902
 
6809
6903
  try {
6810
- const newName = nextUntitledCanvasName(userCanvases.map((c) => c.name || ''));
6904
+ const newName = sketchNameFromHost() || nextUntitledCanvasName(await canvasNamesForNewSketch());
6811
6905
  const createdRaw = await canvasesClient.createCanvas({
6812
6906
  createCanvasRequest: canvasCreateRequest(newName)
6813
6907
  });
@@ -8636,11 +8730,43 @@
8636
8730
  });
8637
8731
  return null;
8638
8732
  }
8639
-
8733
+
8734
+ if (uploadFromMediaLibrary(mediaLibrary)) {
8735
+ try {
8736
+ const partnerImage = await tryPartnerMediaUpload(
8737
+ mediaLibrary,
8738
+ {
8739
+ file,
8740
+ purpose: 'canvas',
8741
+ signal: mountUploadAbortController?.signal ?? undefined,
8742
+ },
8743
+ { storeFileUrl, warnings: partnerUploadWarnings },
8744
+ );
8745
+ if (partnerImage?.url && /^https?:\/\//i.test(partnerImage.url)) {
8746
+ return partnerImage.url;
8747
+ }
8748
+ } catch (error) {
8749
+ if (
8750
+ mountUploadAbortController?.signal.aborted ||
8751
+ (error instanceof DOMException && error.name === 'AbortError')
8752
+ ) {
8753
+ return null;
8754
+ }
8755
+ console.error('[WidgetCreator] Partner canvas image upload failed:', error);
8756
+ const description =
8757
+ error instanceof Error ? error.message : $t('creator.general.couldNotReadTheImage');
8758
+ showToast('error', $t('creator.general.failedToProcessImage'), {
8759
+ description,
8760
+ duration: 3000,
8761
+ });
8762
+ return null;
8763
+ }
8764
+ return null;
8765
+ }
8766
+
8640
8767
  try {
8641
8768
  const webpFile = await imageFileToWebpFile(file, 0.95);
8642
8769
  const base64 = await fileToBase64(webpFile);
8643
- // console.log('[WidgetCreator] Image processed:', file.name, 'Size:', sizeMB.toFixed(2), 'MB');
8644
8770
  return base64;
8645
8771
  } catch (error) {
8646
8772
  console.error('[WidgetCreator] Error processing image:', error);
@@ -10171,6 +10297,7 @@ Requirements:
10171
10297
  // The wait's callback sees the last frame of a stream twice: a job stopped elsewhere is shown as stopped once
10172
10298
  let cancelledElsewhereShown = false;
10173
10299
  await waitForOperation(operationId, (op) => {
10300
+ freezeProbe('sse', `${op?.status ?? ''} ${op?.progress ?? ''}`);
10174
10301
  // Check if aborted before processing updates
10175
10302
  if (signal.aborted) return;
10176
10303
  if (!op) return;
@@ -10231,6 +10358,19 @@ Requirements:
10231
10358
  }
10232
10359
 
10233
10360
  if (op.status === 'completed') {
10361
+ // The SSE callback runs on the page thread. Applying the result here
10362
+ // rebuilds the chat before the browser can paint, so the status stays
10363
+ // on the previous percent and the tab stops answering.
10364
+ // Start the history request on this turn, before any timer. A stall in
10365
+ // the timer then still shows up in the API log as this request.
10366
+ if (generationWidgetId) {
10367
+ void loadPublishHistoryForPanel(generationWidgetId, { silent: true });
10368
+ }
10369
+ setTimeout(() => {
10370
+ setTimeout(() => {
10371
+ const { [generationWidgetId]: _doneGenerating, ...stillGenerating } = generatingWidgetIds;
10372
+ generatingWidgetIds = stillGenerating;
10373
+ isGeneratingCode = !!(focusedPanelWidgetId && generatingWidgetIds[focusedPanelWidgetId]);
10234
10374
  clearActiveOperationId(generationWidgetId);
10235
10375
 
10236
10376
  const completedCommitSha = getOperationCommitId(op.metadata);
@@ -10451,8 +10591,8 @@ Requirements:
10451
10591
  duration: 8000
10452
10592
  });
10453
10593
  } else if (!completedCommitSha) {
10454
- showToast('warning', 'Code was not saved', {
10455
- description: 'Retry saves it and records a version.',
10594
+ showToast('warning', $t('creator.codegen.codeWasNotSaved'), {
10595
+ description: $t('creator.codegen.retrySavesItAndRecordsAVersion'),
10456
10596
  duration: 8000
10457
10597
  });
10458
10598
  } else {
@@ -10570,6 +10710,8 @@ Requirements:
10570
10710
  });
10571
10711
  }
10572
10712
  }, completedPreviewBuildErr ? 400 : 800);
10713
+ }, 0);
10714
+ }, 0);
10573
10715
  } else {
10574
10716
  pushCodegenProgressToUi(op, generationWidgetId);
10575
10717
  }
@@ -11039,14 +11181,18 @@ Requirements:
11039
11181
  });
11040
11182
  }
11041
11183
 
11042
- const publishedPanelRef = getWidgetDetailsRef(capturedWidgetId);
11043
- console.log('[Publish] Refreshing preview after publish (step:', widgetDetailsStep, ')');
11044
- publishedPanelRef?.invalidatePublishedArtifactCache?.();
11045
- await publishedPanelRef?.refreshPreview({ withRetry: true });
11046
- scheduleListThumbnailCapture(capturedWidgetId);
11047
-
11048
- await loadPublishHistory();
11049
- void refreshTrialCounter();
11184
+ try {
11185
+ const publishedPanelRef = getWidgetDetailsRef(capturedWidgetId);
11186
+ console.log('[Publish] Refreshing preview after publish (step:', widgetDetailsStep, ')');
11187
+ publishedPanelRef?.invalidatePublishedArtifactCache?.();
11188
+ await publishedPanelRef?.refreshPreview({ withRetry: true });
11189
+ scheduleListThumbnailCapture(capturedWidgetId);
11190
+ await loadPublishHistory();
11191
+ void refreshTrialCounter();
11192
+ } catch (previewErr) {
11193
+ // The version is already live. A preview reload must not be reported as a failed publish.
11194
+ console.warn('[Publish] Preview refresh after a successful publish failed', previewErr);
11195
+ }
11050
11196
 
11051
11197
  } catch (err: any) {
11052
11198
  console.error('[Publish] Error publishing widget:', err);
@@ -11267,6 +11413,8 @@ Requirements:
11267
11413
 
11268
11414
  // Clean up interval on component destroy
11269
11415
  onDestroy(() => {
11416
+ mountUploadAbortController?.abort();
11417
+ mountUploadAbortController = null;
11270
11418
  clearCanvasLoadFailsafe();
11271
11419
  if (tokenCheckInterval) clearInterval(tokenCheckInterval);
11272
11420
  if (tokenDisplayInterval) clearInterval(tokenDisplayInterval);
@@ -11566,8 +11714,15 @@ Requirements:
11566
11714
  return codegenProgressDebugLine(op, stage, pct);
11567
11715
  }
11568
11716
 
11717
+ function freezeProbe(name: string, detail = ''): void {
11718
+ if (!import.meta.env.DEV) return;
11719
+ const query = new URLSearchParams({ probe: name, status: detail.slice(0, 180) });
11720
+ void fetch(`http://localhost:3000/health?${query}`).catch(() => {});
11721
+ }
11722
+
11569
11723
  function pushCodegenProgressToUi(op: OperationStatus, widgetId: string | null | undefined) {
11570
11724
  const line = formatCodegenProgressStatus(op);
11725
+ freezeProbe('progress', line);
11571
11726
  // Feed the freeze watchdog the latest status so a [FreezeReport] names the
11572
11727
  // stage the UI was showing when the main thread stopped responding.
11573
11728
  (window as any).__widgeticFreezeWatchdog?.setStatus?.(line);
@@ -11599,6 +11754,9 @@ Requirements:
11599
11754
 
11600
11755
  /** Same throttle for the in-chat status bubble (updateLatestCodegenStatusMessage). */
11601
11756
  function scheduleCodegenChatStatusPush(widgetId: string | null | undefined, line: string): void {
11757
+ // Percentage ticks during the model stream rewrite the open chat. A large
11758
+ // design image in that chat is decoded again on each rewrite and the page stalls.
11759
+ if (/^(Generating code|Waiting for|Preparing prompt|Building preview|Saving to repository)\b/i.test(line) || /is thinking/i.test(line)) return;
11602
11760
  const key = widgetId || '_focused';
11603
11761
  codegenChatStatusPendingLine[key] = line;
11604
11762
  if (codegenChatStatusTimers[key]) return;
@@ -11633,6 +11791,23 @@ Requirements:
11633
11791
  .replace(/\s{2,}/g, ' ')
11634
11792
  .trim();
11635
11793
  }
11794
+ const patchKeys = Object.keys(nextPatch);
11795
+ const statusOnly = patchKeys.length > 0 && patchKeys.every((key) =>
11796
+ key === 'generateCodeStatus' || key === 'lastGenerationFailed' || key === 'lastGenerationError'
11797
+ );
11798
+ // A progress line used to copy the whole panel snapshot. Anything that reads
11799
+ // the snapshot (version labels, the open chat) rebuilt on every tick, and
11800
+ // that rebuild ran on the same turn the generation finished.
11801
+ if (statusOnly) {
11802
+ const snap = widgetPanelSnapshots[widgetId];
11803
+ if (snap) Object.assign(snap, nextPatch);
11804
+ if (widgetId === focusedPanelWidgetId) {
11805
+ if (nextPatch.generateCodeStatus !== undefined) generateCodeStatus = nextPatch.generateCodeStatus;
11806
+ if (nextPatch.lastGenerationFailed !== undefined) lastGenerationFailed = nextPatch.lastGenerationFailed;
11807
+ if (nextPatch.lastGenerationError !== undefined) lastGenerationError = nextPatch.lastGenerationError;
11808
+ }
11809
+ return;
11810
+ }
11636
11811
  patchPanelSnapshot(widgetId, nextPatch);
11637
11812
  if (widgetId === focusedPanelWidgetId) {
11638
11813
  if (nextPatch.generateCodeStatus !== undefined) generateCodeStatus = nextPatch.generateCodeStatus;
@@ -12666,9 +12841,27 @@ Requirements:
12666
12841
  }
12667
12842
  }
12668
12843
 
12844
+ /**
12845
+ * History and head for the chat's version labels.
12846
+ * `getPanelDisplayState` copies the design schema on every read. The label
12847
+ * block runs while a generation finishes, and that copy held the page thread.
12848
+ */
12849
+ function versionChromeSnapshot(widgetId: string): { publishHistory: any[]; lastCommitId: string | null; lastPublishedVersion: number | null } {
12850
+ const snap = getPanelState(widgetId);
12851
+ const focused = widgetId === focusedPanelWidgetId;
12852
+ const history = snap.publishHistory?.length
12853
+ ? snap.publishHistory
12854
+ : (focused && publishHistory.length ? publishHistory : (snap.publishHistory || []));
12855
+ return {
12856
+ publishHistory: history,
12857
+ lastCommitId: (focused ? lastCommitId : null) ?? snap.lastCommitId ?? null,
12858
+ lastPublishedVersion: (focused ? lastPublishedVersion : null) ?? snap.lastPublishedVersion ?? null,
12859
+ };
12860
+ }
12861
+
12669
12862
  /** Commit SHA for the version currently selected in the version menu (drives Head-at-commit badge). */
12670
12863
  function resolveViewingCommitShaForPanel(widgetId: string): string | null {
12671
- const ps = getPanelDisplayState(widgetId);
12864
+ const ps = versionChromeSnapshot(widgetId);
12672
12865
  const restored = restoredViewingVersionByWidgetId[widgetId];
12673
12866
  if (Number.isFinite(restored)) {
12674
12867
  const history = ps.publishHistory?.length ? ps.publishHistory : publishHistory;
@@ -12729,6 +12922,8 @@ Requirements:
12729
12922
  let versionPromptLabelsByWidgetId: Record<string, Record<string, string>> = {};
12730
12923
  let versionTimelineByWidgetId: Record<string, Array<{ version: number; sha: string; prompt: string }>> = {};
12731
12924
  let viewingVersionByWidgetId: Record<string, number | null> = {};
12925
+ const emptyVersionLabels: Record<string, string> = {};
12926
+ const emptyVersionTimeline: Array<{ version: number; sha: string; prompt: string }> = [];
12732
12927
  $: {
12733
12928
  void shapePreviewSourceByWidgetId;
12734
12929
  void shapeVersionPreviewByWidgetId;
@@ -12748,11 +12943,13 @@ Requirements:
12748
12943
  nextTimeline[widgetId] = buildVersionTimelineForPanel(widgetId);
12749
12944
  nextViewing[widgetId] = viewingVersionNumberForPanel(widgetId);
12750
12945
  }
12751
- headCommitShaByWidgetId = nextHeads;
12752
- versionLabelsByWidgetId = nextLabels;
12753
- versionPromptLabelsByWidgetId = nextPrompts;
12754
- versionTimelineByWidgetId = nextTimeline;
12755
- viewingVersionByWidgetId = nextViewing;
12946
+ // A new object with the same contents still counts as a change and makes the
12947
+ // chat rebuild every turn. That rebuild was running again on each progress tick.
12948
+ if (JSON.stringify(headCommitShaByWidgetId) !== JSON.stringify(nextHeads)) headCommitShaByWidgetId = nextHeads;
12949
+ if (JSON.stringify(versionLabelsByWidgetId) !== JSON.stringify(nextLabels)) versionLabelsByWidgetId = nextLabels;
12950
+ if (JSON.stringify(versionPromptLabelsByWidgetId) !== JSON.stringify(nextPrompts)) versionPromptLabelsByWidgetId = nextPrompts;
12951
+ if (JSON.stringify(versionTimelineByWidgetId) !== JSON.stringify(nextTimeline)) versionTimelineByWidgetId = nextTimeline;
12952
+ if (JSON.stringify(viewingVersionByWidgetId) !== JSON.stringify(nextViewing)) viewingVersionByWidgetId = nextViewing;
12756
12953
  }
12757
12954
 
12758
12955
  /** Commit shas are keyed on 7 chars — that is what the chat summaries carry. */
@@ -12771,7 +12968,7 @@ Requirements:
12771
12968
 
12772
12969
  function buildVersionLabelsForPanel(widgetId: string): Record<string, string> {
12773
12970
  const labels: Record<string, string> = {};
12774
- const ps = getPanelDisplayState(widgetId);
12971
+ const ps = versionChromeSnapshot(widgetId);
12775
12972
  const history = ps.publishHistory?.length ? ps.publishHistory : publishHistory;
12776
12973
  for (const record of history || []) {
12777
12974
  if (record?.version == null) continue;
@@ -12790,7 +12987,7 @@ Requirements:
12790
12987
  }
12791
12988
 
12792
12989
  function buildVersionTimelineForPanel(widgetId: string): Array<{ version: number; sha: string; prompt: string }> {
12793
- const ps = getPanelDisplayState(widgetId);
12990
+ const ps = versionChromeSnapshot(widgetId);
12794
12991
  const history = ps.publishHistory?.length ? ps.publishHistory : publishHistory;
12795
12992
  const timeline: Array<{ version: number; sha: string; prompt: string }> = [];
12796
12993
  for (const record of history || []) {
@@ -12806,7 +13003,7 @@ Requirements:
12806
13003
  /** User prompt → "Version N", for turns whose commit line was never saved. */
12807
13004
  function buildVersionPromptLabelsForPanel(widgetId: string): Record<string, string> {
12808
13005
  const labels: Record<string, string> = {};
12809
- const ps = getPanelDisplayState(widgetId);
13006
+ const ps = versionChromeSnapshot(widgetId);
12810
13007
  const history = ps.publishHistory?.length ? ps.publishHistory : publishHistory;
12811
13008
  for (const record of history || []) {
12812
13009
  if (record?.version == null) continue;
@@ -12825,6 +13022,8 @@ Requirements:
12825
13022
  }
12826
13023
 
12827
13024
  function syncWidgetShapeLivePreviews(): void {
13025
+ // This runs once per canvas frame while a shape moves. A call limit here
13026
+ // left the live iframe behind the shape.
12828
13027
  measureSync('sync-widget-shape-previews', () => {
12829
13028
  try {
12830
13029
  canvasSelectedWidgetShapeId = canvasRef?.getSelectedWidgetShapeId?.() ?? null;
@@ -12934,6 +13133,13 @@ Requirements:
12934
13133
  ...widgetPanelSnapshots,
12935
13134
  [widgetId]: { ...getPanelState(widgetId), ...patch },
12936
13135
  };
13136
+ // Progress text does not change versions or the chat's commit badges.
13137
+ // Bumping the revision here rebuilt every turn on each percentage.
13138
+ const patchKeys = Object.keys(patch);
13139
+ const statusOnly = patchKeys.length > 0 && patchKeys.every((key) =>
13140
+ key === 'generateCodeStatus' || key === 'lastGenerationFailed' || key === 'lastGenerationError'
13141
+ );
13142
+ if (statusOnly) return;
12937
13143
  if (patch.publishHistoryResolved) {
12938
13144
  if (widgetId === focusedPanelWidgetId) {
12939
13145
  if (patch.publishHistory) publishHistory = [...patch.publishHistory];
@@ -14289,25 +14495,30 @@ $: if ($dynamicWorkerPreviewStatus.widgetId && $dynamicWorkerPreviewStatus.previ
14289
14495
  const wsEventKey = `${wsReadyWidgetId}:${$dynamicWorkerPreviewStatus.previewUrl}:${$dynamicWorkerPreviewStatus.timestamp ?? ''}`;
14290
14496
  if (wsEventKey !== lastWsWorkerPreviewEventKey) {
14291
14497
  lastWsWorkerPreviewEventKey = wsEventKey;
14292
- const selectedVersion = dropdownVersionByWidgetId[wsReadyWidgetId]
14293
- || shapePreviewSourceByWidgetId[wsReadyWidgetId];
14294
- const keepHistoricalSelection = !generatingWidgetIds[wsReadyWidgetId]
14295
- && !!selectedVersion?.startsWith('v:')
14296
- && !versionUsesSharedHeadPreview(wsReadyWidgetId, selectedVersion);
14297
- if (keepHistoricalSelection) {
14298
- console.log('[CreatorApp] Historical version stays selected; shared HEAD build ignored', wsReadyWidgetId.substring(0, 8));
14299
- } else {
14300
- shapePreviewSourceByWidgetId = {
14301
- ...shapePreviewSourceByWidgetId,
14302
- [wsReadyWidgetId]: 'preview',
14303
- };
14304
- if (codegenCaptureBlocked()) {
14305
- console.log('[CreatorApp] Defer canvas Worker preview reload until codegen finishes', wsReadyWidgetId.substring(0, 8));
14498
+ const previewWidgetId = wsReadyWidgetId;
14499
+ // The socket handler runs on the page thread. Deciding the preview here
14500
+ // was in the same turn as "Building preview…", and that turn never returned.
14501
+ setTimeout(() => {
14502
+ const selectedVersion = dropdownVersionByWidgetId[previewWidgetId]
14503
+ || shapePreviewSourceByWidgetId[previewWidgetId];
14504
+ const keepHistoricalSelection = !generatingWidgetIds[previewWidgetId]
14505
+ && !!selectedVersion?.startsWith('v:')
14506
+ && !versionUsesSharedHeadPreview(previewWidgetId, selectedVersion);
14507
+ if (keepHistoricalSelection) {
14508
+ console.log('[CreatorApp] Historical version stays selected; shared HEAD build ignored', previewWidgetId.substring(0, 8));
14509
+ } else if (generatingWidgetIds[previewWidgetId] || codegenCaptureBlocked()) {
14510
+ // Writing the source here retriggers the version maps and the whole chat
14511
+ // in the same turn as "Saving to repository…". Apply it when the turn ends.
14512
+ console.log('[CreatorApp] Defer canvas Worker preview reload until codegen finishes', previewWidgetId.substring(0, 8));
14306
14513
  } else {
14514
+ shapePreviewSourceByWidgetId = {
14515
+ ...shapePreviewSourceByWidgetId,
14516
+ [previewWidgetId]: 'preview',
14517
+ };
14307
14518
  syncWidgetShapeLivePreviews();
14308
- widgetShapeLivePreviewsRef?.requestReload?.(wsReadyWidgetId);
14519
+ widgetShapeLivePreviewsRef?.requestReload?.(previewWidgetId);
14309
14520
  }
14310
- }
14521
+ }, 0);
14311
14522
  }
14312
14523
  }
14313
14524
 
@@ -15568,6 +15779,20 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15568
15779
  canvasesClient.getCanvasRaw({ id: canvasId }),
15569
15780
  'getCanvas',
15570
15781
  );
15782
+ // A 304 has no body. Parsing it throws, the loader treats that as a
15783
+ // failed read, and the page asks for the same canvas again.
15784
+ if (canvasResponse.raw.status === 304) {
15785
+ markCanvasStateLoaded();
15786
+ let cachedIds: string[] = [];
15787
+ if (localCachedJson) {
15788
+ try {
15789
+ cachedIds = extractWidgetIdsFromCanvasContent(JSON.parse(localCachedJson));
15790
+ } catch (parseErr) {
15791
+ console.warn('[CanvasDebug] Cached canvas JSON could not be read after 304', parseErr);
15792
+ }
15793
+ }
15794
+ return { loaded: true, widgetIds: cachedIds };
15795
+ }
15571
15796
  const canvasJson = await canvasResponse.raw.json();
15572
15797
  const canvasRecord = canvasJson?.data || canvasJson;
15573
15798
  if (loadEpoch !== canvasLoadEpoch || ignoreIncomingCanvasLoads) {
@@ -16897,6 +17122,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16897
17122
  panZoomPosition="TC"
16898
17123
  showSaveButton={true}
16899
17124
  autosaveDelayMs={import.meta.env.DEV ? 15000 : 5000}
17125
+ suspendAutosave={suspendCanvasAutosave}
16900
17126
  isExternalDataLoading={!isCanvasStateLoaded}
16901
17127
  />
16902
17128
  {/if}
@@ -17266,7 +17492,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17266
17492
  isGeneratingCode={!!generatingWidgetIds[panelWidgetId]}
17267
17493
  skipBasePreview={(!!pendingAutoGenerateWidgetId && pendingAutoGenerateWidgetId === panelWidgetId) || (!!pendingDuplicateBuildWidgetId && pendingDuplicateBuildWidgetId === panelWidgetId)}
17268
17494
  repositorySetupStatus={repositorySetupByWidgetId[panelWidgetId] ?? (normalizeRepositoryId(panelWidget) ? 'ready' : 'pending')}
17269
- generateCodeStatus={ps.generateCodeStatus}
17495
+ generateCodeStatus={isPanelFocused ? (generateCodeStatus ?? ps.generateCodeStatus) : ps.generateCodeStatus}
17270
17496
  {isCheckingActiveGeneration}
17271
17497
  lastCommitId={ps.lastCommitId ?? loadCommitIdForWidget(panelWidgetId)}
17272
17498
  {debugMode}
@@ -17772,7 +17998,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17772
17998
  {#if ps.lastGenerationFailed}
17773
17999
  <span class="text-red-500 font-medium">{$t('creator.codegen.generationFailed')}</span>
17774
18000
  {:else}
17775
- <span class="text-gray-400">{$t('creator.status.label')}</span> {statusLabel(ps.generateCodeStatus, $t)}
18001
+ <span class="text-gray-400">{$t('creator.status.label')}</span> {statusLabel(isPanelFocused ? (generateCodeStatus ?? ps.generateCodeStatus) : ps.generateCodeStatus, $t)}
17776
18002
  {/if}
17777
18003
  </div>
17778
18004
  </div>
@@ -17951,9 +18177,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17951
18177
  }
17952
18178
  }}
17953
18179
  widgetHeadCommitSha={headCommitShaByWidgetId[panelWidgetId] || ps.lastCommitId}
17954
- versionLabelByCommitSha={versionLabelsByWidgetId[panelWidgetId] || {}}
17955
- versionLabelByPrompt={versionPromptLabelsByWidgetId[panelWidgetId] || {}}
17956
- versionTimeline={versionTimelineByWidgetId[panelWidgetId] || []}
18180
+ versionLabelByCommitSha={versionLabelsByWidgetId[panelWidgetId] ?? emptyVersionLabels}
18181
+ versionLabelByPrompt={versionPromptLabelsByWidgetId[panelWidgetId] ?? emptyVersionLabels}
18182
+ versionTimeline={versionTimelineByWidgetId[panelWidgetId] ?? emptyVersionTimeline}
17957
18183
  viewingVersion={viewingVersionByWidgetId[panelWidgetId] ?? null}
17958
18184
  onSendMessage={(content, attachments) => handleChatSendMessage(content, attachments, panelWidgetId)}
17959
18185
  onRetryMessage={(content) => handleChatRetryMessage(content, panelWidgetId)}
@@ -18207,7 +18433,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18207
18433
  height="620px"
18208
18434
  showDragHandle={false}
18209
18435
  enableDrag={false}
18210
- {mediaLibrary}
18436
+ mediaLibrary={mediaLibraryForFields ?? mediaLibrary}
18437
+ {pickFile}
18438
+ {storeFileUrl}
18211
18439
  defaultTab="design"
18212
18440
  on:propertyChange={handleEditorPropertyChange}
18213
18441
  on:contentItemsChanged={handleEditorContentItemsChanged}
@@ -22,6 +22,7 @@ declare const CreatorApp: $$__sveltets_2_IsomorphicComponent<{
22
22
  initialCompositionId?: CreatorAppProps["initialCompositionId"];
23
23
  initialStep?: CreatorAppProps["initialStep"];
24
24
  forceCreateNewWidget?: CreatorAppProps["forceCreateNewWidget"];
25
+ initialSketchName?: CreatorAppProps["initialSketchName"];
25
26
  apiUrl?: CreatorAppProps["apiUrl"];
26
27
  widgetBuilderUrl?: CreatorAppProps["widgetBuilderUrl"];
27
28
  initialDebugMode?: CreatorAppProps["initialDebugMode"];
@@ -43,7 +44,10 @@ declare const CreatorApp: $$__sveltets_2_IsomorphicComponent<{
43
44
  onCanvasUnavailable?: CreatorAppProps["onCanvasUnavailable"];
44
45
  onCanvasChanged?: CreatorAppProps["onCanvasChanged"];
45
46
  onReady?: CreatorAppProps["onReady"];
46
- /** The page's own media library for the editor's file pickers (see `CreatorAppProps.mediaLibrary`). */ mediaLibrary?: CreatorAppProps["mediaLibrary"];
47
+ /** Partner library for chat/canvas uploads (see `CreatorAppProps.mediaLibrary`). */ mediaLibrary?: CreatorAppProps["mediaLibrary"];
48
+ /** Optional override for PropsEditor file fields (`purpose: 'field'`). */ mediaLibraryForFields?: CreatorAppProps["mediaLibraryForFields"];
49
+ /** Opens the partner's file picker instead of the built-in File Browser (see `CreatorAppProps.pickFile`). */ pickFile?: CreatorAppProps["pickFile"];
50
+ /** Resolves the url stored with a picked file (see `CreatorAppProps.storeFileUrl`). */ storeFileUrl?: CreatorAppProps["storeFileUrl"];
47
51
  /**
48
52
  * The language of everything the creator shows (see `CreatorAppProps.locale` and `CreatorAppProps.messages`). The one flat
49
53
  * `messages` object is split between the creator's own words and the parts it draws: the editor (with its file
@@ -94,7 +94,7 @@
94
94
  </script>
95
95
 
96
96
  <div
97
- class="version-dropdown-row flex items-center justify-between gap-2 rounded px-2 py-1.5 w-full text-[10px] cursor-pointer {selected ? 'bg-emerald-50 text-emerald-800' : 'text-gray-700 hover:bg-gray-50'}"
97
+ class="version-dropdown-row flex items-center justify-between gap-2 rounded px-2 py-1.5 w-full text-[10px] cursor-pointer {selected ? 'bg-emerald-200 text-emerald-950' : 'text-gray-700 hover:bg-emerald-100'}"
98
98
  role="option"
99
99
  aria-selected={selected}
100
100
  tabindex="0"