@widgetic/creator 0.4.2 → 0.4.4

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.
@@ -20,7 +20,6 @@
20
20
  WidgetsApi,
21
21
  AgentApi,
22
22
  OperationsApi,
23
- ComponentsApi,
24
23
  ConversationsApi,
25
24
  MessagesApi,
26
25
  CompositionsApi,
@@ -161,6 +160,7 @@
161
160
  shouldUseTusForChatUpload,
162
161
  uploadChatFileToWidgeticApi
163
162
  } from './utils/widgeticChatUpload.js';
163
+ import { tryPartnerMediaUpload, uploadFromMediaLibrary } from './utils/partnerMediaUpload.js';
164
164
  import { persistWidgetThumbnail } from './utils/persistWidgetThumbnail.js';
165
165
  import { nativeScrollbarPadding } from './utils/nativeScrollbarPadding.js';
166
166
  import { pinScrollToBottom } from './utils/pinScrollToBottom.js';
@@ -232,6 +232,7 @@
232
232
  export let initialCompositionId: CreatorAppProps['initialCompositionId'] = null;
233
233
  export let initialStep: CreatorAppProps['initialStep'] = null;
234
234
  export let forceCreateNewWidget: CreatorAppProps['forceCreateNewWidget'] = false;
235
+ export let initialSketchName: CreatorAppProps['initialSketchName'] = null;
235
236
  export let apiUrl: CreatorAppProps['apiUrl'] = null;
236
237
  export let widgetBuilderUrl: CreatorAppProps['widgetBuilderUrl'] = null;
237
238
  export let initialDebugMode: CreatorAppProps['initialDebugMode'] = undefined;
@@ -258,8 +259,17 @@
258
259
  export let onCanvasUnavailable: CreatorAppProps['onCanvasUnavailable'] = undefined;
259
260
  export let onCanvasChanged: CreatorAppProps['onCanvasChanged'] = undefined;
260
261
  export let onReady: CreatorAppProps['onReady'] = undefined;
261
- /** The page's own media library for the editor's file pickers (see `CreatorAppProps.mediaLibrary`). */
262
+ /** Partner library for chat/canvas uploads (see `CreatorAppProps.mediaLibrary`). */
262
263
  export let mediaLibrary: CreatorAppProps['mediaLibrary'] = undefined;
264
+ /** Optional override for PropsEditor file fields (`purpose: 'field'`). */
265
+ export let mediaLibraryForFields: CreatorAppProps['mediaLibraryForFields'] = undefined;
266
+ /** Opens the partner's file picker instead of the built-in File Browser (see `CreatorAppProps.pickFile`). */
267
+ export let pickFile: CreatorAppProps['pickFile'] = undefined;
268
+ /** Resolves the url stored with a picked file (see `CreatorAppProps.storeFileUrl`). */
269
+ export let storeFileUrl: CreatorAppProps['storeFileUrl'] = undefined;
270
+ /** One console.warn per mount when `mediaLibrary.upload` fails and the creator falls back to Widgetic uploads. */
271
+ const partnerUploadWarnings = { mediaLibraryUpload: false as boolean | undefined };
272
+ let mountUploadAbortController: AbortController | null = null;
263
273
  /**
264
274
  * The language of everything the creator shows (see `CreatorAppProps.locale` and `CreatorAppProps.messages`). The one flat
265
275
  * `messages` object is split between the creator's own words and the parts it draws: the editor (with its file
@@ -526,7 +536,7 @@
526
536
  import { PropsEditor, provideEditorLanguage, setFileBrowserUploadConfig, setGoogleFontsApiKey } from '@widgetic/editor';
527
537
 
528
538
  // API root: embedded hosts pass apiUrl; standalone uses VITE_API_URL / PUBLIC_API_URL.
529
- // If unset, @widgetic/api-sdk falls back to BASE_PATH = dev-api.widgetic.com (OpenAPI default).
539
+ // If unset, @widgetic/api-sdk falls back to its own BASE_PATH, https://api.widgetic.com/v1 (the production API).
530
540
  function resolveApiRoot(): string | undefined {
531
541
  const raw =
532
542
  apiUrl ||
@@ -547,7 +557,6 @@
547
557
  // AUTHENTICATED CLIENTS - created ONCE after login with token
548
558
  let canvasesClient: CanvasesApi;
549
559
  let widgetsClient: WidgetsApi;
550
- let componentsClient: ComponentsApi;
551
560
  let agentClient: AgentApi;
552
561
  let operationsClient: OperationsApi | null = null;
553
562
  let conversationsClient: ConversationsApi;
@@ -581,9 +590,6 @@
581
590
  widgetsClient = apiBasePath
582
591
  ? new WidgetsApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
583
592
  : new WidgetsApi({ accessToken: token, middleware: clientMiddleware });
584
- componentsClient = apiBasePath
585
- ? new ComponentsApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
586
- : new ComponentsApi({ accessToken: token, middleware: clientMiddleware });
587
593
  agentClient = apiBasePath
588
594
  ? new AgentApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
589
595
  : new AgentApi({ accessToken: token, middleware: clientMiddleware });
@@ -793,8 +799,6 @@
793
799
  // @ts-ignore
794
800
  widgetsClient = null;
795
801
  // @ts-ignore
796
- componentsClient = null;
797
- // @ts-ignore
798
802
  agentClient = null;
799
803
  operationsClient = null;
800
804
  // @ts-ignore
@@ -944,6 +948,7 @@
944
948
 
945
949
  // Canvas component resolves eagerly; WidgetDetails loads on demand when panels are opened
946
950
  onMount(async () => {
951
+ mountUploadAbortController = new AbortController();
947
952
  if (canvasModulePromise) {
948
953
  const canvasModule = await canvasModulePromise;
949
954
  // Installed before the canvas mounts so the first save already externalizes
@@ -1042,6 +1047,11 @@
1042
1047
  let userCanvases: CanvasListEntry[] = [];
1043
1048
  let showCanvasDropdown = false; // kept for existing code that sets it to false on switchToCanvas etc.
1044
1049
  let activeCanvasName = 'Loading...';
1050
+ let appliedSketchName = false;
1051
+ $: if (!appliedSketchName && typeof initialSketchName === 'string' && initialSketchName.trim()) {
1052
+ appliedSketchName = true;
1053
+ activeCanvasName = initialSketchName.trim();
1054
+ }
1045
1055
  let canvasNameEditing = false; // kept for existing startCanvasNameEdit/commitCanvasNameEdit
1046
1056
  let canvasNameInputEl: HTMLInputElement | null = null;
1047
1057
 
@@ -1302,6 +1312,9 @@
1302
1312
  * `window`: nothing else reads it, and a partner's page is not a place to leave globals.
1303
1313
  */
1304
1314
  let codegenActiveCount = 0;
1315
+ // Canvas autosave stringifies every shape 15s after the last edit. That
1316
+ // lines up with the stall, so the save waits until this generation ends.
1317
+ $: suspendCanvasAutosave = codegenActiveCount > 0 || isGeneratingCode || Object.keys(generatingWidgetIds).some((id) => generatingWidgetIds[id]);
1305
1318
  function noteCodegenActive(active: boolean): void {
1306
1319
  codegenActiveCount = Math.max(0, codegenActiveCount + (active ? 1 : -1));
1307
1320
  }
@@ -1504,7 +1517,12 @@
1504
1517
 
1505
1518
  async function handleChatUploadFile(
1506
1519
  file: File,
1507
- options?: { onProgress?: (percentage: number) => void; source?: string; widgetId?: string },
1520
+ options?: {
1521
+ onProgress?: (percentage: number) => void;
1522
+ source?: string;
1523
+ widgetId?: string;
1524
+ abortSignal?: AbortSignal;
1525
+ },
1508
1526
  ) {
1509
1527
  if (!authenticatedClientsToken) {
1510
1528
  throw new Error('Upload client not initialized');
@@ -1528,6 +1546,40 @@
1528
1546
  if (partnerMode && shouldUseTusForChatUpload(uploadFile)) {
1529
1547
  throw new Error('This file is too large to attach here (the limit is 10 MB).');
1530
1548
  }
1549
+ const uploadAbortSignal = options?.abortSignal ?? mountUploadAbortController?.signal ?? undefined;
1550
+ let partnerFile: Awaited<ReturnType<typeof tryPartnerMediaUpload>> = null;
1551
+ try {
1552
+ partnerFile = await tryPartnerMediaUpload(
1553
+ mediaLibrary,
1554
+ {
1555
+ file: uploadFile,
1556
+ purpose: 'chat',
1557
+ onProgress: options?.onProgress,
1558
+ signal: uploadAbortSignal,
1559
+ },
1560
+ { storeFileUrl, warnings: partnerUploadWarnings },
1561
+ );
1562
+ } catch (error) {
1563
+ if (
1564
+ uploadAbortSignal?.aborted ||
1565
+ (error instanceof DOMException && error.name === 'AbortError')
1566
+ ) {
1567
+ throw new Error('Upload cancelled.');
1568
+ }
1569
+ throw error;
1570
+ }
1571
+ if (partnerFile) {
1572
+ return {
1573
+ id: partnerFile.id,
1574
+ url: partnerFile.url,
1575
+ fileType: partnerFile.mimeType || uploadFile.type,
1576
+ fileName: partnerFile.name || uploadFile.name,
1577
+ fileSize: partnerFile.size ?? uploadFile.size,
1578
+ };
1579
+ }
1580
+ if (uploadAbortSignal?.aborted) {
1581
+ throw new Error('Upload cancelled.');
1582
+ }
1531
1583
  let result: Awaited<ReturnType<typeof uploadChatFileToWidgeticApi>>;
1532
1584
  try {
1533
1585
  result = await uploadChatFileToWidgeticApi(
@@ -1543,7 +1595,7 @@
1543
1595
  ? currentChatConversationId
1544
1596
  : undefined,
1545
1597
  },
1546
- { onProgress: options?.onProgress },
1598
+ { onProgress: options?.onProgress, abortSignal: uploadAbortSignal },
1547
1599
  );
1548
1600
  } catch (error) {
1549
1601
  // This upload does not go through the API clients, so their middleware did not see the refusal: a full storage
@@ -1772,13 +1824,14 @@
1772
1824
  // Version N+1 would share one message, and "You are here" could not mark the older one.
1773
1825
  // The standing sketch is attached on the server for the model. It is not copied onto the chat row.
1774
1826
  let forkUserMessage = false;
1827
+ let promptForModel = content;
1775
1828
  let retryFileAttachments: Array<{ url: string; file_type: string; file_name: string | null; file_size: number | null }> = [];
1776
1829
  if (draftUploadIds.length === 0 && draftImageUrls.length === 0) {
1777
1830
  try {
1778
1831
  const panelState = getPanelState(widgetId);
1779
1832
  const convId = panelChat?.getConversationId?.() ?? panelState.currentChatConversationId ?? null;
1780
1833
  if (convId) {
1781
- const convMessages = await handleLoadMessages(convId, widgetId) || [];
1834
+ const convMessages = await handleLoadMessages(convId, widgetId, { scope: 'all' }) || [];
1782
1835
  const needle = content.trim();
1783
1836
  let matchIndex = -1;
1784
1837
  for (let i = convMessages.length - 1; i >= 0; i--) {
@@ -1791,7 +1844,28 @@
1791
1844
  }
1792
1845
  }
1793
1846
  if (matchIndex >= 0) {
1794
- forkUserMessage = convMessages.slice(matchIndex + 1).some((message) =>
1847
+ let turnEnd = convMessages.length;
1848
+ for (let i = matchIndex + 1; i < convMessages.length; i++) {
1849
+ const rowType = convMessages[i].messageType || convMessages[i].message_type;
1850
+ if (rowType === 'user') {
1851
+ turnEnd = i;
1852
+ break;
1853
+ }
1854
+ }
1855
+ const turn = convMessages.slice(matchIndex + 1, turnEnd);
1856
+ const controlsMessage = turn.find((message) => message.designControls || message.design_controls);
1857
+ const controls = controlsMessage?.designControls || controlsMessage?.design_controls;
1858
+ const properties = Array.isArray(controls?.properties) ? controls.properties : [];
1859
+ if (properties.length > 0) {
1860
+ const live = getPanelDisplayState(widgetId).liveDesignValues ?? {};
1861
+ const lines = properties.map((property: { id?: string; label?: string; value?: unknown }) => {
1862
+ const id = property.id || '';
1863
+ const value = id && Object.prototype.hasOwnProperty.call(live, id) ? live[id] : property.value;
1864
+ return `Set ${property.label || id} to ${value}.`;
1865
+ });
1866
+ promptForModel = `${content}\n${lines.join('\n')}`;
1867
+ }
1868
+ forkUserMessage = turn.some((message) =>
1795
1869
  (message.messageType || message.message_type) === 'assistant'
1796
1870
  && messageTextHasCommit(message.messageContent || message.message_content),
1797
1871
  );
@@ -1818,9 +1892,11 @@
1818
1892
 
1819
1893
  await generateCode({
1820
1894
  prompt: content,
1895
+ promptForModel,
1821
1896
  fromChat: true,
1822
1897
  widgetId,
1823
1898
  forceRecreateRepo: true,
1899
+ skipIntentGate: true,
1824
1900
  forkUserMessage,
1825
1901
  attachmentIds: forkUserMessage ? undefined : (draftUploadIds.length > 0 ? draftUploadIds : undefined),
1826
1902
  promptImagesOverride: forkUserMessage ? [] : (draftImageUrls.length > 0 ? draftImageUrls : undefined),
@@ -2200,7 +2276,7 @@
2200
2276
  ...att,
2201
2277
  display_order: i + 1,
2202
2278
  }));
2203
- const convMessages = await handleLoadMessages(convId, widgetId);
2279
+ const convMessages = await handleLoadMessages(convId, widgetId, { scope: 'all' });
2204
2280
  const userMessages = (convMessages || []).filter(
2205
2281
  (m) => (m.messageType || (m as any).message_type) === 'user'
2206
2282
  );
@@ -2647,8 +2723,80 @@
2647
2723
  }));
2648
2724
  }
2649
2725
 
2650
- /** Load messages for a conversation from backend */
2651
- async function handleLoadMessages(conversationId: string, widgetIdForSync?: string | null): Promise<any[]> {
2726
+ /** Next older page (newest-first) still to fetch, and whether any remain. */
2727
+ let messageWindowByConversationId: Record<string, { nextOlderPage: number; total: number; loaded: number }> = {};
2728
+
2729
+ async function fetchMessagePage(
2730
+ conversationId: string,
2731
+ page: number,
2732
+ sort: 'created_at:asc' | 'created_at:desc',
2733
+ ): Promise<{ batch: any[]; total: number }> {
2734
+ const response = await messagesClient!.getMessagesRaw({
2735
+ conversationId,
2736
+ sort,
2737
+ page,
2738
+ });
2739
+ const json = await response.raw.json();
2740
+ return {
2741
+ batch: Array.isArray(json?.data) ? json.data : [],
2742
+ total: Number(json?.meta?.total ?? 0),
2743
+ };
2744
+ }
2745
+
2746
+ function stampOlderFlag<T extends any[]>(messages: T, hasOlder: boolean): T {
2747
+ Object.defineProperty(messages, 'hasOlder', { value: hasOlder, enumerable: false });
2748
+ return messages;
2749
+ }
2750
+
2751
+ function mapOneLoadedMessage(m: any, conversationId: string): any {
2752
+ const rawAttachments = m.attachments || m.message_contents || m.messageContents || [];
2753
+ const attachments = (Array.isArray(rawAttachments) ? rawAttachments : []).map((a: any, idx: number) => {
2754
+ const nested = a?.contents || a?.content;
2755
+ const content = Array.isArray(nested) ? (nested[0] || {}) : (nested || a || {});
2756
+ const url = content.url || content.public_url || content.publicUrl || content.file_url || a.url || '';
2757
+ let fileType = content.file_type || content.fileType || a.file_type || a.fileType || '';
2758
+ const fileName = content.file_name || content.fileName || a.file_name || a.fileName || null;
2759
+ if (!fileType || !String(fileType).includes('/')) {
2760
+ fileType = guessAttachmentFileType(url, fileName, fileType);
2761
+ }
2762
+ return {
2763
+ id: content.id || a.id || `att_${idx}`,
2764
+ url,
2765
+ file_type: fileType,
2766
+ file_name: fileName,
2767
+ file_size: content.file_size ?? content.fileSize ?? a.file_size ?? a.fileSize ?? null,
2768
+ display_order: a.display_order ?? a.displayOrder ?? content.display_order ?? idx + 1,
2769
+ created_at: content.created_at || content.createdAt || a.created_at || a.createdAt || new Date().toISOString(),
2770
+ };
2771
+ }).filter((a: { url: string }) => !!a.url);
2772
+ return {
2773
+ id: m.id,
2774
+ conversationId: m.conversation_id || m.conversationId || conversationId,
2775
+ messageContent: m.message_content || m.messageContent || '',
2776
+ messageType: m.message_type || m.messageType || 'user',
2777
+ attachments,
2778
+ suggestions: Array.isArray(m.suggestions) && m.suggestions.length > 0 ? m.suggestions : undefined,
2779
+ designControls: m.design_controls ?? m.designControls ?? undefined,
2780
+ isCommit: m.is_commit || m.isCommit || false,
2781
+ commitTitle: m.commit_title || m.commitTitle || undefined,
2782
+ userId: m.user_id || m.userId || '',
2783
+ createdAt: new Date(m.created_at || m.createdAt),
2784
+ updatedAt: new Date(m.updated_at || m.updatedAt || m.created_at || m.createdAt),
2785
+ rolledBackAt: m.rolled_back_at || m.rolledBackAt || null,
2786
+ };
2787
+ }
2788
+
2789
+ /**
2790
+ * Load messages for a conversation.
2791
+ * `newest` (chat open) is the latest page only, newest at the bottom.
2792
+ * Older pages arrive when the list is scrolled up.
2793
+ * `all` is for a one-off search (retry, the first saved prompt).
2794
+ */
2795
+ async function handleLoadMessages(
2796
+ conversationId: string,
2797
+ widgetIdForSync?: string | null,
2798
+ opts?: { scope?: 'newest' | 'all' },
2799
+ ): Promise<any[]> {
2652
2800
  try {
2653
2801
  // Client-only conversations (draft convert panels) have no DB row.
2654
2802
  if (isLocalOnlyConversationId(conversationId)) return [];
@@ -2656,73 +2804,69 @@
2656
2804
  console.warn('[Chat→Backend] messagesClient not initialized');
2657
2805
  return [];
2658
2806
  }
2659
- const response = await messagesClient.getMessagesRaw({
2660
- conversationId,
2661
- sort: 'created_at:asc',
2662
- size: 100
2663
- });
2664
- const json = await response.raw.json();
2665
- const messages = json?.data || [];
2807
+ const scope = opts?.scope ?? 'newest';
2808
+ const messages: any[] = [];
2809
+ let hasOlder = false;
2810
+ if (scope === 'all') {
2811
+ let page = 1;
2812
+ let total = 0;
2813
+ while (page <= 20) {
2814
+ const { batch, total: pageTotal } = await fetchMessagePage(conversationId, page, 'created_at:asc');
2815
+ total = pageTotal || total;
2816
+ messages.push(...batch);
2817
+ if (batch.length === 0 || (total > 0 && messages.length >= total)) break;
2818
+ page += 1;
2819
+ }
2820
+ } else {
2821
+ // Page 1 of newest-first, then oldest-to-newest inside that page.
2822
+ const { batch, total } = await fetchMessagePage(conversationId, 1, 'created_at:desc');
2823
+ messages.push(...batch.slice().reverse());
2824
+ hasOlder = total > messages.length;
2825
+ messageWindowByConversationId[conversationId] = { nextOlderPage: 2, total, loaded: messages.length };
2826
+ }
2666
2827
  // console.log('[Chat→Backend] Loaded messages for conversation:', conversationId, messages.length);
2667
- const mappedMessages = messages.map((m: any) => {
2668
- const rawAttachments = m.attachments || m.message_contents || m.messageContents || [];
2669
- let attachments = (Array.isArray(rawAttachments) ? rawAttachments : []).map((a: any, idx: number) => {
2670
- const nested = a?.contents || a?.content;
2671
- const content = Array.isArray(nested) ? (nested[0] || {}) : (nested || a || {});
2672
- const url = content.url || content.public_url || content.publicUrl || content.file_url || a.url || '';
2673
- let fileType = content.file_type || content.fileType || a.file_type || a.fileType || '';
2674
- const fileName = content.file_name || content.fileName || a.file_name || a.fileName || null;
2675
- if (!fileType || !String(fileType).includes('/')) {
2676
- fileType = guessAttachmentFileType(url, fileName, fileType);
2677
- }
2678
- return {
2679
- id: content.id || a.id || `att_${idx}`,
2680
- url,
2681
- file_type: fileType,
2682
- file_name: fileName,
2683
- file_size: content.file_size ?? content.fileSize ?? a.file_size ?? a.fileSize ?? null,
2684
- display_order: a.display_order ?? a.displayOrder ?? content.display_order ?? idx + 1,
2685
- created_at: content.created_at || content.createdAt || a.created_at || a.createdAt || new Date().toISOString(),
2686
- };
2687
- }).filter((a: { url: string }) => !!a.url);
2688
- return {
2689
- id: m.id,
2690
- conversationId: m.conversation_id || m.conversationId || conversationId,
2691
- messageContent: m.message_content || m.messageContent || '',
2692
- messageType: m.message_type || m.messageType || 'user',
2693
- attachments,
2694
- // Suggestion chips from a persisted clarification card — restored
2695
- // on reload exactly as they were served.
2696
- suggestions: Array.isArray(m.suggestions) && m.suggestions.length > 0 ? m.suggestions : undefined,
2697
- // The inline design-control card this turn carried, restored on
2698
- // reload so the reply keeps its controls. The server has already
2699
- // normalized the payload to a renderable shape (see the messages
2700
- // service); `compositionId` on it decides whether the card can still
2701
- // read this composition's live values.
2702
- designControls: m.design_controls ?? m.designControls ?? undefined,
2703
- isCommit: m.is_commit || m.isCommit || false,
2704
- // What the turn shipped, in the commit's own words — persisted beside
2705
- // is_commit by the codegen pipeline and rendered on the turn's commit
2706
- // chrome (the surface that survives a reload).
2707
- commitTitle: m.commit_title || m.commitTitle || undefined,
2708
- userId: m.user_id || m.userId || '',
2709
- createdAt: new Date(m.created_at || m.createdAt),
2710
- updatedAt: new Date(m.updated_at || m.updatedAt || m.created_at || m.createdAt),
2711
- rolledBackAt: m.rolled_back_at || m.rolledBackAt || null,
2712
- };
2713
- });
2828
+ const mappedMessages = messages.map((m: any) => mapOneLoadedMessage(m, conversationId));
2714
2829
  const withHead = markWidgetHeadOnLoadedMessages(mappedMessages);
2715
2830
  const syncWidgetId = widgetIdForSync ?? selectedWidgetId;
2716
2831
  if (syncWidgetId) {
2717
2832
  syncCommitIdFromChatMessages(withHead, syncWidgetId);
2833
+ applyDetectedWidgetLanguage(syncWidgetId, withHead);
2718
2834
  }
2719
- return withHead;
2835
+ return stampOlderFlag(withHead, hasOlder);
2720
2836
  } catch (error) {
2721
2837
  console.error('[Chat→Backend] Failed to load messages:', error);
2722
2838
  return [];
2723
2839
  }
2724
2840
  }
2725
2841
 
2842
+ /** The page of messages older than the ones already on screen, oldest first. */
2843
+ async function handleLoadOlderMessages(conversationId: string): Promise<any[]> {
2844
+ try {
2845
+ if (!conversationId || isLocalOnlyConversationId(conversationId) || !messagesClient) return [];
2846
+ const windowState = messageWindowByConversationId[conversationId];
2847
+ if (!windowState) return [];
2848
+ if (windowState.total <= windowState.loaded) return stampOlderFlag([], false);
2849
+ const { batch, total } = await fetchMessagePage(
2850
+ conversationId,
2851
+ windowState.nextOlderPage,
2852
+ 'created_at:desc',
2853
+ );
2854
+ windowState.total = total || windowState.total;
2855
+ windowState.nextOlderPage += 1;
2856
+ const chronological = batch.slice().reverse();
2857
+ windowState.loaded += chronological.length;
2858
+ const hasOlder = windowState.total > windowState.loaded;
2859
+ if (chronological.length === 0) return stampOlderFlag([], false);
2860
+ return stampOlderFlag(
2861
+ chronological.map((m: any) => mapOneLoadedMessage(m, conversationId)),
2862
+ hasOlder,
2863
+ );
2864
+ } catch (error) {
2865
+ console.error('[Chat→Backend] Failed to load older messages:', error);
2866
+ return [];
2867
+ }
2868
+ }
2869
+
2726
2870
  /** Create a new conversation for the current widget */
2727
2871
  async function handleCreateConversation(contextId: string, title: string): Promise<any> {
2728
2872
  try {
@@ -3308,18 +3452,72 @@
3308
3452
  return Math.max(CHAT_MIN_HEIGHT, Math.min(CHAT_MAX_HEIGHT, stored));
3309
3453
  }
3310
3454
 
3455
+ const chatResizeHits: Record<string, number[]> = {};
3456
+ function clampChatContainerHeight(heightPx: number): number {
3457
+ return Math.max(CHAT_MIN_HEIGHT, Math.min(CHAT_MAX_HEIGHT, Math.round(heightPx)));
3458
+ }
3459
+
3460
+ function chatHeightElement(widgetId: string): HTMLElement | null {
3461
+ return document.querySelector(`[data-widget-chat-height="${widgetId}"]`) as HTMLElement | null;
3462
+ }
3463
+
3464
+ /** Height captured when a drag starts, so each move is measured from the pointer, not from a late layout. */
3465
+ let chatDragOriginByWidgetId: Record<string, number> = {};
3466
+ let chatDragPendingByWidgetId: Record<string, number> = {};
3467
+
3468
+ function applyChatHeightDom(widgetId: string, heightPx: number): void {
3469
+ const el = chatHeightElement(widgetId);
3470
+ if (!el) return;
3471
+ const next = clampChatContainerHeight(heightPx);
3472
+ el.style.flex = `0 0 ${next}px`;
3473
+ el.style.height = `${next}px`;
3474
+ el.style.minHeight = `${CHAT_MIN_HEIGHT}px`;
3475
+ }
3476
+
3477
+ /** Pointer drag. Writes the height on the element immediately and stores it when the pointer goes up. */
3478
+ function handleChatDragResize(widgetId: string, totalDy: number): void {
3479
+ if (!widgetId || !Number.isFinite(totalDy)) return;
3480
+ if (chatDragOriginByWidgetId[widgetId] == null) {
3481
+ const measured = chatHeightElement(widgetId)?.getBoundingClientRect().height;
3482
+ chatDragOriginByWidgetId[widgetId] =
3483
+ measured && measured > 0
3484
+ ? measured
3485
+ : (getChatContainerHeightForPanel(widgetId) ?? CHAT_DEFAULT_HEIGHT);
3486
+ }
3487
+ const next = clampChatContainerHeight(chatDragOriginByWidgetId[widgetId] + totalDy);
3488
+ chatDragPendingByWidgetId[widgetId] = next;
3489
+ applyChatHeightDom(widgetId, next);
3490
+ }
3491
+
3492
+ function handleChatDragResizeEnd(widgetId: string): void {
3493
+ const next = chatDragPendingByWidgetId[widgetId];
3494
+ delete chatDragOriginByWidgetId[widgetId];
3495
+ delete chatDragPendingByWidgetId[widgetId];
3496
+ if (next == null) return;
3497
+ patchPanelSnapshot(widgetId, { chatContainerHeight: next });
3498
+ }
3499
+
3311
3500
  function handleChatMessagesResize(widgetId: string, deltaPx: number): void {
3501
+ // Footer open/close. A drag does not come through here.
3312
3502
  // Sub-pixel footer jitter was rewriting the chat height every frame and
3313
3503
  // re-rendering the whole creator while code generation streamed.
3504
+ if (generatingWidgetIds[widgetId]) return;
3505
+ if (chatDragOriginByWidgetId[widgetId] != null) return;
3314
3506
  if (!Number.isFinite(deltaPx) || Math.abs(deltaPx) < 2) return;
3315
- const measured = document
3316
- .querySelector(`[data-widget-chat-height="${widgetId}"]`)
3317
- ?.getBoundingClientRect().height;
3507
+ const now = Date.now();
3508
+ const hits = (chatResizeHits[widgetId] || []).filter((time) => now - time < 2000);
3509
+ hits.push(now);
3510
+ chatResizeHits[widgetId] = hits;
3511
+ if (hits.length > 6) {
3512
+ if (hits.length === 7) console.warn('[CreatorApp] Stopped a chat-height resize loop', widgetId.substring(0, 8));
3513
+ return;
3514
+ }
3515
+ const measured = chatHeightElement(widgetId)?.getBoundingClientRect().height;
3318
3516
  const current =
3319
3517
  measured && measured > 0
3320
3518
  ? measured
3321
3519
  : (getChatContainerHeightForPanel(widgetId) ?? CHAT_DEFAULT_HEIGHT);
3322
- const next = Math.max(CHAT_MIN_HEIGHT, Math.min(CHAT_MAX_HEIGHT, Math.round(current + deltaPx)));
3520
+ const next = clampChatContainerHeight(current + deltaPx);
3323
3521
  if (Math.abs(next - current) < 2) return;
3324
3522
  patchPanelSnapshot(widgetId, { chatContainerHeight: next });
3325
3523
  }
@@ -3845,13 +4043,16 @@
3845
4043
  await scheduleWidgetSchemaLoad(widgetId);
3846
4044
  const schema = getPanelDisplayState(widgetId).compositionDesignSchema;
3847
4045
  const defaults = extractDesignDefaultsFromSchema(schema);
3848
- if (Object.keys(defaults).length > 0) {
4046
+ const mergedDefaults = { ...defaults, ...(designEditsByWidgetId[widgetId] ?? {}) };
4047
+ if (Object.keys(mergedDefaults).length > 0) {
3849
4048
  if (widgetId === focusedPanelWidgetId) {
3850
- liveDesignValues = defaults;
4049
+ liveDesignValues = mergedDefaults;
3851
4050
  } else {
3852
- patchPanelSnapshot(widgetId, { liveDesignValues: defaults });
4051
+ patchPanelSnapshot(widgetId, { liveDesignValues: mergedDefaults });
3853
4052
  }
3854
- getWidgetDetailsRef(widgetId)?.sendMessageToPreview({ type: 'widgetic:update', design: flattenDesignValuesForPreview(defaults) });
4053
+ const designMessage = { type: 'widgetic:update', design: flattenDesignValuesForPreview(mergedDefaults) };
4054
+ getWidgetDetailsRef(widgetId)?.sendMessageToPreview(designMessage);
4055
+ resolveLiveWidgetShapeIframe(widgetId)?.contentWindow?.postMessage(designMessage, '*');
3855
4056
  // console.log('[Create Preview] Applied design schema defaults:', Object.keys(defaults));
3856
4057
  }
3857
4058
  const contentSchema = getPanelDisplayState(widgetId).compositionContentSchema;
@@ -4152,7 +4353,13 @@
4152
4353
  ) as 'off' | 'shadow' | 'enforce';
4153
4354
 
4154
4355
  /** Apply design values to the live preview + persist, mirroring the editor path. */
4356
+ let designEditsByWidgetId: Record<string, Record<string, unknown>> = {};
4357
+
4155
4358
  function applyDesignValuesToPreview(widgetId: string, changes: Record<string, unknown>): void {
4359
+ designEditsByWidgetId = {
4360
+ ...designEditsByWidgetId,
4361
+ [widgetId]: { ...(designEditsByWidgetId[widgetId] ?? {}), ...changes }
4362
+ };
4156
4363
  const ps = getPanelDisplayState(widgetId);
4157
4364
  const base = ps.liveDesignValues ?? {};
4158
4365
  const next = { ...base, ...changes };
@@ -4161,10 +4368,12 @@
4161
4368
  } else {
4162
4369
  patchPanelSnapshot(widgetId, { liveDesignValues: next });
4163
4370
  }
4164
- getWidgetDetailsRef(widgetId)?.sendMessageToPreview({
4371
+ const designMessage = {
4165
4372
  type: 'widgetic:update',
4166
4373
  design: flattenDesignValuesForPreview(next)
4167
- });
4374
+ };
4375
+ getWidgetDetailsRef(widgetId)?.sendMessageToPreview(designMessage);
4376
+ resolveLiveWidgetShapeIframe(widgetId)?.contentWindow?.postMessage(designMessage, '*');
4168
4377
  compositionDirty = true;
4169
4378
  if (widgetId === focusedPanelWidgetId) {
4170
4379
  syncFocusedPanelEditorSnapshot();
@@ -5102,8 +5311,6 @@
5102
5311
  { id: 'baseten-glm-5.3-flash', name: 'GLM 5.3 Flash (Baseten)', provider: 'Baseten', description: 'Cheaper GLM via Baseten Model APIs', supportsVision: true },
5103
5312
  { id: 'zhipu-glm-5.3-flash', name: 'GLM 5.3 Flash (Z.ai)', provider: 'Zhipu', description: 'Cheapest vision + coding model', supportsVision: true },
5104
5313
  { id: 'deepseek-v4.1-flash', name: 'DeepSeek V4.1 Flash (DeepSeek API)', provider: 'DeepSeek', description: 'V4.1 Flash via DeepSeek direct API', supportsVision: true },
5105
- { id: 'deepseek-v4-pro', name: 'DeepSeek V4 Pro', provider: 'DeepSeek', description: 'Frontier coding model, 1M context', supportsVision: false },
5106
- { id: 'deepseek-v4-flash', name: 'DeepSeek V4 Flash', provider: 'DeepSeek', description: 'Legacy id; routes to V4.1 Flash', supportsVision: true },
5107
5314
  { id: 'openai-codex-3.2', name: 'Codex 3.2 (OpenAI)', provider: 'OpenAI', description: 'Coding-specialized model', supportsVision: false },
5108
5315
  { id: 'openai-gpt-5.5', name: 'GPT-5.5 (OpenAI)', provider: 'OpenAI', description: 'Frontier model for complex work', supportsVision: true },
5109
5316
  { id: 'gemini-3.8-flash', name: 'Gemini 3.8 Flash (Google)', provider: 'Google', description: 'Most capable Gemini Flash', supportsVision: true },
@@ -6735,18 +6942,43 @@
6735
6942
  const untitledCanvasBaseName = 'Untitled Widget';
6736
6943
 
6737
6944
  function nextUntitledCanvasName(existingNames: string[]): string {
6738
- const names = new Set(existingNames.map((name) => (name || '').trim()).filter(Boolean));
6739
- if (!names.has(untitledCanvasBaseName)) return untitledCanvasBaseName;
6740
- let highest = 1;
6741
- for (const name of names) {
6742
- const match = name.match(/^Untitled Widget (\d+)$/);
6945
+ let highest = 0;
6946
+ for (const rawName of existingNames) {
6947
+ const name = (rawName || '').trim();
6948
+ const match = name.match(/^Untitled (?:Widget|Image)(?: (\d+))?$/);
6743
6949
  if (!match) continue;
6744
- const value = Number(match[1]);
6745
- if (Number.isFinite(value) && value > highest) highest = value;
6950
+ const value = match[1] ? Number(match[1]) : 1;
6951
+ if (value > highest) highest = value;
6746
6952
  }
6747
6953
  return `${untitledCanvasBaseName} ${highest + 1}`;
6748
6954
  }
6749
6955
 
6956
+ function sketchNameFromHost(): string {
6957
+ return typeof initialSketchName === 'string' ? initialSketchName.trim() : '';
6958
+ }
6959
+
6960
+ async function canvasNamesForNewSketch(): Promise<string[]> {
6961
+ const known = userCanvases.map((canvas) => canvas.name || '');
6962
+ if (!canvasesClient) return known;
6963
+ try {
6964
+ const response = await canvasesClient.getAllCanvases({
6965
+ page: 1,
6966
+ size: 100,
6967
+ sort: 'id:desc'
6968
+ });
6969
+ const rows: any[] = Array.isArray(response)
6970
+ ? response
6971
+ : Array.isArray((response as any)?.data)
6972
+ ? (response as any).data
6973
+ : [];
6974
+ if (rows.length === 0) return known;
6975
+ return rows.map((canvas) => canvas.persistenceKey || canvas.persistence_key || canvas.name || '');
6976
+ } catch (error) {
6977
+ console.warn('[CreatorApp] Could not list canvases before naming a sketch', error);
6978
+ return known;
6979
+ }
6980
+ }
6981
+
6750
6982
  function canvasCreateRequest(persistenceKey: string) {
6751
6983
  const trimmedProjectId = typeof projectId === 'string' ? projectId.trim() : '';
6752
6984
  return {
@@ -6765,7 +6997,7 @@
6765
6997
  return null;
6766
6998
  }
6767
6999
  try {
6768
- const newName = nextUntitledCanvasName(userCanvases.map((c) => c.name || ''));
7000
+ const newName = sketchNameFromHost() || nextUntitledCanvasName(await canvasNamesForNewSketch());
6769
7001
  const createdRaw = await canvasesClient.createCanvas({
6770
7002
  createCanvasRequest: canvasCreateRequest(newName)
6771
7003
  });
@@ -6807,7 +7039,7 @@
6807
7039
  }
6808
7040
 
6809
7041
  try {
6810
- const newName = nextUntitledCanvasName(userCanvases.map((c) => c.name || ''));
7042
+ const newName = sketchNameFromHost() || nextUntitledCanvasName(await canvasNamesForNewSketch());
6811
7043
  const createdRaw = await canvasesClient.createCanvas({
6812
7044
  createCanvasRequest: canvasCreateRequest(newName)
6813
7045
  });
@@ -7906,7 +8138,7 @@
7906
8138
  widget.name.toLowerCase().includes('stairs')
7907
8139
  ) {
7908
8140
  wantStairsReferenceAttach = false;
7909
- userSelectedModelId = 'openai-gpt-5.4';
8141
+ userSelectedModelId = firstVisionModelId() || defaultModelId;
7910
8142
  await tick();
7911
8143
  await attachReferenceImageFromUrl('/refs/stairs-reference.png');
7912
8144
  }
@@ -8636,11 +8868,43 @@
8636
8868
  });
8637
8869
  return null;
8638
8870
  }
8639
-
8871
+
8872
+ if (uploadFromMediaLibrary(mediaLibrary)) {
8873
+ try {
8874
+ const partnerImage = await tryPartnerMediaUpload(
8875
+ mediaLibrary,
8876
+ {
8877
+ file,
8878
+ purpose: 'canvas',
8879
+ signal: mountUploadAbortController?.signal ?? undefined,
8880
+ },
8881
+ { storeFileUrl, warnings: partnerUploadWarnings },
8882
+ );
8883
+ if (partnerImage?.url && /^https?:\/\//i.test(partnerImage.url)) {
8884
+ return partnerImage.url;
8885
+ }
8886
+ } catch (error) {
8887
+ if (
8888
+ mountUploadAbortController?.signal.aborted ||
8889
+ (error instanceof DOMException && error.name === 'AbortError')
8890
+ ) {
8891
+ return null;
8892
+ }
8893
+ console.error('[WidgetCreator] Partner canvas image upload failed:', error);
8894
+ const description =
8895
+ error instanceof Error ? error.message : $t('creator.general.couldNotReadTheImage');
8896
+ showToast('error', $t('creator.general.failedToProcessImage'), {
8897
+ description,
8898
+ duration: 3000,
8899
+ });
8900
+ return null;
8901
+ }
8902
+ return null;
8903
+ }
8904
+
8640
8905
  try {
8641
8906
  const webpFile = await imageFileToWebpFile(file, 0.95);
8642
8907
  const base64 = await fileToBase64(webpFile);
8643
- // console.log('[WidgetCreator] Image processed:', file.name, 'Size:', sizeMB.toFixed(2), 'MB');
8644
8908
  return base64;
8645
8909
  } catch (error) {
8646
8910
  console.error('[WidgetCreator] Error processing image:', error);
@@ -9000,22 +9264,17 @@
9000
9264
  }
9001
9265
  }
9002
9266
 
9003
- /** Vision capability comes from GET /models (`supportsVision`), not from provider-name prefixes. */
9267
+ /** Vision comes only from a model that is in the loaded catalog. Unknown ids are not vision. */
9004
9268
  function modelSupportsVisionClient(modelId: string): boolean {
9005
9269
  if (!modelId) return false;
9006
9270
  const listed = availableModels.find((m) => m.id === modelId);
9007
- if (listed && typeof listed.supportsVision === 'boolean') {
9008
- return listed.supportsVision;
9009
- }
9010
- if (modelId.startsWith('deepseek-')) return false;
9011
- return (
9012
- modelId.startsWith('openai-') ||
9013
- modelId.startsWith('gemini-') ||
9014
- modelId.startsWith('anthropic-') ||
9015
- modelId.startsWith('zhipu-') ||
9016
- modelId.startsWith('baseten-') ||
9017
- modelId.startsWith('glm-')
9018
- );
9271
+ return listed?.supportsVision === true;
9272
+ }
9273
+
9274
+ /** Image requests use the default coder when it has vision, otherwise the first catalog vision model. */
9275
+ function visionCoderFallbackId(): string {
9276
+ if (modelSupportsVisionClient(defaultModelId)) return defaultModelId;
9277
+ return firstVisionModelId() || defaultModelId;
9019
9278
  }
9020
9279
 
9021
9280
  /** Fetch same-origin reference PNG and show it in Chat attachments + promptImages. */
@@ -9475,6 +9734,8 @@ Requirements:
9475
9734
  promptImagesOverride?: string[];
9476
9735
  /** Skip the server's intent gate — the clarification card's explicit "generate anyway" choice. */
9477
9736
  skipIntentGate?: boolean;
9737
+ /** Sent to the model. The chat row keeps `prompt`. */
9738
+ promptForModel?: string;
9478
9739
  /** The tapped chip's structured intent, declared so the server measures the chip conversion without matching copy. */
9479
9740
  chipIntent?: ClarificationSuggestion['intent'];
9480
9741
  /** Successful retry: a new user row already exists. Do not attach images to the previous turn. */
@@ -9676,12 +9937,27 @@ Requirements:
9676
9937
  );
9677
9938
  }
9678
9939
 
9679
- /** A widget that already has code stays on the language it was generated with. Older widgets are Svelte. */
9680
- function languageToShow(widgetId: string, storedLanguage: 'svelte' | 'react' | null): 'svelte' | 'react' {
9681
- if (widgetHasGeneratedCode(widgetId)) {
9682
- return readGeneratedLanguage(widgetId) ?? 'svelte';
9940
+ /** The component path in a generation summary is the language that was generated. */
9941
+ function languageFromMessageText(text: string): 'svelte' | 'react' | null {
9942
+ if (text.includes('src/Widget.jsx')) return 'react';
9943
+ if (text.includes('+page.svelte')) return 'svelte';
9944
+ return null;
9945
+ }
9946
+
9947
+ function applyDetectedWidgetLanguage(widgetId: string, messages: Array<{ messageContent?: string }>): void {
9948
+ let detected: 'svelte' | 'react' | null = null;
9949
+ for (const message of messages) {
9950
+ const found = languageFromMessageText(message?.messageContent || '');
9951
+ if (found) detected = found;
9683
9952
  }
9684
- return storedLanguage ?? 'react';
9953
+ if (!detected) return;
9954
+ rememberGeneratedLanguage(widgetId, detected);
9955
+ if (widgetId === selectedWidgetId || widgetId === focusedPanelWidgetId) widgetLanguage = detected;
9956
+ }
9957
+
9958
+ /** A widget that already has code stays on the language of its generated component. */
9959
+ function languageToShow(widgetId: string, storedLanguage: 'svelte' | 'react' | null): 'svelte' | 'react' {
9960
+ return readGeneratedLanguage(widgetId) ?? storedLanguage ?? 'react';
9685
9961
  }
9686
9962
 
9687
9963
  function restoreGenerationOptions(widgetId: string): void {
@@ -9712,8 +9988,9 @@ Requirements:
9712
9988
 
9713
9989
  function languageForGeneration(widgetId: string): 'svelte' | 'react' {
9714
9990
  const hasCode = widgetHasGeneratedCode(widgetId);
9991
+ const remembered = readGeneratedLanguage(widgetId);
9715
9992
  const language: 'svelte' | 'react' = hasCode
9716
- ? (readGeneratedLanguage(widgetId) ?? 'svelte')
9993
+ ? (remembered ?? (widgetLanguage === 'svelte' ? 'svelte' : 'react'))
9717
9994
  : (widgetLanguage === 'svelte' ? 'svelte' : 'react');
9718
9995
  widgetLanguage = language;
9719
9996
  rememberGeneratedLanguage(widgetId, language);
@@ -9961,10 +10238,7 @@ Requirements:
9961
10238
  // 'CDN attachmentIds',
9962
10239
  // );
9963
10240
  if (!modelSupportsVisionClient(coderModelForRequest)) {
9964
- // Match backend resolveCoderModelId: vision fallback uses DEFAULT_MODEL_ID when vision-capable.
9965
- const visionFallback = modelSupportsVisionClient(defaultModelId)
9966
- ? defaultModelId
9967
- : 'openai-gpt-5.4';
10241
+ const visionFallback = visionCoderFallbackId();
9968
10242
  // console.log('[WidgetCreator] Coder vision fallback (request only, dropdown unchanged)', {
9969
10243
  // from: coderModelForRequest,
9970
10244
  // to: visionFallback,
@@ -10015,7 +10289,7 @@ Requirements:
10015
10289
  const accepted = await agentClient.agentCodeGeneratePostRaw({
10016
10290
  generateCodeRequest: {
10017
10291
  repositoryId: repoId,
10018
- prompt,
10292
+ prompt: options.promptForModel || prompt,
10019
10293
  modelId: coderModelForRequest || undefined,
10020
10294
  plannerModelId: plannerModelIdForRequest,
10021
10295
  widgetId: generationWidgetId,
@@ -10171,6 +10445,7 @@ Requirements:
10171
10445
  // The wait's callback sees the last frame of a stream twice: a job stopped elsewhere is shown as stopped once
10172
10446
  let cancelledElsewhereShown = false;
10173
10447
  await waitForOperation(operationId, (op) => {
10448
+ freezeProbe('sse', `${op?.status ?? ''} ${op?.progress ?? ''}`);
10174
10449
  // Check if aborted before processing updates
10175
10450
  if (signal.aborted) return;
10176
10451
  if (!op) return;
@@ -10231,6 +10506,19 @@ Requirements:
10231
10506
  }
10232
10507
 
10233
10508
  if (op.status === 'completed') {
10509
+ // The SSE callback runs on the page thread. Applying the result here
10510
+ // rebuilds the chat before the browser can paint, so the status stays
10511
+ // on the previous percent and the tab stops answering.
10512
+ // Start the history request on this turn, before any timer. A stall in
10513
+ // the timer then still shows up in the API log as this request.
10514
+ if (generationWidgetId) {
10515
+ void loadPublishHistoryForPanel(generationWidgetId, { silent: true });
10516
+ }
10517
+ setTimeout(() => {
10518
+ setTimeout(() => {
10519
+ const { [generationWidgetId]: _doneGenerating, ...stillGenerating } = generatingWidgetIds;
10520
+ generatingWidgetIds = stillGenerating;
10521
+ isGeneratingCode = !!(focusedPanelWidgetId && generatingWidgetIds[focusedPanelWidgetId]);
10234
10522
  clearActiveOperationId(generationWidgetId);
10235
10523
 
10236
10524
  const completedCommitSha = getOperationCommitId(op.metadata);
@@ -10318,18 +10606,9 @@ Requirements:
10318
10606
  const { [alignWidgetId]: _clearedRestore, ...restRestored } = restoredViewingVersionByWidgetId;
10319
10607
  restoredViewingVersionByWidgetId = restRestored;
10320
10608
  }
10321
- const menuNow = dropdownVersionByWidgetId[alignWidgetId];
10322
- const sourceNow = shapePreviewSourceByWidgetId[alignWidgetId];
10323
- const selectedRow = getShapePublishHistory(alignWidgetId)
10324
- .find((row) => `v:${Number(row.version)}` === menuNow);
10325
- if (
10326
- menuNow?.startsWith('v:')
10327
- && menuNow === sourceNow
10328
- && alignCommitSha
10329
- && !commitsMatch(selectedRow?.commitSha ?? selectedRow?.commit_sha, alignCommitSha)
10330
- ) {
10331
- return;
10332
- }
10609
+ // The prompt that just finished owns the canvas. A published Live
10610
+ // selection is the previous artifact, not a version the user asked
10611
+ // to keep, so the dropdown and the shape move onto this commit.
10333
10612
  selectVersionInDropdowns(alignWidgetId, versionId);
10334
10613
  shapePreviewSourceByWidgetId = {
10335
10614
  ...shapePreviewSourceByWidgetId,
@@ -10340,7 +10619,6 @@ Requirements:
10340
10619
  if (versionUsesSharedHeadPreview(alignWidgetId, versionId)) {
10341
10620
  const headUrl = resolveWidgetShapeLivePreviewUrl(alignWidgetId);
10342
10621
  getWidgetDetailsRef(alignWidgetId)?.showLiveWorkerPreview?.(headUrl);
10343
- widgetShapeLivePreviewsRef?.requestReload?.(alignWidgetId);
10344
10622
  } else {
10345
10623
  const versionNumber = Number(versionId.slice(2));
10346
10624
  if (Number.isFinite(versionNumber)) {
@@ -10451,8 +10729,8 @@ Requirements:
10451
10729
  duration: 8000
10452
10730
  });
10453
10731
  } else if (!completedCommitSha) {
10454
- showToast('warning', 'Code was not saved', {
10455
- description: 'Retry saves it and records a version.',
10732
+ showToast('warning', $t('creator.codegen.codeWasNotSaved'), {
10733
+ description: $t('creator.codegen.retrySavesItAndRecordsAVersion'),
10456
10734
  duration: 8000
10457
10735
  });
10458
10736
  } else {
@@ -10539,9 +10817,6 @@ Requirements:
10539
10817
  [generationWidgetId]: 'preview',
10540
10818
  };
10541
10819
  syncWidgetShapeLivePreviews();
10542
- // WS preview-ready was deferred during codegen so the Worker
10543
- // iframe does not boot on the shared main thread at 80%.
10544
- widgetShapeLivePreviewsRef?.requestReload?.(generationWidgetId);
10545
10820
  if (!completedPreviewBuildErr) {
10546
10821
  await applyDesignSchemaDefaultsToPreview(generationWidgetId);
10547
10822
  pendingCreatePreviewDefaultsWidgetId = null;
@@ -10570,6 +10845,8 @@ Requirements:
10570
10845
  });
10571
10846
  }
10572
10847
  }, completedPreviewBuildErr ? 400 : 800);
10848
+ }, 0);
10849
+ }, 0);
10573
10850
  } else {
10574
10851
  pushCodegenProgressToUi(op, generationWidgetId);
10575
10852
  }
@@ -10683,6 +10960,11 @@ Requirements:
10683
10960
  // Update global flag: true only if the CURRENT widget is still generating
10684
10961
  isGeneratingCode = !!(focusedPanelWidgetId && generatingWidgetIds[focusedPanelWidgetId]);
10685
10962
  setCrossTabGenerating(false, generationWidgetId);
10963
+ // The reload requested while generation was still on was deferred and kept the previous iframe.
10964
+ // Wait until that flag has reached the shape, then load the new document immediately.
10965
+ void tick().then(() => {
10966
+ widgetShapeLivePreviewsRef?.requestReload?.(generationWidgetId, { immediate: true });
10967
+ });
10686
10968
  }
10687
10969
  }
10688
10970
  }
@@ -10881,7 +11163,7 @@ Requirements:
10881
11163
 
10882
11164
  /**
10883
11165
  * Publish the current widget: saves first, then triggers the production build job.
10884
- * Flow: Save → fetch latest component → POST /canvases/{id}/components/{id}/publish
11166
+ * Flow: Save → POST /agent/widget-builder/publish/{widgetId}
10885
11167
  * On completion, the backend sends widget_publish_status via WebSocket.
10886
11168
  */
10887
11169
  async function executePublishWidget(
@@ -10939,64 +11221,20 @@ Requirements:
10939
11221
  publishingWidgetId = capturedWidgetId;
10940
11222
  setCrossTabPublishing(true, capturedWidgetId);
10941
11223
 
10942
- publishWidgetStatus = $t('creator.widget.fetchingWidgetComponent');
10943
-
10944
- if (!componentsClient || !agentClient) {
10945
- throw new Error('API clients are not configured');
10946
- }
10947
-
10948
- const componentsData = await componentsClient.getComponentsByWidgetId({
10949
- widgetId: capturedWidgetId,
10950
- page: 1
10951
- });
10952
- const components = Array.isArray(componentsData?.data) ? componentsData.data : [];
10953
- let matchedComponent =
10954
- components.find(
10955
- (c: { widgetId?: string; widget_id?: string }) =>
10956
- c?.widgetId === capturedWidgetId || c?.widget_id === capturedWidgetId
10957
- ) ?? null;
10958
- if (!matchedComponent?.id && components.length === 1) {
10959
- matchedComponent = components[0];
10960
- }
10961
- // console.log('[Publish] Widget components fetched:', components.length, '— matched:', matchedComponent?.id, 'for widgetId:', capturedWidgetId);
10962
-
10963
- // If no component exists for this widget in the canvas, create one now
10964
- // (in widget-creator, saving to git doesn't auto-create a component record)
10965
- if (!matchedComponent?.id) {
10966
- publishWidgetStatus = $t('creator.widget.creatingWidgetComponent');
10967
- const widgetName = getWidgetById(capturedWidgetId)?.name || 'Widget';
10968
- // console.log('[Publish] No component found — creating one for widget:', capturedWidgetId, 'name:', widgetName);
10969
-
10970
- matchedComponent = await componentsClient.createComponent({
10971
- canvasId: capturedCanvasId,
10972
- createComponentRequest: {
10973
- name: widgetName,
10974
- widget_id: capturedWidgetId,
10975
- is_widget: true,
10976
- description: `Widget component for ${widgetName}`
10977
- }
10978
- });
10979
- // console.log('[Publish] Component created:', matchedComponent?.id);
10980
- }
10981
-
10982
- if (!matchedComponent?.id) {
10983
- throw new Error('Could not find or create a component for this widget.');
10984
- }
10985
-
10986
- const componentId = matchedComponent.id;
10987
- // console.log('[Publish] Publishing component:', { componentId, capturedWidgetId, capturedCanvasId });
11224
+ if (!agentClient) {
11225
+ throw new Error('API clients are not configured');
11226
+ }
10988
11227
 
10989
11228
  publishWidgetStatus = $t('creator.publish.publishingViaWidgetBuilder');
10990
11229
 
10991
11230
  const publishData = await agentClient.agentWidgetBuilderPublishWidgetIdPost({
10992
11231
  widgetId: capturedWidgetId,
10993
11232
  agentWidgetBuilderPublishWidgetIdPostRequest: {
10994
- componentId,
10995
11233
  commitSha: commitShaForPublish || undefined,
10996
11234
  // Publishing a Draft the user chose: the server rebuilds from that
10997
11235
  // version's commit and stamps it Live instead of minting a new one.
10998
11236
  version: targetVersion ?? undefined
10999
- }
11237
+ } as unknown as Parameters<typeof agentClient.agentWidgetBuilderPublishWidgetIdPost>[0]['agentWidgetBuilderPublishWidgetIdPostRequest']
11000
11238
  });
11001
11239
  // console.log('[Publish] Widget Builder publish completed:', publishData);
11002
11240
 
@@ -11039,14 +11277,18 @@ Requirements:
11039
11277
  });
11040
11278
  }
11041
11279
 
11042
- const publishedPanelRef = getWidgetDetailsRef(capturedWidgetId);
11043
- console.log('[Publish] Refreshing preview after publish (step:', widgetDetailsStep, ')');
11044
- publishedPanelRef?.invalidatePublishedArtifactCache?.();
11045
- await publishedPanelRef?.refreshPreview({ withRetry: true });
11046
- scheduleListThumbnailCapture(capturedWidgetId);
11047
-
11048
- await loadPublishHistory();
11049
- void refreshTrialCounter();
11280
+ try {
11281
+ const publishedPanelRef = getWidgetDetailsRef(capturedWidgetId);
11282
+ console.log('[Publish] Refreshing preview after publish (step:', widgetDetailsStep, ')');
11283
+ publishedPanelRef?.invalidatePublishedArtifactCache?.();
11284
+ await publishedPanelRef?.refreshPreview({ withRetry: true });
11285
+ scheduleListThumbnailCapture(capturedWidgetId);
11286
+ await loadPublishHistory();
11287
+ void refreshTrialCounter();
11288
+ } catch (previewErr) {
11289
+ // The version is already live. A preview reload must not be reported as a failed publish.
11290
+ console.warn('[Publish] Preview refresh after a successful publish failed', previewErr);
11291
+ }
11050
11292
 
11051
11293
  } catch (err: any) {
11052
11294
  console.error('[Publish] Error publishing widget:', err);
@@ -11267,6 +11509,8 @@ Requirements:
11267
11509
 
11268
11510
  // Clean up interval on component destroy
11269
11511
  onDestroy(() => {
11512
+ mountUploadAbortController?.abort();
11513
+ mountUploadAbortController = null;
11270
11514
  clearCanvasLoadFailsafe();
11271
11515
  if (tokenCheckInterval) clearInterval(tokenCheckInterval);
11272
11516
  if (tokenDisplayInterval) clearInterval(tokenDisplayInterval);
@@ -11566,8 +11810,15 @@ Requirements:
11566
11810
  return codegenProgressDebugLine(op, stage, pct);
11567
11811
  }
11568
11812
 
11813
+ function freezeProbe(name: string, detail = ''): void {
11814
+ if (!import.meta.env.DEV) return;
11815
+ const query = new URLSearchParams({ probe: name, status: detail.slice(0, 180) });
11816
+ void fetch(`http://localhost:3000/health?${query}`).catch(() => {});
11817
+ }
11818
+
11569
11819
  function pushCodegenProgressToUi(op: OperationStatus, widgetId: string | null | undefined) {
11570
11820
  const line = formatCodegenProgressStatus(op);
11821
+ freezeProbe('progress', line);
11571
11822
  // Feed the freeze watchdog the latest status so a [FreezeReport] names the
11572
11823
  // stage the UI was showing when the main thread stopped responding.
11573
11824
  (window as any).__widgeticFreezeWatchdog?.setStatus?.(line);
@@ -11599,6 +11850,9 @@ Requirements:
11599
11850
 
11600
11851
  /** Same throttle for the in-chat status bubble (updateLatestCodegenStatusMessage). */
11601
11852
  function scheduleCodegenChatStatusPush(widgetId: string | null | undefined, line: string): void {
11853
+ // Percentage ticks during the model stream rewrite the open chat. A large
11854
+ // design image in that chat is decoded again on each rewrite and the page stalls.
11855
+ if (/^(Generating code|Waiting for|Preparing prompt|Building preview|Saving to repository)\b/i.test(line) || /is thinking/i.test(line)) return;
11602
11856
  const key = widgetId || '_focused';
11603
11857
  codegenChatStatusPendingLine[key] = line;
11604
11858
  if (codegenChatStatusTimers[key]) return;
@@ -11633,6 +11887,23 @@ Requirements:
11633
11887
  .replace(/\s{2,}/g, ' ')
11634
11888
  .trim();
11635
11889
  }
11890
+ const patchKeys = Object.keys(nextPatch);
11891
+ const statusOnly = patchKeys.length > 0 && patchKeys.every((key) =>
11892
+ key === 'generateCodeStatus' || key === 'lastGenerationFailed' || key === 'lastGenerationError'
11893
+ );
11894
+ // A progress line used to copy the whole panel snapshot. Anything that reads
11895
+ // the snapshot (version labels, the open chat) rebuilt on every tick, and
11896
+ // that rebuild ran on the same turn the generation finished.
11897
+ if (statusOnly) {
11898
+ const snap = widgetPanelSnapshots[widgetId];
11899
+ if (snap) Object.assign(snap, nextPatch);
11900
+ if (widgetId === focusedPanelWidgetId) {
11901
+ if (nextPatch.generateCodeStatus !== undefined) generateCodeStatus = nextPatch.generateCodeStatus;
11902
+ if (nextPatch.lastGenerationFailed !== undefined) lastGenerationFailed = nextPatch.lastGenerationFailed;
11903
+ if (nextPatch.lastGenerationError !== undefined) lastGenerationError = nextPatch.lastGenerationError;
11904
+ }
11905
+ return;
11906
+ }
11636
11907
  patchPanelSnapshot(widgetId, nextPatch);
11637
11908
  if (widgetId === focusedPanelWidgetId) {
11638
11909
  if (nextPatch.generateCodeStatus !== undefined) generateCodeStatus = nextPatch.generateCodeStatus;
@@ -12266,6 +12537,7 @@ Requirements:
12266
12537
  const cached = shapePublishHistoryByWidgetId[widgetId];
12267
12538
  if (cached && cached.length > 0) {
12268
12539
  shapeHistoryResolvedByWidgetId = { ...shapeHistoryResolvedByWidgetId, [widgetId]: true };
12540
+ queueUnpublishedHeadOnShape(widgetId);
12269
12541
  return;
12270
12542
  }
12271
12543
  const fromPanel = getPanelDisplayState(widgetId).publishHistory;
@@ -12275,6 +12547,7 @@ Requirements:
12275
12547
  [widgetId]: [...fromPanel],
12276
12548
  };
12277
12549
  shapeHistoryResolvedByWidgetId = { ...shapeHistoryResolvedByWidgetId, [widgetId]: true };
12550
+ queueUnpublishedHeadOnShape(widgetId);
12278
12551
  return;
12279
12552
  }
12280
12553
  shapeHistoryLoadInFlight = { ...shapeHistoryLoadInFlight, [widgetId]: true };
@@ -12287,6 +12560,7 @@ Requirements:
12287
12560
  };
12288
12561
  shapeHistoryResolvedByWidgetId = { ...shapeHistoryResolvedByWidgetId, [widgetId]: true };
12289
12562
  syncWidgetShapeLivePreviews();
12563
+ queueUnpublishedHeadOnShape(widgetId);
12290
12564
  } finally {
12291
12565
  const { [widgetId]: _, ...rest } = shapeHistoryLoadInFlight;
12292
12566
  shapeHistoryLoadInFlight = rest;
@@ -12301,6 +12575,59 @@ Requirements:
12301
12575
  return fromPanel?.length ? fromPanel : [];
12302
12576
  }
12303
12577
 
12578
+ /** History length already considered for the automatic jump to the newest draft. */
12579
+ let unpublishedHeadSeenCountByWidgetId: Record<string, number> = {};
12580
+
12581
+ /**
12582
+ * Opening a published widget used to keep the canvas on the Live CDN file
12583
+ * while the chat already had later commits. If the user has not picked
12584
+ * another version, show the newest draft instead.
12585
+ */
12586
+ function queueUnpublishedHeadOnShape(widgetId: string): void {
12587
+ const count = getShapePublishHistory(widgetId).length;
12588
+ if (!widgetId || count === 0) return;
12589
+ if (unpublishedHeadSeenCountByWidgetId[widgetId] === count) return;
12590
+ unpublishedHeadSeenCountByWidgetId = {
12591
+ ...unpublishedHeadSeenCountByWidgetId,
12592
+ [widgetId]: count,
12593
+ };
12594
+ setTimeout(() => showUnpublishedHeadOnShape(widgetId), 0);
12595
+ }
12596
+
12597
+ function showUnpublishedHeadOnShape(widgetId: string): void {
12598
+ if (restoredViewingVersionByWidgetId[widgetId] != null) return;
12599
+ const newestDraft = getNewestDraftVersionId(widgetId);
12600
+ if (newestDraft == null) return;
12601
+ const ps = getPanelDisplayState(widgetId);
12602
+ const liveVersion =
12603
+ ps.lastPublishedVersion ?? resolvePublishedVersionFromWidget(getWidgetById(widgetId));
12604
+ if (liveVersion != null && newestDraft <= liveVersion) return;
12605
+ const current = dropdownVersionByWidgetId[widgetId];
12606
+ const liveId = liveVersion != null ? `v:${liveVersion}` : null;
12607
+ // The default selection is the published version. That is not a choice to stay there.
12608
+ if (current && current !== liveId && current !== 'live') return;
12609
+ const versionId = `v:${newestDraft}`;
12610
+ selectVersionInDropdowns(widgetId, versionId);
12611
+ shapePreviewSourceByWidgetId = {
12612
+ ...shapePreviewSourceByWidgetId,
12613
+ [widgetId]: versionId,
12614
+ };
12615
+ syncWidgetShapeLivePreviews();
12616
+ panelDisplayRevision += 1;
12617
+ if (versionUsesSharedHeadPreview(widgetId, versionId)) {
12618
+ const headUrl = resolveWidgetShapeLivePreviewUrl(widgetId);
12619
+ getWidgetDetailsRef(widgetId)?.showLiveWorkerPreview?.(headUrl);
12620
+ widgetShapeLivePreviewsRef?.requestReload?.(widgetId);
12621
+ } else {
12622
+ void ensureWidgetShapeVersionPreview(widgetId, newestDraft);
12623
+ }
12624
+ console.log('[VersionPreview] Opened newest draft ahead of Live', {
12625
+ widgetId: widgetId.substring(0, 8),
12626
+ versionId,
12627
+ liveVersion,
12628
+ });
12629
+ }
12630
+
12304
12631
  /** Newest unpublished version — Worker `/preview` (repo HEAD) shows this version's code. */
12305
12632
  function getNewestDraftVersionId(widgetId: string): number | null {
12306
12633
  const draftVersions = getShapePublishHistory(widgetId)
@@ -12666,9 +12993,27 @@ Requirements:
12666
12993
  }
12667
12994
  }
12668
12995
 
12996
+ /**
12997
+ * History and head for the chat's version labels.
12998
+ * `getPanelDisplayState` copies the design schema on every read. The label
12999
+ * block runs while a generation finishes, and that copy held the page thread.
13000
+ */
13001
+ function versionChromeSnapshot(widgetId: string): { publishHistory: any[]; lastCommitId: string | null; lastPublishedVersion: number | null } {
13002
+ const snap = getPanelState(widgetId);
13003
+ const focused = widgetId === focusedPanelWidgetId;
13004
+ const history = snap.publishHistory?.length
13005
+ ? snap.publishHistory
13006
+ : (focused && publishHistory.length ? publishHistory : (snap.publishHistory || []));
13007
+ return {
13008
+ publishHistory: history,
13009
+ lastCommitId: (focused ? lastCommitId : null) ?? snap.lastCommitId ?? null,
13010
+ lastPublishedVersion: (focused ? lastPublishedVersion : null) ?? snap.lastPublishedVersion ?? null,
13011
+ };
13012
+ }
13013
+
12669
13014
  /** Commit SHA for the version currently selected in the version menu (drives Head-at-commit badge). */
12670
13015
  function resolveViewingCommitShaForPanel(widgetId: string): string | null {
12671
- const ps = getPanelDisplayState(widgetId);
13016
+ const ps = versionChromeSnapshot(widgetId);
12672
13017
  const restored = restoredViewingVersionByWidgetId[widgetId];
12673
13018
  if (Number.isFinite(restored)) {
12674
13019
  const history = ps.publishHistory?.length ? ps.publishHistory : publishHistory;
@@ -12729,6 +13074,8 @@ Requirements:
12729
13074
  let versionPromptLabelsByWidgetId: Record<string, Record<string, string>> = {};
12730
13075
  let versionTimelineByWidgetId: Record<string, Array<{ version: number; sha: string; prompt: string }>> = {};
12731
13076
  let viewingVersionByWidgetId: Record<string, number | null> = {};
13077
+ const emptyVersionLabels: Record<string, string> = {};
13078
+ const emptyVersionTimeline: Array<{ version: number; sha: string; prompt: string }> = [];
12732
13079
  $: {
12733
13080
  void shapePreviewSourceByWidgetId;
12734
13081
  void shapeVersionPreviewByWidgetId;
@@ -12748,11 +13095,13 @@ Requirements:
12748
13095
  nextTimeline[widgetId] = buildVersionTimelineForPanel(widgetId);
12749
13096
  nextViewing[widgetId] = viewingVersionNumberForPanel(widgetId);
12750
13097
  }
12751
- headCommitShaByWidgetId = nextHeads;
12752
- versionLabelsByWidgetId = nextLabels;
12753
- versionPromptLabelsByWidgetId = nextPrompts;
12754
- versionTimelineByWidgetId = nextTimeline;
12755
- viewingVersionByWidgetId = nextViewing;
13098
+ // A new object with the same contents still counts as a change and makes the
13099
+ // chat rebuild every turn. That rebuild was running again on each progress tick.
13100
+ if (JSON.stringify(headCommitShaByWidgetId) !== JSON.stringify(nextHeads)) headCommitShaByWidgetId = nextHeads;
13101
+ if (JSON.stringify(versionLabelsByWidgetId) !== JSON.stringify(nextLabels)) versionLabelsByWidgetId = nextLabels;
13102
+ if (JSON.stringify(versionPromptLabelsByWidgetId) !== JSON.stringify(nextPrompts)) versionPromptLabelsByWidgetId = nextPrompts;
13103
+ if (JSON.stringify(versionTimelineByWidgetId) !== JSON.stringify(nextTimeline)) versionTimelineByWidgetId = nextTimeline;
13104
+ if (JSON.stringify(viewingVersionByWidgetId) !== JSON.stringify(nextViewing)) viewingVersionByWidgetId = nextViewing;
12756
13105
  }
12757
13106
 
12758
13107
  /** Commit shas are keyed on 7 chars — that is what the chat summaries carry. */
@@ -12771,7 +13120,7 @@ Requirements:
12771
13120
 
12772
13121
  function buildVersionLabelsForPanel(widgetId: string): Record<string, string> {
12773
13122
  const labels: Record<string, string> = {};
12774
- const ps = getPanelDisplayState(widgetId);
13123
+ const ps = versionChromeSnapshot(widgetId);
12775
13124
  const history = ps.publishHistory?.length ? ps.publishHistory : publishHistory;
12776
13125
  for (const record of history || []) {
12777
13126
  if (record?.version == null) continue;
@@ -12790,7 +13139,7 @@ Requirements:
12790
13139
  }
12791
13140
 
12792
13141
  function buildVersionTimelineForPanel(widgetId: string): Array<{ version: number; sha: string; prompt: string }> {
12793
- const ps = getPanelDisplayState(widgetId);
13142
+ const ps = versionChromeSnapshot(widgetId);
12794
13143
  const history = ps.publishHistory?.length ? ps.publishHistory : publishHistory;
12795
13144
  const timeline: Array<{ version: number; sha: string; prompt: string }> = [];
12796
13145
  for (const record of history || []) {
@@ -12806,7 +13155,7 @@ Requirements:
12806
13155
  /** User prompt → "Version N", for turns whose commit line was never saved. */
12807
13156
  function buildVersionPromptLabelsForPanel(widgetId: string): Record<string, string> {
12808
13157
  const labels: Record<string, string> = {};
12809
- const ps = getPanelDisplayState(widgetId);
13158
+ const ps = versionChromeSnapshot(widgetId);
12810
13159
  const history = ps.publishHistory?.length ? ps.publishHistory : publishHistory;
12811
13160
  for (const record of history || []) {
12812
13161
  if (record?.version == null) continue;
@@ -12825,6 +13174,8 @@ Requirements:
12825
13174
  }
12826
13175
 
12827
13176
  function syncWidgetShapeLivePreviews(): void {
13177
+ // This runs once per canvas frame while a shape moves. A call limit here
13178
+ // left the live iframe behind the shape.
12828
13179
  measureSync('sync-widget-shape-previews', () => {
12829
13180
  try {
12830
13181
  canvasSelectedWidgetShapeId = canvasRef?.getSelectedWidgetShapeId?.() ?? null;
@@ -12934,6 +13285,13 @@ Requirements:
12934
13285
  ...widgetPanelSnapshots,
12935
13286
  [widgetId]: { ...getPanelState(widgetId), ...patch },
12936
13287
  };
13288
+ // Progress text does not change versions or the chat's commit badges.
13289
+ // Bumping the revision here rebuilt every turn on each percentage.
13290
+ const patchKeys = Object.keys(patch);
13291
+ const statusOnly = patchKeys.length > 0 && patchKeys.every((key) =>
13292
+ key === 'generateCodeStatus' || key === 'lastGenerationFailed' || key === 'lastGenerationError'
13293
+ );
13294
+ if (statusOnly) return;
12937
13295
  if (patch.publishHistoryResolved) {
12938
13296
  if (widgetId === focusedPanelWidgetId) {
12939
13297
  if (patch.publishHistory) publishHistory = [...patch.publishHistory];
@@ -14289,25 +14647,30 @@ $: if ($dynamicWorkerPreviewStatus.widgetId && $dynamicWorkerPreviewStatus.previ
14289
14647
  const wsEventKey = `${wsReadyWidgetId}:${$dynamicWorkerPreviewStatus.previewUrl}:${$dynamicWorkerPreviewStatus.timestamp ?? ''}`;
14290
14648
  if (wsEventKey !== lastWsWorkerPreviewEventKey) {
14291
14649
  lastWsWorkerPreviewEventKey = wsEventKey;
14292
- const selectedVersion = dropdownVersionByWidgetId[wsReadyWidgetId]
14293
- || shapePreviewSourceByWidgetId[wsReadyWidgetId];
14294
- const keepHistoricalSelection = !generatingWidgetIds[wsReadyWidgetId]
14295
- && !!selectedVersion?.startsWith('v:')
14296
- && !versionUsesSharedHeadPreview(wsReadyWidgetId, selectedVersion);
14297
- if (keepHistoricalSelection) {
14298
- console.log('[CreatorApp] Historical version stays selected; shared HEAD build ignored', wsReadyWidgetId.substring(0, 8));
14299
- } else {
14300
- shapePreviewSourceByWidgetId = {
14301
- ...shapePreviewSourceByWidgetId,
14302
- [wsReadyWidgetId]: 'preview',
14303
- };
14304
- if (codegenCaptureBlocked()) {
14305
- console.log('[CreatorApp] Defer canvas Worker preview reload until codegen finishes', wsReadyWidgetId.substring(0, 8));
14650
+ const previewWidgetId = wsReadyWidgetId;
14651
+ // The socket handler runs on the page thread. Deciding the preview here
14652
+ // was in the same turn as "Building preview…", and that turn never returned.
14653
+ setTimeout(() => {
14654
+ const selectedVersion = dropdownVersionByWidgetId[previewWidgetId]
14655
+ || shapePreviewSourceByWidgetId[previewWidgetId];
14656
+ const keepHistoricalSelection = !generatingWidgetIds[previewWidgetId]
14657
+ && !!selectedVersion?.startsWith('v:')
14658
+ && !versionUsesSharedHeadPreview(previewWidgetId, selectedVersion);
14659
+ if (keepHistoricalSelection) {
14660
+ console.log('[CreatorApp] Historical version stays selected; shared HEAD build ignored', previewWidgetId.substring(0, 8));
14661
+ } else if (generatingWidgetIds[previewWidgetId] || codegenCaptureBlocked()) {
14662
+ // Writing the source here retriggers the version maps and the whole chat
14663
+ // in the same turn as "Saving to repository…". Apply it when the turn ends.
14664
+ console.log('[CreatorApp] Defer canvas Worker preview reload until codegen finishes', previewWidgetId.substring(0, 8));
14306
14665
  } else {
14666
+ shapePreviewSourceByWidgetId = {
14667
+ ...shapePreviewSourceByWidgetId,
14668
+ [previewWidgetId]: 'preview',
14669
+ };
14307
14670
  syncWidgetShapeLivePreviews();
14308
- widgetShapeLivePreviewsRef?.requestReload?.(wsReadyWidgetId);
14671
+ widgetShapeLivePreviewsRef?.requestReload?.(previewWidgetId);
14309
14672
  }
14310
- }
14673
+ }, 0);
14311
14674
  }
14312
14675
  }
14313
14676
 
@@ -14349,6 +14712,7 @@ async function loadPublishHistoryForPanel(widgetId: string, opts: { silent?: boo
14349
14712
  // Mark resolved even when empty — an empty history is a final answer and
14350
14713
  // must stop `ensureShapePublishHistory` from re-fetching on every render.
14351
14714
  shapeHistoryResolvedByWidgetId = { ...shapeHistoryResolvedByWidgetId, [widgetId]: true };
14715
+ queueUnpublishedHeadOnShape(widgetId);
14352
14716
  if (widgetId === focusedPanelWidgetId) {
14353
14717
  publishHistory = history;
14354
14718
  publishHistoryResolved = true;
@@ -15568,6 +15932,20 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15568
15932
  canvasesClient.getCanvasRaw({ id: canvasId }),
15569
15933
  'getCanvas',
15570
15934
  );
15935
+ // A 304 has no body. Parsing it throws, the loader treats that as a
15936
+ // failed read, and the page asks for the same canvas again.
15937
+ if (canvasResponse.raw.status === 304) {
15938
+ markCanvasStateLoaded();
15939
+ let cachedIds: string[] = [];
15940
+ if (localCachedJson) {
15941
+ try {
15942
+ cachedIds = extractWidgetIdsFromCanvasContent(JSON.parse(localCachedJson));
15943
+ } catch (parseErr) {
15944
+ console.warn('[CanvasDebug] Cached canvas JSON could not be read after 304', parseErr);
15945
+ }
15946
+ }
15947
+ return { loaded: true, widgetIds: cachedIds };
15948
+ }
15571
15949
  const canvasJson = await canvasResponse.raw.json();
15572
15950
  const canvasRecord = canvasJson?.data || canvasJson;
15573
15951
  if (loadEpoch !== canvasLoadEpoch || ignoreIncomingCanvasLoads) {
@@ -16080,23 +16458,6 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16080
16458
  }
16081
16459
  const widgetId: string = newWidget.id;
16082
16460
 
16083
- // Component record (canvas → widget bridge) — non-blocking.
16084
- if (canvasId && componentsClient) {
16085
- try {
16086
- await componentsClient.createComponent({
16087
- canvasId,
16088
- createComponentRequest: {
16089
- name: draftName,
16090
- widget_id: widgetId,
16091
- is_widget: true,
16092
- }
16093
- });
16094
- // console.log('[WidgetCreator] Component record created for widget', widgetId);
16095
- } catch (compErr) {
16096
- console.warn('[WidgetCreator] Failed to create component record (non-blocking):', compErr);
16097
- }
16098
- }
16099
-
16100
16461
  // Add to widgets list so getWidgetById resolves the real widget from now on.
16101
16462
  widgets = [{ ...newWidget }, ...widgets.filter((w) => w.id !== draftId)];
16102
16463
 
@@ -16897,6 +17258,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16897
17258
  panZoomPosition="TC"
16898
17259
  showSaveButton={true}
16899
17260
  autosaveDelayMs={import.meta.env.DEV ? 15000 : 5000}
17261
+ suspendAutosave={suspendCanvasAutosave}
16900
17262
  isExternalDataLoading={!isCanvasStateLoaded}
16901
17263
  />
16902
17264
  {/if}
@@ -17266,7 +17628,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17266
17628
  isGeneratingCode={!!generatingWidgetIds[panelWidgetId]}
17267
17629
  skipBasePreview={(!!pendingAutoGenerateWidgetId && pendingAutoGenerateWidgetId === panelWidgetId) || (!!pendingDuplicateBuildWidgetId && pendingDuplicateBuildWidgetId === panelWidgetId)}
17268
17630
  repositorySetupStatus={repositorySetupByWidgetId[panelWidgetId] ?? (normalizeRepositoryId(panelWidget) ? 'ready' : 'pending')}
17269
- generateCodeStatus={ps.generateCodeStatus}
17631
+ generateCodeStatus={isPanelFocused ? (generateCodeStatus ?? ps.generateCodeStatus) : ps.generateCodeStatus}
17270
17632
  {isCheckingActiveGeneration}
17271
17633
  lastCommitId={ps.lastCommitId ?? loadCommitIdForWidget(panelWidgetId)}
17272
17634
  {debugMode}
@@ -17448,7 +17810,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17448
17810
  try {
17449
17811
  const conversations = await handleLoadConversations(widgetId);
17450
17812
  if (conversations?.length > 0) {
17451
- const messages = await handleLoadMessages(conversations[0].id);
17813
+ const messages = await handleLoadMessages(conversations[0].id, null, { scope: 'all' });
17452
17814
  const firstUserMsg = messages?.find((m: any) => (m.messageType || m.message_type) === 'user');
17453
17815
  if (firstUserMsg) {
17454
17816
  const content = firstUserMsg.messageContent || firstUserMsg.message_content || '';
@@ -17772,7 +18134,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17772
18134
  {#if ps.lastGenerationFailed}
17773
18135
  <span class="text-red-500 font-medium">{$t('creator.codegen.generationFailed')}</span>
17774
18136
  {:else}
17775
- <span class="text-gray-400">{$t('creator.status.label')}</span> {statusLabel(ps.generateCodeStatus, $t)}
18137
+ <span class="text-gray-400">{$t('creator.status.label')}</span> {statusLabel(isPanelFocused ? (generateCodeStatus ?? ps.generateCodeStatus) : ps.generateCodeStatus, $t)}
17776
18138
  {/if}
17777
18139
  </div>
17778
18140
  </div>
@@ -17911,7 +18273,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17911
18273
  bind:title={brandTitle}
17912
18274
  bind:sub={brandSub}
17913
18275
  bind:fonts={brandFonts}
17914
- showLanguage={debugMode}
18276
+ showLanguage={true}
17915
18277
  languageLocked={!!(generatingWidgetIds[panelWidgetId] || ps.lastCommitId || ps.lastPublishedVersion != null)}
17916
18278
  bind:language={widgetLanguage}
17917
18279
  />
@@ -17951,9 +18313,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17951
18313
  }
17952
18314
  }}
17953
18315
  widgetHeadCommitSha={headCommitShaByWidgetId[panelWidgetId] || ps.lastCommitId}
17954
- versionLabelByCommitSha={versionLabelsByWidgetId[panelWidgetId] || {}}
17955
- versionLabelByPrompt={versionPromptLabelsByWidgetId[panelWidgetId] || {}}
17956
- versionTimeline={versionTimelineByWidgetId[panelWidgetId] || []}
18316
+ versionLabelByCommitSha={versionLabelsByWidgetId[panelWidgetId] ?? emptyVersionLabels}
18317
+ versionLabelByPrompt={versionPromptLabelsByWidgetId[panelWidgetId] ?? emptyVersionLabels}
18318
+ versionTimeline={versionTimelineByWidgetId[panelWidgetId] ?? emptyVersionTimeline}
17957
18319
  viewingVersion={viewingVersionByWidgetId[panelWidgetId] ?? null}
17958
18320
  onSendMessage={(content, attachments) => handleChatSendMessage(content, attachments, panelWidgetId)}
17959
18321
  onRetryMessage={(content) => handleChatRetryMessage(content, panelWidgetId)}
@@ -17964,6 +18326,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17964
18326
  onCompletionToggle={(detail) => handleChatCompletionToggle(panelWidgetId, detail)}
17965
18327
  onLoadConversations={handleLoadConversations}
17966
18328
  onLoadMessages={(conversationId) => handleLoadMessages(conversationId, panelWidgetId)}
18329
+ onLoadOlderMessages={(conversationId) => handleLoadOlderMessages(conversationId)}
18330
+ onMessagesDrag={(totalDy) => handleChatDragResize(panelWidgetId, totalDy)}
18331
+ onMessagesDragEnd={() => handleChatDragResizeEnd(panelWidgetId)}
17967
18332
  onCreateConversation={handleCreateConversation} onSaveMessage={(conversationId, content, messageType, attachments, suggestions, designControls) =>
17968
18333
  handleSaveMessage(conversationId, content, messageType, attachments, suggestions, panelWidgetId, designControls)
17969
18334
  }
@@ -18207,7 +18572,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18207
18572
  height="620px"
18208
18573
  showDragHandle={false}
18209
18574
  enableDrag={false}
18210
- {mediaLibrary}
18575
+ mediaLibrary={mediaLibraryForFields ?? mediaLibrary}
18576
+ {pickFile}
18577
+ {storeFileUrl}
18211
18578
  defaultTab="design"
18212
18579
  on:propertyChange={handleEditorPropertyChange}
18213
18580
  on:contentItemsChanged={handleEditorContentItemsChanged}