@widgetic/chat 0.1.40 → 0.1.41

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.
@@ -14,6 +14,7 @@
14
14
  import ChatMessages from './ChatMessages.svelte';
15
15
  import ChatComposer, { type ComposerModelOption } from './ChatComposer.svelte';
16
16
  import { Chip } from '@widgetic/design-system/components/chat/index';
17
+ import { showToast } from '@widgetic/design-system/components/toast/index';
17
18
  import ActionBar from './ActionBar.svelte';
18
19
  import PanelChatHeader from './PanelChatHeader.svelte';
19
20
  import ComposerAttachmentsTray from './ComposerAttachmentsTray.svelte';
@@ -110,6 +111,8 @@
110
111
  * so the host can re-run codegen without duplicating the user bubble.
111
112
  */
112
113
  onRetryMessage?: (content: string) => Promise<void>;
114
+ /** Undo the last sketch-assistant canvas turn (one engine undo step). */
115
+ onSketchUndo?: () => void | Promise<void>;
113
116
  /**
114
117
  * What the "Upgrade" button of a failure about the plan or the credits does. Without it the button opens the
115
118
  * billing page of the Widgetic site; a host that is a guest on somebody else's page gives its own function.
@@ -287,7 +290,7 @@
287
290
  updateLastUserMessageAttachments: (attachments: Array<{ id?: string; url: string; file_type?: string; file_name?: string | null }>) => void;
288
291
  }
289
292
 
290
- let { context, config = {}, class: className = '', locale = null, messages: languageMessages = null, dir = undefined, style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onRateVersion, versionRatings: ratingsFromHost = {}, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onUpgradePlans, onUploadChatFile, showHeader = true, showPanelHeader = false, showConsoleControl = false, sendNudgeToken = 0, consoleOpen = false, onToggleConsole, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, onMessagesDrag, onMessagesDragEnd, onLoadOlderMessages, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], isGenerating = false, generationStream = '', generationThinking = '', generationPlan = null, onStopGeneration, members = [], currentUser = null, renderAgentAvatar, agentSound, tightBubbles = true, renderDesignControls, actionBarExtras, completeReplacement, replaceComplete = false, showSelector = false, isSelectorActive = false, selectedElements = [], onToggleSelector, onRemoveSelectedElement, onClearSelectedElements, composerExtras, storedLineLabel, composerModels = [], selectedComposerModelId = null, onSelectComposerModel }: Props = $props();
293
+ let { context, config = {}, class: className = '', locale = null, messages: languageMessages = null, dir = undefined, style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onRateVersion, versionRatings: ratingsFromHost = {}, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onSketchUndo, onUpgradePlans, onUploadChatFile, showHeader = true, showPanelHeader = false, showConsoleControl = false, sendNudgeToken = 0, consoleOpen = false, onToggleConsole, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, onMessagesDrag, onMessagesDragEnd, onLoadOlderMessages, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], isGenerating = false, generationStream = '', generationThinking = '', generationPlan = null, onStopGeneration, members = [], currentUser = null, renderAgentAvatar, agentSound, tightBubbles = true, renderDesignControls, actionBarExtras, completeReplacement, replaceComplete = false, showSelector = false, isSelectorActive = false, selectedElements = [], onToggleSelector, onRemoveSelectedElement, onClearSelectedElements, composerExtras, storedLineLabel, composerModels = [], selectedComposerModelId = null, onSelectComposerModel }: Props = $props();
291
294
 
292
295
  // The words of everything inside the chat, in the language the page chose. The page can change the language while the
293
296
  // chat is open: the settings are read again whenever they change (and setting the same language again does nothing).
@@ -556,7 +559,8 @@
556
559
  await initializeForContext(context.id);
557
560
  } catch (error) {
558
561
  console.error('[Chat] Failed to initialize:', error);
559
- showFailure('chat.error.initialize');
562
+ // A toast of the page (the host mounts the toaster), not the banner over the chat: the chat stays usable under it.
563
+ showToast('error', $t('chat.error.initialize'));
560
564
  } finally {
561
565
  isInitialized = true;
562
566
  }
@@ -1268,6 +1272,19 @@
1268
1272
  }
1269
1273
  }
1270
1274
 
1275
+ /** The sketch's "Undo" chip is used once: take it off the last assistant message that carries it. */
1276
+ function clearUndoSketchSuggestionChip() {
1277
+ const convId = currentConversationId;
1278
+ if (!convId) return;
1279
+ const msgs = getCurrentMessages(convId);
1280
+ for (let index = msgs.length - 1; index >= 0; index--) {
1281
+ const msg = msgs[index];
1282
+ if (msg.messageType !== 'assistant' || !msg.suggestions?.some((item) => item.undoSketch)) continue;
1283
+ chatStore.actions.updateMessageSuggestions(convId, msg.id, undefined);
1284
+ break;
1285
+ }
1286
+ }
1287
+
1271
1288
  function fillDraftFromSuggestion(label: string, intent?: ClarificationSuggestion['intent']) {
1272
1289
  const trimmed = label.trim();
1273
1290
  if (!trimmed) return;
@@ -1289,8 +1306,16 @@
1289
1306
  fillDraftFromSuggestion(suggestion);
1290
1307
  }
1291
1308
 
1292
- /** Clarification chips fill the composer like other suggestions; chipIntent is kept on the draft until send. */
1293
- function handleClarificationSuggestionSelected(suggestion: ClarificationSuggestion) {
1309
+ /**
1310
+ * Clarification chips fill the composer like other suggestions; chipIntent is kept on the draft until send.
1311
+ * The sketch's "Undo" chip is not a suggestion: it takes the last drawing back through the page (onSketchUndo), and goes.
1312
+ */
1313
+ async function handleClarificationSuggestionSelected(suggestion: ClarificationSuggestion) {
1314
+ if (suggestion.undoSketch && onSketchUndo) {
1315
+ await onSketchUndo();
1316
+ clearUndoSketchSuggestionChip();
1317
+ return;
1318
+ }
1294
1319
  if (!suggestion.label.trim()) return;
1295
1320
  if (isGenerating || localIsSending || isSendingOrLoading) return;
1296
1321
  fillDraftFromSuggestion(suggestion.label, suggestion.intent);
@@ -139,6 +139,8 @@ interface Props {
139
139
  * so the host can re-run codegen without duplicating the user bubble.
140
140
  */
141
141
  onRetryMessage?: (content: string) => Promise<void>;
142
+ /** Undo the last sketch-assistant canvas turn (one engine undo step). */
143
+ onSketchUndo?: () => void | Promise<void>;
142
144
  /**
143
145
  * What the "Upgrade" button of a failure about the plan or the credits does. Without it the button opens the
144
146
  * billing page of the Widgetic site; a host that is a guest on somebody else's page gives its own function.
@@ -863,18 +863,28 @@
863
863
  return !isGenerationSummary(reply);
864
864
  }
865
865
 
866
+ /**
867
+ * The parent reads the conversation once and sets `showEmptyState` from what it found. A message that arrives
868
+ * afterwards (a sketch turn, a first send that failed) hides the hero too: kept, it sits over the messages as soon
869
+ * as the list is taller than the panel (the block shrinks to nothing and its content spills over the turns below).
870
+ */
871
+ const emptyStateVisible = $derived(showEmptyState && messages.length === 0);
872
+
866
873
  /** Figma ready frame: follow-up cards sit above the composer, outside the scroll area. */
867
874
  const panelAnchoredFollowUp = $derived.by((): { labels: string[] } | null => {
868
- if (!panelLayout || showEmptyState) return null;
875
+ if (!panelLayout || emptyStateVisible) return null;
869
876
  for (let ti = chatTurns.length - 1; ti >= 0; ti--) {
870
877
  const turn = chatTurns[ti];
871
878
  for (let ri = turn.replies.length - 1; ri >= 0; ri--) {
872
879
  const reply = turn.replies[ri];
873
880
  const meta = reply.metadata as { panelFollowUp?: boolean } | undefined;
874
- if (!reply.suggestions?.length || meta?.panelFollowUp === false) continue;
881
+ // The sketch "Undo drawing" chip is drawn under its own reply (it has no label of its own to show here); this
882
+ // list is for the prompts a reply suggests.
883
+ const followUpSuggestions = (reply.suggestions ?? []).filter((suggestion) => !suggestion?.undoSketch);
884
+ if (!followUpSuggestions.length || meta?.panelFollowUp === false) continue;
875
885
  if (!shouldShowAssistantReply(reply)) continue;
876
886
  // A suggestion without a text label would give the keyed list a NaN key and stop the whole panel from rendering.
877
- const suggestionLabels = reply.suggestions
887
+ const suggestionLabels = followUpSuggestions
878
888
  .map((suggestion) => suggestion?.label)
879
889
  .filter((label): label is string => typeof label === 'string' && label.trim().length > 0);
880
890
  if (suggestionLabels.length === 0) continue;
@@ -1992,7 +2002,7 @@
1992
2002
  <!-- Empty state stays out of the document until the parent has finished reading
1993
2003
  messages and found none. A generation in flight hides it too: the user
1994
2004
  bubble lands a tick after send, so the list is briefly empty again. -->
1995
- {#if showEmptyState && !isLoading && !isGenerating}
2005
+ {#if emptyStateVisible && !isLoading && !isGenerating}
1996
2006
  <!-- Figma: Chat / Empty. The hero (a circle with the sparkles icon, the title and a line under it) sits in the
1997
2007
  middle of the messages, and the suggestions are pinned under it, above the composer. The block takes the
1998
2008
  free height with flex-1 (not min-h-full): the sticky scroll-to-bottom row below it needs its own room, and a
@@ -2231,6 +2241,21 @@
2231
2241
  </div>
2232
2242
  {/if}
2233
2243
 
2244
+ {#if reply.suggestions?.some((suggestion) => suggestion.undoSketch) && panelLayout}
2245
+ <div class="mt-2 flex flex-wrap gap-2">
2246
+ {#each reply.suggestions.filter((suggestion) => suggestion.undoSketch) as suggestion (suggestion.label)}
2247
+ <button
2248
+ type="button"
2249
+ data-testid={suggestion.undoSketch ? 'sketch-undo-chip' : undefined}
2250
+ class="border-border bg-muted text-foreground rounded-full border px-3 py-1 text-sm"
2251
+ onclick={() => onClarificationSuggestionSelected?.(suggestion)}
2252
+ >
2253
+ {suggestion.label || $t('chat.sketch.undoLabel')}
2254
+ </button>
2255
+ {/each}
2256
+ </div>
2257
+ {/if}
2258
+
2234
2259
  {#if reply.suggestions && reply.suggestions.length > 0 && !panelLayout}
2235
2260
  <QuestionCard
2236
2261
  class="mt-1.5 w-full max-w-full"
@@ -1,5 +1,6 @@
1
1
  export { CHAT_MESSAGES, type ChatMessageKey } from './messages.js';
2
2
  export { PUBLISH_NUDGE_BY_LOCALE, PUBLISH_NUDGE_ENGLISH } from './publishNudgeLocales.js';
3
+ export { CHAT_SKETCH_LOCALE_MESSAGES } from './sketchLocales.js';
3
4
  export { checkChatMessages, provideChatLanguage, useChatLanguage } from './language.js';
4
5
  export { actionFailureKey, contextTypeLabel, fileSizeText, versionLabelText } from './labels.js';
5
6
  export { suggestionKeysFor, suggestionTitleKeyFor, panelEmptySuggestionKeys, panelEmptySuggestionTitleKey, } from './suggestions.js';
@@ -1,5 +1,6 @@
1
1
  export { CHAT_MESSAGES } from './messages.js';
2
2
  export { PUBLISH_NUDGE_BY_LOCALE, PUBLISH_NUDGE_ENGLISH } from './publishNudgeLocales.js';
3
+ export { CHAT_SKETCH_LOCALE_MESSAGES } from './sketchLocales.js';
3
4
  export { checkChatMessages, provideChatLanguage, useChatLanguage } from './language.js';
4
5
  export { actionFailureKey, contextTypeLabel, fileSizeText, versionLabelText } from './labels.js';
5
6
  export { suggestionKeysFor, suggestionTitleKeyFor, panelEmptySuggestionKeys, panelEmptySuggestionTitleKey, } from './suggestions.js';
@@ -243,6 +243,21 @@ export declare const CHAT_MESSAGES: {
243
243
  readonly 'chat.error.actionFailed': "The action failed. Please try again.";
244
244
  readonly 'chat.error.statusUpdateFailed': "Failed to update conversation status";
245
245
  readonly 'chat.error.restoreFailed': "Failed to restore checkpoint. Please try again.";
246
+ readonly 'chat.sketch.drewVideoPlayer': "Drew a video player: 16:9 thumbnail with a play button and a navigation bar below it.";
247
+ readonly 'chat.sketch.movedNavigation': "Moved the navigation bar below the video thumbnail.";
248
+ readonly 'chat.sketch.deletedAll': "Removed every sketch from the canvas.";
249
+ readonly 'chat.sketch.namedComponents': "Labelled each component and drew an arrow to it.";
250
+ readonly 'chat.sketch.addedShapes': "Added wireframe shapes on the canvas.";
251
+ readonly 'chat.sketch.followUp': "Ask me to move, label, or delete anything on the board.";
252
+ readonly 'chat.sketch.genericDone': "Updated the sketch on the canvas.";
253
+ readonly 'chat.sketch.failed': "Could not update the sketch: {detail}";
254
+ readonly 'chat.sketch.failedUnknown': "Could not update the sketch.";
255
+ readonly 'chat.sketch.stepCap': "Sketch assistant stopped after too many steps.";
256
+ readonly 'chat.sketch.noCredits': "You are out of credits, so I cannot draw right now. Add credits and ask me again.";
257
+ readonly 'chat.sketch.busy': "A sketch is already being drawn, or you have sent too many requests. Try again in a moment.";
258
+ readonly 'chat.sketch.unavailable': "The sketch assistant is not available right now. Please try again in a moment.";
259
+ readonly 'chat.sketch.stopped': "Stopped drawing.";
260
+ readonly 'chat.sketch.undoLabel': "Undo drawing";
246
261
  };
247
262
  /** The name of one message. */
248
263
  export type ChatMessageKey = keyof typeof CHAT_MESSAGES;
@@ -253,5 +253,21 @@ export const CHAT_MESSAGES = {
253
253
  'chat.error.recordingActionFailed': 'Recording action failed. Please try again.',
254
254
  'chat.error.actionFailed': 'The action failed. Please try again.',
255
255
  'chat.error.statusUpdateFailed': 'Failed to update conversation status',
256
- 'chat.error.restoreFailed': 'Failed to restore checkpoint. Please try again.'
256
+ 'chat.error.restoreFailed': 'Failed to restore checkpoint. Please try again.',
257
+ // ===== Sketch assistant (canvas drawing turns) =====
258
+ 'chat.sketch.drewVideoPlayer': 'Drew a video player: 16:9 thumbnail with a play button and a navigation bar below it.',
259
+ 'chat.sketch.movedNavigation': 'Moved the navigation bar below the video thumbnail.',
260
+ 'chat.sketch.deletedAll': 'Removed every sketch from the canvas.',
261
+ 'chat.sketch.namedComponents': 'Labelled each component and drew an arrow to it.',
262
+ 'chat.sketch.addedShapes': 'Added wireframe shapes on the canvas.',
263
+ 'chat.sketch.followUp': 'Ask me to move, label, or delete anything on the board.',
264
+ 'chat.sketch.genericDone': 'Updated the sketch on the canvas.',
265
+ 'chat.sketch.failed': 'Could not update the sketch: {detail}',
266
+ 'chat.sketch.failedUnknown': 'Could not update the sketch.',
267
+ 'chat.sketch.stepCap': 'Sketch assistant stopped after too many steps.',
268
+ 'chat.sketch.noCredits': 'You are out of credits, so I cannot draw right now. Add credits and ask me again.',
269
+ 'chat.sketch.busy': 'A sketch is already being drawn, or you have sent too many requests. Try again in a moment.',
270
+ 'chat.sketch.unavailable': 'The sketch assistant is not available right now. Please try again in a moment.',
271
+ 'chat.sketch.stopped': 'Stopped drawing.',
272
+ 'chat.sketch.undoLabel': 'Undo drawing'
257
273
  };
@@ -0,0 +1,2 @@
1
+ /** Partner-ready overrides for sketch assistant messages (matches ui-sdk locale tags). */
2
+ export declare const CHAT_SKETCH_LOCALE_MESSAGES: Record<string, Record<string, string>>;
@@ -0,0 +1,83 @@
1
+ /** Partner-ready overrides for sketch assistant messages (matches ui-sdk locale tags). */
2
+ export const CHAT_SKETCH_LOCALE_MESSAGES = {
3
+ de: {
4
+ 'chat.sketch.drewVideoPlayer': 'Video-Player gezeichnet: 16:9-Vorschaubild mit Play-Button und Navigationsleiste darunter.',
5
+ 'chat.sketch.movedNavigation': 'Navigationsleiste unter das Vorschaubild verschoben.',
6
+ 'chat.sketch.deletedAll': 'Alle Skizzen von der Leinwand entfernt.',
7
+ 'chat.sketch.namedComponents': 'Jede Komponente beschriftet und mit einem Pfeil versehen.',
8
+ 'chat.sketch.followUp': 'Bitte mich, etwas zu verschieben, zu beschriften oder zu löschen.',
9
+ 'chat.sketch.failed': 'Skizze konnte nicht aktualisiert werden: {detail}',
10
+ 'chat.sketch.failedUnknown': 'Skizze konnte nicht aktualisiert werden.',
11
+ 'chat.sketch.undoLabel': 'Zeichnung rückgängig'
12
+ },
13
+ fr: {
14
+ 'chat.sketch.drewVideoPlayer': 'Élément lecteur vidéo : vignette 16:9 avec bouton lecture et barre de navigation en dessous.',
15
+ 'chat.sketch.movedNavigation': 'Barre de navigation déplacée sous la vignette.',
16
+ 'chat.sketch.deletedAll': 'Toutes les esquisses ont été supprimées du canevas.',
17
+ 'chat.sketch.namedComponents': 'Chaque composant est étiqueté avec une flèche.',
18
+ 'chat.sketch.followUp': 'Demandez-moi de déplacer, étiqueter ou supprimer un élément.',
19
+ 'chat.sketch.failed': "Impossible de mettre à jour l'esquisse : {detail}",
20
+ 'chat.sketch.failedUnknown': "Impossible de mettre à jour l'esquisse.",
21
+ 'chat.sketch.undoLabel': 'Annuler le dessin'
22
+ },
23
+ es: {
24
+ 'chat.sketch.drewVideoPlayer': 'Reproductor dibujado: miniatura 16:9 con botón de reproducción y barra de navegación debajo.',
25
+ 'chat.sketch.movedNavigation': 'Barra de navegación movida debajo de la miniatura.',
26
+ 'chat.sketch.deletedAll': 'Se eliminaron todos los bocetos del lienzo.',
27
+ 'chat.sketch.namedComponents': 'Cada componente tiene una etiqueta y una flecha.',
28
+ 'chat.sketch.followUp': 'Pídeme mover, etiquetar o borrar algo del lienzo.',
29
+ 'chat.sketch.failed': 'No se pudo actualizar el boceto: {detail}',
30
+ 'chat.sketch.failedUnknown': 'No se pudo actualizar el boceto.',
31
+ 'chat.sketch.undoLabel': 'Deshacer dibujo'
32
+ },
33
+ it: {
34
+ 'chat.sketch.drewVideoPlayer': 'Video player disegnato: anteprima 16:9 con pulsante play e barra di navigazione sotto.',
35
+ 'chat.sketch.movedNavigation': 'Barra di navigazione spostata sotto l’anteprima.',
36
+ 'chat.sketch.deletedAll': 'Rimossi tutti gli schizzi dalla tela.',
37
+ 'chat.sketch.namedComponents': 'Ogni componente ha un’etichetta e una freccia.',
38
+ 'chat.sketch.followUp': 'Chiedimi di spostare, etichettare o cancellare qualcosa.',
39
+ 'chat.sketch.failed': 'Impossibile aggiornare lo schizzo: {detail}',
40
+ 'chat.sketch.failedUnknown': 'Impossibile aggiornare lo schizzo.',
41
+ 'chat.sketch.undoLabel': 'Annulla disegno'
42
+ },
43
+ pt: {
44
+ 'chat.sketch.drewVideoPlayer': 'Player de vídeo desenhado: miniatura 16:9 com botão play e barra de navegação abaixo.',
45
+ 'chat.sketch.movedNavigation': 'Barra de navegação movida para abaixo da miniatura.',
46
+ 'chat.sketch.deletedAll': 'Todos os rascunhos foram removidos da tela.',
47
+ 'chat.sketch.namedComponents': 'Cada componente foi etiquetado com uma seta.',
48
+ 'chat.sketch.followUp': 'Peça para mover, etiquetar ou apagar algo no quadro.',
49
+ 'chat.sketch.failed': 'Não foi possível atualizar o rascunho: {detail}',
50
+ 'chat.sketch.failedUnknown': 'Não foi possível atualizar o rascunho.',
51
+ 'chat.sketch.undoLabel': 'Desfazer desenho'
52
+ },
53
+ pl: {
54
+ 'chat.sketch.drewVideoPlayer': 'Narysowano odtwarzacz wideo: miniatura 16:9 z przyciskiem play i paskiem nawigacji poniżej.',
55
+ 'chat.sketch.movedNavigation': 'Pasek nawigacji przeniesiony pod miniaturę.',
56
+ 'chat.sketch.deletedAll': 'Usunięto wszystkie szkice z kanwy.',
57
+ 'chat.sketch.namedComponents': 'Każdy element ma etykietę i strzałkę.',
58
+ 'chat.sketch.followUp': 'Poproś o przesunięcie, opisanie lub usunięcie czegoś.',
59
+ 'chat.sketch.failed': 'Nie udało się zaktualizować szkicu: {detail}',
60
+ 'chat.sketch.failedUnknown': 'Nie udało się zaktualizować szkicu.',
61
+ 'chat.sketch.undoLabel': 'Cofnij rysunek'
62
+ },
63
+ nl: {
64
+ 'chat.sketch.drewVideoPlayer': 'Videospeler getekend: 16:9-miniatuur met afspeelknop en navigatiebalk eronder.',
65
+ 'chat.sketch.movedNavigation': 'Navigatiebalk onder de miniatuur geplaatst.',
66
+ 'chat.sketch.deletedAll': 'Alle schetsen van het canvas verwijderd.',
67
+ 'chat.sketch.namedComponents': 'Elk onderdeel heeft een label en pijl.',
68
+ 'chat.sketch.followUp': 'Vraag me om iets te verplaatsen, te labelen of te verwijderen.',
69
+ 'chat.sketch.failed': 'Kon de schets niet bijwerken: {detail}',
70
+ 'chat.sketch.failedUnknown': 'Kon de schets niet bijwerken.',
71
+ 'chat.sketch.undoLabel': 'Tekening ongedaan maken'
72
+ },
73
+ ja: {
74
+ 'chat.sketch.drewVideoPlayer': '動画プレーヤーを描画しました(16:9サムネイル、再生ボタン、下にナビ)。',
75
+ 'chat.sketch.movedNavigation': 'ナビゲーションバーをサムネイルの外に移動しました。',
76
+ 'chat.sketch.deletedAll': 'キャンバス上のスケッチをすべて削除しました。',
77
+ 'chat.sketch.namedComponents': '各コンポーネントにラベルと矢印を追加しました。',
78
+ 'chat.sketch.followUp': '移動・ラベル付け・削除を依頼できます。',
79
+ 'chat.sketch.failed': 'スケッチを更新できませんでした: {detail}',
80
+ 'chat.sketch.failedUnknown': 'スケッチを更新できませんでした。',
81
+ 'chat.sketch.undoLabel': '描画を元に戻す'
82
+ }
83
+ };
@@ -1,2 +1,7 @@
1
1
  export { WidgeticChatService, createChatService } from './chatService.js';
2
2
  export type { ChatService, ChatInstance, ChatFactory } from '../types/index.js';
3
+ export { startSketchAssistantRequest, sketchAssistantStepRequest, SketchAssistantRequestError } from './sketchAssistantClient.js';
4
+ export type { SketchToolCall, SketchAssistantStartResponse, SketchSceneSummary } from './sketchAssistantClient.js';
5
+ export { runSketchAssistantLoop, describeSketchRequestFailure } from './sketchAssistantOrchestrator.js';
6
+ export type { CanvasSketchExecutor, SketchAssistantLoopResult } from './sketchAssistantOrchestrator.js';
7
+ export { buildSketchAssistantReply } from './sketchAssistantReply.js';
@@ -1,2 +1,5 @@
1
1
  // Chat Service
2
2
  export { WidgeticChatService, createChatService } from './chatService.js';
3
+ export { startSketchAssistantRequest, sketchAssistantStepRequest, SketchAssistantRequestError } from './sketchAssistantClient.js';
4
+ export { runSketchAssistantLoop, describeSketchRequestFailure } from './sketchAssistantOrchestrator.js';
5
+ export { buildSketchAssistantReply } from './sketchAssistantReply.js';
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Typed client for POST /agent/sketch (base URL already includes `/v1`) until the generated SDK exposes it.
3
+ */
4
+ export interface SketchToolCall {
5
+ id: string;
6
+ name: string;
7
+ arguments: Record<string, unknown>;
8
+ }
9
+ export interface SketchAssistantStartResponse {
10
+ sessionId: string;
11
+ step: number;
12
+ status: 'tool_calls' | 'completed' | 'failed' | 'disabled';
13
+ toolCalls?: SketchToolCall[];
14
+ message?: string;
15
+ error?: string;
16
+ }
17
+ export interface SketchSceneSummary {
18
+ bounds?: {
19
+ width: number;
20
+ height: number;
21
+ };
22
+ /** How many top-level elements the canvas has when `elements` lists only some of them. */
23
+ totalCount?: number;
24
+ elements?: Array<{
25
+ id: string;
26
+ kind: string;
27
+ label: string;
28
+ bbox?: {
29
+ x: number;
30
+ y: number;
31
+ width: number;
32
+ height: number;
33
+ };
34
+ }>;
35
+ }
36
+ /** The status of a request that got no answer at all (offline, the gateway down), which is no HTTP status. */
37
+ export declare const SKETCH_ASSISTANT_NO_ANSWER_STATUS = 0;
38
+ /**
39
+ * What the gateway answered when it did not take a request: the HTTP status, the code of its error envelope
40
+ * (for example `BILLING_INSUFFICIENT_CREDITS`) and its own sentence. A request that got no answer has the status
41
+ * `SKETCH_ASSISTANT_NO_ANSWER_STATUS`.
42
+ */
43
+ export declare class SketchAssistantRequestError extends Error {
44
+ readonly status: number;
45
+ readonly code: string | null;
46
+ constructor(message: string, status: number, code?: string | null);
47
+ }
48
+ export declare function startSketchAssistantRequest(input: {
49
+ apiBaseUrl: string;
50
+ authToken: string | null;
51
+ prompt: string;
52
+ sceneSummary?: SketchSceneSummary;
53
+ conversationId?: string | null;
54
+ canvasId?: string | null;
55
+ signal?: AbortSignal;
56
+ }): Promise<SketchAssistantStartResponse>;
57
+ export declare function sketchAssistantStepRequest(input: {
58
+ apiBaseUrl: string;
59
+ authToken: string | null;
60
+ sessionId: string;
61
+ step: number;
62
+ toolResults?: Array<{
63
+ toolCallId: string;
64
+ result: Record<string, unknown>;
65
+ }>;
66
+ sceneSummary?: SketchSceneSummary;
67
+ signal?: AbortSignal;
68
+ }): Promise<SketchAssistantStartResponse>;
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Typed client for POST /agent/sketch (base URL already includes `/v1`) until the generated SDK exposes it.
3
+ */
4
+ /** The status of a request that got no answer at all (offline, the gateway down), which is no HTTP status. */
5
+ export const SKETCH_ASSISTANT_NO_ANSWER_STATUS = 0;
6
+ /**
7
+ * What the gateway answered when it did not take a request: the HTTP status, the code of its error envelope
8
+ * (for example `BILLING_INSUFFICIENT_CREDITS`) and its own sentence. A request that got no answer has the status
9
+ * `SKETCH_ASSISTANT_NO_ANSWER_STATUS`.
10
+ */
11
+ export class SketchAssistantRequestError extends Error {
12
+ status;
13
+ code;
14
+ constructor(message, status, code = null) {
15
+ super(message);
16
+ this.name = 'SketchAssistantRequestError';
17
+ this.status = status;
18
+ this.code = code;
19
+ }
20
+ }
21
+ /** The sentence and the code of a refusal. The gateway writes `{ message, error: { code, message } }`; some doors write `{ error, code }`. */
22
+ function readRefusal(payload) {
23
+ if (!payload || typeof payload !== 'object')
24
+ return { message: null, code: null };
25
+ const body = payload;
26
+ const nested = body.error && typeof body.error === 'object' ? body.error : null;
27
+ const message = [body.message, nested?.message, typeof body.error === 'string' ? body.error : null].find((candidate) => typeof candidate === 'string' && candidate.trim().length > 0);
28
+ const code = [nested?.code, body.code].find((candidate) => typeof candidate === 'string' && candidate.length > 0);
29
+ return { message: message ?? null, code: code ?? null };
30
+ }
31
+ async function postJson(baseUrl, path, body, token, signal) {
32
+ let response;
33
+ try {
34
+ response = await fetch(`${baseUrl.replace(/\/$/, '')}${path}`, {
35
+ method: 'POST',
36
+ headers: {
37
+ 'Content-Type': 'application/json',
38
+ ...(token ? { Authorization: `Bearer ${token}` } : {})
39
+ },
40
+ body: JSON.stringify(body),
41
+ signal
42
+ });
43
+ }
44
+ catch (error) {
45
+ // A stop asked for stays what it is; anything else is a request that never got an answer.
46
+ if (signal?.aborted)
47
+ throw error;
48
+ throw new SketchAssistantRequestError(error instanceof Error ? error.message : 'no answer', SKETCH_ASSISTANT_NO_ANSWER_STATUS, 'NO_ANSWER');
49
+ }
50
+ // A proxy in front of the gateway can answer with a page that is not JSON; the status is still the answer.
51
+ const payload = (await response.json().catch(() => null));
52
+ if (!response.ok) {
53
+ const refusal = readRefusal(payload);
54
+ throw new SketchAssistantRequestError(refusal.message ?? `Sketch assistant HTTP ${response.status}`, response.status, refusal.code);
55
+ }
56
+ return (payload?.data ?? payload);
57
+ }
58
+ export async function startSketchAssistantRequest(input) {
59
+ return postJson(input.apiBaseUrl, '/agent/sketch', {
60
+ prompt: input.prompt,
61
+ sceneSummary: input.sceneSummary,
62
+ conversationId: input.conversationId,
63
+ canvasId: input.canvasId
64
+ }, input.authToken, input.signal);
65
+ }
66
+ export async function sketchAssistantStepRequest(input) {
67
+ return postJson(input.apiBaseUrl, '/agent/sketch/step', {
68
+ sessionId: input.sessionId,
69
+ step: input.step,
70
+ toolResults: input.toolResults,
71
+ sceneSummary: input.sceneSummary
72
+ }, input.authToken, input.signal);
73
+ }
@@ -0,0 +1,45 @@
1
+ import { type SketchSceneSummary } from './sketchAssistantClient.js';
2
+ import { type SketchToolTrace } from './sketchAssistantReply.js';
3
+ import type { Translate } from '@widgetic/design-system/i18n';
4
+ import type { ChatMessageKey } from '../i18n/messages.js';
5
+ export interface CanvasSketchExecutor {
6
+ getSceneSummary(): SketchSceneSummary;
7
+ executeTool(name: string, args: Record<string, unknown>): Record<string, unknown>;
8
+ undoLastDrawing?(): void;
9
+ beginToolBatch?(): void;
10
+ endToolBatch?(): void;
11
+ }
12
+ export interface SketchAssistantLoopResult {
13
+ ok: boolean;
14
+ message: string;
15
+ steps: number;
16
+ tools: SketchToolTrace[];
17
+ /** Whether a tool changed the canvas, so a run that only talked leaves nothing to undo. */
18
+ changedCanvas: boolean;
19
+ }
20
+ /**
21
+ * The words for a request the gateway did not take, in the page's language where the catalog has them.
22
+ * A refusal the person can act on gets its own sentence (no credits left, a run already going); a gateway that cannot
23
+ * be reached is one sentence; anything else shows the gateway's own words.
24
+ */
25
+ export declare function describeSketchRequestFailure(error: unknown, translate?: Translate<ChatMessageKey>): string;
26
+ /**
27
+ * Runs one request of the author on the canvas: the gateway's model asks for tools, the canvas runs them here, and
28
+ * the results go back until the model has nothing more to ask.
29
+ *
30
+ * A tool that fails (a shape out of the canvas, an id that is gone) is not the end of the run: its error goes back to
31
+ * the model like any other result, so it can correct itself. The run ends when the model answers, when the gateway
32
+ * refuses, or when it has taken too many steps. It never throws: what went wrong comes back as `ok: false` and a message.
33
+ */
34
+ export declare function runSketchAssistantLoop(input: {
35
+ apiBaseUrl: string;
36
+ authToken: string | null;
37
+ prompt: string;
38
+ executor: CanvasSketchExecutor;
39
+ conversationId?: string | null;
40
+ canvasId?: string | null;
41
+ maxSteps?: number;
42
+ translate?: Translate<ChatMessageKey>;
43
+ /** Stops the run between requests, and the request that is on its way. */
44
+ signal?: AbortSignal;
45
+ }): Promise<SketchAssistantLoopResult>;
@@ -0,0 +1,128 @@
1
+ import { SKETCH_ASSISTANT_NO_ANSWER_STATUS, SketchAssistantRequestError, sketchAssistantStepRequest, startSketchAssistantRequest } from './sketchAssistantClient.js';
2
+ import { buildSketchAssistantReply } from './sketchAssistantReply.js';
3
+ import { translateEnglish } from '../i18n/language.js';
4
+ /**
5
+ * How many times a run answers the gateway with tool results. The gateway stops a run after the same number of steps
6
+ * (its last answer is words only), so a run that is still asking for tools after this many has not understood the
7
+ * gateway and is stopped here.
8
+ */
9
+ const SKETCH_ASSISTANT_MAX_STEPS = 8;
10
+ /** The only tool whose job is to read the canvas; every other tool changes it. */
11
+ const READ_ONLY_TOOL_NAME = 'get_canvas';
12
+ /**
13
+ * The words for a request the gateway did not take, in the page's language where the catalog has them.
14
+ * A refusal the person can act on gets its own sentence (no credits left, a run already going); a gateway that cannot
15
+ * be reached is one sentence; anything else shows the gateway's own words.
16
+ */
17
+ export function describeSketchRequestFailure(error, translate = translateEnglish) {
18
+ if (error instanceof SketchAssistantRequestError) {
19
+ if (error.status === 402 || error.code === 'BILLING_INSUFFICIENT_CREDITS')
20
+ return translate('chat.sketch.noCredits');
21
+ if (error.status === 429)
22
+ return translate('chat.sketch.busy');
23
+ if (error.status === SKETCH_ASSISTANT_NO_ANSWER_STATUS || error.status === 408 || error.status >= 500) {
24
+ return translate('chat.sketch.unavailable');
25
+ }
26
+ return translate('chat.sketch.failed', { detail: error.message });
27
+ }
28
+ if (error instanceof Error && error.name === 'AbortError')
29
+ return translate('chat.sketch.stopped');
30
+ return translate('chat.sketch.failedUnknown');
31
+ }
32
+ /** A tool result without the copy of the canvas the executors attach: the gateway is sent the canvas once, in `sceneSummary`. */
33
+ function withoutSceneCopy(result) {
34
+ const { summary: _sceneCopy, ...rest } = result;
35
+ return rest;
36
+ }
37
+ /** What a run says when it is over: the model's own words, else what the tools did, else a plain sentence. */
38
+ function closingMessage(response, tools, translate) {
39
+ const modelWords = response.message?.trim();
40
+ if (modelWords)
41
+ return modelWords;
42
+ return tools.length > 0 ? buildSketchAssistantReply(tools, translate) : translate('chat.sketch.genericDone');
43
+ }
44
+ /**
45
+ * Runs one request of the author on the canvas: the gateway's model asks for tools, the canvas runs them here, and
46
+ * the results go back until the model has nothing more to ask.
47
+ *
48
+ * A tool that fails (a shape out of the canvas, an id that is gone) is not the end of the run: its error goes back to
49
+ * the model like any other result, so it can correct itself. The run ends when the model answers, when the gateway
50
+ * refuses, or when it has taken too many steps. It never throws: what went wrong comes back as `ok: false` and a message.
51
+ */
52
+ export async function runSketchAssistantLoop(input) {
53
+ const translate = input.translate ?? translateEnglish;
54
+ const maxSteps = input.maxSteps ?? SKETCH_ASSISTANT_MAX_STEPS;
55
+ const toolTrace = [];
56
+ let steps = 0;
57
+ let batchOpen = false;
58
+ const outcome = (ok, message) => ({
59
+ ok,
60
+ message,
61
+ steps,
62
+ tools: toolTrace,
63
+ changedCanvas: toolTrace.some((tool) => tool.ok && tool.name !== READ_ONLY_TOOL_NAME)
64
+ });
65
+ try {
66
+ let response = await startSketchAssistantRequest({
67
+ apiBaseUrl: input.apiBaseUrl,
68
+ authToken: input.authToken,
69
+ prompt: input.prompt,
70
+ sceneSummary: input.executor.getSceneSummary(),
71
+ conversationId: input.conversationId,
72
+ canvasId: input.canvasId,
73
+ signal: input.signal
74
+ });
75
+ input.executor.beginToolBatch?.();
76
+ batchOpen = true;
77
+ for (;;) {
78
+ if (response.status === 'failed' || response.status === 'disabled') {
79
+ return outcome(false, response.error ?? response.message ?? translate('chat.sketch.failedUnknown'));
80
+ }
81
+ if (response.status === 'completed') {
82
+ return outcome(true, closingMessage(response, toolTrace, translate));
83
+ }
84
+ if (steps >= maxSteps)
85
+ return outcome(false, translate('chat.sketch.stepCap'));
86
+ const toolResults = [];
87
+ for (const call of response.toolCalls ?? []) {
88
+ let result;
89
+ try {
90
+ result = input.executor.executeTool(call.name, call.arguments);
91
+ }
92
+ catch (error) {
93
+ // A canvas that throws is told to the model like a tool that refused, not left to end the run.
94
+ console.warn('[Sketch] A canvas tool threw', call.name, error);
95
+ result = { ok: false, error: error instanceof Error ? error.message : String(error), code: 'internal' };
96
+ }
97
+ toolTrace.push({
98
+ name: call.name,
99
+ ok: Boolean(result.ok),
100
+ message: typeof result.message === 'string' ? result.message : undefined,
101
+ error: typeof result.error === 'string' ? result.error : undefined
102
+ });
103
+ toolResults.push({ toolCallId: call.id, result: withoutSceneCopy(result) });
104
+ }
105
+ steps += 1;
106
+ response = await sketchAssistantStepRequest({
107
+ apiBaseUrl: input.apiBaseUrl,
108
+ authToken: input.authToken,
109
+ sessionId: response.sessionId,
110
+ step: response.step,
111
+ toolResults,
112
+ sceneSummary: input.executor.getSceneSummary(),
113
+ signal: input.signal
114
+ });
115
+ }
116
+ }
117
+ catch (error) {
118
+ // A refusal of the gateway is an answer the person reads; anything else is a fault worth a line in the console.
119
+ if (!(error instanceof SketchAssistantRequestError) && !input.signal?.aborted) {
120
+ console.warn('[Sketch] The sketch assistant stopped', error);
121
+ }
122
+ return outcome(false, describeSketchRequestFailure(error, translate));
123
+ }
124
+ finally {
125
+ if (batchOpen)
126
+ input.executor.endToolBatch?.();
127
+ }
128
+ }
@@ -0,0 +1,12 @@
1
+ import type { Translate } from '@widgetic/design-system/i18n';
2
+ import type { ChatMessageKey } from '../i18n/messages.js';
3
+ export interface SketchToolTrace {
4
+ name: string;
5
+ ok: boolean;
6
+ message?: string;
7
+ error?: string;
8
+ }
9
+ /**
10
+ * User-facing assistant copy from executed tool results (not gateway filler).
11
+ */
12
+ export declare function buildSketchAssistantReply(tools: SketchToolTrace[], translate?: Translate<ChatMessageKey>): string;
@@ -0,0 +1,28 @@
1
+ import { translateEnglish } from '../i18n/language.js';
2
+ /**
3
+ * User-facing assistant copy from executed tool results (not gateway filler).
4
+ */
5
+ export function buildSketchAssistantReply(tools, translate = translateEnglish) {
6
+ const okTools = tools.filter((tool) => tool.ok);
7
+ if (okTools.length === 0) {
8
+ const firstError = tools.find((tool) => !tool.ok)?.error ?? tools[0]?.message;
9
+ return firstError ? translate('chat.sketch.failed', { detail: firstError }) : translate('chat.sketch.failedUnknown');
10
+ }
11
+ const names = new Set(okTools.map((tool) => tool.name));
12
+ if (names.has('draw_ui_component')) {
13
+ return `${translate('chat.sketch.drewVideoPlayer')} ${translate('chat.sketch.followUp')}`;
14
+ }
15
+ if (names.has('move_elements')) {
16
+ return `${translate('chat.sketch.movedNavigation')} ${translate('chat.sketch.followUp')}`;
17
+ }
18
+ if (names.has('delete_elements')) {
19
+ return translate('chat.sketch.deletedAll');
20
+ }
21
+ if (names.has('name_components_with_arrows')) {
22
+ return `${translate('chat.sketch.namedComponents')} ${translate('chat.sketch.followUp')}`;
23
+ }
24
+ if (names.has('add_shape')) {
25
+ return `${translate('chat.sketch.addedShapes')} ${translate('chat.sketch.followUp')}`;
26
+ }
27
+ return okTools.map((tool) => tool.message).filter(Boolean).join(' ') || translate('chat.sketch.genericDone');
28
+ }
@@ -25,6 +25,7 @@ export declare const chatStore: {
25
25
  updateMessageId: (conversationId: string, oldId: string, newId: string) => void;
26
26
  updateMessageContent: (conversationId: string, messageId: string, messageContent: string) => void;
27
27
  updateMessageAttachments: (conversationId: string, messageId: string, attachments: any[]) => void;
28
+ updateMessageSuggestions: (conversationId: string, messageId: string, suggestions: ChatMessage["suggestions"] | undefined) => void;
28
29
  };
29
30
  };
30
31
  /**
@@ -290,6 +290,27 @@ function createChatStore() {
290
290
  }
291
291
  };
292
292
  });
293
+ },
294
+ updateMessageSuggestions: (conversationId, messageId, suggestions) => {
295
+ update(state => {
296
+ const msgs = state.messages.byConversationId[conversationId];
297
+ if (!msgs)
298
+ return state;
299
+ return {
300
+ ...state,
301
+ messages: {
302
+ ...state.messages,
303
+ byConversationId: {
304
+ ...state.messages.byConversationId,
305
+ [conversationId]: msgs.map((msg) => msg.id === messageId
306
+ ? suggestions && suggestions.length > 0
307
+ ? { ...msg, suggestions }
308
+ : { ...msg, suggestions: undefined }
309
+ : msg)
310
+ }
311
+ }
312
+ };
313
+ });
293
314
  }
294
315
  }
295
316
  };
@@ -105,6 +105,8 @@ export type VersionRating = 'up' | 'down' | 'none';
105
105
  export interface ClarificationSuggestion {
106
106
  label: string;
107
107
  intent: 'refine' | 'generate_anyway';
108
+ /** When true, the host undoes the last sketch assistant turn instead of sending the label as a prompt. */
109
+ undoSketch?: boolean;
108
110
  }
109
111
  /**
110
112
  * Message input type for creating new messages
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/chat",
3
- "version": "0.1.40",
3
+ "version": "0.1.41",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",