@widgetic/creator 0.4.3 → 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,
@@ -558,7 +557,6 @@
558
557
  // AUTHENTICATED CLIENTS - created ONCE after login with token
559
558
  let canvasesClient: CanvasesApi;
560
559
  let widgetsClient: WidgetsApi;
561
- let componentsClient: ComponentsApi;
562
560
  let agentClient: AgentApi;
563
561
  let operationsClient: OperationsApi | null = null;
564
562
  let conversationsClient: ConversationsApi;
@@ -592,9 +590,6 @@
592
590
  widgetsClient = apiBasePath
593
591
  ? new WidgetsApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
594
592
  : new WidgetsApi({ accessToken: token, middleware: clientMiddleware });
595
- componentsClient = apiBasePath
596
- ? new ComponentsApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
597
- : new ComponentsApi({ accessToken: token, middleware: clientMiddleware });
598
593
  agentClient = apiBasePath
599
594
  ? new AgentApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
600
595
  : new AgentApi({ accessToken: token, middleware: clientMiddleware });
@@ -804,8 +799,6 @@
804
799
  // @ts-ignore
805
800
  widgetsClient = null;
806
801
  // @ts-ignore
807
- componentsClient = null;
808
- // @ts-ignore
809
802
  agentClient = null;
810
803
  operationsClient = null;
811
804
  // @ts-ignore
@@ -1831,13 +1824,14 @@
1831
1824
  // Version N+1 would share one message, and "You are here" could not mark the older one.
1832
1825
  // The standing sketch is attached on the server for the model. It is not copied onto the chat row.
1833
1826
  let forkUserMessage = false;
1827
+ let promptForModel = content;
1834
1828
  let retryFileAttachments: Array<{ url: string; file_type: string; file_name: string | null; file_size: number | null }> = [];
1835
1829
  if (draftUploadIds.length === 0 && draftImageUrls.length === 0) {
1836
1830
  try {
1837
1831
  const panelState = getPanelState(widgetId);
1838
1832
  const convId = panelChat?.getConversationId?.() ?? panelState.currentChatConversationId ?? null;
1839
1833
  if (convId) {
1840
- const convMessages = await handleLoadMessages(convId, widgetId) || [];
1834
+ const convMessages = await handleLoadMessages(convId, widgetId, { scope: 'all' }) || [];
1841
1835
  const needle = content.trim();
1842
1836
  let matchIndex = -1;
1843
1837
  for (let i = convMessages.length - 1; i >= 0; i--) {
@@ -1850,7 +1844,28 @@
1850
1844
  }
1851
1845
  }
1852
1846
  if (matchIndex >= 0) {
1853
- 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) =>
1854
1869
  (message.messageType || message.message_type) === 'assistant'
1855
1870
  && messageTextHasCommit(message.messageContent || message.message_content),
1856
1871
  );
@@ -1877,9 +1892,11 @@
1877
1892
 
1878
1893
  await generateCode({
1879
1894
  prompt: content,
1895
+ promptForModel,
1880
1896
  fromChat: true,
1881
1897
  widgetId,
1882
1898
  forceRecreateRepo: true,
1899
+ skipIntentGate: true,
1883
1900
  forkUserMessage,
1884
1901
  attachmentIds: forkUserMessage ? undefined : (draftUploadIds.length > 0 ? draftUploadIds : undefined),
1885
1902
  promptImagesOverride: forkUserMessage ? [] : (draftImageUrls.length > 0 ? draftImageUrls : undefined),
@@ -2259,7 +2276,7 @@
2259
2276
  ...att,
2260
2277
  display_order: i + 1,
2261
2278
  }));
2262
- const convMessages = await handleLoadMessages(convId, widgetId);
2279
+ const convMessages = await handleLoadMessages(convId, widgetId, { scope: 'all' });
2263
2280
  const userMessages = (convMessages || []).filter(
2264
2281
  (m) => (m.messageType || (m as any).message_type) === 'user'
2265
2282
  );
@@ -2706,8 +2723,80 @@
2706
2723
  }));
2707
2724
  }
2708
2725
 
2709
- /** Load messages for a conversation from backend */
2710
- 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[]> {
2711
2800
  try {
2712
2801
  // Client-only conversations (draft convert panels) have no DB row.
2713
2802
  if (isLocalOnlyConversationId(conversationId)) return [];
@@ -2715,73 +2804,69 @@
2715
2804
  console.warn('[Chat→Backend] messagesClient not initialized');
2716
2805
  return [];
2717
2806
  }
2718
- const response = await messagesClient.getMessagesRaw({
2719
- conversationId,
2720
- sort: 'created_at:asc',
2721
- size: 100
2722
- });
2723
- const json = await response.raw.json();
2724
- 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
+ }
2725
2827
  // console.log('[Chat→Backend] Loaded messages for conversation:', conversationId, messages.length);
2726
- const mappedMessages = messages.map((m: any) => {
2727
- const rawAttachments = m.attachments || m.message_contents || m.messageContents || [];
2728
- let attachments = (Array.isArray(rawAttachments) ? rawAttachments : []).map((a: any, idx: number) => {
2729
- const nested = a?.contents || a?.content;
2730
- const content = Array.isArray(nested) ? (nested[0] || {}) : (nested || a || {});
2731
- const url = content.url || content.public_url || content.publicUrl || content.file_url || a.url || '';
2732
- let fileType = content.file_type || content.fileType || a.file_type || a.fileType || '';
2733
- const fileName = content.file_name || content.fileName || a.file_name || a.fileName || null;
2734
- if (!fileType || !String(fileType).includes('/')) {
2735
- fileType = guessAttachmentFileType(url, fileName, fileType);
2736
- }
2737
- return {
2738
- id: content.id || a.id || `att_${idx}`,
2739
- url,
2740
- file_type: fileType,
2741
- file_name: fileName,
2742
- file_size: content.file_size ?? content.fileSize ?? a.file_size ?? a.fileSize ?? null,
2743
- display_order: a.display_order ?? a.displayOrder ?? content.display_order ?? idx + 1,
2744
- created_at: content.created_at || content.createdAt || a.created_at || a.createdAt || new Date().toISOString(),
2745
- };
2746
- }).filter((a: { url: string }) => !!a.url);
2747
- return {
2748
- id: m.id,
2749
- conversationId: m.conversation_id || m.conversationId || conversationId,
2750
- messageContent: m.message_content || m.messageContent || '',
2751
- messageType: m.message_type || m.messageType || 'user',
2752
- attachments,
2753
- // Suggestion chips from a persisted clarification card — restored
2754
- // on reload exactly as they were served.
2755
- suggestions: Array.isArray(m.suggestions) && m.suggestions.length > 0 ? m.suggestions : undefined,
2756
- // The inline design-control card this turn carried, restored on
2757
- // reload so the reply keeps its controls. The server has already
2758
- // normalized the payload to a renderable shape (see the messages
2759
- // service); `compositionId` on it decides whether the card can still
2760
- // read this composition's live values.
2761
- designControls: m.design_controls ?? m.designControls ?? undefined,
2762
- isCommit: m.is_commit || m.isCommit || false,
2763
- // What the turn shipped, in the commit's own words — persisted beside
2764
- // is_commit by the codegen pipeline and rendered on the turn's commit
2765
- // chrome (the surface that survives a reload).
2766
- commitTitle: m.commit_title || m.commitTitle || undefined,
2767
- userId: m.user_id || m.userId || '',
2768
- createdAt: new Date(m.created_at || m.createdAt),
2769
- updatedAt: new Date(m.updated_at || m.updatedAt || m.created_at || m.createdAt),
2770
- rolledBackAt: m.rolled_back_at || m.rolledBackAt || null,
2771
- };
2772
- });
2828
+ const mappedMessages = messages.map((m: any) => mapOneLoadedMessage(m, conversationId));
2773
2829
  const withHead = markWidgetHeadOnLoadedMessages(mappedMessages);
2774
2830
  const syncWidgetId = widgetIdForSync ?? selectedWidgetId;
2775
2831
  if (syncWidgetId) {
2776
2832
  syncCommitIdFromChatMessages(withHead, syncWidgetId);
2833
+ applyDetectedWidgetLanguage(syncWidgetId, withHead);
2777
2834
  }
2778
- return withHead;
2835
+ return stampOlderFlag(withHead, hasOlder);
2779
2836
  } catch (error) {
2780
2837
  console.error('[Chat→Backend] Failed to load messages:', error);
2781
2838
  return [];
2782
2839
  }
2783
2840
  }
2784
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
+
2785
2870
  /** Create a new conversation for the current widget */
2786
2871
  async function handleCreateConversation(contextId: string, title: string): Promise<any> {
2787
2872
  try {
@@ -3368,10 +3453,56 @@
3368
3453
  }
3369
3454
 
3370
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
+
3371
3500
  function handleChatMessagesResize(widgetId: string, deltaPx: number): void {
3501
+ // Footer open/close. A drag does not come through here.
3372
3502
  // Sub-pixel footer jitter was rewriting the chat height every frame and
3373
3503
  // re-rendering the whole creator while code generation streamed.
3374
3504
  if (generatingWidgetIds[widgetId]) return;
3505
+ if (chatDragOriginByWidgetId[widgetId] != null) return;
3375
3506
  if (!Number.isFinite(deltaPx) || Math.abs(deltaPx) < 2) return;
3376
3507
  const now = Date.now();
3377
3508
  const hits = (chatResizeHits[widgetId] || []).filter((time) => now - time < 2000);
@@ -3381,14 +3512,12 @@
3381
3512
  if (hits.length === 7) console.warn('[CreatorApp] Stopped a chat-height resize loop', widgetId.substring(0, 8));
3382
3513
  return;
3383
3514
  }
3384
- const measured = document
3385
- .querySelector(`[data-widget-chat-height="${widgetId}"]`)
3386
- ?.getBoundingClientRect().height;
3515
+ const measured = chatHeightElement(widgetId)?.getBoundingClientRect().height;
3387
3516
  const current =
3388
3517
  measured && measured > 0
3389
3518
  ? measured
3390
3519
  : (getChatContainerHeightForPanel(widgetId) ?? CHAT_DEFAULT_HEIGHT);
3391
- const next = Math.max(CHAT_MIN_HEIGHT, Math.min(CHAT_MAX_HEIGHT, Math.round(current + deltaPx)));
3520
+ const next = clampChatContainerHeight(current + deltaPx);
3392
3521
  if (Math.abs(next - current) < 2) return;
3393
3522
  patchPanelSnapshot(widgetId, { chatContainerHeight: next });
3394
3523
  }
@@ -3914,13 +4043,16 @@
3914
4043
  await scheduleWidgetSchemaLoad(widgetId);
3915
4044
  const schema = getPanelDisplayState(widgetId).compositionDesignSchema;
3916
4045
  const defaults = extractDesignDefaultsFromSchema(schema);
3917
- if (Object.keys(defaults).length > 0) {
4046
+ const mergedDefaults = { ...defaults, ...(designEditsByWidgetId[widgetId] ?? {}) };
4047
+ if (Object.keys(mergedDefaults).length > 0) {
3918
4048
  if (widgetId === focusedPanelWidgetId) {
3919
- liveDesignValues = defaults;
4049
+ liveDesignValues = mergedDefaults;
3920
4050
  } else {
3921
- patchPanelSnapshot(widgetId, { liveDesignValues: defaults });
4051
+ patchPanelSnapshot(widgetId, { liveDesignValues: mergedDefaults });
3922
4052
  }
3923
- 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, '*');
3924
4056
  // console.log('[Create Preview] Applied design schema defaults:', Object.keys(defaults));
3925
4057
  }
3926
4058
  const contentSchema = getPanelDisplayState(widgetId).compositionContentSchema;
@@ -4221,7 +4353,13 @@
4221
4353
  ) as 'off' | 'shadow' | 'enforce';
4222
4354
 
4223
4355
  /** Apply design values to the live preview + persist, mirroring the editor path. */
4356
+ let designEditsByWidgetId: Record<string, Record<string, unknown>> = {};
4357
+
4224
4358
  function applyDesignValuesToPreview(widgetId: string, changes: Record<string, unknown>): void {
4359
+ designEditsByWidgetId = {
4360
+ ...designEditsByWidgetId,
4361
+ [widgetId]: { ...(designEditsByWidgetId[widgetId] ?? {}), ...changes }
4362
+ };
4225
4363
  const ps = getPanelDisplayState(widgetId);
4226
4364
  const base = ps.liveDesignValues ?? {};
4227
4365
  const next = { ...base, ...changes };
@@ -4230,10 +4368,12 @@
4230
4368
  } else {
4231
4369
  patchPanelSnapshot(widgetId, { liveDesignValues: next });
4232
4370
  }
4233
- getWidgetDetailsRef(widgetId)?.sendMessageToPreview({
4371
+ const designMessage = {
4234
4372
  type: 'widgetic:update',
4235
4373
  design: flattenDesignValuesForPreview(next)
4236
- });
4374
+ };
4375
+ getWidgetDetailsRef(widgetId)?.sendMessageToPreview(designMessage);
4376
+ resolveLiveWidgetShapeIframe(widgetId)?.contentWindow?.postMessage(designMessage, '*');
4237
4377
  compositionDirty = true;
4238
4378
  if (widgetId === focusedPanelWidgetId) {
4239
4379
  syncFocusedPanelEditorSnapshot();
@@ -5171,8 +5311,6 @@
5171
5311
  { id: 'baseten-glm-5.3-flash', name: 'GLM 5.3 Flash (Baseten)', provider: 'Baseten', description: 'Cheaper GLM via Baseten Model APIs', supportsVision: true },
5172
5312
  { id: 'zhipu-glm-5.3-flash', name: 'GLM 5.3 Flash (Z.ai)', provider: 'Zhipu', description: 'Cheapest vision + coding model', supportsVision: true },
5173
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 },
5174
- { id: 'deepseek-v4-pro', name: 'DeepSeek V4 Pro', provider: 'DeepSeek', description: 'Frontier coding model, 1M context', supportsVision: false },
5175
- { id: 'deepseek-v4-flash', name: 'DeepSeek V4 Flash', provider: 'DeepSeek', description: 'Legacy id; routes to V4.1 Flash', supportsVision: true },
5176
5314
  { id: 'openai-codex-3.2', name: 'Codex 3.2 (OpenAI)', provider: 'OpenAI', description: 'Coding-specialized model', supportsVision: false },
5177
5315
  { id: 'openai-gpt-5.5', name: 'GPT-5.5 (OpenAI)', provider: 'OpenAI', description: 'Frontier model for complex work', supportsVision: true },
5178
5316
  { id: 'gemini-3.8-flash', name: 'Gemini 3.8 Flash (Google)', provider: 'Google', description: 'Most capable Gemini Flash', supportsVision: true },
@@ -8000,7 +8138,7 @@
8000
8138
  widget.name.toLowerCase().includes('stairs')
8001
8139
  ) {
8002
8140
  wantStairsReferenceAttach = false;
8003
- userSelectedModelId = 'openai-gpt-5.4';
8141
+ userSelectedModelId = firstVisionModelId() || defaultModelId;
8004
8142
  await tick();
8005
8143
  await attachReferenceImageFromUrl('/refs/stairs-reference.png');
8006
8144
  }
@@ -9126,22 +9264,17 @@
9126
9264
  }
9127
9265
  }
9128
9266
 
9129
- /** 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. */
9130
9268
  function modelSupportsVisionClient(modelId: string): boolean {
9131
9269
  if (!modelId) return false;
9132
9270
  const listed = availableModels.find((m) => m.id === modelId);
9133
- if (listed && typeof listed.supportsVision === 'boolean') {
9134
- return listed.supportsVision;
9135
- }
9136
- if (modelId.startsWith('deepseek-')) return false;
9137
- return (
9138
- modelId.startsWith('openai-') ||
9139
- modelId.startsWith('gemini-') ||
9140
- modelId.startsWith('anthropic-') ||
9141
- modelId.startsWith('zhipu-') ||
9142
- modelId.startsWith('baseten-') ||
9143
- modelId.startsWith('glm-')
9144
- );
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;
9145
9278
  }
9146
9279
 
9147
9280
  /** Fetch same-origin reference PNG and show it in Chat attachments + promptImages. */
@@ -9601,6 +9734,8 @@ Requirements:
9601
9734
  promptImagesOverride?: string[];
9602
9735
  /** Skip the server's intent gate — the clarification card's explicit "generate anyway" choice. */
9603
9736
  skipIntentGate?: boolean;
9737
+ /** Sent to the model. The chat row keeps `prompt`. */
9738
+ promptForModel?: string;
9604
9739
  /** The tapped chip's structured intent, declared so the server measures the chip conversion without matching copy. */
9605
9740
  chipIntent?: ClarificationSuggestion['intent'];
9606
9741
  /** Successful retry: a new user row already exists. Do not attach images to the previous turn. */
@@ -9802,12 +9937,27 @@ Requirements:
9802
9937
  );
9803
9938
  }
9804
9939
 
9805
- /** A widget that already has code stays on the language it was generated with. Older widgets are Svelte. */
9806
- function languageToShow(widgetId: string, storedLanguage: 'svelte' | 'react' | null): 'svelte' | 'react' {
9807
- if (widgetHasGeneratedCode(widgetId)) {
9808
- 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;
9809
9952
  }
9810
- 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';
9811
9961
  }
9812
9962
 
9813
9963
  function restoreGenerationOptions(widgetId: string): void {
@@ -9838,8 +9988,9 @@ Requirements:
9838
9988
 
9839
9989
  function languageForGeneration(widgetId: string): 'svelte' | 'react' {
9840
9990
  const hasCode = widgetHasGeneratedCode(widgetId);
9991
+ const remembered = readGeneratedLanguage(widgetId);
9841
9992
  const language: 'svelte' | 'react' = hasCode
9842
- ? (readGeneratedLanguage(widgetId) ?? 'svelte')
9993
+ ? (remembered ?? (widgetLanguage === 'svelte' ? 'svelte' : 'react'))
9843
9994
  : (widgetLanguage === 'svelte' ? 'svelte' : 'react');
9844
9995
  widgetLanguage = language;
9845
9996
  rememberGeneratedLanguage(widgetId, language);
@@ -10087,10 +10238,7 @@ Requirements:
10087
10238
  // 'CDN attachmentIds',
10088
10239
  // );
10089
10240
  if (!modelSupportsVisionClient(coderModelForRequest)) {
10090
- // Match backend resolveCoderModelId: vision fallback uses DEFAULT_MODEL_ID when vision-capable.
10091
- const visionFallback = modelSupportsVisionClient(defaultModelId)
10092
- ? defaultModelId
10093
- : 'openai-gpt-5.4';
10241
+ const visionFallback = visionCoderFallbackId();
10094
10242
  // console.log('[WidgetCreator] Coder vision fallback (request only, dropdown unchanged)', {
10095
10243
  // from: coderModelForRequest,
10096
10244
  // to: visionFallback,
@@ -10141,7 +10289,7 @@ Requirements:
10141
10289
  const accepted = await agentClient.agentCodeGeneratePostRaw({
10142
10290
  generateCodeRequest: {
10143
10291
  repositoryId: repoId,
10144
- prompt,
10292
+ prompt: options.promptForModel || prompt,
10145
10293
  modelId: coderModelForRequest || undefined,
10146
10294
  plannerModelId: plannerModelIdForRequest,
10147
10295
  widgetId: generationWidgetId,
@@ -10458,18 +10606,9 @@ Requirements:
10458
10606
  const { [alignWidgetId]: _clearedRestore, ...restRestored } = restoredViewingVersionByWidgetId;
10459
10607
  restoredViewingVersionByWidgetId = restRestored;
10460
10608
  }
10461
- const menuNow = dropdownVersionByWidgetId[alignWidgetId];
10462
- const sourceNow = shapePreviewSourceByWidgetId[alignWidgetId];
10463
- const selectedRow = getShapePublishHistory(alignWidgetId)
10464
- .find((row) => `v:${Number(row.version)}` === menuNow);
10465
- if (
10466
- menuNow?.startsWith('v:')
10467
- && menuNow === sourceNow
10468
- && alignCommitSha
10469
- && !commitsMatch(selectedRow?.commitSha ?? selectedRow?.commit_sha, alignCommitSha)
10470
- ) {
10471
- return;
10472
- }
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.
10473
10612
  selectVersionInDropdowns(alignWidgetId, versionId);
10474
10613
  shapePreviewSourceByWidgetId = {
10475
10614
  ...shapePreviewSourceByWidgetId,
@@ -10480,7 +10619,6 @@ Requirements:
10480
10619
  if (versionUsesSharedHeadPreview(alignWidgetId, versionId)) {
10481
10620
  const headUrl = resolveWidgetShapeLivePreviewUrl(alignWidgetId);
10482
10621
  getWidgetDetailsRef(alignWidgetId)?.showLiveWorkerPreview?.(headUrl);
10483
- widgetShapeLivePreviewsRef?.requestReload?.(alignWidgetId);
10484
10622
  } else {
10485
10623
  const versionNumber = Number(versionId.slice(2));
10486
10624
  if (Number.isFinite(versionNumber)) {
@@ -10679,9 +10817,6 @@ Requirements:
10679
10817
  [generationWidgetId]: 'preview',
10680
10818
  };
10681
10819
  syncWidgetShapeLivePreviews();
10682
- // WS preview-ready was deferred during codegen so the Worker
10683
- // iframe does not boot on the shared main thread at 80%.
10684
- widgetShapeLivePreviewsRef?.requestReload?.(generationWidgetId);
10685
10820
  if (!completedPreviewBuildErr) {
10686
10821
  await applyDesignSchemaDefaultsToPreview(generationWidgetId);
10687
10822
  pendingCreatePreviewDefaultsWidgetId = null;
@@ -10825,6 +10960,11 @@ Requirements:
10825
10960
  // Update global flag: true only if the CURRENT widget is still generating
10826
10961
  isGeneratingCode = !!(focusedPanelWidgetId && generatingWidgetIds[focusedPanelWidgetId]);
10827
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
+ });
10828
10968
  }
10829
10969
  }
10830
10970
  }
@@ -11023,7 +11163,7 @@ Requirements:
11023
11163
 
11024
11164
  /**
11025
11165
  * Publish the current widget: saves first, then triggers the production build job.
11026
- * Flow: Save → fetch latest component → POST /canvases/{id}/components/{id}/publish
11166
+ * Flow: Save → POST /agent/widget-builder/publish/{widgetId}
11027
11167
  * On completion, the backend sends widget_publish_status via WebSocket.
11028
11168
  */
11029
11169
  async function executePublishWidget(
@@ -11081,64 +11221,20 @@ Requirements:
11081
11221
  publishingWidgetId = capturedWidgetId;
11082
11222
  setCrossTabPublishing(true, capturedWidgetId);
11083
11223
 
11084
- publishWidgetStatus = $t('creator.widget.fetchingWidgetComponent');
11085
-
11086
- if (!componentsClient || !agentClient) {
11087
- throw new Error('API clients are not configured');
11088
- }
11089
-
11090
- const componentsData = await componentsClient.getComponentsByWidgetId({
11091
- widgetId: capturedWidgetId,
11092
- page: 1
11093
- });
11094
- const components = Array.isArray(componentsData?.data) ? componentsData.data : [];
11095
- let matchedComponent =
11096
- components.find(
11097
- (c: { widgetId?: string; widget_id?: string }) =>
11098
- c?.widgetId === capturedWidgetId || c?.widget_id === capturedWidgetId
11099
- ) ?? null;
11100
- if (!matchedComponent?.id && components.length === 1) {
11101
- matchedComponent = components[0];
11102
- }
11103
- // console.log('[Publish] Widget components fetched:', components.length, '— matched:', matchedComponent?.id, 'for widgetId:', capturedWidgetId);
11104
-
11105
- // If no component exists for this widget in the canvas, create one now
11106
- // (in widget-creator, saving to git doesn't auto-create a component record)
11107
- if (!matchedComponent?.id) {
11108
- publishWidgetStatus = $t('creator.widget.creatingWidgetComponent');
11109
- const widgetName = getWidgetById(capturedWidgetId)?.name || 'Widget';
11110
- // console.log('[Publish] No component found — creating one for widget:', capturedWidgetId, 'name:', widgetName);
11111
-
11112
- matchedComponent = await componentsClient.createComponent({
11113
- canvasId: capturedCanvasId,
11114
- createComponentRequest: {
11115
- name: widgetName,
11116
- widget_id: capturedWidgetId,
11117
- is_widget: true,
11118
- description: `Widget component for ${widgetName}`
11119
- }
11120
- });
11121
- // console.log('[Publish] Component created:', matchedComponent?.id);
11122
- }
11123
-
11124
- if (!matchedComponent?.id) {
11125
- throw new Error('Could not find or create a component for this widget.');
11126
- }
11127
-
11128
- const componentId = matchedComponent.id;
11129
- // console.log('[Publish] Publishing component:', { componentId, capturedWidgetId, capturedCanvasId });
11224
+ if (!agentClient) {
11225
+ throw new Error('API clients are not configured');
11226
+ }
11130
11227
 
11131
11228
  publishWidgetStatus = $t('creator.publish.publishingViaWidgetBuilder');
11132
11229
 
11133
11230
  const publishData = await agentClient.agentWidgetBuilderPublishWidgetIdPost({
11134
11231
  widgetId: capturedWidgetId,
11135
11232
  agentWidgetBuilderPublishWidgetIdPostRequest: {
11136
- componentId,
11137
11233
  commitSha: commitShaForPublish || undefined,
11138
11234
  // Publishing a Draft the user chose: the server rebuilds from that
11139
11235
  // version's commit and stamps it Live instead of minting a new one.
11140
11236
  version: targetVersion ?? undefined
11141
- }
11237
+ } as unknown as Parameters<typeof agentClient.agentWidgetBuilderPublishWidgetIdPost>[0]['agentWidgetBuilderPublishWidgetIdPostRequest']
11142
11238
  });
11143
11239
  // console.log('[Publish] Widget Builder publish completed:', publishData);
11144
11240
 
@@ -12441,6 +12537,7 @@ Requirements:
12441
12537
  const cached = shapePublishHistoryByWidgetId[widgetId];
12442
12538
  if (cached && cached.length > 0) {
12443
12539
  shapeHistoryResolvedByWidgetId = { ...shapeHistoryResolvedByWidgetId, [widgetId]: true };
12540
+ queueUnpublishedHeadOnShape(widgetId);
12444
12541
  return;
12445
12542
  }
12446
12543
  const fromPanel = getPanelDisplayState(widgetId).publishHistory;
@@ -12450,6 +12547,7 @@ Requirements:
12450
12547
  [widgetId]: [...fromPanel],
12451
12548
  };
12452
12549
  shapeHistoryResolvedByWidgetId = { ...shapeHistoryResolvedByWidgetId, [widgetId]: true };
12550
+ queueUnpublishedHeadOnShape(widgetId);
12453
12551
  return;
12454
12552
  }
12455
12553
  shapeHistoryLoadInFlight = { ...shapeHistoryLoadInFlight, [widgetId]: true };
@@ -12462,6 +12560,7 @@ Requirements:
12462
12560
  };
12463
12561
  shapeHistoryResolvedByWidgetId = { ...shapeHistoryResolvedByWidgetId, [widgetId]: true };
12464
12562
  syncWidgetShapeLivePreviews();
12563
+ queueUnpublishedHeadOnShape(widgetId);
12465
12564
  } finally {
12466
12565
  const { [widgetId]: _, ...rest } = shapeHistoryLoadInFlight;
12467
12566
  shapeHistoryLoadInFlight = rest;
@@ -12476,6 +12575,59 @@ Requirements:
12476
12575
  return fromPanel?.length ? fromPanel : [];
12477
12576
  }
12478
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
+
12479
12631
  /** Newest unpublished version — Worker `/preview` (repo HEAD) shows this version's code. */
12480
12632
  function getNewestDraftVersionId(widgetId: string): number | null {
12481
12633
  const draftVersions = getShapePublishHistory(widgetId)
@@ -14560,6 +14712,7 @@ async function loadPublishHistoryForPanel(widgetId: string, opts: { silent?: boo
14560
14712
  // Mark resolved even when empty — an empty history is a final answer and
14561
14713
  // must stop `ensureShapePublishHistory` from re-fetching on every render.
14562
14714
  shapeHistoryResolvedByWidgetId = { ...shapeHistoryResolvedByWidgetId, [widgetId]: true };
14715
+ queueUnpublishedHeadOnShape(widgetId);
14563
14716
  if (widgetId === focusedPanelWidgetId) {
14564
14717
  publishHistory = history;
14565
14718
  publishHistoryResolved = true;
@@ -16305,23 +16458,6 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16305
16458
  }
16306
16459
  const widgetId: string = newWidget.id;
16307
16460
 
16308
- // Component record (canvas → widget bridge) — non-blocking.
16309
- if (canvasId && componentsClient) {
16310
- try {
16311
- await componentsClient.createComponent({
16312
- canvasId,
16313
- createComponentRequest: {
16314
- name: draftName,
16315
- widget_id: widgetId,
16316
- is_widget: true,
16317
- }
16318
- });
16319
- // console.log('[WidgetCreator] Component record created for widget', widgetId);
16320
- } catch (compErr) {
16321
- console.warn('[WidgetCreator] Failed to create component record (non-blocking):', compErr);
16322
- }
16323
- }
16324
-
16325
16461
  // Add to widgets list so getWidgetById resolves the real widget from now on.
16326
16462
  widgets = [{ ...newWidget }, ...widgets.filter((w) => w.id !== draftId)];
16327
16463
 
@@ -17674,7 +17810,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17674
17810
  try {
17675
17811
  const conversations = await handleLoadConversations(widgetId);
17676
17812
  if (conversations?.length > 0) {
17677
- const messages = await handleLoadMessages(conversations[0].id);
17813
+ const messages = await handleLoadMessages(conversations[0].id, null, { scope: 'all' });
17678
17814
  const firstUserMsg = messages?.find((m: any) => (m.messageType || m.message_type) === 'user');
17679
17815
  if (firstUserMsg) {
17680
17816
  const content = firstUserMsg.messageContent || firstUserMsg.message_content || '';
@@ -18137,7 +18273,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18137
18273
  bind:title={brandTitle}
18138
18274
  bind:sub={brandSub}
18139
18275
  bind:fonts={brandFonts}
18140
- showLanguage={debugMode}
18276
+ showLanguage={true}
18141
18277
  languageLocked={!!(generatingWidgetIds[panelWidgetId] || ps.lastCommitId || ps.lastPublishedVersion != null)}
18142
18278
  bind:language={widgetLanguage}
18143
18279
  />
@@ -18190,6 +18326,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18190
18326
  onCompletionToggle={(detail) => handleChatCompletionToggle(panelWidgetId, detail)}
18191
18327
  onLoadConversations={handleLoadConversations}
18192
18328
  onLoadMessages={(conversationId) => handleLoadMessages(conversationId, panelWidgetId)}
18329
+ onLoadOlderMessages={(conversationId) => handleLoadOlderMessages(conversationId)}
18330
+ onMessagesDrag={(totalDy) => handleChatDragResize(panelWidgetId, totalDy)}
18331
+ onMessagesDragEnd={() => handleChatDragResizeEnd(panelWidgetId)}
18193
18332
  onCreateConversation={handleCreateConversation} onSaveMessage={(conversationId, content, messageType, attachments, suggestions, designControls) =>
18194
18333
  handleSaveMessage(conversationId, content, messageType, attachments, suggestions, panelWidgetId, designControls)
18195
18334
  }