@widgetic/chat 0.1.42 → 0.1.44

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 (85) hide show
  1. package/README.md +461 -6
  2. package/dist/components/Chat.svelte +1078 -87
  3. package/dist/components/Chat.svelte.d.ts +102 -2
  4. package/dist/components/ChatComposer.svelte +382 -9
  5. package/dist/components/ChatComposer.svelte.d.ts +66 -3
  6. package/dist/components/ChatMessageQueue.svelte +56 -0
  7. package/dist/components/ChatMessageQueue.svelte.d.ts +20 -0
  8. package/dist/components/ChatMessages.svelte +485 -50
  9. package/dist/components/ChatMessages.svelte.d.ts +45 -2
  10. package/dist/components/ComposerAttachmentsTray.svelte +42 -10
  11. package/dist/components/ComposerAttachmentsTray.svelte.d.ts +5 -0
  12. package/dist/components/ComposerMentionChips.svelte +53 -0
  13. package/dist/components/ComposerMentionChips.svelte.d.ts +15 -0
  14. package/dist/components/FollowUpCard.svelte +134 -0
  15. package/dist/components/FollowUpCard.svelte.d.ts +17 -0
  16. package/dist/components/MentionChip.svelte +41 -0
  17. package/dist/components/MentionChip.svelte.d.ts +12 -0
  18. package/dist/components/MentionMenu.svelte +114 -0
  19. package/dist/components/MentionMenu.svelte.d.ts +19 -0
  20. package/dist/components/agent/AgentAvatar.svelte +6 -4
  21. package/dist/components/agent/AgentAvatar.svelte.d.ts +1 -1
  22. package/dist/components/agent/CodeCard.svelte +122 -27
  23. package/dist/components/agent/CodeCard.svelte.d.ts +3 -0
  24. package/dist/components/agent/CodeDiff.svelte +180 -0
  25. package/dist/components/agent/CodeDiff.svelte.d.ts +10 -0
  26. package/dist/components/agent/GenerationModule.svelte +13 -2
  27. package/dist/components/agent/GenerationModule.svelte.d.ts +3 -0
  28. package/dist/components/index.d.ts +4 -0
  29. package/dist/components/index.js +9 -0
  30. package/dist/errors/logTechnicalUserError.d.ts +1 -0
  31. package/dist/errors/logTechnicalUserError.js +37 -0
  32. package/dist/i18n/messages.d.ts +106 -1
  33. package/dist/i18n/messages.js +112 -1
  34. package/dist/i18n/sketchLocales.js +8 -8
  35. package/dist/messageQueue.d.ts +83 -0
  36. package/dist/messageQueue.js +84 -0
  37. package/dist/services/index.d.ts +1 -1
  38. package/dist/services/sketchAssistantClient.d.ts +27 -0
  39. package/dist/services/sketchAssistantClient.js +7 -2
  40. package/dist/services/sketchAssistantErrors.d.ts +4 -0
  41. package/dist/services/sketchAssistantErrors.js +22 -0
  42. package/dist/services/sketchAssistantOrchestrator.d.ts +7 -7
  43. package/dist/services/sketchAssistantOrchestrator.js +11 -24
  44. package/dist/services/sketchAssistantReply.js +3 -1
  45. package/dist/stores/chatStore.d.ts +5 -0
  46. package/dist/stores/chatStore.js +21 -0
  47. package/dist/types/agent.d.ts +4 -3
  48. package/dist/types/attachment.d.ts +16 -0
  49. package/dist/types/config.d.ts +6 -0
  50. package/dist/types/index.d.ts +1 -0
  51. package/dist/types/index.js +2 -0
  52. package/dist/types/mention.d.ts +40 -0
  53. package/dist/types/mention.js +8 -0
  54. package/dist/types/message.d.ts +60 -1
  55. package/dist/utils/agentTurn.d.ts +40 -9
  56. package/dist/utils/agentTurn.js +43 -11
  57. package/dist/utils/attachmentProgress.d.ts +12 -0
  58. package/dist/utils/attachmentProgress.js +18 -0
  59. package/dist/utils/bubbleRichFit.d.ts +68 -0
  60. package/dist/utils/bubbleRichFit.js +45 -0
  61. package/dist/utils/bubbleShrinkWrap.d.ts +8 -1
  62. package/dist/utils/bubbleShrinkWrap.js +113 -17
  63. package/dist/utils/codeChanges.d.ts +103 -0
  64. package/dist/utils/codeChanges.js +226 -0
  65. package/dist/utils/codeHighlight.js +1 -0
  66. package/dist/utils/codeStreamFormat.d.ts +5 -2
  67. package/dist/utils/composerMentions.d.ts +96 -0
  68. package/dist/utils/composerMentions.js +217 -0
  69. package/dist/utils/followUps.d.ts +74 -0
  70. package/dist/utils/followUps.js +116 -0
  71. package/dist/utils/generationArchiveStore.d.ts +6 -0
  72. package/dist/utils/generationArchiveStore.js +11 -3
  73. package/dist/utils/index.d.ts +12 -0
  74. package/dist/utils/index.js +20 -0
  75. package/dist/utils/orderedLine.d.ts +29 -0
  76. package/dist/utils/orderedLine.js +17 -0
  77. package/dist/utils/pastedContent.d.ts +99 -0
  78. package/dist/utils/pastedContent.js +258 -0
  79. package/dist/utils/questionCards.d.ts +131 -0
  80. package/dist/utils/questionCards.js +287 -0
  81. package/dist/utils/referenceItems.d.ts +36 -0
  82. package/dist/utils/referenceItems.js +56 -0
  83. package/dist/utils/sentReferenceBadges.d.ts +26 -0
  84. package/dist/utils/sentReferenceBadges.js +32 -0
  85. package/package.json +1 -1
@@ -45,13 +45,17 @@ async function postJson(baseUrl, path, body, token, signal) {
45
45
  // A stop asked for stays what it is; anything else is a request that never got an answer.
46
46
  if (signal?.aborted)
47
47
  throw error;
48
- throw new SketchAssistantRequestError(error instanceof Error ? error.message : 'no answer', SKETCH_ASSISTANT_NO_ANSWER_STATUS, 'NO_ANSWER');
48
+ const technical = error instanceof Error ? error.message : 'no answer';
49
+ console.error('[chat] sketch assistant fetch', error instanceof Error ? error : technical);
50
+ throw new SketchAssistantRequestError(technical, SKETCH_ASSISTANT_NO_ANSWER_STATUS, 'NO_ANSWER');
49
51
  }
50
52
  // A proxy in front of the gateway can answer with a page that is not JSON; the status is still the answer.
51
53
  const payload = (await response.json().catch(() => null));
52
54
  if (!response.ok) {
53
55
  const refusal = readRefusal(payload);
54
- throw new SketchAssistantRequestError(refusal.message ?? `Sketch assistant HTTP ${response.status}`, response.status, refusal.code);
56
+ const technical = refusal.message ?? `request failed with status ${response.status}`;
57
+ console.error('[chat] sketch assistant response', { status: response.status, code: refusal.code, message: technical });
58
+ throw new SketchAssistantRequestError(technical, response.status, refusal.code);
55
59
  }
56
60
  return (payload?.data ?? payload);
57
61
  }
@@ -59,6 +63,7 @@ export async function startSketchAssistantRequest(input) {
59
63
  return postJson(input.apiBaseUrl, '/agent/sketch', {
60
64
  prompt: input.prompt,
61
65
  sceneSummary: input.sceneSummary,
66
+ sketchContext: input.sketchContext,
62
67
  conversationId: input.conversationId,
63
68
  canvasId: input.canvasId
64
69
  }, input.authToken, input.signal);
@@ -0,0 +1,4 @@
1
+ import type { Translate } from '@widgetic/design-system/i18n';
2
+ import type { ChatMessageKey } from '../i18n/messages.js';
3
+ /** Words shown in the chat bubble when a sketch request fails. */
4
+ export declare function describeSketchRequestFailure(error: unknown, translate?: Translate<ChatMessageKey>): string;
@@ -0,0 +1,22 @@
1
+ import { translateEnglish } from '../i18n/language.js';
2
+ import { SKETCH_ASSISTANT_NO_ANSWER_STATUS, SketchAssistantRequestError, } from './sketchAssistantClient.js';
3
+ import { logTechnicalUserError } from '../errors/logTechnicalUserError.js';
4
+ /** Words shown in the chat bubble when a sketch request fails. */
5
+ export function describeSketchRequestFailure(error, translate = translateEnglish) {
6
+ if (error instanceof SketchAssistantRequestError) {
7
+ logTechnicalUserError('sketch assistant request', error, error.message);
8
+ if (error.status === 402 || error.code === 'BILLING_INSUFFICIENT_CREDITS')
9
+ return translate('chat.sketch.noCredits');
10
+ if (error.status === 429)
11
+ return translate('chat.sketch.busy');
12
+ if (error.status === SKETCH_ASSISTANT_NO_ANSWER_STATUS || error.status === 408 || error.status >= 500) {
13
+ return translate('chat.sketch.unavailable');
14
+ }
15
+ return translate('chat.sketch.failed');
16
+ }
17
+ if (error instanceof Error && error.name === 'AbortError')
18
+ return translate('chat.sketch.stopped');
19
+ if (error !== undefined && error !== null)
20
+ logTechnicalUserError('sketch assistant', error);
21
+ return translate('chat.sketch.failedUnknown');
22
+ }
@@ -1,7 +1,8 @@
1
- import { type SketchSceneSummary } from './sketchAssistantClient.js';
1
+ import { type SketchAssistantContext, type SketchSceneSummary } from './sketchAssistantClient.js';
2
2
  import { type SketchToolTrace } from './sketchAssistantReply.js';
3
3
  import type { Translate } from '@widgetic/design-system/i18n';
4
4
  import type { ChatMessageKey } from '../i18n/messages.js';
5
+ export { describeSketchRequestFailure } from './sketchAssistantErrors.js';
5
6
  export interface CanvasSketchExecutor {
6
7
  getSceneSummary(): SketchSceneSummary;
7
8
  executeTool(name: string, args: Record<string, unknown>): Record<string, unknown>;
@@ -17,12 +18,6 @@ export interface SketchAssistantLoopResult {
17
18
  /** Whether a tool changed the canvas, so a run that only talked leaves nothing to undo. */
18
19
  changedCanvas: boolean;
19
20
  }
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
21
  /**
27
22
  * Runs one request of the author on the canvas: the gateway's model asks for tools, the canvas runs them here, and
28
23
  * the results go back until the model has nothing more to ask.
@@ -38,6 +33,11 @@ export declare function runSketchAssistantLoop(input: {
38
33
  executor: CanvasSketchExecutor;
39
34
  conversationId?: string | null;
40
35
  canvasId?: string | null;
36
+ /**
37
+ * The brand colours and fonts of the person and the assets the model may place with `add_asset`: told to the model once, with the
38
+ * request (the canvas holds the same assets, see `sketchAssets` of `@widgetic/canvas`). Missing: the model draws without them.
39
+ */
40
+ sketchContext?: SketchAssistantContext;
41
41
  maxSteps?: number;
42
42
  translate?: Translate<ChatMessageKey>;
43
43
  /** Stops the run between requests, and the request that is on its way. */
@@ -1,6 +1,9 @@
1
- import { SKETCH_ASSISTANT_NO_ANSWER_STATUS, SketchAssistantRequestError, sketchAssistantStepRequest, startSketchAssistantRequest } from './sketchAssistantClient.js';
1
+ import { SketchAssistantRequestError, sketchAssistantStepRequest, startSketchAssistantRequest } from './sketchAssistantClient.js';
2
2
  import { buildSketchAssistantReply } from './sketchAssistantReply.js';
3
3
  import { translateEnglish } from '../i18n/language.js';
4
+ import { describeSketchRequestFailure } from './sketchAssistantErrors.js';
5
+ import { logTechnicalUserError } from '../errors/logTechnicalUserError.js';
6
+ export { describeSketchRequestFailure } from './sketchAssistantErrors.js';
4
7
  /**
5
8
  * How many times a run answers the gateway with tool results. The gateway stops a run after the same number of steps
6
9
  * (its last answer is words only), so a run that is still asking for tools after this many has not understood the
@@ -9,26 +12,6 @@ import { translateEnglish } from '../i18n/language.js';
9
12
  const SKETCH_ASSISTANT_MAX_STEPS = 8;
10
13
  /** The only tool whose job is to read the canvas; every other tool changes it. */
11
14
  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
15
  /** A tool result without the copy of the canvas the executors attach: the gateway is sent the canvas once, in `sceneSummary`. */
33
16
  function withoutSceneCopy(result) {
34
17
  const { summary: _sceneCopy, ...rest } = result;
@@ -70,13 +53,17 @@ export async function runSketchAssistantLoop(input) {
70
53
  sceneSummary: input.executor.getSceneSummary(),
71
54
  conversationId: input.conversationId,
72
55
  canvasId: input.canvasId,
56
+ sketchContext: input.sketchContext,
73
57
  signal: input.signal
74
58
  });
75
59
  input.executor.beginToolBatch?.();
76
60
  batchOpen = true;
77
61
  for (;;) {
78
62
  if (response.status === 'failed' || response.status === 'disabled') {
79
- return outcome(false, response.error ?? response.message ?? translate('chat.sketch.failedUnknown'));
63
+ const raw = response.error ?? response.message;
64
+ if (raw)
65
+ logTechnicalUserError('sketch assistant status failed', raw);
66
+ return outcome(false, translate('chat.sketch.failedUnknown'));
80
67
  }
81
68
  if (response.status === 'completed') {
82
69
  return outcome(true, closingMessage(response, toolTrace, translate));
@@ -91,8 +78,8 @@ export async function runSketchAssistantLoop(input) {
91
78
  }
92
79
  catch (error) {
93
80
  // 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' };
81
+ logTechnicalUserError(`sketch tool ${call.name}`, error);
82
+ result = { ok: false, error: 'The tool could not finish on the canvas.', code: 'internal' };
96
83
  }
97
84
  toolTrace.push({
98
85
  name: call.name,
@@ -6,7 +6,9 @@ export function buildSketchAssistantReply(tools, translate = translateEnglish) {
6
6
  const okTools = tools.filter((tool) => tool.ok);
7
7
  if (okTools.length === 0) {
8
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');
9
+ if (firstError)
10
+ console.error('[chat] sketch tool reply', firstError);
11
+ return translate('chat.sketch.failed');
10
12
  }
11
13
  const names = new Set(okTools.map((tool) => tool.name));
12
14
  if (names.has('draw_ui_component')) {
@@ -26,6 +26,11 @@ export declare const chatStore: {
26
26
  updateMessageContent: (conversationId: string, messageId: string, messageContent: string) => void;
27
27
  updateMessageAttachments: (conversationId: string, messageId: string, attachments: any[]) => void;
28
28
  updateMessageSuggestions: (conversationId: string, messageId: string, suggestions: ChatMessage["suggestions"] | undefined) => void;
29
+ /**
30
+ * Replaces the card of questions of a message. What the person did with it (`questionCard.result`) is kept this way, on the
31
+ * message that holds the card, so the id the host later swaps for the saved one cannot lose it.
32
+ */
33
+ updateMessageQuestionCard: (conversationId: string, messageId: string, questionCard: ChatMessage["questionCard"]) => void;
29
34
  };
30
35
  };
31
36
  /**
@@ -311,6 +311,27 @@ function createChatStore() {
311
311
  }
312
312
  };
313
313
  });
314
+ },
315
+ /**
316
+ * Replaces the card of questions of a message. What the person did with it (`questionCard.result`) is kept this way, on the
317
+ * message that holds the card, so the id the host later swaps for the saved one cannot lose it.
318
+ */
319
+ updateMessageQuestionCard: (conversationId, messageId, questionCard) => {
320
+ update(state => {
321
+ const msgs = state.messages.byConversationId[conversationId];
322
+ if (!msgs)
323
+ return state;
324
+ return {
325
+ ...state,
326
+ messages: {
327
+ ...state.messages,
328
+ byConversationId: {
329
+ ...state.messages.byConversationId,
330
+ [conversationId]: msgs.map((msg) => msg.id === messageId ? { ...msg, questionCard: questionCard ?? undefined } : msg)
331
+ }
332
+ }
333
+ };
334
+ });
314
335
  }
315
336
  }
316
337
  };
@@ -3,7 +3,8 @@ import type { Snippet } from 'svelte';
3
3
  * The five looks of the assistant's avatar.
4
4
  *
5
5
  * They are the states of the Scribble Mascot of `@widgetic/brand`, word for word, so a page that draws the mascot
6
- * passes `state` straight on. `success` and `error` play once and then rest (the mascot's `settleTo`).
6
+ * passes `state` straight on. `success` and `error` play once and then rest (the mascot's `settleTo`). A failure is held as
7
+ * a still picture instead (`live` is false for it), so that its avatar stays red until the prompt is sent again.
7
8
  */
8
9
  export type AgentAvatarState = 'idle' | 'thinking' | 'writing' | 'success' | 'error';
9
10
  /** What the chat gives the page's avatar snippet each time something about the avatar changes. */
@@ -16,8 +17,8 @@ export interface AgentAvatarRenderProps {
16
17
  */
17
18
  size: number;
18
19
  /**
19
- * False for an avatar that only has to sit there (a message that is not the newest): draw a still picture and keep
20
- * nothing running. True for the one that moves.
20
+ * False for an avatar that only has to sit there (a message that is not the newest, or a failure that holds its red `error`
21
+ * look until the prompt is sent again): draw a still picture of `state` and keep nothing running. True for the one that moves.
21
22
  */
22
23
  live: boolean;
23
24
  /**
@@ -35,7 +35,17 @@ export interface SelectedElementChatReference {
35
35
  * Input for creating attachments
36
36
  */
37
37
  export interface AttachmentInput {
38
+ /**
39
+ * Tells this attachment from the others in the tray while it is on the screen. A name does not: two screenshots pasted one
40
+ * after the other are both "image.png". Not sent anywhere.
41
+ */
42
+ id?: string;
38
43
  file: File;
44
+ /**
45
+ * The words the tray tile says in place of the file's name: for a pasted text, its first words. The name of the file is
46
+ * what is stored and sent, the label is for the screen only.
47
+ */
48
+ label?: string;
39
49
  type?: AttachmentType;
40
50
  metadata?: Record<string, any>;
41
51
  preview?: string;
@@ -49,6 +59,12 @@ export interface AttachmentInput {
49
59
  */
50
60
  persistedDataUrl?: string;
51
61
  uploadProgress?: number;
62
+ /**
63
+ * The word the message can call this file by after a `#` ("hero_banner_final" for `#hero_banner_final`): given when the file joins the
64
+ * tray and kept as long as it stays there. A picture has one; a file that cannot be referenced has none. The host reads it back
65
+ * from the file it is sent with (`referenceLabel`) to tie a `#word` of the text to that file.
66
+ */
67
+ referenceLabel?: string;
52
68
  }
53
69
  /**
54
70
  * Client-side attachment before upload
@@ -59,6 +59,12 @@ export interface ChatConfig {
59
59
  * LLM conversation history regardless of this flag.
60
60
  */
61
61
  showGenerationSummaries?: boolean;
62
+ /**
63
+ * Messages sent while the host's agent works (`isGenerating`) wait in a queue above the composer instead of being sent
64
+ * into the run, and are sent one by one as the agent finishes. Default on; set false to give the composer its old
65
+ * behaviour while an agent works (the send control is Stop).
66
+ */
67
+ messageQueue?: boolean;
62
68
  };
63
69
  websocket?: {
64
70
  enabled: boolean;
@@ -8,6 +8,7 @@ export * from './config.js';
8
8
  export * from './adapter.js';
9
9
  export * from './events.js';
10
10
  export * from './agent.js';
11
+ export * from './mention.js';
11
12
  export type { ChatService, ChatInstance, ChatFactory } from './chat.js';
12
13
  export type { ChatMessage, MessageInput } from './message.js';
13
14
  export type { ChatConversation, ConversationInput } from './conversation.js';
@@ -10,3 +10,5 @@ export * from './adapter.js';
10
10
  export * from './events.js';
11
11
  // The assistant's avatar and the people of the team (what a page hands over to put faces on the messages)
12
12
  export * from './agent.js';
13
+ // What a page lets the person pick with @ in the message box, and the picks that go out with the message
14
+ export * from './mention.js';
@@ -0,0 +1,40 @@
1
+ /**
2
+ * What a person can pick with `@` in the message box.
3
+ *
4
+ * The page hands the chat its lists (`mentionSources` of `Chat`). The chat does not know what an item is (a connected app, a design,
5
+ * a document): it shows the names, takes a pick, draws the chip and gives the pick back with the message (`mentions` in the options
6
+ * of `onSendMessage`). What a pick means, and what the message does with it, is the page's.
7
+ */
8
+ /** One row of the `@` menu. */
9
+ export interface MentionSourceItem {
10
+ /** What the page gets back when the row is picked. Never shown. */
11
+ id: string;
12
+ /** What the row and the chip say. */
13
+ name: string;
14
+ /** A line under the name in the menu (an address, a state). Left out, the row has one line. */
15
+ caption?: string;
16
+ /** Whether a pick is taken. `false` shows the row dimmed with `unavailableReason` and takes no pick. Left out, it can be picked. */
17
+ selectable?: boolean;
18
+ /** Why the row cannot be picked, in the page's language. It is said in place of the caption. */
19
+ unavailableReason?: string;
20
+ /**
21
+ * The sites a link may point to for this row to be offered as a one-tap pick: when the message holds a link to one of them, the
22
+ * box offers "Read this link with {name}" next to the chips, and a tap picks the row. A site matches the sites of its own domain
23
+ * (`mcp.figma.com` and `www.figma.com`). Left out, the row is never offered. Nothing is read or sent by the offer: it is only a pick.
24
+ */
25
+ linkHosts?: readonly string[];
26
+ }
27
+ /** The rows of one kind. The menu lists the kinds in the order the page gave them. */
28
+ export interface MentionSource {
29
+ /** The kind of thing, in the page's own words. Rows are told apart by kind and never by id alone, so ids of two kinds may be alike. */
30
+ kind: string;
31
+ /** The heading of the group, in the page's language. It is shown only while the menu holds rows of more than one kind. */
32
+ label: string;
33
+ items: readonly MentionSourceItem[];
34
+ }
35
+ /** A pick: the chip in the message box, and what the page gets with the message. */
36
+ export interface ComposerMention {
37
+ kind: string;
38
+ id: string;
39
+ name: string;
40
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * What a person can pick with `@` in the message box.
3
+ *
4
+ * The page hands the chat its lists (`mentionSources` of `Chat`). The chat does not know what an item is (a connected app, a design,
5
+ * a document): it shows the names, takes a pick, draws the chip and gives the pick back with the message (`mentions` in the options
6
+ * of `onSendMessage`). What a pick means, and what the message does with it, is the page's.
7
+ */
8
+ export {};
@@ -44,8 +44,17 @@ export interface ChatMessage {
44
44
  * objects: `label` is display copy rendered verbatim, `intent` is the
45
45
  * machine-readable behavior the chip's tap declares back on the next
46
46
  * generate request (`chipIntent`). Bare-string rows from before the
47
- * contract are normalized to refine suggestions by the server on read. */
47
+ * contract are normalized to refine suggestions by the server on read.
48
+ * A chip with a `title` is not an option of a card: it is a follow-up pill
49
+ * (an idea for what to improve next), drawn in the follow-up card under the
50
+ * last reply. */
48
51
  suggestions?: ClarificationSuggestion[];
52
+ /** The card of questions the assistant put to the person before it built anything (assistant only), in the shape the gateway
53
+ * sends (`metadata.clarification`, and `generation_surface.clarification` on the saved message). Each question says on its own
54
+ * whether one option or several can be picked. It is open while it is the newest message; the person answers it in the card, or
55
+ * leaves it by writing in the chat (every question is then shown as skipped). Not the same as `suggestions`: those are the
56
+ * options of a single question the intent gate asked, or follow-up pills. */
57
+ questionCard?: QuestionCardModel | null;
49
58
  /** Design-property controls to render inline under this assistant reply.
50
59
  * Set by the host when a deterministic (model-free) design tweak is applied,
51
60
  * so the user can keep adjusting the property by hand. Persisted with the
@@ -107,6 +116,56 @@ export interface ClarificationSuggestion {
107
116
  intent: 'refine' | 'generate_anyway';
108
117
  /** When true, the host undoes the last sketch assistant turn instead of sending the label as a prompt. */
109
118
  undoSketch?: boolean;
119
+ /**
120
+ * The few words (at most five) a small follow-up pill shows, while `label` (the whole request) is shown in the tooltip and is
121
+ * what a pick puts in the message box. Only a suggested next step after a build has one: a chip with a title is a follow-up
122
+ * pill, a chip without one is an option of a question. Absent on every chip saved before follow-ups existed.
123
+ */
124
+ title?: string;
125
+ }
126
+ /** One option of a question of the card (the gateway's `WidgetClarificationQuestion.options`). */
127
+ export interface QuestionCardOption {
128
+ id: string;
129
+ /** What the option says. A recommended one carries the localized word in it, such as "Minimal (Recommended)". */
130
+ label: string;
131
+ /** True for the option the assistant recommends (the first of its question). */
132
+ recommended?: boolean;
133
+ }
134
+ /** One question of the card. */
135
+ export interface QuestionCardQuestion {
136
+ id: string;
137
+ question: string;
138
+ /** Two to five options; none when the question is answered in words only. */
139
+ options: QuestionCardOption[];
140
+ /** The person may pick more than one option for this question. Left out or false: exactly one. */
141
+ allowMultiple?: boolean;
142
+ /** The person may answer in their own words. The card does not draw a row for it: the message box is where they do. */
143
+ allowOther?: boolean;
144
+ /** The localized word written in parentheses on the recommended option's label (what is cut off the label in a summary). */
145
+ recommendedWord?: string;
146
+ }
147
+ /** One answer the person gave on the card: the question as it was shown, and what was picked. */
148
+ export interface QuestionCardAnswer {
149
+ question: string;
150
+ /**
151
+ * What was picked. Several picks of one question are one per line; empty is a question that was skipped (Next with nothing
152
+ * picked, Skip, or a message typed in the chat instead), which the assistant decides itself. The same pair the gateway takes
153
+ * in `answers` on the request that follows the card.
154
+ */
155
+ answer: string;
156
+ }
157
+ /** What the person did with the card, kept on the message so the card is drawn closed instead of open. */
158
+ export interface QuestionCardResult {
159
+ /** One answer for each question of the card, in its order. */
160
+ answers: QuestionCardAnswer[];
161
+ }
162
+ /** The card of questions of an assistant message (see `ChatMessage.questionCard`). */
163
+ export interface QuestionCardModel {
164
+ /** The sentence that introduces the card ("Before I change it, I have a few questions."), in the person's language. */
165
+ message?: string;
166
+ questions: QuestionCardQuestion[];
167
+ /** Set once the card was answered in the card (or skipped with its Skip). Not part of what the gateway sends. */
168
+ result?: QuestionCardResult | null;
110
169
  }
111
170
  /**
112
171
  * Message input type for creating new messages
@@ -1,5 +1,6 @@
1
1
  import type { ChatMessageKey } from '../i18n/messages.js';
2
2
  import type { AgentAvatarState, ChatMember } from '../types/agent.js';
3
+ import { type CodeChanges } from './codeChanges.js';
3
4
  import type { GenerationActivityPhase } from './generationActivity.js';
4
5
  /**
5
6
  * The rules of the assistant's turn: what its avatar looks like and does at each moment, how a finished turn is judged,
@@ -14,7 +15,7 @@ export type AgentAvatarSize = 'large' | 'small';
14
15
  export interface AgentLook {
15
16
  state: AgentAvatarState;
16
17
  size: AgentAvatarSize;
17
- /** True for the avatar that moves (the newest turn); false for one that only sits there as a still picture. */
18
+ /** True for the avatar that moves (the newest turn); false for one that only sits there as a still picture (an older turn, or a failure holding its red look). */
18
19
  live: boolean;
19
20
  }
20
21
  /**
@@ -59,9 +60,18 @@ export interface TurnReplyFacts {
59
60
  */
60
61
  export declare function turnOutcome(replies: readonly TurnReplyFacts[], generationRanForTurn: boolean): TurnOutcome | null;
61
62
  /**
62
- * The look of a turn that is not running. Only the newest turn moves, and only its conclusion is large (the success or
63
- * the error avatar, or a question to answer): older turns are small still pictures, so a long chat keeps one mascot
64
- * alive instead of one per message.
63
+ * The look of a turn that is not running. Only the newest turn moves, and only its conclusion is large (the success avatar,
64
+ * or a question to answer): older turns are small still pictures, so a long chat keeps one mascot alive instead of one per
65
+ * message.
66
+ *
67
+ * A failure is the one conclusion that does not move: its avatar sits SMALL and STILL in its red error look, and keeps it until
68
+ * the person tries again or sends another message. The turn is then no longer the newest, so it falls back to the quiet picture of
69
+ * every older turn, and the new run brings its own live avatar.
70
+ *
71
+ * - Small, so that the line saying what went wrong sits where the text of any turn sits (an avatar that was large while the run
72
+ * waited glides down to it), and the top of the avatar is the top of that line.
73
+ * - Still, because the mascot's own error is a one-shot that rests back to idle within a second: left to play it would turn
74
+ * the avatar blue again, and a red look that is held can only be a picture.
65
75
  */
66
76
  export declare function settledAgentLook(outcome: TurnOutcome, isNewestTurn: boolean): AgentLook;
67
77
  /** Where the avatar that takes over from the live one starts. */
@@ -74,8 +84,9 @@ export interface AvatarStart {
74
84
  /**
75
85
  * The live avatar of a run and the one of its ending are two avatars, one after the other, in the same place. The second one starts
76
86
  * from how the first one looked when the run ended, so what the person watched carries on instead of being swapped: a Stop pressed
77
- * while the avatar is still large shrinks it down to its small size, and the mascot calms from what it was doing; a conclusion
78
- * grows out of the avatar of the work.
87
+ * while the avatar is still large shrinks it down to its small size, and the mascot calms from what it was doing; so does a failure
88
+ * that ends a run while it waits, which glides down to the small avatar that holds the red look; a success grows out of the avatar
89
+ * of the work.
79
90
  *
80
91
  * Without a live avatar to take over from (the conversation was opened or reloaded after the run) it starts from the small one,
81
92
  * which is where a conclusion has always grown out of.
@@ -137,8 +148,11 @@ export interface GenerationModulesView {
137
148
  }
138
149
  /** The modules while a generation runs. The thoughts fold away once the code starts, the code stays open while it streams. */
139
150
  export declare function liveModulesView(phase: GenerationActivityPhase): GenerationModulesView;
140
- /** The modules under a conclusion: whatever was kept, closed, for the person to open. */
141
- export declare function finishedModulesView(finished: Pick<FinishedGeneration, 'thinking' | 'code'> | null): GenerationModulesView;
151
+ /**
152
+ * The modules under a conclusion: whatever was kept, closed, for the person to open. The code card shows when there is code to
153
+ * show or changes to show (a round whose stream left no code, but whose changes the gateway sent, still has its card).
154
+ */
155
+ export declare function finishedModulesView(finished: (Pick<FinishedGeneration, 'thinking' | 'code'> & Partial<Pick<FinishedGeneration, 'changes'>>) | null): GenerationModulesView;
142
156
  /**
143
157
  * The thinking and the code of the generation that just ended: what the modules under the conclusion show.
144
158
  * Kept in memory for the newest turn only (the host saves neither); it is gone after a reload, and the conclusion
@@ -150,6 +164,11 @@ export interface FinishedGeneration {
150
164
  thinking: string;
151
165
  code: string;
152
166
  thoughtSeconds: number | null;
167
+ /**
168
+ * What the run changed in the widget's files (a later round of a conversation, when the page gave it): the code card then opens
169
+ * on the diff. Null when the run has none: the first message of a conversation, a page that does not give changes.
170
+ */
171
+ changes?: CodeChanges | null;
153
172
  }
154
173
  /**
155
174
  * The most text kept of either part. A generation streams tails; the chat stitches them, and a runaway stream
@@ -161,13 +180,25 @@ export declare const MAX_KEPT_GENERATION_CHARS = 120000;
161
180
  * may reload the whole conversation after a generation. The words the person wrote survive both.
162
181
  */
163
182
  export declare function normalizePromptText(content: string | null | undefined): string;
164
- /** What to keep of a generation that ended, or null when it left nothing to show. */
183
+ /**
184
+ * What to keep of a generation that ended, or null when it left nothing to show. `changes` is whatever the page gave as the
185
+ * changes of the run: it is read here (a part that is not usable is dropped), so what is kept is always plain, bounded data.
186
+ */
165
187
  export declare function keepFinishedGeneration(input: {
166
188
  promptText: string | null | undefined;
167
189
  thinking: string;
168
190
  code: string;
169
191
  thoughtSeconds: number | null;
192
+ changes?: unknown;
170
193
  }): FinishedGeneration | null;
194
+ /**
195
+ * The kept work of a run with the changes of that run put into it, for a page that gives the changes AFTER the run ended. The
196
+ * gateway sends them with the completed operation, and a page that lets the chat take the next message as soon as the preview is
197
+ * up (the widget creator does) lowers `isGenerating` before that. The changes are read here like those of `keepFinishedGeneration`.
198
+ * It gives back the very same object when there is nothing to put in (the work has changes already, or what was given is not
199
+ * usable), so the caller can tell by identity that nothing changed.
200
+ */
201
+ export declare function withChangesOfTheRun(finished: FinishedGeneration, changes: unknown): FinishedGeneration;
171
202
  /** Whether the kept work belongs under the turn of this prompt: the newest turn, found again by the words of its prompt. */
172
203
  export declare function finishedGenerationBelongsTo(finished: FinishedGeneration | null, newestTurnPromptText: string | null | undefined): finished is FinishedGeneration;
173
204
  /**
@@ -1,3 +1,4 @@
1
+ import { readCodeChanges } from './codeChanges.js';
1
2
  /** A turn that is not the newest, or has nothing to say about itself: small, still, calm. */
2
3
  const RESTING_STILL_LOOK = { state: 'idle', size: 'small', live: false };
3
4
  /**
@@ -45,9 +46,18 @@ export function turnOutcome(replies, generationRanForTurn) {
45
46
  return 'answer';
46
47
  }
47
48
  /**
48
- * The look of a turn that is not running. Only the newest turn moves, and only its conclusion is large (the success or
49
- * the error avatar, or a question to answer): older turns are small still pictures, so a long chat keeps one mascot
50
- * alive instead of one per message.
49
+ * The look of a turn that is not running. Only the newest turn moves, and only its conclusion is large (the success avatar,
50
+ * or a question to answer): older turns are small still pictures, so a long chat keeps one mascot alive instead of one per
51
+ * message.
52
+ *
53
+ * A failure is the one conclusion that does not move: its avatar sits SMALL and STILL in its red error look, and keeps it until
54
+ * the person tries again or sends another message. The turn is then no longer the newest, so it falls back to the quiet picture of
55
+ * every older turn, and the new run brings its own live avatar.
56
+ *
57
+ * - Small, so that the line saying what went wrong sits where the text of any turn sits (an avatar that was large while the run
58
+ * waited glides down to it), and the top of the avatar is the top of that line.
59
+ * - Still, because the mascot's own error is a one-shot that rests back to idle within a second: left to play it would turn
60
+ * the avatar blue again, and a red look that is held can only be a picture.
51
61
  */
52
62
  export function settledAgentLook(outcome, isNewestTurn) {
53
63
  if (!isNewestTurn)
@@ -56,7 +66,7 @@ export function settledAgentLook(outcome, isNewestTurn) {
56
66
  case 'success':
57
67
  return { state: 'success', size: 'large', live: true };
58
68
  case 'error':
59
- return { state: 'error', size: 'large', live: true };
69
+ return { state: 'error', size: 'small', live: false };
60
70
  case 'question':
61
71
  return { state: 'idle', size: 'large', live: true };
62
72
  case 'stopped':
@@ -68,8 +78,9 @@ export function settledAgentLook(outcome, isNewestTurn) {
68
78
  /**
69
79
  * The live avatar of a run and the one of its ending are two avatars, one after the other, in the same place. The second one starts
70
80
  * from how the first one looked when the run ended, so what the person watched carries on instead of being swapped: a Stop pressed
71
- * while the avatar is still large shrinks it down to its small size, and the mascot calms from what it was doing; a conclusion
72
- * grows out of the avatar of the work.
81
+ * while the avatar is still large shrinks it down to its small size, and the mascot calms from what it was doing; so does a failure
82
+ * that ends a run while it waits, which glides down to the small avatar that holds the red look; a success grows out of the avatar
83
+ * of the work.
73
84
  *
74
85
  * Without a live avatar to take over from (the conversation was opened or reloaded after the run) it starts from the small one,
75
86
  * which is where a conclusion has always grown out of.
@@ -160,14 +171,17 @@ export function liveModulesView(phase) {
160
171
  return NOTHING_SHOWN;
161
172
  }
162
173
  }
163
- /** The modules under a conclusion: whatever was kept, closed, for the person to open. */
174
+ /**
175
+ * The modules under a conclusion: whatever was kept, closed, for the person to open. The code card shows when there is code to
176
+ * show or changes to show (a round whose stream left no code, but whose changes the gateway sent, still has its card).
177
+ */
164
178
  export function finishedModulesView(finished) {
165
179
  if (!finished)
166
180
  return NOTHING_SHOWN;
167
181
  return {
168
182
  ...NOTHING_SHOWN,
169
183
  showThinking: finished.thinking.trim().length > 0,
170
- showCode: finished.code.trim().length > 0
184
+ showCode: finished.code.trim().length > 0 || (finished.changes?.files.length ?? 0) > 0
171
185
  };
172
186
  }
173
187
  /**
@@ -182,19 +196,37 @@ export const MAX_KEPT_GENERATION_CHARS = 120_000;
182
196
  export function normalizePromptText(content) {
183
197
  return (content ?? '').replace(/\s+/g, ' ').trim();
184
198
  }
185
- /** What to keep of a generation that ended, or null when it left nothing to show. */
199
+ /**
200
+ * What to keep of a generation that ended, or null when it left nothing to show. `changes` is whatever the page gave as the
201
+ * changes of the run: it is read here (a part that is not usable is dropped), so what is kept is always plain, bounded data.
202
+ */
186
203
  export function keepFinishedGeneration(input) {
187
204
  const thinking = input.thinking.slice(-MAX_KEPT_GENERATION_CHARS);
188
205
  const code = input.code.slice(-MAX_KEPT_GENERATION_CHARS);
189
- if (thinking.trim().length === 0 && code.trim().length === 0)
206
+ const changes = readCodeChanges(input.changes);
207
+ if (thinking.trim().length === 0 && code.trim().length === 0 && changes === null)
190
208
  return null;
191
209
  return {
192
210
  prompt: normalizePromptText(input.promptText),
193
211
  thinking,
194
212
  code,
195
- thoughtSeconds: input.thoughtSeconds
213
+ thoughtSeconds: input.thoughtSeconds,
214
+ changes
196
215
  };
197
216
  }
217
+ /**
218
+ * The kept work of a run with the changes of that run put into it, for a page that gives the changes AFTER the run ended. The
219
+ * gateway sends them with the completed operation, and a page that lets the chat take the next message as soon as the preview is
220
+ * up (the widget creator does) lowers `isGenerating` before that. The changes are read here like those of `keepFinishedGeneration`.
221
+ * It gives back the very same object when there is nothing to put in (the work has changes already, or what was given is not
222
+ * usable), so the caller can tell by identity that nothing changed.
223
+ */
224
+ export function withChangesOfTheRun(finished, changes) {
225
+ if (finished.changes && finished.changes.files.length > 0)
226
+ return finished;
227
+ const readChanges = readCodeChanges(changes);
228
+ return readChanges === null ? finished : { ...finished, changes: readChanges };
229
+ }
198
230
  /** Whether the kept work belongs under the turn of this prompt: the newest turn, found again by the words of its prompt. */
199
231
  export function finishedGenerationBelongsTo(finished, newestTurnPromptText) {
200
232
  if (!finished)