@widgetic/creator 0.4.15 → 0.4.17

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.
@@ -161,7 +161,8 @@
161
161
  import {
162
162
  ChatUploadRefusedError,
163
163
  shouldUseTusForChatUpload,
164
- uploadChatFileToWidgeticApi
164
+ uploadChatFileToWidgeticApi,
165
+ uploadIdFromStoredFileUrl
165
166
  } from './utils/widgeticChatUpload.js';
166
167
  import {
167
168
  PARTNER_UPLOAD_FAILED_MESSAGE,
@@ -854,7 +855,7 @@
854
855
  let widgetDetailsOpenTargetId: string | null = null;
855
856
 
856
857
  // Lightweight static imports from canvas (excludes Canvas.svelte — 10K+ lines)
857
- import { Tooltip } from '@widgetic/canvas/components';
858
+ import { Tooltip, CanvasBoardPlaceholder } from '@widgetic/canvas/components';
858
859
  // WidgetConversionPayload lives on the canvas root export (re-exported from
859
860
  // ./canvas); the components barrel only carries the input controls. Type-only
860
861
  // import, so the 10K-line Canvas.svelte still never loads.
@@ -880,6 +881,15 @@
880
881
  type DesignIntentClassification
881
882
  } from './utils/designIntentTelemetry';
882
883
 
884
+ /** Open-time marks (DevTools Performance panel, or `performance.getEntriesByType('mark')`). */
885
+ function markCanvasOpenStep(stepName: string): void {
886
+ try {
887
+ performance.mark(stepName);
888
+ } catch {
889
+ // Marks are diagnostics only.
890
+ }
891
+ }
892
+
883
893
  // Eagerly initiate canvas chunk fetching at script evaluation (parallel with DOM parsing)
884
894
  const canvasModulePromise = typeof window !== 'undefined' ? import('@widgetic/canvas') : null;
885
895
 
@@ -943,6 +953,7 @@
943
953
  mountUploadAbortController = new AbortController();
944
954
  if (canvasModulePromise) {
945
955
  const canvasModule = await canvasModulePromise;
956
+ markCanvasOpenStep('creator:canvas-module-loaded');
946
957
  // Installed before the canvas mounts so the first save already externalizes
947
958
  installCanvasThumbnailStore(canvasModule);
948
959
  // The canvas keeps the visitor's saved colors where the creator keeps its own memory: the browser's
@@ -1008,6 +1019,8 @@
1008
1019
  import {
1009
1020
  saveCanvasState,
1010
1021
  readCanvasState,
1022
+ saveCanvasWidgetList,
1023
+ readCanvasWidgetList,
1011
1024
  saveActiveGeneration,
1012
1025
  readActiveGeneration,
1013
1026
  clearActiveGeneration,
@@ -1993,8 +2006,19 @@
1993
2006
  const name = String(attachment.file_name || '');
1994
2007
  return type.startsWith('image/') || /\.(png|jpe?g|gif|webp|svg)(\?|$)/i.test(name) || /\.(png|jpe?g|gif|webp|svg)(\?|$)/i.test(attachment.url);
1995
2008
  });
2009
+ const retryUploadIds = [
2010
+ ...new Set(
2011
+ retryImageAttachments
2012
+ .map((attachment) => uploadIdFromStoredFileUrl(attachment.url))
2013
+ .filter((id): id is string => !!id),
2014
+ ),
2015
+ ];
1996
2016
  const retryImageDataUrls: string[] = [];
1997
2017
  for (const attachment of retryImageAttachments) {
2018
+ // A stored upload is fetched by the API. The browser fetch fails (no CORS
2019
+ // on the file host) and used to toast "Could not load uploaded image"
2020
+ // even though the picture was already saved.
2021
+ if (uploadIdFromStoredFileUrl(attachment.url)) continue;
1998
2022
  try {
1999
2023
  const dataUrl = await resolvePromptImageForCodegen(undefined, attachment.url);
2000
2024
  if (!dataUrl) continue;
@@ -2006,6 +2030,9 @@
2006
2030
  console.warn('[Chat→Retry] Could not resend an attachment:', imageErr);
2007
2031
  }
2008
2032
  }
2033
+ if (retryUploadIds.length > 0) {
2034
+ console.info('[Chat→Retry] Saved image stays on the server', { uploadCount: retryUploadIds.length });
2035
+ }
2009
2036
  if (forkUserMessage) {
2010
2037
  const bubbleAttachments = retryImageAttachments.map((attachment, index) => ({
2011
2038
  id: `retry_${Date.now()}_${index}`,
@@ -2027,7 +2054,9 @@
2027
2054
  forceRecreateRepo: true,
2028
2055
  skipIntentGate: true,
2029
2056
  forkUserMessage,
2030
- attachmentIds: forkUserMessage ? undefined : (draftUploadIds.length > 0 ? draftUploadIds : undefined),
2057
+ attachmentIds: retryUploadIds.length > 0
2058
+ ? retryUploadIds
2059
+ : (forkUserMessage ? undefined : (draftUploadIds.length > 0 ? draftUploadIds : undefined)),
2031
2060
  promptImagesOverride: retryImageDataUrls.length > 0
2032
2061
  ? retryImageDataUrls
2033
2062
  : (forkUserMessage ? [] : (draftImageUrls.length > 0 ? draftImageUrls : undefined)),
@@ -3325,8 +3354,8 @@
3325
3354
  const response = await messagesClient.restoreCheckpointRaw({
3326
3355
  conversationId,
3327
3356
  restoreCheckpointRequest: {
3328
- conversation_id: conversationId,
3329
- checkpoint_message_id: checkpointMessageId
3357
+ conversationId,
3358
+ checkpointMessageId,
3330
3359
  }
3331
3360
  }, widgetBuilderRequestInit(widgetBuilderPreviewBaseUrl()));
3332
3361
  const json = await response.raw.json();
@@ -5818,6 +5847,7 @@
5818
5847
  id: targetCanvasId,
5819
5848
  updateCanvasRequest: { primaryWidgetId: widgetId }
5820
5849
  });
5850
+ canvasRecordReads.delete(targetCanvasId);
5821
5851
  } catch (err) {
5822
5852
  console.warn('[CreatorApp] Failed to save primary_widget_id:', err);
5823
5853
  }
@@ -6596,6 +6626,47 @@
6596
6626
  ]);
6597
6627
  }
6598
6628
 
6629
+ /**
6630
+ * One read of a canvas record per open. The JSON load and the primary-widget lookups run from two start paths
6631
+ * (loadCurrentCanvas and handleCanvasReady); each used to read the canvas again. A read is shared for
6632
+ * CANVAS_RECORD_SHARE_MS, then the next caller reads fresh.
6633
+ */
6634
+ const CANVAS_RECORD_SHARE_MS = 15000;
6635
+ type CanvasRecordRead = { status: number; record: Record<string, any> | null };
6636
+ const canvasRecordReads = new Map<string, { startedAt: number; read: Promise<CanvasRecordRead> }>();
6637
+
6638
+ function forgetCanvasRecordReads(): void {
6639
+ canvasRecordReads.clear();
6640
+ }
6641
+
6642
+ function readCanvasRecord(targetCanvasId: string, options: { fresh?: boolean } = {}): Promise<CanvasRecordRead> {
6643
+ const shared = canvasRecordReads.get(targetCanvasId);
6644
+ if (!options.fresh && shared && Date.now() - shared.startedAt < CANVAS_RECORD_SHARE_MS) return shared.read;
6645
+ const read = (async (): Promise<CanvasRecordRead> => {
6646
+ if (!canvasesClient) throw new Error('Canvases API client is not configured');
6647
+ const response = await withCanvasApiTimeout(canvasesClient.getCanvasRaw({ id: targetCanvasId }), 'getCanvas');
6648
+ // A 304 has no body; the caller keeps what it already painted.
6649
+ if (response.raw.status === 304) return { status: 304, record: null };
6650
+ const body = await response.raw.json();
6651
+ const record = (body?.data || body) ?? null;
6652
+ announceCanvasName(targetCanvasId, record);
6653
+ return { status: response.raw.status, record };
6654
+ })();
6655
+ canvasRecordReads.set(targetCanvasId, { startedAt: Date.now(), read });
6656
+ // A failed read is not shared: the next caller asks again.
6657
+ read.catch(() => {
6658
+ if (canvasRecordReads.get(targetCanvasId)?.read === read) canvasRecordReads.delete(targetCanvasId);
6659
+ });
6660
+ return read;
6661
+ }
6662
+
6663
+ /** The site header shows the canvas name; it reads it from here instead of asking the API again. */
6664
+ function announceCanvasName(targetCanvasId: string, record: Record<string, any> | null): void {
6665
+ const name = String(record?.persistenceKey || record?.persistence_key || '').trim();
6666
+ if (!name) return;
6667
+ announceToSite('widgetic:creator-canvas-name', { canvasId: targetCanvasId, name });
6668
+ }
6669
+
6599
6670
  function clearCanvasHydrateRetry() {
6600
6671
  if (canvasHydrateRetryTimer) {
6601
6672
  clearTimeout(canvasHydrateRetryTimer);
@@ -6932,8 +7003,8 @@
6932
7003
 
6933
7004
  // Reload canvas shapes first, then widget metadata for the new canvas
6934
7005
  try {
6935
- lastWidgetsCanvasId = null;
6936
- isLoadingWidgetsOnce = false;
7006
+ forgetWidgetListRead();
7007
+ forgetCanvasRecordReads();
6937
7008
  const { widgetIds: widgetIdsOnCanvas } = await tryLoadCanvasState();
6938
7009
  await syncWidgetsWithCanvas(widgetIdsOnCanvas);
6939
7010
  } catch (err) {
@@ -7413,9 +7484,19 @@
7413
7484
  deleteCanvasTarget = null;
7414
7485
  }
7415
7486
 
7416
- let lastWidgetsCanvasId: string | null = null;
7417
- let isLoadingWidgetsOnce = false;
7418
- async function loadWidgetsForCanvas() {
7487
+ /**
7488
+ * The widget list read for the open canvas. Both start paths (loadCurrentCanvas and handleCanvasReady) need it;
7489
+ * they wait on this one read. A refresh, a retry or another canvas forgets it and reads again.
7490
+ */
7491
+ let widgetListReadCanvasId: string | null = null;
7492
+ let widgetListRead: Promise<boolean> | null = null;
7493
+
7494
+ function forgetWidgetListRead(): void {
7495
+ widgetListReadCanvasId = null;
7496
+ widgetListRead = null;
7497
+ }
7498
+
7499
+ async function loadWidgetsForCanvas(): Promise<void> {
7419
7500
  // if no canvas id, return
7420
7501
  if (!canvasId) {
7421
7502
  // console.log('Widget Creator: loadWidgetsForCanvas: No canvas id, returning');
@@ -7425,13 +7506,23 @@
7425
7506
  isLoadingWidgets = false;
7426
7507
  return;
7427
7508
  }
7509
+ if (widgetListRead && widgetListReadCanvasId === canvasId) {
7510
+ await widgetListRead;
7511
+ return;
7512
+ }
7513
+ const listCanvasId = canvasId;
7514
+ const read = readAndApplyWidgetList(listCanvasId);
7515
+ widgetListReadCanvasId = listCanvasId;
7516
+ widgetListRead = read;
7517
+ const loaded = await read;
7518
+ // A failed read is not kept, so the next caller asks again.
7519
+ if (!loaded && widgetListRead === read) forgetWidgetListRead();
7520
+ }
7428
7521
 
7429
- // if canvas id, load the widgets for the canvas
7430
- // console.log('Widget Creator: loadWidgetsForCanvas:', canvasId);
7522
+ async function readAndApplyWidgetList(listCanvasId: string): Promise<boolean> {
7523
+ // console.log('Widget Creator: loadWidgetsForCanvas:', listCanvasId);
7524
+ let networkListSettled = false;
7431
7525
  try {
7432
- if (isLoadingWidgetsOnce && lastWidgetsCanvasId === canvasId) return;
7433
- isLoadingWidgetsOnce = true;
7434
- lastWidgetsCanvasId = canvasId;
7435
7526
  isLoadingWidgets = true;
7436
7527
  widgetsError = null;
7437
7528
  if (!$userSession?.jwt) {
@@ -7442,7 +7533,13 @@
7442
7533
  // which the generated model drops. A refused request or an error answer
7443
7534
  // is thrown (see readWidgetList), so the catch below shows it and
7444
7535
  // saysCanvasIsMissing can read a 404 in partner mode.
7445
- const fetched = await readWidgetList(canvasId);
7536
+ // The request starts first; the cached list is read beside it and shown only until it answers.
7537
+ const networkListPromise = readWidgetList(listCanvasId);
7538
+ void showCachedWidgetList(listCanvasId, () => networkListSettled);
7539
+ const fetched = await networkListPromise;
7540
+ networkListSettled = true;
7541
+ markCanvasOpenStep('creator:widget-list-ready');
7542
+ saveCanvasWidgetList(listCanvasId, fetched);
7446
7543
 
7447
7544
  const previousById = new Map(
7448
7545
  widgets.filter((w) => w.id).map((w) => [w.id as string, w]),
@@ -7520,6 +7617,7 @@
7520
7617
  selectedWidgetId = null;
7521
7618
  saveSelectedWidgetId(null); // Clear localStorage if no widgets
7522
7619
  }
7620
+ return true;
7523
7621
  } catch (error) {
7524
7622
  console.error('Widget Creator: Failed to load widgets for canvas:', error);
7525
7623
  const defaultError = $t('creator.widget.failedToLoadWidgets');
@@ -7535,9 +7633,34 @@
7535
7633
  duration: 5000
7536
7634
  });
7537
7635
  }
7636
+ return false;
7538
7637
  } finally {
7638
+ networkListSettled = true;
7539
7639
  isLoadingWidgets = false;
7540
- isLoadingWidgetsOnce = false;
7640
+ }
7641
+ }
7642
+
7643
+ /**
7644
+ * Second open of a canvas: show the widget list saved last time, so names and
7645
+ * thumbnails on the board do not wait for the network. Needs enableLocalCache.
7646
+ */
7647
+ async function showCachedWidgetList(listCanvasId: string, hasNetworkSettled: () => boolean): Promise<void> {
7648
+ if (!isLocalCacheEnabled()) return;
7649
+ try {
7650
+ const cachedList = (await readCanvasWidgetList(listCanvasId)) as WidgetSummary[] | null;
7651
+ if (!cachedList?.length || hasNetworkSettled() || canvasId !== listCanvasId) return;
7652
+ // Something already put widgets of this canvas on screen; the network list will replace them.
7653
+ const alreadyShowsThisCanvas = widgets.some(
7654
+ (widget) => widgetCanvasIdOf(widget as { canvasId?: string | null; canvas_id?: string | null }) === listCanvasId,
7655
+ );
7656
+ if (alreadyShowsThisCanvas) return;
7657
+ widgets = sortWidgetSummaries(cachedList);
7658
+ markCanvasOpenStep('creator:widget-list-from-cache');
7659
+ widgetNamesRevision += 1;
7660
+ backfillWidgetShapeMetadata();
7661
+ syncWidgetShapeLivePreviews();
7662
+ } catch (error) {
7663
+ console.warn('[WidgetCreator] Cached widget list could not be read:', error);
7541
7664
  }
7542
7665
  }
7543
7666
 
@@ -7969,10 +8092,10 @@
7969
8092
  async function readPrimaryWidgetIdForCanvas(targetCanvasId: string): Promise<string | null> {
7970
8093
  if (!canvasesClient || !targetCanvasId?.trim()) return null;
7971
8094
  try {
7972
- const canvasRecord = await canvasesClient.getCanvas({ id: targetCanvasId });
7973
- const record =
7974
- (canvasRecord as { data?: Record<string, unknown> })?.data ??
7975
- (canvasRecord as unknown as Record<string, unknown>);
8095
+ const canvasRead = await readCanvasRecord(targetCanvasId);
8096
+ // 304: nothing new about this canvas; keep the primary already known.
8097
+ if (!canvasRead.record) return canvasPrimaryWidgetId || null;
8098
+ const record = canvasRead.record;
7976
8099
  const raw =
7977
8100
  (record as { primaryWidgetId?: unknown })?.primaryWidgetId ??
7978
8101
  (record as { primary_widget_id?: unknown })?.primary_widget_id ??
@@ -8202,13 +8325,14 @@
8202
8325
 
8203
8326
  function handleRefreshWidgets() {
8204
8327
  // console.log('Widget Creator: Refresh widgets clicked');
8205
- lastWidgetsCanvasId = null;
8206
- isLoadingWidgetsOnce = false;
8328
+ forgetWidgetListRead();
8207
8329
  void syncWidgetsWithCanvas();
8208
8330
  }
8209
8331
 
8210
8332
  function retryLoadCanvas() {
8211
8333
  console.log('Widget Creator: Retry loading canvas');
8334
+ forgetWidgetListRead();
8335
+ forgetCanvasRecordReads();
8212
8336
  isLoadingCanvasOnce = false;
8213
8337
  isCanvasStateLoaded = false;
8214
8338
  canvasHydrateRetryCount = 0;
@@ -10404,12 +10528,10 @@ Requirements:
10404
10528
  (url) => typeof url === 'string' && (url.startsWith('data:image/') || /^https?:\/\//i.test(url)) && url.length > 20,
10405
10529
  );
10406
10530
  const chatAttachmentUrls = options.forkUserMessage ? [] : (panelChat?.getAttachmentDataUrls?.() ?? []);
10407
- const chatUploadIds = options.forkUserMessage
10408
- ? []
10409
- : [
10410
- ...(options.attachmentIds || []),
10411
- ...(panelChat?.getAttachmentUploadIds?.() ?? []),
10412
- ].filter((id, index, arr) => id && arr.indexOf(id) === index);
10531
+ const chatUploadIds = [
10532
+ ...(options.attachmentIds || []),
10533
+ ...(options.forkUserMessage ? [] : (panelChat?.getAttachmentUploadIds?.() ?? [])),
10534
+ ].filter((id, index, arr) => id && arr.indexOf(id) === index);
10413
10535
  if (!options.forkUserMessage && chatAttachmentUrls.length > 0 && !(options.promptImagesOverride?.length)) {
10414
10536
  const fromChat = chatAttachmentUrls.filter(
10415
10537
  (url) => typeof url === 'string' && (url.startsWith('data:image/') || /^https?:\/\//i.test(url)) && url.length > 20,
@@ -11046,12 +11168,28 @@ Requirements:
11046
11168
  activePanelRef?.setHasAutoOpenedPreview(true);
11047
11169
  pendingCreatePreviewDefaultsWidgetId = generationWidgetId;
11048
11170
  suppressNextBuildFromRepoChatMessage = true;
11049
- // Codegen already compiled the Worker. A forced GitLab rebuild races the
11050
- // new commit and overwrites the iframe with the previous version.
11051
- activePanelRef?.markCodegenPreviewFresh?.();
11052
- if (completedPreviewBuildErr) {
11171
+ // A cache hit did not compile anything. The earlier build may have
11172
+ // failed, so the worker has no HTML and the canvas is still the sketch.
11173
+ // Compile the saved code before saying the preview is ready.
11174
+ const cachedWithoutLivePreview = completedCached && !activePanelRef?.hasLiveWorkerPreview?.();
11175
+ let previewCompiled = false;
11176
+ if (completedCached) {
11177
+ activePanelRef?.clearCodegenPreviewFresh?.();
11178
+ } else {
11179
+ // Codegen already compiled the Worker. A forced GitLab rebuild races the
11180
+ // new commit and overwrites the iframe with the previous version.
11181
+ activePanelRef?.markCodegenPreviewFresh?.();
11182
+ }
11183
+ if (completedPreviewBuildErr || cachedWithoutLivePreview) {
11053
11184
  activePanelRef?.setPreviewLoadingState(true);
11054
- await activePanelRef?.triggerBuildFromRepo({ force: true });
11185
+ if (cachedWithoutLivePreview) {
11186
+ patchCodegenUiState(generationWidgetId, {
11187
+ generateCodeStatus: `Code already saved${commitShort ? ` (${commitShort})` : ''} — compiling preview…`,
11188
+ });
11189
+ }
11190
+ previewCompiled = (await activePanelRef?.triggerBuildFromRepo(
11191
+ completedPreviewBuildErr ? { force: true } : undefined,
11192
+ )) === true;
11055
11193
  } else if (activePanelRef?.hasLiveWorkerPreview?.()) {
11056
11194
  // WS already remounted the Worker iframe — a second refreshPreview
11057
11195
  // cache-busts the same URL and looks like an extra reload.
@@ -11065,7 +11203,10 @@ Requirements:
11065
11203
  activePanelRef?.setPreviewLoadingState(true);
11066
11204
  await activePanelRef?.refreshPreview?.({ withRetry: true, skipIfAlreadyShowing: true });
11067
11205
  }
11068
- activePanelRef?.setPreviewBuildError(null);
11206
+ const attemptedRepoBuild = !!(completedPreviewBuildErr || cachedWithoutLivePreview);
11207
+ if (!attemptedRepoBuild || previewCompiled) {
11208
+ activePanelRef?.setPreviewBuildError(null);
11209
+ }
11069
11210
  // Show Worker preview on the canvas shape (not the previous Live CDN artifact).
11070
11211
  // History alignment below moves the dropdown onto the commit this build belongs to.
11071
11212
  shapePreviewSourceByWidgetId = {
@@ -11073,7 +11214,16 @@ Requirements:
11073
11214
  [generationWidgetId]: 'preview',
11074
11215
  };
11075
11216
  syncWidgetShapeLivePreviews();
11076
- if (!completedPreviewBuildErr) {
11217
+ if (cachedWithoutLivePreview && !previewCompiled) {
11218
+ panelChat?.updateLatestCodegenStatusMessage?.(
11219
+ `Code already saved${commitShort ? ` (${commitShort})` : ''}, but the preview could not be compiled.`,
11220
+ );
11221
+ patchCodegenUiState(generationWidgetId, {
11222
+ generateCodeStatus: `Code already saved${commitShort ? ` (${commitShort})` : ''} — preview failed.`,
11223
+ lastGenerationFailed: true,
11224
+ lastGenerationError: 'The saved code could not be compiled into a preview.',
11225
+ });
11226
+ } else if (!completedPreviewBuildErr) {
11077
11227
  await applyDesignSchemaDefaultsToPreview(generationWidgetId);
11078
11228
  pendingCreatePreviewDefaultsWidgetId = null;
11079
11229
  panelChat?.updateLatestCodegenStatusMessage?.(
@@ -16051,13 +16201,29 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16051
16201
  return !!getWidgetById(widgetId);
16052
16202
  }
16053
16203
 
16204
+ /**
16205
+ * The canvas calls onReady from its own mount, before `bind:this` has filled canvasRef.
16206
+ * Loading then would be skipped and wait for the retry timer (~0.9s), so wait for the ref.
16207
+ */
16208
+ async function waitForCanvasRef(): Promise<boolean> {
16209
+ if (canvasRef) return true;
16210
+ await tick();
16211
+ for (let frame = 0; frame < 3 && !canvasRef; frame++) {
16212
+ await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
16213
+ }
16214
+ if (!canvasRef) console.warn('[WidgetCreator] Canvas ready, but its ref is still empty');
16215
+ return !!canvasRef;
16216
+ }
16217
+
16054
16218
  /**
16055
16219
  * Called when WidgeticCanvas is initialized and ready.
16056
16220
  * Marks the canvas as ready; actual state loading happens in loadCanvasState()
16057
16221
  * which is called after loadCurrentCanvas() resolves canvasId.
16058
16222
  */
16059
16223
  async function handleCanvasReady() {
16224
+ markCanvasOpenStep('creator:canvas-ready');
16060
16225
  // console.log('[WidgetCreator] Canvas component ready');
16226
+ await waitForCanvasRef();
16061
16227
  canvasComponentReady = true;
16062
16228
  if (ignoreIncomingCanvasLoads) {
16063
16229
  // console.log('[WidgetCreator] Canvas ready — skipping JSON hydrate (new widget)');
@@ -16112,6 +16278,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16112
16278
  canvasLoadFailsafeArmedForId = null;
16113
16279
  }
16114
16280
  function markCanvasStateLoaded() {
16281
+ if (!isCanvasStateLoaded) markCanvasOpenStep('creator:canvas-state-loaded');
16115
16282
  isCanvasStateLoaded = true;
16116
16283
  canvasHydrateRetryCount = 0;
16117
16284
  clearCanvasHydrateRetry();
@@ -16190,6 +16357,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16190
16357
  localCachedJson = (await readCanvasState(canvasId)) ?? (() => {
16191
16358
  try { return creatorStorage.getItem(getCanvasStorageKey()); } catch { return null; }
16192
16359
  })();
16360
+ markCanvasOpenStep(localCachedJson ? 'creator:canvas-cache-hit' : 'creator:canvas-cache-miss');
16193
16361
  if (localCachedJson && canvasRef) {
16194
16362
  const parsed = JSON.parse(localCachedJson);
16195
16363
  const objects = parsed?.canvas?.objects ?? parsed?.objects ?? [];
@@ -16219,13 +16387,11 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16219
16387
  // Another read has already found out there is no such canvas for this visitor.
16220
16388
  if (canvasUnavailable) return emptyResult;
16221
16389
  try {
16222
- const canvasResponse = await withCanvasApiTimeout(
16223
- canvasesClient.getCanvasRaw({ id: canvasId }),
16224
- 'getCanvas',
16225
- );
16390
+ // The first attempt joins the read a primary-widget lookup may already have started.
16391
+ const canvasRead = await readCanvasRecord(canvasId, { fresh: attempt > 0 });
16226
16392
  // A 304 has no body. Parsing it throws, the loader treats that as a
16227
16393
  // failed read, and the page asks for the same canvas again.
16228
- if (canvasResponse.raw.status === 304) {
16394
+ if (canvasRead.status === 304) {
16229
16395
  markCanvasStateLoaded();
16230
16396
  let cachedIds: string[] = [];
16231
16397
  if (localCachedJson) {
@@ -16237,8 +16403,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16237
16403
  }
16238
16404
  return { loaded: true, widgetIds: cachedIds };
16239
16405
  }
16240
- const canvasJson = await canvasResponse.raw.json();
16241
- const canvasRecord = canvasJson?.data || canvasJson;
16406
+ markCanvasOpenStep('creator:canvas-json-fetched');
16407
+ const canvasRecord = canvasRead.record;
16242
16408
  if (loadEpoch !== canvasLoadEpoch || ignoreIncomingCanvasLoads) {
16243
16409
  console.log('[CanvasDebug] Ignoring stale getCanvas result', { loadEpoch, canvasLoadEpoch });
16244
16410
  return emptyResult;
@@ -16526,6 +16692,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16526
16692
  canvasContent: parsedCanvas ?? JSON.parse(json)
16527
16693
  }
16528
16694
  });
16695
+ canvasRecordReads.delete(canvasId);
16529
16696
  if (currentSeq < lastResolvedAutosaveSequence) {
16530
16697
  // console.log(
16531
16698
  // `[CanvasDebug] Dropped out-of-order autosave response (${currentSeq} < ${lastResolvedAutosaveSequence})`
@@ -17624,6 +17791,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17624
17791
  suspendAutosave={suspendCanvasAutosave}
17625
17792
  isExternalDataLoading={!isCanvasStateLoaded}
17626
17793
  />
17794
+ {:else}
17795
+ <!-- Empty board while the canvas code downloads; the canvas mounts over the same surface. -->
17796
+ <CanvasBoardPlaceholder class="wc-canvas-placeholder" {locale} messages={canvasMessages} />
17627
17797
  {/if}
17628
17798
  </div>
17629
17799
 
@@ -1434,20 +1434,20 @@
1434
1434
  return builder.buildWidgetFromRepo({ widgetId }, widgetBuilderRequestInit(widgetBuilderPublicBaseUrl));
1435
1435
  }
1436
1436
 
1437
- export async function triggerBuildFromRepo(options?: { force?: boolean }): Promise<void> {
1437
+ export async function triggerBuildFromRepo(options?: { force?: boolean }): Promise<boolean> {
1438
1438
  const forceRebuild = options?.force === true;
1439
- if (!selectedWidgetId) return;
1439
+ if (!selectedWidgetId) return false;
1440
1440
  if (shouldDeferPreviewNetworkWork(forceRebuild)) {
1441
1441
  // console.log('[WidgetDetails] triggerBuildFromRepo deferred (background panel)');
1442
1442
  previewBuildDeferred = true;
1443
- return;
1443
+ return false;
1444
1444
  }
1445
1445
  const hasRepo = !!(normalizeRepositoryId(selectedWidget) || currentRepositoryId);
1446
1446
  if (!hasRepo) {
1447
1447
  // console.log('[WidgetDetails] triggerBuildFromRepo skipped — widget has no repository yet');
1448
1448
  previewLoading = false;
1449
1449
  previewError = 'NO_CODE_YET';
1450
- return;
1450
+ return false;
1451
1451
  }
1452
1452
  const capturedWidgetId = selectedWidgetId;
1453
1453
  const runId = ++buildFromRepoRunId;
@@ -1459,7 +1459,7 @@
1459
1459
 
1460
1460
  if (forceRebuild && isCodegenPreviewFresh()) {
1461
1461
  const freshProbe = await probeWorkerReachable(workerPreviewUrl);
1462
- if (selectedWidgetId !== capturedWidgetId || runId !== buildFromRepoRunId) return;
1462
+ if (selectedWidgetId !== capturedWidgetId || runId !== buildFromRepoRunId) return false;
1463
1463
  if (freshProbe === 'ok') {
1464
1464
  // console.log('[WidgetDetails] triggerBuildFromRepo: skipping GitLab rebuild — codegen preview is fresh');
1465
1465
  dynamicWorkerPreviewUrl = workerPreviewUrl;
@@ -1467,7 +1467,7 @@
1467
1467
  inlinePanelView = 'preview';
1468
1468
  await forceReloadPreviewIframe(workerPreviewUrl);
1469
1469
  dispatch('buildFromRepoSuccess', { widgetId: capturedWidgetId, source: 'codegen-fresh' });
1470
- return;
1470
+ return true;
1471
1471
  }
1472
1472
  }
1473
1473
 
@@ -1499,18 +1499,18 @@
1499
1499
 
1500
1500
  // Step 1: Probe Worker — if widget is already compiled, just show preview (unless forced rebuild)
1501
1501
  const probeResult = await probeWorkerReachable(workerPreviewUrl);
1502
- if (isStaleRun()) return;
1502
+ if (isStaleRun()) return false;
1503
1503
  if (!forceRebuild && probeResult === 'ok') {
1504
1504
  // console.log('[WidgetDetails] triggerBuildFromRepo: Worker already has widget, loading preview directly');
1505
1505
  dispatch('buildFromRepoSuccess', { widgetId: capturedWidgetId });
1506
1506
  loadPreviewFromWorker();
1507
- return;
1507
+ return true;
1508
1508
  }
1509
1509
  if (probeResult === 'unreachable') {
1510
1510
  console.warn('[WidgetDetails] triggerBuildFromRepo: Worker unreachable at', workerPreviewUrl);
1511
1511
  previewLoading = false;
1512
1512
  previewError = 'Widget Builder is not reachable. Make sure the Worker is running.';
1513
- return;
1513
+ return false;
1514
1514
  }
1515
1515
 
1516
1516
  // Skip build-from-repo while codegen is running — WS / refreshPreview will load when ready
@@ -1518,7 +1518,7 @@
1518
1518
  // console.log('[WidgetDetails] triggerBuildFromRepo: codegen in progress — deferring build-from-repo');
1519
1519
  previewLoading = true;
1520
1520
  previewError = null;
1521
- return;
1521
+ return false;
1522
1522
  }
1523
1523
 
1524
1524
  // Step 2: Try build-from-repo with retries
@@ -1528,10 +1528,10 @@
1528
1528
  const maxRetries = 3;
1529
1529
  const retryDelayMs = 3000;
1530
1530
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
1531
- if (isStaleRun()) return;
1531
+ if (isStaleRun()) return false;
1532
1532
  try {
1533
1533
  const buildData = await requestBuildFromRepo(capturedWidgetId);
1534
- if (isStaleRun()) return;
1534
+ if (isStaleRun()) return false;
1535
1535
 
1536
1536
  // console.log('[WidgetDetails] triggerBuildFromRepo succeeded', { buildTimeMs: buildData?.data?.buildTimeMs ?? buildData?.buildTimeMs, attempt });
1537
1537
  previewError = null;
@@ -1545,9 +1545,9 @@
1545
1545
  buildData?.data?.repo_head_commit_sha ??
1546
1546
  buildData?.repoHeadCommitSha,
1547
1547
  });
1548
- if (isStaleRun()) return;
1548
+ if (isStaleRun()) return false;
1549
1549
  loadPreviewFromWorker();
1550
- return;
1550
+ return true;
1551
1551
  } catch (buildErr: any) {
1552
1552
  let buildErrorCode = '';
1553
1553
  lastBuildErrorMsg = buildErr?.message || 'Build request failed'; // Retired-surface 410 (PLANNER_REMOVED / VM_REMOVED): this running
@@ -1600,7 +1600,7 @@
1600
1600
  }
1601
1601
 
1602
1602
  // Step 3: All builds failed — decide what to show
1603
- if (isStaleRun()) return;
1603
+ if (isStaleRun()) return false;
1604
1604
 
1605
1605
  // Forced rebuild (user clicked Rebuild) must surface compile errors — never keep a stale iframe.
1606
1606
  const allowStalePreviewRecovery = !forceRebuild;
@@ -1610,12 +1610,12 @@
1610
1610
  // console.log('[WidgetDetails] triggerBuildFromRepo: build failed but preview iframe already loaded — keeping preview');
1611
1611
  previewError = null;
1612
1612
  previewLoading = false;
1613
- return;
1613
+ return true;
1614
1614
  }
1615
1615
 
1616
1616
  if (allowStalePreviewRecovery && (await tryRecoverPreviewFromWorker())) {
1617
1617
  // console.log('[WidgetDetails] triggerBuildFromRepo: recovered preview from Worker after build-from-repo failure');
1618
- return;
1618
+ return true;
1619
1619
  }
1620
1620
 
1621
1621
  if (selectedWidgetId === capturedWidgetId) {
@@ -1628,7 +1628,7 @@
1628
1628
  previewError = null;
1629
1629
  previewLoading = true;
1630
1630
  applyPreviewUrlToIframe(sourceArtifactUrl);
1631
- return;
1631
+ return true;
1632
1632
  }
1633
1633
  console.warn('[WidgetDetails] js_path artifact not reachable — showing Rebuild');
1634
1634
  }
@@ -1655,6 +1655,7 @@
1655
1655
  dispatch('buildFromRepoFailed', { widgetId: capturedWidgetId });
1656
1656
  console.warn('[WidgetDetails] triggerBuildFromRepo: all build attempts failed for widget', capturedWidgetId);
1657
1657
  }
1658
+ return false;
1658
1659
  } finally {
1659
1660
  if (forceRebuild) isRebuildingPreview = false;
1660
1661
  }
@@ -123,7 +123,7 @@ declare const WidgetDetails: $$__sveltets_2_IsomorphicComponent<{
123
123
  }) => Promise<void>;
124
124
  triggerBuildFromRepo?: (options?: {
125
125
  force?: boolean;
126
- }) => Promise<void>;
126
+ }) => Promise<boolean>;
127
127
  enqueueAction?: (action: {
128
128
  type: "generate";
129
129
  prompt: string;
@@ -225,7 +225,7 @@ declare const WidgetDetails: $$__sveltets_2_IsomorphicComponent<{
225
225
  }) => Promise<void>;
226
226
  triggerBuildFromRepo: (options?: {
227
227
  force?: boolean;
228
- }) => Promise<void>;
228
+ }) => Promise<boolean>;
229
229
  enqueueAction: (action: {
230
230
  type: "generate";
231
231
  prompt: string;
@@ -12,6 +12,8 @@ export declare function readAllWidgetDrafts(): Promise<Record<string, WidgetDraf
12
12
  export declare function copyWidgetDraft(sourceWidgetId: string, targetWidgetId: string): Promise<void>;
13
13
  export declare function saveCanvasState(canvasId: string | null, json: string): void;
14
14
  export declare function readCanvasState(canvasId: string | null): Promise<string | null>;
15
+ export declare function saveCanvasWidgetList(canvasId: string, widgetList: unknown[]): void;
16
+ export declare function readCanvasWidgetList(canvasId: string): Promise<unknown[] | null>;
15
17
  /** False before an owner is known — nothing can be persisted yet. */
16
18
  export declare function canPersistShapeThumbnails(): boolean;
17
19
  export declare function saveShapeThumbnail(ref: string, dataUrl: string): void;
@@ -10,6 +10,7 @@
10
10
  import { deleteEntity, getCacheOwner, readAllEntitiesForKind, readEntity, writeEntity } from '@widgetic/cache-layer';
11
11
  const DRAFT_KIND = 'creatorDrafts';
12
12
  const CANVAS_KIND = 'creatorCanvasState';
13
+ const CANVAS_WIDGETS_KIND = 'creatorCanvasWidgets';
13
14
  const GENERATION_KIND = 'creatorActiveGeneration';
14
15
  const SHAPE_THUMBNAIL_KIND = 'creatorShapeThumbnails';
15
16
  function ownerIdOrNull() {
@@ -70,6 +71,26 @@ export async function readCanvasState(canvasId) {
70
71
  const record = await readEntity(ownerId, CANVAS_KIND, canvasId ?? 'default');
71
72
  return record?.json ?? null;
72
73
  }
74
+ // ─── Canvas widget list ──────────────────────────────────────────
75
+ //
76
+ // The last widget list read for a canvas. A second open shows it before the
77
+ // network answers; the network list then replaces it.
78
+ export function saveCanvasWidgetList(canvasId, widgetList) {
79
+ const ownerId = ownerIdOrNull();
80
+ if (!ownerId || !canvasId)
81
+ return;
82
+ // Wrapped in an object: readEntity only hands back object payloads.
83
+ void writeEntity(ownerId, CANVAS_WIDGETS_KIND, canvasId, { widgets: widgetList }).catch((error) => {
84
+ console.warn('[creatorDraftStorage] Failed to persist the canvas widget list:', error);
85
+ });
86
+ }
87
+ export async function readCanvasWidgetList(canvasId) {
88
+ const ownerId = ownerIdOrNull();
89
+ if (!ownerId || !canvasId)
90
+ return null;
91
+ const record = await readEntity(ownerId, CANVAS_WIDGETS_KIND, canvasId);
92
+ return Array.isArray(record?.widgets) ? record.widgets : null;
93
+ }
73
94
  // ─── Widget shape thumbnails ─────────────────────────────────────
74
95
  //
75
96
  // Widget screenshots used to be serialized inline in the canvas JSON, which
@@ -39,6 +39,13 @@ export declare function requestTusComplete(url: string, init: RequestInit, optio
39
39
  abortSignal?: AbortSignal;
40
40
  }): Promise<Response>;
41
41
  export declare function shouldUseTusForChatUpload(file: File): boolean;
42
+ /**
43
+ * Upload id stored in a Widgetic file URL (`uploads/{owner}/{date}/{uploadId}-{name}`).
44
+ * The page can show that URL in an img tag. It cannot read the bytes: the file host
45
+ * does not send CORS headers, so a browser fetch fails and Retry shows a toast.
46
+ * The API fetches the same URL by this id.
47
+ */
48
+ export declare function uploadIdFromStoredFileUrl(url: string): string | null;
42
49
  /**
43
50
  * Upload a chat attachment via multipart (≤10MB) or TUS (>10MB).
44
51
  */
@@ -209,6 +209,23 @@ function uploadTus(file, config, options = {}) {
209
209
  export function shouldUseTusForChatUpload(file) {
210
210
  return file.size > CHAT_MULTIPART_MAX_BYTES;
211
211
  }
212
+ /**
213
+ * Upload id stored in a Widgetic file URL (`uploads/{owner}/{date}/{uploadId}-{name}`).
214
+ * The page can show that URL in an img tag. It cannot read the bytes: the file host
215
+ * does not send CORS headers, so a browser fetch fails and Retry shows a toast.
216
+ * The API fetches the same URL by this id.
217
+ */
218
+ export function uploadIdFromStoredFileUrl(url) {
219
+ let pathname = '';
220
+ try {
221
+ pathname = new URL(url).pathname;
222
+ }
223
+ catch {
224
+ return null;
225
+ }
226
+ const match = pathname.match(/\/uploads\/[A-Za-z0-9_-]+\/\d{4}-\d{2}-\d{2}\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})-/i);
227
+ return match ? match[1] : null;
228
+ }
212
229
  function normalizeChatUploadFile(file) {
213
230
  if (file.name.toLowerCase().endsWith('.csv') && file.type !== 'text/csv') {
214
231
  return new File([file], file.name, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/creator",
3
- "version": "0.4.15",
3
+ "version": "0.4.17",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "type": "module",
6
6
  "peerDependencies": {