@widgetic/chat 0.1.35 → 0.1.37

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.
Files changed (35) hide show
  1. package/README.md +34 -6
  2. package/dist/components/ActionBar.svelte +8 -0
  3. package/dist/components/Chat.svelte +120 -106
  4. package/dist/components/Chat.svelte.d.ts +19 -1
  5. package/dist/components/ChatComposer.svelte +166 -0
  6. package/dist/components/ChatComposer.svelte.d.ts +30 -0
  7. package/dist/components/ChatMessages.svelte +483 -393
  8. package/dist/components/ChatMessages.svelte.d.ts +16 -6
  9. package/dist/components/IconButton.svelte +125 -0
  10. package/dist/components/IconButton.svelte.d.ts +22 -0
  11. package/dist/components/MessageActions.svelte +48 -0
  12. package/dist/components/MessageActions.svelte.d.ts +13 -0
  13. package/dist/components/PanelChatHeader.svelte +79 -0
  14. package/dist/components/PanelChatHeader.svelte.d.ts +19 -0
  15. package/dist/components/PanelFollowUpSuggestions.svelte +34 -0
  16. package/dist/components/PanelFollowUpSuggestions.svelte.d.ts +8 -0
  17. package/dist/components/PanelSuggestionButtons.svelte +60 -0
  18. package/dist/components/PanelSuggestionButtons.svelte.d.ts +10 -0
  19. package/dist/components/SuggestionButtons.svelte +11 -163
  20. package/dist/i18n/index.d.ts +1 -1
  21. package/dist/i18n/index.js +1 -1
  22. package/dist/i18n/messages.d.ts +54 -13
  23. package/dist/i18n/messages.js +54 -13
  24. package/dist/i18n/suggestions.d.ts +6 -0
  25. package/dist/i18n/suggestions.js +24 -0
  26. package/dist/types/message.d.ts +7 -0
  27. package/dist/utils/generationActivity.d.ts +12 -0
  28. package/dist/utils/generationActivity.js +47 -0
  29. package/dist/utils/generationPlan.d.ts +32 -0
  30. package/dist/utils/generationPlan.js +89 -0
  31. package/dist/utils/index.d.ts +4 -0
  32. package/dist/utils/index.js +2 -0
  33. package/dist/utils/messageActions.d.ts +54 -0
  34. package/dist/utils/messageActions.js +104 -0
  35. package/package.json +3 -3
@@ -0,0 +1,89 @@
1
+ const MAX_PLAN_TASKS = 20;
2
+ function isRecord(value) {
3
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
4
+ }
5
+ function coerceTaskStatus(status) {
6
+ if (status === 'in_progress')
7
+ return 'active';
8
+ if (status === 'done')
9
+ return 'done';
10
+ if (status === 'failed')
11
+ return 'pending';
12
+ return 'pending';
13
+ }
14
+ function coerceLabel(label) {
15
+ if (typeof label === 'string')
16
+ return label;
17
+ if (label == null)
18
+ return '';
19
+ return String(label);
20
+ }
21
+ function parseWidgetPlan(value) {
22
+ if (!isRecord(value))
23
+ return null;
24
+ if (!Array.isArray(value.tasks))
25
+ return null;
26
+ const tasks = [];
27
+ for (const raw of value.tasks) {
28
+ if (!isRecord(raw))
29
+ continue;
30
+ if (typeof raw.id !== 'string' || raw.id.trim() === '')
31
+ continue;
32
+ tasks.push({
33
+ id: raw.id,
34
+ label: coerceLabel(raw.label),
35
+ ...(typeof raw.kind === 'string' ? { kind: raw.kind } : {}),
36
+ status: ['pending', 'in_progress', 'done', 'failed'].includes(raw.status)
37
+ ? raw.status
38
+ : 'pending',
39
+ });
40
+ if (tasks.length >= MAX_PLAN_TASKS)
41
+ break;
42
+ }
43
+ if (tasks.length === 0)
44
+ return null;
45
+ const title = typeof value.title === 'string' ? value.title : '';
46
+ const completed = typeof value.completed === 'number' && Number.isFinite(value.completed)
47
+ ? Math.max(0, Math.floor(value.completed))
48
+ : undefined;
49
+ const activeIndex = value.activeIndex === null
50
+ ? null
51
+ : typeof value.activeIndex === 'number' && Number.isFinite(value.activeIndex)
52
+ ? Math.floor(value.activeIndex)
53
+ : undefined;
54
+ return {
55
+ title,
56
+ tasks,
57
+ ...(completed !== undefined ? { completed } : {}),
58
+ ...(activeIndex !== undefined ? { activeIndex } : {}),
59
+ ...(value.decisions !== undefined ? { decisions: value.decisions } : {}),
60
+ };
61
+ }
62
+ /**
63
+ * Reads `metadata.plan`. Missing key → `undefined` (leave UI as-is); `null` → hide; bad shape → `null`.
64
+ */
65
+ export function readGenerationPlanFromMetadata(metadata) {
66
+ if (!metadata || !Object.prototype.hasOwnProperty.call(metadata, 'plan'))
67
+ return undefined;
68
+ if (metadata.plan === null)
69
+ return null;
70
+ return parseWidgetPlan(metadata.plan);
71
+ }
72
+ /** Maps gateway plan data to {@link PlanCard} props, or `null` when nothing should render. */
73
+ export function mapWidgetPlanToPlanCard(plan, fallbackTitle) {
74
+ if (!plan.tasks.length)
75
+ return null;
76
+ const tasks = plan.tasks.slice(0, MAX_PLAN_TASKS).map((task) => ({
77
+ id: task.id,
78
+ label: coerceLabel(task.label),
79
+ status: coerceTaskStatus(task.status),
80
+ }));
81
+ const progressTotal = tasks.length;
82
+ const doneCount = tasks.filter((t) => t.status === 'done').length;
83
+ const progressCurrent = typeof plan.completed === 'number' && Number.isFinite(plan.completed)
84
+ ? Math.min(progressTotal, Math.max(0, Math.floor(plan.completed)))
85
+ : doneCount;
86
+ const trimmedTitle = plan.title.trim();
87
+ const title = trimmedTitle.length > 0 ? trimmedTitle : fallbackTitle;
88
+ return { title, tasks, progressCurrent, progressTotal };
89
+ }
@@ -2,4 +2,8 @@ export { fileTypeConfig, detectFileType, validateFile, validateFiles, formatFile
2
2
  export { VERSION_RATINGS, ratingAfterPress, ratingOfVersion, isRatableVersionReply } from './versionRatings.js';
3
3
  export type { VersionThumb } from './versionRatings.js';
4
4
  export { setLogsEnabled, chatLog, chatWarn, chatError } from './logger.js';
5
+ export { readThinkingTail, readCodegenStreamTail, generationActivityPhase, thoughtDurationSeconds, generationActivityAriaKey, } from './generationActivity.js';
6
+ export type { GenerationActivityPhase } from './generationActivity.js';
7
+ export { readGenerationPlanFromMetadata, mapWidgetPlanToPlanCard, } from './generationPlan.js';
8
+ export type { GenerationPlanWire, MappedGenerationPlanCard, WidgetPlanTaskStatusWire, } from './generationPlan.js';
5
9
  export type { AttachmentType, AttachmentValidation, PendingAttachment, UploadStatus } from '../types/index.js';
@@ -4,3 +4,5 @@ export { fileTypeConfig, detectFileType, validateFile, validateFiles, formatFile
4
4
  export { VERSION_RATINGS, ratingAfterPress, ratingOfVersion, isRatableVersionReply } from './versionRatings.js';
5
5
  // Logger
6
6
  export { setLogsEnabled, chatLog, chatWarn, chatError } from './logger.js';
7
+ export { readThinkingTail, readCodegenStreamTail, generationActivityPhase, thoughtDurationSeconds, generationActivityAriaKey, } from './generationActivity.js';
8
+ export { readGenerationPlanFromMetadata, mapWidgetPlanToPlanCard, } from './generationPlan.js';
@@ -0,0 +1,54 @@
1
+ /**
2
+ * What a turn's copy icon copies: the words the assistant said under the person's message, in order, else the title of the commit the
3
+ * turn made (a build says nothing in words; "Add the pricing cards" is what it shipped). '' when there is nothing to copy, and the icon
4
+ * is then left out.
5
+ */
6
+ export declare function textToCopy(spokenLines: readonly string[], commitTitle: string | null | undefined): string;
7
+ /**
8
+ * Puts `text` on the clipboard. The Clipboard API first; a page that embeds the chat without the permission for it (a frame with no
9
+ * `clipboard-write`) refuses it, and the old way (select a hidden field, `copy`) still works from a click there.
10
+ *
11
+ * Resolves true when the text was copied. Never throws: a failure is one line in the console, and the icon simply does not say "Copied".
12
+ */
13
+ export declare function copyTextToClipboard(text: string): Promise<boolean>;
14
+ /**
15
+ * A message the chat made up for itself carries an id like `assistant_1762500000000_k3j9x2a1b` until the host has saved it and told
16
+ * the chat the real one. The host's backend does not know such an id, so it cannot be asked to restore to it.
17
+ */
18
+ export declare function isLocalMessageId(messageId: string | null | undefined): boolean;
19
+ /**
20
+ * What one turn of the list is, as a place to go back to:
21
+ * - `none`: it made no version (a question, a prompt that failed), so it is no place to go back to and no mark on the way.
22
+ * - `blocked`: it made one, but the host cannot be asked for it by an id that is safe to send (an older version the chat only lists, a
23
+ * version a restore already undid, a reply that is not saved yet). Nothing before it is offered either: going back to the wrong
24
+ * version would be worse than not offering to go back.
25
+ * - `version`: a saved reply announced its commit; `replyId` is that reply. `wearsIcon` is whether the person's message of the turn gets
26
+ * the restore icon (the copy a restore appends is a place to go back TO, but not a message to go back before). `isLatest` is whether
27
+ * the widget sits on this version now.
28
+ */
29
+ export type TurnRestorePoint = {
30
+ kind: 'none';
31
+ } | {
32
+ kind: 'blocked';
33
+ } | {
34
+ kind: 'version';
35
+ replyId: string;
36
+ wearsIcon: boolean;
37
+ isLatest: boolean;
38
+ };
39
+ /**
40
+ * The id of the saved reply the host is asked to restore when the restore icon of turn `turnIndex` is pressed, or null when that turn
41
+ * has no such icon.
42
+ *
43
+ * The icon sits on a message the person sent and means "go back to before this message": the widget as it was after the nearest
44
+ * earlier turn that made a version. That version is what the host restores (its message id is the checkpoint; the gateway puts the code
45
+ * back to the commit that turn made). Turns that made no version are stepped over: a question in between changed nothing.
46
+ *
47
+ * - The turn itself must be a version that wears the icon: a prompt that failed or a copy a restore appended has nothing to go back from.
48
+ * - When the nearest earlier version is `blocked`, there is no safe id to ask for, so there is no icon (null) and never a version
49
+ * further back.
50
+ * - The first version has nothing before it. While it is the one the widget sits on, the host is asked for its own reply, which is
51
+ * what the restore of the first message always did (the gateway undoes the generation: the board with the drawing). Once later
52
+ * versions exist, the gateway would give back the first version itself, not what came before it, so there is no icon.
53
+ */
54
+ export declare function restoreBeforeTarget(points: readonly TurnRestorePoint[], turnIndex: number): string | null;
@@ -0,0 +1,104 @@
1
+ /**
2
+ * @file messageActions.ts
3
+ * @description The rules of the icons the chat draws around its messages, kept out of the components so they can be tested on their own:
4
+ *
5
+ * - what the copy icon puts on the clipboard for a turn (`textToCopy`), and how it gets there (`copyTextToClipboard`);
6
+ * - which saved reply the host is asked to restore when the person presses the restore icon on one of their own messages, so the widget
7
+ * goes back to how it was BEFORE that message (`restoreBeforeTarget`).
8
+ *
9
+ * Pure apart from the clipboard: arrays and strings in, ids and strings out.
10
+ */
11
+ import { chatWarn } from './logger.js';
12
+ // --- copy ---------------------------------------------------------------------------------------------------
13
+ /**
14
+ * What a turn's copy icon copies: the words the assistant said under the person's message, in order, else the title of the commit the
15
+ * turn made (a build says nothing in words; "Add the pricing cards" is what it shipped). '' when there is nothing to copy, and the icon
16
+ * is then left out.
17
+ */
18
+ export function textToCopy(spokenLines, commitTitle) {
19
+ const spoken = spokenLines.map((line) => line.trim()).filter((line) => line !== '');
20
+ if (spoken.length > 0)
21
+ return spoken.join('\n\n');
22
+ return (commitTitle ?? '').trim();
23
+ }
24
+ /**
25
+ * Puts `text` on the clipboard. The Clipboard API first; a page that embeds the chat without the permission for it (a frame with no
26
+ * `clipboard-write`) refuses it, and the old way (select a hidden field, `copy`) still works from a click there.
27
+ *
28
+ * Resolves true when the text was copied. Never throws: a failure is one line in the console, and the icon simply does not say "Copied".
29
+ */
30
+ export async function copyTextToClipboard(text) {
31
+ if (text === '')
32
+ return false;
33
+ try {
34
+ if (typeof navigator !== 'undefined' && typeof navigator.clipboard?.writeText === 'function') {
35
+ await navigator.clipboard.writeText(text);
36
+ return true;
37
+ }
38
+ }
39
+ catch (error) {
40
+ chatWarn('[Chat] The clipboard did not take the text, trying the old way:', error);
41
+ }
42
+ return copyThroughSelection(text);
43
+ }
44
+ /** The old way: select the text in a hidden field and run the browser's `copy` command. */
45
+ function copyThroughSelection(text) {
46
+ if (typeof document === 'undefined' || !document.body)
47
+ return false;
48
+ const field = document.createElement('textarea');
49
+ field.value = text;
50
+ field.setAttribute('readonly', '');
51
+ field.setAttribute('aria-hidden', 'true');
52
+ field.style.position = 'fixed';
53
+ field.style.top = '0';
54
+ field.style.insetInlineStart = '0';
55
+ field.style.opacity = '0';
56
+ field.style.pointerEvents = 'none';
57
+ document.body.appendChild(field);
58
+ try {
59
+ field.select();
60
+ return document.execCommand('copy') === true;
61
+ }
62
+ catch (error) {
63
+ chatWarn('[Chat] The text could not be copied:', error);
64
+ return false;
65
+ }
66
+ finally {
67
+ field.remove();
68
+ }
69
+ }
70
+ // --- restore ------------------------------------------------------------------------------------------------
71
+ /**
72
+ * A message the chat made up for itself carries an id like `assistant_1762500000000_k3j9x2a1b` until the host has saved it and told
73
+ * the chat the real one. The host's backend does not know such an id, so it cannot be asked to restore to it.
74
+ */
75
+ export function isLocalMessageId(messageId) {
76
+ return /^(assistant|user)_\d{10,}_[a-z0-9]+$/.test(String(messageId ?? ''));
77
+ }
78
+ /**
79
+ * The id of the saved reply the host is asked to restore when the restore icon of turn `turnIndex` is pressed, or null when that turn
80
+ * has no such icon.
81
+ *
82
+ * The icon sits on a message the person sent and means "go back to before this message": the widget as it was after the nearest
83
+ * earlier turn that made a version. That version is what the host restores (its message id is the checkpoint; the gateway puts the code
84
+ * back to the commit that turn made). Turns that made no version are stepped over: a question in between changed nothing.
85
+ *
86
+ * - The turn itself must be a version that wears the icon: a prompt that failed or a copy a restore appended has nothing to go back from.
87
+ * - When the nearest earlier version is `blocked`, there is no safe id to ask for, so there is no icon (null) and never a version
88
+ * further back.
89
+ * - The first version has nothing before it. While it is the one the widget sits on, the host is asked for its own reply, which is
90
+ * what the restore of the first message always did (the gateway undoes the generation: the board with the drawing). Once later
91
+ * versions exist, the gateway would give back the first version itself, not what came before it, so there is no icon.
92
+ */
93
+ export function restoreBeforeTarget(points, turnIndex) {
94
+ const own = points[turnIndex];
95
+ if (!own || own.kind !== 'version' || !own.wearsIcon)
96
+ return null;
97
+ for (let index = turnIndex - 1; index >= 0; index--) {
98
+ const earlier = points[index];
99
+ if (earlier.kind === 'none')
100
+ continue;
101
+ return earlier.kind === 'version' ? earlier.replyId : null;
102
+ }
103
+ return own.isLatest ? own.replyId : null;
104
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/chat",
3
- "version": "0.1.35",
3
+ "version": "0.1.37",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -57,7 +57,7 @@
57
57
  },
58
58
  "peerDependencies": {
59
59
  "@widgetic/api-sdk": "*",
60
- "@widgetic/design-system": ">=0.3.0",
60
+ "@widgetic/design-system": ">=0.5.27",
61
61
  "svelte": "^5.25.6"
62
62
  },
63
63
  "dependencies": {
@@ -73,7 +73,7 @@
73
73
  "@tailwindcss/postcss": "^4.1.4",
74
74
  "@types/node": "^26.4.1",
75
75
  "@widgetic/api-sdk": "^1.0.10",
76
- "@widgetic/design-system": "^0.5.17",
76
+ "@widgetic/design-system": "^0.5.23",
77
77
  "@widgetic/dev-tools": "^0.2.0",
78
78
  "autoprefixer": "^10.4.20",
79
79
  "eslint": "^9.0.0",