@widgetic/creator 0.4.47 → 0.4.49

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.
@@ -10,7 +10,6 @@
10
10
  import {
11
11
  Button,
12
12
  CreatorBar,
13
- CanvasBoardStatusChip,
14
13
  DropdownMenu,
15
14
  PasswordInput,
16
15
  showToast,
@@ -62,6 +61,8 @@
62
61
  sketchBarShowsPublish,
63
62
  sketchSavedStatusLabel,
64
63
  } from './sketchBarState.js';
64
+ import { isDebugTabVisible } from './debug/debugUiVisibility.js';
65
+ import { shouldNudgeSendBeforePublish } from './publish/publishGenerationGate.js';
65
66
 
66
67
  /**
67
68
  * Idempotency middleware (Phase 2 hardening): the gateway rejects
@@ -294,6 +295,7 @@
294
295
  } from './host/hostControls.js';
295
296
  import { createSerialQueue } from './utils/serialQueue.js';
296
297
  import { createHeldAutosave } from './utils/heldAutosave.js';
298
+ import { refusesEmptyCanvas, requestInitForSave } from './utils/canvasSavePolicy.js';
297
299
  import { widgetsToRestore } from './utils/widgetsToRestore.js';
298
300
 
299
301
  function resolveCreatorWorkflowStep(
@@ -310,11 +312,15 @@
310
312
  export let projectId: CreatorAppProps['projectId'] = null;
311
313
  export let workspaceType: CreatorAppProps['workspaceType'] = 'personal';
312
314
  export let organizationId: CreatorAppProps['organizationId'] = null;
315
+ /** Brand-kit fonts the host mapped for the sketch canvas. */
316
+ export let canvasWorkspaceFonts: CreatorAppProps['canvasWorkspaceFonts'] = [];
313
317
  export let initialWidgetId: CreatorAppProps['initialWidgetId'] = null;
314
318
  export let initialCompositionId: CreatorAppProps['initialCompositionId'] = null;
315
319
  export let initialStep: CreatorAppProps['initialStep'] = null;
316
320
  export let forceCreateNewWidget: CreatorAppProps['forceCreateNewWidget'] = false;
317
321
  export let initialSketchName: CreatorAppProps['initialSketchName'] = null;
322
+ /** Title the host already knows for the canvas being opened: shown at once, then replaced by the canvas record's own. */
323
+ export let initialCanvasTitle: CreatorAppProps['initialCanvasTitle'] = null;
318
324
  /** Words to put in the chat input of a new widget, once (never sent by the creator itself). */
319
325
  export let initialPrompt: CreatorAppProps['initialPrompt'] = null;
320
326
  /** The initial prompt was put in the input; later draft restores leave the person's own text alone. */
@@ -323,6 +329,8 @@
323
329
  export let initialMessage: CreatorAppProps['initialMessage'] = null;
324
330
  /** The host's message was put in the input (and sent, when asked); later draft restores leave the person's text alone. */
325
331
  let appliedInitialMessage = false;
332
+ /** Opened from the Home page with a drawing: the drawing is centred in the main window once, when it has loaded. */
333
+ let centerSketchOnFirstLoad = !!initialMessage;
326
334
  /** Where the canvas's tool bar stands along the bottom edge (see `CreatorAppProps.toolbarPosition`). */
327
335
  export let toolbarPosition: CreatorAppProps['toolbarPosition'] = undefined;
328
336
  /** Whether the canvas shows its Save button (see `CreatorAppProps.showSaveButton`): the site and the standalone creator do. */
@@ -332,14 +340,21 @@
332
340
  $: limitNoticeMode = normalizeLimitNotices(limitNotices);
333
341
  /** What Publish would do now, for the host that draws its own button (see `CreatorAppProps.onPublishStateChanged`). */
334
342
  export let onPublishStateChanged: CreatorAppProps['onPublishStateChanged'] = undefined;
343
+ /**
344
+ * How long the canvas waits after the last change before it saves. The API is not asked after every stroke: a burst of
345
+ * changes is one save. The same on a developer's machine and for a visitor (a longer wait in development hid how the
346
+ * canvas is saved from the people who build it).
347
+ */
348
+ const CANVAS_AUTOSAVE_DELAY_MS = 3000;
335
349
  /**
336
350
  * How long the person can keep changing the canvas before it is saved anyway. The canvas waits for a quiet moment
337
- * (`autosaveDelayMs`) so the API is not asked after every stroke; this is the most that waiting may take.
351
+ * (`CANVAS_AUTOSAVE_DELAY_MS`) so the API is not asked after every stroke; this is the most that waiting may take.
338
352
  */
339
- const CANVAS_AUTOSAVE_MAX_WAIT_MS = 15000;
353
+ const CANVAS_AUTOSAVE_MAX_WAIT_MS = 10000;
340
354
  export let apiUrl: CreatorAppProps['apiUrl'] = null;
341
355
  export let widgetBuilderUrl: CreatorAppProps['widgetBuilderUrl'] = null;
342
356
  export let initialDebugMode: CreatorAppProps['initialDebugMode'] = undefined;
357
+ export let initialDebugOn: CreatorAppProps['initialDebugOn'] = undefined;
343
358
  export let initialAdvancedFeatures: CreatorAppProps['initialAdvancedFeatures'] = false;
344
359
  export let defaultCoderModelId: CreatorAppProps['defaultCoderModelId'] = undefined;
345
360
  export let defaultPlannerModelId: CreatorAppProps['defaultPlannerModelId'] = undefined;
@@ -622,7 +637,7 @@
622
637
  function handleHostRequestPublishEvent(): void {
623
638
  const targetId = focusedPanelWidgetId || selectedWidgetId;
624
639
  if (!targetId) {
625
- showToast('error', $t('creator.publish.cannotPublish'), { description: $t('creator.widget.noWidgetSelected') });
640
+ showToast('error', $t('creator.publish.cannotPublish'), { description: $t('creator.sketch.publishNeedsWidget') });
626
641
  return;
627
642
  }
628
643
  // console.log('[CreatorApp] Host requested publish for', targetId.substring(0, 8));
@@ -644,7 +659,7 @@
644
659
  const targetId = publishTargetOf(focusedPanelWidgetId, canvasPrimaryWidgetId, isDraftConvertId);
645
660
  if (!targetId) {
646
661
  console.warn('[CreatorApp] Host publish ignored: there is no widget to publish yet');
647
- showToast('error', $t('creator.publish.cannotPublish'), { description: $t('creator.widget.noWidgetSelected') });
662
+ showToast('error', $t('creator.publish.cannotPublish'), { description: $t('creator.sketch.publishNeedsWidget') });
648
663
  return;
649
664
  }
650
665
  try {
@@ -1147,7 +1162,7 @@
1147
1162
  */
1148
1163
  let canvasRef: WithoutIndexKeys<InstanceType<typeof import('@widgetic/canvas').Canvas>> | null = null;
1149
1164
  /**
1150
- * HTML iframe overlays over Fabric WidgetShapes (W3).
1165
+ * HTML iframe overlays over the canvas's widget shapes (W3).
1151
1166
  *
1152
1167
  * Typed as the component's **own instance type**, not a hand-written
1153
1168
  * mirror: a Svelte 5 component is a call-signature type whose return is
@@ -1162,7 +1177,7 @@
1162
1177
  * lazily — the optionality lives at the binding, not in the type.
1163
1178
  */
1164
1179
  let widgetShapeLivePreviewsRef: ReturnType<typeof WidgetShapeLivePreviews> | null = null;
1165
- /** Selected WidgetShape id for chrome highlight (from Fabric selection). */
1180
+ /** Selected WidgetShape id for chrome highlight (from the canvas selection). */
1166
1181
  let canvasSelectedWidgetShapeId: string | null = null;
1167
1182
  let widgetDetailsModulePromise: Promise<typeof WidgetDetailsComponent> | null = null;
1168
1183
 
@@ -1289,6 +1304,18 @@
1289
1304
  appliedSketchName = true;
1290
1305
  activeCanvasName = initialSketchName.trim();
1291
1306
  }
1307
+ let appliedInitialCanvasTitle = false;
1308
+ // The dashboard already holds this title: show it before the canvas record has been read (about a second).
1309
+ $: if (
1310
+ !appliedInitialCanvasTitle &&
1311
+ !appliedSketchName &&
1312
+ activeCanvasName === 'Loading...' &&
1313
+ typeof initialCanvasTitle === 'string' &&
1314
+ initialCanvasTitle.trim()
1315
+ ) {
1316
+ appliedInitialCanvasTitle = true;
1317
+ activeCanvasName = initialCanvasTitle.trim();
1318
+ }
1292
1319
  let canvasNameEditing = false; // kept for existing startCanvasNameEdit/commitCanvasNameEdit
1293
1320
  let canvasNameInputEl: HTMLInputElement | null = null;
1294
1321
 
@@ -1381,6 +1408,16 @@
1381
1408
  try { return parseInt(creatorSessionStorage.getItem(CANVAS_OBJ_COUNT_KEY) || '0', 10) || 0; }
1382
1409
  catch { return 0; }
1383
1410
  })();
1411
+ /**
1412
+ * How many changes the canvas has reported (`onCanvasDirty`), and how many of them a save had seen when it got past the
1413
+ * guard against an empty canvas. A canvas that is empty after the person changed it (deleted everything) is a board
1414
+ * emptied on purpose; one that looks empty with no change reported is a snapshot gone wrong, and is not written over
1415
+ * the server's copy. See `handleCanvasAutoSave`.
1416
+ */
1417
+ let canvasEditRevision = 0;
1418
+ let canvasRevisionPassedGuard = 0;
1419
+ /** An autosave has failed and the person was told; cleared by the next save that goes through, so a run of failures is one notice. */
1420
+ let autosaveFailureToldToPerson = false;
1384
1421
 
1385
1422
  let selectedWidget: WidgetSummary | null = null;
1386
1423
  /** Set after canvas widget list restore; triggers preview load once WidgetDetails mounts. */
@@ -1639,15 +1676,9 @@
1639
1676
  let pendingAutoGenerateWidgetId: string | null = null; // Widget created from canvas that needs auto code generation
1640
1677
  let pendingDuplicateBuildWidgetId: string | null = null; // Duplicated widget awaiting repo fork + compile
1641
1678
  let isWidgetOperationInProgress = false; // Guards against concurrent duplicate/convert
1642
- /** Convert-to-widget skips the confirm dialog and auto-starts codegen once. */
1643
- const skipAutoGenConfirmWidgetIds = new Set<string>();
1644
1679
  /** New widgets: 'pending' while GitLab repo is created — preview shows loader, not "no repository". */
1645
1680
  let repositorySetupByWidgetId: Record<string, 'pending' | 'ready' | 'failed'> = {};
1646
1681
 
1647
- // Confirm generation dialog state (shown before auto-generating on convert)
1648
- let confirmGenerateDialogOpen = false;
1649
- /** Widget targeted by the open confirm-generate dialog (may differ from focused panel). */
1650
- let confirmGenerateWidgetId: string | null = null;
1651
1682
 
1652
1683
  // ─── Convert UX v2: draft panel state (no widget record until first Send) ────
1653
1684
  /** Synthetic id for the draft convert panel — NOT a widget id in the DB. */
@@ -1658,7 +1689,7 @@
1658
1689
  const draftConvertObjectIds = new Map<string, string>();
1659
1690
  /** Captured sketch screenshot (data URL) per draft id — reused on first Send. */
1660
1691
  const draftConvertScreenshots = new Map<string, string>();
1661
- /** Fabric JSON of the board, kept so the first checkpoint can put the sketch back. */
1692
+ /** The board's saved scene (JSON), kept so the first checkpoint can put the sketch back. */
1662
1693
  const draftConvertSketchJson = new Map<string, string>();
1663
1694
  const sketchSnapshotsByWidgetId = new Map<string, string>();
1664
1695
 
@@ -1711,6 +1742,7 @@
1711
1742
  getDraftText?: () => string;
1712
1743
  setDraftText?: (text: string) => void;
1713
1744
  getAttachmentDataUrls?: () => string[];
1745
+ getDraftAttachmentDataUrls?: () => string[];
1714
1746
  getAttachmentUploadIds?: () => string[];
1715
1747
  restoreAttachmentsFromDataUrls?: (dataUrls: string[]) => void;
1716
1748
  clearDraft?: () => void;
@@ -2280,33 +2312,6 @@
2280
2312
  return /(?:Commit:?\s+|Code saved\s*\()[a-f0-9]{7,40}/i.test(String(content || ''));
2281
2313
  }
2282
2314
 
2283
- /** The "Try again" button of the failed chip on the board: runs the last prompt of the primary widget's chat again,
2284
- * the same way the retry button of the failed message in the chat does. */
2285
- async function handleSketchRetryFailedGeneration() {
2286
- const widgetId = canvasPrimaryWidgetId;
2287
- if (!widgetId) return;
2288
- try {
2289
- const panelChat = getChatMethodsForWidget(widgetId);
2290
- const conversationId = panelChat?.getConversationId?.() ?? getPanelState(widgetId).currentChatConversationId ?? null;
2291
- if (!conversationId) {
2292
- console.warn('[Creator] Try again on the failed chip: the widget has no conversation to read the prompt from');
2293
- return;
2294
- }
2295
- const conversationMessages = (await handleLoadMessages(conversationId, widgetId, { scope: 'all' })) || [];
2296
- const lastUserMessage = [...conversationMessages]
2297
- .reverse()
2298
- .find((message) => (message.messageType || message.message_type) === 'user');
2299
- const lastPromptText = String(lastUserMessage?.messageContent || lastUserMessage?.message_content || '').trim();
2300
- if (!lastPromptText) {
2301
- console.warn('[Creator] Try again on the failed chip: no earlier prompt found in the conversation');
2302
- return;
2303
- }
2304
- await handleChatRetryMessage(lastPromptText, widgetId);
2305
- } catch (error) {
2306
- console.error('[Creator] Try again on the failed chip did not start', error);
2307
- }
2308
- }
2309
-
2310
2315
  /** Retry failed codegen without duplicating the user bubble. A successful prompt forks a new message so each version has its own turn. */
2311
2316
  async function handleChatRetryMessage(content: string, sourceWidgetId?: string) {
2312
2317
  const widgetId = sourceWidgetId ?? selectedWidgetId;
@@ -2557,7 +2562,9 @@
2557
2562
  try {
2558
2563
  const panelChat = getChatMethodsForWidget(widgetId);
2559
2564
  const chatDraft = panelChat?.getDraftText?.() ?? '';
2560
- const chatAttachmentUrls = panelChat?.getAttachmentDataUrls?.() ?? [];
2565
+ // The draft keeps pictures as data: URLs, the one form a refresh can rebuild them from (an older chat only has the send list).
2566
+ const chatAttachmentUrls =
2567
+ panelChat?.getDraftAttachmentDataUrls?.() ?? panelChat?.getAttachmentDataUrls?.() ?? [];
2561
2568
  patchPanelSnapshot(widgetId, {
2562
2569
  codeGenerationPrompt: chatDraft || getPanelState(widgetId).codeGenerationPrompt,
2563
2570
  promptImages: chatAttachmentUrls,
@@ -2699,15 +2706,16 @@
2699
2706
  }
2700
2707
  }
2701
2708
 
2702
- /** Push confirm-dialog / local prompt into chat input (not as a sent message). */
2703
- function syncPromptToChatDraft() {
2704
- if (!chatMethods) return;
2709
+ /** Push the local prompt into the chat input of a widget's panel (the focused one by default), not as a sent message. */
2710
+ function syncPromptToChatDraft(widgetId?: string | null) {
2711
+ const targetChatMethods = (widgetId ? getChatMethodsForWidget(widgetId) : null) ?? chatMethods;
2712
+ if (!targetChatMethods) return;
2705
2713
  suppressChatDraftSync = true;
2706
2714
  try {
2707
2715
  if (promptImages.length > 0) {
2708
- chatMethods.restoreAttachmentsFromDataUrls?.(promptImages);
2716
+ targetChatMethods.restoreAttachmentsFromDataUrls?.(promptImages);
2709
2717
  }
2710
- chatMethods.setDraftText?.(codeGenerationPrompt);
2718
+ targetChatMethods.setDraftText?.(codeGenerationPrompt);
2711
2719
  } finally {
2712
2720
  suppressChatDraftSync = false;
2713
2721
  }
@@ -2757,7 +2765,7 @@
2757
2765
  /**
2758
2766
  * Keeps widget screenshots out of the canvas JSON.
2759
2767
  *
2760
- * Fabric serialized each widget shape's screenshot inline as base64, so an
2768
+ * The canvas used to serialize each widget shape's screenshot inline as base64, so an
2761
2769
  * autosave stringified megabytes of image data and wrote it three times over —
2762
2770
  * the main-thread block the freeze reports kept naming. The canvas now stores a
2763
2771
  * reference and asks for the bytes back through this store: the local copy
@@ -3246,7 +3254,7 @@
3246
3254
  try {
3247
3255
  const screenshot = await handleChatScreenshot(widgetId, iframe, true);
3248
3256
  if (!screenshot || !isCurrent()) return;
3249
- // Persist before Fabric/autosave side effects can resync the live overlay.
3257
+ // Persist before the canvas/autosave side effects can resync the live overlay.
3250
3258
  await persistWidgetListThumbnail(widgetId, screenshot, isCurrent);
3251
3259
  if (!isCurrent()) return;
3252
3260
  capturedCanvas?.updateWidgetImage(widgetId, screenshot);
@@ -3260,7 +3268,7 @@
3260
3268
  }
3261
3269
  }
3262
3270
 
3263
- /** Screenshot: capture the live WidgetShape iframe (CDN or Worker), not Fabric wireframe. */
3271
+ /** Screenshot: capture the live WidgetShape iframe (CDN or Worker), not the wireframe on the canvas. */
3264
3272
  async function handleChatScreenshot(widgetId?: string | null, requiredIframe: HTMLIFrameElement | null = null, quiet = false): Promise<string | null> {
3265
3273
  const targetId = widgetId || focusedPanelWidgetId || selectedWidgetId;
3266
3274
  if (!targetId) {
@@ -3329,7 +3337,7 @@
3329
3337
  console.warn('[Chat→Screenshot] Live iframe capture failed:', fromLive.error);
3330
3338
  }
3331
3339
 
3332
- // Explicit refresh must not persist a different version or a stale Fabric image.
3340
+ // Explicit refresh must not persist a different version or a stale canvas image.
3333
3341
  if (requiredIframe) return null;
3334
3342
  // Quiet thumbnail sync must NEVER construct a temporary hidden iframe and compile worker preview.
3335
3343
  if (quiet) return null;
@@ -3338,14 +3346,14 @@
3338
3346
  const fromWorker = await captureViaHiddenWorkerPreview(targetId);
3339
3347
  if (fromWorker && fromWorker.length > 500) return fromWorker;
3340
3348
 
3341
- // 3) Last resort: Fabric thumbnail (often stale / wireframe) — only if nothing else works
3349
+ // 3) Last resort: the canvas's own thumbnail (often stale / wireframe) — only if nothing else works
3342
3350
  const shapeDataUrl =
3343
3351
  typeof canvasRef?.getWidgetShapeDataUrl === 'function'
3344
3352
  ? canvasRef.getWidgetShapeDataUrl(targetId)
3345
3353
  : null;
3346
3354
  if (shapeDataUrl && shapeDataUrl.length > 100) {
3347
3355
  console.warn(
3348
- '[Chat→Screenshot] Falling back to Fabric thumbnail (may be stale wireframe)',
3356
+ '[Chat→Screenshot] Falling back to the canvas thumbnail (may be stale wireframe)',
3349
3357
  targetId.substring(0, 8),
3350
3358
  );
3351
3359
  return shapeDataUrl;
@@ -6385,8 +6393,12 @@
6385
6393
  ? false
6386
6394
  : (VITE_DEBUG_MODE === 'true' || VITE_DEBUG_MODE === '1' || !isProduction);
6387
6395
 
6396
+ // A host that keeps the preference itself (the site, per account) says whether debug starts ON; the creator then neither
6397
+ // reads nor writes its own stored copy, which was one flag for every account of the browser.
6398
+ const hostOwnsDebugPreference = hostProvidedDebug && typeof initialDebugOn === 'boolean';
6399
+
6388
6400
  // debugMode — current ON/OFF state. User can still toggle when the UI is available.
6389
- let debugMode = debugModeAvailable;
6401
+ let debugMode = hostOwnsDebugPreference ? debugModeAvailable && initialDebugOn === true : debugModeAvailable;
6390
6402
  $: codegenErrorDisplay = { debugMode, ...CODEGEN_ERROR_DISPLAY };
6391
6403
  $: canvasLoadErrorDisplay = { debugMode, ...CANVAS_LOAD_ERROR_DISPLAY };
6392
6404
  /** Mobile embedded sketch: Canvas | Chat tabs (both panes stay mounted; CSS hides the inactive one). */
@@ -6536,39 +6548,6 @@
6536
6548
  }
6537
6549
  }
6538
6550
 
6539
- $: sketchBoardStatusChip = (() => {
6540
- if (!embeddedSketchShell) return null;
6541
- const id = canvasPrimaryWidgetId;
6542
- if (!id) return null;
6543
- if (generatingWidgetIds[id] || sketchWidgetHasActiveCodegenOperation(id)) {
6544
- return { variant: 'generating' as const, label: $t('creator.sketch.boardGenerating') };
6545
- }
6546
- const ps = getPanelDisplayState(id);
6547
- const w = getWidgetById(id) as Record<string, unknown> | null;
6548
- const codegenStatus = String(
6549
- (w?.codegenStatus as string | undefined) ?? (w?.codegen_status as string | undefined) ?? '',
6550
- ).trim();
6551
- const failed =
6552
- ps.lastGenerationFailed
6553
- || codegenStatus === 'failed'
6554
- || (w as { generationFailed?: boolean } | null)?.generationFailed === true
6555
- || (w as { generation_failed?: boolean } | null)?.generation_failed === true;
6556
- if (failed) {
6557
- return {
6558
- variant: 'failed' as const,
6559
- label: $t('creator.sketch.boardFailed'),
6560
- actionLabel: $t('creator.sketch.boardFailedRetry'),
6561
- };
6562
- }
6563
- if (sketchPrimaryShowsLiveBadge(id)) {
6564
- return null;
6565
- }
6566
- if (sketchPrimaryHasGeneratedCode(id)) {
6567
- return { variant: 'ready' as const, label: $t('creator.sketch.boardReady') };
6568
- }
6569
- return null;
6570
- })();
6571
-
6572
6551
  function handleSketchBarTitleClick() {
6573
6552
  if (canvasPrimaryWidgetId) {
6574
6553
  void openWidgetDetailsPanel(canvasPrimaryWidgetId);
@@ -6587,8 +6566,10 @@
6587
6566
 
6588
6567
  $: sketchCanvasShowZoom = embeddedSketchShell || debugMode;
6589
6568
  $: sketchCanvasPanZoomPosition = (embeddedSketchShell ? 'BL' : 'TL') as 'BL' | 'TL';
6569
+ $: canvasWorkspaceStorageId =
6570
+ workspaceType === 'organization' && organizationId ? `organization:${organizationId}` : 'personal';
6590
6571
  $: sketchCanvasShowSaveButton = embeddedSketchShell ? false : showSaveButton;
6591
- if (debugModeAvailable && typeof window !== 'undefined') {
6572
+ if (debugModeAvailable && !hostOwnsDebugPreference && typeof window !== 'undefined') {
6592
6573
  try {
6593
6574
  const storedDebugMode = creatorStorage.getItem('widgetic:site-debug-on');
6594
6575
  if (storedDebugMode === '1' || storedDebugMode === 'true') debugMode = true;
@@ -6776,7 +6757,8 @@
6776
6757
  debugMode = !debugMode;
6777
6758
  if (!debugMode) brandKitEnabled = false;
6778
6759
  try {
6779
- creatorStorage.setItem('widgetic:site-debug-on', debugMode ? '1' : '0');
6760
+ // The host that owns the preference stores it (it is told below); the creator's own copy is for standalone use
6761
+ if (!hostOwnsDebugPreference) creatorStorage.setItem('widgetic:site-debug-on', debugMode ? '1' : '0');
6780
6762
  } catch (err) {
6781
6763
  console.warn('[WidgetCreator] Could not persist debug mode', err);
6782
6764
  }
@@ -6961,6 +6943,13 @@
6961
6943
  announceToSite('widgetic:creator-save-state', { dirty });
6962
6944
  }
6963
6945
 
6946
+ /** The canvas says the person changed the board (a shape, a property, the letters of a text): it is unsaved until a save goes through. */
6947
+ function handleCanvasDirty(): void {
6948
+ canvasEditRevision += 1;
6949
+ emitCreatorSaveState(true);
6950
+ scheduleSketchPrefillFromCanvasDirty();
6951
+ }
6952
+
6964
6953
  function handleHostSaveCanvasEvent(): void {
6965
6954
  // Explicit Save must always persist — bypass soft load-cooldown / not-ready guards.
6966
6955
  const json = canvasRef?.saveCanvas?.() ?? null;
@@ -7602,7 +7591,8 @@
7602
7591
  // This tab learned of it from the browser's own store: the other tabs may not know of it yet
7603
7592
  if (origin === 'stored') generationChannel?.announceStarted(widgetId, operationId);
7604
7593
  // (A refused request has been told already, in the words of its refusal)
7605
- if (widgetId === focusedPanelWidgetId && origin !== 'stop-failed' && origin !== 'refused') {
7594
+ // In the sketch layout the side chat is where the generation is told: no toast over the canvas.
7595
+ if (widgetId === focusedPanelWidgetId && origin !== 'stop-failed' && origin !== 'refused' && !embeddedSketchShell) {
7606
7596
  showToast('info', $t('creator.codegen.generationInProgress'), {
7607
7597
  description: $t('creator.codegen.reconnectedToAnActiveCode'),
7608
7598
  duration: 4000
@@ -8469,7 +8459,7 @@
8469
8459
  return;
8470
8460
  }
8471
8461
  } else {
8472
- // Recreate at the current viewport center. A shape added while Fabric is still
8462
+ // Recreate at the current viewport center. A shape added while the canvas is still
8473
8463
  // 300×150 lands off-screen after the canvas grows to the full page.
8474
8464
  canvasRef.onClearAllObjects?.();
8475
8465
  }
@@ -10858,6 +10848,9 @@
10858
10848
  if (promptImages.length > 0) {
10859
10849
  chatMethods.restoreAttachmentsFromDataUrls?.(promptImages);
10860
10850
  }
10851
+ } else if (promptImages.length > 0 && !hostInitialMessage) {
10852
+ // A draft of only pictures is a draft too (it used to be cleared as if it were empty).
10853
+ chatMethods.restoreAttachmentsFromDataUrls?.(promptImages);
10861
10854
  } else if (hostInitialMessage && !appliedInitialMessage) {
10862
10855
  // The host opened a new widget with a message for it (a link to replicate): it goes into the input first, so
10863
10856
  // a person whose message could not be sent still has it, and is sent after the restore when the host asked.
@@ -11309,7 +11302,7 @@
11309
11302
  if (!openWidgetPanelIds.includes(widgetId)) {
11310
11303
  if (quiet || isConvertOrDraftPanelOpen()) {
11311
11304
  // A draft convert has no widget row and no live iframe yet — the
11312
- // Fabric sketch is genuinely all there is to show.
11305
+ // canvas sketch is genuinely all there is to show.
11313
11306
  if (isDraftConvertId(widgetId)) {
11314
11307
  const draftShapeDataUrl = canvasRef?.getWidgetShapeDataUrl?.(widgetId);
11315
11308
  if (draftShapeDataUrl && canvasRef) {
@@ -11322,7 +11315,7 @@
11322
11315
  // is still on the canvas. Capture from it so both the canvas image
11323
11316
  // and the project-list thumbnail track the latest preview.
11324
11317
  //
11325
- // Without this the Fabric `_imageElement` set at convert time wins
11318
+ // Without this the image set on the canvas shape at convert time wins
11326
11319
  // forever — it is the sketch screenshot frozen at creation, so the
11327
11320
  // Projects list kept showing the initial design after later
11328
11321
  // generations and preview refreshes.
@@ -12981,7 +12974,8 @@ Requirements:
12981
12974
  // A refusal because of a limit (credits used up) is told in the chat alone when the page asked for that
12982
12975
  // (`limitNotices: 'chat'`): the toast would say the same thing a second time. Any other failure keeps its toast.
12983
12976
  const refusedForALimit = await responseIsALimit(error?.response);
12984
- if (!limitRefusalNeedsNoToast(limitNoticeMode, refusedForALimit)) {
12977
+ // In the sketch layout the failure is told in the side chat (`pushCodegenFailureToChat` below), not in a toast.
12978
+ if (!limitRefusalNeedsNoToast(limitNoticeMode, refusedForALimit) && !embeddedSketchShell) {
12985
12979
  showToast('error', $t('creator.codegen.codeGenerationError'), { description: message, duration: 6000 });
12986
12980
  }
12987
12981
  pushCodegenFailureToChat(generationWidgetId, message);
@@ -15588,7 +15582,7 @@ Requirements:
15588
15582
  try {
15589
15583
  canvasSelectedWidgetShapeId = canvasRef?.getSelectedWidgetShapeId?.() ?? null;
15590
15584
  widgetShapeLivePreviewsRef?.sync?.();
15591
- // Hide Fabric screenshots under live iframes (avoids ghost bleed in padding).
15585
+ // Hide the canvas screenshots under live iframes (avoids ghost bleed in padding).
15592
15586
  const rects = canvasRef?.listWidgetShapeScreenRects?.() ?? [];
15593
15587
  const liveWidgetIds = new Set<string>();
15594
15588
  for (const rect of rects) {
@@ -16723,6 +16717,21 @@ Requirements:
16723
16717
  };
16724
16718
  }
16725
16719
  if (!repoId && !hasCode) {
16720
+ if (
16721
+ targetVersion == null &&
16722
+ shouldNudgeSendBeforePublish({
16723
+ hasGeneratedCode: ps.hasGeneratedCode,
16724
+ lastPublishedVersion: ps.lastPublishedVersion,
16725
+ lastCommitId: ps.lastCommitId,
16726
+ })
16727
+ ) {
16728
+ return {
16729
+ disabled: false,
16730
+ label: getPublishButtonLabelFallback(ps),
16731
+ reason: null,
16732
+ showDisabledHint: false,
16733
+ };
16734
+ }
16726
16735
  return {
16727
16736
  disabled: true,
16728
16737
  label: getPublishButtonLabelFallback(ps),
@@ -16761,10 +16770,10 @@ Requirements:
16761
16770
 
16762
16771
  if (!hasCode) {
16763
16772
  return {
16764
- disabled: true,
16773
+ disabled: false,
16765
16774
  label: getPublishButtonLabelFallback(ps),
16766
- reason: $t('creator.publish.generateWidgetCodeBeforePublishing'),
16767
- showDisabledHint: true,
16775
+ reason: null,
16776
+ showDisabledHint: false,
16768
16777
  };
16769
16778
  }
16770
16779
 
@@ -16939,6 +16948,16 @@ Requirements:
16939
16948
  * omit it to publish the newest generated code. The promise ends when the request is over; the buttons that start it do
16940
16949
  * not wait for it, and `publish()` (the host's control) does.
16941
16950
  */
16951
+ let sendNudgeTokenByWidgetId: Record<string, number> = {};
16952
+
16953
+ function requestSendNudgeForPanel(panelWidgetId: string): void {
16954
+ focusWidgetPanel(panelWidgetId);
16955
+ sendNudgeTokenByWidgetId = {
16956
+ ...sendNudgeTokenByWidgetId,
16957
+ [panelWidgetId]: (sendNudgeTokenByWidgetId[panelWidgetId] ?? 0) + 1,
16958
+ };
16959
+ }
16960
+
16942
16961
  function runPublishForPanel(panelWidgetId: string, targetVersion?: number | null): Promise<void> {
16943
16962
  return (async () => {
16944
16963
  if (isPublishing && !publishingWidgetId) {
@@ -16950,6 +16969,19 @@ Requirements:
16950
16969
  return;
16951
16970
  }
16952
16971
 
16972
+ const ps = getPanelDisplayState(panelWidgetId);
16973
+ if (
16974
+ targetVersion == null &&
16975
+ shouldNudgeSendBeforePublish({
16976
+ hasGeneratedCode: ps.hasGeneratedCode,
16977
+ lastPublishedVersion: ps.lastPublishedVersion,
16978
+ lastCommitId: ps.lastCommitId,
16979
+ })
16980
+ ) {
16981
+ requestSendNudgeForPanel(panelWidgetId);
16982
+ return;
16983
+ }
16984
+
16953
16985
  // Gate BEFORE focus/tick — focusing can reconcile HEAD/live SHA mid-click and
16954
16986
  // used to toast "already live" after the button still said "Publish new vN".
16955
16987
  const gateBefore = getPublishGateForPanel(panelWidgetId, targetVersion ?? null);
@@ -17500,46 +17532,6 @@ $: if (selectedWidgetId && canvasRef && conversationsClient && messagesClient &&
17500
17532
  }
17501
17533
  }
17502
17534
 
17503
- // Show "Confirm Generation" dialog for converted widgets that have a prompt + repo
17504
- // but no generated code yet. Separate from DB sync so it triggers on every widget
17505
- // selection and page refresh, not just the first time.
17506
- // Uses setTimeout to allow async prompt loading to finish before evaluating.
17507
- let autoGenDialogCheckedForWidgetId: string | null = null;
17508
- $: if (selectedWidgetId && autoGenDialogCheckedForWidgetId !== selectedWidgetId) {
17509
- // Draft convert panels: chat is already prefilled with the convert prompt —
17510
- // the confirm dialog would be redundant and targets a non-existent widget.
17511
- if (isDraftConvertId(selectedWidgetId)) {
17512
- autoGenDialogCheckedForWidgetId = selectedWidgetId;
17513
- } else {
17514
- autoGenDialogCheckedForWidgetId = selectedWidgetId;
17515
- const capturedWidgetId = selectedWidgetId;
17516
- setTimeout(() => {
17517
- if (capturedWidgetId !== selectedWidgetId) return;
17518
- if (skipAutoGenConfirmWidgetIds.has(capturedWidgetId)) {
17519
- skipAutoGenConfirmWidgetIds.delete(capturedWidgetId);
17520
- return;
17521
- }
17522
- if (isGeneratingCode || confirmGenerateDialogOpen) return;
17523
- const widgetForDialog = getWidgetById(capturedWidgetId);
17524
- const panelSnap = getPanelState(capturedWidgetId);
17525
- const hasRepo = !!normalizeRepositoryId(widgetForDialog);
17526
- const publishedVersion = panelSnap.lastPublishedVersion ?? resolvePublishedVersionFromWidget(widgetForDialog);
17527
- const hasNoCode = !panelSnap.lastCommitId
17528
- && publishedVersion == null
17529
- && (panelSnap.publishHistory?.length ?? 0) === 0;
17530
- const hasPrompt = codeGenerationPrompt !== DEFAULT_PROMPT || promptImages.length > 0;
17531
- const hasPreview = widgetDetails?.hasValidPreview() ?? false;
17532
- if (hasRepo && hasNoCode && !hasPreview && hasPrompt) {
17533
- // console.log('[AutoGenDialog] Widget has repo + prompt but no code — showing confirm generation dialog');
17534
- confirmGenerateWidgetId = capturedWidgetId;
17535
- confirmGenerateDialogOpen = true;
17536
- } else {
17537
- // console.log('[AutoGenDialog] Conditions not met:', { hasRepo, hasNoCode, hasPreview, hasPrompt, lastCommitId, lastPublishedVersion });
17538
- }
17539
- }, 1500);
17540
- }
17541
- }
17542
-
17543
17535
  // Auto-save prompt text to the durable draft when it changes (debounced 500ms)
17544
17536
  let promptSaveDebounceTimer: ReturnType<typeof setTimeout> | null = null;
17545
17537
  $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === selectedWidgetId) {
@@ -17935,7 +17927,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17935
17927
 
17936
17928
  // ─── Canvas Handlers ───────────────────────────────────────────────
17937
17929
 
17938
- /** Debounce Fabric dblclick bursts (same shape can fire twice). */
17930
+ /** Debounce canvas dblclick bursts (same shape can fire twice). */
17939
17931
  let lastWidgetShapeClickAt = 0;
17940
17932
  let lastWidgetShapeClickId = '';
17941
17933
  const WIDGET_SHAPE_CLICK_DEBOUNCE_MS = 450;
@@ -18412,11 +18404,28 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18412
18404
  requestAnimationFrame(() => {
18413
18405
  setTimeout(() => applyPrimarySelectionOnCanvas(primaryId), 80);
18414
18406
  });
18407
+ centerSketchInMainWindowOnce();
18415
18408
  syncWidgetShapeLivePreviews();
18416
18409
  singleWidgetChromeReady = true;
18417
18410
  void ensureSimpleCanvasChat();
18418
18411
  }
18419
18412
 
18413
+ /**
18414
+ * The drawing from the Home page, in the middle of the main window. The fit never zooms in past 100%, so a small
18415
+ * sketch is centred, not blown up. Only the first load after Home: a person who moves the board is left alone.
18416
+ */
18417
+ function centerSketchInMainWindowOnce() {
18418
+ if (!centerSketchOnFirstLoad) return;
18419
+ centerSketchOnFirstLoad = false;
18420
+ requestAnimationFrame(() => {
18421
+ try {
18422
+ canvasRef?.zoomFit?.();
18423
+ } catch (error) {
18424
+ console.warn('[CreatorApp] Could not centre the drawing from Home in the main window', error);
18425
+ }
18426
+ });
18427
+ }
18428
+
18420
18429
  /**
18421
18430
  * Loads saved canvas state from API (or localStorage fallback).
18422
18431
  * Only runs when both canvasId is resolved and the Canvas component is ready.
@@ -18435,7 +18444,11 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18435
18444
  canvasLoadFailsafeArmedForId = null;
18436
18445
  }
18437
18446
  function markCanvasStateLoaded() {
18438
- if (!isCanvasStateLoaded) markCanvasOpenStep('creator:canvas-state-loaded');
18447
+ if (!isCanvasStateLoaded) {
18448
+ markCanvasOpenStep('creator:canvas-state-loaded');
18449
+ // What was reported before the board loaded belongs to the board that was there: the guard starts again from here.
18450
+ canvasRevisionPassedGuard = canvasEditRevision;
18451
+ }
18439
18452
  isCanvasStateLoaded = true;
18440
18453
  canvasHydrateRetryCount = 0;
18441
18454
  clearCanvasHydrateRetry();
@@ -18616,7 +18629,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18616
18629
  // Persist remote state to local cache for subsequent instant loads
18617
18630
  saveCanvasState(canvasId, jsonString);
18618
18631
 
18619
- // Only re-hydrate Fabric if remote state differs from what was painted by SWR
18632
+ // Only re-hydrate the canvas if remote state differs from what was painted by SWR
18620
18633
  const shouldRehydrate = !localCachedJson || jsonString !== localCachedJson;
18621
18634
  if (shouldRehydrate) {
18622
18635
  if (loadEpoch !== canvasLoadEpoch || ignoreIncomingCanvasLoads) {
@@ -18752,6 +18765,15 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18752
18765
  */
18753
18766
  let autosaveSequence = 0;
18754
18767
  let lastResolvedAutosaveSequence = 0;
18768
+ /**
18769
+ * What `handleCanvasAutoSave` did with the canvas it was given:
18770
+ * - `skipped`: nothing was kept (the canvas is not ready, or a guard refused an empty snapshot);
18771
+ * - `held`: kept back for the few seconds after a load, and sent when they are over;
18772
+ * - `local`: kept on this device only (there is no canvas row or client to send it to yet);
18773
+ * - `saved`: the API has it;
18774
+ * - `failed`: the API refused it; the copy on this device is written.
18775
+ */
18776
+ type CanvasSaveOutcome = 'skipped' | 'held' | 'local' | 'saved' | 'failed';
18755
18777
  /** The requests that write the canvas to the API, one at a time and in the order they were made (see `handleCanvasAutoSave`). */
18756
18778
  const canvasSaveQueue = createSerialQueue();
18757
18779
  /** How long after a canvas load we still defer (not drop) autosaves. */
@@ -18776,21 +18798,23 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18776
18798
  async function handleCanvasAutoSave(
18777
18799
  json: string | null,
18778
18800
  isUnmountSave = false,
18779
- opts: { force?: boolean } = {},
18780
- ) {
18801
+ opts: { force?: boolean; pageIsLeaving?: boolean } = {},
18802
+ ): Promise<CanvasSaveOutcome> {
18781
18803
  if (!json) {
18782
18804
  if (isUnmountSave) console.warn('[CanvasDebug] onBeforeUnmount: saveCanvas returned null — canvas not initialized');
18783
- return;
18805
+ return 'skipped';
18784
18806
  }
18785
18807
 
18786
18808
  const force = opts.force === true;
18809
+ // The changes this save takes with it: a change reported while it is on its way is not saved by it.
18810
+ const editRevisionAtStart = canvasEditRevision;
18787
18811
 
18788
18812
  // Guard: don't overwrite DB with an empty canvas if state hasn't loaded yet
18789
18813
  if (!force && !isCanvasStateLoaded) {
18790
18814
  // console.log(
18791
18815
  // '[CanvasDebug] Skipping autosave — canvas state not loaded yet (guard active, avoids overwrite with empty)'
18792
18816
  // );
18793
- return;
18817
+ return 'skipped';
18794
18818
  }
18795
18819
 
18796
18820
  // Guard: skip autosaves triggered by loadCanvas() object:added events
@@ -18802,7 +18826,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18802
18826
  // persisted rather than silently discarded.
18803
18827
  if (!force && isLoadCooldownActive && !isUnmountSave) {
18804
18828
  heldCooldownAutosave.hold(json);
18805
- return;
18829
+ return 'held';
18806
18830
  }
18807
18831
 
18808
18832
  let objectCount = 0;
@@ -18827,11 +18851,20 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18827
18851
 
18828
18852
  // Guard: prevent saving empty canvas over non-empty data.
18829
18853
  // Unmount saves (HMR) are always blocked when going from N→0.
18830
- // Normal autosaves going from N→0 are allowed only if the drop is gradual
18831
- // (user deleted objects one by one) — a sudden jump from many to 0 is suspicious.
18832
- // Explicit Save (force) still blocks sudden N→0 to avoid wiping the canvas.
18854
+ // Normal autosaves going from N→0 are allowed when the drop is gradual (user deleted objects one by one), and when
18855
+ // the canvas has reported a change since the last save got past this guard (`canvasEditRevision`): a person who
18856
+ // selects everything and deletes it has emptied the board on purpose, and the server must not keep the old shapes.
18857
+ // A canvas that looks empty with no change reported is a snapshot gone wrong, and is still refused.
18858
+ // Explicit Save (force) follows the same rule.
18833
18859
  if (objectCount === 0 && lastSavedCanvasObjectCount > 0) {
18834
- if (isUnmountSave || lastSavedCanvasObjectCount > 1) {
18860
+ if (
18861
+ refusesEmptyCanvas({
18862
+ shapesToSave: objectCount,
18863
+ shapesSavedBefore: lastSavedCanvasObjectCount,
18864
+ isUnmountSave,
18865
+ changedSinceLastSave: canvasEditRevision > canvasRevisionPassedGuard,
18866
+ })
18867
+ ) {
18835
18868
  console.warn(
18836
18869
  `[CanvasDebug] BLOCKING save: would overwrite ${lastSavedCanvasObjectCount} shapes with 0 (isUnmount=${isUnmountSave}, force=${force})`
18837
18870
  );
@@ -18840,7 +18873,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18840
18873
  description: $t('creator.canvas.canvasSnapshotLookedEmptyRefresh'),
18841
18874
  });
18842
18875
  }
18843
- return;
18876
+ return 'skipped';
18844
18877
  }
18845
18878
  // lastSavedCanvasObjectCount === 1 → user deleted the last object, allow it
18846
18879
  // console.log('[CanvasDebug] Allowing save: last object deleted by user (1→0)');
@@ -18852,9 +18885,10 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18852
18885
 
18853
18886
  lastSavedCanvasObjectCount = objectCount;
18854
18887
  try { creatorSessionStorage.setItem(CANVAS_OBJ_COUNT_KEY, String(objectCount)); } catch {}
18888
+ // The changes reported so far are in this save: the next empty canvas needs a change of its own to be written.
18889
+ canvasRevisionPassedGuard = editRevisionAtStart;
18855
18890
  noteDrawnObjectCount(countDrawnCanvasObjectsInJson(json));
18856
18891
  maybeSyncSketchGeneratePrefill();
18857
- emitCreatorSaveState(false);
18858
18892
 
18859
18893
  // Save to durable L1 fallback (always, even with 0 objects for legitimate clears)
18860
18894
  saveCanvasState(canvasId, json);
@@ -18880,11 +18914,19 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18880
18914
  }
18881
18915
 
18882
18916
  // Save to API via SDK with sequence race protection
18917
+ let outcome: CanvasSaveOutcome = 'local';
18883
18918
  if (canvasId && canvasesClient) {
18884
18919
  const currentSeq = ++autosaveSequence;
18885
18920
  // The canvas this save is for, read now: the request waits its turn in the queue, and the person may switch canvas meanwhile.
18886
18921
  const saveCanvasId = canvasId;
18887
18922
  const saveClient = canvasesClient;
18923
+ // A page that is going away (the tab closes, a reload) drops a request that is still on its way, and the last
18924
+ // changes would be lost. `keepalive` lets the browser finish it; it takes bodies up to 64 KB, so a larger canvas goes as usual.
18925
+ const requestInit = requestInitForSave(json, {
18926
+ isUnmountSave,
18927
+ pageIsLeaving: opts.pageIsLeaving === true,
18928
+ visibilityState: typeof document !== 'undefined' ? document.visibilityState : null,
18929
+ });
18888
18930
  try {
18889
18931
  // One request at a time, in the order the canvas was changed: two in flight can reach the server in either
18890
18932
  // order, and the older canvas would overwrite the newer one.
@@ -18894,14 +18936,16 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18894
18936
  updateCanvasRequest: {
18895
18937
  canvasContent: parsedCanvas ?? JSON.parse(json)
18896
18938
  }
18897
- })
18939
+ }, requestInit)
18898
18940
  );
18899
18941
  canvasRecordReads.delete(saveCanvasId);
18942
+ outcome = 'saved';
18943
+ autosaveFailureToldToPerson = false;
18900
18944
  if (currentSeq < lastResolvedAutosaveSequence) {
18901
18945
  // console.log(
18902
18946
  // `[CanvasDebug] Dropped out-of-order autosave response (${currentSeq} < ${lastResolvedAutosaveSequence})`
18903
18947
  // );
18904
- return;
18948
+ return outcome;
18905
18949
  }
18906
18950
  lastResolvedAutosaveSequence = currentSeq;
18907
18951
  if (force) {
@@ -18912,10 +18956,18 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18912
18956
  // );
18913
18957
  } catch (err) {
18914
18958
  console.warn('[WidgetCreator] Failed to save canvas to API:', err);
18959
+ outcome = 'failed';
18915
18960
  if (force) {
18916
18961
  showToast('error', $t('creator.canvas.canvasSaveFailed'), {
18917
18962
  description: $t('creator.general.keptALocalCopyCheck'),
18918
18963
  });
18964
+ } else if (!isUnmountSave && !autosaveFailureToldToPerson) {
18965
+ // An automatic save the person did not ask for: said once, until a save goes through again.
18966
+ autosaveFailureToldToPerson = true;
18967
+ showToast('error', $t('creator.canvas.canvasSaveFailed'), {
18968
+ description: $t('creator.canvas.autosaveFailedWillRetry'),
18969
+ duration: 8000,
18970
+ });
18919
18971
  }
18920
18972
  }
18921
18973
  } else if (force) {
@@ -18925,7 +18977,24 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18925
18977
  });
18926
18978
  }
18927
18979
 
18980
+ // The page around the creator says "saved" once the server has the canvas (or there is no server to send it to), and
18981
+ // only if nothing was changed while the save was on its way: a refused save leaves it saying there are changes.
18982
+ if (outcome !== 'failed' && editRevisionAtStart === canvasEditRevision) emitCreatorSaveState(false);
18983
+
18928
18984
  refreshLinkedWidgetIds();
18985
+ return outcome;
18986
+ }
18987
+
18988
+ /**
18989
+ * What the canvas's own autosave calls. The same save as `handleCanvasAutoSave`, with one difference: when the API
18990
+ * refuses it, this rejects, so the canvas keeps the board marked as unsaved and asks again (a swallowed failure told
18991
+ * the person "saved" for a board the server never got). Everything else that saves the canvas keeps the quiet
18992
+ * version: a rejection there would stop a flow that does not care.
18993
+ */
18994
+ async function saveCanvasForHost(json: string | null, context?: { leaving?: boolean }): Promise<void> {
18995
+ // The canvas says when the page is going away (`pagehide`): that save has to be a request that outlives the page.
18996
+ const outcome = await handleCanvasAutoSave(json, false, { pageIsLeaving: context?.leaving === true });
18997
+ if (outcome === 'failed') throw new Error('The canvas could not be saved to the server');
18929
18998
  }
18930
18999
 
18931
19000
  /**
@@ -19790,7 +19859,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19790
19859
  <LogoWidgeticType class="wc-logo-type h-5 w-auto" />
19791
19860
  <span class="wc-creator-label text-[28px] mt-0.5" style="color: #314F2F;">creator</span>
19792
19861
  </div>
19793
- {#if debugModeAvailable}
19862
+ {#if isDebugTabVisible({ debugEnabled: debugMode, isAdmin: debugModeAvailable })}
19794
19863
  <span
19795
19864
  class="wc-build-info text-[10px] font-mono text-gray-400 leading-none ps-0.5"
19796
19865
  title="Deployed build — remove when beta ends"
@@ -19827,13 +19896,13 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19827
19896
  : ` · ${trialCounter.days} ${trialCounter.days === 1 ? 'day' : 'days'}`}
19828
19897
  </span>
19829
19898
  {/if}
19830
- {#if debugModeAvailable}
19831
- <HoverTooltip text={debugMode ? 'Debug mode ON — click to disable (hides console tab, widgets panel)' : 'Debug mode OFF — click to enable'}>
19899
+ {#if isDebugTabVisible({ debugEnabled: debugMode, isAdmin: debugModeAvailable })}
19900
+ <HoverTooltip text={'Debug mode ON — click to disable (hides console tab, widgets panel)'}>
19832
19901
  <button
19833
19902
  onclick={toggleDebugMode}
19834
- class="wc-debug-toggle px-2.5 py-1 cursor-pointer text-xs font-medium rounded-lg border transition-colors {debugMode ? 'bg-red-50 border-red-400 text-red-600 hover:bg-red-100' : 'bg-gray-100 border-gray-300 text-gray-500 hover:bg-gray-200'}"
19903
+ class="wc-debug-toggle px-2.5 py-1 cursor-pointer text-xs font-medium rounded-lg border transition-colors bg-red-50 border-red-400 text-red-600 hover:bg-red-100"
19835
19904
  >
19836
- 🐛 Debug {debugMode ? 'ON' : 'OFF'}
19905
+ 🐛 Debug ON
19837
19906
  </button>
19838
19907
  </HoverTooltip>
19839
19908
  {/if}
@@ -19915,11 +19984,11 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19915
19984
  customizeLabel={$t('creator.sketch.customize')}
19916
19985
  showPublish={sketchBarShowPublish}
19917
19986
  publishLabel={sketchBarPublishLabel}
19918
- publishDisabled={!canvasPrimaryWidgetId || isPublishDisabledForPanel(canvasPrimaryWidgetId)}
19987
+ publishDisabled={!!canvasPrimaryWidgetId && isPublishDisabledForPanel(canvasPrimaryWidgetId)}
19919
19988
  onBack={() => window.dispatchEvent(new CustomEvent('widgetic:host-request-back'))}
19920
19989
  onTitleClick={handleSketchBarTitleClick}
19921
19990
  onCustomize={handleSketchCustomize}
19922
- onPublish={() => window.dispatchEvent(new CustomEvent('widgetic:host-request-publish'))}
19991
+ onPublish={() => void publish()}
19923
19992
  />
19924
19993
  {/if}
19925
19994
  <div
@@ -19935,14 +20004,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19935
20004
  : ''}"
19936
20005
  aria-hidden={embeddedSketchShell && embeddedSketchMobileTab !== 'canvas' ? 'true' : undefined}
19937
20006
  >
19938
- {#if sketchBoardStatusChip}
19939
- <CanvasBoardStatusChip
19940
- variant={sketchBoardStatusChip.variant}
19941
- label={sketchBoardStatusChip.label}
19942
- actionLabel={'actionLabel' in sketchBoardStatusChip ? sketchBoardStatusChip.actionLabel : ''}
19943
- onAction={'actionLabel' in sketchBoardStatusChip ? () => void handleSketchRetryFailedGeneration() : undefined}
19944
- />
19945
- {/if}
20007
+ <!-- Generating, ready and failed are said in the side chat only: nothing about the generation is drawn over the canvas. -->
19946
20008
  <!-- Embedded: Debug toggle lives in site AppHeader (avoids overlapping Props Panel). -->
19947
20009
  {#if canvasApiLoadError || canvasShapesMissingWarning}
19948
20010
  <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">
@@ -19981,7 +20043,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19981
20043
  advancedFeatures={canvasAdvancedFeatures}
19982
20044
  showZoomPanel={sketchCanvasShowZoom}
19983
20045
  onReady={handleCanvasReady}
19984
- onAutoSave={handleCanvasAutoSave}
20046
+ onAutoSave={saveCanvasForHost}
19985
20047
  onBeforeUnmount={(json) => {
19986
20048
  // console.log('[CanvasDebug] onBeforeUnmount fired, json length:', json?.length ?? 0, 'lastSavedCount:', lastSavedCanvasObjectCount);
19987
20049
  handleCanvasAutoSave(json, true);
@@ -19991,10 +20053,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19991
20053
  }}
19992
20054
  onRecognizeStroke={handleRecognizeStroke}
19993
20055
  onWidgetImageClick={handleWidgetImageClick}
19994
- onCanvasDirty={() => {
19995
- emitCreatorSaveState(true);
19996
- scheduleSketchPrefillFromCanvasDirty();
19997
- }}
20056
+ onCanvasDirty={handleCanvasDirty}
19998
20057
  onWidgetShapeDuplicated={handleWidgetShapeDuplicated}
19999
20058
  onWidgetShapeDeleting={handleWidgetShapeDeleting}
20000
20059
  onWidgetRename={handleWidgetRename}
@@ -20038,8 +20097,10 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20038
20097
  }}
20039
20098
  panZoomPosition={sketchCanvasPanZoomPosition}
20040
20099
  toolbarPosition={toolbarPosition}
20100
+ workspaceId={canvasWorkspaceStorageId}
20101
+ workspaceFonts={canvasWorkspaceFonts ?? []}
20041
20102
  showSaveButton={sketchCanvasShowSaveButton}
20042
- autosaveDelayMs={import.meta.env.DEV ? 15000 : 5000}
20103
+ autosaveDelayMs={CANVAS_AUTOSAVE_DELAY_MS}
20043
20104
  autosaveMaxWaitMs={CANVAS_AUTOSAVE_MAX_WAIT_MS}
20044
20105
  suspendAutosave={suspendCanvasAutosave}
20045
20106
  isExternalDataLoading={!isCanvasStateLoaded}
@@ -20650,10 +20711,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20650
20711
  }
20651
20712
 
20652
20713
  if (hasPrompt) {
20653
- // Show confirm generation dialog
20654
- confirmGenerateWidgetId = widgetId;
20655
- confirmGenerateDialogOpen = true;
20656
- // console.log('[RetryRepo] Showing confirm generation dialog for widget:', widgetId);
20714
+ // The chat builds the widget: the prompt waits in its input for the person to send it
20715
+ syncPromptToChatDraft(widgetId);
20657
20716
  } else {
20658
20717
  widgetDetails?.showNoCodeYetState();
20659
20718
  // console.log('[RetryRepo] No prompt available — showing No Code Yet state');
@@ -20687,8 +20746,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20687
20746
  void fixWidgetCompileError(widgetId, compileErr);
20688
20747
  return;
20689
20748
  }
20690
- confirmGenerateWidgetId = widgetId;
20691
- confirmGenerateDialogOpen = true;
20749
+ // The chat builds the widget: the prompt waits in its input for the person to send it
20750
+ syncPromptToChatDraft(widgetId);
20692
20751
  }}
20693
20752
  on:widgetDetailsToggle={({ detail }) => {
20694
20753
  const isClosing = detail?.open === false || detail?.showWidgetDetails === false;
@@ -21125,7 +21184,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
21125
21184
  showHeader={false}
21126
21185
  showPanelHeader={dockedChatPanel}
21127
21186
  headerTitle={panelWidget?.name || ''}
21128
- showConsoleControl={dockedChatPanel}
21187
+ showConsoleControl={dockedChatPanel && isDebugTabVisible({ debugEnabled: debugMode, isAdmin: debugModeAvailable })}
21188
+ sendNudgeToken={sendNudgeTokenByWidgetId[panelWidgetId] ?? 0}
21129
21189
  consoleOpen={!!panelConsoleOpenByWidgetId[panelWidgetId]}
21130
21190
  onToggleConsole={dockedChatPanel
21131
21191
  ? () => {
@@ -21808,60 +21868,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
21808
21868
  </Dialog.Content>
21809
21869
  </Dialog.Root>
21810
21870
 
21811
- <!-- Confirm Generation Dialog (shown on convert-to-widget before auto-generating) -->
21812
- <Dialog.Root
21813
- open={confirmGenerateDialogOpen}
21814
- onOpenChange={(open) => {
21815
- confirmGenerateDialogOpen = open;
21816
- if (!open) confirmGenerateWidgetId = null;
21817
- }}
21818
- >
21819
- <Dialog.Content closeLabel={$t('creator.common.close')} layerBase={creatorDialogLayerBase} class="confirm-generate-dialog-content max-w-lg bg-white z-9999">
21820
- <Dialog.Header class="confirm-generate-dialog-header">
21821
- <Dialog.Title>{$t('creator.codegen.confirmCodeGeneration')}</Dialog.Title>
21822
- <Dialog.Description>
21823
- {promptImages.length > 0
21824
- ? $t('creator.codegen.reviewThePromptAndReference')
21825
- : $t('creator.codegen.describeTheWidgetYouWant')}
21826
- </Dialog.Description>
21827
- </Dialog.Header>
21828
- <div class="flex flex-col gap-3 py-3 px-1">
21829
- <div class="text-xs font-medium text-gray-500 uppercase tracking-wide">{$t('creator.codegen.prompt')}</div>
21830
- <textarea
21831
- bind:value={codeGenerationPrompt}
21832
- class="w-full min-h-[80px] max-h-[160px] rounded-md border border-gray-300 p-2 text-sm resize-y focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent"
21833
- placeholder={$t('creator.general.describeWhatYouWant')}
21834
- ></textarea>
21835
- {#if promptImages.length > 0}
21836
- <div class="text-xs font-medium text-gray-500 uppercase tracking-wide">{$t('creator.codegen.referenceImages', { count: promptImages.length })}</div>
21837
- <div class="flex gap-2 flex-wrap">
21838
- {#each promptImages as img, i}
21839
- <div class="relative">
21840
- <span class="absolute top-0.5 start-0.5 z-10 w-4 h-4 flex items-center justify-center rounded-full bg-blue-600 text-white text-[9px] font-bold shadow">{i + 1}</span>
21841
- <img src={img} alt={$t('creator.codegen.referenceNumber', { number: i + 1 })} class="w-16 h-16 rounded border border-gray-200 object-cover" />
21842
- </div>
21843
- {/each}
21844
- </div>
21845
- {/if}
21846
- </div>
21847
- <div class="flex justify-end gap-2 pt-2">
21848
- <Button variant="outline" size="sm" onclick={() => {
21849
- confirmGenerateDialogOpen = false;
21850
- syncPromptToChatDraft();
21851
- }}>
21852
- {$t('creator.codegen.editPromptFirst')}
21853
- </Button>
21854
- <Button variant="default" size="sm" onclick={() => {
21855
- const targetWidgetId = confirmGenerateWidgetId ?? selectedWidgetId ?? undefined;
21856
- confirmGenerateDialogOpen = false;
21857
- confirmGenerateWidgetId = null;
21858
- generateCode({ widgetId: targetWidgetId });
21859
- }}>
21860
- {$t('creator.codegen.generateNow')}
21861
- </Button>
21862
- </div>
21863
- </Dialog.Content>
21864
- </Dialog.Root>
21871
+
21865
21872
 
21866
21873
  <style>
21867
21874
  /* ── Top Bar: only truly non-Tailwind styles ─────────────── */