@widgetic/creator 0.4.27 → 0.4.29

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.
@@ -191,6 +191,7 @@
191
191
  type GenerationChannel,
192
192
  type OperationSnapshot
193
193
  } from './utils/generationSharing.js';
194
+ import { failureNoticeChanges } from './utils/failureNotice.js';
194
195
  import { generateEmbedCode, EMBED_FORMATS, type EmbedFormat } from './utils/embedCode.js';
195
196
 
196
197
  function openEmbedTestPage(href: string) {
@@ -492,10 +493,19 @@
492
493
  const gate = targetId ? getPublishGateForPanel(targetId) : null;
493
494
  const canPublish = !!gate && !gate.disabled;
494
495
  const label = gate?.label || $t('creator.common.publish');
495
- const signature = `${targetId}:${canPublish}:${label}:${panelDisplayRevision}:${isPublishing}:${generatingMark}`;
496
+ const publishedAlready = !!targetId && getPanelDisplayState(targetId).lastPublishedVersion !== null;
497
+ const unpublished = canPublish && (
498
+ /publish new v/i.test(label)
499
+ || (publishedAlready && hasUnpublishedChangesForPanel(targetId))
500
+ );
501
+ const signature = `${targetId}:${canPublish}:${label}:${unpublished}:${panelDisplayRevision}:${isPublishing}:${generatingMark}`;
496
502
  if (signature !== lastAnnouncedPublishState) {
497
503
  lastAnnouncedPublishState = signature;
498
- announceToSite(CREATOR_PUBLISH_STATE_EVENT, { canPublish, label });
504
+ announceToSite(CREATOR_PUBLISH_STATE_EVENT, {
505
+ canPublish,
506
+ label: unpublished ? 'Publish changes' : label,
507
+ unpublished,
508
+ });
499
509
  }
500
510
  }
501
511
 
@@ -1341,6 +1351,13 @@
1341
1351
  // while the repository save is still finishing. The canvas shape stays
1342
1352
  // deferred because generatingWidgetIds is still set.
1343
1353
  let previewUnblockedByWidgetId: Record<string, boolean> = {};
1354
+ /** The status line was set when the preview appeared. A later GitLab save must not write "Preview ready" again. */
1355
+ let previewReadyAnnouncedByWidgetId: Record<string, boolean> = {};
1356
+ /** Publish stays hidden until about five seconds after the preview is on screen. */
1357
+ let publishHeldByWidgetId: Record<string, boolean> = {};
1358
+ const PREVIEW_READY_STATUS = 'Generation complete (100%) · Preview ready';
1359
+ const PUBLISH_REVEAL_DELAY_MS = 5000;
1360
+ const publishRevealTimers = new Map<string, ReturnType<typeof setTimeout>>();
1344
1361
  /** Last slice of the model stream, per widget. Painted with the status throttle, not per token. */
1345
1362
  let generationStreamByWidgetId: Record<string, string> = {};
1346
1363
  function isAnyWidgetGenerating(): boolean {
@@ -1780,6 +1797,16 @@
1780
1797
  ...(attachments || []),
1781
1798
  { url: canvasSketch, fileType: 'image/png', fileName: 'design-screenshot.png' },
1782
1799
  ];
1800
+ getChatMethodsForWidget(widgetId)?.updateLastUserMessageAttachments?.(
1801
+ (attachments || [])
1802
+ .filter((attachment) => typeof attachment.url === 'string' && attachment.url.length > 0)
1803
+ .map((attachment) => ({
1804
+ url: attachment.url,
1805
+ file_type: attachment.fileType,
1806
+ file_name: attachment.fileName ?? null,
1807
+ })),
1808
+ );
1809
+ console.log('[Chat→Sketch] Sketch attached to the sent message', widgetId.substring(0, 8));
1783
1810
  }
1784
1811
  }
1785
1812
  } catch (captureError) {
@@ -4549,14 +4576,7 @@
4549
4576
  // Clear stuck "Code saved — loading preview…" once the iframe has content
4550
4577
  const panelStatus = getPanelState(panelWidgetId).generateCodeStatus || '';
4551
4578
  if (/loading preview|building preview|preview rebuilt from saved code/i.test(panelStatus)) {
4552
- const panelCommit =
4553
- getPanelState(panelWidgetId).lastCommitId || loadCommitIdForWidget(panelWidgetId);
4554
- const commitShort = panelCommit ? panelCommit.substring(0, 7) : '';
4555
- patchCodegenUiState(panelWidgetId, {
4556
- hasGeneratedCode: true,
4557
- ...(panelCommit ? { lastCommitId: panelCommit } : {}),
4558
- generateCodeStatus: `Code generation completed!${commitShort ? ` Commit: ${commitShort}` : ''} Preview ready.`,
4559
- });
4579
+ markGenerationPreviewReady(panelWidgetId);
4560
4580
  }
4561
4581
  if (event.detail.step === 'create') {
4562
4582
  let psCreate = getPanelDisplayState(panelWidgetId);
@@ -4801,12 +4821,20 @@
4801
4821
  compositionDirty = true;
4802
4822
  if (widgetId === focusedPanelWidgetId) {
4803
4823
  syncFocusedPanelEditorSnapshot();
4804
- // Design edits are committed as soon as they are made, so the next codegen
4805
- // turn already sees the updated values.
4824
+ scheduleDesignPersist(widgetId);
4825
+ }
4826
+ }
4827
+
4828
+ let designPersistTimer: ReturnType<typeof setTimeout> | null = null;
4829
+ /** The preview updates on each key. The composition save waits until typing pauses, so a slow save cannot put the old color back. */
4830
+ function scheduleDesignPersist(widgetId: string): void {
4831
+ if (designPersistTimer) clearTimeout(designPersistTimer);
4832
+ designPersistTimer = setTimeout(() => {
4833
+ designPersistTimer = null;
4806
4834
  if (selectedComposition && selectedWidgetId === widgetId) {
4807
4835
  void updateCompositionValues();
4808
4836
  }
4809
- }
4837
+ }, 400);
4810
4838
  }
4811
4839
 
4812
4840
  /**
@@ -6701,18 +6729,6 @@
6701
6729
  if (panelHadPublishedVersion) patchPanelSnapshot(widgetId, { pendingPublishAfterCodegen: true });
6702
6730
  panelDisplayRevision += 1;
6703
6731
 
6704
- if (announce) {
6705
- const isFocusedPanel = widgetId === focusedPanelWidgetId;
6706
- const completedWidgetName = getWidgetById(widgetId)?.name || 'widget';
6707
- showToast(
6708
- 'success',
6709
- isFocusedPanel ? $t('creator.codegen.codeGenerationCompleted') : $t('creator.codegen.generationCompleted', { name: completedWidgetName }),
6710
- {
6711
- description: isFocusedPanel ? $t('creator.codegen.codeSavedToGitlabAnd') : $t('creator.general.switchToThatPanelTo'),
6712
- duration: 5000
6713
- }
6714
- );
6715
- }
6716
6732
  setTimeout(() => {
6717
6733
  void refreshWidgetAfterRemoteGeneration(widgetId);
6718
6734
  }, 800);
@@ -6746,7 +6762,8 @@
6746
6762
  shapePreviewSourceByWidgetId = { ...shapePreviewSourceByWidgetId, [widgetId]: 'preview' };
6747
6763
  syncWidgetShapeLivePreviews();
6748
6764
  widgetShapeLivePreviewsRef?.requestReload?.(widgetId);
6749
- patchCodegenUiState(widgetId, { generateCodeStatus: 'Code generation completed! Preview ready.' });
6765
+ patchCodegenUiState(widgetId, { generateCodeStatus: PREVIEW_READY_STATUS });
6766
+ markGenerationPreviewReady(widgetId);
6750
6767
  void refreshTrialCounter();
6751
6768
  setTimeout(async () => {
6752
6769
  try {
@@ -10688,6 +10705,12 @@ Requirements:
10688
10705
  cancelQuietScreenshots();
10689
10706
  cancelIdleThumbnailPersist();
10690
10707
  widgetShapeLivePreviewsRef?.cancelReloads?.();
10708
+ if (options.fromChat) {
10709
+ console.log('[Chat→Preview] Reloading preview iframe on send', generationWidgetId.substring(0, 8));
10710
+ widgetShapeLivePreviewsRef?.requestReload?.(generationWidgetId, { immediate: true });
10711
+ void getWidgetDetailsRef(generationWidgetId)?.refreshPreview?.();
10712
+ }
10713
+ holdPublishForGeneration(generationWidgetId);
10691
10714
  if (restoredViewingVersionByWidgetId[generationWidgetId] != null) {
10692
10715
  const { [generationWidgetId]: _droppedRestore, ...restRestored } = restoredViewingVersionByWidgetId;
10693
10716
  restoredViewingVersionByWidgetId = restRestored;
@@ -10967,6 +10990,57 @@ Requirements:
10967
10990
  // a generation slot. Anything unexpected here falls through to the
10968
10991
  // normal path (operation tracking), never blocks a real build.
10969
10992
  const gatedData = (response as any)?.data;
10993
+ if (gatedData?.gated === true && gatedData.action === 'property_edit') {
10994
+ const propertyKey = typeof gatedData.key === 'string' ? gatedData.key : '';
10995
+ const propertyValue = gatedData.value;
10996
+ clearActiveOperationId(generationWidgetId);
10997
+ if (propertyKey && gatedData.group !== 'content') {
10998
+ applyDesignValuesToPreview(generationWidgetId, { [propertyKey]: propertyValue });
10999
+ }
11000
+ const psNow = getPanelDisplayState(generationWidgetId);
11001
+ const schemaProp = collectDesignProperties(psNow.compositionDesignSchema).find(
11002
+ (property) => property.id === propertyKey || property.id.endsWith(`.${propertyKey}`)
11003
+ );
11004
+ const label = schemaProp?.label || propertyKey;
11005
+ const card: DesignControlRequest = {
11006
+ summary: gatedData.reply || `Set ${label} to ${String(propertyValue)}.`,
11007
+ properties: propertyKey
11008
+ ? [{
11009
+ id: schemaProp?.id || propertyKey,
11010
+ label,
11011
+ controllerType: schemaProp?.controllerType ?? '',
11012
+ value: propertyValue,
11013
+ options: schemaProp?.options,
11014
+ min: schemaProp?.min,
11015
+ max: schemaProp?.max,
11016
+ step: schemaProp?.step,
11017
+ helpText: schemaProp?.helpText,
11018
+ }]
11019
+ : [],
11020
+ compositionId: psNow.selectedComposition?.id ?? gatedData.compositionId ?? null,
11021
+ };
11022
+ getChatMethodsForWidget(generationWidgetId)?.addDesignControlsMessage?.(card.summary, card);
11023
+ patchCodegenUiState(generationWidgetId, {
11024
+ lastGenerationFailed: false,
11025
+ lastGenerationError: null,
11026
+ generateCodeStatus: 'Ready',
11027
+ });
11028
+ if (debugMode) {
11029
+ showToast('info', $t('creator.codegen.noGenerationStarted'), {
11030
+ description: String(gatedData.reply || '').slice(0, 140),
11031
+ duration: 8000,
11032
+ });
11033
+ }
11034
+ generatingWidgetIds = (() => {
11035
+ const { [generationWidgetId]: _gated, ...rest } = generatingWidgetIds;
11036
+ return rest;
11037
+ })();
11038
+ isGeneratingCode = !!(focusedPanelWidgetId && generatingWidgetIds[focusedPanelWidgetId]);
11039
+ setCrossTabGenerating(false, generationWidgetId);
11040
+ widgetAbortControllers.delete(generationWidgetId);
11041
+ console.log('[DesignIntent] Applied a property edit without generating', propertyKey);
11042
+ return;
11043
+ }
10970
11044
  if (gatedData?.gated === true && typeof gatedData.action === 'string' && gatedData.action !== 'generate') {
10971
11045
  const gatedAction = gatedData.action as 'answer' | 'redirect' | 'clarify';
10972
11046
  const gatedReply: string = gatedData.reply ?? '';
@@ -10993,14 +11067,16 @@ Requirements:
10993
11067
  chatMethods.addAssistantMessage(gatedReply);
10994
11068
  }
10995
11069
 
10996
- showToast(
10997
- gatedAction === 'answer' ? 'info' : 'warning',
10998
- gatedAction === 'answer' ? $t('creator.codegen.answeredWithoutGenerating') : $t('creator.codegen.noGenerationStarted'),
10999
- {
11000
- description: gatedReply.slice(0, 140),
11001
- duration: 8000,
11002
- },
11003
- );
11070
+ if (debugMode) {
11071
+ showToast(
11072
+ gatedAction === 'answer' ? 'info' : 'warning',
11073
+ gatedAction === 'answer' ? $t('creator.codegen.answeredWithoutGenerating') : $t('creator.codegen.noGenerationStarted'),
11074
+ {
11075
+ description: gatedReply.slice(0, 140),
11076
+ duration: 8000,
11077
+ },
11078
+ );
11079
+ }
11004
11080
  generatingWidgetIds = (() => {
11005
11081
  const { [generationWidgetId]: _gated, ...rest } = generatingWidgetIds;
11006
11082
  return rest;
@@ -11113,7 +11189,7 @@ Requirements:
11113
11189
  ...previewUnblockedByWidgetId,
11114
11190
  [generationWidgetId]: true,
11115
11191
  };
11116
- panelChat?.updateLatestCodegenStatusMessage?.('Preview ready');
11192
+ markGenerationPreviewReady(generationWidgetId);
11117
11193
  options.onPreviewVisible?.();
11118
11194
  }
11119
11195
  }
@@ -11377,11 +11453,18 @@ Requirements:
11377
11453
  const commitShort = completedCommitSha ? completedCommitSha.substring(0, 7) : '';
11378
11454
  const unsavedText = repositorySaveError
11379
11455
  || 'Code was not saved to the repository. Retry saves it and records a version.';
11456
+ const previewAlreadyOnCanvas = !!(
11457
+ previewReadyAnnouncedByWidgetId[generationWidgetId]
11458
+ || previewUnblockedByWidgetId[generationWidgetId]
11459
+ || runningWorkerPreviewUrlByWidgetId[generationWidgetId]
11460
+ );
11380
11461
  const savedStatus = !completedCommitSha
11381
11462
  ? unsavedText
11382
- : completedPreviewBuildErr
11383
- ? `Code saved (${commitShort}) — building preview…`
11384
- : `Code saved (${commitShort}) — loading preview…`;
11463
+ : previewAlreadyOnCanvas
11464
+ ? PREVIEW_READY_STATUS
11465
+ : completedPreviewBuildErr
11466
+ ? `Code saved (${commitShort}) — building preview…`
11467
+ : `Code saved (${commitShort}) — loading preview…`;
11385
11468
  const shownFailure = [completedPreviewBuildErr, !completedCommitSha ? unsavedText : null]
11386
11469
  .filter((part): part is string => !!part)
11387
11470
  .join('\n');
@@ -11392,6 +11475,9 @@ Requirements:
11392
11475
  lastGenerationError: shownFailure || null,
11393
11476
  generateCodeStatus: savedStatus,
11394
11477
  });
11478
+ if (previewAlreadyOnCanvas && completedCommitSha && !completedPreviewBuildErr) {
11479
+ markGenerationPreviewReady(generationWidgetId);
11480
+ }
11395
11481
 
11396
11482
  if (!completedCached) {
11397
11483
  panelChat?.updateLatestCodegenStatusMessage?.(savedStatus);
@@ -11415,7 +11501,7 @@ Requirements:
11415
11501
  description: repositorySaveError || $t('creator.codegen.retrySavesItAndRecordsAVersion'),
11416
11502
  duration: 8000
11417
11503
  });
11418
- } else {
11504
+ } else if (debugMode) {
11419
11505
  showToast(
11420
11506
  'success',
11421
11507
  isFocusedPanel ? $t('creator.codegen.codeGenerationCompleted') : $t('creator.codegen.generationCompleted', { name: completedWidgetName }),
@@ -11461,7 +11547,7 @@ Requirements:
11461
11547
  // Served from the operation metadata; the server also embeds it in the
11462
11548
  // persisted reply, so it survives a reload.
11463
11549
  const designContractWarning = getOperationDesignContractWarning(op.metadata);
11464
- if (designContractWarning) {
11550
+ if (designContractWarning && debugMode) {
11465
11551
  panelChat?.addAssistantMessage(designContractWarning, true);
11466
11552
  }
11467
11553
 
@@ -11499,10 +11585,10 @@ Requirements:
11499
11585
  // cache-busts the same URL and looks like an extra reload.
11500
11586
  // console.log('[CreatorApp] Skipping extra preview remount — Worker iframe already showing');
11501
11587
  activePanelRef?.setPreviewLoadingState(false);
11502
- // previewReady may not re-fire when we skip remount — clear stuck status.
11503
- patchCodegenUiState(generationWidgetId, {
11504
- generateCodeStatus: `Code generation completed!${commitShort ? ` Commit: ${commitShort}` : ''} Preview ready.`,
11505
- });
11588
+ // The running preview already wrote the status. Don't write "Preview ready" again.
11589
+ if (!previewReadyAnnouncedByWidgetId[generationWidgetId]) {
11590
+ markGenerationPreviewReady(generationWidgetId);
11591
+ }
11506
11592
  } else {
11507
11593
  activePanelRef?.setPreviewLoadingState(true);
11508
11594
  await activePanelRef?.refreshPreview?.({ withRetry: true, skipIfAlreadyShowing: true });
@@ -11530,12 +11616,9 @@ Requirements:
11530
11616
  } else if (!completedPreviewBuildErr) {
11531
11617
  await applyDesignSchemaDefaultsToPreview(generationWidgetId);
11532
11618
  pendingCreatePreviewDefaultsWidgetId = null;
11533
- panelChat?.updateLatestCodegenStatusMessage?.(
11534
- `Code generation completed!${commitShort ? ` Commit: ${commitShort}` : ''}\nPreview ready.`,
11535
- );
11536
- patchCodegenUiState(generationWidgetId, {
11537
- generateCodeStatus: `Code generation completed!${commitShort ? ` Commit: ${commitShort}` : ''} Preview ready.`,
11538
- });
11619
+ if (!previewReadyAnnouncedByWidgetId[generationWidgetId]) {
11620
+ markGenerationPreviewReady(generationWidgetId);
11621
+ }
11539
11622
  void refreshTrialCounter();
11540
11623
  setTimeout(async () => {
11541
11624
  await panelChat?.reloadConversationMessages?.();
@@ -11690,11 +11773,13 @@ Requirements:
11690
11773
  // Update global flag: true only if the CURRENT widget is still generating
11691
11774
  isGeneratingCode = !!(focusedPanelWidgetId && generatingWidgetIds[focusedPanelWidgetId]);
11692
11775
  setCrossTabGenerating(false, generationWidgetId);
11693
- // The reload requested while generation was still on was deferred and kept the previous iframe.
11694
- // Wait until that flag has reached the shape, then load the new document immediately.
11695
- void tick().then(() => {
11696
- widgetShapeLivePreviewsRef?.requestReload?.(generationWidgetId, { immediate: true });
11697
- });
11776
+ // A finished run already loads the new preview. Reloading here as well
11777
+ // flashed the shape a second time. A failed run still needs the one reload.
11778
+ if (getPanelState(generationWidgetId).lastGenerationFailed) {
11779
+ void tick().then(() => {
11780
+ widgetShapeLivePreviewsRef?.requestReload?.(generationWidgetId, { immediate: true });
11781
+ });
11782
+ }
11698
11783
  }
11699
11784
  }
11700
11785
  }
@@ -12369,6 +12454,18 @@ Requirements:
12369
12454
  return () => window.removeEventListener('keydown', handleEscapeCapture, { capture: true });
12370
12455
  });
12371
12456
 
12457
+ onMount(() => {
12458
+ const closeSelectorOnSelectTool = () => {
12459
+ const next: Record<string, boolean> = {};
12460
+ for (const widgetId of Object.keys(selectorEnabledByWidgetId)) next[widgetId] = false;
12461
+ selectorEnabledByWidgetId = next;
12462
+ panelDisplayRevision += 1;
12463
+ console.log('[WidgetShape] Select tool closes the element selector');
12464
+ };
12465
+ window.addEventListener('widgetic:canvas-select-tool', closeSelectorOnSelectTool);
12466
+ return () => window.removeEventListener('widgetic:canvas-select-tool', closeSelectorOnSelectTool);
12467
+ });
12468
+
12372
12469
  // Capture-phase paste: redirect clipboard images to prompt images
12373
12470
  // ONLY when the paste target is inside the widget-details panel or widgets-list
12374
12471
  // (e.g., user is focused on the prompt input). If target is body/document/canvas area,
@@ -12546,9 +12643,10 @@ Requirements:
12546
12643
  /** The canvas iframe painted, so the chat is no longer waiting on a hidden side preview. */
12547
12644
  function noteShapePreviewShown(widgetId: string): void {
12548
12645
  const status = getPanelDisplayState(widgetId).generateCodeStatus || '';
12549
- if (!status.includes('loading preview')) return;
12550
- patchCodegenUiState(widgetId, { generateCodeStatus: 'Preview ready' });
12551
- getChatMethodsForWidget(widgetId)?.updateLatestCodegenStatusMessage?.('Preview ready');
12646
+ const waitingOnPreview = /loading preview|building preview|generating code|code generation in progress|code saved/i.test(status);
12647
+ const generationRunning = !!generatingWidgetIds[widgetId] || !!previewUnblockedByWidgetId[widgetId];
12648
+ if (!waitingOnPreview && !generationRunning) return;
12649
+ markGenerationPreviewReady(widgetId);
12552
12650
  }
12553
12651
 
12554
12652
  function getOperationPreviewBuildError(metadata?: Record<string, unknown>): string | null {
@@ -12644,10 +12742,79 @@ Requirements:
12644
12742
  return typeof raw === 'string' ? raw.slice(-1600) : '';
12645
12743
  }
12646
12744
 
12745
+ function holdPublishForGeneration(widgetId: string): void {
12746
+ const pending = publishRevealTimers.get(widgetId);
12747
+ if (pending) {
12748
+ clearTimeout(pending);
12749
+ publishRevealTimers.delete(widgetId);
12750
+ }
12751
+ publishHeldByWidgetId = { ...publishHeldByWidgetId, [widgetId]: true };
12752
+ if (previewReadyAnnouncedByWidgetId[widgetId]) {
12753
+ const next = { ...previewReadyAnnouncedByWidgetId };
12754
+ delete next[widgetId];
12755
+ previewReadyAnnouncedByWidgetId = next;
12756
+ }
12757
+ }
12758
+
12759
+ function releasePublishHold(widgetId: string): void {
12760
+ const pending = publishRevealTimers.get(widgetId);
12761
+ if (pending) {
12762
+ clearTimeout(pending);
12763
+ publishRevealTimers.delete(widgetId);
12764
+ }
12765
+ if (!publishHeldByWidgetId[widgetId]) return;
12766
+ const next = { ...publishHeldByWidgetId };
12767
+ delete next[widgetId];
12768
+ publishHeldByWidgetId = next;
12769
+ panelDisplayRevision += 1;
12770
+ }
12771
+
12772
+ function schedulePublishReveal(widgetId: string): void {
12773
+ const pending = publishRevealTimers.get(widgetId);
12774
+ if (pending) clearTimeout(pending);
12775
+ publishRevealTimers.set(widgetId, setTimeout(() => {
12776
+ publishRevealTimers.delete(widgetId);
12777
+ releasePublishHold(widgetId);
12778
+ console.log('[CodeGen] Publish revealed after preview', widgetId.substring(0, 8));
12779
+ }, PUBLISH_REVEAL_DELAY_MS));
12780
+ }
12781
+
12782
+ function cancelPendingCodegenStatus(widgetId: string): void {
12783
+ if (codegenStatusTimers[widgetId]) {
12784
+ clearTimeout(codegenStatusTimers[widgetId]);
12785
+ delete codegenStatusTimers[widgetId];
12786
+ }
12787
+ delete codegenStatusPendingLine[widgetId];
12788
+ delete codegenStreamPending[widgetId];
12789
+ if (codegenChatStatusTimers[widgetId]) {
12790
+ clearTimeout(codegenChatStatusTimers[widgetId]);
12791
+ delete codegenChatStatusTimers[widgetId];
12792
+ }
12793
+ delete codegenChatStatusPendingLine[widgetId];
12794
+ }
12795
+
12796
+ /** Preview is on screen. Status settles once. Publish waits about five seconds. GitLab keeps saving. */
12797
+ function markGenerationPreviewReady(widgetId: string): void {
12798
+ const alreadyAnnounced = !!previewReadyAnnouncedByWidgetId[widgetId];
12799
+ if (!alreadyAnnounced) {
12800
+ previewReadyAnnouncedByWidgetId = { ...previewReadyAnnouncedByWidgetId, [widgetId]: true };
12801
+ cancelPendingCodegenStatus(widgetId);
12802
+ schedulePublishReveal(widgetId);
12803
+ console.log('[CodeGen] Preview ready', widgetId.substring(0, 8));
12804
+ }
12805
+ const current = getPanelState(widgetId).generateCodeStatus || '';
12806
+ if (current === PREVIEW_READY_STATUS) return;
12807
+ patchCodegenUiState(widgetId, { generateCodeStatus: PREVIEW_READY_STATUS });
12808
+ if (!alreadyAnnounced) {
12809
+ getChatMethodsForWidget(widgetId)?.updateLatestCodegenStatusMessage?.(PREVIEW_READY_STATUS);
12810
+ }
12811
+ }
12812
+
12647
12813
  function pushCodegenProgressToUi(op: OperationStatus, widgetId: string | null | undefined) {
12648
12814
  // The preview is already on the canvas while the version is still saving.
12649
12815
  // The bar stays at 70 until that save ends, so show 100 for that pause.
12650
12816
  const stillRunning = String(op.status || '').toLowerCase() === 'running';
12817
+ if (widgetId && previewReadyAnnouncedByWidgetId[widgetId] && stillRunning) return;
12651
12818
  const versionStillSaving = !!(widgetId && previewUnblockedByWidgetId[widgetId] && stillRunning);
12652
12819
  const shown = versionStillSaving ? { ...op, progress: 100 } : op;
12653
12820
  const line = formatCodegenProgressStatus(shown);
@@ -12695,7 +12862,7 @@ Requirements:
12695
12862
  const pendingTail = codegenStreamPending[widgetId];
12696
12863
  delete codegenStatusPendingLine[widgetId];
12697
12864
  delete codegenStreamPending[widgetId];
12698
- if (pending) patchCodegenUiState(widgetId, { generateCodeStatus: pending });
12865
+ if (pending && !previewReadyAnnouncedByWidgetId[widgetId]) patchCodegenUiState(widgetId, { generateCodeStatus: pending });
12699
12866
  if (pendingTail && pendingTail !== generationStreamByWidgetId[widgetId]) {
12700
12867
  generationStreamByWidgetId = { ...generationStreamByWidgetId, [widgetId]: pendingTail };
12701
12868
  }
@@ -12714,7 +12881,9 @@ Requirements:
12714
12881
  delete codegenChatStatusTimers[key];
12715
12882
  const pending = codegenChatStatusPendingLine[key];
12716
12883
  delete codegenChatStatusPendingLine[key];
12717
- if (pending) getChatMethodsForWidget(widgetId)?.updateLatestCodegenStatusMessage?.(pending);
12884
+ if (pending && !(widgetId && previewReadyAnnouncedByWidgetId[widgetId])) {
12885
+ getChatMethodsForWidget(widgetId)?.updateLatestCodegenStatusMessage?.(pending);
12886
+ }
12718
12887
  }, CODEGEN_STATUS_THROTTLE_MS);
12719
12888
  }
12720
12889
 
@@ -12750,12 +12919,24 @@ Requirements:
12750
12919
  // that rebuild ran on the same turn the generation finished.
12751
12920
  if (statusOnly) {
12752
12921
  const snap = widgetPanelSnapshots[widgetId];
12922
+ // The failure notice the panel shows right now, read before the patch lands: the focused panel is drawn from the
12923
+ // globals, the others from their snapshot.
12924
+ const failureNoticeShown = widgetId === focusedPanelWidgetId ? { lastGenerationFailed, lastGenerationError } : snap;
12925
+ const failureNoticeChanged = failureNoticeChanges(failureNoticeShown, nextPatch);
12753
12926
  if (snap) Object.assign(snap, nextPatch);
12754
12927
  if (widgetId === focusedPanelWidgetId) {
12755
12928
  if (nextPatch.generateCodeStatus !== undefined) generateCodeStatus = nextPatch.generateCodeStatus;
12756
12929
  if (nextPatch.lastGenerationFailed !== undefined) lastGenerationFailed = nextPatch.lastGenerationFailed;
12757
12930
  if (nextPatch.lastGenerationError !== undefined) lastGenerationError = nextPatch.lastGenerationError;
12758
12931
  }
12932
+ // A progress line stays free, but the failure notice is drawn from the display state that only a new revision reads
12933
+ // again. Without this bump a generation that failed or that the gateway refused left the status line on "Status: ..."
12934
+ // with no "Generation Failed", and the note with its message and Retry never came up (the Dismiss button of that note
12935
+ // moves the revision by hand for the same reason).
12936
+ if (failureNoticeChanged) {
12937
+ panelDisplayRevision += 1;
12938
+ if (debugMode) console.debug('[FailureNotice] The failure notice of a panel changed; its status area is drawn again', { widgetId, failed: nextPatch.lastGenerationFailed ?? null });
12939
+ }
12759
12940
  return;
12760
12941
  }
12761
12942
  patchPanelSnapshot(widgetId, nextPatch);
@@ -14182,6 +14363,8 @@ Requirements:
14182
14363
  }
14183
14364
 
14184
14365
  function patchPanelSnapshot(widgetId: string, patch: Partial<WidgetPanelSnapshot>): void {
14366
+ // The failure notice the panel shows before the patch lands (a status-only patch below decides on it).
14367
+ const failureNoticeChanged = failureNoticeChanges(getPanelState(widgetId), patch);
14185
14368
  widgetPanelSnapshots = {
14186
14369
  ...widgetPanelSnapshots,
14187
14370
  [widgetId]: { ...getPanelState(widgetId), ...patch },
@@ -14192,7 +14375,11 @@ Requirements:
14192
14375
  const statusOnly = patchKeys.length > 0 && patchKeys.every((key) =>
14193
14376
  key === 'generateCodeStatus' || key === 'lastGenerationFailed' || key === 'lastGenerationError'
14194
14377
  );
14195
- if (statusOnly) return;
14378
+ if (statusOnly) {
14379
+ // A patch that raises or clears the failure notice moves the revision all the same (see patchCodegenUiState).
14380
+ if (failureNoticeChanged) panelDisplayRevision++;
14381
+ return;
14382
+ }
14196
14383
  if (patch.publishHistoryResolved) {
14197
14384
  if (widgetId === focusedPanelWidgetId) {
14198
14385
  if (patch.publishHistory) publishHistory = [...patch.publishHistory];
@@ -15050,6 +15237,10 @@ Requirements:
15050
15237
  }
15051
15238
 
15052
15239
  function hasUnpublishedChangesForPanel(widgetId: string): boolean {
15240
+ if (publishHeldByWidgetId[widgetId]) return false;
15241
+ if (generatingWidgetIds[widgetId] && !previewReadyAnnouncedByWidgetId[widgetId]) return false;
15242
+ // Preview is up and the five seconds have passed. GitLab may still be saving.
15243
+ if (generatingWidgetIds[widgetId] && previewReadyAnnouncedByWidgetId[widgetId]) return true;
15053
15244
  const ps = getPanelDisplayState(widgetId);
15054
15245
  if (ps.pendingPublishAfterCodegen) return true;
15055
15246
 
@@ -15184,7 +15375,12 @@ Requirements:
15184
15375
  showDisabledHint: true,
15185
15376
  };
15186
15377
  }
15187
- if (generatingWidgetIds[widgetId]) {
15378
+ const gitlabSaveStillRunning = !!(
15379
+ generatingWidgetIds[widgetId]
15380
+ && previewReadyAnnouncedByWidgetId[widgetId]
15381
+ && !publishHeldByWidgetId[widgetId]
15382
+ );
15383
+ if (generatingWidgetIds[widgetId] && !gitlabSaveStillRunning) {
15188
15384
  return {
15189
15385
  disabled: true,
15190
15386
  label: getPublishButtonLabelFallback(ps),
@@ -15464,15 +15660,23 @@ $: if ($widgetPublishStatus.timestamp && $widgetPublishStatus.widgetId) {
15464
15660
  // console.log('[Publish] WS success — refreshing preview after publish for', publishWidgetId.substring(0, 8));
15465
15661
  void getWidgetDetailsRef(publishWidgetId)?.refreshPreview({ withRetry: true });
15466
15662
  }
15467
- if (publishWidgetId) {
15468
- // console.log('[Publish] Refreshing canvas widget screenshot after successful publish');
15469
- scheduleQuietScreenshot(publishWidgetId, 2000);
15470
- }
15471
15663
  if (embedded && onPublishComplete && publishWidgetId) {
15472
- onPublishComplete({
15473
- widgetId: publishWidgetId,
15474
- version: publishResult.version
15475
- });
15664
+ const publishedWidgetId = publishWidgetId;
15665
+ const publishedVersion = publishResult.version;
15666
+ void (async () => {
15667
+ await Promise.race([
15668
+ handleRefreshScreenshot(publishedWidgetId, { quiet: true }).catch((error) => {
15669
+ console.warn('[Publish] Thumbnail before leaving the canvas failed', error);
15670
+ }),
15671
+ new Promise((resolve) => setTimeout(resolve, 2500)),
15672
+ ]);
15673
+ onPublishComplete({
15674
+ widgetId: publishedWidgetId,
15675
+ version: publishedVersion
15676
+ });
15677
+ })();
15678
+ } else if (publishWidgetId) {
15679
+ scheduleQuietScreenshot(publishWidgetId, 2000);
15476
15680
  }
15477
15681
  } else if (publishResult.status === 'failure') {
15478
15682
  if (isFocusedPublish) {
@@ -15641,6 +15845,30 @@ async function readPublishHistoryForPanel(widgetId: string, opts: { silent?: boo
15641
15845
  // must stop `ensureShapePublishHistory` from re-fetching on every render.
15642
15846
  shapeHistoryResolvedByWidgetId = { ...shapeHistoryResolvedByWidgetId, [widgetId]: true };
15643
15847
  queueUnpublishedHeadOnShape(widgetId);
15848
+ const publishedVersions = history
15849
+ .filter((row) => row.publishedAt ?? row.published_at)
15850
+ .map((row) => Number(row.version))
15851
+ .filter((version) => Number.isFinite(version));
15852
+ const liveFromHistory = publishedVersions.length > 0 ? Math.max(...publishedVersions) : null;
15853
+ const draftVersions = history
15854
+ .filter((row) => !(row.publishedAt ?? row.published_at))
15855
+ .map((row) => Number(row.version))
15856
+ .filter((version) => Number.isFinite(version));
15857
+ const newestDraft = draftVersions.length > 0 ? Math.max(...draftVersions) : null;
15858
+ const knownLive = getPanelState(widgetId).lastPublishedVersion ?? liveFromHistory;
15859
+ const draftAhead = newestDraft != null && knownLive != null && newestDraft > knownLive;
15860
+ if ((getPanelState(widgetId).lastPublishedVersion == null && liveFromHistory != null) || draftAhead) {
15861
+ patchPanelSnapshot(widgetId, {
15862
+ ...(getPanelState(widgetId).lastPublishedVersion == null && liveFromHistory != null
15863
+ ? { lastPublishedVersion: liveFromHistory }
15864
+ : {}),
15865
+ ...(draftAhead ? { pendingPublishAfterCodegen: true, hasGeneratedCode: true } : {}),
15866
+ });
15867
+ if (widgetId === focusedPanelWidgetId && getPanelState(widgetId).lastPublishedVersion != null) {
15868
+ lastPublishedVersion = getPanelState(widgetId).lastPublishedVersion;
15869
+ }
15870
+ }
15871
+ void reconcileWidgetHeadCommit(widgetId);
15644
15872
  if (widgetId === focusedPanelWidgetId) {
15645
15873
  publishHistory = history;
15646
15874
  publishHistoryResolved = true;
@@ -18295,7 +18523,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18295
18523
 
18296
18524
 
18297
18525
  <!-- Widgetic Canvas Editor - Full width background (lazy-loaded) -->
18298
- <div class="wc-canvas-area flex-1 min-h-0 relative {embedded && !canvasAdvancedFeatures ? 'pe-[480px]' : ''}">
18526
+ <div class="wc-canvas-area flex-1 min-h-0 relative {embedded && !canvasAdvancedFeatures ? 'pe-[450px]' : ''}">
18299
18527
  <!-- Embedded: Debug toggle lives in site AppHeader (avoids overlapping Props Panel). -->
18300
18528
  {#if canvasApiLoadError || canvasShapesMissingWarning}
18301
18529
  <div class="canvas-state-warning-ct absolute top-3 left-1/2 -translate-x-1/2 z-30 max-w-lg w-[calc(100%-2rem)] pointer-events-auto">
@@ -18435,7 +18663,17 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18435
18663
  resolveSelectedElements={(widgetId) => selectedElementsByWidgetId[widgetId] ?? []}
18436
18664
  onSelectWidgetElement={(widgetId, element) => handleSelectWidgetElement(widgetId, element)}
18437
18665
  onRemoveWidgetElement={(widgetId, elementId) => handleRemoveWidgetElement(widgetId, elementId)}
18438
- onCloseWidgetSelector={(widgetId) => handleToggleWidgetSelector(widgetId, false)}
18666
+ onCloseWidgetSelector={(widgetId) => {
18667
+ handleToggleWidgetSelector(widgetId, false);
18668
+ canvasRef?.setWidgetShapeBodyDragAllowed?.(widgetId, false);
18669
+ }}
18670
+ onCommandClickPreview={(widgetId) => {
18671
+ const next = !selectorEnabledByWidgetId[widgetId];
18672
+ canvasRef?.selectWidgetShapeById?.(widgetId);
18673
+ canvasSelectedWidgetShapeId = widgetId;
18674
+ handleToggleWidgetSelector(widgetId, next);
18675
+ console.log('[WidgetShape] Alt click toggles the selector', widgetId.substring(0, 8), next);
18676
+ }}
18439
18677
  />
18440
18678
 
18441
18679
  <!-- ═══ PANEL 2: Widgets Panel — debug + showWidgetsList (site passes false) ═══ -->
@@ -18573,7 +18811,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18573
18811
  <!-- svelte-ignore a11y-click-events-have-key-events -->
18574
18812
  <div
18575
18813
  class="widget-item widgets-list-grid-row items-center gap-x-2 border rounded px-2 py-1 text-sm {selectedWidgetId === w.id ? 'border-blue-500 bg-blue-50 cursor-default' : 'border-gray-200 cursor-pointer hover:bg-blue-50'}"
18576
- tabindex="0"
18814
+ tabindex="-1"
18577
18815
  role="button"
18578
18816
  onclick={() => {
18579
18817
  if (renamingWidgetId === w.id) return;
@@ -18830,12 +19068,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18830
19068
  if (!previewWidgetId) return;
18831
19069
  // Clear the "…loading preview…" / "…building preview…" status once the iframe reports ready.
18832
19070
  const panelStatus = getPanelState(previewWidgetId).generateCodeStatus || '';
18833
- if (/loading preview|building preview|preview rebuilt from saved code/i.test(panelStatus)) {
18834
- const panelCommit = getPanelState(previewWidgetId).lastCommitId;
18835
- const commitShort = panelCommit ? panelCommit.substring(0, 7) : '';
18836
- patchCodegenUiState(previewWidgetId, {
18837
- generateCodeStatus: `Code generation completed!${commitShort ? ` Commit: ${commitShort}` : ''} Preview ready.`,
18838
- });
19071
+ if (/loading preview|building preview|preview rebuilt from saved code|generating code/i.test(panelStatus)) {
19072
+ markGenerationPreviewReady(previewWidgetId);
18839
19073
  }
18840
19074
  if (isPanelFocused && previewWidgetId === panelWidgetId) {
18841
19075
  chatMethods?.clearStalePreviewBuildFailures?.();
@@ -19167,7 +19401,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19167
19401
  {/if}
19168
19402
  {/if}
19169
19403
  {#if isHistoryOpen && isPanelFocused}
19170
- <Portal target="wc-live-history-portal-{panelWidgetId}">
19404
+ <Portal target="wc-live-history-portal-{panelWidgetId}" style="z-index: 100000010; width: auto; height: auto; overflow: visible;">
19171
19405
  <button
19172
19406
  type="button"
19173
19407
  class="wc-live-history-backdrop fixed start-0 end-0 bottom-0 top-14 z-[9998] cursor-default bg-transparent"
@@ -288,6 +288,7 @@
288
288
  />
289
289
  {$t('creator.brandKit.brandKit')}
290
290
  </label>
291
+ {#if showLanguage || showPresetLibraries}
291
292
  <div class="generation-libraries-row flex w-full flex-col gap-2">
292
293
  <div class="generation-libraries-checks flex flex-nowrap items-center gap-1">
293
294
  {#if showLanguage}
@@ -387,6 +388,7 @@
387
388
  {/each}
388
389
  {/if}
389
390
  </div>
391
+ {/if}
390
392
  </div>
391
393
  {#if brandPanelOpen}
392
394
  <Portal