@widgetic/creator 0.4.45 → 0.4.46

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.
@@ -7,7 +7,17 @@
7
7
  /**
8
8
  * COMPONENTS IMPORTS from WIDGETIC DS
9
9
  */
10
- import { Button, DropdownMenu, PasswordInput, showToast, Dialog, GenerateLoader, Portal } from '@widgetic/design-system/components';
10
+ import {
11
+ Button,
12
+ CreatorBar,
13
+ CanvasBoardStatusChip,
14
+ DropdownMenu,
15
+ PasswordInput,
16
+ showToast,
17
+ Dialog,
18
+ GenerateLoader,
19
+ Portal
20
+ } from '@widgetic/design-system/components';
11
21
  import type { EmbeddedSketchMobileTab } from './embeddedSketchLayout.js';
12
22
  import EmbeddedSketchViewportShell from './components/EmbeddedSketchViewportShell.svelte';
13
23
  import { LogoWidgeticType } from '@widgetic/design-system/icons';
@@ -46,6 +56,12 @@
46
56
  sketchCanvasJsonWithinPersistLimit,
47
57
  widgetPanelIndicatesBuiltArtifact,
48
58
  } from './sketchBoardVisibility.js';
59
+ import {
60
+ isSketchGenerationFailed,
61
+ sketchBarShowsCustomize,
62
+ sketchBarShowsPublish,
63
+ sketchSavedStatusLabel,
64
+ } from './sketchBarState.js';
49
65
 
50
66
  /**
51
67
  * Idempotency middleware (Phase 2 hardening): the gateway rejects
@@ -1264,6 +1280,10 @@
1264
1280
  let userCanvases: CanvasListEntry[] = [];
1265
1281
  let showCanvasDropdown = false; // kept for existing code that sets it to false on switchToCanvas etc.
1266
1282
  let activeCanvasName = 'Loading...';
1283
+ /** Sketch bar title from the canvas row `persistenceKey` (authoritative over placeholder widget names). */
1284
+ let sketchCanvasPersistenceName = '';
1285
+ /** Sketch bar: latest batch API names for widgets on this canvas (wins over stale list rows). */
1286
+ let sketchWidgetNamesFromBatch: Record<string, string> = {};
1267
1287
  let appliedSketchName = false;
1268
1288
  $: if (!appliedSketchName && typeof initialSketchName === 'string' && initialSketchName.trim()) {
1269
1289
  appliedSketchName = true;
@@ -1526,6 +1546,8 @@
1526
1546
  'Create a widget from the attached image (short description inside).';
1527
1547
  /** Prefilled prompt for Convert-to-Widget — user edits or presses Send to start. */
1528
1548
  const CONVERT_PROMPT = 'Create a widget starting from the attached image';
1549
+ /** Id of the one model the docked chat offers when the person is not in debug mode (its label is a message: `creator.codegen.assistantModelLabel`). */
1550
+ const ASSISTANT_MODEL_ID = 'assistant';
1529
1551
  let codeGenerationPrompt = DEFAULT_PROMPT;
1530
1552
  let isGeneratingCode = false;
1531
1553
  let generatingWidgetIds: Record<string, boolean> = {};
@@ -2258,6 +2280,33 @@
2258
2280
  return /(?:Commit:?\s+|Code saved\s*\()[a-f0-9]{7,40}/i.test(String(content || ''));
2259
2281
  }
2260
2282
 
2283
+ /** The "Try again" button of the failed chip on the board: runs the last prompt of the primary widget's chat again,
2284
+ * the same way the retry button of the failed message in the chat does. */
2285
+ async function handleSketchRetryFailedGeneration() {
2286
+ const widgetId = canvasPrimaryWidgetId;
2287
+ if (!widgetId) return;
2288
+ try {
2289
+ const panelChat = getChatMethodsForWidget(widgetId);
2290
+ const conversationId = panelChat?.getConversationId?.() ?? getPanelState(widgetId).currentChatConversationId ?? null;
2291
+ if (!conversationId) {
2292
+ console.warn('[Creator] Try again on the failed chip: the widget has no conversation to read the prompt from');
2293
+ return;
2294
+ }
2295
+ const conversationMessages = (await handleLoadMessages(conversationId, widgetId, { scope: 'all' })) || [];
2296
+ const lastUserMessage = [...conversationMessages]
2297
+ .reverse()
2298
+ .find((message) => (message.messageType || message.message_type) === 'user');
2299
+ const lastPromptText = String(lastUserMessage?.messageContent || lastUserMessage?.message_content || '').trim();
2300
+ if (!lastPromptText) {
2301
+ console.warn('[Creator] Try again on the failed chip: no earlier prompt found in the conversation');
2302
+ return;
2303
+ }
2304
+ await handleChatRetryMessage(lastPromptText, widgetId);
2305
+ } catch (error) {
2306
+ console.error('[Creator] Try again on the failed chip did not start', error);
2307
+ }
2308
+ }
2309
+
2261
2310
  /** Retry failed codegen without duplicating the user bubble. A successful prompt forks a new message so each version has its own turn. */
2262
2311
  async function handleChatRetryMessage(content: string, sourceWidgetId?: string) {
2263
2312
  const widgetId = sourceWidgetId ?? selectedWidgetId;
@@ -6343,6 +6392,202 @@
6343
6392
  /** Mobile embedded sketch: Canvas | Chat tabs (both panes stay mounted; CSS hides the inactive one). */
6344
6393
  let embeddedSketchMobileTab: EmbeddedSketchMobileTab = 'canvas';
6345
6394
  $: embeddedSketchShell = embedded && !canvasAdvancedFeatures;
6395
+
6396
+ function sketchPrimaryGenerationFailed(widgetId: string | null): boolean {
6397
+ if (!widgetId) return false;
6398
+ const w = getWidgetById(widgetId) as Record<string, unknown> | null;
6399
+ return isSketchGenerationFailed(getPanelDisplayState(widgetId), w);
6400
+ }
6401
+
6402
+ $: sketchBarGenerationFailed = sketchPrimaryGenerationFailed(canvasPrimaryWidgetId);
6403
+
6404
+ $: sketchBarTitleLabel = (void panelDisplayRevision, void sketchBarGenerationFailed, void canvasPrimaryWidgetId, sketchBarTitle());
6405
+
6406
+ function sketchBarTitle(): string {
6407
+ const untitled = $t('creator.widget.untitledName');
6408
+ const persistence = String(sketchCanvasPersistenceName || activeCanvasName || '').trim();
6409
+ const persistenceOk = persistence && persistence !== 'Loading...' && persistence !== 'No Canvas';
6410
+ if (canvasPrimaryWidgetId) {
6411
+ if (sketchPrimaryGenerationFailed(canvasPrimaryWidgetId)) {
6412
+ const fromWidget = getWidgetNameById(canvasPrimaryWidgetId);
6413
+ if (fromWidget) return fromWidget;
6414
+ return untitled;
6415
+ }
6416
+ const fromBatch = (sketchWidgetNamesFromBatch[canvasPrimaryWidgetId] || '').trim();
6417
+ if (fromBatch && fromBatch !== untitled) return fromBatch;
6418
+ const fromWidget = getWidgetNameById(canvasPrimaryWidgetId);
6419
+ if (fromWidget && fromWidget !== untitled) return fromWidget;
6420
+ if (persistenceOk) return persistence;
6421
+ return fromWidget || fromBatch || $t('creator.widget.fallbackName');
6422
+ }
6423
+ if (persistenceOk) return persistence;
6424
+ return untitled;
6425
+ }
6426
+
6427
+ function sketchWidgetHasCommitArtifact(widget: Record<string, unknown> | null | undefined): boolean {
6428
+ if (!widget) return false;
6429
+ const commit =
6430
+ (widget as { lastCommitSha?: string | null }).lastCommitSha
6431
+ ?? (widget as { last_commit_sha?: string | null }).last_commit_sha
6432
+ ?? null;
6433
+ const publish =
6434
+ (widget as { lastPublishCommitSha?: string | null }).lastPublishCommitSha
6435
+ ?? (widget as { last_publish_commit_sha?: string | null }).last_publish_commit_sha
6436
+ ?? null;
6437
+ return !!(String(commit || '').trim() || String(publish || '').trim());
6438
+ }
6439
+
6440
+ function sketchPrimaryHasGeneratedCode(widgetId: string | null): boolean {
6441
+ if (!widgetId) return false;
6442
+ const ps = getPanelDisplayState(widgetId);
6443
+ if (ps.lastCommitId || ps.hasGeneratedCode || ps.lastPublishedVersion != null) return true;
6444
+ return sketchWidgetHasCommitArtifact(getWidgetById(widgetId) as Record<string, unknown> | null);
6445
+ }
6446
+
6447
+ function sketchPrimaryShowsLiveBadge(widgetId: string | null): boolean {
6448
+ if (!widgetId) return false;
6449
+ const widget = getWidgetById(widgetId) as Record<string, unknown> | null;
6450
+ if (!widget) return false;
6451
+ if (widget.hasLiveVersion === true || widget.has_live_version === true) return true;
6452
+ return resolvePublishedVersionFromWidget(widget as WidgetSummary | null) !== null;
6453
+ }
6454
+
6455
+ function sketchWidgetHasActiveCodegenOperation(widgetId: string | null): boolean {
6456
+ if (!widgetId) return false;
6457
+ const w = getWidgetById(widgetId) as Record<string, unknown> | null;
6458
+ const op = String(
6459
+ (w?.activeOperationId as string | undefined) ?? (w?.active_operation_id as string | undefined) ?? '',
6460
+ ).trim();
6461
+ return !!op;
6462
+ }
6463
+
6464
+ $: sketchBarCanvasGenerating =
6465
+ !!canvasPrimaryWidgetId &&
6466
+ (!!generatingWidgetIds[canvasPrimaryWidgetId] ||
6467
+ sketchWidgetHasActiveCodegenOperation(canvasPrimaryWidgetId));
6468
+
6469
+ $: sketchBarStatusLabel = !embeddedSketchShell
6470
+ ? ''
6471
+ : !canvasPrimaryWidgetId
6472
+ ? $t('creator.common.draft')
6473
+ : sketchPrimaryShowsLiveBadge(canvasPrimaryWidgetId)
6474
+ ? $t('creator.sketch.publishedJustNow')
6475
+ : sketchBarGenerationFailed
6476
+ ? $t('creator.common.draft')
6477
+ : sketchPrimaryHasGeneratedCode(canvasPrimaryWidgetId)
6478
+ ? sketchSavedStatusLabel(
6479
+ $t('creator.general.saved'),
6480
+ (getWidgetById(canvasPrimaryWidgetId) as { updatedAt?: string; updated_at?: string } | null)
6481
+ ?.updatedAt ?? (getWidgetById(canvasPrimaryWidgetId) as { updated_at?: string } | null)?.updated_at,
6482
+ )
6483
+ : $t('creator.common.draft');
6484
+
6485
+ $: sketchBarShowPublish = sketchBarShowsPublish({
6486
+ embedded: embeddedSketchShell,
6487
+ widgetId: canvasPrimaryWidgetId,
6488
+ hasGeneratedCode: sketchPrimaryHasGeneratedCode(canvasPrimaryWidgetId),
6489
+ showsLive: sketchPrimaryShowsLiveBadge(canvasPrimaryWidgetId),
6490
+ generating: sketchBarCanvasGenerating,
6491
+ failed: sketchBarGenerationFailed,
6492
+ });
6493
+
6494
+ $: sketchBarShowCustomize = sketchBarShowsCustomize({
6495
+ embedded: embeddedSketchShell,
6496
+ widgetId: canvasPrimaryWidgetId,
6497
+ hasGeneratedCode: sketchPrimaryHasGeneratedCode(canvasPrimaryWidgetId),
6498
+ generating: !!canvasPrimaryWidgetId && !!generatingWidgetIds[canvasPrimaryWidgetId],
6499
+ failed: sketchBarGenerationFailed,
6500
+ hasActiveCodegen: sketchWidgetHasActiveCodegenOperation(canvasPrimaryWidgetId),
6501
+ });
6502
+
6503
+ $: sketchBarShowLiveBadge =
6504
+ embeddedSketchShell && sketchPrimaryShowsLiveBadge(canvasPrimaryWidgetId);
6505
+
6506
+ $: sketchBarPublishLabel =
6507
+ sketchBarShowLiveBadge
6508
+ ? $t('creator.common.update')
6509
+ : $t('creator.common.publish');
6510
+
6511
+ $: if (embeddedSketchShell && canvasRef?.saveCanvas && isCanvasStateLoaded) {
6512
+ try {
6513
+ const raw = canvasRef.saveCanvas();
6514
+ if (raw) {
6515
+ const parsed = JSON.parse(raw);
6516
+ const shapes = parsed?.canvas?.objects ?? parsed?.objects ?? [];
6517
+ if (Array.isArray(shapes)) {
6518
+ const primaryId = (canvasPrimaryWidgetId || '').trim();
6519
+ const card = shapes.find(
6520
+ (obj: { _widgetId?: string; name?: string; type?: string; _isWidgetImage?: boolean }) => {
6521
+ if (primaryId && obj?._widgetId === primaryId) return true;
6522
+ return (
6523
+ (obj?.type === 'widget' || obj?._isWidgetImage) && String(obj?.name ?? '').trim()
6524
+ );
6525
+ },
6526
+ );
6527
+ const shapeTitle = String((card as { name?: string } | undefined)?.name ?? '').trim();
6528
+ if (shapeTitle) {
6529
+ sketchCanvasPersistenceName = shapeTitle;
6530
+ activeCanvasName = shapeTitle;
6531
+ }
6532
+ }
6533
+ }
6534
+ } catch {
6535
+ /* saveCanvas not ready */
6536
+ }
6537
+ }
6538
+
6539
+ $: sketchBoardStatusChip = (() => {
6540
+ if (!embeddedSketchShell) return null;
6541
+ const id = canvasPrimaryWidgetId;
6542
+ if (!id) return null;
6543
+ if (generatingWidgetIds[id] || sketchWidgetHasActiveCodegenOperation(id)) {
6544
+ return { variant: 'generating' as const, label: $t('creator.sketch.boardGenerating') };
6545
+ }
6546
+ const ps = getPanelDisplayState(id);
6547
+ const w = getWidgetById(id) as Record<string, unknown> | null;
6548
+ const codegenStatus = String(
6549
+ (w?.codegenStatus as string | undefined) ?? (w?.codegen_status as string | undefined) ?? '',
6550
+ ).trim();
6551
+ const failed =
6552
+ ps.lastGenerationFailed
6553
+ || codegenStatus === 'failed'
6554
+ || (w as { generationFailed?: boolean } | null)?.generationFailed === true
6555
+ || (w as { generation_failed?: boolean } | null)?.generation_failed === true;
6556
+ if (failed) {
6557
+ return {
6558
+ variant: 'failed' as const,
6559
+ label: $t('creator.sketch.boardFailed'),
6560
+ actionLabel: $t('creator.sketch.boardFailedRetry'),
6561
+ };
6562
+ }
6563
+ if (sketchPrimaryShowsLiveBadge(id)) {
6564
+ return null;
6565
+ }
6566
+ if (sketchPrimaryHasGeneratedCode(id)) {
6567
+ return { variant: 'ready' as const, label: $t('creator.sketch.boardReady') };
6568
+ }
6569
+ return null;
6570
+ })();
6571
+
6572
+ function handleSketchBarTitleClick() {
6573
+ if (canvasPrimaryWidgetId) {
6574
+ void openWidgetDetailsPanel(canvasPrimaryWidgetId);
6575
+ return;
6576
+ }
6577
+ startCanvasNameEdit();
6578
+ }
6579
+
6580
+ function handleSketchCustomize() {
6581
+ const id = canvasPrimaryWidgetId;
6582
+ if (!id) return;
6583
+ void openWidgetDetailsPanel(id).then(() => {
6584
+ widgetDetailsStep = 'edit';
6585
+ });
6586
+ }
6587
+
6588
+ $: sketchCanvasShowZoom = embeddedSketchShell || debugMode;
6589
+ $: sketchCanvasPanZoomPosition = (embeddedSketchShell ? 'BL' : 'TL') as 'BL' | 'TL';
6590
+ $: sketchCanvasShowSaveButton = embeddedSketchShell ? false : showSaveButton;
6346
6591
  if (debugModeAvailable && typeof window !== 'undefined') {
6347
6592
  try {
6348
6593
  const storedDebugMode = creatorStorage.getItem('widgetic:site-debug-on');
@@ -6575,6 +6820,9 @@
6575
6820
  if (singleWidgetChromeReady || !canvasComponentReady || !isCanvasStateLoaded) return;
6576
6821
  singleWidgetChromeReady = true;
6577
6822
  console.log('[CreatorApp] Bottom bars released after the canvas was read', { canvasId, primaryId: canvasPrimaryWidgetId });
6823
+ if (embeddedSketchShell && !(canvasPrimaryWidgetId || '').trim()) {
6824
+ void ensureSimpleCanvasChat();
6825
+ }
6578
6826
  }
6579
6827
 
6580
6828
  // Whichever code made the canvas known, a canvas that is up, read, and has its primary widget gets its bar.
@@ -6616,6 +6864,9 @@
6616
6864
  && primaryWidgetHasGeneratedCode()
6617
6865
  )
6618
6866
  );
6867
+ $: sketchCanvasShowDrawingTools = embeddedSketchShell
6868
+ ? !canvasPrimaryWidgetId || showDrawingTools
6869
+ : showDrawingTools;
6619
6870
 
6620
6871
  function emitCreatorWireframeChanged() {
6621
6872
  announceToSite(CREATOR_WIREFRAME_CHANGED_EVENT, { wireframeMode: canvasWireframeMode });
@@ -6904,6 +7155,39 @@
6904
7155
  void persistPrimaryWidgetId(widgetId);
6905
7156
  }
6906
7157
 
7158
+ async function resumeEmbeddedSketchScenario(primaryId: string): Promise<void> {
7159
+ if (!embeddedSketchShell || !primaryId) return;
7160
+ ensurePanelState(primaryId);
7161
+ const widget = getWidgetById(primaryId) as Record<string, unknown> | null;
7162
+ const opId = String(
7163
+ (widget?.activeOperationId as string | undefined)
7164
+ ?? (widget?.active_operation_id as string | undefined)
7165
+ ?? '',
7166
+ ).trim();
7167
+ if (opId && operationsClient) {
7168
+ await followGeneration(primaryId, opId, 'announced');
7169
+ return;
7170
+ }
7171
+ const base = String(apiUrl || import.meta.env.VITE_API_URL || '').replace(/\/+$/, '');
7172
+ if (!base) return;
7173
+ try {
7174
+ const res = await fetch(`${base}/v1/__mock/creator/sketch-ui`);
7175
+ if (!res.ok) return;
7176
+ const payload = (await res.json()) as { data?: { mode?: string; widgetId?: string } };
7177
+ const ui = (payload?.data ?? payload) as { mode?: string; widgetId?: string };
7178
+ if (ui?.mode === 'generating' && ui.widgetId === primaryId) {
7179
+ generatingWidgetIds = { ...generatingWidgetIds, [primaryId]: true };
7180
+ patchCodegenUiState(primaryId, {
7181
+ generateCodeStatus: 'Code generation in progress...',
7182
+ lastGenerationFailed: false,
7183
+ lastGenerationError: null,
7184
+ });
7185
+ }
7186
+ } catch {
7187
+ /* mock-only hint; ignore when absent */
7188
+ }
7189
+ }
7190
+
6907
7191
  async function hydrateCanvasPrimaryWidget(linkedIds?: string[]): Promise<string | null> {
6908
7192
  const targetCanvasId = (typeof canvasId === 'string' && canvasId.trim()) ? canvasId.trim() : null;
6909
7193
  if (!targetCanvasId) return canvasPrimaryWidgetId || null;
@@ -6952,9 +7236,31 @@
6952
7236
  }
6953
7237
  }
6954
7238
  if (primaryId) {
7239
+ if (embeddedSketchShell && widgetsClient) {
7240
+ try {
7241
+ const response = await widgetsClient.getWidgetsBatch({
7242
+ getWidgetsBatchRequest: { widgetIds: [primaryId] },
7243
+ });
7244
+ const row =
7245
+ (response as { widgets?: Array<{ id?: string; name?: string }> })?.widgets?.[0]
7246
+ ?? (response as { data?: { widgets?: Array<{ id?: string; name?: string }> } })?.data
7247
+ ?.widgets?.[0];
7248
+ const batchName = String(row?.name ?? '').trim();
7249
+ if (batchName) {
7250
+ sketchWidgetNamesFromBatch = { ...sketchWidgetNamesFromBatch, [primaryId]: batchName };
7251
+ widgets = widgets.map((w) => (w.id === primaryId ? { ...w, name: batchName } : w));
7252
+ panelDisplayRevision += 1;
7253
+ }
7254
+ } catch (batchNameErr) {
7255
+ console.warn('[CreatorApp] Sketch primary batch name read failed', batchNameErr);
7256
+ }
7257
+ }
6955
7258
  const widget = getWidgetById(primaryId);
6956
7259
  if (widget) notifyHostWidgetName(widget);
6957
7260
  emitCanvasWidgetsList('hydrate-primary');
7261
+ if (embeddedSketchShell) {
7262
+ await mergeWidgetsLinkedOnCanvas([primaryId]);
7263
+ }
6958
7264
  }
6959
7265
  return primaryId || canvasPrimaryWidgetId || null;
6960
7266
  }
@@ -6962,6 +7268,10 @@
6962
7268
  function applyPrimarySelectionOnCanvas(primaryId: string | null | undefined): void {
6963
7269
  if (!primaryId || !canvasRef || isConvertOrDraftPanelOpen()) return;
6964
7270
  canvasRef.setPrimaryWidgetShape?.(primaryId);
7271
+ if (embeddedSketchShell && sketchPrimaryHasGeneratedCode(primaryId)) {
7272
+ canvasRef.deselectAll?.();
7273
+ return;
7274
+ }
6965
7275
  canvasRef.selectWidgetShape?.(primaryId);
6966
7276
  }
6967
7277
 
@@ -7613,6 +7923,13 @@
7613
7923
  function announceCanvasName(targetCanvasId: string, record: Record<string, any> | null): void {
7614
7924
  const name = String(record?.persistenceKey || record?.persistence_key || '').trim();
7615
7925
  if (!name) return;
7926
+ if (embedded && !canvasAdvancedFeatures) {
7927
+ const activeId = (canvasId || sessionCanvasId || routeCanvasId || '').trim();
7928
+ if (!activeId || activeId === targetCanvasId) {
7929
+ sketchCanvasPersistenceName = name;
7930
+ activeCanvasName = name;
7931
+ }
7932
+ }
7616
7933
  announceToSite('widgetic:creator-canvas-name', { canvasId: targetCanvasId, name });
7617
7934
  }
7618
7935
 
@@ -7682,6 +7999,10 @@
7682
7999
 
7683
8000
  // Resolve the canvas from the address bar before any localStorage fallback — see
7684
8001
  // readCanvasIdFromAddressBar(). This must happen before initialCandidateCanvasId.
8002
+ if (!routeCanvasId) {
8003
+ const fromProp = typeof canvasId === 'string' ? canvasId.trim() : '';
8004
+ if (fromProp) routeCanvasId = fromProp;
8005
+ }
7685
8006
  if (!routeCanvasId) {
7686
8007
  const fromAddressBar = readCanvasIdFromAddressBar();
7687
8008
  if (fromAddressBar) routeCanvasId = fromAddressBar;
@@ -7729,6 +8050,12 @@
7729
8050
  // New canvas session — clear primary from previous canvas before hydrate.
7730
8051
  canvasPrimaryWidgetId = null;
7731
8052
  embeddedDeepLinkAutoOpenDone = false;
8053
+ try {
8054
+ const routeRead = await readCanvasRecord(routeCanvasId);
8055
+ if (routeRead.record) announceCanvasName(routeCanvasId, routeRead.record);
8056
+ } catch (routeNameErr) {
8057
+ console.warn('[CreatorApp] Route canvas name prefetch failed', routeNameErr);
8058
+ }
7732
8059
  // console.log('WidgetCreator.loadCurrentCanvas: Loading data for route canvasId:', canvasId);
7733
8060
  }
7734
8061
  // Fallback: get latest canvas from current user's canvases
@@ -7871,6 +8198,9 @@
7871
8198
  });
7872
8199
  }
7873
8200
  releaseSingleWidgetChrome();
8201
+ if (primaryId && embeddedSketchShell) {
8202
+ void resumeEmbeddedSketchScenario(primaryId);
8203
+ }
7874
8204
  } catch (error) {
7875
8205
  console.error('Widget Creator: Load canvases error:', error);
7876
8206
  const defaultError = $t('creator.canvas.failedToLoadCanvases');
@@ -8869,18 +9199,29 @@
8869
9199
  }
8870
9200
 
8871
9201
  const existingIds = new Set(widgets.map((w) => w.id).filter(Boolean) as string[]);
9202
+ const untitled = $t('creator.widget.untitledName');
8872
9203
  const missingIds = [...linkedIds].filter((id) => !existingIds.has(id));
9204
+ const staleNameIds = embeddedSketchShell
9205
+ ? [...linkedIds].filter((id) => {
9206
+ const row = getWidgetById(id);
9207
+ const nm = String(row?.name ?? '').trim();
9208
+ return !!row && (!nm || nm === untitled);
9209
+ })
9210
+ : [];
9211
+ const fetchIds = embeddedSketchShell
9212
+ ? [...new Set([...linkedIds, ...missingIds, ...staleNameIds])]
9213
+ : [...new Set([...missingIds, ...staleNameIds])];
8873
9214
  refreshLinkedWidgetIds();
8874
9215
 
8875
- if (missingIds.length === 0) return;
9216
+ if (fetchIds.length === 0) return;
8876
9217
 
8877
9218
  // Both start paths reach here together once the shared widget list arrives; the same ids are fetched once.
8878
- const mergeKey = `${resolveHostCanvasId() ?? ''}:${[...missingIds].sort().join(',')}`;
9219
+ const mergeKey = `${resolveHostCanvasId() ?? ''}:${[...fetchIds].sort().join(',')}`;
8879
9220
  if (linkedWidgetsMerge?.key === mergeKey) {
8880
9221
  await linkedWidgetsMerge.done;
8881
9222
  return;
8882
9223
  }
8883
- const done = fetchAndMergeLinkedWidgets(missingIds);
9224
+ const done = fetchAndMergeLinkedWidgets(fetchIds);
8884
9225
  linkedWidgetsMerge = { key: mergeKey, done };
8885
9226
  try {
8886
9227
  await done;
@@ -8940,6 +9281,10 @@
8940
9281
  for (const widget of fetched) {
8941
9282
  if (widget?.id) {
8942
9283
  mergedById.set(widget.id, preserveRepositoryOnWidget(widget, previousById.get(widget.id)));
9284
+ const batchName = String(widget.name ?? '').trim();
9285
+ if (embeddedSketchShell && batchName) {
9286
+ sketchWidgetNamesFromBatch = { ...sketchWidgetNamesFromBatch, [widget.id]: batchName };
9287
+ }
8943
9288
  }
8944
9289
  }
8945
9290
  widgets = sortWidgetSummaries([...mergedById.values()]);
@@ -9717,6 +10062,9 @@
9717
10062
  ?? null;
9718
10063
  // HEAD commit: localStorage or last codegen SHA only — never default to publish SHA (that hides "ahead of live").
9719
10064
  lastCommitId = storedCommitId || widgetCommitSha || null;
10065
+ if (!lastCommitId && widgetPublishSha && embeddedSketchShell) {
10066
+ lastCommitId = widgetPublishSha;
10067
+ }
9720
10068
  if (lastCommitId) {
9721
10069
  // console.log(
9722
10070
  // `[Version] Widget "${widget?.name}" commit loaded: ${lastCommitId.substring(0, 7)}`,
@@ -14159,7 +14507,7 @@ Requirements:
14159
14507
  }
14160
14508
 
14161
14509
  function defaultPanelState(widgetId: string): WidgetPanelSnapshot {
14162
- const widget = getWidgetById(widgetId);
14510
+ const widget = isDraftConvertId(widgetId) ? null : getWidgetById(widgetId);
14163
14511
  let storedPrompt = DEFAULT_PROMPT;
14164
14512
  try {
14165
14513
  storedPrompt =
@@ -14182,6 +14530,15 @@ Requirements:
14182
14530
  const livePublishSha = getWidgetLastPublishCommitSha(widgetId);
14183
14531
  const pendingPublishSha = loadPendingPublishShaForWidget(widgetId);
14184
14532
  const publishedVersion = resolvePublishedVersionFromWidget(widget);
14533
+ const codegenStatus =
14534
+ (widget as { codegenStatus?: string | null; codegen_status?: string | null } | undefined)
14535
+ ?.codegenStatus
14536
+ ?? (widget as { codegen_status?: string | null } | undefined)?.codegen_status
14537
+ ?? null;
14538
+ const generationFailedFlag =
14539
+ codegenStatus === 'failed'
14540
+ || (widget as { generationFailed?: boolean } | null)?.generationFailed === true
14541
+ || (widget as { generation_failed?: boolean } | null)?.generation_failed === true;
14185
14542
  const unpublishedPending =
14186
14543
  !!pendingPublishSha
14187
14544
  && !!livePublishSha
@@ -14199,7 +14556,7 @@ Requirements:
14199
14556
  currentRepositoryId: normalizeRepositoryId(widget),
14200
14557
  widgetDetailsStep: resolveCreatorWorkflowStep(publishedVersion !== null ? 'edit' : 'create'),
14201
14558
  generateCodeStatus: null,
14202
- lastGenerationFailed: false,
14559
+ lastGenerationFailed: generationFailedFlag,
14203
14560
  lastGenerationError: null,
14204
14561
  currentChatConversationId: null,
14205
14562
  publishHistory: [],
@@ -14689,7 +15046,12 @@ Requirements:
14689
15046
  if (!widgetId) return null;
14690
15047
  const source = shapePreviewSourceByWidgetId[widgetId] || 'live';
14691
15048
  const ps = getPanelDisplayState(widgetId);
14692
- const hasCode = !!(ps.lastCommitId || loadCommitIdForWidget(widgetId));
15049
+ const widgetRow = getWidgetById(widgetId) as Record<string, unknown> | null;
15050
+ const hasCode = !!(
15051
+ ps.lastCommitId
15052
+ || loadCommitIdForWidget(widgetId)
15053
+ || (embeddedSketchShell && sketchWidgetHasCommitArtifact(widgetRow))
15054
+ );
14693
15055
  const workerUrl = hasCode
14694
15056
  ? `${widgetBuilderPreviewBaseUrl()}/preview/${widgetId}`
14695
15057
  : null;
@@ -17944,7 +18306,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17944
18306
 
17945
18307
  /** Simple canvas: one chat, always. The draft id stands in until the first Send creates the widget. */
17946
18308
  async function ensureSimpleCanvasChat(): Promise<void> {
17947
- if (!embedded || canvasAdvancedFeatures || !canvasComponentReady || !hasValidToken || !conversationsClient) return;
18309
+ if (!embedded || canvasAdvancedFeatures || !canvasComponentReady || !hasValidToken) return;
17948
18310
  if (finalizingDraftConversions.size > 0) return;
17949
18311
  const primaryId = (canvasPrimaryWidgetId || '').trim();
17950
18312
  // The canvas JSON is loaded before the primary widget is known. Opening the draft chat in that gap
@@ -17979,6 +18341,32 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17979
18341
  void ensureSimpleCanvasChat();
17980
18342
  }
17981
18343
 
18344
+ $: if (
18345
+ conversationsClient &&
18346
+ hasValidToken &&
18347
+ embedded &&
18348
+ !canvasAdvancedFeatures &&
18349
+ canvasComponentReady &&
18350
+ isCanvasStateLoaded &&
18351
+ (singleWidgetChromeReady || !!(canvasPrimaryWidgetId || '').trim()) &&
18352
+ openWidgetPanelIds.length === 0
18353
+ ) {
18354
+ void ensureSimpleCanvasChat();
18355
+ }
18356
+
18357
+ /** Figma empty/sketch: dock the canvas draft chat as soon as chrome is released without a primary widget. */
18358
+ $: if (
18359
+ embeddedSketchShell &&
18360
+ hasValidToken &&
18361
+ canvasComponentReady &&
18362
+ isCanvasStateLoaded &&
18363
+ singleWidgetChromeReady &&
18364
+ !(canvasPrimaryWidgetId || '').trim() &&
18365
+ !openWidgetPanelIds.includes(CANVAS_SKETCH_DRAFT_ID)
18366
+ ) {
18367
+ void openWidgetDetailsPanel(CANVAS_SKETCH_DRAFT_ID);
18368
+ }
18369
+
17982
18370
  async function handleCanvasReady() {
17983
18371
  markCanvasOpenStep('creator:canvas-ready');
17984
18372
  // console.log('[WidgetCreator] Canvas component ready');
@@ -18178,6 +18566,13 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18178
18566
  console.log('[CanvasDebug] Ignoring stale getCanvas result', { loadEpoch, canvasLoadEpoch });
18179
18567
  return emptyResult;
18180
18568
  }
18569
+ const persistenceLabel = String(
18570
+ canvasRecord?.persistenceKey || canvasRecord?.persistence_key || '',
18571
+ ).trim();
18572
+ if (persistenceLabel && embedded && !canvasAdvancedFeatures) {
18573
+ sketchCanvasPersistenceName = persistenceLabel;
18574
+ activeCanvasName = persistenceLabel;
18575
+ }
18181
18576
  canvasContent = canvasRecord?.canvasContent ?? canvasRecord?.canvas_content ?? null;
18182
18577
  if (canvasContent) break;
18183
18578
  // A canvas that was never saved is empty for certain; waiting for content would take seconds.
@@ -18202,6 +18597,19 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18202
18597
  // console.log(`[CanvasDebug] Loading canvas ${canvasId}: ${objectCount} shapes found in DB`);
18203
18598
 
18204
18599
  const widgetIdsOnCanvas = extractWidgetIdsFromCanvasContent(parsed);
18600
+ if (embeddedSketchShell) {
18601
+ const shapes = parsed?.canvas?.objects ?? parsed?.objects ?? [];
18602
+ const primaryShape =
18603
+ (Array.isArray(shapes) ? shapes : []).find(
18604
+ (obj: { type?: string; _widgetId?: string; _isWidgetImage?: boolean; name?: string }) =>
18605
+ (obj?.type === 'widget' || obj?._isWidgetImage) && String(obj?.name ?? '').trim(),
18606
+ ) ?? null;
18607
+ const shapeTitle = String((primaryShape as { name?: string } | null)?.name ?? '').trim();
18608
+ if (shapeTitle) {
18609
+ sketchCanvasPersistenceName = shapeTitle;
18610
+ activeCanvasName = shapeTitle;
18611
+ }
18612
+ }
18205
18613
  const jsonString =
18206
18614
  typeof canvasContent === 'string' ? canvasContent : JSON.stringify(canvasContent);
18207
18615
 
@@ -18520,150 +18928,6 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18520
18928
  refreshLinkedWidgetIds();
18521
18929
  }
18522
18930
 
18523
- /**
18524
- * Convert UX v2 — clicking "Convert to Widget" no longer creates anything in
18525
- * the DB. It only:
18526
- * 1. keeps the sketch on the canvas (the caller groups it via onGroupSelection),
18527
- * 2. opens a DRAFT WidgetDetails panel under a synthetic id,
18528
- * 3. prefills the panel chat with the captured screenshot + CONVERT_PROMPT.
18529
- * The widget record, component, repository, and shape replacement all happen
18530
- * in finalizeDraftConversion() when the user sends the first prompt.
18531
- */
18532
- async function handleConvertToWidget(payload: WidgetConversionPayload) {
18533
- // console.log('[WidgetCreator] Convert to widget (draft, v2):', payload);
18534
-
18535
- if (!$userSession.user || !hasValidToken) {
18536
- showToast('error', $t('creator.session.pleaseLoginFirst'));
18537
- return;
18538
- }
18539
- if (simpleCanvasHasItsWidget()) {
18540
- showToast('info', $t('creator.widget.oneWidgetAlready'));
18541
- return;
18542
- }
18543
- if (isWidgetOperationInProgress) {
18544
- console.warn('[WidgetCreator] Another widget operation in progress, skipping convert');
18545
- showToast('warning', $t('creator.general.pleaseWaitForTheCurrent'));
18546
- return;
18547
- }
18548
-
18549
- const screenshotValid =
18550
- !!payload.screenshot && payload.screenshot.startsWith('data:image/');
18551
- if (!screenshotValid) {
18552
- console.error(
18553
- '[WidgetCreator] Convert screenshot capture FAILED (length:',
18554
- payload.screenshot?.length ?? 0,
18555
- ') — keeping original shapes so the sketch is not lost'
18556
- );
18557
- showToast('warning', $t('creator.general.screenshotCouldNotBeCaptured'), {
18558
- description: $t('creator.general.fixTheSelectionZoomOut'),
18559
- duration: 10000
18560
- });
18561
- return;
18562
- }
18563
-
18564
- const draftId = `${DRAFT_CONVERT_ID_PREFIX}${Date.now()}`;
18565
- const draftName = payload.frameName && payload.frameName !== 'image'
18566
- ? `Converted ${payload.frameName}`
18567
- : `ConvertedW-${Date.now()}`;
18568
- draftConvertScreenshots.set(draftId, payload.screenshot);
18569
- draftConvertObjectIds.set(draftId, payload.frameId);
18570
- // Grouping deselects the sketch; that must not close the draft or open the primary widget.
18571
- suppressWidgetDetailsClose = true;
18572
-
18573
- // Group the sketch into one editable object and keep it on canvas — the
18574
- // user may keep editing it (ungroup, move, restyle) and re-convert later.
18575
- // The returned id identifies the group for the later shape replacement.
18576
- if (canvasRef?.onGroupSelection) {
18577
- try {
18578
- const groupId = await canvasRef.onGroupSelection();
18579
- if (groupId) draftConvertObjectIds.set(draftId, groupId);
18580
- } catch (groupErr) {
18581
- console.warn('[WidgetCreator] Group selection failed — continuing with raw selection:', groupErr);
18582
- }
18583
- }
18584
-
18585
- // Re-convert of a group that already has a draft: reopen that draft
18586
- // panel instead of piling up duplicate drafts for the same sketch.
18587
- const canvasObjectId = draftConvertObjectIds.get(draftId);
18588
- const existingDraftId = canvasObjectId
18589
- ? [...draftConvertObjectIds.entries()].find(([id, objId]) => id !== draftId && objId === canvasObjectId)?.[0]
18590
- : undefined;
18591
- if (existingDraftId) {
18592
- draftConvertObjectIds.delete(draftId);
18593
- draftConvertScreenshots.delete(draftId);
18594
- // console.log('[WidgetCreator] Convert re-opened existing draft for group:', existingDraftId);
18595
- await openWidgetDetailsPanel(existingDraftId);
18596
- // Refresh the stored screenshot so finalize uses the latest sketch look
18597
- draftConvertScreenshots.set(existingDraftId, payload.screenshot);
18598
- authStatus = 'Widget draft ready — send the prompt to generate.';
18599
- setTimeout(() => {
18600
- if (!finalizingDraftConversions.size) {
18601
- suppressWidgetDetailsClose = false;
18602
- }
18603
- }, 1500);
18604
- return;
18605
- }
18606
-
18607
- try {
18608
- isWidgetOperationInProgress = true;
18609
- authStatus = 'Preparing widget draft...';
18610
-
18611
- // Draft panel snapshot (no widget record in DB). WidgetDetails is
18612
- // null-safe for a missing widget — the panel shows the draft name.
18613
- await openWidgetDetailsPanel(draftId);
18614
- embeddedDeepLinkAutoOpenDone = true;
18615
- patchPanelSnapshot(draftId, {
18616
- codeGenerationPrompt: CONVERT_PROMPT,
18617
- promptImages: [payload.screenshot],
18618
- });
18619
-
18620
- // Prefill the chat draft — sending the message starts the real conversion.
18621
- // Set the globals too: if the Chat component registers later (async mount),
18622
- // restoreChatDraftFromStorage reapplies this exact draft to the input.
18623
- loadPromptGeneration += 1;
18624
- promptImages = [payload.screenshot];
18625
- codeGenerationPrompt = CONVERT_PROMPT;
18626
- promptLoadedForWidgetId = draftId;
18627
- pendingChatDraftText = CONVERT_PROMPT;
18628
- chatDraftRestoredForWidgetId = null;
18629
- pendingSketchGeneratePrefill = false;
18630
- sketchPrefillApplied = true;
18631
- savePromptForWidget(draftId);
18632
- const panelChat = getChatMethodsForWidget(draftId);
18633
- if (panelChat) {
18634
- panelChat.setDraftText?.(CONVERT_PROMPT);
18635
- panelChat.addImageAttachment?.(payload.screenshot, 'design-screenshot.png');
18636
- // console.log(
18637
- // '[Convert] Draft chat prefilled (no auto-start):',
18638
- // draftId,
18639
- // '| prompt:',
18640
- // CONVERT_PROMPT,
18641
- // '| screenshot attached: true'
18642
- // );
18643
- } else {
18644
- console.warn('[Convert] Chat methods not ready — draft stays in panel snapshot for restore:', draftId);
18645
- }
18646
-
18647
- authStatus = 'Widget draft ready — send the prompt to generate.';
18648
- showToast('info', $t('creator.widget.widgetDraftCreated'), {
18649
- description: $t('creator.codegen.editTheSketchFreelySending')
18650
- });
18651
- } catch (error) {
18652
- console.error('[WidgetCreator] Convert to widget (draft) error:', error);
18653
- draftConvertObjectIds.delete(draftId);
18654
- draftConvertScreenshots.delete(draftId);
18655
- authStatus = toErrorMessage(error, 'Failed to prepare widget draft.');
18656
- showToast('error', $t('creator.widget.failedToPrepareWidgetDraft'));
18657
- } finally {
18658
- isWidgetOperationInProgress = false;
18659
- setTimeout(() => {
18660
- if (!finalizingDraftConversions.size) {
18661
- suppressWidgetDetailsClose = false;
18662
- }
18663
- }, 1500);
18664
- }
18665
- }
18666
-
18667
18931
  /**
18668
18932
  * Runs on the FIRST prompt send of a draft conversion: creates the widget
18669
18933
  * record + component + repository, replaces the grouped sketch on canvas with
@@ -19613,9 +19877,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19613
19877
  <!-- Widgetic Canvas Editor - Full width background (lazy-loaded) -->
19614
19878
  <div
19615
19879
  class="wc-canvas-area flex-1 min-h-0 min-w-0 relative {embeddedSketchShell
19616
- ? 'flex flex-col lg:pe-[450px] max-lg:pe-0'
19880
+ ? 'flex flex-col bg-sidebar'
19617
19881
  : embedded && !canvasAdvancedFeatures
19618
- ? 'pe-[450px]'
19882
+ ? 'pe-[448px]'
19619
19883
  : ''}"
19620
19884
  >
19621
19885
  <EmbeddedSketchViewportShell
@@ -19626,14 +19890,59 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19626
19890
  tabChatLabel={$t('creator.livePreviews.chat')}
19627
19891
  >
19628
19892
  {#snippet children()}
19893
+ <div
19894
+ class="{embeddedSketchShell
19895
+ ? 'embedded-sketch-panel-wrap min-h-0 w-full min-w-0 flex-1 gap-2 p-2 max-md:flex max-md:min-h-0 max-md:flex-col md:max-lg:grid md:max-lg:min-h-0 md:max-lg:grid-rows-[600px_400px] md:max-lg:grid-cols-1 lg:flex lg:flex-row lg:items-stretch'
19896
+ : 'contents'}"
19897
+ data-testid="embedded-sketch-panel-wrap"
19898
+ >
19899
+ <section
19900
+ data-sketch-mobile-tab={embeddedSketchShell ? embeddedSketchMobileTab : undefined}
19901
+ class="{embeddedSketchShell
19902
+ ? 'embedded-sketch-canvas-panel border-border bg-background flex min-h-0 min-w-0 w-full flex-1 flex-col overflow-hidden rounded-panel max-md:data-[sketch-mobile-tab=chat]:hidden md:max-lg:row-start-1 md:max-lg:h-[600px] md:max-lg:max-h-[600px] md:max-lg:min-h-0 md:max-lg:w-full md:max-lg:flex-none max-md:flex-1 max-md:min-h-0 lg:min-h-0 lg:min-w-0'
19903
+ : 'contents'}"
19904
+ >
19905
+ {#if embeddedSketchShell}
19906
+ <CreatorBar
19907
+ class="shrink-0"
19908
+ title={sketchBarTitleLabel}
19909
+ status={sketchBarStatusLabel}
19910
+ showStatus={true}
19911
+ showTitleChevron={true}
19912
+ showLiveBadge={sketchBarShowLiveBadge}
19913
+ liveLabel={$t('creator.common.live')}
19914
+ showCustomize={sketchBarShowCustomize}
19915
+ customizeLabel={$t('creator.sketch.customize')}
19916
+ showPublish={sketchBarShowPublish}
19917
+ publishLabel={sketchBarPublishLabel}
19918
+ publishDisabled={!canvasPrimaryWidgetId || isPublishDisabledForPanel(canvasPrimaryWidgetId)}
19919
+ onBack={() => window.dispatchEvent(new CustomEvent('widgetic:host-request-back'))}
19920
+ onTitleClick={handleSketchBarTitleClick}
19921
+ onCustomize={handleSketchCustomize}
19922
+ onPublish={() => window.dispatchEvent(new CustomEvent('widgetic:host-request-publish'))}
19923
+ />
19924
+ {/if}
19925
+ <div
19926
+ class="{embeddedSketchShell
19927
+ ? 'embedded-sketch-canvas-wrap flex min-h-0 flex-1 flex-col px-2 pb-2'
19928
+ : 'contents'}"
19929
+ >
19629
19930
  <div
19630
19931
  class="embedded-sketch-canvas-stage flex-1 min-h-0 relative min-w-0 {embeddedSketchShell
19631
- ? 'max-lg:shrink-0 max-lg:basis-[58%] max-lg:min-h-0 max-md:absolute max-md:inset-0 max-md:z-0 max-md:basis-auto'
19932
+ ? 'rounded-card bg-muted overflow-hidden max-md:absolute max-md:inset-0 max-md:z-0'
19632
19933
  : ''} {embeddedSketchShell && embeddedSketchMobileTab !== 'canvas'
19633
19934
  ? 'max-md:pointer-events-none max-md:opacity-0 max-md:[visibility:hidden]'
19634
19935
  : ''}"
19635
19936
  aria-hidden={embeddedSketchShell && embeddedSketchMobileTab !== 'canvas' ? 'true' : undefined}
19636
19937
  >
19938
+ {#if sketchBoardStatusChip}
19939
+ <CanvasBoardStatusChip
19940
+ variant={sketchBoardStatusChip.variant}
19941
+ label={sketchBoardStatusChip.label}
19942
+ actionLabel={'actionLabel' in sketchBoardStatusChip ? sketchBoardStatusChip.actionLabel : ''}
19943
+ onAction={'actionLabel' in sketchBoardStatusChip ? () => void handleSketchRetryFailedGeneration() : undefined}
19944
+ />
19945
+ {/if}
19637
19946
  <!-- Embedded: Debug toggle lives in site AppHeader (avoids overlapping Props Panel). -->
19638
19947
  {#if canvasApiLoadError || canvasShapesMissingWarning}
19639
19948
  <div class="canvas-state-warning-ct absolute top-3 left-1/2 -translate-x-1/2 z-30 max-w-lg w-[calc(100%-2rem)] pointer-events-auto">
@@ -19666,11 +19975,11 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19666
19975
  bind:this={canvasRef}
19667
19976
  locale={locale}
19668
19977
  messages={canvasMessages}
19669
- showContainerFrame={!embedded}
19978
+ showContainerFrame={embeddedSketchShell || !embedded}
19670
19979
  widgetSelectionLayerTarget="floating-panels-overlay"
19671
19980
  bind:wireframeMode={canvasWireframeMode}
19672
19981
  advancedFeatures={canvasAdvancedFeatures}
19673
- showZoomPanel={debugMode}
19982
+ showZoomPanel={sketchCanvasShowZoom}
19674
19983
  onReady={handleCanvasReady}
19675
19984
  onAutoSave={handleCanvasAutoSave}
19676
19985
  onBeforeUnmount={(json) => {
@@ -19680,7 +19989,6 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19680
19989
  clearCanvasLoadFailsafe();
19681
19990
  canvasComponentReady = false;
19682
19991
  }}
19683
- onConvertToWidget={handleConvertToWidget}
19684
19992
  onRecognizeStroke={handleRecognizeStroke}
19685
19993
  onWidgetImageClick={handleWidgetImageClick}
19686
19994
  onCanvasDirty={() => {
@@ -19695,7 +20003,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19695
20003
  }}
19696
20004
  onSetPrimaryWidget={handleSetPrimaryWidget}
19697
20005
  showElementSelector={(multipleWidgetsAllowed || singleWidgetChromeReady) && !!canvasPrimaryWidgetId && !isDraftConvertId(canvasPrimaryWidgetId)}
19698
- showDrawingTools={showDrawingTools}
20006
+ showDrawingTools={sketchCanvasShowDrawingTools}
19699
20007
  elementSelectorActive={!!(canvasPrimaryWidgetId && selectorEnabledByWidgetId[canvasPrimaryWidgetId])}
19700
20008
  selectorGuide={{
19701
20009
  click: $t('creator.elementSelector.clickPartToReference'),
@@ -19728,9 +20036,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19728
20036
  }
19729
20037
  widgetDetails?.closeWidgetDetails();
19730
20038
  }}
19731
- panZoomPosition="TL"
20039
+ panZoomPosition={sketchCanvasPanZoomPosition}
19732
20040
  toolbarPosition={toolbarPosition}
19733
- showSaveButton={showSaveButton}
20041
+ showSaveButton={sketchCanvasShowSaveButton}
19734
20042
  autosaveDelayMs={import.meta.env.DEV ? 15000 : 5000}
19735
20043
  autosaveMaxWaitMs={CANVAS_AUTOSAVE_MAX_WAIT_MS}
19736
20044
  suspendAutosave={suspendCanvasAutosave}
@@ -19741,12 +20049,14 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
19741
20049
  <CanvasBoardPlaceholder class="wc-canvas-placeholder" {locale} messages={canvasMessages} />
19742
20050
  {/if}
19743
20051
  </div>
20052
+ </div>
20053
+ </section>
19744
20054
 
19745
20055
  <!-- FLOATING PANELS OVERLAY (pointer-events-none container, each panel is pointer-events-auto) -->
19746
20056
  <div
19747
- class="floating-panels-overlay z-2003 pointer-events-none {embeddedSketchShell
19748
- ? 'max-lg:relative max-lg:inset-auto max-lg:flex max-lg:flex-1 max-lg:min-h-0 max-lg:basis-[42%] max-lg:shrink-0 max-lg:w-full max-md:absolute max-md:inset-0 max-md:z-[1] max-md:basis-auto lg:absolute lg:inset-0'
19749
- : 'absolute inset-0'} {embeddedSketchShell && embeddedSketchMobileTab !== 'chat'
20057
+ class="floating-panels-overlay z-2003 {embeddedSketchShell
20058
+ ? 'md:max-lg:pointer-events-auto md:max-lg:relative md:max-lg:row-start-2 md:max-lg:flex md:max-lg:h-[400px] md:max-lg:max-h-[400px] md:max-lg:min-h-0 md:max-lg:w-full md:max-lg:min-w-0 md:max-lg:flex-none md:max-lg:flex-col max-md:absolute max-md:inset-x-2 max-md:bottom-0 max-md:top-0 max-md:z-[1] max-md:flex max-md:flex-1 max-md:min-h-0 lg:pointer-events-none lg:relative lg:flex lg:w-chat-panel lg:max-w-full lg:shrink-0 lg:flex-col'
20059
+ : 'pointer-events-none absolute inset-0'} {embeddedSketchShell && embeddedSketchMobileTab !== 'chat'
19750
20060
  ? 'max-md:pointer-events-none max-md:opacity-0 max-md:[visibility:hidden]'
19751
20061
  : ''}"
19752
20062
  aria-hidden={embeddedSketchShell && embeddedSketchMobileTab !== 'chat' ? 'true' : undefined}
@@ -20635,6 +20945,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20635
20945
  </svelte:fragment>
20636
20946
 
20637
20947
  <svelte:fragment slot="code-generation-status">
20948
+ {#if !(embedded && !canvasAdvancedFeatures)}
20638
20949
  {#if true}
20639
20950
  {@const statusText = isPanelFocused ? (generateCodeStatus ?? ps.generateCodeStatus) : ps.generateCodeStatus}
20640
20951
  {@const hourlyLimit = isHourlyLimitText(statusText) || isHourlyLimitText(ps.lastGenerationError)}
@@ -20676,13 +20987,14 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20676
20987
  {/if}
20677
20988
  </div>
20678
20989
  {/if}
20990
+ {/if}
20679
20991
  </svelte:fragment>
20680
20992
 
20681
20993
  <svelte:fragment slot="code-generation">
20682
20994
  {@const chatUserHeight = rev(panelDisplayRevision, getChatContainerHeightForPanel(panelWidgetId))}
20683
20995
  <!-- svelte-ignore a11y_no_static_element_interactions -->
20684
20996
  <div
20685
- class="generation-scroll-ct relative flex flex-col h-full min-h-0 overflow-y-auto border-t border-gray-200"
20997
+ class="generation-scroll-ct relative flex flex-col h-full min-h-0 overflow-y-auto {embedded && !canvasAdvancedFeatures ? '' : 'border-t border-gray-200'}"
20686
20998
  style="padding: 0;"
20687
20999
  use:nativeScrollbarPadding={0}
20688
21000
  use:pinScrollToBottom
@@ -20792,9 +21104,13 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20792
21104
  <!-- Svelte 5: `{@const}` must be the direct child of a block; this wrapper exists only for dockedChatPanel and composerModelOptions. -->
20793
21105
  {#if true}
20794
21106
  {@const dockedChatPanel = embedded && !canvasAdvancedFeatures}
20795
- {@const composerModelOptions = debugMode
20796
- ? availableModels.map((model) => ({ id: model.id, label: model.name }))
20797
- : []}
21107
+ {@const composerModelOptions = dockedChatPanel
21108
+ ? debugMode
21109
+ ? availableModels.map((model) => ({ id: model.id, label: model.name }))
21110
+ : [{ id: ASSISTANT_MODEL_ID, label: $t('creator.codegen.assistantModelLabel') }]
21111
+ : debugMode
21112
+ ? availableModels.map((model) => ({ id: model.id, label: model.name }))
21113
+ : []}
20798
21114
  <Chat class="code-generation-chat h-full w-full max-w-full rounded-none border-0"
20799
21115
  locale={locale}
20800
21116
  messages={chatMessages}
@@ -20808,9 +21124,14 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
20808
21124
  showLogs={debugMode}
20809
21125
  showHeader={false}
20810
21126
  showPanelHeader={dockedChatPanel}
20811
- showConsoleControl={dockedChatPanel && debugMode}
21127
+ headerTitle={panelWidget?.name || ''}
21128
+ showConsoleControl={dockedChatPanel}
20812
21129
  consoleOpen={!!panelConsoleOpenByWidgetId[panelWidgetId]}
20813
- onToggleConsole={dockedChatPanel && debugMode ? () => toggleDockedChatConsole(panelWidgetId, panelInstanceKey) : undefined}
21130
+ onToggleConsole={dockedChatPanel
21131
+ ? () => {
21132
+ if (debugMode) toggleDockedChatConsole(panelWidgetId, panelInstanceKey);
21133
+ }
21134
+ : undefined}
20814
21135
  showDescriptionHeader={false}
20815
21136
  composerModels={composerModelOptions}
20816
21137
  selectedComposerModelId={selectedModelId}
@@ -21312,6 +21633,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
21312
21633
  {/if}
21313
21634
 
21314
21635
  </div> <!-- end of floating-panels-overlay -->
21636
+ </div>
21315
21637
  {/snippet}
21316
21638
  </EmbeddedSketchViewportShell>
21317
21639
  </div> <!-- end of wc-canvas-area -->