@widgetic/chat 0.1.40 → 0.1.42
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.
- package/dist/components/Chat.svelte +72 -40
- package/dist/components/Chat.svelte.d.ts +12 -0
- package/dist/components/ChatComposer.svelte +8 -0
- package/dist/components/ChatComposer.svelte.d.ts +6 -0
- package/dist/components/ChatMessages.svelte +29 -4
- package/dist/components/SelectedElementChip.svelte +73 -0
- package/dist/components/SelectedElementChip.svelte.d.ts +20 -0
- package/dist/components/index.d.ts +1 -0
- package/dist/components/index.js +3 -0
- package/dist/i18n/index.d.ts +1 -0
- package/dist/i18n/index.js +1 -0
- package/dist/i18n/messages.d.ts +15 -0
- package/dist/i18n/messages.js +17 -1
- package/dist/i18n/sketchLocales.d.ts +2 -0
- package/dist/i18n/sketchLocales.js +83 -0
- package/dist/services/index.d.ts +5 -0
- package/dist/services/index.js +3 -0
- package/dist/services/sketchAssistantClient.d.ts +68 -0
- package/dist/services/sketchAssistantClient.js +73 -0
- package/dist/services/sketchAssistantOrchestrator.d.ts +45 -0
- package/dist/services/sketchAssistantOrchestrator.js +128 -0
- package/dist/services/sketchAssistantReply.d.ts +12 -0
- package/dist/services/sketchAssistantReply.js +28 -0
- package/dist/stores/chatStore.d.ts +1 -0
- package/dist/stores/chatStore.js +21 -0
- package/dist/types/message.d.ts +2 -0
- package/dist/utils/index.d.ts +2 -0
- package/dist/utils/index.js +2 -0
- package/dist/utils/selectedElementChip.d.ts +47 -0
- package/dist/utils/selectedElementChip.js +73 -0
- package/package.json +1 -1
|
@@ -13,7 +13,9 @@
|
|
|
13
13
|
import type { AgentAvatarRenderer, AgentSoundPlayer, ChatMember } from '../types/agent.js';
|
|
14
14
|
import ChatMessages from './ChatMessages.svelte';
|
|
15
15
|
import ChatComposer, { type ComposerModelOption } from './ChatComposer.svelte';
|
|
16
|
-
import {
|
|
16
|
+
import { showToast } from '@widgetic/design-system/components/toast/index';
|
|
17
|
+
import SelectedElementChip from './SelectedElementChip.svelte';
|
|
18
|
+
import { selectedElementChipLabel, selectedElementChipTitle } from '../utils/selectedElementChip.js';
|
|
17
19
|
import ActionBar from './ActionBar.svelte';
|
|
18
20
|
import PanelChatHeader from './PanelChatHeader.svelte';
|
|
19
21
|
import ComposerAttachmentsTray from './ComposerAttachmentsTray.svelte';
|
|
@@ -110,6 +112,8 @@
|
|
|
110
112
|
* so the host can re-run codegen without duplicating the user bubble.
|
|
111
113
|
*/
|
|
112
114
|
onRetryMessage?: (content: string) => Promise<void>;
|
|
115
|
+
/** Undo the last sketch-assistant canvas turn (one engine undo step). */
|
|
116
|
+
onSketchUndo?: () => void | Promise<void>;
|
|
113
117
|
/**
|
|
114
118
|
* What the "Upgrade" button of a failure about the plan or the credits does. Without it the button opens the
|
|
115
119
|
* billing page of the Widgetic site; a host that is a guest on somebody else's page gives its own function.
|
|
@@ -242,6 +246,16 @@
|
|
|
242
246
|
onRemoveSelectedElement?: (elementId: string) => void;
|
|
243
247
|
/** Fired when all selected widget elements should be cleared (e.g. after sending). */
|
|
244
248
|
onClearSelectedElements?: () => void;
|
|
249
|
+
/**
|
|
250
|
+
* The part whose note is open over the preview, if any. Its chip is drawn as active. Together with
|
|
251
|
+
* `onSelectedElementClick` it lets a chip and the part's marker on the preview open and fold the same note.
|
|
252
|
+
*/
|
|
253
|
+
activeSelectedElementId?: string | null;
|
|
254
|
+
/**
|
|
255
|
+
* Fired when the body of a part's chip is clicked: the host shows that part's note over the preview (or folds it when it is
|
|
256
|
+
* already open). Left out, the chips only say what they hold and are not clickable.
|
|
257
|
+
*/
|
|
258
|
+
onSelectedElementClick?: (elementId: string) => void;
|
|
245
259
|
/** Model list for the DS composer Assistant menu; hidden when empty. */
|
|
246
260
|
composerModels?: ComposerModelOption[];
|
|
247
261
|
selectedComposerModelId?: string | null;
|
|
@@ -287,7 +301,7 @@
|
|
|
287
301
|
updateLastUserMessageAttachments: (attachments: Array<{ id?: string; url: string; file_type?: string; file_name?: string | null }>) => void;
|
|
288
302
|
}
|
|
289
303
|
|
|
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();
|
|
304
|
+
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, activeSelectedElementId = null, onSelectedElementClick, composerExtras, storedLineLabel, composerModels = [], selectedComposerModelId = null, onSelectComposerModel }: Props = $props();
|
|
291
305
|
|
|
292
306
|
// The words of everything inside the chat, in the language the page chose. The page can change the language while the
|
|
293
307
|
// chat is open: the settings are read again whenever they change (and setting the same language again does nothing).
|
|
@@ -556,7 +570,8 @@
|
|
|
556
570
|
await initializeForContext(context.id);
|
|
557
571
|
} catch (error) {
|
|
558
572
|
console.error('[Chat] Failed to initialize:', error);
|
|
559
|
-
|
|
573
|
+
// A toast of the page (the host mounts the toaster), not the banner over the chat: the chat stays usable under it.
|
|
574
|
+
showToast('error', $t('chat.error.initialize'));
|
|
560
575
|
} finally {
|
|
561
576
|
isInitialized = true;
|
|
562
577
|
}
|
|
@@ -1268,6 +1283,19 @@
|
|
|
1268
1283
|
}
|
|
1269
1284
|
}
|
|
1270
1285
|
|
|
1286
|
+
/** The sketch's "Undo" chip is used once: take it off the last assistant message that carries it. */
|
|
1287
|
+
function clearUndoSketchSuggestionChip() {
|
|
1288
|
+
const convId = currentConversationId;
|
|
1289
|
+
if (!convId) return;
|
|
1290
|
+
const msgs = getCurrentMessages(convId);
|
|
1291
|
+
for (let index = msgs.length - 1; index >= 0; index--) {
|
|
1292
|
+
const msg = msgs[index];
|
|
1293
|
+
if (msg.messageType !== 'assistant' || !msg.suggestions?.some((item) => item.undoSketch)) continue;
|
|
1294
|
+
chatStore.actions.updateMessageSuggestions(convId, msg.id, undefined);
|
|
1295
|
+
break;
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1271
1299
|
function fillDraftFromSuggestion(label: string, intent?: ClarificationSuggestion['intent']) {
|
|
1272
1300
|
const trimmed = label.trim();
|
|
1273
1301
|
if (!trimmed) return;
|
|
@@ -1289,8 +1317,16 @@
|
|
|
1289
1317
|
fillDraftFromSuggestion(suggestion);
|
|
1290
1318
|
}
|
|
1291
1319
|
|
|
1292
|
-
/**
|
|
1293
|
-
|
|
1320
|
+
/**
|
|
1321
|
+
* Clarification chips fill the composer like other suggestions; chipIntent is kept on the draft until send.
|
|
1322
|
+
* The sketch's "Undo" chip is not a suggestion: it takes the last drawing back through the page (onSketchUndo), and goes.
|
|
1323
|
+
*/
|
|
1324
|
+
async function handleClarificationSuggestionSelected(suggestion: ClarificationSuggestion) {
|
|
1325
|
+
if (suggestion.undoSketch && onSketchUndo) {
|
|
1326
|
+
await onSketchUndo();
|
|
1327
|
+
clearUndoSketchSuggestionChip();
|
|
1328
|
+
return;
|
|
1329
|
+
}
|
|
1294
1330
|
if (!suggestion.label.trim()) return;
|
|
1295
1331
|
if (isGenerating || localIsSending || isSendingOrLoading) return;
|
|
1296
1332
|
fillDraftFromSuggestion(suggestion.label, suggestion.intent);
|
|
@@ -2170,41 +2206,6 @@
|
|
|
2170
2206
|
</div>
|
|
2171
2207
|
{/if}
|
|
2172
2208
|
|
|
2173
|
-
{#if selectedElements && selectedElements.length > 0}
|
|
2174
|
-
<div
|
|
2175
|
-
class="prompt-chat-selected-elements-tray flex flex-wrap items-center gap-1.5 border-t border-gray-100 bg-[#F7FAF5] px-3 py-2 shrink-0"
|
|
2176
|
-
data-testid="chat-selected-elements-tray"
|
|
2177
|
-
>
|
|
2178
|
-
{#each selectedElements as item, index (item.id)}
|
|
2179
|
-
{@const chipLabel = `<${item.tagName}${item.idAttr ? `#${item.idAttr}` : ''}>${item.note?.trim() ? ` · ${item.note.trim()}` : item.textSnippet ? ` · ${item.textSnippet}` : item.selector ? ` · ${item.selector}` : ''}`}
|
|
2180
|
-
<span class="prompt-chat-selected-element-chip max-w-full" title={item.selector} data-testid="chat-selected-element-chip">
|
|
2181
|
-
<Chip
|
|
2182
|
-
class="max-w-full"
|
|
2183
|
-
label={chipLabel}
|
|
2184
|
-
showRemove={!!onRemoveSelectedElement}
|
|
2185
|
-
removeLabel={$t('chat.selector.removeElement')}
|
|
2186
|
-
onRemove={() => onRemoveSelectedElement?.(item.id)}
|
|
2187
|
-
>
|
|
2188
|
-
{#snippet leading()}
|
|
2189
|
-
<span class="bg-primary text-primary-foreground flex h-4 w-4 shrink-0 items-center justify-center rounded-full text-[10px] font-bold">
|
|
2190
|
-
{index + 1}
|
|
2191
|
-
</span>
|
|
2192
|
-
{/snippet}
|
|
2193
|
-
</Chip>
|
|
2194
|
-
</span>
|
|
2195
|
-
{/each}
|
|
2196
|
-
{#if selectedElements.length > 1 && onClearSelectedElements}
|
|
2197
|
-
<button
|
|
2198
|
-
type="button"
|
|
2199
|
-
class="ms-auto text-[11px] font-medium text-gray-500 hover:text-gray-800 cursor-pointer"
|
|
2200
|
-
onclick={() => onClearSelectedElements?.()}
|
|
2201
|
-
>
|
|
2202
|
-
{$t('chat.selector.clearAll')}
|
|
2203
|
-
</button>
|
|
2204
|
-
{/if}
|
|
2205
|
-
</div>
|
|
2206
|
-
{/if}
|
|
2207
|
-
|
|
2208
2209
|
{#if localAttachments.length > 0}
|
|
2209
2210
|
<ComposerAttachmentsTray
|
|
2210
2211
|
attachments={localAttachments}
|
|
@@ -2217,8 +2218,39 @@
|
|
|
2217
2218
|
/>
|
|
2218
2219
|
{/if}
|
|
2219
2220
|
|
|
2221
|
+
<!--
|
|
2222
|
+
The parts the person picked on the preview, as chips inside the message box (Figma: Selecting elements, frames 2 to 4).
|
|
2223
|
+
A chip says the first words of the part's note; its body opens that note over the part on the preview, and the cross takes
|
|
2224
|
+
the part out of the message. The number on the badge is the number of the marker on the part.
|
|
2225
|
+
-->
|
|
2226
|
+
{#snippet selectedElementChips()}
|
|
2227
|
+
<div class="prompt-chat-selected-elements-tray flex w-full min-w-0 flex-wrap items-center gap-1.5" data-testid="chat-selected-elements-tray">
|
|
2228
|
+
{#each selectedElements ?? [] as item, index (item.id)}
|
|
2229
|
+
<SelectedElementChip
|
|
2230
|
+
index={index + 1}
|
|
2231
|
+
label={selectedElementChipLabel(item)}
|
|
2232
|
+
title={selectedElementChipTitle(item)}
|
|
2233
|
+
active={activeSelectedElementId === item.id}
|
|
2234
|
+
removeLabel={$t('chat.selector.removeElement')}
|
|
2235
|
+
onOpen={onSelectedElementClick ? () => onSelectedElementClick?.(item.id) : undefined}
|
|
2236
|
+
onRemove={onRemoveSelectedElement ? () => onRemoveSelectedElement?.(item.id) : undefined}
|
|
2237
|
+
/>
|
|
2238
|
+
{/each}
|
|
2239
|
+
{#if (selectedElements?.length ?? 0) > 1 && onClearSelectedElements}
|
|
2240
|
+
<button
|
|
2241
|
+
type="button"
|
|
2242
|
+
class="text-caption text-muted-foreground hover:text-foreground ms-auto cursor-pointer"
|
|
2243
|
+
onclick={() => onClearSelectedElements?.()}
|
|
2244
|
+
>
|
|
2245
|
+
{$t('chat.selector.clearAll')}
|
|
2246
|
+
</button>
|
|
2247
|
+
{/if}
|
|
2248
|
+
</div>
|
|
2249
|
+
{/snippet}
|
|
2250
|
+
|
|
2220
2251
|
<ChatComposer
|
|
2221
2252
|
{sendNudgeToken}
|
|
2253
|
+
attachments={selectedElements && selectedElements.length > 0 ? selectedElementChips : undefined}
|
|
2222
2254
|
panelLayout={showPanelHeader}
|
|
2223
2255
|
placeholder={showPanelHeader
|
|
2224
2256
|
? (currentMessages?.length ?? 0) > 0
|
|
@@ -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.
|
|
@@ -281,6 +283,16 @@ interface Props {
|
|
|
281
283
|
onRemoveSelectedElement?: (elementId: string) => void;
|
|
282
284
|
/** Fired when all selected widget elements should be cleared (e.g. after sending). */
|
|
283
285
|
onClearSelectedElements?: () => void;
|
|
286
|
+
/**
|
|
287
|
+
* The part whose note is open over the preview, if any. Its chip is drawn as active. Together with
|
|
288
|
+
* `onSelectedElementClick` it lets a chip and the part's marker on the preview open and fold the same note.
|
|
289
|
+
*/
|
|
290
|
+
activeSelectedElementId?: string | null;
|
|
291
|
+
/**
|
|
292
|
+
* Fired when the body of a part's chip is clicked: the host shows that part's note over the preview (or folds it when it is
|
|
293
|
+
* already open). Left out, the chips only say what they hold and are not clickable.
|
|
294
|
+
*/
|
|
295
|
+
onSelectedElementClick?: (elementId: string) => void;
|
|
284
296
|
/** Model list for the DS composer Assistant menu; hidden when empty. */
|
|
285
297
|
composerModels?: ComposerModelOption[];
|
|
286
298
|
selectedComposerModelId?: string | null;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
|
+
import type { Snippet } from 'svelte';
|
|
2
3
|
import type { AttachmentInput } from '../types/attachment.js';
|
|
3
4
|
import { useChatLanguage } from '../i18n/language.js';
|
|
4
5
|
import { dirForUserText, useTextDirection } from '@widgetic/design-system/components/textDirection';
|
|
@@ -34,6 +35,11 @@
|
|
|
34
35
|
sendIcon?: 'send' | 'arrow-up';
|
|
35
36
|
/** Increment from the host to nudge Send before publish. */
|
|
36
37
|
sendNudgeToken?: number;
|
|
38
|
+
/**
|
|
39
|
+
* What sits inside the message box above the text (the chips of the parts picked on the preview). The box draws nothing
|
|
40
|
+
* for it while this is not given, so a message with no parts looks as it always did.
|
|
41
|
+
*/
|
|
42
|
+
attachments?: Snippet;
|
|
37
43
|
}
|
|
38
44
|
|
|
39
45
|
let {
|
|
@@ -55,6 +61,7 @@
|
|
|
55
61
|
panelLayout = false,
|
|
56
62
|
sendIcon = 'send',
|
|
57
63
|
sendNudgeToken = 0,
|
|
64
|
+
attachments,
|
|
58
65
|
}: Props = $props();
|
|
59
66
|
|
|
60
67
|
const composerSendIcon = $derived(panelLayout ? 'arrow-up' : sendIcon);
|
|
@@ -228,6 +235,7 @@
|
|
|
228
235
|
onSend={handleComposerSend}
|
|
229
236
|
onStop={() => onStop?.()}
|
|
230
237
|
leading={attachControl}
|
|
238
|
+
{attachments}
|
|
231
239
|
{sendAttention}
|
|
232
240
|
/>
|
|
233
241
|
</div>
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { Snippet } from 'svelte';
|
|
1
2
|
import type { AttachmentInput } from '../types/attachment.js';
|
|
2
3
|
export type ComposerModelOption = {
|
|
3
4
|
id: string;
|
|
@@ -26,6 +27,11 @@ interface Props {
|
|
|
26
27
|
sendIcon?: 'send' | 'arrow-up';
|
|
27
28
|
/** Increment from the host to nudge Send before publish. */
|
|
28
29
|
sendNudgeToken?: number;
|
|
30
|
+
/**
|
|
31
|
+
* What sits inside the message box above the text (the chips of the parts picked on the preview). The box draws nothing
|
|
32
|
+
* for it while this is not given, so a message with no parts looks as it always did.
|
|
33
|
+
*/
|
|
34
|
+
attachments?: Snippet;
|
|
29
35
|
}
|
|
30
36
|
declare const ChatComposer: import("svelte").Component<Props, {}, "value">;
|
|
31
37
|
type ChatComposer = ReturnType<typeof ChatComposer>;
|
|
@@ -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 ||
|
|
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
|
-
|
|
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 =
|
|
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
|
|
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"
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
Figma: Part Chip (component set 1882:6845 on the Canvas page, file GCC2aXrh3PEHlMWFaAOisR): Default, Hover, Active.
|
|
3
|
+
|
|
4
|
+
One chip per part the person picked on the preview, in the message box. The number on the badge is the number of the marker
|
|
5
|
+
on the part, so the two can be matched by eye. Its body opens the part's note over the part (and folds it again when it is
|
|
6
|
+
already open); the cross takes the part out of the message. A page that does not give `onOpen` gets a chip that only
|
|
7
|
+
says what it holds, as the chat has always shown it.
|
|
8
|
+
-->
|
|
9
|
+
<script lang="ts">
|
|
10
|
+
import IconX from '@tabler/icons-svelte/icons/x';
|
|
11
|
+
|
|
12
|
+
interface Props {
|
|
13
|
+
/** The number on the badge: the part's number on the preview. */
|
|
14
|
+
index: number;
|
|
15
|
+
/** What the chip says: the first words of the part's note, or the part's name while the note is empty. */
|
|
16
|
+
label: string;
|
|
17
|
+
/** The tooltip: the whole note. Defaults to the label. */
|
|
18
|
+
title?: string;
|
|
19
|
+
/** The part's note is open over the preview. */
|
|
20
|
+
active?: boolean;
|
|
21
|
+
/** Name of the cross, for screen readers and its tooltip. */
|
|
22
|
+
removeLabel?: string;
|
|
23
|
+
/** The body was clicked: show the part's note over the preview. */
|
|
24
|
+
onOpen?: () => void;
|
|
25
|
+
/** The cross was clicked: take the part out of the message. */
|
|
26
|
+
onRemove?: () => void;
|
|
27
|
+
class?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
let { index, label, title, active = false, removeLabel = 'Remove', onOpen, onRemove, class: className = '' }: Props = $props();
|
|
31
|
+
</script>
|
|
32
|
+
|
|
33
|
+
{#snippet chipBody()}
|
|
34
|
+
<span class="bg-brand text-brand-foreground flex size-4 shrink-0 items-center justify-center rounded-full text-[10px] leading-none font-semibold">
|
|
35
|
+
{index}
|
|
36
|
+
</span>
|
|
37
|
+
<span class="truncate">{label}</span>
|
|
38
|
+
{/snippet}
|
|
39
|
+
|
|
40
|
+
<div
|
|
41
|
+
class="prompt-chat-selected-element-chip text-label-small text-foreground duration-fast inline-flex h-7 max-w-full min-w-0 items-center gap-1.5 rounded-lg border ps-2 pe-1.5 transition-colors {active
|
|
42
|
+
? 'border-brand bg-brand-subtle'
|
|
43
|
+
: 'border-border bg-background hover:bg-accent'} {className}"
|
|
44
|
+
title={title ?? label}
|
|
45
|
+
data-testid="chat-selected-element-chip"
|
|
46
|
+
data-active={active ? 'true' : undefined}
|
|
47
|
+
>
|
|
48
|
+
{#if onOpen}
|
|
49
|
+
<button
|
|
50
|
+
type="button"
|
|
51
|
+
class="focus-visible:ring-ring flex min-w-0 cursor-pointer items-center gap-1.5 rounded-sm focus-visible:ring-2 focus-visible:outline-hidden"
|
|
52
|
+
aria-pressed={active}
|
|
53
|
+
onclick={() => onOpen?.()}
|
|
54
|
+
>
|
|
55
|
+
{@render chipBody()}
|
|
56
|
+
</button>
|
|
57
|
+
{:else}
|
|
58
|
+
<span class="flex min-w-0 items-center gap-1.5">
|
|
59
|
+
{@render chipBody()}
|
|
60
|
+
</span>
|
|
61
|
+
{/if}
|
|
62
|
+
{#if onRemove}
|
|
63
|
+
<button
|
|
64
|
+
type="button"
|
|
65
|
+
class="text-muted-foreground hover:text-foreground focus-visible:ring-ring inline-flex size-4 shrink-0 cursor-pointer items-center justify-center rounded-sm focus-visible:ring-2 focus-visible:outline-hidden"
|
|
66
|
+
aria-label={removeLabel}
|
|
67
|
+
title={removeLabel}
|
|
68
|
+
onclick={() => onRemove?.()}
|
|
69
|
+
>
|
|
70
|
+
<IconX class="size-4 stroke-2" aria-hidden="true" />
|
|
71
|
+
</button>
|
|
72
|
+
{/if}
|
|
73
|
+
</div>
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
interface Props {
|
|
2
|
+
/** The number on the badge: the part's number on the preview. */
|
|
3
|
+
index: number;
|
|
4
|
+
/** What the chip says: the first words of the part's note, or the part's name while the note is empty. */
|
|
5
|
+
label: string;
|
|
6
|
+
/** The tooltip: the whole note. Defaults to the label. */
|
|
7
|
+
title?: string;
|
|
8
|
+
/** The part's note is open over the preview. */
|
|
9
|
+
active?: boolean;
|
|
10
|
+
/** Name of the cross, for screen readers and its tooltip. */
|
|
11
|
+
removeLabel?: string;
|
|
12
|
+
/** The body was clicked: show the part's note over the preview. */
|
|
13
|
+
onOpen?: () => void;
|
|
14
|
+
/** The cross was clicked: take the part out of the message. */
|
|
15
|
+
onRemove?: () => void;
|
|
16
|
+
class?: string;
|
|
17
|
+
}
|
|
18
|
+
declare const SelectedElementChip: import("svelte").Component<Props, {}, "">;
|
|
19
|
+
type SelectedElementChip = ReturnType<typeof SelectedElementChip>;
|
|
20
|
+
export default SelectedElementChip;
|
|
@@ -14,4 +14,5 @@ export { default as AgentTurn } from './agent/AgentTurn.svelte';
|
|
|
14
14
|
export { default as CodeCard } from './agent/CodeCard.svelte';
|
|
15
15
|
export { default as GenerationModule } from './agent/GenerationModule.svelte';
|
|
16
16
|
export { default as MemberAvatar } from './agent/MemberAvatar.svelte';
|
|
17
|
+
export { default as SelectedElementChip } from './SelectedElementChip.svelte';
|
|
17
18
|
export type { ComponentProps } from 'svelte';
|
package/dist/components/index.js
CHANGED
|
@@ -19,3 +19,6 @@ export { default as AgentTurn } from './agent/AgentTurn.svelte';
|
|
|
19
19
|
export { default as CodeCard } from './agent/CodeCard.svelte';
|
|
20
20
|
export { default as GenerationModule } from './agent/GenerationModule.svelte';
|
|
21
21
|
export { default as MemberAvatar } from './agent/MemberAvatar.svelte';
|
|
22
|
+
// The chip of a part the person picked on the preview (the numbered badge, the first words of its note, the cross), for a page
|
|
23
|
+
// that builds its own message box. Inside `Chat` the chips are drawn for the page, in the message box.
|
|
24
|
+
export { default as SelectedElementChip } from './SelectedElementChip.svelte';
|
package/dist/i18n/index.d.ts
CHANGED
|
@@ -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';
|
package/dist/i18n/index.js
CHANGED
|
@@ -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';
|
package/dist/i18n/messages.d.ts
CHANGED
|
@@ -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;
|
package/dist/i18n/messages.js
CHANGED
|
@@ -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,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
|
+
};
|
package/dist/services/index.d.ts
CHANGED
|
@@ -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';
|
package/dist/services/index.js
CHANGED
|
@@ -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
|
/**
|
package/dist/stores/chatStore.js
CHANGED
|
@@ -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
|
};
|
package/dist/types/message.d.ts
CHANGED
|
@@ -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/dist/utils/index.d.ts
CHANGED
|
@@ -7,5 +7,7 @@ export type { GenerationActivityPhase } from './generationActivity.js';
|
|
|
7
7
|
export { readGenerationPlanFromMetadata, mapWidgetPlanToPlanCard, } from './generationPlan.js';
|
|
8
8
|
export type { GenerationPlanWire, MappedGenerationPlanCard, WidgetPlanTaskStatusWire, } from './generationPlan.js';
|
|
9
9
|
export { AGENT_AVATAR_PIXELS, CURRENT_USER_PLACEHOLDER_ID, LOCAL_SERVICE_USER_ID, MAX_KEPT_GENERATION_CHARS, agentAvatarLabelKey, agentAvatarPixels, agentLookSignature, avatarStartAfter, finishedGenerationBelongsTo, finishedModulesView, keepFinishedGeneration, keptWorkIsOutdated, liveAgentLook, liveModulesView, memberDisplayName, memberMailtoHref, memberTooltipEmail, normalizePromptText, pageNamesPeople, resolveChatMember, settledAgentLook, soundStateOf, turnOutcome } from './agentTurn.js';
|
|
10
|
+
export { CHIP_NOTE_MAX_CHARACTERS, CHIP_NOTE_MAX_WORDS, firstWords, selectedElementChipLabel, selectedElementChipTitle, selectedElementName, } from './selectedElementChip.js';
|
|
11
|
+
export type { SelectedElementChipSource } from './selectedElementChip.js';
|
|
10
12
|
export type { AgentAvatarSize, AgentLook, AvatarStart, FinishedGeneration, GenerationModulesView, SoundStateInput, TurnOutcome, TurnReplyFacts } from './agentTurn.js';
|
|
11
13
|
export type { AttachmentType, AttachmentValidation, PendingAttachment, UploadStatus } from '../types/index.js';
|
package/dist/utils/index.js
CHANGED
|
@@ -9,3 +9,5 @@ export { readGenerationPlanFromMetadata, mapWidgetPlanToPlanCard, } from './gene
|
|
|
9
9
|
// The assistant's turn: its avatar's looks, the judgement of a finished turn, who wrote a message, what is kept of the work.
|
|
10
10
|
// A page that is not the chat (the workflows assistant) follows the same choreography through these.
|
|
11
11
|
export { AGENT_AVATAR_PIXELS, CURRENT_USER_PLACEHOLDER_ID, LOCAL_SERVICE_USER_ID, MAX_KEPT_GENERATION_CHARS, agentAvatarLabelKey, agentAvatarPixels, agentLookSignature, avatarStartAfter, finishedGenerationBelongsTo, finishedModulesView, keepFinishedGeneration, keptWorkIsOutdated, liveAgentLook, liveModulesView, memberDisplayName, memberMailtoHref, memberTooltipEmail, normalizePromptText, pageNamesPeople, resolveChatMember, settledAgentLook, soundStateOf, turnOutcome } from './agentTurn.js';
|
|
12
|
+
// What the chip of a picked part says: the first words of its note, or its name while the note is empty.
|
|
13
|
+
export { CHIP_NOTE_MAX_CHARACTERS, CHIP_NOTE_MAX_WORDS, firstWords, selectedElementChipLabel, selectedElementChipTitle, selectedElementName, } from './selectedElementChip.js';
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a chip in the message box says about a part the person picked on the preview.
|
|
3
|
+
*
|
|
4
|
+
* Someone who picked a part and wrote a note on it ("Make this button bigger and round.") knows the chip by the first words
|
|
5
|
+
* of that note, so that is what it shows. A part with no note yet is named by what it is: "button · Shop the sale", the tag
|
|
6
|
+
* and the first words of the text it holds (Figma: Part Chip, component set 1882:6845, and Part Note, 1882:6867).
|
|
7
|
+
* The chip's tooltip keeps the whole note, so nothing is lost by the shortening.
|
|
8
|
+
*
|
|
9
|
+
* Plain TypeScript with no Svelte in it, so the tests run it in Node as it is.
|
|
10
|
+
*/
|
|
11
|
+
/** How many words of a note a chip shows before it ends in an ellipsis. */
|
|
12
|
+
export declare const CHIP_NOTE_MAX_WORDS = 4;
|
|
13
|
+
/** The most characters of a note a chip shows, so that one long word cannot stretch the chip. */
|
|
14
|
+
export declare const CHIP_NOTE_MAX_CHARACTERS = 26;
|
|
15
|
+
/** How many words of the text a part holds name it, when it has no note. */
|
|
16
|
+
export declare const PART_TEXT_MAX_WORDS = 3;
|
|
17
|
+
/** The most characters of the text a part holds that name it. */
|
|
18
|
+
export declare const PART_TEXT_MAX_CHARACTERS = 24;
|
|
19
|
+
/** The shape of a part this file reads: the chat's `SelectedElementChatReference` has all of it, and a host's own type may too. */
|
|
20
|
+
export interface SelectedElementChipSource {
|
|
21
|
+
tagName?: string;
|
|
22
|
+
/** Compact label the host made when the part was picked (`<em> · to shared company work.`). */
|
|
23
|
+
label?: string;
|
|
24
|
+
/** What the part's text says. */
|
|
25
|
+
textSnippet?: string;
|
|
26
|
+
/** What the person wrote about the part. */
|
|
27
|
+
note?: string;
|
|
28
|
+
rect?: {
|
|
29
|
+
width: number;
|
|
30
|
+
height: number;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The first few words of a text, with an ellipsis when something was left out; an empty string when there is nothing to say.
|
|
35
|
+
* Counts words by spaces and characters by code points (so an emoji or a Chinese character is one), and cuts at the last
|
|
36
|
+
* space that fits rather than in the middle of a word, unless the first word alone is too long.
|
|
37
|
+
*/
|
|
38
|
+
export declare function firstWords(text: string | null | undefined, maxWords?: number, maxCharacters?: number): string;
|
|
39
|
+
/**
|
|
40
|
+
* What a part is called when it has no note: its tag and the first words of its text ("button · Shop the sale"), or its size
|
|
41
|
+
* when it holds no text ("div · 240 × 80"). A box drawn on the preview has no tag, so it keeps the label it was given.
|
|
42
|
+
*/
|
|
43
|
+
export declare function selectedElementName(part: SelectedElementChipSource): string;
|
|
44
|
+
/** The text on the chip: the first words of the note, or the name of the part while the note is empty. */
|
|
45
|
+
export declare function selectedElementChipLabel(part: SelectedElementChipSource): string;
|
|
46
|
+
/** The chip's tooltip: the whole note, or the name of the part while the note is empty. */
|
|
47
|
+
export declare function selectedElementChipTitle(part: SelectedElementChipSource): string;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a chip in the message box says about a part the person picked on the preview.
|
|
3
|
+
*
|
|
4
|
+
* Someone who picked a part and wrote a note on it ("Make this button bigger and round.") knows the chip by the first words
|
|
5
|
+
* of that note, so that is what it shows. A part with no note yet is named by what it is: "button · Shop the sale", the tag
|
|
6
|
+
* and the first words of the text it holds (Figma: Part Chip, component set 1882:6845, and Part Note, 1882:6867).
|
|
7
|
+
* The chip's tooltip keeps the whole note, so nothing is lost by the shortening.
|
|
8
|
+
*
|
|
9
|
+
* Plain TypeScript with no Svelte in it, so the tests run it in Node as it is.
|
|
10
|
+
*/
|
|
11
|
+
/** How many words of a note a chip shows before it ends in an ellipsis. */
|
|
12
|
+
export const CHIP_NOTE_MAX_WORDS = 4;
|
|
13
|
+
/** The most characters of a note a chip shows, so that one long word cannot stretch the chip. */
|
|
14
|
+
export const CHIP_NOTE_MAX_CHARACTERS = 26;
|
|
15
|
+
/** How many words of the text a part holds name it, when it has no note. */
|
|
16
|
+
export const PART_TEXT_MAX_WORDS = 3;
|
|
17
|
+
/** The most characters of the text a part holds that name it. */
|
|
18
|
+
export const PART_TEXT_MAX_CHARACTERS = 24;
|
|
19
|
+
const ELLIPSIS = '…';
|
|
20
|
+
/**
|
|
21
|
+
* The first few words of a text, with an ellipsis when something was left out; an empty string when there is nothing to say.
|
|
22
|
+
* Counts words by spaces and characters by code points (so an emoji or a Chinese character is one), and cuts at the last
|
|
23
|
+
* space that fits rather than in the middle of a word, unless the first word alone is too long.
|
|
24
|
+
*/
|
|
25
|
+
export function firstWords(text, maxWords = CHIP_NOTE_MAX_WORDS, maxCharacters = CHIP_NOTE_MAX_CHARACTERS) {
|
|
26
|
+
const collapsed = (text ?? '').replace(/\s+/g, ' ').trim();
|
|
27
|
+
if (!collapsed)
|
|
28
|
+
return '';
|
|
29
|
+
const words = collapsed.split(' ');
|
|
30
|
+
let kept = words.slice(0, Math.max(1, maxWords)).join(' ');
|
|
31
|
+
let leftOut = words.length > maxWords;
|
|
32
|
+
const characters = Array.from(kept);
|
|
33
|
+
if (characters.length > maxCharacters) {
|
|
34
|
+
const fitting = characters.slice(0, maxCharacters).join('');
|
|
35
|
+
const lastSpace = fitting.lastIndexOf(' ');
|
|
36
|
+
kept = lastSpace > 0 ? fitting.slice(0, lastSpace) : fitting;
|
|
37
|
+
leftOut = true;
|
|
38
|
+
}
|
|
39
|
+
if (!leftOut)
|
|
40
|
+
return kept;
|
|
41
|
+
// A comma or a full stop before the ellipsis reads as noise ("bigger,…"), so it goes.
|
|
42
|
+
return `${kept.replace(/[\s,;:.\-–—]+$/u, '')}${ELLIPSIS}`;
|
|
43
|
+
}
|
|
44
|
+
/** The label a host made, without the angle brackets of the tag (`<h2> · Title` → `h2 · Title`). */
|
|
45
|
+
function readableLabel(label) {
|
|
46
|
+
return (label ?? '').replace(/[<>]/g, '').replace(/\s+/g, ' ').trim();
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* What a part is called when it has no note: its tag and the first words of its text ("button · Shop the sale"), or its size
|
|
50
|
+
* when it holds no text ("div · 240 × 80"). A box drawn on the preview has no tag, so it keeps the label it was given.
|
|
51
|
+
*/
|
|
52
|
+
export function selectedElementName(part) {
|
|
53
|
+
const tag = (part.tagName ?? '').trim().toLowerCase();
|
|
54
|
+
if (!tag || tag === 'area')
|
|
55
|
+
return readableLabel(part.label) || tag;
|
|
56
|
+
const text = firstWords(part.textSnippet, PART_TEXT_MAX_WORDS, PART_TEXT_MAX_CHARACTERS);
|
|
57
|
+
if (text)
|
|
58
|
+
return `${tag} · ${text}`;
|
|
59
|
+
const size = part.rect;
|
|
60
|
+
if (size && size.width > 0 && size.height > 0) {
|
|
61
|
+
return `${tag} · ${Math.round(size.width)} × ${Math.round(size.height)}`;
|
|
62
|
+
}
|
|
63
|
+
return tag;
|
|
64
|
+
}
|
|
65
|
+
/** The text on the chip: the first words of the note, or the name of the part while the note is empty. */
|
|
66
|
+
export function selectedElementChipLabel(part) {
|
|
67
|
+
return firstWords(part.note) || selectedElementName(part);
|
|
68
|
+
}
|
|
69
|
+
/** The chip's tooltip: the whole note, or the name of the part while the note is empty. */
|
|
70
|
+
export function selectedElementChipTitle(part) {
|
|
71
|
+
const note = (part.note ?? '').replace(/\s+/g, ' ').trim();
|
|
72
|
+
return note || selectedElementName(part);
|
|
73
|
+
}
|