@widgetic/creator 0.4.19 → 0.4.21

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);
@@ -10143,6 +10303,8 @@ Requirements:
10143
10303
  }>;
10144
10304
  /** Widget DOM elements selected via the interactive canvas Selector. */
10145
10305
  selectedElements?: SelectedWidgetElementReference[];
10306
+ /** Fires once, when the worker preview is up and the chat can accept the next message. */
10307
+ onPreviewVisible?: () => void;
10146
10308
  } = {}) {
10147
10309
  const targetWidgetId = options.widgetId ?? selectedWidgetId;
10148
10310
  if (!targetWidgetId) return;
@@ -10233,6 +10395,7 @@ Requirements:
10233
10395
  skipIntentGate: options.skipIntentGate,
10234
10396
  chipIntent: options.chipIntent,
10235
10397
  selectedElements: options.selectedElements,
10398
+ onPreviewVisible: options.onPreviewVisible,
10236
10399
  });
10237
10400
  }
10238
10401
 
@@ -10444,6 +10607,8 @@ Requirements:
10444
10607
  display_order?: number;
10445
10608
  }>;
10446
10609
  selectedElements?: SelectedWidgetElementReference[];
10610
+ /** Fires once, when the worker preview is up and the chat can accept the next message. */
10611
+ onPreviewVisible?: () => void;
10447
10612
  } = {},
10448
10613
  ) {
10449
10614
  const generationWidgetId = options.widgetId ?? selectedWidgetId;
@@ -10466,6 +10631,10 @@ Requirements:
10466
10631
  generationOperationByWidgetId.delete(generationWidgetId);
10467
10632
 
10468
10633
  generatingWidgetIds = { ...generatingWidgetIds, [generationWidgetId]: true };
10634
+ if (previewUnblockedByWidgetId[generationWidgetId]) {
10635
+ const { [generationWidgetId]: _dropPreview, ...restPreview } = previewUnblockedByWidgetId;
10636
+ previewUnblockedByWidgetId = restPreview;
10637
+ }
10469
10638
  noteCodegenActive(true);
10470
10639
  screenshotGenerationEpoch += 1;
10471
10640
  abortScreenshotsInFlight();
@@ -10711,6 +10880,7 @@ Requirements:
10711
10880
  images: imagesToSend,
10712
10881
  attachmentIds: attachmentIdsToSend,
10713
10882
  runtimeLogs: runtimeLogsForRequest,
10883
+ ...(options.compileFixOnly ? {} : { baseCommitSha: generationBaseCommitSha(generationWidgetId) }),
10714
10884
  compileFixOnly: options.compileFixOnly === true,
10715
10885
  skipIntentGate: options.skipIntentGate === true,
10716
10886
  chipIntent: options.chipIntent,
@@ -10881,6 +11051,25 @@ Requirements:
10881
11051
  if (signal.aborted) return;
10882
11052
  if (!op) return;
10883
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
+
10884
11073
  if (op.status === 'failed') {
10885
11074
  const errorMsg = op.error || 'Unknown error';
10886
11075
  patchCodegenUiState(generationWidgetId, {
@@ -10937,6 +11126,13 @@ Requirements:
10937
11126
  }
10938
11127
 
10939
11128
  if (op.status === 'completed') {
11129
+ const completedPreviewUrl = getOperationPreviewUrl(op.metadata);
11130
+ if (
11131
+ completedPreviewUrl
11132
+ && widgetAbortControllers.get(generationWidgetId) === abortController
11133
+ ) {
11134
+ publishRunningWorkerPreview(generationWidgetId, completedPreviewUrl);
11135
+ }
10940
11136
  // The SSE callback runs on the page thread. Applying the result here
10941
11137
  // rebuilds the chat before the browser can paint, so the status stays
10942
11138
  // on the previous percent and the tab stops answering.
@@ -10954,6 +11150,7 @@ Requirements:
10954
11150
 
10955
11151
  const completedCommitSha = getOperationCommitId(op.metadata);
10956
11152
  const completedCommitTitle = getOperationCommitTitle(op.metadata);
11153
+ if (generationWidgetId) applySuggestedWidgetName(generationWidgetId, op.metadata);
10957
11154
  const completedPreviewBuildErr = getOperationPreviewBuildError(op.metadata);
10958
11155
  const repositorySaveError = getOperationRepositorySaveError(op.metadata);
10959
11156
  const completedCached = getOperationCached(op.metadata);
@@ -11437,6 +11634,8 @@ Requirements:
11437
11634
  if (widgetAbortControllers.get(generationWidgetId) === abortController) {
11438
11635
  const { [generationWidgetId]: _done, ...restFinally } = generatingWidgetIds;
11439
11636
  generatingWidgetIds = restFinally;
11637
+ const { [generationWidgetId]: _previewDone, ...restPreview } = previewUnblockedByWidgetId;
11638
+ previewUnblockedByWidgetId = restPreview;
11440
11639
  widgetAbortControllers.delete(generationWidgetId);
11441
11640
  if (currentGenerationOperationId === generationOperationByWidgetId.get(generationWidgetId)) currentGenerationOperationId = null;
11442
11641
  generationOperationByWidgetId.delete(generationWidgetId);
@@ -12238,6 +12437,28 @@ Requirements:
12238
12437
  return typeof raw === 'string' && /^[a-f0-9]{7,40}$/i.test(raw) ? raw : null;
12239
12438
  }
12240
12439
 
12440
+ /** A title from the first generation replaces only the automatic placeholder, not a name already set. */
12441
+ function isPlaceholderWidgetName(name: string | null | undefined): boolean {
12442
+ const trimmed = (name || '').trim();
12443
+ if (!trimmed) return true;
12444
+ if (/^ConvertedW-\d+$/.test(trimmed)) return true;
12445
+ if (/^Converted /.test(trimmed)) return true;
12446
+ return trimmed === 'Widget Draft' || trimmed === 'Untitled Widget' || trimmed === 'Untitled';
12447
+ }
12448
+
12449
+ function getSuggestedWidgetName(metadata?: Record<string, unknown>): string | null {
12450
+ if (!metadata) return null;
12451
+ const raw = metadata.suggestedWidgetName ?? metadata.suggested_widget_name;
12452
+ return typeof raw === 'string' && raw.trim().length > 0 ? raw.trim() : null;
12453
+ }
12454
+
12455
+ function applySuggestedWidgetName(widgetId: string, metadata?: Record<string, unknown>): void {
12456
+ const suggested = getSuggestedWidgetName(metadata);
12457
+ if (!suggested || !isPlaceholderWidgetName(getWidgetById(widgetId)?.name)) return;
12458
+ console.log('[CreatorApp] Applying suggested widget name', widgetId.substring(0, 8), suggested);
12459
+ void applyHostWidgetName(widgetId, suggested);
12460
+ }
12461
+
12241
12462
  /** The version title a completed codegen operation shipped ("Update header styles"), from operation metadata. */
12242
12463
  function getOperationCommitTitle(metadata?: Record<string, unknown>): string | null {
12243
12464
  if (!metadata) return null;
@@ -12245,6 +12466,43 @@ Requirements:
12245
12466
  return typeof raw === 'string' && raw.trim().length > 0 ? raw.trim() : null;
12246
12467
  }
12247
12468
 
12469
+ function getOperationPreviewUrl(metadata?: Record<string, unknown>): string | null {
12470
+ if (!metadata) return null;
12471
+ if (metadata.previewReady !== true && metadata.preview_ready !== true) return null;
12472
+ const raw = metadata.previewUrl ?? metadata.preview_url;
12473
+ return typeof raw === 'string' && raw.trim().length > 0 ? raw.trim() : null;
12474
+ }
12475
+
12476
+ let lastRunningPreviewKey = '';
12477
+ /** Worker document published before the repository save. The shape uses it while the version row is still catching up. */
12478
+ let runningWorkerPreviewUrlByWidgetId: Record<string, string> = {};
12479
+ function publishRunningWorkerPreview(widgetId: string, previewUrl: string): void {
12480
+ const key = `${widgetId}:${previewUrl}`;
12481
+ if (key === lastRunningPreviewKey) return;
12482
+ lastRunningPreviewKey = key;
12483
+ runningWorkerPreviewUrlByWidgetId = {
12484
+ ...runningWorkerPreviewUrlByWidgetId,
12485
+ [widgetId]: previewUrl,
12486
+ };
12487
+ dynamicWorkerPreviewStatus.set({
12488
+ widgetId,
12489
+ previewUrl,
12490
+ buildTimeMs: null,
12491
+ timestamp: new Date().toISOString(),
12492
+ });
12493
+ // The chat can already show the version while this flag is still on. The shape
12494
+ // has to take the document now, not after the save finishes.
12495
+ widgetShapeLivePreviewsRef?.requestReload?.(widgetId, { immediate: true });
12496
+ }
12497
+
12498
+ /** The canvas iframe painted, so the chat is no longer waiting on a hidden side preview. */
12499
+ function noteShapePreviewShown(widgetId: string): void {
12500
+ const status = getPanelDisplayState(widgetId).generateCodeStatus || '';
12501
+ if (!status.includes('loading preview')) return;
12502
+ patchCodegenUiState(widgetId, { generateCodeStatus: 'Preview ready' });
12503
+ getChatMethodsForWidget(widgetId)?.updateLatestCodegenStatusMessage?.('Preview ready');
12504
+ }
12505
+
12248
12506
  function getOperationPreviewBuildError(metadata?: Record<string, unknown>): string | null {
12249
12507
  if (!metadata) return null;
12250
12508
  const raw = metadata.previewBuildError ?? metadata.preview_build_error;
@@ -12331,6 +12589,13 @@ Requirements:
12331
12589
  // reaches the API from the watchdog. Ordinary progress does not.
12332
12590
  }
12333
12591
 
12592
+ function readGenerationStreamTail(op: OperationStatus): string {
12593
+ const metadata = op.metadata;
12594
+ if (!metadata) return '';
12595
+ const raw = metadata.streamTail ?? metadata.stream_tail;
12596
+ return typeof raw === 'string' ? raw.slice(-1600) : '';
12597
+ }
12598
+
12334
12599
  function pushCodegenProgressToUi(op: OperationStatus, widgetId: string | null | undefined) {
12335
12600
  const line = formatCodegenProgressStatus(op);
12336
12601
  freezeProbe('progress', line);
@@ -12340,7 +12605,14 @@ Requirements:
12340
12605
  // SSE progress frames can arrive many times per second while the LLM
12341
12606
  // streams. Each one re-renders every open panel — coalesce them.
12342
12607
  if (widgetId) {
12343
- scheduleCodegenStatusPush(widgetId, line);
12608
+ const status = String(op.status || '').toLowerCase();
12609
+ if (status === 'completed' || status === 'failed' || status === 'cancelled') {
12610
+ delete codegenStreamPending[widgetId];
12611
+ clearGenerationStream(widgetId);
12612
+ scheduleCodegenStatusPush(widgetId, line);
12613
+ } else {
12614
+ scheduleCodegenStatusPush(widgetId, line, readGenerationStreamTail(op));
12615
+ }
12344
12616
  }
12345
12617
  scheduleCodegenChatStatusPush(widgetId, line);
12346
12618
  }
@@ -12348,18 +12620,32 @@ Requirements:
12348
12620
  const CODEGEN_STATUS_THROTTLE_MS = 400;
12349
12621
  const codegenStatusTimers: Record<string, ReturnType<typeof setTimeout>> = {};
12350
12622
  const codegenStatusPendingLine: Record<string, string> = {};
12623
+ const codegenStreamPending: Record<string, string> = {};
12351
12624
  const codegenChatStatusTimers: Record<string, ReturnType<typeof setTimeout>> = {};
12352
12625
  const codegenChatStatusPendingLine: Record<string, string> = {};
12353
12626
 
12627
+ function clearGenerationStream(widgetId: string): void {
12628
+ if (!generationStreamByWidgetId[widgetId]) return;
12629
+ const next = { ...generationStreamByWidgetId };
12630
+ delete next[widgetId];
12631
+ generationStreamByWidgetId = next;
12632
+ }
12633
+
12354
12634
  /** At most one panel status write per widget per interval; trailing line always lands. */
12355
- function scheduleCodegenStatusPush(widgetId: string, line: string): void {
12635
+ function scheduleCodegenStatusPush(widgetId: string, line: string, streamTail = ''): void {
12356
12636
  codegenStatusPendingLine[widgetId] = line;
12637
+ if (streamTail) codegenStreamPending[widgetId] = streamTail;
12357
12638
  if (codegenStatusTimers[widgetId]) return;
12358
12639
  codegenStatusTimers[widgetId] = setTimeout(() => {
12359
12640
  delete codegenStatusTimers[widgetId];
12360
12641
  const pending = codegenStatusPendingLine[widgetId];
12642
+ const pendingTail = codegenStreamPending[widgetId];
12361
12643
  delete codegenStatusPendingLine[widgetId];
12644
+ delete codegenStreamPending[widgetId];
12362
12645
  if (pending) patchCodegenUiState(widgetId, { generateCodeStatus: pending });
12646
+ if (pendingTail && pendingTail !== generationStreamByWidgetId[widgetId]) {
12647
+ generationStreamByWidgetId = { ...generationStreamByWidgetId, [widgetId]: pendingTail };
12648
+ }
12363
12649
  }, CODEGEN_STATUS_THROTTLE_MS);
12364
12650
  }
12365
12651
 
@@ -13199,6 +13485,10 @@ Requirements:
13199
13485
  const workerUrl = hasCode
13200
13486
  ? `${widgetBuilderPreviewBaseUrl()}/preview/${widgetId}`
13201
13487
  : null;
13488
+ const runningPreview = runningWorkerPreviewUrlByWidgetId[widgetId] || null;
13489
+ // The poll learned this URL while the save was still running. The version menu
13490
+ // can already name the commit; the shape must not wait for that row's own build.
13491
+ if (runningPreview && generatingWidgetIds[widgetId]) return runningPreview;
13202
13492
 
13203
13493
  if (source.startsWith('v:')) {
13204
13494
  const version = parseInt(source.slice(2), 10);
@@ -13236,7 +13526,21 @@ Requirements:
13236
13526
  ) {
13237
13527
  return workerUrl;
13238
13528
  }
13239
- return resolveWidgetShapeVersionPreviewState(widgetId)?.url ?? null;
13529
+ const isolatedUrl = resolveWidgetShapeVersionPreviewState(widgetId)?.url ?? null;
13530
+ if (isolatedUrl) return isolatedUrl;
13531
+ // The generation that just finished already published a Worker document.
13532
+ // A history row whose commit has not caught up yet must not hide that document.
13533
+ // A restored version stays on its own build: the shared URL would be the wrong commit.
13534
+ if (
13535
+ runningPreview
13536
+ && !isPublished
13537
+ && newestDraft != null
13538
+ && version === newestDraft
13539
+ && restoredViewingVersionByWidgetId[widgetId] == null
13540
+ ) {
13541
+ return runningPreview;
13542
+ }
13543
+ return null;
13240
13544
  }
13241
13545
  return null;
13242
13546
  }
@@ -13385,8 +13689,37 @@ Requirements:
13385
13689
  panelDisplayRevision += 1;
13386
13690
  }
13387
13691
 
13388
- function handleWidgetShapeVersionChange(widgetId: string, versionId: string, buildPreview = true): void {
13692
+ /** Switch Version paints into a widget shape. After a sketch restore that shape is gone, so put it back first. */
13693
+ async function ensureWidgetShapeOnCanvas(widgetId: string): Promise<void> {
13694
+ if (!canvasRef?.getLinkedWidgetIds || !widgetId) return;
13695
+ if (canvasRef.getLinkedWidgetIds().has(widgetId)) return;
13696
+ const board = canvasRef.saveCanvas?.() ?? null;
13697
+ if (board && !sketchSnapshotsByWidgetId.get(widgetId)) {
13698
+ sketchSnapshotsByWidgetId.set(widgetId, board);
13699
+ }
13700
+ const absorber = canvasRef as typeof canvasRef & {
13701
+ absorbCanvasSketchIntoWidget?: (id: string, screenshotDataUrl: string) => Promise<string | null>;
13702
+ };
13703
+ try {
13704
+ if (embedded && !canvasAdvancedFeatures && absorber.absorbCanvasSketchIntoWidget) {
13705
+ await absorber.absorbCanvasSketchIntoWidget(widgetId, '');
13706
+ } else {
13707
+ canvasRef.addWidgetShape?.(widgetId, getWidgetById(widgetId)?.name, 0, 1, null);
13708
+ }
13709
+ if (!canvasRef.getLinkedWidgetIds().has(widgetId)) {
13710
+ canvasRef.addWidgetShape?.(widgetId, getWidgetById(widgetId)?.name, 0, 1, null);
13711
+ }
13712
+ canvasRef.saveNow?.();
13713
+ syncWidgetShapeLivePreviews();
13714
+ console.log('[VersionPreview] Widget shape put back on the board', widgetId.substring(0, 8));
13715
+ } catch (error) {
13716
+ console.warn('[VersionPreview] Could not put the widget shape back', error);
13717
+ }
13718
+ }
13719
+
13720
+ async function handleWidgetShapeVersionChange(widgetId: string, versionId: string, buildPreview = true): Promise<void> {
13389
13721
  if (!versionId) return;
13722
+ await ensureWidgetShapeOnCanvas(widgetId);
13390
13723
  // Both dropdowns show the pick. Only the dropdown the user clicked reloads the preview.
13391
13724
  selectVersionInDropdowns(widgetId, versionId);
13392
13725
  if (!buildPreview) return;
@@ -16323,6 +16656,38 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16323
16656
  * Marks the canvas as ready; actual state loading happens in loadCanvasState()
16324
16657
  * which is called after loadCurrentCanvas() resolves canvasId.
16325
16658
  */
16659
+ let simpleCanvasChatKey = '';
16660
+
16661
+ /** Simple canvas: one chat, always. The draft id stands in until the first Send creates the widget. */
16662
+ async function ensureSimpleCanvasChat(): Promise<void> {
16663
+ if (!embedded || canvasAdvancedFeatures || !canvasComponentReady) return;
16664
+ if (finalizingDraftConversions.size > 0) return;
16665
+ const primaryId = (canvasPrimaryWidgetId || '').trim();
16666
+ const targetId = primaryId || CANVAS_SKETCH_DRAFT_ID;
16667
+ const key = `${canvasId || 'pending'}:${targetId}`;
16668
+ if (simpleCanvasChatKey === key && openWidgetPanelIds.includes(targetId)) return;
16669
+ simpleCanvasChatKey = key;
16670
+ try {
16671
+ if (primaryId && openWidgetPanelIds.includes(CANVAS_SKETCH_DRAFT_ID)) {
16672
+ closeWidgetDetailsPanel(CANVAS_SKETCH_DRAFT_ID, { fromShapeSwitch: true });
16673
+ }
16674
+ if (!openWidgetPanelIds.includes(targetId)) {
16675
+ await openWidgetDetailsPanel(targetId);
16676
+ } else if (focusedPanelWidgetId !== targetId) {
16677
+ focusWidgetPanel(targetId);
16678
+ }
16679
+ } catch (chatError) {
16680
+ console.warn('[CreatorApp] Could not open the canvas chat', chatError);
16681
+ }
16682
+ }
16683
+
16684
+ $: if (embedded && !canvasAdvancedFeatures && canvasComponentReady && isCanvasStateLoaded) {
16685
+ const simpleChatTarget = (canvasPrimaryWidgetId || '').trim() || CANVAS_SKETCH_DRAFT_ID;
16686
+ if (!openWidgetPanelIds.includes(simpleChatTarget)) {
16687
+ void ensureSimpleCanvasChat();
16688
+ }
16689
+ }
16690
+
16326
16691
  async function handleCanvasReady() {
16327
16692
  markCanvasOpenStep('creator:canvas-ready');
16328
16693
  // console.log('[WidgetCreator] Canvas component ready');
@@ -16338,6 +16703,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16338
16703
  placeSelectedWidgetShapeOnCanvas();
16339
16704
  }
16340
16705
  syncWidgetShapeLivePreviews();
16706
+ void ensureSimpleCanvasChat();
16341
16707
  return;
16342
16708
  }
16343
16709
  const { loaded, widgetIds: widgetIdsOnCanvas } = await tryLoadCanvasState();
@@ -16347,6 +16713,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16347
16713
  scheduleCanvasHydrateRetry('canvas ready before canvasId');
16348
16714
  }
16349
16715
  syncWidgetShapeLivePreviews();
16716
+ void ensureSimpleCanvasChat();
16350
16717
  return;
16351
16718
  }
16352
16719
  await syncWidgetsWithCanvas(widgetIdsOnCanvas);
@@ -16361,6 +16728,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16361
16728
  setTimeout(() => applyPrimarySelectionOnCanvas(primaryId), 80);
16362
16729
  });
16363
16730
  syncWidgetShapeLivePreviews();
16731
+ void ensureSimpleCanvasChat();
16364
16732
  }
16365
16733
 
16366
16734
  /**
@@ -16996,7 +17364,13 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16996
17364
  name: draftName,
16997
17365
  type: 'widget',
16998
17366
  // Canvas sketch snapshot is stored on the widget for future reference
16999
- content: { source: 'canvas_convert', prompt },
17367
+ content: {
17368
+ source: embedded && !canvasAdvancedFeatures ? 'canvas_sketch' : 'canvas_convert',
17369
+ prompt,
17370
+ ...(draftConvertSketchJson.get(draftId) && (draftConvertSketchJson.get(draftId)?.length ?? 0) < 400000
17371
+ ? { sketchCanvasJson: draftConvertSketchJson.get(draftId) }
17372
+ : {}),
17373
+ },
17000
17374
  isDraft: true,
17001
17375
  // (No `description`: a new widget has no such field, the API ignored it, and a partner's session is
17002
17376
  // refused for sending a field it may not write.)
@@ -17020,6 +17394,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17020
17394
  return null;
17021
17395
  }
17022
17396
  const widgetId: string = newWidget.id;
17397
+ const sketchJson = draftConvertSketchJson.get(draftId);
17398
+ if (sketchJson) sketchSnapshotsByWidgetId.set(widgetId, sketchJson);
17023
17399
 
17024
17400
  // Add to widgets list so getWidgetById resolves the real widget from now on.
17025
17401
  widgets = [{ ...newWidget }, ...widgets.filter((w) => w.id !== draftId)];
@@ -17033,9 +17409,23 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17033
17409
 
17034
17410
  // Replace the grouped sketch with a WidgetShape screenshot. On failure
17035
17411
  // fall back to linking the sketch object to the widget id.
17036
- if (canvasRef && canvasObjectId) {
17412
+ const sketchCanvas = canvasRef as (typeof canvasRef & {
17413
+ absorbCanvasSketchIntoWidget?: (widgetId: string, screenshotDataUrl: string) => Promise<string | null>;
17414
+ }) | null;
17415
+ let placedShapeId: string | null = null;
17416
+ if (embedded && !canvasAdvancedFeatures && sketchCanvas?.absorbCanvasSketchIntoWidget) {
17417
+ try {
17418
+ placedShapeId = await sketchCanvas.absorbCanvasSketchIntoWidget(widgetId, screenshot);
17419
+ setTimeout(() => {
17420
+ canvasRef?.saveNow?.();
17421
+ }, 800);
17422
+ } catch (absorbError) {
17423
+ console.warn('[CreatorApp] Whole-canvas sketch absorb failed:', absorbError);
17424
+ }
17425
+ } else if (canvasRef && canvasObjectId) {
17037
17426
  try {
17038
17427
  await canvasRef.replaceObjectWithWidgetImage(canvasObjectId, widgetId, screenshot);
17428
+ placedShapeId = canvasObjectId;
17039
17429
  // console.log('[WidgetCreator] Sketch replaced with WidgetShape screenshot');
17040
17430
  // Flush the canvas AFTER the WidgetShape image fields are set
17041
17431
  // (synchronous in replaceObjectWithWidgetImage). saveNow bypasses
@@ -17046,12 +17436,24 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17046
17436
  } catch (replaceErr) {
17047
17437
  console.warn('[WidgetCreator] Sketch replace failed (falling back to link):', replaceErr);
17048
17438
  canvasRef.linkFrameToWidget(canvasObjectId, widgetId);
17439
+ placedShapeId = canvasObjectId;
17049
17440
  setTimeout(() => {
17050
17441
  canvasRef?.saveNow?.();
17051
17442
  }, 800);
17052
17443
  }
17053
17444
  }
17054
17445
 
17446
+ // A text-only prompt leaves the board empty, and the published canvas
17447
+ // then absorbs nothing. The preview iframe needs a frame anyway.
17448
+ if (!placedShapeId && canvasRef?.addWidgetShape && !canvasRef.getLinkedWidgetIds?.().has(widgetId)) {
17449
+ placedShapeId = canvasRef.addWidgetShape(widgetId, newWidget.name || undefined, 0, 1, screenshot || null);
17450
+ console.log('[CreatorApp] Placed a preview frame — the board had no sketch', widgetId.substring(0, 8));
17451
+ setTimeout(() => {
17452
+ canvasRef?.saveNow?.();
17453
+ }, 800);
17454
+ }
17455
+ syncWidgetShapeLivePreviews();
17456
+
17055
17457
  if (screenshot) {
17056
17458
  void persistWidgetListThumbnail(widgetId, screenshot);
17057
17459
  }
@@ -17819,7 +18221,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17819
18221
 
17820
18222
 
17821
18223
  <!-- Widgetic Canvas Editor - Full width background (lazy-loaded) -->
17822
- <div class="wc-canvas-area flex-1 min-h-0 relative">
18224
+ <div class="wc-canvas-area flex-1 min-h-0 relative {embedded && !canvasAdvancedFeatures ? 'pe-[480px]' : ''}">
17823
18225
  <!-- Embedded: Debug toggle lives in site AppHeader (avoids overlapping Props Panel). -->
17824
18226
  {#if canvasApiLoadError || canvasShapesMissingWarning}
17825
18227
  <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">
@@ -17881,6 +18283,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17881
18283
  widgetNameRevision={widgetNamesRevision}
17882
18284
  isWidgetKnown={isWidgetKnownById}
17883
18285
  onNonWidgetSelected={() => {
18286
+ if (embedded && !canvasAdvancedFeatures) return;
17884
18287
  if (suppressWidgetDetailsClose || isConvertOrDraftPanelOpen()) {
17885
18288
  // console.log('[CreatorApp] Skip Widget Details close — convert/draft panel is open');
17886
18289
  return;
@@ -17908,6 +18311,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17908
18311
  <!-- W3: live iframe + drag bar on WidgetShapes (iframe interactive; body drag locked) -->
17909
18312
  <WidgetShapeLivePreviews
17910
18313
  bind:this={widgetShapeLivePreviewsRef}
18314
+ showChrome={!(embedded && !canvasAdvancedFeatures)}
17911
18315
  getRects={() => canvasRef?.listWidgetShapeScreenRects?.() ?? []}
17912
18316
  resolveUrl={resolveWidgetShapeLivePreviewUrl}
17913
18317
  resolvePreviewState={resolveWidgetShapeVersionPreviewState}
@@ -17951,6 +18355,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17951
18355
  }}
17952
18356
  onRefresh={handleWidgetShapeRefresh}
17953
18357
  isGenerating={isAnyWidgetGenerating()}
18358
+ onLiveFrameShown={noteShapePreviewShown}
17954
18359
  resolveSelectorEnabled={(widgetId) => !!selectorEnabledByWidgetId[widgetId]}
17955
18360
  resolveSelectedElements={(widgetId) => selectedElementsByWidgetId[widgetId] ?? []}
17956
18361
  onSelectWidgetElement={(widgetId, element) => handleSelectWidgetElement(widgetId, element)}
@@ -18313,6 +18718,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18313
18718
  panelTopOffset={widgetsPanelTopOffset}
18314
18719
  panelBottomMargin={embedded ? 24 : widgetsPanelBottomMargin}
18315
18720
  fillViewport={false}
18721
+ dockRight={embedded && !canvasAdvancedFeatures}
18316
18722
  showCompositionSteps={canvasAdvancedFeatures}
18317
18723
  currentStep={ps.widgetDetailsStep}
18318
18724
  on:focusPanel={() => focusWidgetPanel(panelWidgetId)}
@@ -18629,6 +19035,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18629
19035
  <span class="text-emerald-500">{isHistoryOpen && isPanelFocused ? '▲' : '▼'}</span>
18630
19036
  </button>
18631
19037
  </HoverTooltip>
19038
+ {#if !(embedded && !canvasAdvancedFeatures)}
18632
19039
  {#if panelHasUnpublishedChanges && !Number.isFinite(viewingVersion)}
18633
19040
  <button
18634
19041
  type="button"
@@ -18683,6 +19090,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18683
19090
  {isSettingLiveVersion === Number(viewingVersion) ? '...' : $t('creator.common.setLive')}
18684
19091
  </button>
18685
19092
  {/if}
19093
+ {/if}
18686
19094
  {#if isHistoryOpen && isPanelFocused}
18687
19095
  <Portal target="wc-live-history-portal-{panelWidgetId}">
18688
19096
  <button
@@ -18771,13 +19179,16 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18771
19179
  </svelte:fragment>
18772
19180
 
18773
19181
  <svelte:fragment slot="code-generation-status">
18774
- <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;">
19182
+ {#if true}
19183
+ {@const statusText = isPanelFocused ? (generateCodeStatus ?? ps.generateCodeStatus) : ps.generateCodeStatus}
19184
+ {@const hourlyLimit = isHourlyLimitText(statusText) || isHourlyLimitText(ps.lastGenerationError)}
19185
+ <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;">
18775
19186
  <div class="flex items-center justify-between gap-2 min-w-0">
18776
- <div class="generate-code-status-el text-xs flex-1 min-w-0 truncate {ps.lastGenerationFailed ? 'text-red-600' : 'text-gray-500'}">
18777
- {#if ps.lastGenerationFailed}
19187
+ <div class="generate-code-status-el text-xs flex-1 min-w-0 truncate {ps.lastGenerationFailed && !hourlyLimit ? 'text-red-600' : 'text-gray-500'}">
19188
+ {#if ps.lastGenerationFailed && !hourlyLimit}
18778
19189
  <span class="text-red-500 font-medium">{$t('creator.codegen.generationFailed')}</span>
18779
19190
  {:else}
18780
- <span class="text-gray-400">{$t('creator.status.label')}</span> {statusLabel(isPanelFocused ? (generateCodeStatus ?? ps.generateCodeStatus) : ps.generateCodeStatus, $t)}
19191
+ <span class="text-gray-400">{$t('creator.status.label')}</span> {hourlyLimit ? $t('creator.status.ready') : statusLabel(statusText, $t)}
18781
19192
  {/if}
18782
19193
  </div>
18783
19194
  </div>
@@ -18808,7 +19219,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18808
19219
  </div>
18809
19220
  </div>
18810
19221
  {/if}
18811
- {#if ps.lastGenerationFailed}
19222
+ {#if ps.lastGenerationFailed && !hourlyLimit}
18812
19223
  <div class="p-3 bg-red-50 border border-red-200" style="border-radius: 0;">
18813
19224
  <p class="text-xs text-red-700 whitespace-pre-wrap">{errorLabel(ps.lastGenerationError, $t)}</p>
18814
19225
  <div class="flex gap-2 mt-3 justify-center">
@@ -18864,6 +19275,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18864
19275
  </div>
18865
19276
  {/if}
18866
19277
  </div>
19278
+ {/if}
18867
19279
  </svelte:fragment>
18868
19280
 
18869
19281
  <svelte:fragment slot="code-generation">
@@ -18990,7 +19402,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18990
19402
  onChatReady={(methods) => handleChatReady(methods, panelWidgetId)}
18991
19403
  onDraftChange={() => handleChatDraftChange(panelWidgetId)}
18992
19404
  onConversationChange={(conversationId) => handleChatConversationChange(conversationId, panelWidgetId)}
18993
- isGenerating={!!generatingWidgetIds[panelWidgetId]}
19405
+ isGenerating={!!generatingWidgetIds[panelWidgetId] && !previewUnblockedByWidgetId[panelWidgetId]}
19406
+ generationStream={generationStreamByWidgetId[panelWidgetId] || ''}
18994
19407
  onStopGeneration={() => {
18995
19408
  if (!isPanelFocused) focusWidgetPanel(panelWidgetId);
18996
19409
  // Stop belongs to the panel it was pressed in: the other panels' generations go on