@widgetic/creator 0.4.1 → 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.
@@ -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;
@@ -6732,6 +6801,54 @@
6732
6801
  let canvasRowDeferred = false;
6733
6802
  let canvasRowCreatePromise: Promise<string | null> | null = null;
6734
6803
 
6804
+ const untitledCanvasBaseName = 'Untitled Widget';
6805
+
6806
+ function nextUntitledCanvasName(existingNames: string[]): string {
6807
+ let highest = 0;
6808
+ for (const rawName of existingNames) {
6809
+ const name = (rawName || '').trim();
6810
+ const match = name.match(/^Untitled (?:Widget|Image)(?: (\d+))?$/);
6811
+ if (!match) continue;
6812
+ const value = match[1] ? Number(match[1]) : 1;
6813
+ if (value > highest) highest = value;
6814
+ }
6815
+ return `${untitledCanvasBaseName} ${highest + 1}`;
6816
+ }
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
+
6844
+ function canvasCreateRequest(persistenceKey: string) {
6845
+ const trimmedProjectId = typeof projectId === 'string' ? projectId.trim() : '';
6846
+ return {
6847
+ persistenceKey,
6848
+ ...(trimmedProjectId ? { projectId: trimmedProjectId } : {})
6849
+ };
6850
+ }
6851
+
6735
6852
  async function ensureCanvasRowForFirstEdit(): Promise<string | null> {
6736
6853
  const existingId = typeof canvasId === 'string' ? canvasId.trim() : '';
6737
6854
  if (existingId) return existingId;
@@ -6742,15 +6859,9 @@
6742
6859
  return null;
6743
6860
  }
6744
6861
  try {
6745
- const usedNames = new Set(userCanvases.map((c) => (c.name || '').trim()).filter(Boolean));
6746
- let canvasIndex = userCanvases.length + 1;
6747
- let newName = `Canvas ${canvasIndex}`;
6748
- while (usedNames.has(newName)) {
6749
- canvasIndex += 1;
6750
- newName = `Canvas ${canvasIndex}`;
6751
- }
6862
+ const newName = sketchNameFromHost() || nextUntitledCanvasName(await canvasNamesForNewSketch());
6752
6863
  const createdRaw = await canvasesClient.createCanvas({
6753
- createCanvasRequest: { persistenceKey: newName }
6864
+ createCanvasRequest: canvasCreateRequest(newName)
6754
6865
  });
6755
6866
  const createdId = unwrapCreatedCanvasId(createdRaw);
6756
6867
  if (!createdId) {
@@ -6790,17 +6901,9 @@
6790
6901
  }
6791
6902
 
6792
6903
  try {
6793
- // Names must be unique per user — duplicate keys ("Canvas 1" x N) made
6794
- // canvases indistinguishable and contributed to cross-canvas widget mix-ups.
6795
- const usedNames = new Set(userCanvases.map((c) => (c.name || '').trim()).filter(Boolean));
6796
- let canvasIndex = userCanvases.length + 1;
6797
- let newName = `Canvas ${canvasIndex}`;
6798
- while (usedNames.has(newName)) {
6799
- canvasIndex += 1;
6800
- newName = `Canvas ${canvasIndex}`;
6801
- }
6904
+ const newName = sketchNameFromHost() || nextUntitledCanvasName(await canvasNamesForNewSketch());
6802
6905
  const createdRaw = await canvasesClient.createCanvas({
6803
- createCanvasRequest: { persistenceKey: newName }
6906
+ createCanvasRequest: canvasCreateRequest(newName)
6804
6907
  });
6805
6908
  const createdId = unwrapCreatedCanvasId(createdRaw);
6806
6909
  // console.log('[WidgetCreator] New canvas created:', createdId, newName, createdRaw);
@@ -8627,11 +8730,43 @@
8627
8730
  });
8628
8731
  return null;
8629
8732
  }
8630
-
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
+
8631
8767
  try {
8632
8768
  const webpFile = await imageFileToWebpFile(file, 0.95);
8633
8769
  const base64 = await fileToBase64(webpFile);
8634
- // console.log('[WidgetCreator] Image processed:', file.name, 'Size:', sizeMB.toFixed(2), 'MB');
8635
8770
  return base64;
8636
8771
  } catch (error) {
8637
8772
  console.error('[WidgetCreator] Error processing image:', error);
@@ -10162,6 +10297,7 @@ Requirements:
10162
10297
  // The wait's callback sees the last frame of a stream twice: a job stopped elsewhere is shown as stopped once
10163
10298
  let cancelledElsewhereShown = false;
10164
10299
  await waitForOperation(operationId, (op) => {
10300
+ freezeProbe('sse', `${op?.status ?? ''} ${op?.progress ?? ''}`);
10165
10301
  // Check if aborted before processing updates
10166
10302
  if (signal.aborted) return;
10167
10303
  if (!op) return;
@@ -10222,6 +10358,19 @@ Requirements:
10222
10358
  }
10223
10359
 
10224
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]);
10225
10374
  clearActiveOperationId(generationWidgetId);
10226
10375
 
10227
10376
  const completedCommitSha = getOperationCommitId(op.metadata);
@@ -10410,38 +10559,42 @@ Requirements:
10410
10559
  stampWidgetRepositoryId(generationWidgetId, completedRepoId);
10411
10560
  }
10412
10561
 
10562
+ const commitShort = completedCommitSha ? completedCommitSha.substring(0, 7) : '';
10563
+ const savedStatus = !completedCommitSha
10564
+ ? 'Code was not saved to the repository. Retry saves it and records a version.'
10565
+ : completedPreviewBuildErr
10566
+ ? `Code saved (${commitShort}) — building preview…`
10567
+ : `Code saved (${commitShort}) — loading preview…`;
10413
10568
  patchCodegenUiState(generationWidgetId, {
10414
10569
  hasGeneratedCode: true,
10415
10570
  ...(completedCommitSha ? { lastCommitId: completedCommitSha } : {}),
10416
- lastGenerationFailed: false,
10571
+ lastGenerationFailed: !completedCommitSha,
10417
10572
  lastGenerationError: completedPreviewBuildErr,
10418
- generateCodeStatus: completedPreviewBuildErr
10419
- ? `Code saved${completedCommitSha ? ` (${completedCommitSha.substring(0, 7)})` : ''} — building preview…`
10420
- : `Code saved${completedCommitSha ? ` (${completedCommitSha.substring(0, 7)})` : ''} — loading preview…`,
10573
+ generateCodeStatus: savedStatus,
10421
10574
  });
10422
10575
 
10423
- const commitShort = completedCommitSha ? completedCommitSha.substring(0, 7) : '';
10424
10576
  if (!completedCached) {
10425
- panelChat?.updateLatestCodegenStatusMessage?.(
10426
- completedPreviewBuildErr
10427
- ? `Code saved${commitShort ? ` (${commitShort})` : ''} — building preview…`
10428
- : `Code saved${commitShort ? ` (${commitShort})` : ''} — loading preview…`,
10429
- );
10577
+ panelChat?.updateLatestCodegenStatusMessage?.(savedStatus);
10430
10578
  }
10431
10579
 
10432
10580
  // console.log('Widget Creator: Code generation operation completed for widget', generationWidgetId.substring(0, 8), ':', op);
10433
10581
 
10434
- if (completedPreviewBuildErr) {
10582
+ if (completedPreviewBuildErr && completedCommitSha) {
10435
10583
  generationPanelRef?.setPreviewBuildError(null);
10436
10584
  generationPanelRef?.setPreviewLoadingState(true);
10437
10585
  panelChat?.addAssistantMessage(
10438
- `Code saved${completedCommitSha ? ` (Commit: ${completedCommitSha.substring(0, 7)})` : ''}, but preview build failed:\n${completedPreviewBuildErr}\n\nRebuilding preview…`,
10586
+ `Code saved (Commit: ${commitShort}), but preview build failed:\n${completedPreviewBuildErr}\n\nRebuilding preview…`,
10439
10587
  true
10440
10588
  );
10441
10589
  showToast('warning', $t('creator.codegen.codeSavedRebuildingPreview'), {
10442
10590
  description: completedPreviewBuildErr.length > 120 ? `${completedPreviewBuildErr.slice(0, 120)}…` : completedPreviewBuildErr,
10443
10591
  duration: 8000
10444
10592
  });
10593
+ } else if (!completedCommitSha) {
10594
+ showToast('warning', $t('creator.codegen.codeWasNotSaved'), {
10595
+ description: $t('creator.codegen.retrySavesItAndRecordsAVersion'),
10596
+ duration: 8000
10597
+ });
10445
10598
  } else {
10446
10599
  showToast(
10447
10600
  'success',
@@ -10468,14 +10621,16 @@ Requirements:
10468
10621
  // generation just happened.
10469
10622
  panelChat?.addAssistantMessage(
10470
10623
  cachedChatSummary ??
10471
- (completedPreviewBuildErr
10472
- ? `Code saved${completedCommitSha ? ` (Commit: ${completedCommitSha.substring(0, 7)})` : ''}, but preview build failed:\n${completedPreviewBuildErr}\n\nRebuilding preview…`
10473
- : `Code generation completed!${completedCommitSha ? ` Commit: ${completedCommitSha.substring(0, 7)}` : ''}\nPreview is loading…`),
10624
+ (!completedCommitSha
10625
+ ? 'Code was not saved to the repository. Retry saves it and records a version.'
10626
+ : completedPreviewBuildErr
10627
+ ? `Code saved (Commit: ${commitShort}), but preview build failed:\n${completedPreviewBuildErr}\n\nRebuilding preview…`
10628
+ : `Code generation completed! Commit: ${commitShort}\nPreview is loading…`),
10474
10629
  true
10475
10630
  );
10476
- if (!completedPreviewBuildErr && !completedCached) {
10631
+ if (!completedPreviewBuildErr && !completedCached && completedCommitSha) {
10477
10632
  panelChat?.updateLatestCodegenStatusMessage?.(
10478
- `Code generation completed!${completedCommitSha ? ` Commit: ${completedCommitSha.substring(0, 7)}` : ''}\nPreview is loading…`,
10633
+ `Code generation completed! Commit: ${commitShort}\nPreview is loading…`,
10479
10634
  );
10480
10635
  }
10481
10636
 
@@ -10555,6 +10710,8 @@ Requirements:
10555
10710
  });
10556
10711
  }
10557
10712
  }, completedPreviewBuildErr ? 400 : 800);
10713
+ }, 0);
10714
+ }, 0);
10558
10715
  } else {
10559
10716
  pushCodegenProgressToUi(op, generationWidgetId);
10560
10717
  }
@@ -11024,14 +11181,18 @@ Requirements:
11024
11181
  });
11025
11182
  }
11026
11183
 
11027
- const publishedPanelRef = getWidgetDetailsRef(capturedWidgetId);
11028
- console.log('[Publish] Refreshing preview after publish (step:', widgetDetailsStep, ')');
11029
- publishedPanelRef?.invalidatePublishedArtifactCache?.();
11030
- await publishedPanelRef?.refreshPreview({ withRetry: true });
11031
- scheduleListThumbnailCapture(capturedWidgetId);
11032
-
11033
- await loadPublishHistory();
11034
- 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
+ }
11035
11196
 
11036
11197
  } catch (err: any) {
11037
11198
  console.error('[Publish] Error publishing widget:', err);
@@ -11252,6 +11413,8 @@ Requirements:
11252
11413
 
11253
11414
  // Clean up interval on component destroy
11254
11415
  onDestroy(() => {
11416
+ mountUploadAbortController?.abort();
11417
+ mountUploadAbortController = null;
11255
11418
  clearCanvasLoadFailsafe();
11256
11419
  if (tokenCheckInterval) clearInterval(tokenCheckInterval);
11257
11420
  if (tokenDisplayInterval) clearInterval(tokenDisplayInterval);
@@ -11551,8 +11714,15 @@ Requirements:
11551
11714
  return codegenProgressDebugLine(op, stage, pct);
11552
11715
  }
11553
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
+
11554
11723
  function pushCodegenProgressToUi(op: OperationStatus, widgetId: string | null | undefined) {
11555
11724
  const line = formatCodegenProgressStatus(op);
11725
+ freezeProbe('progress', line);
11556
11726
  // Feed the freeze watchdog the latest status so a [FreezeReport] names the
11557
11727
  // stage the UI was showing when the main thread stopped responding.
11558
11728
  (window as any).__widgeticFreezeWatchdog?.setStatus?.(line);
@@ -11584,6 +11754,9 @@ Requirements:
11584
11754
 
11585
11755
  /** Same throttle for the in-chat status bubble (updateLatestCodegenStatusMessage). */
11586
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;
11587
11760
  const key = widgetId || '_focused';
11588
11761
  codegenChatStatusPendingLine[key] = line;
11589
11762
  if (codegenChatStatusTimers[key]) return;
@@ -11618,6 +11791,23 @@ Requirements:
11618
11791
  .replace(/\s{2,}/g, ' ')
11619
11792
  .trim();
11620
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
+ }
11621
11811
  patchPanelSnapshot(widgetId, nextPatch);
11622
11812
  if (widgetId === focusedPanelWidgetId) {
11623
11813
  if (nextPatch.generateCodeStatus !== undefined) generateCodeStatus = nextPatch.generateCodeStatus;
@@ -12651,9 +12841,27 @@ Requirements:
12651
12841
  }
12652
12842
  }
12653
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
+
12654
12862
  /** Commit SHA for the version currently selected in the version menu (drives Head-at-commit badge). */
12655
12863
  function resolveViewingCommitShaForPanel(widgetId: string): string | null {
12656
- const ps = getPanelDisplayState(widgetId);
12864
+ const ps = versionChromeSnapshot(widgetId);
12657
12865
  const restored = restoredViewingVersionByWidgetId[widgetId];
12658
12866
  if (Number.isFinite(restored)) {
12659
12867
  const history = ps.publishHistory?.length ? ps.publishHistory : publishHistory;
@@ -12714,6 +12922,8 @@ Requirements:
12714
12922
  let versionPromptLabelsByWidgetId: Record<string, Record<string, string>> = {};
12715
12923
  let versionTimelineByWidgetId: Record<string, Array<{ version: number; sha: string; prompt: string }>> = {};
12716
12924
  let viewingVersionByWidgetId: Record<string, number | null> = {};
12925
+ const emptyVersionLabels: Record<string, string> = {};
12926
+ const emptyVersionTimeline: Array<{ version: number; sha: string; prompt: string }> = [];
12717
12927
  $: {
12718
12928
  void shapePreviewSourceByWidgetId;
12719
12929
  void shapeVersionPreviewByWidgetId;
@@ -12733,11 +12943,13 @@ Requirements:
12733
12943
  nextTimeline[widgetId] = buildVersionTimelineForPanel(widgetId);
12734
12944
  nextViewing[widgetId] = viewingVersionNumberForPanel(widgetId);
12735
12945
  }
12736
- headCommitShaByWidgetId = nextHeads;
12737
- versionLabelsByWidgetId = nextLabels;
12738
- versionPromptLabelsByWidgetId = nextPrompts;
12739
- versionTimelineByWidgetId = nextTimeline;
12740
- 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;
12741
12953
  }
12742
12954
 
12743
12955
  /** Commit shas are keyed on 7 chars — that is what the chat summaries carry. */
@@ -12756,7 +12968,7 @@ Requirements:
12756
12968
 
12757
12969
  function buildVersionLabelsForPanel(widgetId: string): Record<string, string> {
12758
12970
  const labels: Record<string, string> = {};
12759
- const ps = getPanelDisplayState(widgetId);
12971
+ const ps = versionChromeSnapshot(widgetId);
12760
12972
  const history = ps.publishHistory?.length ? ps.publishHistory : publishHistory;
12761
12973
  for (const record of history || []) {
12762
12974
  if (record?.version == null) continue;
@@ -12775,7 +12987,7 @@ Requirements:
12775
12987
  }
12776
12988
 
12777
12989
  function buildVersionTimelineForPanel(widgetId: string): Array<{ version: number; sha: string; prompt: string }> {
12778
- const ps = getPanelDisplayState(widgetId);
12990
+ const ps = versionChromeSnapshot(widgetId);
12779
12991
  const history = ps.publishHistory?.length ? ps.publishHistory : publishHistory;
12780
12992
  const timeline: Array<{ version: number; sha: string; prompt: string }> = [];
12781
12993
  for (const record of history || []) {
@@ -12791,7 +13003,7 @@ Requirements:
12791
13003
  /** User prompt → "Version N", for turns whose commit line was never saved. */
12792
13004
  function buildVersionPromptLabelsForPanel(widgetId: string): Record<string, string> {
12793
13005
  const labels: Record<string, string> = {};
12794
- const ps = getPanelDisplayState(widgetId);
13006
+ const ps = versionChromeSnapshot(widgetId);
12795
13007
  const history = ps.publishHistory?.length ? ps.publishHistory : publishHistory;
12796
13008
  for (const record of history || []) {
12797
13009
  if (record?.version == null) continue;
@@ -12810,6 +13022,8 @@ Requirements:
12810
13022
  }
12811
13023
 
12812
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.
12813
13027
  measureSync('sync-widget-shape-previews', () => {
12814
13028
  try {
12815
13029
  canvasSelectedWidgetShapeId = canvasRef?.getSelectedWidgetShapeId?.() ?? null;
@@ -12919,6 +13133,13 @@ Requirements:
12919
13133
  ...widgetPanelSnapshots,
12920
13134
  [widgetId]: { ...getPanelState(widgetId), ...patch },
12921
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;
12922
13143
  if (patch.publishHistoryResolved) {
12923
13144
  if (widgetId === focusedPanelWidgetId) {
12924
13145
  if (patch.publishHistory) publishHistory = [...patch.publishHistory];
@@ -14274,25 +14495,30 @@ $: if ($dynamicWorkerPreviewStatus.widgetId && $dynamicWorkerPreviewStatus.previ
14274
14495
  const wsEventKey = `${wsReadyWidgetId}:${$dynamicWorkerPreviewStatus.previewUrl}:${$dynamicWorkerPreviewStatus.timestamp ?? ''}`;
14275
14496
  if (wsEventKey !== lastWsWorkerPreviewEventKey) {
14276
14497
  lastWsWorkerPreviewEventKey = wsEventKey;
14277
- const selectedVersion = dropdownVersionByWidgetId[wsReadyWidgetId]
14278
- || shapePreviewSourceByWidgetId[wsReadyWidgetId];
14279
- const keepHistoricalSelection = !generatingWidgetIds[wsReadyWidgetId]
14280
- && !!selectedVersion?.startsWith('v:')
14281
- && !versionUsesSharedHeadPreview(wsReadyWidgetId, selectedVersion);
14282
- if (keepHistoricalSelection) {
14283
- console.log('[CreatorApp] Historical version stays selected; shared HEAD build ignored', wsReadyWidgetId.substring(0, 8));
14284
- } else {
14285
- shapePreviewSourceByWidgetId = {
14286
- ...shapePreviewSourceByWidgetId,
14287
- [wsReadyWidgetId]: 'preview',
14288
- };
14289
- if (codegenCaptureBlocked()) {
14290
- 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));
14291
14513
  } else {
14514
+ shapePreviewSourceByWidgetId = {
14515
+ ...shapePreviewSourceByWidgetId,
14516
+ [previewWidgetId]: 'preview',
14517
+ };
14292
14518
  syncWidgetShapeLivePreviews();
14293
- widgetShapeLivePreviewsRef?.requestReload?.(wsReadyWidgetId);
14519
+ widgetShapeLivePreviewsRef?.requestReload?.(previewWidgetId);
14294
14520
  }
14295
- }
14521
+ }, 0);
14296
14522
  }
14297
14523
  }
14298
14524
 
@@ -15553,6 +15779,20 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15553
15779
  canvasesClient.getCanvasRaw({ id: canvasId }),
15554
15780
  'getCanvas',
15555
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
+ }
15556
15796
  const canvasJson = await canvasResponse.raw.json();
15557
15797
  const canvasRecord = canvasJson?.data || canvasJson;
15558
15798
  if (loadEpoch !== canvasLoadEpoch || ignoreIncomingCanvasLoads) {
@@ -16882,6 +17122,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16882
17122
  panZoomPosition="TC"
16883
17123
  showSaveButton={true}
16884
17124
  autosaveDelayMs={import.meta.env.DEV ? 15000 : 5000}
17125
+ suspendAutosave={suspendCanvasAutosave}
16885
17126
  isExternalDataLoading={!isCanvasStateLoaded}
16886
17127
  />
16887
17128
  {/if}
@@ -17251,7 +17492,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17251
17492
  isGeneratingCode={!!generatingWidgetIds[panelWidgetId]}
17252
17493
  skipBasePreview={(!!pendingAutoGenerateWidgetId && pendingAutoGenerateWidgetId === panelWidgetId) || (!!pendingDuplicateBuildWidgetId && pendingDuplicateBuildWidgetId === panelWidgetId)}
17253
17494
  repositorySetupStatus={repositorySetupByWidgetId[panelWidgetId] ?? (normalizeRepositoryId(panelWidget) ? 'ready' : 'pending')}
17254
- generateCodeStatus={ps.generateCodeStatus}
17495
+ generateCodeStatus={isPanelFocused ? (generateCodeStatus ?? ps.generateCodeStatus) : ps.generateCodeStatus}
17255
17496
  {isCheckingActiveGeneration}
17256
17497
  lastCommitId={ps.lastCommitId ?? loadCommitIdForWidget(panelWidgetId)}
17257
17498
  {debugMode}
@@ -17757,7 +17998,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17757
17998
  {#if ps.lastGenerationFailed}
17758
17999
  <span class="text-red-500 font-medium">{$t('creator.codegen.generationFailed')}</span>
17759
18000
  {:else}
17760
- <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)}
17761
18002
  {/if}
17762
18003
  </div>
17763
18004
  </div>
@@ -17936,9 +18177,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17936
18177
  }
17937
18178
  }}
17938
18179
  widgetHeadCommitSha={headCommitShaByWidgetId[panelWidgetId] || ps.lastCommitId}
17939
- versionLabelByCommitSha={versionLabelsByWidgetId[panelWidgetId] || {}}
17940
- versionLabelByPrompt={versionPromptLabelsByWidgetId[panelWidgetId] || {}}
17941
- versionTimeline={versionTimelineByWidgetId[panelWidgetId] || []}
18180
+ versionLabelByCommitSha={versionLabelsByWidgetId[panelWidgetId] ?? emptyVersionLabels}
18181
+ versionLabelByPrompt={versionPromptLabelsByWidgetId[panelWidgetId] ?? emptyVersionLabels}
18182
+ versionTimeline={versionTimelineByWidgetId[panelWidgetId] ?? emptyVersionTimeline}
17942
18183
  viewingVersion={viewingVersionByWidgetId[panelWidgetId] ?? null}
17943
18184
  onSendMessage={(content, attachments) => handleChatSendMessage(content, attachments, panelWidgetId)}
17944
18185
  onRetryMessage={(content) => handleChatRetryMessage(content, panelWidgetId)}
@@ -18192,7 +18433,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18192
18433
  height="620px"
18193
18434
  showDragHandle={false}
18194
18435
  enableDrag={false}
18195
- {mediaLibrary}
18436
+ mediaLibrary={mediaLibraryForFields ?? mediaLibrary}
18437
+ {pickFile}
18438
+ {storeFileUrl}
18196
18439
  defaultTab="design"
18197
18440
  on:propertyChange={handleEditorPropertyChange}
18198
18441
  on:contentItemsChanged={handleEditorContentItemsChanged}