Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions layers/nuxi/agent/lib/identity/surface-instructions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.`

Expand All @@ -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<Record<Surface, string>> = {
web: WEB_INSTRUCTIONS,
discord: DISCORD_INSTRUCTIONS,
slack: SLACK_INSTRUCTIONS
}
Expand Down
2 changes: 2 additions & 0 deletions layers/nuxi/app/components/agent/AgentChatMessages.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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)"
/>
</div>
</div>
Expand Down
8 changes: 5 additions & 3 deletions layers/nuxi/app/components/agent/AgentComark.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'])
Expand All @@ -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'
})
44 changes: 44 additions & 0 deletions layers/nuxi/app/components/agent/AgentFollowUps.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<script setup lang="ts">
defineOptions({ inheritAttrs: false })

const props = defineProps<{ first?: string, second?: string }>()
const followUp = inject<{ enabled: Ref<boolean>, ask: (question: string) => void }>('chat-follow-up')
const { rateLimitReached } = useNuxtAgent()
const selected = ref(false)
const questions = computed(() => [...new Set([props.first, props.second]
.filter((value): value is string => typeof value === 'string')
.map(value => value.trim())
.filter(value => value.length > 0 && value.length <= 100))])

function ask(question: string) {
selected.value = true
followUp?.ask(question)
}
</script>

<template>
<Transition
enter-from-class="opacity-0 translate-y-1 motion-reduce:translate-y-0"
enter-active-class="transition-[opacity,transform] duration-200 ease-out motion-reduce:transition-none"
>
<div
v-if="followUp?.enabled.value && !rateLimitReached && !selected && questions.length"
class="flex flex-wrap gap-2 pt-3 pb-1"
role="group"
aria-label="Suggested follow-up questions"
data-follow-up-suggestions
>
<UButton
v-for="question in questions"
:key="question"
:label="question"
color="neutral"
variant="outline"
size="xs"
class="max-w-full rounded-full bg-default px-3 py-1.5 text-left font-normal text-muted shadow-xs transition-[color,border-color,box-shadow] duration-150 hover:border-primary/40 hover:text-highlighted hover:shadow-sm motion-reduce:transition-none"
:ui="{ label: 'whitespace-normal' }"
@click="ask(question)"
/>
</div>
</Transition>
</template>
9 changes: 7 additions & 2 deletions layers/nuxi/app/components/agent/AgentStreamText.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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[] = [{
Expand Down
5 changes: 4 additions & 1 deletion layers/nuxi/app/components/chat/ChatContent.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>()

function onTextPending(key: string, pending: boolean) {
Expand Down Expand Up @@ -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)"
/>
</template>
</template>
Expand Down
4 changes: 2 additions & 2 deletions layers/nuxi/app/components/chat/ChatMessageActions.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand Down
15 changes: 10 additions & 5 deletions layers/nuxi/app/composables/useStreamedText.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions layers/nuxi/app/pages/dashboard/chat/[id].vue
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ const {
prompt,
getVote,
vote,
askQuestion,
onSubmit,
handlePaste,
removeAttachment
Expand Down Expand Up @@ -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"
Expand Down
4 changes: 4 additions & 0 deletions layers/nuxi/app/utils/ai.ts
Original file line number Diff line number Diff line change
@@ -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) {
Expand Down
59 changes: 59 additions & 0 deletions test/nuxt/chat-follow-ups.spec.ts
Original file line number Diff line number Diff line change
@@ -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: '<main><slot name="body" /></main>' },
AgentChatBody: { emits: ['askQuestion'], template: '<button @click="$emit(\'askQuestion\', \'How can I debug hydration?\')">Follow up</button>' }
}
}
})
try {
await wrapper.get('button').trigger('click')
expect(askQuestion).toHaveBeenCalledExactlyOnceWith('How can I debug hydration?')
} finally {
wrapper.unmount()
}
})
32 changes: 32 additions & 0 deletions test/unit/chat-follow-ups.spec.ts
Original file line number Diff line number Diff line change
@@ -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{')
}
})
})
18 changes: 18 additions & 0 deletions test/unit/streamed-text.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
})
})
Loading