Skip to content
Merged
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
10 changes: 10 additions & 0 deletions .changeset/ai-assistant-react-ui.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@tanstack/create': patch
---

Rebuild the React AI add-on's floating "AI Assistant" on the
`@tanstack/ai-react/ui` `createChatHook` registry pattern. The assistant now
registers layout/message/input chrome plus text and `recommendGuitar` tool
components instead of hand-rolling message rendering, matching the newer
react-ui chat architecture. Behaviour and styling are unchanged; the guitar
recommendation card still renders inline.
56 changes: 49 additions & 7 deletions packages/cli/tests-e2e/ai-smoke.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,45 @@ test('@blocking builds the AI scaffold and streams a mocked chat without provide
})
expect(invalid.status()).toBe(400)
await optimizePageForFastE2E(page)
let threadId: unknown
const threadIds: Array<unknown> = []
await page.route('**/demo/api/ai/chat', async (route) => {
threadId = route.request().postDataJSON().threadId
const { threadId } = route.request().postDataJSON()
threadIds.push(threadId)
const floating = threadIds.length === 2
const reply = floating ? 'Floating assistant reply' : 'Local mock reply'
const messageId = `mock-message-${threadIds.length}`
const toolCallId = 'mock-guitar'
const events = [
{ type: 'RUN_STARTED', threadId, runId: 'mock-run' },
{
type: 'TEXT_MESSAGE_START',
messageId: 'mock-message',
messageId,
role: 'assistant',
},
{
type: 'TEXT_MESSAGE_CONTENT',
messageId: 'mock-message',
delta: 'Local mock reply',
messageId,
delta: reply,
},
{ type: 'TEXT_MESSAGE_END', messageId: 'mock-message' },
{ type: 'TEXT_MESSAGE_END', messageId },
...(floating
? [
{
type: 'TOOL_CALL_START',
toolCallId,
toolCallName: 'recommendGuitar',
parentMessageId: messageId,
},
{ type: 'TOOL_CALL_ARGS', toolCallId, delta: '{"id":2}' },
{ type: 'TOOL_CALL_END', toolCallId },
{
type: 'TOOL_CALL_RESULT',
messageId: 'mock-guitar-result',
toolCallId,
content: '{"id":2}',
},
]
: []),
{ type: 'RUN_FINISHED', threadId, runId: 'mock-run' },
]
await route.fulfill({
Expand All @@ -57,7 +80,26 @@ test('@blocking builds the AI scaffold and streams a mocked chat without provide
await expect(
page.getByText('Local mock reply', { exact: true }),
).toBeVisible()
expect(threadId).toBe('guitar-recommendations')
await page.getByRole('link', { name: 'Home', exact: true }).click()
await expect(page).toHaveURL(new URL('/', fixture.url).href)
await page
.getByRole('button', { name: 'AI Assistant', exact: true })
.click({ timeout: 7_000 })
const assistantInput = page.getByPlaceholder('Type your message...')
await assistantInput.fill('Hello from the floating assistant', {
timeout: 7_000,
})
await assistantInput.press('Enter', { timeout: 7_000 })
await expect(
page.getByText('Floating assistant reply', { exact: true }),
).toBeVisible()
expect(threadIds).toEqual([
'guitar-recommendations',
'guitar-recommendations',
])
await expect(
page.getByRole('heading', { name: 'Video Game Guitar', exact: true }),
).toBeVisible()
} finally {
await fixture.stop()
await fixture.cleanup()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { createChatHookContexts } from '@tanstack/ai-react/ui'

// Scoped contexts so the registered chrome/part/tool widgets can read the
// chat instance even though they live in separate files from the hook.
export const { chatContext, partContext, interruptContext } =
createChatHookContexts()
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { useEffect, useRef, useState } from 'react'
import { createChatHook } from '@tanstack/ai-react/ui'
import type {
LayoutProps,
MessageProps,
PartProps,
ToolProps,
} from '@tanstack/ai-react/ui'

import { Send } from 'lucide-react'
import { Streamdown } from 'streamdown'

import { chatOptions } from '#/lib/demo-ai-hook'
import GuitarRecommendation from '#/components/demo-GuitarRecommendation'

import {
chatContext,
interruptContext,
partContext,
} from './demo-ai-ui-context'

// The chrome around the message list. `Messages` and `Input` are supplied by
// the kit; this component owns the scroll container and auto-scroll behaviour.
function ChatLayout({ Messages, Input }: LayoutProps<typeof chatOptions>) {
const chat = useChatContext()
const scrollRef = useRef<HTMLDivElement>(null)

useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight
}
}, [chat.messages])

return (
<div className="flex min-h-0 flex-1 flex-col">
{chat.error ? (
<p className="p-4 text-sm text-red-500">{chat.error.message}</p>
) : null}
<div ref={scrollRef} className="flex-1 overflow-y-auto">
{chat.messages.length === 0 ? (
<div className="demo-muted flex h-full items-center justify-center text-sm">
Ask me anything! I'm here to help.
</div>
) : (
<Messages />
)}
</div>
<div className="border-t border-[var(--line)] p-3">
<Input />
</div>
</div>
)
}

// One message row: an avatar chip plus the automatically-dispatched parts.
function ChatMessage({ message, Parts }: MessageProps<typeof chatOptions>) {
const isAssistant = message.role === 'assistant'
return (
<div className={`py-3 ${isAssistant ? 'bg-[var(--chip-bg)]' : ''}`}>
<div className="flex items-start gap-2 px-4">
<div
className={`flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-lg text-xs font-medium text-white ${
isAssistant ? 'bg-[var(--lagoon-deep)]' : 'bg-[var(--sea-ink-soft)]'
}`}
>
{isAssistant ? 'AI' : 'Y'}
</div>
<div className="min-w-0 flex-1 max-w-none text-sm text-[var(--sea-ink)]">
<Parts />
</div>
</div>
</div>
)
}

// The message composer.
function ChatInput() {
const chat = useChatContext()
const [input, setInput] = useState('')

const send = () => {
const trimmed = input.trim()
if (!trimmed) return
void chat.sendMessage(trimmed)
setInput('')
}

return (
<form
onSubmit={(e) => {
e.preventDefault()
send()
}}
>
<div className="relative">
<textarea
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Type your message..."
className="demo-textarea pr-10 text-sm"
rows={1}
style={{ minHeight: '36px', maxHeight: '120px' }}
onInput={(e) => {
const target = e.target as HTMLTextAreaElement
target.style.height = 'auto'
target.style.height = Math.min(target.scrollHeight, 120) + 'px'
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
send()
}
}}
/>
<button
type="submit"
disabled={!input.trim()}
className="absolute right-2 top-1/2 -translate-y-1/2 p-1.5 text-[var(--lagoon-deep)] transition-colors hover:text-[var(--sea-ink)] disabled:text-[var(--sea-ink-soft)]"
>
<Send className="w-4 h-4" />
</button>
</div>
</form>
)
}

// Markdown text part.
function TextPart({ part }: PartProps<typeof chatOptions, 'text'>) {
if (!part.content) return null
return <Streamdown>{part.content}</Streamdown>
}

// Anything the assistant emits that we don't render explicitly (e.g. the
// server-side getGuitars lookup) is intentionally suppressed.
function FallbackPart() {
return null
}

// The recommendGuitar client tool renders the rich guitar card.
function RecommendGuitarTool({
part,
}: ToolProps<typeof chatOptions, 'recommendGuitar'>) {
if (!part.output) return null
return (
<div className="mx-auto max-w-[80%]">
<GuitarRecommendation id={String(part.output.id)} />
</div>
)
}

export const { useAppChat, useChatContext } = createChatHook({
options: chatOptions,
context: {
chatContext,
partContext,
interruptContext,
},
components: {
layout: ChatLayout,
message: ChatMessage,
input: ChatInput,
},
partsComponents: {
text: TextPart,
fallback: FallbackPart,
},
toolsComponents: {
recommendGuitar: RecommendGuitarTool,
},
})
Loading
Loading