@widgetic/creator 0.4.18 → 0.4.20

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.
@@ -429,6 +429,7 @@
429
429
  const CREATOR_WIREFRAME_CHANGED_EVENT = 'widgetic:creator-wireframe-changed';
430
430
  const CREATOR_ADVANCED_CHANGED_EVENT = 'widgetic:creator-advanced-changed';
431
431
  const CREATOR_CANVAS_WIDGETS_EVENT = 'widgetic:creator-canvas-widgets';
432
+ const CREATOR_PUBLISH_STATE_EVENT = 'widgetic:creator-publish-state';
432
433
 
433
434
  /** Site AppHeader rename — embed is a second Svelte runtime, so mount props do not update. */
434
435
  async function applyHostWidgetName(widgetId: string | null | undefined, newName: string): Promise<void> {
@@ -470,6 +471,22 @@
470
471
  void applyHostWidgetName(detail.widgetId, detail.name);
471
472
  }
472
473
 
474
+ let lastAnnouncedPublishState = '';
475
+ $: if (embedded && typeof window !== 'undefined') {
476
+ const targetId = (focusedPanelWidgetId && !isDraftConvertId(focusedPanelWidgetId))
477
+ ? focusedPanelWidgetId
478
+ : ((canvasPrimaryWidgetId || '').trim());
479
+ const generatingMark = targetId ? !!generatingWidgetIds[targetId] : false;
480
+ const gate = targetId ? getPublishGateForPanel(targetId) : null;
481
+ const canPublish = !!gate && !gate.disabled;
482
+ const label = gate?.label || 'Publish';
483
+ const signature = `${targetId}:${canPublish}:${label}:${panelDisplayRevision}:${isPublishing}:${generatingMark}`;
484
+ if (signature !== lastAnnouncedPublishState) {
485
+ lastAnnouncedPublishState = signature;
486
+ announceToSite(CREATOR_PUBLISH_STATE_EVENT, { canPublish, label });
487
+ }
488
+ }
489
+
473
490
  function handleHostRequestPublishEvent(): void {
474
491
  const targetId = focusedPanelWidgetId || selectedWidgetId;
475
492
  if (!targetId) {
@@ -1308,6 +1325,12 @@
1308
1325
  let codeGenerationPrompt = DEFAULT_PROMPT;
1309
1326
  let isGeneratingCode = false;
1310
1327
  let generatingWidgetIds: Record<string, boolean> = {};
1328
+ // The worker preview is on screen, so the chat can take the next message
1329
+ // while the repository save is still finishing. The canvas shape stays
1330
+ // deferred because generatingWidgetIds is still set.
1331
+ let previewUnblockedByWidgetId: Record<string, boolean> = {};
1332
+ /** Last slice of the model stream, per widget. Painted with the status throttle, not per token. */
1333
+ let generationStreamByWidgetId: Record<string, string> = {};
1311
1334
  function isAnyWidgetGenerating(): boolean {
1312
1335
  return isGeneratingCode || Object.keys(generatingWidgetIds).some((id) => generatingWidgetIds[id]);
1313
1336
  }
@@ -1358,6 +1381,11 @@
1358
1381
  let lastGenerationFailed = false; // Track if last generation failed for retry UI
1359
1382
  let publishPlanMessageByWidgetId: Record<string, string> = {};
1360
1383
 
1384
+ function isHourlyLimitText(message: string | null | undefined): boolean {
1385
+ if (!message) return false;
1386
+ return /hourly limit reached/i.test(message);
1387
+ }
1388
+
1361
1389
  function isPlanLimitMessage(message: string | null | undefined): boolean {
1362
1390
  if (!message) return false;
1363
1391
  return /credit balance|free trial|not available in your plan|not available on the free plan|upgrade your plan|upgrade to a solo/i.test(message);
@@ -1389,10 +1417,15 @@
1389
1417
  // ─── Convert UX v2: draft panel state (no widget record until first Send) ────
1390
1418
  /** Synthetic id for the draft convert panel — NOT a widget id in the DB. */
1391
1419
  const DRAFT_CONVERT_ID_PREFIX = 'draft_convert_';
1420
+ /** One chat for the whole canvas, before the widget row exists. */
1421
+ const CANVAS_SKETCH_DRAFT_ID = 'draft_convert_canvas';
1392
1422
  /** Canvas object ids (group or selection id) captured at convert time, per draft id. */
1393
1423
  const draftConvertObjectIds = new Map<string, string>();
1394
1424
  /** Captured sketch screenshot (data URL) per draft id — reused on first Send. */
1395
1425
  const draftConvertScreenshots = new Map<string, string>();
1426
+ /** Fabric JSON of the board, kept so the first checkpoint can put the sketch back. */
1427
+ const draftConvertSketchJson = new Map<string, string>();
1428
+ const sketchSnapshotsByWidgetId = new Map<string, string>();
1396
1429
  /** True while a draft conversion is being finalized (widget creation + shape replace). */
1397
1430
  const finalizingDraftConversions = new Set<string>();
1398
1431
  /** Keep Widget Details on this convert/draft widget until the user closes the panel. */
@@ -1714,6 +1747,34 @@
1714
1747
  const widgetId = sourceWidgetId ?? selectedWidgetId;
1715
1748
  if (!widgetId) return;
1716
1749
 
1750
+ const sketchCanvas = canvasRef as (typeof canvasRef & {
1751
+ captureCanvasSketch?: () => Promise<string>;
1752
+ absorbCanvasSketchIntoWidget?: (widgetId: string, screenshotDataUrl: string) => Promise<string | null>;
1753
+ }) | null;
1754
+ if (embedded && !canvasAdvancedFeatures && sketchCanvas?.captureCanvasSketch) {
1755
+ try {
1756
+ const canvasSketch = await sketchCanvas.captureCanvasSketch();
1757
+ if (canvasSketch?.startsWith('data:image/')) {
1758
+ if (isDraftConvertId(widgetId)) {
1759
+ draftConvertScreenshots.set(widgetId, canvasSketch);
1760
+ const sketchJson = sketchCanvas.saveCanvas?.() ?? '';
1761
+ if (sketchJson) draftConvertSketchJson.set(widgetId, sketchJson);
1762
+ }
1763
+ const alreadyHasImage = (attachments || []).some((attachment) =>
1764
+ attachment.fileType?.startsWith('image/')
1765
+ );
1766
+ if (!alreadyHasImage) {
1767
+ attachments = [
1768
+ ...(attachments || []),
1769
+ { url: canvasSketch, fileType: 'image/png', fileName: 'design-screenshot.png' },
1770
+ ];
1771
+ }
1772
+ }
1773
+ } catch (captureError) {
1774
+ console.warn('[CreatorApp] Whole-canvas sketch capture failed', captureError);
1775
+ }
1776
+ }
1777
+
1717
1778
  // console.log(
1718
1779
  // '[Chat→CodeGen] User sent message for widget',
1719
1780
  // widgetId.substring(0, 8),
@@ -1884,16 +1945,29 @@
1884
1945
  }));
1885
1946
  // Chat.onSaveMessage already persisted this turn. generateCode keeps one
1886
1947
  // ensureCodegenUserMessagePersisted after imagesToSend is finalized.
1887
- await generateCode({
1888
- prompt: content,
1889
- fromChat: true,
1890
- widgetId: codegenWidgetId,
1891
- attachmentIds: cdnUploadIds.length > 0 ? cdnUploadIds : undefined,
1892
- promptImagesOverride: effectivePromptImages.length > 0 ? effectivePromptImages : undefined,
1893
- persistFileAttachments: persistFileAttachments.length > 0 ? persistFileAttachments : undefined,
1894
- skipIntentGate: sendOptions?.skipIntentGate === true,
1895
- chipIntent: sendOptions?.chipIntent,
1896
- selectedElements: selectedElementsForTurn,
1948
+ await new Promise<void>((resolve, reject) => {
1949
+ let released = false;
1950
+ const job = generateCode({
1951
+ prompt: content,
1952
+ fromChat: true,
1953
+ widgetId: codegenWidgetId,
1954
+ attachmentIds: cdnUploadIds.length > 0 ? cdnUploadIds : undefined,
1955
+ promptImagesOverride: effectivePromptImages.length > 0 ? effectivePromptImages : undefined,
1956
+ persistFileAttachments: persistFileAttachments.length > 0 ? persistFileAttachments : undefined,
1957
+ skipIntentGate: sendOptions?.skipIntentGate === true,
1958
+ chipIntent: sendOptions?.chipIntent,
1959
+ selectedElements: selectedElementsForTurn,
1960
+ onPreviewVisible: () => {
1961
+ released = true;
1962
+ resolve();
1963
+ },
1964
+ });
1965
+ void job.then(() => {
1966
+ if (!released) resolve();
1967
+ }).catch((error) => {
1968
+ if (!released) reject(error);
1969
+ else console.warn('[CodeGen] Generation failed after the preview was shown', error);
1970
+ });
1897
1971
  });
1898
1972
  }
1899
1973
 
@@ -2667,6 +2741,7 @@
2667
2741
  * Capture via a temporary same-path Worker /preview iframe (has html2canvas handler).
2668
2742
  */
2669
2743
  async function captureViaHiddenWorkerPreview(widgetId: string): Promise<string | null> {
2744
+ if (isDraftConvertId(widgetId)) return null;
2670
2745
  // Loading a widget in a hidden iframe costs a full Svelte + Tailwind CDN
2671
2746
  // startup on the main thread this page shares with it, and the capture that
2672
2747
  // follows is refused during a generation anyway (`requestIframeScreenshot`),
@@ -2782,6 +2857,22 @@
2782
2857
  }
2783
2858
 
2784
2859
  async function performChatScreenshot(targetId: string, requiredIframe: HTMLIFrameElement | null, quiet = false): Promise<string | null> {
2860
+ // A sketch has no widget preview yet. Capture the board, not /preview/<draft id>.
2861
+ if (isDraftConvertId(targetId)) {
2862
+ const sketchCanvas = canvasRef as (typeof canvasRef & {
2863
+ captureCanvasSketch?: () => Promise<string>;
2864
+ }) | null;
2865
+ try {
2866
+ const sketch = sketchCanvas?.captureCanvasSketch
2867
+ ? await sketchCanvas.captureCanvasSketch()
2868
+ : '';
2869
+ if (sketch && sketch.length > 100) return sketch;
2870
+ } catch (sketchError) {
2871
+ console.warn('[Chat→Screenshot] Canvas sketch capture failed', sketchError);
2872
+ }
2873
+ console.warn('[Chat→Screenshot] Draft sketch capture returned nothing', targetId);
2874
+ return null;
2875
+ }
2785
2876
  const liveIframe = requiredIframe ?? resolveLiveWidgetShapeIframe(targetId);
2786
2877
  if (requiredIframe && (requiredIframe !== resolveLiveWidgetShapeIframe(targetId) || !requiredIframe.isConnected)) return null;
2787
2878
  const liveSrc = liveIframe
@@ -3377,6 +3468,49 @@
3377
3468
  const rollbackHeadSha =
3378
3469
  gitRollback.commitId ?? gitRollback.commit_id ?? targetCommit ?? null;
3379
3470
  const historicalSha = targetCommit || rollbackHeadSha;
3471
+ const targetSha = String(historicalSha || '').toLowerCase();
3472
+ const matchedVersion = panelWidgetId
3473
+ ? (resolveWidgetShapeVersionOptions(panelWidgetId) ?? []).find((option) => {
3474
+ const optionSha = String(option.commitSha ?? '').toLowerCase();
3475
+ return optionSha.length >= 7 && targetSha.length >= 7
3476
+ && (optionSha === targetSha || optionSha.startsWith(targetSha) || targetSha.startsWith(optionSha));
3477
+ })
3478
+ : undefined;
3479
+ const restoredVersion = matchedVersion?.id?.startsWith('v:')
3480
+ ? parseInt(matchedVersion.id.slice(2), 10)
3481
+ : NaN;
3482
+ // Version 1 is the board before a generation replaced the drawing.
3483
+ // Later versions put that generation's code back on the shape.
3484
+ const restoreSketch = !targetCommit || restoredVersion === 1;
3485
+ if (panelWidgetId && restoreSketch) {
3486
+ const sketchFromWidget = (getWidgetById(panelWidgetId) as { content?: { sketchCanvasJson?: string } } | null)?.content?.sketchCanvasJson;
3487
+ const sketch = sketchSnapshotsByWidgetId.get(panelWidgetId) || sketchFromWidget;
3488
+ if (sketch && canvasRef?.loadCanvas) {
3489
+ try {
3490
+ await canvasRef.loadCanvas(sketch);
3491
+ canvasRef.saveNow?.();
3492
+ syncWidgetShapeLivePreviews();
3493
+ if (rollbackHeadSha) {
3494
+ lastCommitId = rollbackHeadSha;
3495
+ saveCommitIdForWidget(panelWidgetId, rollbackHeadSha);
3496
+ patchPanelSnapshot(panelWidgetId, { lastCommitId: rollbackHeadSha });
3497
+ patchCodegenUiState(panelWidgetId, { lastCommitId: rollbackHeadSha });
3498
+ }
3499
+ if (Number.isFinite(restoredVersion)) {
3500
+ restoredViewingVersionByWidgetId = {
3501
+ ...restoredViewingVersionByWidgetId,
3502
+ [panelWidgetId]: restoredVersion,
3503
+ };
3504
+ }
3505
+ showToast('success', $t('creator.canvas.sketchRestored'), { duration: 4000 });
3506
+ return data;
3507
+ } catch (sketchError) {
3508
+ console.warn('[Restore] Sketch snapshot reload failed', sketchError);
3509
+ }
3510
+ } else {
3511
+ console.warn('[Restore] First checkpoint has no saved sketch', panelWidgetId);
3512
+ }
3513
+ }
3380
3514
  if (panelWidgetId) {
3381
3515
  if (rollbackHeadSha) {
3382
3516
  lastCommitId = rollbackHeadSha;
@@ -3384,22 +3518,12 @@
3384
3518
  patchPanelSnapshot(panelWidgetId, { lastCommitId: rollbackHeadSha });
3385
3519
  patchCodegenUiState(panelWidgetId, { lastCommitId: rollbackHeadSha });
3386
3520
  }
3387
- const targetSha = String(historicalSha || '').toLowerCase();
3388
- const matchedVersion = (resolveWidgetShapeVersionOptions(panelWidgetId) ?? [])
3389
- .find((option) => {
3390
- const optionSha = String(option.commitSha ?? '').toLowerCase();
3391
- return optionSha.length >= 7 && targetSha.length >= 7
3392
- && (optionSha === targetSha || optionSha.startsWith(targetSha) || targetSha.startsWith(optionSha));
3393
- });
3394
- if (matchedVersion?.id?.startsWith('v:')) {
3395
- const restoredVersion = parseInt(matchedVersion.id.slice(2), 10);
3396
- if (Number.isFinite(restoredVersion)) {
3397
- restoredViewingVersionByWidgetId = {
3398
- ...restoredViewingVersionByWidgetId,
3399
- [panelWidgetId]: restoredVersion,
3400
- };
3401
- widgetShapeLivePreviewsRef?.setSelectedVersion?.(panelWidgetId, `v:${restoredVersion}`);
3402
- }
3521
+ if (Number.isFinite(restoredVersion)) {
3522
+ restoredViewingVersionByWidgetId = {
3523
+ ...restoredViewingVersionByWidgetId,
3524
+ [panelWidgetId]: restoredVersion,
3525
+ };
3526
+ widgetShapeLivePreviewsRef?.setSelectedVersion?.(panelWidgetId, `v:${restoredVersion}`);
3403
3527
  }
3404
3528
  shapePreviewSourceByWidgetId = {
3405
3529
  ...shapePreviewSourceByWidgetId,
@@ -3561,6 +3685,27 @@
3561
3685
  return sha.trim().toLowerCase();
3562
3686
  }
3563
3687
 
3688
+ /** Commit of the version selected in the menu, when it is not already the repo head. */
3689
+ function generationBaseCommitSha(widgetId: string): string | null {
3690
+ const source = shapePreviewSourceByWidgetId[widgetId];
3691
+ const selectedId = dropdownVersionByWidgetId[widgetId]
3692
+ || (typeof source === 'string' && source.startsWith('v:') ? source : null);
3693
+ if (!selectedId?.startsWith('v:')) return null;
3694
+ const version = Number(selectedId.slice(2));
3695
+ if (!Number.isFinite(version)) return null;
3696
+ const record = getShapePublishHistory(widgetId).find((row) => Number(row.version) === version);
3697
+ const sha = String(record?.commitSha ?? record?.commit_sha ?? '').trim();
3698
+ if (!/^[0-9a-f]{7,40}$/i.test(sha)) return null;
3699
+ const head = getPanelDisplayState(widgetId).lastCommitId ?? loadCommitIdForWidget(widgetId);
3700
+ if (commitsMatch(head, sha)) return null;
3701
+ console.log('[CodeGen] Selected version is the code base', {
3702
+ widgetId: widgetId.substring(0, 8),
3703
+ version,
3704
+ sha: sha.slice(0, 8),
3705
+ });
3706
+ return sha;
3707
+ }
3708
+
3564
3709
  function commitsMatch(a: string | null | undefined, b: string | null | undefined): boolean {
3565
3710
  const normalizedA = normalizeCommitSha(a);
3566
3711
  const normalizedB = normalizeCommitSha(b);
@@ -4056,6 +4201,12 @@
4056
4201
  patchPanelSnapshot(widgetId, { compositionSchemasLoading: false, schemaLoadStartedAt: null });
4057
4202
  return;
4058
4203
  }
4204
+ // Edit and Embed are not on screen while Advanced is off. Their schema
4205
+ // requests wait until that step is actually opened.
4206
+ if (embedded && !canvasAdvancedFeatures) {
4207
+ patchPanelSnapshot(widgetId, { compositionSchemasLoading: false, schemaLoadStartedAt: null });
4208
+ return;
4209
+ }
4059
4210
 
4060
4211
  if (options?.force) {
4061
4212
  widgetSchemaCache.delete(widgetId);
@@ -5765,6 +5916,7 @@
5765
5916
  patchPanelSnapshot(panelId, { widgetDetailsStep: 'create' });
5766
5917
  }
5767
5918
  }
5919
+ void ensureSimpleCanvasChat();
5768
5920
  }
5769
5921
  }
5770
5922
 
@@ -5981,10 +6133,17 @@
5981
6133
  primaryWidgetId = items[0].id;
5982
6134
  }
5983
6135
  // console.log('[CreatorApp] Emit canvas widgets for header', reason, items.length, primaryWidgetId);
5984
- announceToSite(CREATOR_CANVAS_WIDGETS_EVENT, { widgets: items, primaryWidgetId: primaryWidgetId || '' });
6136
+ const listed = embedded && !canvasAdvancedFeatures && primaryWidgetId
6137
+ ? items.filter((item) => item.id === primaryWidgetId)
6138
+ : items;
6139
+ announceToSite(CREATOR_CANVAS_WIDGETS_EVENT, {
6140
+ widgets: listed.length > 0 ? listed : items,
6141
+ primaryWidgetId: primaryWidgetId || '',
6142
+ });
5985
6143
  }
5986
6144
 
5987
6145
  function handleHostRequestCanvasWidgetsEvent() {
6146
+ if (embedded && !canvasAdvancedFeatures) return;
5988
6147
  emitCanvasWidgetsList('host-request');
5989
6148
  }
5990
6149
 
@@ -6487,6 +6646,7 @@
6487
6646
  const commitTitle = getOperationCommitTitle(operation.metadata);
6488
6647
  const panelHadPublishedVersion =
6489
6648
  getPanelState(widgetId).lastPublishedVersion !== null || getPanelDisplayState(widgetId).lastPublishedVersion !== null;
6649
+ applySuggestedWidgetName(widgetId, operation.metadata as Record<string, unknown> | undefined);
6490
6650
  if (commitSha) {
6491
6651
  saveCommitIdForWidget(widgetId, commitSha);
6492
6652
  stampCodegenTitleIntoPanelHistory(widgetId, commitSha, commitTitle);
@@ -6689,6 +6849,17 @@
6689
6849
  return read;
6690
6850
  }
6691
6851
 
6852
+ /**
6853
+ * A new canvas row is written once, with no content, so its update time is its creation time. Rows without both
6854
+ * times are not judged here (the caller keeps retrying, as before).
6855
+ */
6856
+ function canvasRecordWasNeverSaved(record: Record<string, any> | null): boolean {
6857
+ const createdAt = Date.parse(record?.createdAt ?? record?.created_at ?? '');
6858
+ const updatedAt = Date.parse(record?.updatedAt ?? record?.updated_at ?? '');
6859
+ if (Number.isNaN(createdAt) || Number.isNaN(updatedAt)) return false;
6860
+ return updatedAt - createdAt < 1000;
6861
+ }
6862
+
6692
6863
  /** The site header shows the canvas name; it reads it from here instead of asking the API again. */
6693
6864
  function announceCanvasName(targetCanvasId: string, record: Record<string, any> | null): void {
6694
6865
  const name = String(record?.persistenceKey || record?.persistence_key || '').trim();
@@ -10132,6 +10303,8 @@ Requirements:
10132
10303
  }>;
10133
10304
  /** Widget DOM elements selected via the interactive canvas Selector. */
10134
10305
  selectedElements?: SelectedWidgetElementReference[];
10306
+ /** Fires once, when the worker preview is up and the chat can accept the next message. */
10307
+ onPreviewVisible?: () => void;
10135
10308
  } = {}) {
10136
10309
  const targetWidgetId = options.widgetId ?? selectedWidgetId;
10137
10310
  if (!targetWidgetId) return;
@@ -10222,6 +10395,7 @@ Requirements:
10222
10395
  skipIntentGate: options.skipIntentGate,
10223
10396
  chipIntent: options.chipIntent,
10224
10397
  selectedElements: options.selectedElements,
10398
+ onPreviewVisible: options.onPreviewVisible,
10225
10399
  });
10226
10400
  }
10227
10401
 
@@ -10433,6 +10607,8 @@ Requirements:
10433
10607
  display_order?: number;
10434
10608
  }>;
10435
10609
  selectedElements?: SelectedWidgetElementReference[];
10610
+ /** Fires once, when the worker preview is up and the chat can accept the next message. */
10611
+ onPreviewVisible?: () => void;
10436
10612
  } = {},
10437
10613
  ) {
10438
10614
  const generationWidgetId = options.widgetId ?? selectedWidgetId;
@@ -10455,6 +10631,10 @@ Requirements:
10455
10631
  generationOperationByWidgetId.delete(generationWidgetId);
10456
10632
 
10457
10633
  generatingWidgetIds = { ...generatingWidgetIds, [generationWidgetId]: true };
10634
+ if (previewUnblockedByWidgetId[generationWidgetId]) {
10635
+ const { [generationWidgetId]: _dropPreview, ...restPreview } = previewUnblockedByWidgetId;
10636
+ previewUnblockedByWidgetId = restPreview;
10637
+ }
10458
10638
  noteCodegenActive(true);
10459
10639
  screenshotGenerationEpoch += 1;
10460
10640
  abortScreenshotsInFlight();
@@ -10700,6 +10880,7 @@ Requirements:
10700
10880
  images: imagesToSend,
10701
10881
  attachmentIds: attachmentIdsToSend,
10702
10882
  runtimeLogs: runtimeLogsForRequest,
10883
+ ...(options.compileFixOnly ? {} : { baseCommitSha: generationBaseCommitSha(generationWidgetId) }),
10703
10884
  compileFixOnly: options.compileFixOnly === true,
10704
10885
  skipIntentGate: options.skipIntentGate === true,
10705
10886
  chipIntent: options.chipIntent,
@@ -10870,6 +11051,25 @@ Requirements:
10870
11051
  if (signal.aborted) return;
10871
11052
  if (!op) return;
10872
11053
 
11054
+ // The worker preview is ready while GitLab is still saving. The socket
11055
+ // often never arrives on production, so the poll is what shows it.
11056
+ const runningPreviewUrl = getOperationPreviewUrl(op.metadata);
11057
+ if (
11058
+ runningPreviewUrl
11059
+ && (op.status || '').toLowerCase() === 'running'
11060
+ && widgetAbortControllers.get(generationWidgetId) === abortController
11061
+ ) {
11062
+ publishRunningWorkerPreview(generationWidgetId, runningPreviewUrl);
11063
+ if (!previewUnblockedByWidgetId[generationWidgetId]) {
11064
+ previewUnblockedByWidgetId = {
11065
+ ...previewUnblockedByWidgetId,
11066
+ [generationWidgetId]: true,
11067
+ };
11068
+ panelChat?.updateLatestCodegenStatusMessage?.('Preview ready');
11069
+ options.onPreviewVisible?.();
11070
+ }
11071
+ }
11072
+
10873
11073
  if (op.status === 'failed') {
10874
11074
  const errorMsg = op.error || 'Unknown error';
10875
11075
  patchCodegenUiState(generationWidgetId, {
@@ -10943,6 +11143,7 @@ Requirements:
10943
11143
 
10944
11144
  const completedCommitSha = getOperationCommitId(op.metadata);
10945
11145
  const completedCommitTitle = getOperationCommitTitle(op.metadata);
11146
+ if (generationWidgetId) applySuggestedWidgetName(generationWidgetId, op.metadata);
10946
11147
  const completedPreviewBuildErr = getOperationPreviewBuildError(op.metadata);
10947
11148
  const repositorySaveError = getOperationRepositorySaveError(op.metadata);
10948
11149
  const completedCached = getOperationCached(op.metadata);
@@ -11426,6 +11627,8 @@ Requirements:
11426
11627
  if (widgetAbortControllers.get(generationWidgetId) === abortController) {
11427
11628
  const { [generationWidgetId]: _done, ...restFinally } = generatingWidgetIds;
11428
11629
  generatingWidgetIds = restFinally;
11630
+ const { [generationWidgetId]: _previewDone, ...restPreview } = previewUnblockedByWidgetId;
11631
+ previewUnblockedByWidgetId = restPreview;
11429
11632
  widgetAbortControllers.delete(generationWidgetId);
11430
11633
  if (currentGenerationOperationId === generationOperationByWidgetId.get(generationWidgetId)) currentGenerationOperationId = null;
11431
11634
  generationOperationByWidgetId.delete(generationWidgetId);
@@ -12227,6 +12430,28 @@ Requirements:
12227
12430
  return typeof raw === 'string' && /^[a-f0-9]{7,40}$/i.test(raw) ? raw : null;
12228
12431
  }
12229
12432
 
12433
+ /** A title from the first generation replaces only the automatic placeholder, not a name already set. */
12434
+ function isPlaceholderWidgetName(name: string | null | undefined): boolean {
12435
+ const trimmed = (name || '').trim();
12436
+ if (!trimmed) return true;
12437
+ if (/^ConvertedW-\d+$/.test(trimmed)) return true;
12438
+ if (/^Converted /.test(trimmed)) return true;
12439
+ return trimmed === 'Widget Draft' || trimmed === 'Untitled Widget' || trimmed === 'Untitled';
12440
+ }
12441
+
12442
+ function getSuggestedWidgetName(metadata?: Record<string, unknown>): string | null {
12443
+ if (!metadata) return null;
12444
+ const raw = metadata.suggestedWidgetName ?? metadata.suggested_widget_name;
12445
+ return typeof raw === 'string' && raw.trim().length > 0 ? raw.trim() : null;
12446
+ }
12447
+
12448
+ function applySuggestedWidgetName(widgetId: string, metadata?: Record<string, unknown>): void {
12449
+ const suggested = getSuggestedWidgetName(metadata);
12450
+ if (!suggested || !isPlaceholderWidgetName(getWidgetById(widgetId)?.name)) return;
12451
+ console.log('[CreatorApp] Applying suggested widget name', widgetId.substring(0, 8), suggested);
12452
+ void applyHostWidgetName(widgetId, suggested);
12453
+ }
12454
+
12230
12455
  /** The version title a completed codegen operation shipped ("Update header styles"), from operation metadata. */
12231
12456
  function getOperationCommitTitle(metadata?: Record<string, unknown>): string | null {
12232
12457
  if (!metadata) return null;
@@ -12234,6 +12459,26 @@ Requirements:
12234
12459
  return typeof raw === 'string' && raw.trim().length > 0 ? raw.trim() : null;
12235
12460
  }
12236
12461
 
12462
+ function getOperationPreviewUrl(metadata?: Record<string, unknown>): string | null {
12463
+ if (!metadata) return null;
12464
+ if (metadata.previewReady !== true && metadata.preview_ready !== true) return null;
12465
+ const raw = metadata.previewUrl ?? metadata.preview_url;
12466
+ return typeof raw === 'string' && raw.trim().length > 0 ? raw.trim() : null;
12467
+ }
12468
+
12469
+ let lastRunningPreviewKey = '';
12470
+ function publishRunningWorkerPreview(widgetId: string, previewUrl: string): void {
12471
+ const key = `${widgetId}:${previewUrl}`;
12472
+ if (key === lastRunningPreviewKey) return;
12473
+ lastRunningPreviewKey = key;
12474
+ dynamicWorkerPreviewStatus.set({
12475
+ widgetId,
12476
+ previewUrl,
12477
+ buildTimeMs: null,
12478
+ timestamp: new Date().toISOString(),
12479
+ });
12480
+ }
12481
+
12237
12482
  function getOperationPreviewBuildError(metadata?: Record<string, unknown>): string | null {
12238
12483
  if (!metadata) return null;
12239
12484
  const raw = metadata.previewBuildError ?? metadata.preview_build_error;
@@ -12320,6 +12565,13 @@ Requirements:
12320
12565
  // reaches the API from the watchdog. Ordinary progress does not.
12321
12566
  }
12322
12567
 
12568
+ function readGenerationStreamTail(op: OperationStatus): string {
12569
+ const metadata = op.metadata;
12570
+ if (!metadata) return '';
12571
+ const raw = metadata.streamTail ?? metadata.stream_tail;
12572
+ return typeof raw === 'string' ? raw.slice(-1600) : '';
12573
+ }
12574
+
12323
12575
  function pushCodegenProgressToUi(op: OperationStatus, widgetId: string | null | undefined) {
12324
12576
  const line = formatCodegenProgressStatus(op);
12325
12577
  freezeProbe('progress', line);
@@ -12329,7 +12581,14 @@ Requirements:
12329
12581
  // SSE progress frames can arrive many times per second while the LLM
12330
12582
  // streams. Each one re-renders every open panel — coalesce them.
12331
12583
  if (widgetId) {
12332
- scheduleCodegenStatusPush(widgetId, line);
12584
+ const status = String(op.status || '').toLowerCase();
12585
+ if (status === 'completed' || status === 'failed' || status === 'cancelled') {
12586
+ delete codegenStreamPending[widgetId];
12587
+ clearGenerationStream(widgetId);
12588
+ scheduleCodegenStatusPush(widgetId, line);
12589
+ } else {
12590
+ scheduleCodegenStatusPush(widgetId, line, readGenerationStreamTail(op));
12591
+ }
12333
12592
  }
12334
12593
  scheduleCodegenChatStatusPush(widgetId, line);
12335
12594
  }
@@ -12337,18 +12596,32 @@ Requirements:
12337
12596
  const CODEGEN_STATUS_THROTTLE_MS = 400;
12338
12597
  const codegenStatusTimers: Record<string, ReturnType<typeof setTimeout>> = {};
12339
12598
  const codegenStatusPendingLine: Record<string, string> = {};
12599
+ const codegenStreamPending: Record<string, string> = {};
12340
12600
  const codegenChatStatusTimers: Record<string, ReturnType<typeof setTimeout>> = {};
12341
12601
  const codegenChatStatusPendingLine: Record<string, string> = {};
12342
12602
 
12603
+ function clearGenerationStream(widgetId: string): void {
12604
+ if (!generationStreamByWidgetId[widgetId]) return;
12605
+ const next = { ...generationStreamByWidgetId };
12606
+ delete next[widgetId];
12607
+ generationStreamByWidgetId = next;
12608
+ }
12609
+
12343
12610
  /** At most one panel status write per widget per interval; trailing line always lands. */
12344
- function scheduleCodegenStatusPush(widgetId: string, line: string): void {
12611
+ function scheduleCodegenStatusPush(widgetId: string, line: string, streamTail = ''): void {
12345
12612
  codegenStatusPendingLine[widgetId] = line;
12613
+ if (streamTail) codegenStreamPending[widgetId] = streamTail;
12346
12614
  if (codegenStatusTimers[widgetId]) return;
12347
12615
  codegenStatusTimers[widgetId] = setTimeout(() => {
12348
12616
  delete codegenStatusTimers[widgetId];
12349
12617
  const pending = codegenStatusPendingLine[widgetId];
12618
+ const pendingTail = codegenStreamPending[widgetId];
12350
12619
  delete codegenStatusPendingLine[widgetId];
12620
+ delete codegenStreamPending[widgetId];
12351
12621
  if (pending) patchCodegenUiState(widgetId, { generateCodeStatus: pending });
12622
+ if (pendingTail && pendingTail !== generationStreamByWidgetId[widgetId]) {
12623
+ generationStreamByWidgetId = { ...generationStreamByWidgetId, [widgetId]: pendingTail };
12624
+ }
12352
12625
  }, CODEGEN_STATUS_THROTTLE_MS);
12353
12626
  }
12354
12627
 
@@ -13374,8 +13647,37 @@ Requirements:
13374
13647
  panelDisplayRevision += 1;
13375
13648
  }
13376
13649
 
13377
- function handleWidgetShapeVersionChange(widgetId: string, versionId: string, buildPreview = true): void {
13650
+ /** Switch Version paints into a widget shape. After a sketch restore that shape is gone, so put it back first. */
13651
+ async function ensureWidgetShapeOnCanvas(widgetId: string): Promise<void> {
13652
+ if (!canvasRef?.getLinkedWidgetIds || !widgetId) return;
13653
+ if (canvasRef.getLinkedWidgetIds().has(widgetId)) return;
13654
+ const board = canvasRef.saveCanvas?.() ?? null;
13655
+ if (board && !sketchSnapshotsByWidgetId.get(widgetId)) {
13656
+ sketchSnapshotsByWidgetId.set(widgetId, board);
13657
+ }
13658
+ const absorber = canvasRef as typeof canvasRef & {
13659
+ absorbCanvasSketchIntoWidget?: (id: string, screenshotDataUrl: string) => Promise<string | null>;
13660
+ };
13661
+ try {
13662
+ if (embedded && !canvasAdvancedFeatures && absorber.absorbCanvasSketchIntoWidget) {
13663
+ await absorber.absorbCanvasSketchIntoWidget(widgetId, '');
13664
+ } else {
13665
+ canvasRef.addWidgetShape?.(widgetId, getWidgetById(widgetId)?.name, 0, 1, null);
13666
+ }
13667
+ if (!canvasRef.getLinkedWidgetIds().has(widgetId)) {
13668
+ canvasRef.addWidgetShape?.(widgetId, getWidgetById(widgetId)?.name, 0, 1, null);
13669
+ }
13670
+ canvasRef.saveNow?.();
13671
+ syncWidgetShapeLivePreviews();
13672
+ console.log('[VersionPreview] Widget shape put back on the board', widgetId.substring(0, 8));
13673
+ } catch (error) {
13674
+ console.warn('[VersionPreview] Could not put the widget shape back', error);
13675
+ }
13676
+ }
13677
+
13678
+ async function handleWidgetShapeVersionChange(widgetId: string, versionId: string, buildPreview = true): Promise<void> {
13378
13679
  if (!versionId) return;
13680
+ await ensureWidgetShapeOnCanvas(widgetId);
13379
13681
  // Both dropdowns show the pick. Only the dropdown the user clicked reloads the preview.
13380
13682
  selectVersionInDropdowns(widgetId, versionId);
13381
13683
  if (!buildPreview) return;
@@ -16312,6 +16614,38 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16312
16614
  * Marks the canvas as ready; actual state loading happens in loadCanvasState()
16313
16615
  * which is called after loadCurrentCanvas() resolves canvasId.
16314
16616
  */
16617
+ let simpleCanvasChatKey = '';
16618
+
16619
+ /** Simple canvas: one chat, always. The draft id stands in until the first Send creates the widget. */
16620
+ async function ensureSimpleCanvasChat(): Promise<void> {
16621
+ if (!embedded || canvasAdvancedFeatures || !canvasComponentReady) return;
16622
+ if (finalizingDraftConversions.size > 0) return;
16623
+ const primaryId = (canvasPrimaryWidgetId || '').trim();
16624
+ const targetId = primaryId || CANVAS_SKETCH_DRAFT_ID;
16625
+ const key = `${canvasId || 'pending'}:${targetId}`;
16626
+ if (simpleCanvasChatKey === key && openWidgetPanelIds.includes(targetId)) return;
16627
+ simpleCanvasChatKey = key;
16628
+ try {
16629
+ if (primaryId && openWidgetPanelIds.includes(CANVAS_SKETCH_DRAFT_ID)) {
16630
+ closeWidgetDetailsPanel(CANVAS_SKETCH_DRAFT_ID, { fromShapeSwitch: true });
16631
+ }
16632
+ if (!openWidgetPanelIds.includes(targetId)) {
16633
+ await openWidgetDetailsPanel(targetId);
16634
+ } else if (focusedPanelWidgetId !== targetId) {
16635
+ focusWidgetPanel(targetId);
16636
+ }
16637
+ } catch (chatError) {
16638
+ console.warn('[CreatorApp] Could not open the canvas chat', chatError);
16639
+ }
16640
+ }
16641
+
16642
+ $: if (embedded && !canvasAdvancedFeatures && canvasComponentReady && isCanvasStateLoaded) {
16643
+ const simpleChatTarget = (canvasPrimaryWidgetId || '').trim() || CANVAS_SKETCH_DRAFT_ID;
16644
+ if (!openWidgetPanelIds.includes(simpleChatTarget)) {
16645
+ void ensureSimpleCanvasChat();
16646
+ }
16647
+ }
16648
+
16315
16649
  async function handleCanvasReady() {
16316
16650
  markCanvasOpenStep('creator:canvas-ready');
16317
16651
  // console.log('[WidgetCreator] Canvas component ready');
@@ -16327,6 +16661,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16327
16661
  placeSelectedWidgetShapeOnCanvas();
16328
16662
  }
16329
16663
  syncWidgetShapeLivePreviews();
16664
+ void ensureSimpleCanvasChat();
16330
16665
  return;
16331
16666
  }
16332
16667
  const { loaded, widgetIds: widgetIdsOnCanvas } = await tryLoadCanvasState();
@@ -16336,6 +16671,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16336
16671
  scheduleCanvasHydrateRetry('canvas ready before canvasId');
16337
16672
  }
16338
16673
  syncWidgetShapeLivePreviews();
16674
+ void ensureSimpleCanvasChat();
16339
16675
  return;
16340
16676
  }
16341
16677
  await syncWidgetsWithCanvas(widgetIdsOnCanvas);
@@ -16350,6 +16686,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16350
16686
  setTimeout(() => applyPrimarySelectionOnCanvas(primaryId), 80);
16351
16687
  });
16352
16688
  syncWidgetShapeLivePreviews();
16689
+ void ensureSimpleCanvasChat();
16353
16690
  }
16354
16691
 
16355
16692
  /**
@@ -16503,6 +16840,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16503
16840
  }
16504
16841
  canvasContent = canvasRecord?.canvasContent ?? canvasRecord?.canvas_content ?? null;
16505
16842
  if (canvasContent) break;
16843
+ // A canvas that was never saved is empty for certain; waiting for content would take seconds.
16844
+ if (canvasRecordWasNeverSaved(canvasRecord)) break;
16506
16845
  console.log('[CanvasDebug] getCanvas returned no canvasContent, retry', attempt + 1);
16507
16846
  } catch (getErr) {
16508
16847
  console.warn('[CanvasDebug] getCanvas failed, retry', attempt + 1, getErr);
@@ -16983,7 +17322,13 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16983
17322
  name: draftName,
16984
17323
  type: 'widget',
16985
17324
  // Canvas sketch snapshot is stored on the widget for future reference
16986
- content: { source: 'canvas_convert', prompt },
17325
+ content: {
17326
+ source: embedded && !canvasAdvancedFeatures ? 'canvas_sketch' : 'canvas_convert',
17327
+ prompt,
17328
+ ...(draftConvertSketchJson.get(draftId) && (draftConvertSketchJson.get(draftId)?.length ?? 0) < 400000
17329
+ ? { sketchCanvasJson: draftConvertSketchJson.get(draftId) }
17330
+ : {}),
17331
+ },
16987
17332
  isDraft: true,
16988
17333
  // (No `description`: a new widget has no such field, the API ignored it, and a partner's session is
16989
17334
  // refused for sending a field it may not write.)
@@ -17007,6 +17352,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17007
17352
  return null;
17008
17353
  }
17009
17354
  const widgetId: string = newWidget.id;
17355
+ const sketchJson = draftConvertSketchJson.get(draftId);
17356
+ if (sketchJson) sketchSnapshotsByWidgetId.set(widgetId, sketchJson);
17010
17357
 
17011
17358
  // Add to widgets list so getWidgetById resolves the real widget from now on.
17012
17359
  widgets = [{ ...newWidget }, ...widgets.filter((w) => w.id !== draftId)];
@@ -17020,7 +17367,19 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17020
17367
 
17021
17368
  // Replace the grouped sketch with a WidgetShape screenshot. On failure
17022
17369
  // fall back to linking the sketch object to the widget id.
17023
- if (canvasRef && canvasObjectId) {
17370
+ const sketchCanvas = canvasRef as (typeof canvasRef & {
17371
+ absorbCanvasSketchIntoWidget?: (widgetId: string, screenshotDataUrl: string) => Promise<string | null>;
17372
+ }) | null;
17373
+ if (embedded && !canvasAdvancedFeatures && sketchCanvas?.absorbCanvasSketchIntoWidget) {
17374
+ try {
17375
+ await sketchCanvas.absorbCanvasSketchIntoWidget(widgetId, screenshot);
17376
+ setTimeout(() => {
17377
+ canvasRef?.saveNow?.();
17378
+ }, 800);
17379
+ } catch (absorbError) {
17380
+ console.warn('[CreatorApp] Whole-canvas sketch absorb failed:', absorbError);
17381
+ }
17382
+ } else if (canvasRef && canvasObjectId) {
17024
17383
  try {
17025
17384
  await canvasRef.replaceObjectWithWidgetImage(canvasObjectId, widgetId, screenshot);
17026
17385
  // console.log('[WidgetCreator] Sketch replaced with WidgetShape screenshot');
@@ -17806,7 +18165,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17806
18165
 
17807
18166
 
17808
18167
  <!-- Widgetic Canvas Editor - Full width background (lazy-loaded) -->
17809
- <div class="wc-canvas-area flex-1 min-h-0 relative">
18168
+ <div class="wc-canvas-area flex-1 min-h-0 relative {embedded && !canvasAdvancedFeatures ? 'pe-[480px]' : ''}">
17810
18169
  <!-- Embedded: Debug toggle lives in site AppHeader (avoids overlapping Props Panel). -->
17811
18170
  {#if canvasApiLoadError || canvasShapesMissingWarning}
17812
18171
  <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">
@@ -17868,6 +18227,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17868
18227
  widgetNameRevision={widgetNamesRevision}
17869
18228
  isWidgetKnown={isWidgetKnownById}
17870
18229
  onNonWidgetSelected={() => {
18230
+ if (embedded && !canvasAdvancedFeatures) return;
17871
18231
  if (suppressWidgetDetailsClose || isConvertOrDraftPanelOpen()) {
17872
18232
  // console.log('[CreatorApp] Skip Widget Details close — convert/draft panel is open');
17873
18233
  return;
@@ -17877,7 +18237,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17877
18237
  }
17878
18238
  widgetDetails?.closeWidgetDetails();
17879
18239
  }}
17880
- panZoomPosition="TC"
18240
+ panZoomPosition="TL"
17881
18241
  showSaveButton={true}
17882
18242
  autosaveDelayMs={import.meta.env.DEV ? 15000 : 5000}
17883
18243
  suspendAutosave={suspendCanvasAutosave}
@@ -17895,6 +18255,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17895
18255
  <!-- W3: live iframe + drag bar on WidgetShapes (iframe interactive; body drag locked) -->
17896
18256
  <WidgetShapeLivePreviews
17897
18257
  bind:this={widgetShapeLivePreviewsRef}
18258
+ showChrome={!(embedded && !canvasAdvancedFeatures)}
17898
18259
  getRects={() => canvasRef?.listWidgetShapeScreenRects?.() ?? []}
17899
18260
  resolveUrl={resolveWidgetShapeLivePreviewUrl}
17900
18261
  resolvePreviewState={resolveWidgetShapeVersionPreviewState}
@@ -18300,6 +18661,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18300
18661
  panelTopOffset={widgetsPanelTopOffset}
18301
18662
  panelBottomMargin={embedded ? 24 : widgetsPanelBottomMargin}
18302
18663
  fillViewport={false}
18664
+ dockRight={embedded && !canvasAdvancedFeatures}
18303
18665
  showCompositionSteps={canvasAdvancedFeatures}
18304
18666
  currentStep={ps.widgetDetailsStep}
18305
18667
  on:focusPanel={() => focusWidgetPanel(panelWidgetId)}
@@ -18616,6 +18978,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18616
18978
  <span class="text-emerald-500">{isHistoryOpen && isPanelFocused ? '▲' : '▼'}</span>
18617
18979
  </button>
18618
18980
  </HoverTooltip>
18981
+ {#if !(embedded && !canvasAdvancedFeatures)}
18619
18982
  {#if panelHasUnpublishedChanges && !Number.isFinite(viewingVersion)}
18620
18983
  <button
18621
18984
  type="button"
@@ -18670,6 +19033,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18670
19033
  {isSettingLiveVersion === Number(viewingVersion) ? '...' : $t('creator.common.setLive')}
18671
19034
  </button>
18672
19035
  {/if}
19036
+ {/if}
18673
19037
  {#if isHistoryOpen && isPanelFocused}
18674
19038
  <Portal target="wc-live-history-portal-{panelWidgetId}">
18675
19039
  <button
@@ -18758,16 +19122,47 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18758
19122
  </svelte:fragment>
18759
19123
 
18760
19124
  <svelte:fragment slot="code-generation-status">
18761
- <div class="generate-code-status-ct flex flex-col gap-2 shrink-0 border-b border-gray-200 bg-gray-50" style="padding: 10px; margin: 0px; border-radius: 0;">
19125
+ {#if true}
19126
+ {@const statusText = isPanelFocused ? (generateCodeStatus ?? ps.generateCodeStatus) : ps.generateCodeStatus}
19127
+ {@const hourlyLimit = isHourlyLimitText(statusText) || isHourlyLimitText(ps.lastGenerationError)}
19128
+ <div class="generate-code-status-ct flex flex-col gap-2 shrink-0 {embedded && !canvasAdvancedFeatures ? 'border-0 bg-transparent' : 'border-b border-gray-200 bg-gray-50'}" style="padding: 10px; margin: 0px; border-radius: 0;">
18762
19129
  <div class="flex items-center justify-between gap-2 min-w-0">
18763
- <div class="generate-code-status-el text-xs flex-1 min-w-0 truncate {ps.lastGenerationFailed ? 'text-red-600' : 'text-gray-500'}">
18764
- {#if ps.lastGenerationFailed}
19130
+ <div class="generate-code-status-el text-xs flex-1 min-w-0 truncate {ps.lastGenerationFailed && !hourlyLimit ? 'text-red-600' : 'text-gray-500'}">
19131
+ {#if ps.lastGenerationFailed && !hourlyLimit}
18765
19132
  <span class="text-red-500 font-medium">{$t('creator.codegen.generationFailed')}</span>
18766
19133
  {:else}
18767
- <span class="text-gray-400">{$t('creator.status.label')}</span> {statusLabel(isPanelFocused ? (generateCodeStatus ?? ps.generateCodeStatus) : ps.generateCodeStatus, $t)}
19134
+ <span class="text-gray-400">{$t('creator.status.label')}</span> {hourlyLimit ? $t('creator.status.ready') : statusLabel(statusText, $t)}
18768
19135
  {/if}
18769
19136
  </div>
18770
19137
  </div>
19138
+ {#if hourlyLimit}
19139
+ <div class="hourly-limit-banner p-3 bg-red-50 border border-red-200" style="border-radius: 0;">
19140
+ <p class="text-xs text-red-700 whitespace-pre-wrap">{$t('creator.preview.versionHourlyLimit')}</p>
19141
+ <div class="flex gap-2 mt-3 justify-center">
19142
+ <Button
19143
+ onclick={() => {
19144
+ if (!isPanelFocused) focusWidgetPanel(panelWidgetId);
19145
+ patchPanelSnapshot(panelWidgetId, {
19146
+ lastGenerationFailed: false,
19147
+ lastGenerationError: null,
19148
+ generateCodeStatus: 'Ready',
19149
+ });
19150
+ if (isPanelFocused || focusedPanelWidgetId === panelWidgetId) {
19151
+ lastGenerationFailed = false;
19152
+ lastGenerationError = null;
19153
+ generateCodeStatus = 'Ready';
19154
+ }
19155
+ panelDisplayRevision += 1;
19156
+ }}
19157
+ variant="outline"
19158
+ size="sm"
19159
+ class="border-gray-300 text-gray-600 hover:bg-gray-50 rounded-lg"
19160
+ >
19161
+ {$t('creator.general.dismiss')}
19162
+ </Button>
19163
+ </div>
19164
+ </div>
19165
+ {/if}
18771
19166
  {#if publishPlanMessageByWidgetId[panelWidgetId]}
18772
19167
  <div class="publish-plan-notice p-3 bg-red-50 border border-red-200" style="border-radius: 0;">
18773
19168
  <p class="text-xs text-red-700 whitespace-pre-wrap">{publishPlanMessageByWidgetId[panelWidgetId]}</p>
@@ -18795,7 +19190,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18795
19190
  </div>
18796
19191
  </div>
18797
19192
  {/if}
18798
- {#if ps.lastGenerationFailed}
19193
+ {#if ps.lastGenerationFailed && !hourlyLimit}
18799
19194
  <div class="p-3 bg-red-50 border border-red-200" style="border-radius: 0;">
18800
19195
  <p class="text-xs text-red-700 whitespace-pre-wrap">{errorLabel(ps.lastGenerationError, $t)}</p>
18801
19196
  <div class="flex gap-2 mt-3 justify-center">
@@ -18851,6 +19246,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18851
19246
  </div>
18852
19247
  {/if}
18853
19248
  </div>
19249
+ {/if}
18854
19250
  </svelte:fragment>
18855
19251
 
18856
19252
  <svelte:fragment slot="code-generation">
@@ -18977,7 +19373,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18977
19373
  onChatReady={(methods) => handleChatReady(methods, panelWidgetId)}
18978
19374
  onDraftChange={() => handleChatDraftChange(panelWidgetId)}
18979
19375
  onConversationChange={(conversationId) => handleChatConversationChange(conversationId, panelWidgetId)}
18980
- isGenerating={!!generatingWidgetIds[panelWidgetId]}
19376
+ isGenerating={!!generatingWidgetIds[panelWidgetId] && !previewUnblockedByWidgetId[panelWidgetId]}
19377
+ generationStream={generationStreamByWidgetId[panelWidgetId] || ''}
18981
19378
  onStopGeneration={() => {
18982
19379
  if (!isPanelFocused) focusWidgetPanel(panelWidgetId);
18983
19380
  // Stop belongs to the panel it was pressed in: the other panels' generations go on