@aleph-alpha/chat-kit 5.8.0 → 5.9.0

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 (24) hide show
  1. package/dist/{CkHistory.vue_vue_type_script_setup_true_lang-DG96wNug.js → CkHistory.vue_vue_type_script_setup_true_lang-CEqJtMuI.js} +61 -40
  2. package/dist/adapters/responses-api.d.ts.map +1 -1
  3. package/dist/adapters/responses-api.js +46 -33
  4. package/dist/chat-kit.css +1 -1
  5. package/dist/components/base/CkConversationLayout/CkConversationLayout.stories.d.ts +7 -0
  6. package/dist/components/base/CkConversationLayout/CkConversationLayout.stories.d.ts.map +1 -1
  7. package/dist/components/base/CkConversationLayout/CkConversationLayout.vue.d.ts +3 -1
  8. package/dist/components/base/CkConversationLayout/CkConversationLayout.vue.d.ts.map +1 -1
  9. package/dist/components/composed/CkConversation/CkConversation.stories.d.ts +23 -3
  10. package/dist/components/composed/CkConversation/CkConversation.stories.d.ts.map +1 -1
  11. package/dist/components/composed/CkConversation/CkConversation.vue.d.ts +17 -2
  12. package/dist/components/composed/CkConversation/CkConversation.vue.d.ts.map +1 -1
  13. package/dist/components/composed/CkHistory/CkHistory.vue.d.ts +1 -1
  14. package/dist/components/index.js +1 -1
  15. package/dist/index.js +1 -1
  16. package/package.json +1 -1
  17. package/src/adapters/responses-api.spec.ts +6 -3
  18. package/src/adapters/responses-api.ts +62 -35
  19. package/src/components/base/CkConversationLayout/CkConversationLayout.spec.ts +209 -1
  20. package/src/components/base/CkConversationLayout/CkConversationLayout.stories.ts +84 -0
  21. package/src/components/base/CkConversationLayout/CkConversationLayout.vue +59 -21
  22. package/src/components/composed/CkConversation/CkConversation.spec.ts +96 -5
  23. package/src/components/composed/CkConversation/CkConversation.stories.ts +328 -4
  24. package/src/components/composed/CkConversation/CkConversation.vue +38 -8
@@ -125,34 +125,66 @@ function updateSpacerHeight(): void {
125
125
  const lastUserTop = lastUserRow.offsetTop;
126
126
  const lastRowBottom = lastRow.offsetTop + lastRow.offsetHeight;
127
127
  const contentFromUserToEnd = lastRowBottom - lastUserTop;
128
- const gap = parseFloat(getComputedStyle(container).rowGap) || 0;
128
+ // The last user message carries a top margin (mt-3xl for non-first rows) that
129
+ // is scrolled into view above it, so it consumes viewport height just like the
130
+ // content does. Account for it here instead of the removed row gap.
131
+ const topMargin = parseFloat(getComputedStyle(lastUserRow).marginTop) || 0;
129
132
 
130
133
  spacerHeight.value = Math.max(
131
134
  0,
132
- containerHeight.value - contentFromUserToEnd - gap,
135
+ containerHeight.value - contentFromUserToEnd - topMargin,
133
136
  );
134
137
  }
135
138
 
136
139
  /**
137
- * Scroll so the last user message is at the top of the viewport.
138
- * The bottom spacer ensures enough scroll room.
140
+ * Scroll so the message at `index` is at the top of the viewport, keeping its
141
+ * top margin in view. `index` is the zero-based position among the rendered
142
+ * rows — regardless of role, and with the `thread-footer` (when present)
143
+ * counting as the trailing row. When omitted it targets the last row.
144
+ *
145
+ * If there isn't a full viewport of content below the target, a bottom spacer
146
+ * is added so it can still reach the top, and auto-scroll resumes so streamed
147
+ * content keeps following — the newest-turn behaviour. Navigating to an earlier
148
+ * message (enough content already below it) adds no spacer and stops following.
149
+ *
150
+ * This only performs the scroll — it does not focus the message. Any
151
+ * accompanying focus handling must be done separately by the caller.
139
152
  */
140
- function scrollUserMessageToTop(): void {
153
+ function scrollMessageToTop(index?: number): void {
141
154
  const container = scrollContainerRef.value;
142
155
  if (!container) return;
143
156
 
144
- hasBottomSpacer.value = true;
145
- spacerHeight.value = containerHeight.value;
157
+ const rows = container.querySelectorAll<HTMLElement>('[data-message-row]');
158
+ if (rows.length === 0) return;
159
+
160
+ const targetIndex = index ?? rows.length - 1;
161
+ const targetRow = rows[targetIndex];
162
+ if (!targetRow) return;
163
+
164
+ // Scroll to just above the row so its top margin stays in view.
165
+ const topMargin = parseFloat(getComputedStyle(targetRow).marginTop) || 0;
166
+ const targetTop = targetRow.offsetTop - topMargin;
167
+
168
+ const lastRow = rows[rows.length - 1];
169
+ const contentBottom = lastRow.offsetTop + lastRow.offsetHeight;
170
+ const contentBelowTarget = contentBottom - targetTop;
171
+ const needsSpacer = contentBelowTarget < containerHeight.value;
172
+
173
+ // Size the spacer so the target lands exactly at the top; skip it when there
174
+ // is already enough content below (avoids a trailing empty gap). Clear any
175
+ // spacer left over from a previous near-end navigation so it doesn't leave a
176
+ // gap at the bottom.
177
+ if (needsSpacer) {
178
+ hasBottomSpacer.value = true;
179
+ spacerHeight.value = containerHeight.value - contentBelowTarget;
180
+ } else {
181
+ hasBottomSpacer.value = false;
182
+ spacerHeight.value = 0;
183
+ }
146
184
 
147
185
  nextTick(() => {
148
- const userRows = container.querySelectorAll<HTMLElement>(
149
- '[data-message-row="user"]',
150
- );
151
- const lastUserRow = userRows[userRows.length - 1];
152
- if (lastUserRow) {
153
- lastUserRow.scrollIntoView({ behavior: 'smooth', block: 'start' });
154
- }
155
- isAutoScrollEnabled.value = true;
186
+ container.scrollTo({ top: targetTop, behavior: 'smooth' });
187
+ isAutoScrollEnabled.value = needsSpacer;
156
188
  });
157
189
  }
158
190
 
@@ -177,7 +209,9 @@ function scrollToEndOfContent(): void {
177
209
  }
178
210
  }
179
211
 
180
- // When a new user message is added, scroll it to the top of the viewport
212
+ // When a new user message is added, scroll it to the top of the viewport.
213
+ // Its row index matches its position in `messages` (any `thread-footer` is
214
+ // appended after, so it never shifts earlier rows).
181
215
  watch(
182
216
  () => props.messages.length,
183
217
  (newLen, oldLen) => {
@@ -185,7 +219,7 @@ watch(
185
219
  const lastMessage = props.messages[newLen - 1];
186
220
  if (lastMessage?.role === 'user') {
187
221
  nextTick(() => {
188
- scrollUserMessageToTop();
222
+ scrollMessageToTop(newLen - 1);
189
223
  updateFades();
190
224
  });
191
225
  }
@@ -198,8 +232,8 @@ watch(
198
232
  // The trailing content can also be the `thread-footer` slot (e.g. streaming
199
233
  // preference-comparison lanes), which continues the thread after a trunk whose
200
234
  // last message is the shared *user* prompt. That case must run the same
201
- // spacer-shrink/follow pass — otherwise the full-viewport spacer set by
202
- // `scrollUserMessageToTop` is never reduced, leaving a viewport-sized gap that
235
+ // spacer-shrink/follow pass — otherwise the bottom spacer set by
236
+ // `scrollMessageToTop` is never reduced, leaving a viewport-sized gap that
203
237
  // pushes the prompt and answers out of view. `updateSpacerHeight` already
204
238
  // measures the footer (it carries `data-message-row="agent"`, so it is the
205
239
  // `lastRow`); it just needs to be invoked here. The watch fires on every tree
@@ -222,6 +256,8 @@ watch(
222
256
  },
223
257
  { deep: true },
224
258
  );
259
+
260
+ defineExpose({ scrollToMessage: scrollMessageToTop });
225
261
  </script>
226
262
 
227
263
  <template>
@@ -234,14 +270,15 @@ watch(
234
270
  />
235
271
  <div
236
272
  ref="scrollContainerRef"
237
- class="relative flex min-h-0 flex-1 flex-col gap-8 overflow-y-auto"
273
+ class="relative flex min-h-0 flex-1 flex-col overflow-y-auto"
238
274
  @scroll="handleScroll"
239
275
  >
240
276
  <div
241
- v-for="message in messages"
277
+ v-for="(message, index) in messages"
242
278
  :key="message.id"
243
279
  :data-message-row="message.role"
244
280
  class="min-w-0"
281
+ :class="index === 0 ? 'mt-2xl' : 'mt-3xl'"
245
282
  >
246
283
  <div v-if="message.role === 'user'" class="flex min-w-0 justify-end">
247
284
  <slot name="user-message" :message="message" />
@@ -256,6 +293,7 @@ watch(
256
293
  v-if="$slots['thread-footer']"
257
294
  data-message-row="agent"
258
295
  class="flex min-w-0 justify-start"
296
+ :class="messages.length === 0 ? 'mt-2xl' : 'mt-3xl'"
259
297
  >
260
298
  <slot name="thread-footer" />
261
299
  </div>
@@ -2,7 +2,16 @@ import type { BaseMessage, MessageContent } from '../../../types';
2
2
  import CkConversation from './CkConversation.vue';
3
3
  import { defaultMarkdownClasses } from '../../base/CkMarkdownRenderer/defaultMarkdownClasses';
4
4
  import { render, screen } from '@testing-library/vue';
5
- import { createCommentVNode, h } from 'vue';
5
+ import {
6
+ createCommentVNode,
7
+ defineComponent,
8
+ h,
9
+ nextTick,
10
+ onMounted,
11
+ ref,
12
+ } from 'vue';
13
+
14
+ type ConversationInstance = { scrollToMessage: (index?: number) => void };
6
15
 
7
16
  const now = new Date();
8
17
 
@@ -649,16 +658,98 @@ describe('CkConversation', () => {
649
658
  expect(container.querySelector('pre > code')).toBeNull();
650
659
  });
651
660
 
652
- it('renders default code block when agent-message-code-block slot is not provided', () => {
661
+ it('renders a UiCodeBlock by default when agent-message-code-block slot is not provided', () => {
662
+ const markdown = '```javascript\nconsole.log("hi");\n```';
663
+
664
+ const { container } = render(CkConversation, {
665
+ props: { messages: [agentMessage({ text: markdown })] },
666
+ });
667
+
668
+ // The default renderer is now UiCodeBlock, not a bare `pre > code`.
669
+ const codeBlock = container.querySelector('.ui-code-block');
670
+ expect(codeBlock).not.toBeNull();
671
+ expect(codeBlock?.textContent).toContain('console.log("hi");');
672
+ });
673
+
674
+ it('passes the fenced language through to the default UiCodeBlock', () => {
653
675
  const markdown = '```javascript\nconsole.log("hi");\n```';
654
676
 
677
+ render(CkConversation, {
678
+ props: { messages: [agentMessage({ text: markdown })] },
679
+ });
680
+
681
+ // UiCodeBlock surfaces the language as its header label.
682
+ expect(screen.getByText('javascript')).toBeInTheDocument();
683
+ });
684
+
685
+ it('falls back to "text" language when the fence has no language', () => {
686
+ const markdown = '```\nplain code\n```';
687
+
655
688
  const { container } = render(CkConversation, {
656
689
  props: { messages: [agentMessage({ text: markdown })] },
657
690
  });
658
691
 
659
- const codeEl = container.querySelector('pre > code');
660
- expect(codeEl).not.toBeNull();
661
- expect(codeEl?.textContent).toContain('console.log("hi");');
692
+ const codeBlock = container.querySelector('.ui-code-block');
693
+ expect(codeBlock).not.toBeNull();
694
+ expect(codeBlock?.textContent).toContain('plain code');
695
+ });
696
+ });
697
+
698
+ describe('scrollToMessage', () => {
699
+ function renderWithInstance() {
700
+ let instance: ConversationInstance | undefined;
701
+
702
+ const Wrapper = defineComponent({
703
+ setup() {
704
+ const conversationRef = ref<ConversationInstance>();
705
+ onMounted(() => {
706
+ instance = conversationRef.value;
707
+ });
708
+ return () => h(CkConversation, { messages, ref: conversationRef });
709
+ },
710
+ });
711
+
712
+ const { container } = render(Wrapper);
713
+ const scrollEl = container.querySelector(
714
+ '[class*="overflow-y-auto"]',
715
+ ) as HTMLElement;
716
+ const scrollTo = vi.fn();
717
+ scrollEl.scrollTo = scrollTo;
718
+
719
+ // jsdom reports offsetTop as 0, so stub distinct positions per row.
720
+ container
721
+ .querySelectorAll<HTMLElement>('[data-message-row]')
722
+ .forEach((row, i) => {
723
+ Object.defineProperty(row, 'offsetTop', {
724
+ configurable: true,
725
+ value: (i + 1) * 100,
726
+ });
727
+ });
728
+
729
+ return { getInstance: () => instance!, scrollTo };
730
+ }
731
+
732
+ it('delegates to the layout and scrolls to the last message by default', async () => {
733
+ // Four rows (user, agent, user, agent) → last row is at offsetTop 400.
734
+ const { getInstance, scrollTo } = renderWithInstance();
735
+
736
+ getInstance().scrollToMessage();
737
+ await nextTick();
738
+
739
+ expect(scrollTo).toHaveBeenCalledWith(
740
+ expect.objectContaining({ top: 400, behavior: 'smooth' }),
741
+ );
742
+ });
743
+
744
+ it('scrolls to the message at the given index, regardless of role', async () => {
745
+ const { getInstance, scrollTo } = renderWithInstance();
746
+
747
+ getInstance().scrollToMessage(1);
748
+ await nextTick();
749
+
750
+ expect(scrollTo).toHaveBeenCalledWith(
751
+ expect.objectContaining({ top: 200, behavior: 'smooth' }),
752
+ );
662
753
  });
663
754
  });
664
755
  });
@@ -9,7 +9,7 @@ import type {
9
9
  } from '../../../types';
10
10
  import CkConversation from './CkConversation.vue';
11
11
  import type { Meta, StoryObj } from '@storybook/vue3-vite';
12
- import { ref } from 'vue';
12
+ import { h, ref, type VNode } from 'vue';
13
13
 
14
14
  const now = new Date();
15
15
 
@@ -455,6 +455,17 @@ const customClasses = {
455
455
  />
456
456
  </template>`;
457
457
 
458
+ const defaultCodeBlockTemplateSource = `<script setup lang="ts">
459
+ import { CkConversation } from '@aleph-alpha/chat-kit';
460
+ import type { BaseMessage } from '@aleph-alpha/chat-kit';
461
+
462
+ const messages: BaseMessage[] = [/* ... */];
463
+ </script>
464
+
465
+ <template>
466
+ <CkConversation :messages="messages" agent-avatar-fallback="AI" style="height: 100%;" />
467
+ </template>`;
468
+
458
469
  const withCustomCodeBlockTemplateSource = `<script setup lang="ts">
459
470
  import { CkConversation } from '@aleph-alpha/chat-kit';
460
471
  import type { BaseMessage } from '@aleph-alpha/chat-kit';
@@ -481,6 +492,60 @@ import { CkConversation } from '@aleph-alpha/chat-kit';
481
492
  <CkConversation :messages="[]" style="height: 100%;" />
482
493
  </template>`;
483
494
 
495
+ const scrollToMessageTemplateSource = `<script setup lang="ts">
496
+ import { CkConversation } from '@aleph-alpha/chat-kit';
497
+ import type { BaseMessage } from '@aleph-alpha/chat-kit';
498
+ import { ref, useTemplateRef } from 'vue';
499
+
500
+ const messages: BaseMessage[] = [/* ... */];
501
+
502
+ const conversation = useTemplateRef('conversation');
503
+ const index = ref(0);
504
+
505
+ function scrollToMessage(): void {
506
+ // Zero-based index among all rows; omit the argument to scroll to the last.
507
+ conversation.value?.scrollToMessage(index.value);
508
+ }
509
+ </script>
510
+
511
+ <template>
512
+ <div class="flex h-[400px] flex-col">
513
+ <div class="flex items-center gap-2 border-b p-2">
514
+ <label for="msg-index">Message index</label>
515
+ <input id="msg-index" v-model.number="index" type="number" min="0" />
516
+ <button @click="scrollToMessage">Scroll to message</button>
517
+ </div>
518
+ <CkConversation
519
+ ref="conversation"
520
+ :messages="messages"
521
+ agent-avatar-fallback="AI"
522
+ class="min-h-0 flex-1"
523
+ />
524
+ </div>
525
+ <template>`;
526
+
527
+ const slotAnatomyTemplateSource = `<script setup lang="ts">
528
+ import { CkConversation } from '@aleph-alpha/chat-kit';
529
+ import type { BaseMessage } from '@aleph-alpha/chat-kit';
530
+
531
+ const messages: BaseMessage[] = [/* ... */];
532
+ </script>
533
+
534
+ <template>
535
+ <!--
536
+ Each slot has a default rendering. Overriding a parent slot replaces
537
+ everything nested beneath it, so the child slots below it no longer apply.
538
+ The anatomy story visualizes this "folding" relationship.
539
+ -->
540
+ <CkConversation :messages="messages">
541
+ <!-- Replaces the whole agent row: the header / content / footer slots
542
+ nested under it are no longer rendered. -->
543
+ <template #agent-message="{ message }">
544
+ <MyAgentBubble :message="message" />
545
+ </template>
546
+ </CkConversation>
547
+ </template>`;
548
+
484
549
  /**
485
550
  * Drop-in conversation UI. Pass `messages` with `role`, `content` (a list of
486
551
  * text / tool / reasoning parts), and `status` fields and CkConversation
@@ -506,6 +571,167 @@ export const Default: Story = {
506
571
  parameters: { docs: { source: { code: defaultTemplateSource } } },
507
572
  };
508
573
 
574
+ /**
575
+ * A slot to which the consumer can pass content, describing what its default
576
+ * rendering is and which nested slots it supersedes when overridden.
577
+ */
578
+ interface SlotDoc {
579
+ /** Slot name as used in `<template #name>`. */
580
+ name: string;
581
+ /** What overriding this slot replaces. */
582
+ summary: string;
583
+ /** Slots that live inside this one's default rendering. */
584
+ children?: SlotDoc[];
585
+ }
586
+
587
+ /**
588
+ * The slot hierarchy of `CkConversation`. Nesting mirrors the component's
589
+ * template: a child slot only renders as part of its parent's *default*
590
+ * rendering, so overriding a parent slot removes every child beneath it.
591
+ */
592
+ const slotTree: SlotDoc[] = [
593
+ {
594
+ name: 'user-message',
595
+ summary: 'Replaces the entire user row.',
596
+ children: [
597
+ {
598
+ name: 'user-message-content',
599
+ summary: 'The content inside the default CkUserMessage bubble.',
600
+ },
601
+ ],
602
+ },
603
+ {
604
+ name: 'agent-message',
605
+ summary: 'Replaces the entire agent row.',
606
+ children: [
607
+ {
608
+ name: 'agent-message-header',
609
+ summary: 'Replaces the whole CkAgentMessageHeader.',
610
+ children: [
611
+ {
612
+ name: 'agent-message-icon',
613
+ summary: 'The avatar shown for a completed message.',
614
+ },
615
+ {
616
+ name: 'agent-message-loading-icon',
617
+ summary: 'The avatar shown while the message is being generated.',
618
+ },
619
+ {
620
+ name: 'agent-message-header-content',
621
+ summary: 'The header text (e.g. a reasoning trail).',
622
+ },
623
+ {
624
+ name: 'agent-message-header-activity',
625
+ summary: 'An activity control on the right of the header.',
626
+ },
627
+ ],
628
+ },
629
+ {
630
+ name: 'agent-message-content',
631
+ summary: 'Replaces the message body (the CkMarkdownRenderer).',
632
+ children: [
633
+ {
634
+ name: 'agent-message-code-block',
635
+ summary: 'Code blocks rendered inside the default markdown.',
636
+ },
637
+ ],
638
+ },
639
+ {
640
+ name: 'agent-message-footer',
641
+ summary: 'Footer actions (a copy button by default).',
642
+ },
643
+ ],
644
+ },
645
+ {
646
+ name: 'thread-footer',
647
+ summary: 'Trailing content appended after the last message.',
648
+ },
649
+ ];
650
+
651
+ const slotPillStyle =
652
+ 'font-family: monospace; font-size: 12px; background: #eef1fb; color: #33408a; ' +
653
+ 'padding: 2px 6px; border-radius: 4px; white-space: nowrap;';
654
+ const slotSummaryTextStyle = 'color: #666; font-size: 13px;';
655
+
656
+ /** Recursively render a slot node as a foldable `<details>` tree. */
657
+ function renderSlotNode(node: SlotDoc): VNode {
658
+ const children = node.children ?? [];
659
+ const label = h(
660
+ 'span',
661
+ {
662
+ style:
663
+ 'display: inline-flex; align-items: baseline; gap: 8px; flex-wrap: wrap;',
664
+ },
665
+ [
666
+ h('code', { style: slotPillStyle }, node.name),
667
+ h('span', { style: slotSummaryTextStyle }, node.summary),
668
+ ],
669
+ );
670
+
671
+ if (children.length === 0) {
672
+ return h('div', { style: 'padding: 6px 0 6px 20px;' }, [label]);
673
+ }
674
+
675
+ return h(
676
+ 'details',
677
+ {
678
+ open: true,
679
+ style: 'padding: 6px 0;',
680
+ },
681
+ [
682
+ h('summary', { style: 'cursor: pointer; padding: 2px 0;' }, [label]),
683
+ h(
684
+ 'div',
685
+ {
686
+ style:
687
+ 'margin: 4px 0 0 8px; padding-left: 12px; border-left: 1px solid #e0e0e0;',
688
+ },
689
+ children.map(renderSlotNode),
690
+ ),
691
+ ],
692
+ );
693
+ }
694
+
695
+ /**
696
+ * A diagram of how CkConversation's slots nest. Every slot has a default
697
+ * rendering; overriding a parent slot replaces everything nested beneath it,
698
+ * so the child slots below it no longer apply. Collapse a node to see which
699
+ * slots "fold away" when you take over its parent.
700
+ */
701
+ export const SlotAnatomy: Story = {
702
+ // Emoji prefix marks this out in the sidebar as a reference diagram rather
703
+ // than a rendered component example.
704
+ name: '🧩 Slot Anatomy',
705
+ render: () => ({
706
+ setup() {
707
+ return () =>
708
+ h(
709
+ 'div',
710
+ {
711
+ // Fill and scroll within the meta decorator's fixed-height frame
712
+ // instead of being clipped by its `overflow: hidden`.
713
+ style:
714
+ 'font-family: system-ui, sans-serif; padding: 16px; line-height: 1.5; ' +
715
+ 'height: 100%; overflow-y: auto; box-sizing: border-box;',
716
+ },
717
+ [
718
+ h(
719
+ 'p',
720
+ { style: 'margin: 0 0 12px; color: #444; font-size: 13px;' },
721
+ 'Every slot has a default rendering. Overriding a parent slot ' +
722
+ 'replaces everything nested beneath it — the child slots below ' +
723
+ 'it no longer apply. Collapse a node to see which slots fold away.',
724
+ ),
725
+ ...slotTree.map(renderSlotNode),
726
+ ],
727
+ );
728
+ },
729
+ }),
730
+ parameters: {
731
+ docs: { source: { code: slotAnatomyTemplateSource } },
732
+ },
733
+ };
734
+
509
735
  /**
510
736
  * Uses a remote avatar image (with fallback text). Use when you want a
511
737
  * branded agent identity in each reply.
@@ -826,9 +1052,61 @@ export const WithCustomMarkdownClasses: Story = {
826
1052
  };
827
1053
 
828
1054
  /**
829
- * Integrates a custom code-block renderer (Shiki, Prism, etc.) via
830
- * `#agent-message-code-block`. Use when you want syntax highlighting or
831
- * inline copy buttons for assistant code.
1055
+ * Fenced code blocks in agent markdown render with `UiCodeBlock` out of the
1056
+ * box — syntax highlighting, a language label, and a copy button — without any
1057
+ * slot wiring.
1058
+ */
1059
+ export const DefaultCodeBlock: Story = {
1060
+ render: () => ({
1061
+ components: { CkConversation },
1062
+ setup() {
1063
+ const messages: BaseMessage[] = [
1064
+ {
1065
+ id: '1',
1066
+ role: 'user',
1067
+ content: [text('Show me a code example')],
1068
+ createdAt: now,
1069
+ status: 'completed',
1070
+ },
1071
+ {
1072
+ id: '2',
1073
+ role: 'assistant',
1074
+ content: [
1075
+ text(
1076
+ [
1077
+ 'Here is an example:',
1078
+ '',
1079
+ '```typescript',
1080
+ 'const greeting = "Hello, world!";',
1081
+ 'console.log(greeting);',
1082
+ '```',
1083
+ '',
1084
+ 'And another one:',
1085
+ '',
1086
+ '```python',
1087
+ 'def greet(name: str) -> str:',
1088
+ ' return f"Hello, {name}!"',
1089
+ '```',
1090
+ ].join('\n'),
1091
+ ),
1092
+ ],
1093
+ createdAt: now,
1094
+ status: 'completed',
1095
+ },
1096
+ ];
1097
+ return { messages };
1098
+ },
1099
+ template: `
1100
+ <CkConversation :messages="messages" agent-avatar-fallback="AI" style="height: 100%;" />
1101
+ `,
1102
+ }),
1103
+ parameters: { docs: { source: { code: defaultCodeBlockTemplateSource } } },
1104
+ };
1105
+
1106
+ /**
1107
+ * Fenced code blocks render with `UiCodeBlock` (syntax highlighting + copy
1108
+ * button) by default. Override that with a custom renderer (Prism, a bespoke
1109
+ * theme, etc.) via `#agent-message-code-block`, as shown here.
832
1110
  */
833
1111
  export const WithCustomCodeBlock: Story = {
834
1112
  render: () => ({
@@ -884,6 +1162,52 @@ export const WithCustomCodeBlock: Story = {
884
1162
  parameters: { docs: { source: { code: withCustomCodeBlockTemplateSource } } },
885
1163
  };
886
1164
 
1165
+ /**
1166
+ * Programmatic navigation via the exposed `scrollToMessage(index)` method. Enter
1167
+ * a zero-based row index and the conversation scrolls that message to the top.
1168
+ * Index counts all rows regardless of role (a `thread-footer`, when present, is
1169
+ * the trailing row); omitting the index scrolls to the last row.
1170
+ */
1171
+ export const ScrollToMessage: Story = {
1172
+ render: () => ({
1173
+ components: { CkConversation },
1174
+ setup() {
1175
+ const messages: BaseMessage[] = Array.from({ length: 10 }, (_, i) => ({
1176
+ id: `m-${i}`,
1177
+ role: i % 2 === 0 ? 'user' : 'assistant',
1178
+ content: [
1179
+ text(
1180
+ `[${i}] ${
1181
+ i % 2 === 0 ? 'User' : 'Agent'
1182
+ } message number ${i}. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore.`,
1183
+ ),
1184
+ ],
1185
+ createdAt: now,
1186
+ status: 'completed',
1187
+ }));
1188
+ const conversation = ref();
1189
+ const index = ref(0);
1190
+ function scrollToMessage() {
1191
+ conversation.value?.scrollToMessage(index.value);
1192
+ }
1193
+ return { messages, conversation, index, scrollToMessage };
1194
+ },
1195
+ template: `
1196
+ <div style="display: flex; flex-direction: column; height: 100%;">
1197
+ <div style="display: flex; align-items: center; gap: 8px; padding: 8px; border-bottom: 1px solid #e0e0e0;">
1198
+ <label for="msg-index">Message index</label>
1199
+ <input id="msg-index" v-model.number="index" type="number" min="0" style="width: 72px; padding: 4px 8px; border: 1px solid #ccc; border-radius: 6px;" />
1200
+ <button @click="scrollToMessage" style="padding: 6px 16px; border-radius: 6px; background: #333; color: white; cursor: pointer;">
1201
+ Scroll to message
1202
+ </button>
1203
+ </div>
1204
+ <CkConversation ref="conversation" :messages="messages" agent-avatar-fallback="AI" style="flex: 1; min-height: 0;" />
1205
+ </div>
1206
+ `,
1207
+ }),
1208
+ parameters: { docs: { source: { code: scrollToMessageTemplateSource } } },
1209
+ };
1210
+
887
1211
  /**
888
1212
  * Empty state — an initial view before the first turn. Use to show a welcome
889
1213
  * screen, quick prompts, or onboarding content above this surface.