@widgetic/chat 0.1.33 → 0.1.35
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/README.md +34 -0
- package/dist/components/Chat.svelte +87 -16
- package/dist/components/Chat.svelte.d.ts +13 -1
- package/dist/components/ChatMessages.svelte +104 -8
- package/dist/components/ChatMessages.svelte.d.ts +15 -2
- package/dist/i18n/messages.d.ts +4 -0
- package/dist/i18n/messages.js +4 -0
- package/dist/types/message.d.ts +6 -0
- package/dist/utils/index.d.ts +2 -0
- package/dist/utils/index.js +2 -0
- package/dist/utils/versionRatings.d.ts +28 -0
- package/dist/utils/versionRatings.js +41 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -161,6 +161,40 @@ You can also use individual components:
|
|
|
161
161
|
/>
|
|
162
162
|
```
|
|
163
163
|
|
|
164
|
+
### Rating a version
|
|
165
|
+
|
|
166
|
+
Next to the name of each version (the reply that announced a change of the widget) the chat can draw two thumbs, so a person can say whether
|
|
167
|
+
that version is good. The thumbs are **opt-in**: give `Chat` an `onRateVersion` callback and they appear, leave it out and the chat looks and
|
|
168
|
+
works as it always did. The chat keeps no rating of its own: the page decides where a rating goes. A rating is one of three words: `up`,
|
|
169
|
+
`down`, or `none` (the person took their rating back).
|
|
170
|
+
|
|
171
|
+
```svelte
|
|
172
|
+
<script lang="ts">
|
|
173
|
+
import { Chat, type VersionRating } from '@widgetic/chat';
|
|
174
|
+
|
|
175
|
+
// What the page already knows: message id -> rating (optional, see below)
|
|
176
|
+
let ratingsKeptByThePage: Record<string, VersionRating> = {};
|
|
177
|
+
|
|
178
|
+
async function rateVersion(conversationId: string, messageId: string, rating: VersionRating) {
|
|
179
|
+
// Throw when the rating was not kept: the chat puts the thumb back as it was.
|
|
180
|
+
await api.rateMessageVersion({ conversationId, messageId, rateMessageVersionRequest: { rating } });
|
|
181
|
+
}
|
|
182
|
+
</script>
|
|
183
|
+
|
|
184
|
+
<Chat {context} onRateVersion={rateVersion} versionRatings={ratingsKeptByThePage} />
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
- `onRateVersion(conversationId, messageId, rating)` is called with the id of the saved message that announced the version and the rating the
|
|
188
|
+
version has **now**. Pressing the thumb that is already chosen takes the rating back, and the callback then receives `none`.
|
|
189
|
+
- The chat shows the press at once. When the callback throws or rejects, the thumb goes back to what it was; while a call for a version is
|
|
190
|
+
still on its way, a second press on that version is ignored, so two answers cannot arrive in the wrong order.
|
|
191
|
+
- `versionRatings` (optional) is a record of `messageId` to rating, for a page that keeps ratings and gives them back when the chat opens
|
|
192
|
+
again. What the person pressed in this chat is shown over it. Without it, the thumbs start empty each time the chat opens.
|
|
193
|
+
- Only a version the backend saved can be rated: not a reply still on its way or one that failed, not the copy a restore appends, not the
|
|
194
|
+
stand-in the chat draws while the widget's head is ahead of every saved message, and not a version a restore undid. Nothing is drawn while
|
|
195
|
+
the chat is loading.
|
|
196
|
+
- Words: `chat.messages.rateGroup`, `chat.messages.rateUp` and `chat.messages.rateDown` (see [Languages](#languages)).
|
|
197
|
+
|
|
164
198
|
## State Management
|
|
165
199
|
|
|
166
200
|
The chat module uses Svelte 5 runes for reactive state management:
|
|
@@ -6,8 +6,9 @@
|
|
|
6
6
|
import { chatStore, getCurrentState, getCurrentMessages } from '../stores/chatStore.js';
|
|
7
7
|
import { createChatService } from '../services/chatService.js';
|
|
8
8
|
import { setLogsEnabled, chatLog, chatWarn } from '../utils/logger.js';
|
|
9
|
+
import { ratingAfterPress, ratingOfVersion, type VersionThumb } from '../utils/versionRatings.js';
|
|
9
10
|
import type { ChatConfig, ChatContext } from '../types/index.js';
|
|
10
|
-
import type { ClarificationSuggestion, DesignControlRequest } from '../types/message.js';
|
|
11
|
+
import type { ClarificationSuggestion, DesignControlRequest, VersionRating } from '../types/message.js';
|
|
11
12
|
import type { AttachmentInput, SelectedElementChatReference } from '../types/attachment.js';
|
|
12
13
|
import ChatMessages from './ChatMessages.svelte';
|
|
13
14
|
import ChatInput from './ChatInput.svelte';
|
|
@@ -80,6 +81,18 @@
|
|
|
80
81
|
designControls?: DesignControlRequest,
|
|
81
82
|
) => Promise<any>;
|
|
82
83
|
onRestoreCheckpointBackend?: (conversationId: string, checkpointMessageId: string) => Promise<any>;
|
|
84
|
+
/**
|
|
85
|
+
* Keeps the person's thumbs on a version: the assistant message that announced a commit of the widget. Called with the id of the
|
|
86
|
+
* conversation, the id of that message and `up`, `down` or `none` (the rating was taken back); the host sends it to its backend.
|
|
87
|
+
* The two thumbs are drawn next to a version's name only when this is given. Resolve when the rating is kept: a rejection puts the
|
|
88
|
+
* thumb back as it was. The rating is a hint for the host, so a host that cannot keep one should say nothing about it, not fail.
|
|
89
|
+
*/
|
|
90
|
+
onRateVersion?: (conversationId: string, messageId: string, rating: VersionRating) => Promise<unknown>;
|
|
91
|
+
/**
|
|
92
|
+
* The rating each version already has, by the id of the message that announced it, for a host that keeps ratings and gives them
|
|
93
|
+
* back when the chat opens again. What the person presses in this chat is read over it.
|
|
94
|
+
*/
|
|
95
|
+
versionRatings?: Record<string, VersionRating>;
|
|
83
96
|
onTakeScreenshot?: () => Promise<string | null>;
|
|
84
97
|
/** Fires whenever the active conversation ID changes (including initial null → uuid). */
|
|
85
98
|
onConversationChange?: (conversationId: string | null) => void;
|
|
@@ -218,7 +231,7 @@
|
|
|
218
231
|
updateLastUserMessageAttachments: (attachments: Array<{ id?: string; url: string; file_type?: string; file_name?: string | null }>) => void;
|
|
219
232
|
}
|
|
220
233
|
|
|
221
|
-
let { context, config = {}, class: className = '', locale = null, messages: languageMessages = null, dir = undefined, style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onUpgradePlans, onUploadChatFile, showHeader = true, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, onMessagesDrag, onMessagesDragEnd, onLoadOlderMessages, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], viewingVersion = null, isGenerating = false, generationStream = '', onStopGeneration, renderDesignControls, actionBarExtras, completeReplacement, replaceComplete = false, showSelector = false, isSelectorActive = false, selectedElements = [], onToggleSelector, onRemoveSelectedElement, onClearSelectedElements, composerExtras, storedLineLabel }: Props = $props();
|
|
234
|
+
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, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, onMessagesDrag, onMessagesDragEnd, onLoadOlderMessages, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], viewingVersion = null, isGenerating = false, generationStream = '', onStopGeneration, renderDesignControls, actionBarExtras, completeReplacement, replaceComplete = false, showSelector = false, isSelectorActive = false, selectedElements = [], onToggleSelector, onRemoveSelectedElement, onClearSelectedElements, composerExtras, storedLineLabel }: Props = $props();
|
|
222
235
|
|
|
223
236
|
// The words of everything inside the chat, in the language the page chose. The page can change the language while the
|
|
224
237
|
// chat is open: the settings are read again whenever they change (and setting the same language again does nothing).
|
|
@@ -268,6 +281,8 @@
|
|
|
268
281
|
// Local state
|
|
269
282
|
let chatContainer: HTMLElement;
|
|
270
283
|
let isInitialized = $state(false);
|
|
284
|
+
/** Suggestions stay hidden from the first paint. Turned on only after the message read, and only when it was empty. */
|
|
285
|
+
let showEmptyState = $state(false);
|
|
271
286
|
let chatService = $state(createChatService());
|
|
272
287
|
let currentConversationId = $state<string | null>(null);
|
|
273
288
|
|
|
@@ -439,27 +454,43 @@
|
|
|
439
454
|
}
|
|
440
455
|
|
|
441
456
|
let lastLoadedContextId = $state('');
|
|
457
|
+
let contextInitToken = 0;
|
|
442
458
|
|
|
443
459
|
async function initializeForContext(contextId: string) {
|
|
444
460
|
if (!contextId) return;
|
|
461
|
+
const token = ++contextInitToken;
|
|
445
462
|
lastLoadedContextId = contextId;
|
|
446
|
-
//
|
|
447
|
-
|
|
463
|
+
// Hidden until this read finishes, so suggestion chips do not flash over a conversation that has messages.
|
|
464
|
+
isInitialized = false;
|
|
465
|
+
showEmptyState = false;
|
|
466
|
+
let conversationWasRead = false;
|
|
467
|
+
try {
|
|
468
|
+
// chatLog('[Chat] Initializing with context:', contextId);
|
|
469
|
+
chatStore.actions.setActiveContext(contextId, true);
|
|
448
470
|
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
471
|
+
const loaded = await loadConversations();
|
|
472
|
+
if (token !== contextInitToken) return;
|
|
473
|
+
if (loaded === null) {
|
|
474
|
+
showLoadFailure('chat.error.loadHistory');
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
454
477
|
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
478
|
+
if (loaded.length === 0) {
|
|
479
|
+
// chatLog('[Chat] No existing conversations, creating new one');
|
|
480
|
+
await createNewConversation();
|
|
481
|
+
} else {
|
|
482
|
+
// chatLog('[Chat] Selecting from', loaded.length, 'conversation(s)');
|
|
483
|
+
await activateBestConversation(loaded);
|
|
484
|
+
}
|
|
485
|
+
conversationWasRead = true;
|
|
486
|
+
// chatLog('[Chat] Initialized successfully');
|
|
487
|
+
} finally {
|
|
488
|
+
if (token !== contextInitToken) return;
|
|
489
|
+
const loadedMessages = currentConversationId ? (getCurrentMessages(currentConversationId) ?? []) : [];
|
|
490
|
+
// Only the read that just finished may show suggestions, and only when it stored no messages.
|
|
491
|
+
showEmptyState = conversationWasRead && loadedMessages.length === 0;
|
|
492
|
+
isInitialized = true;
|
|
461
493
|
}
|
|
462
|
-
// chatLog('[Chat] Initialized successfully');
|
|
463
494
|
}
|
|
464
495
|
|
|
465
496
|
async function retryLoadHistory() {
|
|
@@ -1199,6 +1230,37 @@
|
|
|
1199
1230
|
?? null;
|
|
1200
1231
|
}
|
|
1201
1232
|
|
|
1233
|
+
/** What the person pressed in this chat, by the id of the message that announced the version: read over what the host gave. */
|
|
1234
|
+
let chosenVersionRatings = $state<Record<string, VersionRating>>({});
|
|
1235
|
+
/** The versions whose rating is on its way to the host: a press made meanwhile is ignored, so the thumbs and the host cannot disagree on which came last. */
|
|
1236
|
+
let versionRatingsInFlight = $state<Record<string, boolean>>({});
|
|
1237
|
+
|
|
1238
|
+
/** What each version's thumbs shows as pressed: the person's own press, else what the host knew. */
|
|
1239
|
+
const shownVersionRatings = $derived({ ...ratingsFromHost, ...chosenVersionRatings });
|
|
1240
|
+
|
|
1241
|
+
/** A thumb was pressed next to a version: the thumb answers at once, and goes back if the host could not keep the rating. */
|
|
1242
|
+
async function handleRateVersion(messageId: string, pressed: VersionThumb) {
|
|
1243
|
+
const conversationId = currentConversationId;
|
|
1244
|
+
if (!onRateVersion || !conversationId || !messageId) return;
|
|
1245
|
+
if (versionRatingsInFlight[messageId]) return;
|
|
1246
|
+
|
|
1247
|
+
const ratingBefore = ratingOfVersion(messageId, chosenVersionRatings, ratingsFromHost);
|
|
1248
|
+
const ratingAfter = ratingAfterPress(ratingBefore, pressed);
|
|
1249
|
+
chosenVersionRatings = { ...chosenVersionRatings, [messageId]: ratingAfter };
|
|
1250
|
+
versionRatingsInFlight = { ...versionRatingsInFlight, [messageId]: true };
|
|
1251
|
+
try {
|
|
1252
|
+
await onRateVersion(conversationId, messageId, ratingAfter);
|
|
1253
|
+
chatLog('[Chat] Version rated:', { messageId, rating: ratingAfter });
|
|
1254
|
+
} catch (error) {
|
|
1255
|
+
chosenVersionRatings = { ...chosenVersionRatings, [messageId]: ratingBefore };
|
|
1256
|
+
chatWarn('[Chat] The rating of a version could not be kept:', error);
|
|
1257
|
+
} finally {
|
|
1258
|
+
const stillInFlight = { ...versionRatingsInFlight };
|
|
1259
|
+
delete stillInFlight[messageId];
|
|
1260
|
+
versionRatingsInFlight = stillInFlight;
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1202
1264
|
async function handleRestoreCheckpoint(messageId: string, messageIndex: number) {
|
|
1203
1265
|
// chatLog('Restore checkpoint requested:', { messageId, messageIndex, conversationId: currentConversationId });
|
|
1204
1266
|
|
|
@@ -1636,6 +1698,8 @@
|
|
|
1636
1698
|
/** Reload messages from backend and re-mark widget HEAD (picks up server-persisted summaries). */
|
|
1637
1699
|
async function reloadConversationMessages() {
|
|
1638
1700
|
if (!currentConversationId || !onLoadMessages) return;
|
|
1701
|
+
const conversationId = currentConversationId;
|
|
1702
|
+
showEmptyState = false;
|
|
1639
1703
|
try {
|
|
1640
1704
|
const localMsgs = getCurrentMessages(currentConversationId);
|
|
1641
1705
|
const localHasHead = localMsgs.some((m) => m.isWidgetHead || messageHasWidgetCommit(m.messageContent));
|
|
@@ -1669,6 +1733,10 @@
|
|
|
1669
1733
|
// chatLog('[Chat] Reloaded conversation messages:', loaded?.length ?? 0);
|
|
1670
1734
|
} catch (err) {
|
|
1671
1735
|
chatWarn('[Chat] Failed to reload conversation messages:', err);
|
|
1736
|
+
} finally {
|
|
1737
|
+
if (currentConversationId !== conversationId) return;
|
|
1738
|
+
const loadedCount = getCurrentMessages(conversationId)?.length ?? 0;
|
|
1739
|
+
showEmptyState = loadedCount === 0;
|
|
1672
1740
|
}
|
|
1673
1741
|
}
|
|
1674
1742
|
|
|
@@ -1895,6 +1963,7 @@
|
|
|
1895
1963
|
messages={currentMessages || []}
|
|
1896
1964
|
isLoading={isLoading}
|
|
1897
1965
|
isInitialized={isInitialized}
|
|
1966
|
+
{showEmptyState}
|
|
1898
1967
|
{context}
|
|
1899
1968
|
isCompleted={isCompleted}
|
|
1900
1969
|
enableAutoCodeDetection={config?.features?.autoCodeDetection === true}
|
|
@@ -1911,6 +1980,8 @@
|
|
|
1911
1980
|
generationStream={isGenerating ? generationStream : ''}
|
|
1912
1981
|
onSuggestionSelected={handleSuggestionSelected}
|
|
1913
1982
|
onRestoreCheckpoint={handleRestoreCheckpoint}
|
|
1983
|
+
onRateVersion={onRateVersion ? handleRateVersion : undefined}
|
|
1984
|
+
versionRatings={shownVersionRatings}
|
|
1914
1985
|
onRetryMessage={handleRetryMessage}
|
|
1915
1986
|
{onUpgradePlans}
|
|
1916
1987
|
onClarificationSuggestionSelected={handleClarificationSuggestionSelected}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Snippet } from 'svelte';
|
|
2
2
|
import { type TextDirection } from '@widgetic/design-system/components/textDirection';
|
|
3
3
|
import type { ChatConfig, ChatContext } from '../types/index.js';
|
|
4
|
-
import type { ClarificationSuggestion, DesignControlRequest } from '../types/message.js';
|
|
4
|
+
import type { ClarificationSuggestion, DesignControlRequest, VersionRating } from '../types/message.js';
|
|
5
5
|
import type { AttachmentInput, SelectedElementChatReference } from '../types/attachment.js';
|
|
6
6
|
interface ChatMethods {
|
|
7
7
|
sendMessage: (content: string, attachments?: Array<File | AttachmentInput>, options?: {
|
|
@@ -113,6 +113,18 @@ interface Props {
|
|
|
113
113
|
display_order?: number;
|
|
114
114
|
}>, suggestions?: ClarificationSuggestion[], designControls?: DesignControlRequest) => Promise<any>;
|
|
115
115
|
onRestoreCheckpointBackend?: (conversationId: string, checkpointMessageId: string) => Promise<any>;
|
|
116
|
+
/**
|
|
117
|
+
* Keeps the person's thumbs on a version: the assistant message that announced a commit of the widget. Called with the id of the
|
|
118
|
+
* conversation, the id of that message and `up`, `down` or `none` (the rating was taken back); the host sends it to its backend.
|
|
119
|
+
* The two thumbs are drawn next to a version's name only when this is given. Resolve when the rating is kept: a rejection puts the
|
|
120
|
+
* thumb back as it was. The rating is a hint for the host, so a host that cannot keep one should say nothing about it, not fail.
|
|
121
|
+
*/
|
|
122
|
+
onRateVersion?: (conversationId: string, messageId: string, rating: VersionRating) => Promise<unknown>;
|
|
123
|
+
/**
|
|
124
|
+
* The rating each version already has, by the id of the message that announced it, for a host that keeps ratings and gives them
|
|
125
|
+
* back when the chat opens again. What the person presses in this chat is read over it.
|
|
126
|
+
*/
|
|
127
|
+
versionRatings?: Record<string, VersionRating>;
|
|
116
128
|
onTakeScreenshot?: () => Promise<string | null>;
|
|
117
129
|
/** Fires whenever the active conversation ID changes (including initial null → uuid). */
|
|
118
130
|
onConversationChange?: (conversationId: string | null) => void;
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
2
|
import type { ChatMessage, ChatContext } from '../types/index.js';
|
|
3
|
-
import type { ClarificationSuggestion, DesignControlRequest } from '../types/message.js';
|
|
3
|
+
import type { ClarificationSuggestion, DesignControlRequest, VersionRating } from '../types/message.js';
|
|
4
4
|
import { MESSAGE_COLORS } from '../constants/colors.js';
|
|
5
5
|
import { chatLog } from '../utils/logger.js';
|
|
6
|
+
import { isRatableVersionReply, type VersionThumb } from '../utils/versionRatings.js';
|
|
6
7
|
import { AttachmentDisplay, SuggestionButtons } from './index.js';
|
|
7
8
|
import CodeBlock from './CodeBlock.svelte';
|
|
8
9
|
import { onDestroy, onMount, tick } from 'svelte';
|
|
@@ -22,8 +23,13 @@
|
|
|
22
23
|
class?: string;
|
|
23
24
|
messages: ChatMessage[];
|
|
24
25
|
isLoading?: boolean;
|
|
25
|
-
/** True after the conversation list/messages finished initializing
|
|
26
|
+
/** True after the conversation list/messages finished initializing. */
|
|
26
27
|
isInitialized?: boolean;
|
|
28
|
+
/**
|
|
29
|
+
* The empty-state suggestions. Stays false from the first paint.
|
|
30
|
+
* The parent sets it only after the message read, and only when that read was empty.
|
|
31
|
+
*/
|
|
32
|
+
showEmptyState?: boolean;
|
|
27
33
|
context: ChatContext;
|
|
28
34
|
isCompleted?: boolean;
|
|
29
35
|
/**
|
|
@@ -66,6 +72,13 @@
|
|
|
66
72
|
generationStream?: string;
|
|
67
73
|
onSuggestionSelected?: (suggestion: string) => void;
|
|
68
74
|
onRestoreCheckpoint?: (messageId: string, messageIndex: number) => void;
|
|
75
|
+
/**
|
|
76
|
+
* Gives each version a thumbs up and a thumbs down next to its name. Called with the id of the assistant message that
|
|
77
|
+
* announced the version and the thumb that was pressed; the host keeps the rating. Without it no thumbs are drawn.
|
|
78
|
+
*/
|
|
79
|
+
onRateVersion?: (messageId: string, pressed: VersionThumb) => void;
|
|
80
|
+
/** The rating each version has, by the id of the message that announced it: what the thumbs show as pressed. */
|
|
81
|
+
versionRatings?: Record<string, VersionRating>;
|
|
69
82
|
onRetryMessage?: (content: string) => void;
|
|
70
83
|
/**
|
|
71
84
|
* What the "Upgrade" button of a failure about the plan or the credits does. Without it the button opens the
|
|
@@ -91,7 +104,8 @@
|
|
|
91
104
|
class: className = '',
|
|
92
105
|
messages,
|
|
93
106
|
isLoading = false,
|
|
94
|
-
isInitialized =
|
|
107
|
+
isInitialized = false,
|
|
108
|
+
showEmptyState = false,
|
|
95
109
|
context,
|
|
96
110
|
isCompleted = false,
|
|
97
111
|
enableAutoCodeDetection = false,
|
|
@@ -106,6 +120,8 @@
|
|
|
106
120
|
generationStream = '',
|
|
107
121
|
onSuggestionSelected,
|
|
108
122
|
onRestoreCheckpoint,
|
|
123
|
+
onRateVersion,
|
|
124
|
+
versionRatings = {},
|
|
109
125
|
onRetryMessage,
|
|
110
126
|
onUpgradePlans,
|
|
111
127
|
onClarificationSuggestionSelected,
|
|
@@ -679,6 +695,17 @@
|
|
|
679
695
|
};
|
|
680
696
|
}
|
|
681
697
|
|
|
698
|
+
/**
|
|
699
|
+
* The message a thumbs on this turn's version is given to: the saved assistant reply that announced the commit. Never the stand-in
|
|
700
|
+
* the chat draws for a head that no saved message names, a copy made by Restore, or a reply that was not saved, because the host's
|
|
701
|
+
* backend knows only the messages it saved. Null when the turn has no such reply (a failed prompt, an older prompt with no commit line).
|
|
702
|
+
*/
|
|
703
|
+
function ratableVersionReplyId(turn: ChatTurn): string | null {
|
|
704
|
+
const reply = getTurnCommitReply(turn);
|
|
705
|
+
if (!reply || isRestoreForkContent(reply.messageContent)) return null;
|
|
706
|
+
return isRatableVersionReply(reply) ? reply.id : null;
|
|
707
|
+
}
|
|
708
|
+
|
|
682
709
|
/** Older user turns with no persisted assistant commit — Restore still uses the user message id. */
|
|
683
710
|
function canRestoreLegacyUserTurn(turn: ChatTurn): boolean {
|
|
684
711
|
if (!turn.user) return false;
|
|
@@ -1436,11 +1463,10 @@
|
|
|
1436
1463
|
use:detectMessagesScrollbar
|
|
1437
1464
|
onscroll={handleScroll}
|
|
1438
1465
|
>
|
|
1439
|
-
<!-- Empty state
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
{#if isInitialized && messages.length === 0 && !isLoading && !isGenerating}
|
|
1466
|
+
<!-- Empty state stays out of the document until the parent has finished reading
|
|
1467
|
+
messages and found none. A generation in flight hides it too: the user
|
|
1468
|
+
bubble lands a tick after send, so the list is briefly empty again. -->
|
|
1469
|
+
{#if showEmptyState && !isLoading && !isGenerating}
|
|
1444
1470
|
<div class="empty-state-ct flex flex-col items-center justify-center text-center max-w-sm w-full" style="align-self: center;">
|
|
1445
1471
|
<h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">💬 {$t('chat.messages.startTitle')}</h3>
|
|
1446
1472
|
<p class="text-gray-600 dark:text-gray-400 text-sm mb-6">
|
|
@@ -1560,6 +1586,38 @@
|
|
|
1560
1586
|
{versionLabelText(versionLabel, $t)}
|
|
1561
1587
|
</span>
|
|
1562
1588
|
{/if}
|
|
1589
|
+
{#if onRateVersion && !isLoading}
|
|
1590
|
+
{@const ratedMessageId = ratableVersionReplyId(turn)}
|
|
1591
|
+
{#if ratedMessageId}
|
|
1592
|
+
{@const givenRating = versionRatings[ratedMessageId]}
|
|
1593
|
+
<span class="wc-version-rating inline-flex items-center gap-1" role="group" aria-label={$t('chat.messages.rateGroup')}>
|
|
1594
|
+
<button
|
|
1595
|
+
type="button"
|
|
1596
|
+
class="wc-version-rating-btn wc-version-rating-up"
|
|
1597
|
+
aria-pressed={givenRating === 'up'}
|
|
1598
|
+
aria-label={$t('chat.messages.rateUp')}
|
|
1599
|
+
title={$t('chat.messages.rateUp')}
|
|
1600
|
+
onclick={() => onRateVersion?.(ratedMessageId, 'up')}
|
|
1601
|
+
>
|
|
1602
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill={givenRating === 'up' ? 'currentColor' : 'none'} stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
1603
|
+
<path d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3" />
|
|
1604
|
+
</svg>
|
|
1605
|
+
</button>
|
|
1606
|
+
<button
|
|
1607
|
+
type="button"
|
|
1608
|
+
class="wc-version-rating-btn wc-version-rating-down"
|
|
1609
|
+
aria-pressed={givenRating === 'down'}
|
|
1610
|
+
aria-label={$t('chat.messages.rateDown')}
|
|
1611
|
+
title={$t('chat.messages.rateDown')}
|
|
1612
|
+
onclick={() => onRateVersion?.(ratedMessageId, 'down')}
|
|
1613
|
+
>
|
|
1614
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill={givenRating === 'down' ? 'currentColor' : 'none'} stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
1615
|
+
<path d="M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17" />
|
|
1616
|
+
</svg>
|
|
1617
|
+
</button>
|
|
1618
|
+
</span>
|
|
1619
|
+
{/if}
|
|
1620
|
+
{/if}
|
|
1563
1621
|
{#if showCommitMeta && getTurnCommitShort(turn)}
|
|
1564
1622
|
<span class="wc-user-commit-sha whitespace-nowrap font-mono text-xs text-gray-500">
|
|
1565
1623
|
{$t('chat.messages.commitId', { id: getTurnCommitShort(turn) ?? '' })}
|
|
@@ -1867,6 +1925,44 @@
|
|
|
1867
1925
|
cursor: not-allowed;
|
|
1868
1926
|
pointer-events: none;
|
|
1869
1927
|
}
|
|
1928
|
+
|
|
1929
|
+
/* The thumbs next to a version's name. A pressed thumb is filled and takes the colour of what it says. */
|
|
1930
|
+
.wc-version-rating-btn {
|
|
1931
|
+
display: inline-flex;
|
|
1932
|
+
align-items: center;
|
|
1933
|
+
justify-content: center;
|
|
1934
|
+
width: 22px;
|
|
1935
|
+
height: 22px;
|
|
1936
|
+
padding: 0;
|
|
1937
|
+
background: transparent;
|
|
1938
|
+
color: #9ca3af;
|
|
1939
|
+
border: 1px solid transparent;
|
|
1940
|
+
border-radius: 6px;
|
|
1941
|
+
cursor: pointer;
|
|
1942
|
+
transition: background-color 0.15s ease, color 0.15s ease, border-color 0.15s ease;
|
|
1943
|
+
}
|
|
1944
|
+
|
|
1945
|
+
.wc-version-rating-btn:hover {
|
|
1946
|
+
background: rgba(0, 0, 0, 0.06);
|
|
1947
|
+
color: #555;
|
|
1948
|
+
}
|
|
1949
|
+
|
|
1950
|
+
.wc-version-rating-btn:focus-visible {
|
|
1951
|
+
outline: 2px solid #93c5fd;
|
|
1952
|
+
outline-offset: 1px;
|
|
1953
|
+
}
|
|
1954
|
+
|
|
1955
|
+
.wc-version-rating-btn[aria-pressed='true'].wc-version-rating-up {
|
|
1956
|
+
color: #15803d;
|
|
1957
|
+
background: #f0fdf4;
|
|
1958
|
+
border-color: #bbf7d0;
|
|
1959
|
+
}
|
|
1960
|
+
|
|
1961
|
+
.wc-version-rating-btn[aria-pressed='true'].wc-version-rating-down {
|
|
1962
|
+
color: #b91c1c;
|
|
1963
|
+
background: #fef2f2;
|
|
1964
|
+
border-color: #fecaca;
|
|
1965
|
+
}
|
|
1870
1966
|
|
|
1871
1967
|
.retry-codegen-btn {
|
|
1872
1968
|
color: #b91c1c;
|
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
import type { ChatMessage, ChatContext } from '../types/index.js';
|
|
2
|
-
import type { ClarificationSuggestion, DesignControlRequest } from '../types/message.js';
|
|
2
|
+
import type { ClarificationSuggestion, DesignControlRequest, VersionRating } from '../types/message.js';
|
|
3
|
+
import { type VersionThumb } from '../utils/versionRatings.js';
|
|
3
4
|
import type { Snippet } from 'svelte';
|
|
4
5
|
interface Props {
|
|
5
6
|
class?: string;
|
|
6
7
|
messages: ChatMessage[];
|
|
7
8
|
isLoading?: boolean;
|
|
8
|
-
/** True after the conversation list/messages finished initializing
|
|
9
|
+
/** True after the conversation list/messages finished initializing. */
|
|
9
10
|
isInitialized?: boolean;
|
|
11
|
+
/**
|
|
12
|
+
* The empty-state suggestions. Stays false from the first paint.
|
|
13
|
+
* The parent sets it only after the message read, and only when that read was empty.
|
|
14
|
+
*/
|
|
15
|
+
showEmptyState?: boolean;
|
|
10
16
|
context: ChatContext;
|
|
11
17
|
isCompleted?: boolean;
|
|
12
18
|
/**
|
|
@@ -53,6 +59,13 @@ interface Props {
|
|
|
53
59
|
generationStream?: string;
|
|
54
60
|
onSuggestionSelected?: (suggestion: string) => void;
|
|
55
61
|
onRestoreCheckpoint?: (messageId: string, messageIndex: number) => void;
|
|
62
|
+
/**
|
|
63
|
+
* Gives each version a thumbs up and a thumbs down next to its name. Called with the id of the assistant message that
|
|
64
|
+
* announced the version and the thumb that was pressed; the host keeps the rating. Without it no thumbs are drawn.
|
|
65
|
+
*/
|
|
66
|
+
onRateVersion?: (messageId: string, pressed: VersionThumb) => void;
|
|
67
|
+
/** The rating each version has, by the id of the message that announced it: what the thumbs show as pressed. */
|
|
68
|
+
versionRatings?: Record<string, VersionRating>;
|
|
56
69
|
onRetryMessage?: (content: string) => void;
|
|
57
70
|
/**
|
|
58
71
|
* What the "Upgrade" button of a failure about the plan or the credits does. Without it the button opens the
|
package/dist/i18n/messages.d.ts
CHANGED
|
@@ -58,6 +58,10 @@ export declare const CHAT_MESSAGES: {
|
|
|
58
58
|
readonly 'chat.messages.restore': "Restore Checkpoint";
|
|
59
59
|
readonly 'chat.messages.restoreTitle': "Restore widget code to this prompt's commit";
|
|
60
60
|
readonly 'chat.messages.alreadyHead': "This checkpoint is already HEAD";
|
|
61
|
+
/** The two thumbs next to a version's name, when the page gave the chat a way to keep a rating (`onRateVersion`). */
|
|
62
|
+
readonly 'chat.messages.rateGroup': "Rate this version";
|
|
63
|
+
readonly 'chat.messages.rateUp': "This version is good";
|
|
64
|
+
readonly 'chat.messages.rateDown': "This version is not good";
|
|
61
65
|
/**
|
|
62
66
|
* Versions are named "Version 4" between the page and the chat, and in the lines the chat saves ("Restored from Version
|
|
63
67
|
* 4"): the chat reads the number out of those words. It says them again in the page's language with these three.
|
package/dist/i18n/messages.js
CHANGED
|
@@ -62,6 +62,10 @@ export const CHAT_MESSAGES = {
|
|
|
62
62
|
'chat.messages.restore': 'Restore Checkpoint',
|
|
63
63
|
'chat.messages.restoreTitle': 'Restore widget code to this prompt\'s commit',
|
|
64
64
|
'chat.messages.alreadyHead': 'This checkpoint is already HEAD',
|
|
65
|
+
/** The two thumbs next to a version's name, when the page gave the chat a way to keep a rating (`onRateVersion`). */
|
|
66
|
+
'chat.messages.rateGroup': 'Rate this version',
|
|
67
|
+
'chat.messages.rateUp': 'This version is good',
|
|
68
|
+
'chat.messages.rateDown': 'This version is not good',
|
|
65
69
|
/**
|
|
66
70
|
* Versions are named "Version 4" between the page and the chat, and in the lines the chat saves ("Restored from Version
|
|
67
71
|
* 4"): the chat reads the number out of those words. It says them again in the page's language with these three.
|
package/dist/types/message.d.ts
CHANGED
|
@@ -86,6 +86,12 @@ export interface DesignControlRequest {
|
|
|
86
86
|
*/
|
|
87
87
|
compositionId?: string | null;
|
|
88
88
|
}
|
|
89
|
+
/**
|
|
90
|
+
* What a person says about a version of a widget with the thumbs next to the version's name: `up`, `down`, or `none`
|
|
91
|
+
* to take the rating back. The chat tells the host with `onRateVersion`; the three words are the ones the gateway's
|
|
92
|
+
* rating call takes, so a host can pass them on as they are.
|
|
93
|
+
*/
|
|
94
|
+
export type VersionRating = 'up' | 'down' | 'none';
|
|
89
95
|
/** One suggestion chip on a clarification card — display copy plus the
|
|
90
96
|
* machine-readable behavior of tapping it. The client keys off `intent`;
|
|
91
97
|
* `label` is never parsed. */
|
package/dist/utils/index.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
export { fileTypeConfig, detectFileType, validateFile, validateFiles, formatFileSize, getFileExtension, generateFileId, createFilePreview, createPendingAttachment, getAcceptString, supportsPreview, getFileIcon, compressImage } from './fileUtils.js';
|
|
2
|
+
export { VERSION_RATINGS, ratingAfterPress, ratingOfVersion, isRatableVersionReply } from './versionRatings.js';
|
|
3
|
+
export type { VersionThumb } from './versionRatings.js';
|
|
2
4
|
export { setLogsEnabled, chatLog, chatWarn, chatError } from './logger.js';
|
|
3
5
|
export type { AttachmentType, AttachmentValidation, PendingAttachment, UploadStatus } from '../types/index.js';
|
package/dist/utils/index.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
// File utilities
|
|
2
2
|
export { fileTypeConfig, detectFileType, validateFile, validateFiles, formatFileSize, getFileExtension, generateFileId, createFilePreview, createPendingAttachment, getAcceptString, supportsPreview, getFileIcon, compressImage } from './fileUtils.js';
|
|
3
|
+
// The thumbs next to a version
|
|
4
|
+
export { VERSION_RATINGS, ratingAfterPress, ratingOfVersion, isRatableVersionReply } from './versionRatings.js';
|
|
3
5
|
// Logger
|
|
4
6
|
export { setLogsEnabled, chatLog, chatWarn, chatError } from './logger.js';
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file versionRatings.ts
|
|
3
|
+
* @description The rules of the thumbs next to a version in the chat, kept out of the components so they can be tested on their own:
|
|
4
|
+
* what a press of a thumb makes of the rating a version has, and which reply can be rated at all.
|
|
5
|
+
*
|
|
6
|
+
* A version is the assistant message that announced a commit of the widget. That message is what a rating is given to, and its id is what
|
|
7
|
+
* the host passes on, so only a message that was saved can carry one.
|
|
8
|
+
*/
|
|
9
|
+
import type { ChatMessage, VersionRating } from '../types/index.js';
|
|
10
|
+
/** What a person can press. */
|
|
11
|
+
export type VersionThumb = 'up' | 'down';
|
|
12
|
+
/** The three words a host is told, in the order they are listed in the documentation. */
|
|
13
|
+
export declare const VERSION_RATINGS: readonly VersionRating[];
|
|
14
|
+
/**
|
|
15
|
+
* What a press of a thumb makes of the rating a version has. The thumb that is already chosen takes the rating back when it is
|
|
16
|
+
* pressed again (`none`); the other thumb replaces it.
|
|
17
|
+
*/
|
|
18
|
+
export declare function ratingAfterPress(current: VersionRating, pressed: VersionThumb): VersionRating;
|
|
19
|
+
/**
|
|
20
|
+
* Whether the reply that announces a version can be rated: it has an id the host's backend knows (it was saved, it is not a stand-in the
|
|
21
|
+
* chat made up and not a copy Restore made), it did not fail, and it was not undone by a restore.
|
|
22
|
+
*/
|
|
23
|
+
export declare function isRatableVersionReply(reply: Pick<ChatMessage, 'id' | '_optimistic' | '_failed' | 'rolledBackAt'> | null | undefined): boolean;
|
|
24
|
+
/**
|
|
25
|
+
* The rating a version has: the person's latest press in this chat, else what the host seeded (a host that keeps ratings gives them
|
|
26
|
+
* back when the chat opens again), else none. A word that is not one of the three is no word.
|
|
27
|
+
*/
|
|
28
|
+
export declare function ratingOfVersion(messageId: string, chosen: Readonly<Record<string, VersionRating>>, seeded: Readonly<Record<string, VersionRating>>): VersionRating;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** The three words a host is told, in the order they are listed in the documentation. */
|
|
2
|
+
export const VERSION_RATINGS = ['up', 'down', 'none'];
|
|
3
|
+
/**
|
|
4
|
+
* What a press of a thumb makes of the rating a version has. The thumb that is already chosen takes the rating back when it is
|
|
5
|
+
* pressed again (`none`); the other thumb replaces it.
|
|
6
|
+
*/
|
|
7
|
+
export function ratingAfterPress(current, pressed) {
|
|
8
|
+
return current === pressed ? 'none' : pressed;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* The ids the chat makes up for messages that are not a version saved by a generation: the copy Restore appends (`version-fork-…`)
|
|
12
|
+
* and the stand-in the chat draws while the widget's head is ahead of every saved message (`fallback-head-…`).
|
|
13
|
+
*/
|
|
14
|
+
const ID_PREFIXES_OF_STAND_INS = ['version-fork-', 'fallback-head-'];
|
|
15
|
+
/**
|
|
16
|
+
* Whether the reply that announces a version can be rated: it has an id the host's backend knows (it was saved, it is not a stand-in the
|
|
17
|
+
* chat made up and not a copy Restore made), it did not fail, and it was not undone by a restore.
|
|
18
|
+
*/
|
|
19
|
+
export function isRatableVersionReply(reply) {
|
|
20
|
+
if (!reply || typeof reply.id !== 'string' || reply.id === '')
|
|
21
|
+
return false;
|
|
22
|
+
if (reply._optimistic === true || reply._failed === true)
|
|
23
|
+
return false;
|
|
24
|
+
if (reply.rolledBackAt)
|
|
25
|
+
return false;
|
|
26
|
+
return !ID_PREFIXES_OF_STAND_INS.some((prefix) => reply.id.startsWith(prefix));
|
|
27
|
+
}
|
|
28
|
+
/** A word of a record that is its own: an id never reads a name every object has (`constructor`, `toString`). */
|
|
29
|
+
function ownRating(ratings, messageId) {
|
|
30
|
+
if (!Object.prototype.hasOwnProperty.call(ratings, messageId))
|
|
31
|
+
return undefined;
|
|
32
|
+
const rating = ratings[messageId];
|
|
33
|
+
return VERSION_RATINGS.includes(rating) ? rating : undefined;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* The rating a version has: the person's latest press in this chat, else what the host seeded (a host that keeps ratings gives them
|
|
37
|
+
* back when the chat opens again), else none. A word that is not one of the three is no word.
|
|
38
|
+
*/
|
|
39
|
+
export function ratingOfVersion(messageId, chosen, seeded) {
|
|
40
|
+
return ownRating(chosen, messageId) ?? ownRating(seeded, messageId) ?? 'none';
|
|
41
|
+
}
|