@widgetic/creator 0.4.41 → 0.4.43

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.
@@ -8,6 +8,8 @@
8
8
  * COMPONENTS IMPORTS from WIDGETIC DS
9
9
  */
10
10
  import { Button, DropdownMenu, PasswordInput, showToast, Dialog, GenerateLoader, Portal } from '@widgetic/design-system/components';
11
+ import type { EmbeddedSketchMobileTab } from './embeddedSketchLayout.js';
12
+ import EmbeddedSketchViewportShell from './components/EmbeddedSketchViewportShell.svelte';
11
13
  import { LogoWidgeticType } from '@widgetic/design-system/icons';
12
14
 
13
15
  /**
@@ -39,6 +41,11 @@
39
41
  import type { SelectedWidgetElementReference } from './utils/widgetElementSelector.js';
40
42
  import BrandKitPanel from './components/BrandKitPanel.svelte';
41
43
  import { brandKitForRequest } from './generation/brandKitForRequest.js';
44
+ import {
45
+ shouldHideSketchOnBoard,
46
+ sketchCanvasJsonWithinPersistLimit,
47
+ widgetPanelIndicatesBuiltArtifact,
48
+ } from './sketchBoardVisibility.js';
42
49
 
43
50
  /**
44
51
  * Idempotency middleware (Phase 2 hardening): the gateway rejects
@@ -202,6 +209,18 @@
202
209
  type VersionRating
203
210
  } from './utils/versionRatings.js';
204
211
  import { generationVersionAndDocumentFields } from './utils/generationRequestFields.js';
212
+ import {
213
+ readGenerationStreamTail,
214
+ readPlanFromMetadata,
215
+ readThinkingTail,
216
+ type GenerationPlanWire,
217
+ } from './utils/codegenStatusTails.js';
218
+ import {
219
+ countDrawnCanvasObjectsInJson,
220
+ decideSketchDraftPrefill,
221
+ resolveSketchGenerateCodePrompt,
222
+ shouldScanBoardForSketchPrefill,
223
+ } from './sketchChatDraftPrefill.js';
205
224
  import {
206
225
  generationRefusalText,
207
226
  headCommitForComparison,
@@ -875,6 +894,31 @@
875
894
  return partnerMode && err instanceof ResponseError && err.response?.status === 404;
876
895
  }
877
896
 
897
+ function canvasReadStatus(err: unknown): number | null {
898
+ return err instanceof ResponseError ? (err.response?.status ?? null) : null;
899
+ }
900
+
901
+ /** 401 and 403 are the answer. Asking again only delays the message on screen. */
902
+ function canvasReadWillNotChange(err: unknown): boolean {
903
+ const status = canvasReadStatus(err);
904
+ return status === 401 || status === 403 || saysCanvasIsMissing(err);
905
+ }
906
+
907
+ /** Stops the load retries and shows the API's own sentence. */
908
+ function stopAskingForCanvas(err: unknown, message: string): void {
909
+ if (canvasUnavailable) return;
910
+ canvasUnavailable = true;
911
+ clearCanvasLoadFailsafe();
912
+ clearCanvasHydrateRetry();
913
+ canvasApiLoadError = message;
914
+ const status = canvasReadStatus(err);
915
+ reportCanvasUnavailable({
916
+ canvasId: canvasId || null,
917
+ message,
918
+ code: status === 403 ? 'FORBIDDEN' : status === 401 ? 'UNAUTHORIZED' : 'NOT_FOUND',
919
+ });
920
+ }
921
+
878
922
  /** Credits left and days left, from the same billing status the publish gate uses. */
879
923
  async function refreshTrialCounter() {
880
924
  // An account matter: a visitor of a partner has no trial and no balance of their own to show.
@@ -973,7 +1017,7 @@
973
1017
  import type { DropdownItem } from './components/SelectorDropdown.svelte';
974
1018
  import WidgetShapeLivePreviews from './components/WidgetShapeLivePreviews.svelte';
975
1019
  import HoverTooltip from './components/HoverTooltip.svelte';
976
- import VersionDropdownRow from './components/VersionDropdownRow.svelte';
1020
+ import VersionDropdownRow, { revealSelectedVersion } from './components/VersionDropdownRow.svelte';
977
1021
  // Type-only: erased at compile time, so the component's code is still
978
1022
  // dynamically imported below — this line exists so the ref types below can
979
1023
  // derive from the component's REAL class instead of the `any` a dynamic
@@ -1481,6 +1525,8 @@
1481
1525
  const publishRevealTimers = new Map<string, ReturnType<typeof setTimeout>>();
1482
1526
  /** Last slice of the model stream, per widget. Painted with the status throttle, not per token. */
1483
1527
  let generationStreamByWidgetId: Record<string, string> = {};
1528
+ let generationThinkingByWidgetId: Record<string, string> = {};
1529
+ let generationPlanByWidgetId: Record<string, GenerationPlanWire> = {};
1484
1530
  function isAnyWidgetGenerating(): boolean {
1485
1531
  return isGeneratingCode || Object.keys(generatingWidgetIds).some((id) => generatingWidgetIds[id]);
1486
1532
  }
@@ -1576,6 +1622,40 @@
1576
1622
  /** Fabric JSON of the board, kept so the first checkpoint can put the sketch back. */
1577
1623
  const draftConvertSketchJson = new Map<string, string>();
1578
1624
  const sketchSnapshotsByWidgetId = new Map<string, string>();
1625
+
1626
+ function widgetBuiltForSketchHiding(widgetId: string): boolean {
1627
+ if (isDraftConvertId(widgetId)) return false;
1628
+ return widgetPanelIndicatesBuiltArtifact(getPanelState(widgetId));
1629
+ }
1630
+
1631
+ function rememberSketchSnapshotForWidget(widgetId: string, json: string | null | undefined): void {
1632
+ if (!widgetId || !sketchCanvasJsonWithinPersistLimit(json)) return;
1633
+ if (!sketchSnapshotsByWidgetId.has(widgetId)) {
1634
+ sketchSnapshotsByWidgetId.set(widgetId, json);
1635
+ }
1636
+ }
1637
+
1638
+ /** Simple canvas: stash the sketch for restore, then show only the widget shape on the board. */
1639
+ function hideSketchOnBoardForWidget(widgetId: string): void {
1640
+ if (!shouldHideSketchOnBoard({
1641
+ embedded,
1642
+ advancedFeatures: canvasAdvancedFeatures,
1643
+ isDraftConvertId: isDraftConvertId(widgetId),
1644
+ widgetHasBuiltArtifact: widgetBuiltForSketchHiding(widgetId),
1645
+ })) return;
1646
+ if (!canvasRef) return;
1647
+ const board = canvasRef.saveCanvas?.() ?? null;
1648
+ rememberSketchSnapshotForWidget(widgetId, board);
1649
+ const pruner = canvasRef as typeof canvasRef & {
1650
+ removeSketchObjectsKeepingWidget?: (id: string) => number;
1651
+ };
1652
+ const removed = pruner.removeSketchObjectsKeepingWidget?.(widgetId) ?? 0;
1653
+ if (removed > 0) {
1654
+ canvasRef.saveNow?.();
1655
+ syncWidgetShapeLivePreviews();
1656
+ console.log('[CreatorApp] Sketch hidden on board after build', widgetId.substring(0, 8), removed);
1657
+ }
1658
+ }
1579
1659
  /** True while a draft conversion is being finalized (widget creation + shape replace). */
1580
1660
  const finalizingDraftConversions = new Set<string>();
1581
1661
  /** Keep Widget Details on this convert/draft widget until the user closes the panel. */
@@ -1619,6 +1699,16 @@
1619
1699
  let promptLoadedForWidgetId: string | null = null;
1620
1700
  /** Skip draft→prompt sync while restoring chat draft (avoids clearing promptImages). */
1621
1701
  let suppressChatDraftSync = false;
1702
+ /** Sketch prefill: applied once per sketch session until the canvas clears or the user edits the draft. */
1703
+ let sketchPrefillApplied = false;
1704
+ /** Visitor-drawn shapes only (widget shapes on the board do not count). */
1705
+ let lastDrawnObjectCount = 0;
1706
+ /** Set when a prefill apply was decided before the panel Chat exposed setDraftText. */
1707
+ let pendingSketchGeneratePrefill = false;
1708
+ /** The one pending look at the board after the canvas went dirty (see `scheduleSketchPrefillFromCanvasDirty`). */
1709
+ let sketchPrefillDirtyTimer: ReturnType<typeof setTimeout> | null = null;
1710
+ /** A short delay: it coalesces a burst of dirty events into one look, and is still well ahead of the debounced autosave. */
1711
+ const SKETCH_PREFILL_DIRTY_DELAY_MS = 120;
1622
1712
 
1623
1713
  // Current active conversation ID for the selected widget's chat.
1624
1714
  // Populated via Chat's onConversationChange callback and passed to generateCode()
@@ -1892,12 +1982,21 @@
1892
1982
  // picking up the line on the canvas instead of the widget.
1893
1983
  if (!widgetAlreadyBuilt && embedded && !canvasAdvancedFeatures && sketchCanvas?.captureCanvasSketch) {
1894
1984
  try {
1985
+ const sketchJsonBeforeSend = sketchCanvas.saveCanvas?.() ?? '';
1986
+ rememberSketchSnapshotForWidget(widgetId, sketchJsonBeforeSend);
1895
1987
  const canvasSketch = await sketchCanvas.captureCanvasSketch();
1896
1988
  if (canvasSketch?.startsWith('data:image/')) {
1897
1989
  if (isDraftConvertId(widgetId)) {
1898
1990
  draftConvertScreenshots.set(widgetId, canvasSketch);
1899
- const sketchJson = sketchCanvas.saveCanvas?.() ?? '';
1900
- if (sketchJson) draftConvertSketchJson.set(widgetId, sketchJson);
1991
+ if (sketchJsonBeforeSend) draftConvertSketchJson.set(widgetId, sketchJsonBeforeSend);
1992
+ } else if (sketchCanvas.absorbCanvasSketchIntoWidget) {
1993
+ try {
1994
+ await sketchCanvas.absorbCanvasSketchIntoWidget(widgetId, canvasSketch);
1995
+ sketchCanvas.saveNow?.();
1996
+ syncWidgetShapeLivePreviews();
1997
+ } catch (absorbErr) {
1998
+ console.warn('[Chat→Sketch] Could not absorb sketch into widget shape', absorbErr);
1999
+ }
1901
2000
  }
1902
2001
  const alreadyHasImage = (attachments || []).some((attachment) =>
1903
2002
  attachment.fileType?.startsWith('image/')
@@ -2142,7 +2241,7 @@
2142
2241
  return /(?:Commit:?\s+|Code saved\s*\()[a-f0-9]{7,40}/i.test(String(content || ''));
2143
2242
  }
2144
2243
 
2145
- /** Retry failed codegen without duplicating the user bubble. A successful prompt forks a new message so each version can show "You are here". */
2244
+ /** Retry failed codegen without duplicating the user bubble. A successful prompt forks a new message so each version has its own turn. */
2146
2245
  async function handleChatRetryMessage(content: string, sourceWidgetId?: string) {
2147
2246
  const widgetId = sourceWidgetId ?? selectedWidgetId;
2148
2247
  if (!widgetId) return;
@@ -2161,7 +2260,7 @@
2161
2260
  const draftImageUrls = panelChat?.getAttachmentDataUrls?.() ?? [];
2162
2261
 
2163
2262
  // A prompt that already has a commit must not reuse that bubble: Version N and
2164
- // Version N+1 would share one message, and "You are here" could not mark the older one.
2263
+ // Version N+1 would share one message, and the older version would have no turn of its own.
2165
2264
  // The pictures of that sentence go with the retry, including when an earlier
2166
2265
  // copy of the same sentence is the one that still has them.
2167
2266
  let forkUserMessage = false;
@@ -2415,6 +2514,115 @@
2415
2514
  }
2416
2515
  }
2417
2516
 
2517
+ function sketchPrefillTargetWidgetId(widgetId?: string | null): string | null {
2518
+ return (
2519
+ widgetId ??
2520
+ focusedPanelWidgetId ??
2521
+ (canvasPrimaryWidgetId && !isDraftConvertId(canvasPrimaryWidgetId) ? canvasPrimaryWidgetId : null) ??
2522
+ (embedded && !canvasAdvancedFeatures ? CANVAS_SKETCH_DRAFT_ID : null) ??
2523
+ selectedWidgetId ??
2524
+ null
2525
+ );
2526
+ }
2527
+
2528
+ function sketchPrefillWidgetBuilt(targetWidgetId: string): boolean {
2529
+ if (!isDraftConvertId(targetWidgetId) && targetWidgetId === canvasPrimaryWidgetId) {
2530
+ return primaryWidgetHasGeneratedCode();
2531
+ }
2532
+ if (isDraftConvertId(targetWidgetId)) return false;
2533
+ const panel = getPanelState(targetWidgetId);
2534
+ return !!(panel.lastCommitId || panel.hasGeneratedCode || panel.lastPublishedVersion != null);
2535
+ }
2536
+
2537
+ /** Convert-to-widget owns the draft with CONVERT_PROMPT — never compete with generate-code prefill. */
2538
+ function sketchConvertDraftActive(targetWidgetId: string): boolean {
2539
+ if (promptLoadedForWidgetId === targetWidgetId && pendingChatDraftText === CONVERT_PROMPT) return true;
2540
+ if (codeGenerationPrompt === CONVERT_PROMPT && focusedPanelWidgetId === targetWidgetId) return true;
2541
+ return false;
2542
+ }
2543
+
2544
+ function noteDrawnObjectCount(drawnObjectCount: number) {
2545
+ if (lastDrawnObjectCount === 0 && drawnObjectCount > 0) {
2546
+ sketchPrefillApplied = false;
2547
+ }
2548
+ lastDrawnObjectCount = drawnObjectCount;
2549
+ }
2550
+
2551
+ /**
2552
+ * Faster than waiting for the debounced autosave, for ONE moment only: the first drawn object. A short coalescing timer (one look per
2553
+ * burst of dirty events, never one per event) reads the serialized board (the canvas has no "drawn objects only" count yet), and only
2554
+ * while no drawing is known and the widget is not built (`shouldScanBoardForSketchPrefill`), so drawing or dragging on a busy board
2555
+ * never costs a serialization per event. The autosave stays the source of truth for everything after (a cleared board, a typed draft).
2556
+ */
2557
+ function scheduleSketchPrefillFromCanvasDirty() {
2558
+ if (!embedded || canvasAdvancedFeatures || !canvasRef?.saveCanvas) return;
2559
+ if (sketchPrefillDirtyTimer != null) return;
2560
+ if (!shouldScanBoardForSketchPrefill({ lastDrawnObjectCount, widgetBuilt: sketchPrefillWidgetBuiltNow() })) return;
2561
+ sketchPrefillDirtyTimer = setTimeout(() => {
2562
+ sketchPrefillDirtyTimer = null;
2563
+ try {
2564
+ if (!shouldScanBoardForSketchPrefill({ lastDrawnObjectCount, widgetBuilt: sketchPrefillWidgetBuiltNow() })) return;
2565
+ const json = canvasRef?.saveCanvas?.();
2566
+ const drawn = countDrawnCanvasObjectsInJson(json);
2567
+ if (drawn === lastDrawnObjectCount) return;
2568
+ noteDrawnObjectCount(drawn);
2569
+ maybeSyncSketchGeneratePrefill();
2570
+ } catch (error) {
2571
+ console.warn('[CreatorApp] Sketch prefill dirty check failed', error);
2572
+ }
2573
+ }, SKETCH_PREFILL_DIRTY_DELAY_MS);
2574
+ }
2575
+
2576
+ /** True once the widget the prefill would be for has generated code (the prefill never applies after that). */
2577
+ function sketchPrefillWidgetBuiltNow(): boolean {
2578
+ const targetWidgetId = sketchPrefillTargetWidgetId();
2579
+ return targetWidgetId ? sketchPrefillWidgetBuilt(targetWidgetId) : false;
2580
+ }
2581
+
2582
+ function maybeSyncSketchGeneratePrefill(widgetId?: string | null) {
2583
+ if (!embedded || canvasAdvancedFeatures) return;
2584
+ const targetWidgetId = sketchPrefillTargetWidgetId(widgetId);
2585
+ if (!targetWidgetId) return;
2586
+ if (sketchConvertDraftActive(targetWidgetId)) {
2587
+ pendingSketchGeneratePrefill = false;
2588
+ return;
2589
+ }
2590
+ const widgetBuilt = sketchPrefillWidgetBuilt(targetWidgetId);
2591
+ const prefillMessage = resolveSketchGenerateCodePrompt(locale, chatMessages);
2592
+ const chat = getChatMethodsForWidget(targetWidgetId);
2593
+ const draft = chat?.getDraftText?.() ?? '';
2594
+ const action = decideSketchDraftPrefill({
2595
+ drawnObjectCount: lastDrawnObjectCount,
2596
+ widgetBuilt,
2597
+ draft,
2598
+ prefillMessage,
2599
+ prefillAppliedForSketch: sketchPrefillApplied,
2600
+ });
2601
+ if (action === 'none') {
2602
+ if (pendingSketchGeneratePrefill && (widgetBuilt || lastDrawnObjectCount <= 0)) {
2603
+ pendingSketchGeneratePrefill = false;
2604
+ }
2605
+ return;
2606
+ }
2607
+ if (!chat?.getDraftText || !chat.setDraftText) {
2608
+ if (action === 'apply') pendingSketchGeneratePrefill = true;
2609
+ return;
2610
+ }
2611
+ pendingSketchGeneratePrefill = false;
2612
+ suppressChatDraftSync = true;
2613
+ try {
2614
+ if (action === 'apply') {
2615
+ chat.setDraftText(prefillMessage);
2616
+ sketchPrefillApplied = true;
2617
+ } else if (action === 'clear') {
2618
+ chat.setDraftText('');
2619
+ sketchPrefillApplied = false;
2620
+ }
2621
+ } finally {
2622
+ suppressChatDraftSync = false;
2623
+ }
2624
+ }
2625
+
2418
2626
  function handleChatDraftChange(sourceWidgetId?: string) {
2419
2627
  const widgetId = sourceWidgetId ?? selectedWidgetId;
2420
2628
  if (suppressChatDraftSync || !widgetId) return;
@@ -3758,6 +3966,9 @@
3758
3966
  : $t('creator.codegen.widgetCodeAtCommitRefreshing', { commit: formatCommitShaShort(historicalSha) }),
3759
3967
  duration: 6000,
3760
3968
  });
3969
+ const alreadyCurrent = gitRollback?.alreadyCurrent === true || gitRollback?.already_current === true;
3970
+ const rebuiltFromFiles = gitRollback?.rebuilt === true;
3971
+ const previewWithoutGitlab = alreadyCurrent || rebuiltFromFiles;
3761
3972
  liveDesignValues = {};
3762
3973
  liveContentValues = {};
3763
3974
  liveContentItems = [];
@@ -3767,13 +3978,15 @@
3767
3978
  _isRestoringCheckpoint = true;
3768
3979
  const panelRef = panelWidgetId ? getWidgetDetailsRef(panelWidgetId) : widgetDetails;
3769
3980
  const scheduleBuildRetry = async () => {
3770
- const delays = [400, 2500, 5000, 8000];
3981
+ const delays = previewWithoutGitlab ? [400] : [400, 2500, 5000, 8000];
3771
3982
  for (let i = 0; i < delays.length; i++) {
3772
3983
  if (i > 0) await new Promise((r) => setTimeout(r, delays[i]));
3773
3984
  if (i === 0) suppressNextBuildFromRepoChatMessage = true;
3774
3985
  try {
3775
3986
  const activeRef = panelWidgetId ? getWidgetDetailsRef(panelWidgetId) : panelRef;
3776
- await activeRef?.triggerBuildFromRepo({ force: true });
3987
+ // The server already built from the files it read, or the branch was already
3988
+ // that version. Reloading the preview must not read GitLab again.
3989
+ await activeRef?.triggerBuildFromRepo(previewWithoutGitlab ? undefined : { force: true });
3777
3990
  const err = activeRef?.getPreviewError?.() ?? null;
3778
3991
  if (!err) {
3779
3992
  _isRestoringCheckpoint = false;
@@ -3803,8 +4016,14 @@
3803
4016
  console.warn('[Restore] The code was not rolled back', { widgetId: panelWidgetId, rollbackError });
3804
4017
  showToast('warning', gitlabLimited ? $t('creator.general.rateLimited') : $t('creator.version.failedToRestoreCheckpoint'), {
3805
4018
  description: rollbackError || $t('creator.version.codeWasNotRolledBack'),
3806
- duration: 9000,
4019
+ duration: gitlabLimited ? 20000 : 9000,
3807
4020
  });
4021
+ if (gitlabLimited && panelWidgetId) {
4022
+ getChatMethodsForWidget(panelWidgetId)?.addAssistantMessage?.(
4023
+ codegenFailureChatLine(rollbackError || 'GitLab rate limit reached (429), so nothing was changed. Wait a minute and try again.'),
4024
+ true,
4025
+ );
4026
+ }
3808
4027
  return null;
3809
4028
  } else {
3810
4029
  console.warn('[Chat→Backend] Git rollback not detected in response, refreshing preview anyway...');
@@ -5419,6 +5638,7 @@
5419
5638
  }
5420
5639
  }
5421
5640
  }
5641
+ if (selectedWidgetId) void postVisitorEntriesHost(selectedWidgetId);
5422
5642
  } catch (err: any) {
5423
5643
  console.error('[Compositions] Failed to load:', err);
5424
5644
  } finally {
@@ -5496,6 +5716,86 @@
5496
5716
  resolveLiveWidgetShapeIframe(widgetId)?.contentWindow?.postMessage(message, '*');
5497
5717
  }
5498
5718
 
5719
+ /** One lookup per composition. A failed lookup is dropped so the next preview can ask again. */
5720
+ const entriesHostByCompositionId = new Map<string, Promise<{ url: string; writeToken?: string } | null>>();
5721
+
5722
+ function entriesHostForComposition(compositionId: string): Promise<{ url: string; writeToken?: string } | null> {
5723
+ const cached = entriesHostByCompositionId.get(compositionId);
5724
+ if (cached) return cached;
5725
+ const root = (apiRoot || '').replace(/\/+$/, '');
5726
+ if (!root) return Promise.resolve(null);
5727
+ const pending = (async () => {
5728
+ try {
5729
+ const response = await fetch(`${root}/embed/compositions/${compositionId}`, { cache: 'reload' });
5730
+ if (!response.ok) {
5731
+ console.warn('[CreatorApp] Visitor entries address was not available', response.status);
5732
+ entriesHostByCompositionId.delete(compositionId);
5733
+ return null;
5734
+ }
5735
+ const body = await response.json();
5736
+ const data = body?.data ?? body;
5737
+ const writeToken = data?.entries?.writeToken || data?.entryWriteToken;
5738
+ return {
5739
+ url: `${root}/embed/compositions/${compositionId}/entries`,
5740
+ ...(typeof writeToken === 'string' && writeToken ? { writeToken } : {}),
5741
+ };
5742
+ } catch (error) {
5743
+ console.warn('[CreatorApp] Visitor entries address failed', error);
5744
+ entriesHostByCompositionId.delete(compositionId);
5745
+ return null;
5746
+ }
5747
+ })();
5748
+ entriesHostByCompositionId.set(compositionId, pending);
5749
+ return pending;
5750
+ }
5751
+
5752
+ /** The composition whose table a vote from this preview should fill. The open one, else the first. */
5753
+ async function compositionIdForVisitorEntries(widgetId: string): Promise<string | null> {
5754
+ const panel = getPanelDisplayState(widgetId);
5755
+ const openId = panel?.selectedComposition?.id;
5756
+ if (typeof openId === 'string' && openId) return openId;
5757
+ if (widgetId === selectedWidgetId && typeof selectedComposition?.id === 'string' && selectedComposition.id) {
5758
+ return selectedComposition.id;
5759
+ }
5760
+ if (!compositionsClient) return null;
5761
+ try {
5762
+ const res = await compositionsClient.getAllCompositions({ widgetId });
5763
+ const rows = ((res as { data?: unknown[] })?.data ?? []) as Array<Record<string, unknown>>;
5764
+ const mine = rows.filter((row) => (row.widget_id || row.widgetId) === widgetId);
5765
+ mine.sort((a, b) => {
5766
+ const aTime = new Date(String(a.createdAt ?? a.created_at ?? 0)).getTime();
5767
+ const bTime = new Date(String(b.createdAt ?? b.created_at ?? 0)).getTime();
5768
+ return aTime - bTime;
5769
+ });
5770
+ const id = mine[0]?.id;
5771
+ return typeof id === 'string' ? id : null;
5772
+ } catch (error) {
5773
+ console.warn('[CreatorApp] Could not read the composition for visitor entries', error);
5774
+ return null;
5775
+ }
5776
+ }
5777
+
5778
+ /** Tell the canvas preview, and the side preview, where a visitor entry is saved. */
5779
+ async function postVisitorEntriesHost(widgetId: string): Promise<void> {
5780
+ if (!widgetId) return;
5781
+ const compositionId = await compositionIdForVisitorEntries(widgetId);
5782
+ if (!compositionId) return;
5783
+ const entries = await entriesHostForComposition(compositionId);
5784
+ if (!entries) return;
5785
+ const message = {
5786
+ type: 'widgetic:host',
5787
+ version: 1,
5788
+ compositionId,
5789
+ context: null,
5790
+ values: null,
5791
+ mediaResolver: null,
5792
+ entries,
5793
+ };
5794
+ getWidgetDetailsRef(widgetId)?.sendMessageToPreview(message);
5795
+ resolveLiveWidgetShapeIframe(widgetId)?.contentWindow?.postMessage(message, '*');
5796
+ console.log('[CreatorApp] Told the preview where visitor entries are saved');
5797
+ }
5798
+
5499
5799
  /** Push composition overlay to a specific panel preview iframe. */
5500
5800
  function applyPanelCompositionToPreview(widgetId: string): void {
5501
5801
  const panelRef = getWidgetDetailsRef(widgetId);
@@ -6021,6 +6321,9 @@
6021
6321
 
6022
6322
  // debugMode — current ON/OFF state. User can still toggle when the UI is available.
6023
6323
  let debugMode = debugModeAvailable;
6324
+ /** Mobile embedded sketch: Canvas | Chat tabs (both panes stay mounted; CSS hides the inactive one). */
6325
+ let embeddedSketchMobileTab: EmbeddedSketchMobileTab = 'canvas';
6326
+ $: embeddedSketchShell = embedded && !canvasAdvancedFeatures;
6024
6327
  if (debugModeAvailable && typeof window !== 'undefined') {
6025
6328
  try {
6026
6329
  const storedDebugMode = creatorStorage.getItem('widgetic:site-debug-on');
@@ -6236,6 +6539,50 @@
6236
6539
  let canvasPrimaryWidgetId: string | null = null;
6237
6540
  /** Restore Checkpoint back to the sketch brings the drawing tools back until the next generation. */
6238
6541
  let sketchToolbarAfterRestore = false;
6542
+ /**
6543
+ * Single-widget canvases hide both bottom bars until the primary widget has been read.
6544
+ * Otherwise the drawing toolbar flashes, then the selector replaces it.
6545
+ */
6546
+ let singleWidgetChromeReady = false;
6547
+
6548
+ /**
6549
+ * Lets the bottom bars appear once the canvas component is up and the canvas has been read.
6550
+ * `handleCanvasReady` does it for a canvas whose id was already known when the canvas component came up.
6551
+ * A canvas whose id is resolved afterwards (the person's latest canvas, the one remembered from the last
6552
+ * visit, or the blank one made for a person who has none) is read or made by other code, so that ends here
6553
+ * too: without it neither bar ever appeared on such a canvas, and the person had no tools and no selector.
6554
+ */
6555
+ function releaseSingleWidgetChrome(): void {
6556
+ if (singleWidgetChromeReady || !canvasComponentReady || !isCanvasStateLoaded) return;
6557
+ singleWidgetChromeReady = true;
6558
+ console.log('[CreatorApp] Bottom bars released after the canvas was read', { canvasId, primaryId: canvasPrimaryWidgetId });
6559
+ }
6560
+
6561
+ // Whichever code made the canvas known, a canvas that is up, read, and has its primary widget gets its bar.
6562
+ $: if (!singleWidgetChromeReady && canvasComponentReady && isCanvasStateLoaded && !!(canvasPrimaryWidgetId || '').trim()) {
6563
+ releaseSingleWidgetChrome();
6564
+ }
6565
+
6566
+ /**
6567
+ * A net under all of the above: no way of loading a canvas may leave the person without bars for good.
6568
+ * Once the canvas is up and read, the bars come at the latest after this wait, even if none of the places that
6569
+ * release them ran. The person may then see the drawing tools first and the selector a moment later, as every
6570
+ * version before the bars waited for the widget showed them.
6571
+ */
6572
+ const SINGLE_WIDGET_CHROME_FAILSAFE_MS = 2500;
6573
+ let singleWidgetChromeFailsafeTimer: ReturnType<typeof setTimeout> | null = null;
6574
+
6575
+ function armSingleWidgetChromeFailsafe(): void {
6576
+ if (singleWidgetChromeFailsafeTimer) return;
6577
+ singleWidgetChromeFailsafeTimer = setTimeout(() => {
6578
+ singleWidgetChromeFailsafeTimer = null;
6579
+ if (singleWidgetChromeReady) return;
6580
+ console.warn('[CreatorApp] Bottom bars released by the failsafe: no step of loading the canvas released them');
6581
+ releaseSingleWidgetChrome();
6582
+ }, SINGLE_WIDGET_CHROME_FAILSAFE_MS);
6583
+ }
6584
+
6585
+ $: if (!singleWidgetChromeReady && canvasComponentReady && isCanvasStateLoaded) armSingleWidgetChromeFailsafe();
6239
6586
 
6240
6587
  function primaryWidgetHasGeneratedCode(): boolean {
6241
6588
  if (!canvasPrimaryWidgetId || isDraftConvertId(canvasPrimaryWidgetId)) return false;
@@ -6243,10 +6590,12 @@
6243
6590
  return !!(panel.hasGeneratedCode || panel.lastCommitId || panel.lastPublishedVersion != null);
6244
6591
  }
6245
6592
 
6246
- $: showDrawingTools = sketchToolbarAfterRestore || !(
6247
- panelDisplayRevision >= 0
6248
- && !!canvasPrimaryWidgetId
6249
- && primaryWidgetHasGeneratedCode()
6593
+ $: showDrawingTools = (multipleWidgetsAllowed || singleWidgetChromeReady) && (
6594
+ sketchToolbarAfterRestore || !(
6595
+ panelDisplayRevision >= 0
6596
+ && !!canvasPrimaryWidgetId
6597
+ && primaryWidgetHasGeneratedCode()
6598
+ )
6250
6599
  );
6251
6600
 
6252
6601
  function emitCreatorWireframeChanged() {
@@ -6897,6 +7246,9 @@
6897
7246
  followedGenerationWidgetIds.add(widgetId);
6898
7247
  generationOperationByWidgetId.set(widgetId, operationId);
6899
7248
  generatingWidgetIds = { ...generatingWidgetIds, [widgetId]: true };
7249
+ clearGenerationStream(widgetId);
7250
+ clearGenerationThinking(widgetId);
7251
+ clearGenerationPlan(widgetId);
6900
7252
  noteCodegenActive(true);
6901
7253
  let endedOperation: OperationSnapshot | null = null;
6902
7254
  try {
@@ -7469,6 +7821,7 @@
7469
7821
  setTimeout(() => applyPrimarySelectionOnCanvas(primaryId), 80);
7470
7822
  });
7471
7823
  }
7824
+ releaseSingleWidgetChrome();
7472
7825
  return;
7473
7826
  }
7474
7827
  }
@@ -7495,6 +7848,7 @@
7495
7848
  setTimeout(() => applyPrimarySelectionOnCanvas(primaryId), 80);
7496
7849
  });
7497
7850
  }
7851
+ releaseSingleWidgetChrome();
7498
7852
  } catch (error) {
7499
7853
  console.error('Widget Creator: Load canvases error:', error);
7500
7854
  const defaultError = $t('creator.canvas.failedToLoadCanvases');
@@ -7569,6 +7923,7 @@
7569
7923
  // widget_id belonging to the previous canvas.
7570
7924
  routeCanvasId = entry.id;
7571
7925
  canvasPrimaryWidgetId = null;
7926
+ singleWidgetChromeReady = false;
7572
7927
  syncUrlCanvasId(entry.id);
7573
7928
 
7574
7929
  // Clear existing widgets and canvas visually
@@ -7907,6 +8262,8 @@
7907
8262
  canvasRef?.onClearAllObjects();
7908
8263
  lastSavedCanvasObjectCount = 0;
7909
8264
  markCanvasStateLoaded();
8265
+ // The canvas is empty: no widget to wait for.
8266
+ releaseSingleWidgetChrome();
7910
8267
  // console.log('[WidgetCreator] New canvas ready:', createdId);
7911
8268
  return createdId;
7912
8269
  }
@@ -7946,6 +8303,8 @@
7946
8303
  } finally {
7947
8304
  markCanvasStateLoaded();
7948
8305
  isLoadingWidgets = false;
8306
+ // A blank canvas has no widget to wait for: the person gets the drawing tools.
8307
+ releaseSingleWidgetChrome();
7949
8308
  }
7950
8309
  })();
7951
8310
  return blankCanvasEnsurePromise;
@@ -7956,6 +8315,7 @@
7956
8315
  // console.log('[CreatorApp] bootstrapEmbeddedNewWidget already ran — skip');
7957
8316
  isLoadingWidgets = false;
7958
8317
  markCanvasStateLoaded();
8318
+ releaseSingleWidgetChrome();
7959
8319
  return;
7960
8320
  }
7961
8321
  didForceCreateNewWidget = true;
@@ -7977,6 +8337,8 @@
7977
8337
  lastSavedCanvasObjectCount = 0;
7978
8338
  markCanvasStateLoaded();
7979
8339
  isLoadingWidgets = false;
8340
+ // A new widget starts on an empty canvas: nothing to wait for, so the drawing tools come at once.
8341
+ releaseSingleWidgetChrome();
7980
8342
  setTimeout(() => {
7981
8343
  ignoreIncomingCanvasLoads = false;
7982
8344
  // console.log('[CreatorApp] New-widget canvas lock released');
@@ -9364,9 +9726,9 @@
9364
9726
  publishHistoryResolvedForWidgetId: widget.id,
9365
9727
  });
9366
9728
  }
9367
- // Reconcile GitLab HEAD whenever we have a repo — unpublished widgets
9368
- // also need lastCommitId so Create preview is not stuck on "No Code Yet".
9369
- if (currentRepositoryId) {
9729
+ // The version menu is the database history. GitLab is asked for HEAD only when this
9730
+ // browser has no commit yet, so a first open on another machine can leave "No Code Yet".
9731
+ if (currentRepositoryId && !lastCommitId) {
9370
9732
  void reconcileWidgetHeadCommit(widget.id);
9371
9733
  }
9372
9734
  }
@@ -10207,6 +10569,9 @@
10207
10569
  chatMethods = methods;
10208
10570
  restoreChatDraftFromStorage();
10209
10571
  }
10572
+ if (pendingSketchGeneratePrefill || (embedded && !canvasAdvancedFeatures)) {
10573
+ maybeSyncSketchGeneratePrefill(ownerWidgetId);
10574
+ }
10210
10575
  // console.log('[Chat] Chat ready for widget', ownerWidgetId?.substring(0, 8), 'methods exposed');
10211
10576
 
10212
10577
  // A console helper of Widgetic's own pages; a partner's page gets no globals from the creator.
@@ -11096,6 +11461,9 @@ Requirements:
11096
11461
  generationOperationByWidgetId.delete(generationWidgetId);
11097
11462
 
11098
11463
  generatingWidgetIds = { ...generatingWidgetIds, [generationWidgetId]: true };
11464
+ clearGenerationStream(generationWidgetId);
11465
+ clearGenerationThinking(generationWidgetId);
11466
+ clearGenerationPlan(generationWidgetId);
11099
11467
  // The preview address does not change between builds. Without this, the next build
11100
11468
  // is treated as the one already on the shape, and the shape keeps the previous document.
11101
11469
  lastRunningPreviewKey = '';
@@ -11351,6 +11719,10 @@ Requirements:
11351
11719
  });
11352
11720
  // Stopped, or replaced, while the request was being prepared: no job is started for a run nobody waits for
11353
11721
  if (signal.aborted) return;
11722
+ // PLAN UI (metadata.plan): do not send `clientCapabilities` here yet. Shopify/editor-session
11723
+ // `POST /agent/code/generate` rejects any body key outside `EDITOR_SESSION_CREATOR_WRITABLE_FIELDS.codeGenerate`
11724
+ // (`editorSessionSurfaces.ts`); `clientCapabilities` is not on that list until the gateway owner adds it.
11725
+ // Once it is listed and plan policy is switched on, add e.g. `clientCapabilities: { plan: true }` beside the fields below.
11354
11726
  // The generated client types this call as void and drops the 202 body.
11355
11727
  // Read the raw JSON so operationId and the intent-gate payload survive.
11356
11728
  const accepted = await agentClient.generateCodeRaw({
@@ -11825,16 +12197,12 @@ Requirements:
11825
12197
  setTimeout(() => alignGeneratedVersion(0), 1200);
11826
12198
  }
11827
12199
 
11828
- // Always reconcile GitLab HEAD after codegen (metadata.commitId can be missing/stale).
11829
- // Deferred — same window as the schema/history reloads above.
12200
+ // The generation already returned its commit. Ask GitLab for HEAD only when that commit is missing.
11830
12201
  if (generationWidgetId) {
11831
12202
  setTimeout(() => {
11832
12203
  void (async () => {
11833
12204
  try {
11834
- const fetchedHead = await fetchRepoHeadCommitSha(generationWidgetId);
11835
- // Prefer the codegen commit from the operation. GitLab HEAD can still
11836
- // be the previous live SHA for a few seconds — that used to clear
11837
- // pending publish until Widget Details was reopened.
12205
+ const fetchedHead = completedCommitSha ? null : await fetchRepoHeadCommitSha(generationWidgetId);
11838
12206
  const headSha = completedCommitSha || fetchedHead;
11839
12207
  if (!headSha) return;
11840
12208
  saveCommitIdForWidget(generationWidgetId, headSha);
@@ -11952,6 +12320,10 @@ Requirements:
11952
12320
  );
11953
12321
  }
11954
12322
 
12323
+ if (generationWidgetId && completedCommitSha) {
12324
+ hideSketchOnBoardForWidget(generationWidgetId);
12325
+ }
12326
+
11955
12327
  if (isFocusedPanel) {
11956
12328
  liveDesignValues = {};
11957
12329
  liveContentValues = {};
@@ -12644,7 +13016,10 @@ Requirements:
12644
13016
  for (const frame of frames) {
12645
13017
  if (!(frame instanceof HTMLIFrameElement) || event.source !== frame.contentWindow) continue;
12646
13018
  const widgetId = frame.dataset.widgetId;
12647
- if (widgetId) postContentItemsToPreviewFrames(widgetId);
13019
+ if (widgetId) {
13020
+ postContentItemsToPreviewFrames(widgetId);
13021
+ void postVisitorEntriesHost(widgetId);
13022
+ }
12648
13023
  }
12649
13024
  };
12650
13025
  window.addEventListener('message', onShapeWidgetReady);
@@ -12822,6 +13197,14 @@ Requirements:
12822
13197
  mountUploadAbortController?.abort();
12823
13198
  mountUploadAbortController = null;
12824
13199
  clearCanvasLoadFailsafe();
13200
+ if (singleWidgetChromeFailsafeTimer) {
13201
+ clearTimeout(singleWidgetChromeFailsafeTimer);
13202
+ singleWidgetChromeFailsafeTimer = null;
13203
+ }
13204
+ if (sketchPrefillDirtyTimer != null) {
13205
+ clearTimeout(sketchPrefillDirtyTimer);
13206
+ sketchPrefillDirtyTimer = null;
13207
+ }
12825
13208
  if (tokenCheckInterval) clearInterval(tokenCheckInterval);
12826
13209
  if (tokenDisplayInterval) clearInterval(tokenDisplayInterval);
12827
13210
  if (hydrationSafetyTimeout) clearTimeout(hydrationSafetyTimeout);
@@ -13120,6 +13503,10 @@ Requirements:
13120
13503
 
13121
13504
  /** The canvas iframe painted, so the chat is no longer waiting on a hidden side preview. */
13122
13505
  function noteShapePreviewShown(widgetId: string): void {
13506
+ // The widget listens after it mounts. The load event can be early, and a reload can miss
13507
+ // `widgetic:ready`, so the address is sent again once the frame has had time to listen.
13508
+ void postVisitorEntriesHost(widgetId);
13509
+ setTimeout(() => { void postVisitorEntriesHost(widgetId); }, 800);
13123
13510
  const status = getPanelDisplayState(widgetId).generateCodeStatus || '';
13124
13511
  const waitingOnPreview = /loading preview|building preview|generating code|code generation in progress|code saved/i.test(status);
13125
13512
  const generationRunning = !!generatingWidgetIds[widgetId] || !!previewUnblockedByWidgetId[widgetId];
@@ -13213,11 +13600,16 @@ Requirements:
13213
13600
  // reaches the API from the watchdog. Ordinary progress does not.
13214
13601
  }
13215
13602
 
13216
- function readGenerationStreamTail(op: OperationStatus): string {
13217
- const metadata = op.metadata;
13218
- if (!metadata) return '';
13219
- const raw = metadata.streamTail ?? metadata.stream_tail;
13220
- return typeof raw === 'string' ? raw.slice(-1600) : '';
13603
+ function readCodegenStreamTailFromOp(op: OperationStatus): string {
13604
+ return readGenerationStreamTail(op.metadata as Record<string, unknown> | undefined);
13605
+ }
13606
+
13607
+ function readCodegenThinkingTailFromOp(op: OperationStatus): string {
13608
+ return readThinkingTail(op.metadata as Record<string, unknown> | undefined);
13609
+ }
13610
+
13611
+ function readCodegenPlanFromOp(op: OperationStatus): GenerationPlanWire | null | undefined {
13612
+ return readPlanFromMetadata(op.metadata as Record<string, unknown> | undefined);
13221
13613
  }
13222
13614
 
13223
13615
  function holdPublishForGeneration(widgetId: string): void {
@@ -13264,6 +13656,7 @@ Requirements:
13264
13656
  }
13265
13657
  delete codegenStatusPendingLine[widgetId];
13266
13658
  delete codegenStreamPending[widgetId];
13659
+ delete codegenThinkingPending[widgetId];
13267
13660
  if (codegenChatStatusTimers[widgetId]) {
13268
13661
  clearTimeout(codegenChatStatusTimers[widgetId]);
13269
13662
  delete codegenChatStatusTimers[widgetId];
@@ -13306,10 +13699,20 @@ Requirements:
13306
13699
  const status = String(op.status || '').toLowerCase();
13307
13700
  if (status === 'completed' || status === 'failed' || status === 'cancelled') {
13308
13701
  delete codegenStreamPending[widgetId];
13702
+ delete codegenThinkingPending[widgetId];
13703
+ delete codegenPlanPending[widgetId];
13309
13704
  clearGenerationStream(widgetId);
13705
+ clearGenerationThinking(widgetId);
13706
+ clearGenerationPlan(widgetId);
13310
13707
  scheduleCodegenStatusPush(widgetId, line);
13311
13708
  } else {
13312
- scheduleCodegenStatusPush(widgetId, line, readGenerationStreamTail(op));
13709
+ scheduleCodegenStatusPush(
13710
+ widgetId,
13711
+ line,
13712
+ readCodegenStreamTailFromOp(op),
13713
+ readCodegenThinkingTailFromOp(op),
13714
+ readCodegenPlanFromOp(op),
13715
+ );
13313
13716
  }
13314
13717
  }
13315
13718
  scheduleCodegenChatStatusPush(widgetId, line);
@@ -13319,6 +13722,9 @@ Requirements:
13319
13722
  const codegenStatusTimers: Record<string, ReturnType<typeof setTimeout>> = {};
13320
13723
  const codegenStatusPendingLine: Record<string, string> = {};
13321
13724
  const codegenStreamPending: Record<string, string> = {};
13725
+ const codegenThinkingPending: Record<string, string> = {};
13726
+ type CodegenPlanPending = { kind: 'clear' } | { kind: 'set'; plan: GenerationPlanWire };
13727
+ const codegenPlanPending: Record<string, CodegenPlanPending> = {};
13322
13728
  const codegenChatStatusTimers: Record<string, ReturnType<typeof setTimeout>> = {};
13323
13729
  const codegenChatStatusPendingLine: Record<string, string> = {};
13324
13730
 
@@ -13329,21 +13735,56 @@ Requirements:
13329
13735
  generationStreamByWidgetId = next;
13330
13736
  }
13331
13737
 
13738
+ function clearGenerationThinking(widgetId: string): void {
13739
+ if (!generationThinkingByWidgetId[widgetId]) return;
13740
+ const next = { ...generationThinkingByWidgetId };
13741
+ delete next[widgetId];
13742
+ generationThinkingByWidgetId = next;
13743
+ }
13744
+
13745
+ function clearGenerationPlan(widgetId: string): void {
13746
+ if (!generationPlanByWidgetId[widgetId]) return;
13747
+ const next = { ...generationPlanByWidgetId };
13748
+ delete next[widgetId];
13749
+ generationPlanByWidgetId = next;
13750
+ }
13751
+
13332
13752
  /** At most one panel status write per widget per interval; trailing line always lands. */
13333
- function scheduleCodegenStatusPush(widgetId: string, line: string, streamTail = ''): void {
13753
+ function scheduleCodegenStatusPush(
13754
+ widgetId: string,
13755
+ line: string,
13756
+ streamTail = '',
13757
+ thinkingTail = '',
13758
+ plan?: GenerationPlanWire | null,
13759
+ ): void {
13334
13760
  codegenStatusPendingLine[widgetId] = line;
13335
13761
  if (streamTail) codegenStreamPending[widgetId] = streamTail;
13762
+ if (thinkingTail) codegenThinkingPending[widgetId] = thinkingTail;
13763
+ if (plan !== undefined) {
13764
+ codegenPlanPending[widgetId] = plan === null ? { kind: 'clear' } : { kind: 'set', plan };
13765
+ }
13336
13766
  if (codegenStatusTimers[widgetId]) return;
13337
13767
  codegenStatusTimers[widgetId] = setTimeout(() => {
13338
13768
  delete codegenStatusTimers[widgetId];
13339
13769
  const pending = codegenStatusPendingLine[widgetId];
13340
13770
  const pendingTail = codegenStreamPending[widgetId];
13771
+ const pendingThinking = codegenThinkingPending[widgetId];
13772
+ const pendingPlan = codegenPlanPending[widgetId];
13341
13773
  delete codegenStatusPendingLine[widgetId];
13342
13774
  delete codegenStreamPending[widgetId];
13775
+ delete codegenThinkingPending[widgetId];
13776
+ delete codegenPlanPending[widgetId];
13343
13777
  if (pending && !previewReadyAnnouncedByWidgetId[widgetId]) patchCodegenUiState(widgetId, { generateCodeStatus: pending });
13344
13778
  if (pendingTail && pendingTail !== generationStreamByWidgetId[widgetId]) {
13345
13779
  generationStreamByWidgetId = { ...generationStreamByWidgetId, [widgetId]: pendingTail };
13346
13780
  }
13781
+ if (pendingThinking && pendingThinking !== generationThinkingByWidgetId[widgetId]) {
13782
+ generationThinkingByWidgetId = { ...generationThinkingByWidgetId, [widgetId]: pendingThinking };
13783
+ }
13784
+ if (pendingPlan?.kind === 'clear') clearGenerationPlan(widgetId);
13785
+ else if (pendingPlan?.kind === 'set') {
13786
+ generationPlanByWidgetId = { ...generationPlanByWidgetId, [widgetId]: pendingPlan.plan };
13787
+ }
13347
13788
  }, CODEGEN_STATUS_THROTTLE_MS);
13348
13789
  }
13349
13790
 
@@ -13570,6 +14011,14 @@ Requirements:
13570
14011
  let widgetPanelSnapshots: Record<string, WidgetPanelSnapshot> = {};
13571
14012
  /** Bumped on every panel snapshot write so {#each} panels re-read display state. */
13572
14013
  let panelDisplayRevision = 0;
14014
+ /** Mirrors WidgetDetails `showRuntimeConsole` for the docked chat header icon. */
14015
+ let panelConsoleOpenByWidgetId: Record<string, boolean> = {};
14016
+
14017
+ function toggleDockedChatConsole(panelWidgetId: string, panelInstanceKey: string) {
14018
+ widgetDetailsRefs[panelInstanceKey]?.toggleRuntimeConsole?.();
14019
+ const open = widgetDetailsRefs[panelInstanceKey]?.isRuntimeConsoleOpen?.() ?? false;
14020
+ panelConsoleOpenByWidgetId = { ...panelConsoleOpenByWidgetId, [panelWidgetId]: open };
14021
+ }
13573
14022
  /** Bumped on rename so shape chrome / host title re-read widget names. */
13574
14023
  let widgetNamesRevision = 0;
13575
14024
  const schemaLoadInFlight = new Set<string>();
@@ -14121,6 +14570,16 @@ Requirements:
14121
14570
  if (current && current !== liveId && current !== 'live') return;
14122
14571
  const versionId = `v:${newestDraft}`;
14123
14572
  selectVersionInDropdowns(widgetId, versionId);
14573
+ const draftRecord = getShapePublishHistory(widgetId).find((row) => Number(row.version) === newestDraft);
14574
+ const draftCommit = draftRecord?.commitSha ?? draftRecord?.commit_sha ?? null;
14575
+ if (!draftCommit) {
14576
+ // A version row with no commit has no build. Asking /preview for it is a 404.
14577
+ console.log('[VersionPreview] Newest draft has no build yet', {
14578
+ widgetId: widgetId.substring(0, 8),
14579
+ versionId,
14580
+ });
14581
+ return;
14582
+ }
14124
14583
  shapePreviewSourceByWidgetId = {
14125
14584
  ...shapePreviewSourceByWidgetId,
14126
14585
  [widgetId]: versionId,
@@ -14634,7 +15093,6 @@ Requirements:
14634
15093
  let versionLabelsByWidgetId: Record<string, Record<string, string>> = {};
14635
15094
  let versionPromptLabelsByWidgetId: Record<string, Record<string, string>> = {};
14636
15095
  let versionTimelineByWidgetId: Record<string, Array<{ version: number; sha: string; prompt: string }>> = {};
14637
- let viewingVersionByWidgetId: Record<string, number | null> = {};
14638
15096
  const emptyVersionLabels: Record<string, string> = {};
14639
15097
  const emptyVersionTimeline: Array<{ version: number; sha: string; prompt: string }> = [];
14640
15098
  $: {
@@ -14648,13 +15106,11 @@ Requirements:
14648
15106
  const nextLabels: Record<string, Record<string, string>> = {};
14649
15107
  const nextPrompts: Record<string, Record<string, string>> = {};
14650
15108
  const nextTimeline: Record<string, Array<{ version: number; sha: string; prompt: string }>> = {};
14651
- const nextViewing: Record<string, number | null> = {};
14652
15109
  for (const widgetId of openWidgetPanelIds) {
14653
15110
  nextHeads[widgetId] = resolveViewingCommitShaForPanel(widgetId);
14654
15111
  nextLabels[widgetId] = buildVersionLabelsForPanel(widgetId);
14655
15112
  nextPrompts[widgetId] = buildVersionPromptLabelsForPanel(widgetId);
14656
15113
  nextTimeline[widgetId] = buildVersionTimelineForPanel(widgetId);
14657
- nextViewing[widgetId] = viewingVersionNumberForPanel(widgetId);
14658
15114
  }
14659
15115
  // A new object with the same contents still counts as a change and makes the
14660
15116
  // chat rebuild every turn. That rebuild was running again on each progress tick.
@@ -14662,7 +15118,6 @@ Requirements:
14662
15118
  if (JSON.stringify(versionLabelsByWidgetId) !== JSON.stringify(nextLabels)) versionLabelsByWidgetId = nextLabels;
14663
15119
  if (JSON.stringify(versionPromptLabelsByWidgetId) !== JSON.stringify(nextPrompts)) versionPromptLabelsByWidgetId = nextPrompts;
14664
15120
  if (JSON.stringify(versionTimelineByWidgetId) !== JSON.stringify(nextTimeline)) versionTimelineByWidgetId = nextTimeline;
14665
- if (JSON.stringify(viewingVersionByWidgetId) !== JSON.stringify(nextViewing)) viewingVersionByWidgetId = nextViewing;
14666
15121
  }
14667
15122
 
14668
15123
  /** Commit shas are keyed on 7 chars — that is what the chat summaries carry. */
@@ -14727,13 +15182,6 @@ Requirements:
14727
15182
  return labels;
14728
15183
  }
14729
15184
 
14730
- function viewingVersionNumberForPanel(widgetId: string): number | null {
14731
- const selected = resolveWidgetShapeVersionSelectedId(widgetId);
14732
- if (!selected?.startsWith('v:')) return null;
14733
- const version = parseInt(selected.slice(2), 10);
14734
- return Number.isFinite(version) ? version : null;
14735
- }
14736
-
14737
15185
  function syncWidgetShapeLivePreviews(): void {
14738
15186
  // This runs once per canvas frame while a shape moves. A call limit here
14739
15187
  // left the live iframe behind the shape.
@@ -16067,6 +16515,7 @@ Requirements:
16067
16515
  */
16068
16516
  function notifyPublishComplete(publishedWidgetId: string, publishedVersion: number | undefined): void {
16069
16517
  if (!embedded || !onPublishComplete) return;
16518
+ hideSketchOnBoardForWidget(publishedWidgetId);
16070
16519
  void (async () => {
16071
16520
  await Promise.race([
16072
16521
  handleRefreshScreenshot(publishedWidgetId, { quiet: true }).catch((error) => {
@@ -16386,7 +16835,6 @@ async function readPublishHistoryForPanel(widgetId: string, opts: { silent?: boo
16386
16835
  lastPublishedVersion = getPanelState(widgetId).lastPublishedVersion;
16387
16836
  }
16388
16837
  }
16389
- void reconcileWidgetHeadCommit(widgetId);
16390
16838
  if (widgetId === focusedPanelWidgetId) {
16391
16839
  publishHistory = history;
16392
16840
  publishHistoryResolved = true;
@@ -17459,9 +17907,12 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17459
17907
 
17460
17908
  /** Simple canvas: one chat, always. The draft id stands in until the first Send creates the widget. */
17461
17909
  async function ensureSimpleCanvasChat(): Promise<void> {
17462
- if (!embedded || canvasAdvancedFeatures || !canvasComponentReady) return;
17910
+ if (!embedded || canvasAdvancedFeatures || !canvasComponentReady || !hasValidToken || !conversationsClient) return;
17463
17911
  if (finalizingDraftConversions.size > 0) return;
17464
17912
  const primaryId = (canvasPrimaryWidgetId || '').trim();
17913
+ // The canvas JSON is loaded before the primary widget is known. Opening the draft chat in that gap
17914
+ // paints the empty suggestions, then the real conversation replaces them.
17915
+ if (!primaryId && !singleWidgetChromeReady) return;
17465
17916
  const targetId = primaryId || CANVAS_SKETCH_DRAFT_ID;
17466
17917
  const key = `${canvasId || 'pending'}:${targetId}`;
17467
17918
  if (simpleCanvasChatKey === key && openWidgetPanelIds.includes(targetId)) return;
@@ -17480,16 +17931,21 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17480
17931
  }
17481
17932
  }
17482
17933
 
17483
- $: if (embedded && !canvasAdvancedFeatures && canvasComponentReady && isCanvasStateLoaded) {
17484
- const simpleChatTarget = (canvasPrimaryWidgetId || '').trim() || CANVAS_SKETCH_DRAFT_ID;
17485
- if (!openWidgetPanelIds.includes(simpleChatTarget)) {
17486
- void ensureSimpleCanvasChat();
17487
- }
17934
+ $: if (
17935
+ hasValidToken &&
17936
+ embedded &&
17937
+ !canvasAdvancedFeatures &&
17938
+ canvasComponentReady &&
17939
+ isCanvasStateLoaded &&
17940
+ (singleWidgetChromeReady || !!(canvasPrimaryWidgetId || '').trim())
17941
+ ) {
17942
+ void ensureSimpleCanvasChat();
17488
17943
  }
17489
17944
 
17490
17945
  async function handleCanvasReady() {
17491
17946
  markCanvasOpenStep('creator:canvas-ready');
17492
17947
  // console.log('[WidgetCreator] Canvas component ready');
17948
+ singleWidgetChromeReady = false;
17493
17949
  await waitForCanvasRef();
17494
17950
  canvasComponentReady = true;
17495
17951
  if (ignoreIncomingCanvasLoads) {
@@ -17502,12 +17958,16 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17502
17958
  placeSelectedWidgetShapeOnCanvas();
17503
17959
  }
17504
17960
  syncWidgetShapeLivePreviews();
17961
+ singleWidgetChromeReady = true;
17505
17962
  void ensureSimpleCanvasChat();
17506
17963
  return;
17507
17964
  }
17508
17965
  const { loaded, widgetIds: widgetIdsOnCanvas } = await tryLoadCanvasState();
17509
17966
  if (!loaded) {
17510
17967
  console.log('[WidgetCreator] Canvas ready — JSON load deferred until canvasId is resolved');
17968
+ if (isCanvasStateLoaded && (canvasPrimaryWidgetId || widgets.length === 0)) {
17969
+ singleWidgetChromeReady = true;
17970
+ }
17511
17971
  if (!isCanvasStateLoaded) {
17512
17972
  scheduleCanvasHydrateRetry('canvas ready before canvasId');
17513
17973
  }
@@ -17528,6 +17988,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17528
17988
  setTimeout(() => applyPrimarySelectionOnCanvas(primaryId), 80);
17529
17989
  });
17530
17990
  syncWidgetShapeLivePreviews();
17991
+ singleWidgetChromeReady = true;
17531
17992
  void ensureSimpleCanvasChat();
17532
17993
  }
17533
17994
 
@@ -17687,8 +18148,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17687
18148
  console.log('[CanvasDebug] getCanvas returned no canvasContent, retry', attempt + 1);
17688
18149
  } catch (getErr) {
17689
18150
  console.warn('[CanvasDebug] getCanvas failed, retry', attempt + 1, getErr);
17690
- // "No such canvas" is an answer, not a hiccup: asking again would only get it again.
17691
- if (saysCanvasIsMissing(getErr) || attempt >= maxCanvasReadAttempts - 1) throw getErr;
18151
+ // Access denied and "no such canvas" are answers. A pause and another read only delay the sentence.
18152
+ if (canvasReadWillNotChange(getErr) || attempt >= maxCanvasReadAttempts - 1) throw getErr;
17692
18153
  }
17693
18154
  if (attempt < maxCanvasReadAttempts - 1) {
17694
18155
  await new Promise((resolve) => setTimeout(resolve, 400 * (attempt + 1)));
@@ -17755,8 +18216,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17755
18216
  canvasApiLoadError = errMsg;
17756
18217
  // Partner mode: the API says the canvas does not exist for this visitor. It is not an empty canvas to start on
17757
18218
  // (the fallbacks below would call it one and say the creator is ready): the page is told, and that is the end.
17758
- if (saysCanvasIsMissing(err)) {
17759
- declareCanvasUnavailable(canvasId || null, errMsg);
18219
+ if (canvasReadWillNotChange(err)) {
18220
+ if (saysCanvasIsMissing(err)) declareCanvasUnavailable(canvasId || null, errMsg);
18221
+ else stopAskingForCanvas(err, errMsg);
17760
18222
  return emptyResult;
17761
18223
  }
17762
18224
  if (/timed out|failed to fetch|network|econnrefused|503|502|load canvases/i.test(errMsg)) {
@@ -17939,6 +18401,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17939
18401
 
17940
18402
  lastSavedCanvasObjectCount = objectCount;
17941
18403
  try { creatorSessionStorage.setItem(CANVAS_OBJ_COUNT_KEY, String(objectCount)); } catch {}
18404
+ noteDrawnObjectCount(countDrawnCanvasObjectsInJson(json));
18405
+ maybeSyncSketchGeneratePrefill();
17942
18406
  emitCreatorSaveState(false);
17943
18407
 
17944
18408
  // Save to durable L1 fallback (always, even with 0 objects for legitimate clears)
@@ -18119,6 +18583,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18119
18583
  promptLoadedForWidgetId = draftId;
18120
18584
  pendingChatDraftText = CONVERT_PROMPT;
18121
18585
  chatDraftRestoredForWidgetId = null;
18586
+ pendingSketchGeneratePrefill = false;
18587
+ sketchPrefillApplied = true;
18122
18588
  savePromptForWidget(draftId);
18123
18589
  const panelChat = getChatMethodsForWidget(draftId);
18124
18590
  if (panelChat) {
@@ -18382,10 +18848,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18382
18848
  promptLoadedForWidgetId = widgetId;
18383
18849
  pendingChatDraftText = '';
18384
18850
 
18851
+ // No "Widget created" toast: the chat already shows the build starting, so the person sees it there.
18385
18852
  authStatus = 'Widget created from design.';
18386
- showToast('success', $t('creator.widget.widgetCreated'), {
18387
- description: $t('creator.codegen.isReadyGenerationStarted', { name: newWidget.name || widgetName })
18388
- });
18389
18853
  return widgetId;
18390
18854
  } catch (error) {
18391
18855
  console.error('[WidgetCreator] finalizeDraftConversion error:', error);
@@ -18410,6 +18874,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18410
18874
  */
18411
18875
  async function lockSimpleCanvasToOneWidget(primaryId: string | null): Promise<void> {
18412
18876
  if (!embedded || multipleWidgetsAllowed || !canvasRef || !primaryId) return;
18877
+ if (widgetBuiltForSketchHiding(primaryId)) {
18878
+ hideSketchOnBoardForWidget(primaryId);
18879
+ }
18413
18880
  const removed = canvasRef.keepOnlyWidgetShape?.(primaryId) ?? 0;
18414
18881
  const linked = canvasRef.getLinkedWidgetIds?.() ?? new Set<string>();
18415
18882
  let placed = false;
@@ -19097,7 +19564,29 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19097
19564
 
19098
19565
 
19099
19566
  <!-- Widgetic Canvas Editor - Full width background (lazy-loaded) -->
19100
- <div class="wc-canvas-area flex-1 min-h-0 relative {embedded && !canvasAdvancedFeatures ? 'pe-[450px]' : ''}">
19567
+ <div
19568
+ class="wc-canvas-area flex-1 min-h-0 min-w-0 relative {embeddedSketchShell
19569
+ ? 'flex flex-col lg:pe-[450px] max-lg:pe-0'
19570
+ : embedded && !canvasAdvancedFeatures
19571
+ ? 'pe-[450px]'
19572
+ : ''}"
19573
+ >
19574
+ <EmbeddedSketchViewportShell
19575
+ {embedded}
19576
+ sketchShell={embeddedSketchShell}
19577
+ bind:mobileTab={embeddedSketchMobileTab}
19578
+ tabCanvasLabel={$t('creator.embedded.tabCanvas')}
19579
+ tabChatLabel={$t('creator.livePreviews.chat')}
19580
+ >
19581
+ {#snippet children()}
19582
+ <div
19583
+ class="embedded-sketch-canvas-stage flex-1 min-h-0 relative min-w-0 {embeddedSketchShell
19584
+ ? 'max-lg:shrink-0 max-lg:basis-[58%] max-lg:min-h-0 max-md:absolute max-md:inset-0 max-md:z-0 max-md:basis-auto'
19585
+ : ''} {embeddedSketchShell && embeddedSketchMobileTab !== 'canvas'
19586
+ ? 'max-md:pointer-events-none max-md:opacity-0 max-md:[visibility:hidden]'
19587
+ : ''}"
19588
+ aria-hidden={embeddedSketchShell && embeddedSketchMobileTab !== 'canvas' ? 'true' : undefined}
19589
+ >
19101
19590
  <!-- Embedded: Debug toggle lives in site AppHeader (avoids overlapping Props Panel). -->
19102
19591
  {#if canvasApiLoadError || canvasShapesMissingWarning}
19103
19592
  <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">
@@ -19106,7 +19595,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19106
19595
  {#if canvasApiLoadError}
19107
19596
  <p class="font-semibold">{canvasUnavailable ? $t('creator.canvas.canvasUnavailable') : $t('creator.canvas.canvasShapesFailedToLoad')}</p>
19108
19597
  <p class="text-xs mt-1">{canvasApiLoadError}</p>
19109
- {#if !partnerMode}
19598
+ {#if !partnerMode && !canvasUnavailable}
19110
19599
  <p class="text-xs mt-1 opacity-90">If Supabase shows a billing/quota warning, upgrade or review billing — API reads may fail while the widget list still loads.</p>
19111
19600
  {/if}
19112
19601
  {:else}
@@ -19147,7 +19636,10 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19147
19636
  onConvertToWidget={handleConvertToWidget}
19148
19637
  onRecognizeStroke={handleRecognizeStroke}
19149
19638
  onWidgetImageClick={handleWidgetImageClick}
19150
- onCanvasDirty={() => emitCreatorSaveState(true)}
19639
+ onCanvasDirty={() => {
19640
+ emitCreatorSaveState(true);
19641
+ scheduleSketchPrefillFromCanvasDirty();
19642
+ }}
19151
19643
  onWidgetShapeDuplicated={handleWidgetShapeDuplicated}
19152
19644
  onWidgetShapeDeleting={handleWidgetShapeDeleting}
19153
19645
  onWidgetRename={handleWidgetRename}
@@ -19155,7 +19647,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19155
19647
  void captureListThumbnail(widgetId, true);
19156
19648
  }}
19157
19649
  onSetPrimaryWidget={handleSetPrimaryWidget}
19158
- showElementSelector={!!canvasPrimaryWidgetId && !isDraftConvertId(canvasPrimaryWidgetId)}
19650
+ showElementSelector={(multipleWidgetsAllowed || singleWidgetChromeReady) && !!canvasPrimaryWidgetId && !isDraftConvertId(canvasPrimaryWidgetId)}
19159
19651
  showDrawingTools={showDrawingTools}
19160
19652
  elementSelectorActive={!!(canvasPrimaryWidgetId && selectorEnabledByWidgetId[canvasPrimaryWidgetId])}
19161
19653
  selectorGuide={{
@@ -19204,7 +19696,14 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19204
19696
  </div>
19205
19697
 
19206
19698
  <!-- FLOATING PANELS OVERLAY (pointer-events-none container, each panel is pointer-events-auto) -->
19207
- <div class="floating-panels-overlay absolute inset-0 z-2003 pointer-events-none">
19699
+ <div
19700
+ class="floating-panels-overlay z-2003 pointer-events-none {embeddedSketchShell
19701
+ ? 'max-lg:relative max-lg:inset-auto max-lg:flex max-lg:flex-1 max-lg:min-h-0 max-lg:basis-[42%] max-lg:shrink-0 max-lg:w-full max-md:absolute max-md:inset-0 max-md:z-[1] max-md:basis-auto lg:absolute lg:inset-0'
19702
+ : 'absolute inset-0'} {embeddedSketchShell && embeddedSketchMobileTab !== 'chat'
19703
+ ? 'max-md:pointer-events-none max-md:opacity-0 max-md:[visibility:hidden]'
19704
+ : ''}"
19705
+ aria-hidden={embeddedSketchShell && embeddedSketchMobileTab !== 'chat' ? 'true' : undefined}
19706
+ >
19208
19707
 
19209
19708
  <!-- W3: live iframe + drag bar on WidgetShapes (iframe interactive; body drag locked) -->
19210
19709
  <WidgetShapeLivePreviews
@@ -20017,6 +20516,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20017
20516
  {:else}
20018
20517
  <div
20019
20518
  class="wc-version-history-scroll flex flex-col gap-1 overflow-x-hidden {hasChatScroll ? 'overflow-y-auto' : 'overflow-y-visible'}"
20519
+ use:revealSelectedVersion
20020
20520
  style="{hasChatScroll ? 'max-height: 185px; margin-inline-end: -4px; padding-inline-end: 4px;' : 'max-height: none;'} scrollbar-width: thin; scrollbar-color: rgba(0,0,0,0.2) transparent;"
20021
20521
  >
20022
20522
  {#each [...ps.publishHistory].sort((a, b) => Number(a.version) - Number(b.version)) as record (record.id)}
@@ -20059,7 +20559,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20059
20559
  {/if}
20060
20560
  </svelte:fragment>
20061
20561
  <svelte:fragment slot="code-generation-models">
20562
+ <!-- The debug model list stays inside `{#if debugMode}`: the i18n source guard reads that test to leave debug words in English. -->
20062
20563
  {#if debugMode}
20564
+ {#if !(!canvasAdvancedFeatures && embedded)}
20063
20565
  <div class="generation-chat-sticky-header shrink-0 z-20 bg-white border-b border-gray-200">
20064
20566
  <!-- svelte-ignore a11y_label_has_associated_control -->
20065
20567
  <div class="generation-models-header flex items-center justify-end gap-2 px-2 py-1.5 bg-gray-50">
@@ -20082,6 +20584,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20082
20584
  </div>
20083
20585
  </div>
20084
20586
  {/if}
20587
+ {/if}
20085
20588
  </svelte:fragment>
20086
20589
 
20087
20590
  <svelte:fragment slot="code-generation-status">
@@ -20239,7 +20742,13 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20239
20742
  bind:language={widgetLanguage}
20240
20743
  />
20241
20744
  {/snippet}
20242
- <Chat class="code-generation-chat w-full h-full rounded-none border-0"
20745
+ <!-- Svelte 5: `{@const}` must be the direct child of a block; this wrapper exists only for dockedChatPanel and composerModelOptions. -->
20746
+ {#if true}
20747
+ {@const dockedChatPanel = embedded && !canvasAdvancedFeatures}
20748
+ {@const composerModelOptions = debugMode
20749
+ ? availableModels.map((model) => ({ id: model.id, label: model.name }))
20750
+ : []}
20751
+ <Chat class="code-generation-chat h-full w-full max-w-full rounded-none border-0"
20243
20752
  locale={locale}
20244
20753
  messages={chatMessages}
20245
20754
  storedLineLabel={(line) => conversationLineLabel(line, $t)}
@@ -20250,7 +20759,14 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20250
20759
  onMessagesResize={(deltaPx) => handleChatMessagesResize(panelWidgetId, deltaPx)}
20251
20760
  showLogs={debugMode}
20252
20761
  showHeader={false}
20762
+ showPanelHeader={dockedChatPanel}
20763
+ showConsoleControl={dockedChatPanel && debugMode}
20764
+ consoleOpen={!!panelConsoleOpenByWidgetId[panelWidgetId]}
20765
+ onToggleConsole={dockedChatPanel && debugMode ? () => toggleDockedChatConsole(panelWidgetId, panelInstanceKey) : undefined}
20253
20766
  showDescriptionHeader={false}
20767
+ composerModels={composerModelOptions}
20768
+ selectedComposerModelId={selectedModelId}
20769
+ onSelectComposerModel={handleModelSelect}
20254
20770
  context={{
20255
20771
  id: panelWidgetId,
20256
20772
  type: ContextType.FRAME,
@@ -20259,7 +20775,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20259
20775
  }}
20260
20776
  config={{
20261
20777
  features: {
20262
- screenshot: true,
20778
+ screenshot: false,
20263
20779
  screenRecording: false,
20264
20780
  voiceTranscription: false,
20265
20781
  fileUpload: true,
@@ -20277,7 +20793,6 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20277
20793
  versionLabelByCommitSha={versionLabelsByWidgetId[panelWidgetId] ?? emptyVersionLabels}
20278
20794
  versionLabelByPrompt={versionPromptLabelsByWidgetId[panelWidgetId] ?? emptyVersionLabels}
20279
20795
  versionTimeline={versionTimelineByWidgetId[panelWidgetId] ?? emptyVersionTimeline}
20280
- viewingVersion={viewingVersionByWidgetId[panelWidgetId] ?? null}
20281
20796
  showSelector={false}
20282
20797
  isSelectorActive={!!selectorEnabledByWidgetId[panelWidgetId]}
20283
20798
  selectedElements={selectedElementsByWidgetId[panelWidgetId] ?? []}
@@ -20288,7 +20803,6 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20288
20803
  onRetryMessage={(content) => handleChatRetryMessage(content, panelWidgetId)}
20289
20804
  onUpgradePlans={openUpgradePlans}
20290
20805
  onUploadChatFile={handleChatUploadFile}
20291
- onTakeScreenshot={() => handleChatScreenshot(panelWidgetId)}
20292
20806
  isCompleted={!!conversationCompletedByWidgetId[panelWidgetId]}
20293
20807
  onCompletionToggle={(detail) => handleChatCompletionToggle(panelWidgetId, detail)}
20294
20808
  onLoadConversations={handleLoadConversations}
@@ -20309,6 +20823,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20309
20823
  onConversationChange={(conversationId) => handleChatConversationChange(conversationId, panelWidgetId)}
20310
20824
  isGenerating={!!generatingWidgetIds[panelWidgetId] && !previewUnblockedByWidgetId[panelWidgetId]}
20311
20825
  generationStream={generationStreamByWidgetId[panelWidgetId] || ''}
20826
+ generationThinking={generationThinkingByWidgetId[panelWidgetId] || ''}
20827
+ generationPlan={generationPlanByWidgetId[panelWidgetId] ?? null}
20312
20828
  onStopGeneration={() => {
20313
20829
  if (!isPanelFocused) focusWidgetPanel(panelWidgetId);
20314
20830
  // Stop belongs to the panel it was pressed in: the other panels' generations go on
@@ -20318,6 +20834,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20318
20834
  // console.log('[Chat] Stats update:', { messageCount, firstMessage });
20319
20835
  }}
20320
20836
  />
20837
+ {/if}
20321
20838
  </div>
20322
20839
  {/key}
20323
20840
 
@@ -20747,6 +21264,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20747
21264
  {/if}
20748
21265
 
20749
21266
  </div> <!-- end of floating-panels-overlay -->
21267
+ {/snippet}
21268
+ </EmbeddedSketchViewportShell>
21269
+ </div> <!-- end of wc-canvas-area -->
20750
21270
  {/if} <!-- end of logged in section (canvas + main panel) -->
20751
21271
  </div> <!-- end of widget-creator-root-page-ct -->
20752
21272