From 016c4dd86081cf223d2c2cb008a376f7dcf16257 Mon Sep 17 00:00:00 2001 From: Hugo Richard Date: Wed, 18 Nov 2026 14:45:06 +0100 Subject: [PATCH 1/2] feat(nuxi): suggest contextual follow-up questions --- .../lib/identity/surface-instructions.ts | 6 +++ .../components/agent/AgentChatMessages.vue | 2 + .../nuxi/app/components/agent/AgentComark.ts | 8 ++-- .../app/components/agent/AgentFollowUps.vue | 44 +++++++++++++++++++ .../app/components/agent/AgentStreamText.vue | 9 +++- .../nuxi/app/components/chat/ChatContent.vue | 5 ++- .../components/chat/ChatMessageActions.vue | 4 +- .../nuxi/app/composables/useStreamedText.ts | 15 ++++--- layers/nuxi/app/utils/ai.ts | 4 ++ test/unit/chat-follow-ups.spec.ts | 32 ++++++++++++++ test/unit/streamed-text.spec.ts | 18 ++++++++ 11 files changed, 134 insertions(+), 13 deletions(-) create mode 100644 layers/nuxi/app/components/agent/AgentFollowUps.vue create mode 100644 test/unit/chat-follow-ups.spec.ts diff --git a/layers/nuxi/agent/lib/identity/surface-instructions.ts b/layers/nuxi/agent/lib/identity/surface-instructions.ts index 01e1d217f..1ee69abda 100644 --- a/layers/nuxi/agent/lib/identity/surface-instructions.ts +++ b/layers/nuxi/agent/lib/identity/surface-instructions.ts @@ -7,6 +7,11 @@ import type { Surface } from './context.js' * belong in the always-on prompt instead, resolved once per session from the * principal (see `instructions.ts`). */ +const WEB_INSTRUCTIONS = `**Follow-up questions — web chat:** +- After a helpful answer, suggest up to two short questions the user could ask next to make progress: understand the concept, try a concrete example, debug the next likely obstacle, or apply the answer to their project. Use the conversation and the user's current goal; do not repeat questions you already answered or force generic suggestions. +- Write them from the user's perspective, in their language, at most 100 characters each. Skip suggestions for greetings, unresolved tool failures, or when there is no useful next step. +- Append one Comark component at the very end of the answer on its own line: \`:follow-ups{first="How can I debug hydration?" second="Can you show a minimal example?"}\`. Omit \`second\` when only one question is useful. Escape quotes inside attribute values. The UI turns these into clickable pills; do not repeat them as a heading or prose.` + const SLACK_INSTRUCTIONS = `**You are on Slack.** - **Slack emojis:** When it fits, use our workspace custom emojis (sparingly — 0–2 per message) instead of generic Unicode emoji: :nuxter: (Nuxt logo), :nuxt-intensifies:, :nuxt_lurk:, :nuxt_cool:, :nuxi:. Examples: :nuxter: or :nuxi: for greetings or Nuxt pride; :nuxt_cool: when something works; :nuxt-intensifies: for excitement; :nuxt_lurk: while investigating. Use Slack :colon: syntax exactly as written.` @@ -17,6 +22,7 @@ const DISCORD_INSTRUCTIONS = `**You are on Discord, answering in a thread (like - Prefer compact replies — Discord caps a message at 2000 characters, so anything longer is split across follow-up messages.` const BY_SURFACE: Partial> = { + web: WEB_INSTRUCTIONS, discord: DISCORD_INSTRUCTIONS, slack: SLACK_INSTRUCTIONS } diff --git a/layers/nuxi/app/components/agent/AgentChatMessages.vue b/layers/nuxi/app/components/agent/AgentChatMessages.vue index 24af9720f..fa35f5a1b 100644 --- a/layers/nuxi/app/components/agent/AgentChatMessages.vue +++ b/layers/nuxi/app/components/agent/AgentChatMessages.vue @@ -167,7 +167,9 @@ defineShortcuts({ :animate="liveMessages.has(message.id)" :preparing="message.id === betweenStepsMessageId && !revealingMessages.has(message.id)" :streaming="(chat.status === 'submitted' || chat.status === 'streaming') && message.id === chat.messages.at(-1)?.id" + :show-follow-ups="message.id === chat.messages.at(-1)?.id && chat.status === 'ready' && !isAssistantPending(message)" @pending="onMessagePending(message.id, $event)" + @follow-up="emit('askQuestion', $event)" /> diff --git a/layers/nuxi/app/components/agent/AgentComark.ts b/layers/nuxi/app/components/agent/AgentComark.ts index 4104123ed..f174ce7de 100644 --- a/layers/nuxi/app/components/agent/AgentComark.ts +++ b/layers/nuxi/app/components/agent/AgentComark.ts @@ -2,13 +2,14 @@ import rangi from '@comark/vue/plugins/rangi' import security from 'comark/plugins/security' import type { ElementNode } from 'comark' import SourceLink from '#layers/nuxi/app/components/tools/SourceLink.vue' +import AgentFollowUps from './AgentFollowUps.vue' -// Only the tags plain markdown produces are rendered; anything else is unwrapped or dropped. +// Render Markdown and explicit chat components; unwrap or drop other tags. const allowedTags = [ 'p', 'br', 'hr', 'span', 'a', 'strong', 'em', 'b', 'i', 'u', 's', 'del', 'mark', 'small', 'sub', 'sup', 'kbd', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'ul', 'ol', 'li', 'code', 'pre', 'img', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'details', 'summary', - 'source-link' + 'source-link', 'follow-ups' ] const droppedTags = new Set(['script', 'style', 'iframe', 'frame', 'object', 'embed', 'template', 'textarea', 'title', 'noscript', 'svg', 'math']) @@ -30,7 +31,8 @@ export default defineMarkdownComponent({ ], components: { ...proseComponents, - 'source-link': SourceLink + 'source-link': SourceLink, + 'follow-ups': AgentFollowUps }, class: '*:first:mt-0 *:last:mb-0' }) diff --git a/layers/nuxi/app/components/agent/AgentFollowUps.vue b/layers/nuxi/app/components/agent/AgentFollowUps.vue new file mode 100644 index 000000000..8b04288f9 --- /dev/null +++ b/layers/nuxi/app/components/agent/AgentFollowUps.vue @@ -0,0 +1,44 @@ + + + diff --git a/layers/nuxi/app/components/agent/AgentStreamText.vue b/layers/nuxi/app/components/agent/AgentStreamText.vue index 24940db90..58c27939e 100644 --- a/layers/nuxi/app/components/agent/AgentStreamText.vue +++ b/layers/nuxi/app/components/agent/AgentStreamText.vue @@ -6,17 +6,22 @@ const props = defineProps<{ value: string streaming: boolean animate?: boolean + showFollowUps?: boolean }>() -const emit = defineEmits<{ pending: [value: boolean] }>() +const emit = defineEmits<{ pending: [value: boolean], followUp: [question: string] }>() const { text, pending } = useStreamedText(() => props.value, () => props.streaming, props.animate) +provide('chat-follow-up', { + enabled: computed(() => !!props.showFollowUps && !pending.value), + ask: (question: string) => emit('followUp', question) +}) // Keep the same word nodes when the turn settles, including a one-word reply. const animate = props.animate || props.streaming function wrapWords(node: Node): Node[] { if (typeof node === 'string') { return Array.from(streamWordSegmenter.segment(node), ({ segment }) => /^\s+$/u.test(segment) ? segment : ['span', { class: 'nuxi-stream-word' }, segment]) } - if (!node[0] || ['pre', 'code', 'source-link'].includes(node[0]) || node[1].class === 'nuxi-stream-word') return [node] + if (!node[0] || ['pre', 'code', 'source-link', 'follow-ups'].includes(node[0]) || node[1].class === 'nuxi-stream-word') return [node] return [[node[0], node[1], ...node.slice(2).flatMap(child => wrapWords(child as Node))]] } const plugins: ComarkPlugin[] = [{ diff --git a/layers/nuxi/app/components/chat/ChatContent.vue b/layers/nuxi/app/components/chat/ChatContent.vue index 93c91df11..5a8390cbb 100644 --- a/layers/nuxi/app/components/chat/ChatContent.vue +++ b/layers/nuxi/app/components/chat/ChatContent.vue @@ -11,12 +11,13 @@ const props = defineProps<{ animate?: boolean streaming?: boolean preparing?: boolean + showFollowUps?: boolean }>() const parts = computed(() => getMergedParts(props.message.parts)) const activity = computed(() => parts.value.filter((part): part is ToolPart | ReasoningUIPart => isToolUIPart(part) || (isReasoningUIPart(part) && part.text.trim().length > 0))) -const emit = defineEmits<{ pending: [value: boolean] }>() +const emit = defineEmits<{ pending: [value: boolean], followUp: [question: string] }>() const pendingParts = new Set() function onTextPending(key: string, pending: boolean) { @@ -85,7 +86,9 @@ function partKey(part: UIMessage['parts'][number], index: number) { :value="part.text" :streaming="streaming && isPartStreaming(part)" :animate="animate" + :show-follow-ups="showFollowUps" @pending="onTextPending(partKey(part, partIndex), $event)" + @follow-up="emit('followUp', $event)" /> diff --git a/layers/nuxi/app/components/chat/ChatMessageActions.vue b/layers/nuxi/app/components/chat/ChatMessageActions.vue index 13a90f7df..0ff3dc1b4 100644 --- a/layers/nuxi/app/components/chat/ChatMessageActions.vue +++ b/layers/nuxi/app/components/chat/ChatMessageActions.vue @@ -21,10 +21,10 @@ const { refresh: refreshChats } = useChats() const toast = useToast() const textContent = computed(() => { - return props.message.parts + return stripFollowUpSuggestions(props.message.parts .filter(p => p.type === 'text') .map(p => (p as { text: string }).text) - .join('\n') + .join('\n')) }) const createdAt = computed(() => { diff --git a/layers/nuxi/app/composables/useStreamedText.ts b/layers/nuxi/app/composables/useStreamedText.ts index cd33833fd..608aeb13e 100644 --- a/layers/nuxi/app/composables/useStreamedText.ts +++ b/layers/nuxi/app/composables/useStreamedText.ts @@ -13,11 +13,16 @@ function nextTextBoundary(text: string, position: number, budget: number, comple if (end >= target) break } - const citationStart = text.indexOf(':source-link{', position) - if (citationStart >= 0 && citationStart < end) { - const citationEnd = text.indexOf('}', citationStart) - if (citationEnd >= 0) return citationEnd + 1 - if (!complete) return Math.max(position, citationStart) + const componentStart = text.slice(position).search(/:source-link\{|:follow-ups\{/) + if (componentStart >= 0 && position + componentStart < end) { + const start = position + componentStart + const component = /^:[\w-]+\{(?:[^}"'\\]|\\[\s\S]|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*')*\}/u.exec(text.slice(start)) + if (component) return start + component[0].length + if (!complete) return Math.max(position, start) + } + const colon = text.lastIndexOf(':') + if (!complete && colon >= position && [':source-link{', ':follow-ups{'].some(marker => marker.startsWith(text.slice(colon)))) { + end = Math.min(end, colon) } const candidate = text.slice(0, end) diff --git a/layers/nuxi/app/utils/ai.ts b/layers/nuxi/app/utils/ai.ts index 64a233b74..0f9af9e1d 100644 --- a/layers/nuxi/app/utils/ai.ts +++ b/layers/nuxi/app/utils/ai.ts @@ -1,6 +1,10 @@ import type { UIMessage } from 'ai' import { isTextUIPart } from 'ai' +export function stripFollowUpSuggestions(text: string): string { + return text.replace(/(?:^|\n)\s*:follow-ups\{(?:[^}"'\\]|\\[\s\S]|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*')*\}\s*$/u, '').trimEnd() +} + export function getMergedParts(parts: UIMessage['parts']): UIMessage['parts'] { const result: UIMessage['parts'] = [] for (const part of parts) { diff --git a/test/unit/chat-follow-ups.spec.ts b/test/unit/chat-follow-ups.spec.ts new file mode 100644 index 000000000..2346672dd --- /dev/null +++ b/test/unit/chat-follow-ups.spec.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest' +import { parseMarkdown } from 'comark' +import { stripFollowUpSuggestions } from '../../layers/nuxi/app/utils/ai' +import { surfaceInstructions } from '../../layers/nuxi/agent/lib/identity/surface-instructions' + +describe('follow-up suggestions', () => { + const suggestions = ':follow-ups{first="How can I debug hydration?" second="Can you show an example?"}' + + it('uses native Comark props for the suggested questions', async () => { + const parsed = await parseMarkdown(`An answer.\n\n${suggestions}`) + expect(parsed.nodes.at(-1)).toEqual(['follow-ups', { + first: 'How can I debug hydration?', second: 'Can you show an example?' + }]) + }) + + it('copies the answer without the suggestion component', () => { + expect(stripFollowUpSuggestions(`An answer.\n\n${suggestions}`)).toBe('An answer.') + expect(stripFollowUpSuggestions('An answer.\n\n:follow-ups{first="Explain {{ name }}?"}')).toBe('An answer.') + }) + + it('preserves component syntax shown in a code sample', () => { + const sample = `For example:\n\n\`\`\`md\n${suggestions}\n\`\`\`` + expect(stripFollowUpSuggestions(sample)).toBe(sample) + }) + + it('requests suggestions only for the web chat', () => { + expect(surfaceInstructions('web')).toContain(':follow-ups{') + for (const surface of ['slack', 'discord', 'schedule', 'cli'] as const) { + expect(surfaceInstructions(surface) ?? '').not.toContain(':follow-ups{') + } + }) +}) diff --git a/test/unit/streamed-text.spec.ts b/test/unit/streamed-text.spec.ts index c96e74add..f9e34c4f5 100644 --- a/test/unit/streamed-text.spec.ts +++ b/test/unit/streamed-text.spec.ts @@ -78,4 +78,22 @@ describe('streamed text', () => { replay.stop() } }) + + it('holds follow-up markup across chunks and reveals the whole component at once', async () => { + const replay = setup('Here is the answer.\n\n:follow') + try { + replay.drain() + expect(replay.stream.text.value).toBe('Here is the answer.\n\n') + replay.source.value += '-ups{first="How does {{ name }}' + await nextTick() + replay.drain() + expect(replay.stream.text.value).toBe('Here is the answer.\n\n') + replay.source.value += ' work?"}' + await nextTick() + replay.drain() + expect(replay.stream.text.value).toBe(replay.source.value) + } finally { + replay.stop() + } + }) }) From 592f80ad884047c9e7c03b63fdcf156a6d10474d Mon Sep 17 00:00:00 2001 From: Hugo Richard Date: Wed, 18 Nov 2026 15:13:48 +0100 Subject: [PATCH 2/2] fix(nuxi): send follow-up suggestions from the chat page --- layers/nuxi/app/pages/dashboard/chat/[id].vue | 2 + test/nuxt/chat-follow-ups.spec.ts | 59 +++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 test/nuxt/chat-follow-ups.spec.ts diff --git a/layers/nuxi/app/pages/dashboard/chat/[id].vue b/layers/nuxi/app/pages/dashboard/chat/[id].vue index 600fdcf55..a2bb28a25 100644 --- a/layers/nuxi/app/pages/dashboard/chat/[id].vue +++ b/layers/nuxi/app/pages/dashboard/chat/[id].vue @@ -54,6 +54,7 @@ const { prompt, getVote, vote, + askQuestion, onSubmit, handlePaste, removeAttachment @@ -148,6 +149,7 @@ useNuxiChatSeo({ header: 'px-1.5 pt-1.5 pb-0 gap-1.5 flex flex-wrap items-start' }" @submit="onSubmit" + @ask-question="askQuestion" @paste="handlePaste" @remove-attachment="removeAttachment" @vote="vote" diff --git a/test/nuxt/chat-follow-ups.spec.ts b/test/nuxt/chat-follow-ups.spec.ts new file mode 100644 index 000000000..da55a4286 --- /dev/null +++ b/test/nuxt/chat-follow-ups.spec.ts @@ -0,0 +1,59 @@ +import { expect, it, vi } from 'vitest' +import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime' +import ChatPage from '../../layers/nuxi/app/pages/dashboard/chat/[id].vue' + +const { askQuestion } = vi.hoisted(() => ({ askQuestion: vi.fn() })) + +vi.mock('../../layers/nuxi/app/composables/useNuxiChat', async () => { + const { ref } = await import('vue') + return { + setupStaleChatRefresh: () => {}, + useNuxiChat: () => ({ + chat: { messages: [], status: 'ready' }, + input: ref(''), + prompt: ref({ canSubmit: true, pasteAttachments: [] }), + getVote: () => null, + vote: vi.fn(), + askQuestion, + onSubmit: vi.fn(), + handlePaste: vi.fn(), + removeAttachment: vi.fn() + }) + } +}) + +vi.mock('../../layers/nuxi/app/composables/useChatDetail', async () => { + const { ref } = await import('vue') + return { + resolveChatRouteId: () => 'follow-up-chat', + useChatRouteId: () => ref('follow-up-chat'), + useChatDetail: () => ({ + data: ref({ isOwner: true, title: 'Follow-up chat', messages: [] }), + error: ref(null), + status: ref('success'), + refresh: async () => {} + }) + } +}) + +mockNuxtImport('useUserSession', () => () => ({ loggedIn: ref(true) })) +mockNuxtImport('useNuxtAgent', () => () => ({ usage: ref(), rateLimitReached: ref(false) })) +mockNuxtImport('useChats', () => () => ({ refresh: vi.fn() })) +mockNuxtImport('useNuxiChatSeo', () => () => {}) + +it('sends a follow-up from the full chat page through its chat handler', async () => { + const wrapper = await mountSuspended(ChatPage, { + global: { + stubs: { + UDashboardPanel: { template: '
' }, + AgentChatBody: { emits: ['askQuestion'], template: '' } + } + } + }) + try { + await wrapper.get('button').trigger('click') + expect(askQuestion).toHaveBeenCalledExactlyOnceWith('How can I debug hydration?') + } finally { + wrapper.unmount() + } +})