mirror of
https://github.com/simstudioai/sim.git
synced 2026-09-24 15:45:35 +08:00
improvement(docs): remove Ask AI, add the missing platform surfaces, align the sidebar (#6259)
* improvement(docs): remove Ask AI, add missing surfaces, align sidebar to the app - Removes the Ask AI widget, its /api/chat route, and the four deps exclusive to it (@ai-sdk/openai, @ai-sdk/react, ai, streamdown). lib/embeddings and docsEmbeddings stay — /api/search uses them. - Adds --surface-7 and --surface-hover, the last two platform surfaces docs lacked. - Aligns the sidebar with the app's canonical nav chrome: px-2.5 -> px-2, text-small -> text-sm, hover --surface-3 -> --surface-active, and an active hover of --surface-6, matching the Chip the app's sidebar items are built on. * fix(docs): make the sidebar hover CSS agree with the utilities Review caught that the sidebar hover alignment in this PR had no visual effect. `global.css` carries !important rules for both the link and button sidebar items — they exist to beat fumadocs' own styles — and they were still forcing the pre-alignment values: --surface-3 on an inactive hover, and --surface-active on an active hover. So the Tailwind utilities were dead on arrival. The global rules now carry the app's values instead (--surface-active inactive, --surface-6 active), matching the utilities rather than fighting them, with a comment noting the two must move together.
This commit is contained in:
@@ -3,7 +3,6 @@ import { defineI18nUI } from 'fumadocs-ui/i18n'
|
||||
import { DocsLayout } from 'fumadocs-ui/layouts/docs'
|
||||
import { RootProvider } from 'fumadocs-ui/provider/next'
|
||||
import { Geist_Mono, Inter } from 'next/font/google'
|
||||
import { AskAI } from '@/components/ai/ask-ai'
|
||||
import {
|
||||
SidebarFolder,
|
||||
SidebarItem,
|
||||
@@ -124,7 +123,6 @@ export default async function Layout({ children, params }: LayoutProps) {
|
||||
{children}
|
||||
</DocsLayout>
|
||||
<Footer />
|
||||
<AskAI locale={lang} />
|
||||
</RootProvider>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,363 +0,0 @@
|
||||
import { openai } from '@ai-sdk/openai'
|
||||
import {
|
||||
convertToModelMessages,
|
||||
jsonSchema,
|
||||
stepCountIs,
|
||||
streamText,
|
||||
tool,
|
||||
type UIMessage,
|
||||
} from 'ai'
|
||||
import { sql } from 'drizzle-orm'
|
||||
import { db, docsEmbeddings } from '@/lib/db'
|
||||
import { generateSearchEmbedding } from '@/lib/embeddings'
|
||||
|
||||
export const runtime = 'nodejs'
|
||||
export const maxDuration = 30
|
||||
|
||||
/** Model used for the Ask AI chat. Override with OPENAI_CHAT_MODEL in the environment. */
|
||||
const CHAT_MODEL = process.env.OPENAI_CHAT_MODEL || 'gpt-5.4-mini'
|
||||
|
||||
/** Max documentation chunks returned per search to ground an answer. */
|
||||
const SEARCH_LIMIT = 6
|
||||
|
||||
/** Candidates pulled before locale filtering, so a locale still yields SEARCH_LIMIT results. */
|
||||
const SEARCH_CANDIDATES = SEARCH_LIMIT * 4
|
||||
|
||||
/** Minimum cosine similarity for an English vector match (mirrors the site search route). */
|
||||
const SIMILARITY_THRESHOLD = 0.6
|
||||
|
||||
/** Locales the docs are published in (mirrors the site search route). */
|
||||
const KNOWN_LOCALES = ['en', 'es', 'fr', 'de', 'ja', 'zh']
|
||||
const DEFAULT_LOCALE = 'en'
|
||||
|
||||
/** Postgres full-text config per locale (mirrors the site search route). */
|
||||
const TS_CONFIG: Record<string, string> = {
|
||||
en: 'english',
|
||||
es: 'spanish',
|
||||
fr: 'french',
|
||||
de: 'german',
|
||||
ja: 'simple',
|
||||
zh: 'simple',
|
||||
}
|
||||
|
||||
/**
|
||||
* Abuse guards. This endpoint proxies a paid LLM, so an unauthenticated public
|
||||
* route is a target for scripted "free inference". These bounds cap the cost of
|
||||
* any single request; an in-memory per-IP rate limit (below) caps volume on the
|
||||
* hot path. A shared-store rate limit, a provider spend cap, and edge bot
|
||||
* protection remain the durable controls (see the PR checklist).
|
||||
*
|
||||
* The size cap counts only user-authored text — NOT the conversation history,
|
||||
* assistant turns, or retrieved doc chunks we add via the searchDocs tool, which
|
||||
* legitimately grow large over a multi-turn chat.
|
||||
*/
|
||||
const MAX_MESSAGES = 200
|
||||
const MAX_USER_INPUT_CHARS = 400_000
|
||||
const MAX_OUTPUT_TOKENS = 4000
|
||||
const MAX_STEPS = 6
|
||||
/** Backstop on the sanitized model payload — bounds total LLM input (e.g. stuffed assistant text). */
|
||||
const MAX_TOTAL_CHARS = 1_000_000
|
||||
|
||||
/**
|
||||
* Per-IP rate limit. Fixed window, in-memory: this bounds volume from a single
|
||||
* source on a warm instance without external infra. It is best-effort on
|
||||
* serverless (state is per-instance, not shared across regions/cold starts);
|
||||
* a shared store (e.g. Vercel KV) and an edge WAF remain the durable controls,
|
||||
* but this closes the "no volume limit at all" gap on the hot path.
|
||||
*/
|
||||
const RATE_LIMIT_MAX = 20
|
||||
const RATE_LIMIT_WINDOW_MS = 60_000
|
||||
const rateLimitHits = new Map<string, { count: number; resetAt: number }>()
|
||||
|
||||
/** Resolve the client IP from forwarding headers, falling back to a shared bucket. */
|
||||
function getClientIp(req: Request): string {
|
||||
const forwarded = req.headers.get('x-forwarded-for')
|
||||
if (forwarded) return forwarded.split(',')[0].trim()
|
||||
return req.headers.get('x-real-ip') ?? 'unknown'
|
||||
}
|
||||
|
||||
/** Fixed-window check. Returns retry-after seconds when the caller is over the limit, else null. */
|
||||
function rateLimit(ip: string, now: number): number | null {
|
||||
const entry = rateLimitHits.get(ip)
|
||||
if (!entry || now >= entry.resetAt) {
|
||||
rateLimitHits.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS })
|
||||
return null
|
||||
}
|
||||
if (entry.count >= RATE_LIMIT_MAX) {
|
||||
return Math.ceil((entry.resetAt - now) / 1000)
|
||||
}
|
||||
entry.count += 1
|
||||
return null
|
||||
}
|
||||
|
||||
/** Drop expired buckets so the Map doesn't grow unbounded on a long-lived instance. */
|
||||
function sweepRateLimit(now: number): void {
|
||||
if (rateLimitHits.size < 10_000) return
|
||||
for (const [ip, entry] of rateLimitHits) {
|
||||
if (now >= entry.resetAt) rateLimitHits.delete(ip)
|
||||
}
|
||||
}
|
||||
|
||||
/** A structurally valid UI message: has a role and a parts array. */
|
||||
function isValidMessage(message: unknown): message is UIMessage {
|
||||
return (
|
||||
typeof message === 'object' &&
|
||||
message !== null &&
|
||||
typeof (message as { role?: unknown }).role === 'string' &&
|
||||
Array.isArray((message as { parts?: unknown }).parts)
|
||||
)
|
||||
}
|
||||
|
||||
/** Total length of user-authored text across the conversation. */
|
||||
function userInputChars(messages: UIMessage[]): number {
|
||||
let total = 0
|
||||
for (const message of messages) {
|
||||
if (message.role !== 'user') continue
|
||||
for (const part of message.parts) {
|
||||
if (part.type === 'text' && typeof part.text === 'string') total += part.text.length
|
||||
}
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip everything the model shouldn't trust from client-supplied history:
|
||||
* drop `system` messages (client-injected instructions) and every non-text part
|
||||
* (e.g. crafted tool results faking searchDocs output). Only user/assistant text
|
||||
* survives, so grounding comes from the server-run searchDocs tool — not the
|
||||
* client's payload.
|
||||
*/
|
||||
function sanitizeMessages(messages: UIMessage[]): UIMessage[] {
|
||||
return messages
|
||||
.filter((message) => message.role === 'user' || message.role === 'assistant')
|
||||
.map((message) => ({
|
||||
...message,
|
||||
parts: message.parts.filter((part) => part.type === 'text' && typeof part.text === 'string'),
|
||||
}))
|
||||
.filter((message) => message.parts.length > 0)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reject obvious cross-origin calls. Same-origin browser requests send an
|
||||
* `Origin` header matching the host; we allow those, plus any host in
|
||||
* DOCS_ALLOWED_ORIGINS (comma-separated). Requests with no Origin (e.g. curl)
|
||||
* are allowed through to the cost caps rather than blocked, since Origin is
|
||||
* trivially spoofable and is a filter, not a security boundary.
|
||||
*/
|
||||
function isAllowedOrigin(req: Request): boolean {
|
||||
const origin = req.headers.get('origin')
|
||||
if (!origin) return true
|
||||
|
||||
let originHost: string
|
||||
try {
|
||||
originHost = new URL(origin).host.toLowerCase()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
|
||||
const forwardedHost = req.headers.get('x-forwarded-host') ?? req.headers.get('host')
|
||||
const requestHost = forwardedHost?.split(',')[0].trim().toLowerCase()
|
||||
if (requestHost && originHost === requestHost) return true
|
||||
|
||||
const allowlist = (process.env.DOCS_ALLOWED_ORIGINS ?? '')
|
||||
.split(',')
|
||||
.map((value) => value.trim().toLowerCase())
|
||||
.filter(Boolean)
|
||||
return allowlist.includes(originHost)
|
||||
}
|
||||
|
||||
const SYSTEM_PROMPT = `You are the documentation assistant for Sim — the open-source AI workspace where teams build, deploy, and manage AI agents.
|
||||
|
||||
Answer questions about Sim using the documentation. Always call the searchDocs tool before answering anything specific about Sim's features, configuration, or usage — do not answer from memory. Base your answer only on the returned documentation; if the docs do not cover the question, say so plainly rather than guessing.
|
||||
|
||||
Guidelines:
|
||||
- Be direct and concrete. Lead with the answer, then the detail.
|
||||
- Reference the relevant pages by their titles so the user knows where to read more.
|
||||
- When you show configuration or code, keep it minimal and correct.
|
||||
- The agent is called "Sim" and the chat surface is "Chat" — never say "Mothership" or "copilot".
|
||||
- If a question is unrelated to Sim, briefly say it's outside the docs' scope.`
|
||||
|
||||
const SEARCH_COLUMNS = {
|
||||
chunkId: docsEmbeddings.chunkId,
|
||||
title: docsEmbeddings.headerText,
|
||||
url: docsEmbeddings.sourceLink,
|
||||
content: docsEmbeddings.chunkText,
|
||||
sourceDocument: docsEmbeddings.sourceDocument,
|
||||
}
|
||||
|
||||
/** Reciprocal-rank-fusion constant, matching the site search route. */
|
||||
const RRF_K = 60
|
||||
|
||||
/**
|
||||
* SQL predicate selecting only the locale's documents, so the row limit applies
|
||||
* to matching rows: non-English docs are prefixed with their locale segment;
|
||||
* English is everything not prefixed with another locale.
|
||||
*/
|
||||
function localeFilter(locale: string) {
|
||||
const firstSegment = sql`split_part(${docsEmbeddings.sourceDocument}, '/', 1)`
|
||||
if (locale === DEFAULT_LOCALE) {
|
||||
const others = KNOWN_LOCALES.filter((l) => l !== DEFAULT_LOCALE)
|
||||
return sql`${firstSegment} not in (${sql.join(
|
||||
others.map((l) => sql`${l}`),
|
||||
sql`, `
|
||||
)})`
|
||||
}
|
||||
return sql`${firstSegment} = ${locale}`
|
||||
}
|
||||
|
||||
type SearchRow = {
|
||||
chunkId: string
|
||||
title: string
|
||||
url: string
|
||||
content: string
|
||||
sourceDocument: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve candidate chunks for grounding, mirroring the site search route's
|
||||
* hybrid strategy: Postgres full-text keyword search for every locale, plus
|
||||
* vector similarity (thresholded) for English — fused by reciprocal rank so a
|
||||
* page found by either signal can ground the answer.
|
||||
*/
|
||||
async function searchDocs(query: string, locale: string) {
|
||||
const tsConfig = TS_CONFIG[locale] ?? 'simple'
|
||||
|
||||
// Each retrieval path is best-effort and independent: a failure in one still
|
||||
// lets the other ground the answer (both empty just yields no grounding).
|
||||
let keywordRows: SearchRow[] = []
|
||||
try {
|
||||
keywordRows = await db
|
||||
.select(SEARCH_COLUMNS)
|
||||
.from(docsEmbeddings)
|
||||
.where(
|
||||
sql`${docsEmbeddings.chunkTextTsv} @@ plainto_tsquery(${tsConfig}, ${query}) and ${localeFilter(locale)}`
|
||||
)
|
||||
.orderBy(
|
||||
sql`ts_rank(${docsEmbeddings.chunkTextTsv}, plainto_tsquery(${tsConfig}, ${query})) DESC`
|
||||
)
|
||||
.limit(SEARCH_CANDIDATES)
|
||||
} catch (error) {
|
||||
console.error('Ask AI keyword search failed:', error)
|
||||
}
|
||||
|
||||
let vectorRows: SearchRow[] = []
|
||||
if (locale === DEFAULT_LOCALE) {
|
||||
// Vector retrieval (embedding call + pgvector query) is best-effort: if it
|
||||
// fails, fall back to the keyword rows already fetched rather than losing all
|
||||
// grounding for the turn.
|
||||
try {
|
||||
const embedding = await generateSearchEmbedding(query)
|
||||
const vectorLiteral = JSON.stringify(embedding)
|
||||
vectorRows = await db
|
||||
.select(SEARCH_COLUMNS)
|
||||
.from(docsEmbeddings)
|
||||
.where(
|
||||
sql`1 - (${docsEmbeddings.embedding} <=> ${vectorLiteral}::vector) >= ${SIMILARITY_THRESHOLD} and ${localeFilter(locale)}`
|
||||
)
|
||||
.orderBy(sql`${docsEmbeddings.embedding} <=> ${vectorLiteral}::vector`)
|
||||
.limit(SEARCH_CANDIDATES)
|
||||
} catch (error) {
|
||||
console.error('Ask AI vector search failed; using keyword results only:', error)
|
||||
}
|
||||
}
|
||||
|
||||
// Reciprocal rank fusion across the two rankings, deduped by chunk.
|
||||
const scores = new Map<string, number>()
|
||||
const rowById = new Map<string, SearchRow>()
|
||||
for (const list of [vectorRows, keywordRows]) {
|
||||
list.forEach((row, index) => {
|
||||
scores.set(row.chunkId, (scores.get(row.chunkId) ?? 0) + 1 / (RRF_K + index + 1))
|
||||
if (!rowById.has(row.chunkId)) rowById.set(row.chunkId, row)
|
||||
})
|
||||
}
|
||||
|
||||
return [...rowById.values()]
|
||||
.sort((a, b) => (scores.get(b.chunkId) ?? 0) - (scores.get(a.chunkId) ?? 0))
|
||||
.slice(0, SEARCH_LIMIT)
|
||||
.map((row) => ({
|
||||
title: row.title,
|
||||
url: row.url,
|
||||
content: row.content,
|
||||
}))
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
if (!isAllowedOrigin(req)) {
|
||||
return new Response('Forbidden', { status: 403 })
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
sweepRateLimit(now)
|
||||
const retryAfter = rateLimit(getClientIp(req), now)
|
||||
if (retryAfter !== null) {
|
||||
return new Response('Too many requests', {
|
||||
status: 429,
|
||||
headers: { 'Retry-After': String(retryAfter) },
|
||||
})
|
||||
}
|
||||
|
||||
let body: { messages: UIMessage[]; locale?: string }
|
||||
try {
|
||||
body = await req.json()
|
||||
} catch {
|
||||
return new Response('Invalid JSON', { status: 400 })
|
||||
}
|
||||
const { messages } = body
|
||||
const locale = KNOWN_LOCALES.includes(body.locale ?? '')
|
||||
? (body.locale as string)
|
||||
: DEFAULT_LOCALE
|
||||
|
||||
if (!Array.isArray(messages) || messages.length === 0 || messages.length > MAX_MESSAGES) {
|
||||
return new Response('Invalid request', { status: 400 })
|
||||
}
|
||||
if (!messages.every(isValidMessage)) {
|
||||
return new Response('Invalid request', { status: 400 })
|
||||
}
|
||||
if (userInputChars(messages) > MAX_USER_INPUT_CHARS) {
|
||||
return new Response('Request too large', { status: 413 })
|
||||
}
|
||||
|
||||
const modelMessages = sanitizeMessages(messages)
|
||||
if (modelMessages.length === 0) {
|
||||
return new Response('Invalid request', { status: 400 })
|
||||
}
|
||||
// Bound what actually reaches the model. Measured AFTER sanitization, so the
|
||||
// prior searchDocs tool outputs that accumulate in client history (and are
|
||||
// stripped here) don't count — only user/assistant text the model will see.
|
||||
if (JSON.stringify(modelMessages).length > MAX_TOTAL_CHARS) {
|
||||
return new Response('Request too large', { status: 413 })
|
||||
}
|
||||
|
||||
const result = streamText({
|
||||
model: openai(CHAT_MODEL),
|
||||
system: SYSTEM_PROMPT,
|
||||
messages: convertToModelMessages(modelMessages),
|
||||
stopWhen: stepCountIs(MAX_STEPS),
|
||||
maxOutputTokens: MAX_OUTPUT_TOKENS,
|
||||
tools: {
|
||||
searchDocs: tool({
|
||||
description:
|
||||
'Search the Sim documentation for relevant content. Use this before answering any question about Sim.',
|
||||
/**
|
||||
* The SDK's own schema helper instead of a zod schema: the `ai`
|
||||
* package's zod-v4 typings lag the workspace zod version, so a zod
|
||||
* object here fails the tool() overloads whenever the two drift.
|
||||
*/
|
||||
inputSchema: jsonSchema<{ query: string }>({
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: {
|
||||
type: 'string',
|
||||
description: 'A focused natural-language search query.',
|
||||
},
|
||||
},
|
||||
required: ['query'],
|
||||
additionalProperties: false,
|
||||
}),
|
||||
execute: async ({ query }) => searchDocs(query, locale),
|
||||
}),
|
||||
},
|
||||
})
|
||||
|
||||
return result.toUIMessageStreamResponse()
|
||||
}
|
||||
@@ -31,11 +31,6 @@ body {
|
||||
--text-md: 16px;
|
||||
}
|
||||
|
||||
/* Hide the floating Ask Sim widget while a workflow-preview lightbox is open. */
|
||||
body.wp-lightbox-open [aria-label="Ask Sim"] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Pure white light mode background */
|
||||
:root:not(.dark) {
|
||||
--color-fd-background: hsl(0, 0%, 100%) !important;
|
||||
@@ -64,7 +59,9 @@ body.wp-lightbox-open [aria-label="Ask Sim"] {
|
||||
--surface-4: #f5f5f5;
|
||||
--surface-5: #f3f3f3;
|
||||
--surface-6: #e5e5e5;
|
||||
--surface-7: #d9d9d9;
|
||||
--surface-active: #ececec;
|
||||
--surface-hover: #f2f2f2;
|
||||
--border: #d8d8d8;
|
||||
/** Legacy neutral-border aliases. New work should use --border. */
|
||||
--border-1: var(--border);
|
||||
@@ -133,7 +130,9 @@ body.wp-lightbox-open [aria-label="Ask Sim"] {
|
||||
--surface-4: #292929;
|
||||
--surface-5: #363636;
|
||||
--surface-6: #454545;
|
||||
--surface-7: #505050;
|
||||
--surface-active: #2c2c2c;
|
||||
--surface-hover: #262626;
|
||||
--border: #444444;
|
||||
/** Legacy neutral-border aliases. New work should use --border. */
|
||||
--border-1: var(--border);
|
||||
@@ -463,16 +462,18 @@ html #nd-sidebar button[data-active="true"] {
|
||||
color: var(--text-body) !important;
|
||||
}
|
||||
|
||||
/* Hover state — platform --surface-3 */
|
||||
/* Hover state — the app's nav Chip hovers to --surface-active. These rules must
|
||||
carry !important to beat fumadocs' own sidebar styles, which also means they
|
||||
override the Tailwind hover utilities on the items; keep the two in step. */
|
||||
html #nd-sidebar a:not(:has(span.font-mono)):hover:not([data-active="true"]),
|
||||
html #nd-sidebar button:hover:not([data-active="true"]) {
|
||||
background-color: var(--surface-3) !important;
|
||||
background-color: var(--surface-active) !important;
|
||||
}
|
||||
|
||||
/* Active items don't change on hover */
|
||||
/* An active item darkens one surface on hover, matching the app's active Chip */
|
||||
html #nd-sidebar a[data-active="true"]:not(:has(span.font-mono)):hover,
|
||||
html #nd-sidebar button[data-active="true"]:hover {
|
||||
background-color: var(--surface-active) !important;
|
||||
background-color: var(--surface-6) !important;
|
||||
color: var(--text-body) !important;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,234 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { type FormEvent, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useChat } from '@ai-sdk/react'
|
||||
import { ArrowUp, Square, Task, X } from '@sim/emcn/icons'
|
||||
import { DefaultChatTransport } from 'ai'
|
||||
import { Streamdown } from 'streamdown'
|
||||
import { cn } from '@/lib/utils'
|
||||
import 'streamdown/styles.css'
|
||||
|
||||
interface DocSource {
|
||||
title: string
|
||||
url: string
|
||||
}
|
||||
|
||||
/** Pull the deduped doc sources surfaced by the searchDocs tool out of a message's parts. */
|
||||
function getSources(parts: ReadonlyArray<{ type: string; [key: string]: unknown }>): DocSource[] {
|
||||
const seen = new Set<string>()
|
||||
const sources: DocSource[] = []
|
||||
|
||||
for (const part of parts) {
|
||||
if (part.type !== 'tool-searchDocs') continue
|
||||
const output = (part as { output?: unknown }).output
|
||||
if (!Array.isArray(output)) continue
|
||||
for (const item of output as DocSource[]) {
|
||||
if (!item?.url || seen.has(item.url)) continue
|
||||
seen.add(item.url)
|
||||
sources.push({ title: item.title, url: item.url })
|
||||
}
|
||||
}
|
||||
|
||||
return sources
|
||||
}
|
||||
|
||||
/** Concatenate the streamed text parts of a message. */
|
||||
function getText(parts: ReadonlyArray<{ type: string; [key: string]: unknown }>): string {
|
||||
return parts
|
||||
.filter((part) => part.type === 'text')
|
||||
.map((part) => (part as unknown as { text: string }).text)
|
||||
.join('')
|
||||
}
|
||||
|
||||
interface AskAIPanelProps {
|
||||
/** Active docs locale, forwarded so retrieval is scoped to the reader's language. */
|
||||
locale: string
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export function AskAIPanel({ locale, open, onClose }: AskAIPanelProps) {
|
||||
const [input, setInput] = useState('')
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null)
|
||||
|
||||
const transport = useMemo(() => new DefaultChatTransport({ api: '/api/chat' }), [])
|
||||
|
||||
const { messages, sendMessage, status, stop, error } = useChat({ transport })
|
||||
|
||||
const isBusy = status === 'submitted' || status === 'streaming'
|
||||
|
||||
const handleClose = () => {
|
||||
stop()
|
||||
onClose()
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
textareaRef.current?.focus()
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') {
|
||||
handleClose()
|
||||
}
|
||||
}
|
||||
document.addEventListener('keydown', handleKeyDown)
|
||||
return () => document.removeEventListener('keydown', handleKeyDown)
|
||||
}, [open])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight })
|
||||
}, [open])
|
||||
|
||||
useEffect(() => {
|
||||
scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' })
|
||||
}, [messages])
|
||||
|
||||
const handleSubmit = (event: FormEvent) => {
|
||||
event.preventDefault()
|
||||
const text = input.trim()
|
||||
if (!text || isBusy) return
|
||||
sendMessage({ text }, { body: { locale } })
|
||||
setInput('')
|
||||
}
|
||||
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
role='dialog'
|
||||
aria-label='Ask Sim'
|
||||
className='fixed right-4 bottom-4 z-50 flex h-[600px] max-h-[calc(100vh-2rem)] w-[400px] max-w-[calc(100vw-2rem)] flex-col overflow-hidden rounded-xl border border-[var(--border-1)] bg-[var(--surface-5)] shadow-[var(--shadow-medium)] dark:bg-[var(--surface-4)]'
|
||||
>
|
||||
<div className='flex items-center justify-between border-[var(--border-1)] border-b px-4 py-3'>
|
||||
<span className='flex items-center gap-1.5 font-season text-[var(--text-body)] text-sm'>
|
||||
<Task className='size-[16px] text-[var(--text-icon)]' />
|
||||
Ask Sim
|
||||
</span>
|
||||
<button
|
||||
type='button'
|
||||
aria-label='Close'
|
||||
onClick={handleClose}
|
||||
className='flex size-7 items-center justify-center rounded-lg text-[var(--text-icon)] transition-colors hover:bg-[var(--surface-active)]'
|
||||
>
|
||||
<X className='size-[16px]' />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div ref={scrollRef} className='flex-1 space-y-4 overflow-y-auto px-4 py-4'>
|
||||
{messages.length === 0 && (
|
||||
<p className='text-[var(--text-muted)] text-sm'>
|
||||
Ask anything about building, deploying, and managing AI agents in Sim.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{messages.map((message, index) => {
|
||||
const text = getText(message.parts)
|
||||
const isStreaming = isBusy && index === messages.length - 1
|
||||
const sources = message.role === 'assistant' ? getSources(message.parts) : []
|
||||
return (
|
||||
<div
|
||||
key={message.id}
|
||||
className={cn(
|
||||
'flex flex-col gap-1.5',
|
||||
message.role === 'user' ? 'items-end' : 'items-start'
|
||||
)}
|
||||
>
|
||||
{message.role === 'user' ? (
|
||||
<div className='max-w-[85%] whitespace-pre-wrap rounded-[16px] bg-[var(--surface-5)] px-3 py-2 text-[var(--text-primary)] text-base leading-[23px]'>
|
||||
{text}
|
||||
</div>
|
||||
) : (
|
||||
<div className='max-w-full text-[var(--text-primary)] text-base'>
|
||||
{text ? (
|
||||
<Streamdown
|
||||
className={cn(
|
||||
'space-y-3 text-[var(--text-primary)] text-base leading-relaxed',
|
||||
'[&_a]:text-[var(--text-primary)] [&_a]:underline [&_a]:decoration-dashed [&_a]:underline-offset-4',
|
||||
'[&_strong]:font-semibold',
|
||||
'[&_h1]:font-semibold [&_h2]:font-semibold [&_h3]:font-semibold [&_h4]:font-semibold',
|
||||
'[&_li]:my-1 [&_ol]:my-3 [&_ol]:list-decimal [&_ol]:pl-5 [&_ul]:my-3 [&_ul]:list-disc [&_ul]:pl-5',
|
||||
'[&_code]:font-mono [&_pre]:my-3 [&_pre]:overflow-x-auto [&_pre]:rounded-lg [&_pre]:bg-[var(--surface-5)] [&_pre]:p-3 [&_pre]:text-small'
|
||||
)}
|
||||
>
|
||||
{text}
|
||||
</Streamdown>
|
||||
) : isStreaming ? (
|
||||
'…'
|
||||
) : sources.length === 0 ? (
|
||||
<span className='text-[var(--text-muted)]'>No answer returned.</span>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
{sources.length > 0 && (
|
||||
<div className='flex max-w-[90%] flex-wrap gap-1.5'>
|
||||
{sources.map((source) => (
|
||||
<a
|
||||
key={source.url}
|
||||
href={source.url}
|
||||
target='_blank'
|
||||
rel='noopener noreferrer'
|
||||
className='rounded-lg border border-[var(--border-1)] px-2 py-0.5 text-[var(--text-muted)] text-xs transition-colors hover:bg-[var(--surface-active)]'
|
||||
>
|
||||
{source.title || source.url}
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
{error && (
|
||||
<p className='text-[var(--text-muted)] text-sm'>
|
||||
Something went wrong. Please try again.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className='px-3 pb-3'>
|
||||
<div className='flex items-end gap-2 rounded-2xl border border-[var(--border-1)] bg-white px-2.5 py-1.5 dark:bg-[var(--surface-5)]'>
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
aria-label='Ask Sim about the docs'
|
||||
value={input}
|
||||
onChange={(event) => setInput(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' && !event.shiftKey) {
|
||||
event.preventDefault()
|
||||
handleSubmit(event)
|
||||
}
|
||||
}}
|
||||
rows={1}
|
||||
placeholder='Ask Sim about the docs…'
|
||||
className='max-h-32 flex-1 resize-none bg-transparent py-1 font-season text-[var(--text-body)] text-sm outline-none placeholder:text-[var(--text-muted)]'
|
||||
/>
|
||||
{isBusy ? (
|
||||
<button
|
||||
type='button'
|
||||
aria-label='Stop'
|
||||
onClick={() => stop()}
|
||||
className='flex size-[28px] shrink-0 items-center justify-center rounded-full bg-[#383838] transition-colors hover:bg-[#575757] dark:bg-[#e0e0e0] dark:hover:bg-[#cfcfcf]'
|
||||
>
|
||||
<Square className='size-[12px] fill-white text-white dark:fill-black dark:text-black' />
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type='submit'
|
||||
aria-label='Send'
|
||||
disabled={!input.trim()}
|
||||
className={cn(
|
||||
'flex size-[28px] shrink-0 items-center justify-center rounded-full transition-colors',
|
||||
input.trim()
|
||||
? 'bg-[#383838] hover:bg-[#575757] dark:bg-[#e0e0e0] dark:hover:bg-[#cfcfcf]'
|
||||
: 'bg-[#808080]'
|
||||
)}
|
||||
>
|
||||
<ArrowUp className='size-[16px] text-white dark:text-black' />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useRef, useState } from 'react'
|
||||
import { Task } from '@sim/emcn/icons'
|
||||
import dynamic from 'next/dynamic'
|
||||
|
||||
const AskAIPanel = dynamic(() => import('./ask-ai-panel').then((m) => m.AskAIPanel), {
|
||||
ssr: false,
|
||||
loading: () => (
|
||||
<div
|
||||
aria-hidden
|
||||
className='fixed right-4 bottom-4 z-50 flex size-11 items-center justify-center rounded-full border border-[var(--border-1)] bg-[var(--surface-5)] shadow-[var(--shadow-medium)] dark:bg-[var(--surface-4)]'
|
||||
>
|
||||
<Task className='size-[16px] animate-pulse text-[var(--text-icon)]' />
|
||||
</div>
|
||||
),
|
||||
})
|
||||
|
||||
interface AskAIProps {
|
||||
/** Active docs locale, forwarded so retrieval is scoped to the reader's language. */
|
||||
locale: string
|
||||
}
|
||||
|
||||
export function AskAI({ locale }: AskAIProps) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [hasOpened, setHasOpened] = useState(false)
|
||||
const openButtonRef = useRef<HTMLButtonElement>(null)
|
||||
|
||||
const handleOpen = () => {
|
||||
setHasOpened(true)
|
||||
setOpen(true)
|
||||
}
|
||||
|
||||
const handleClose = () => {
|
||||
setOpen(false)
|
||||
openButtonRef.current?.focus()
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{!open && (
|
||||
<button
|
||||
ref={openButtonRef}
|
||||
type='button'
|
||||
aria-label='Ask Sim'
|
||||
onClick={handleOpen}
|
||||
className='fixed right-4 bottom-4 z-50 flex h-11 items-center gap-1.5 rounded-full border border-[var(--border-1)] bg-[var(--surface-5)] px-4 font-season text-[var(--text-body)] text-sm shadow-[var(--shadow-medium)] transition-colors hover:bg-[var(--surface-active)] dark:bg-[var(--surface-4)]'
|
||||
>
|
||||
<Task className='size-[16px] text-[var(--text-icon)]' />
|
||||
Ask Sim
|
||||
</button>
|
||||
)}
|
||||
|
||||
{hasOpened && <AskAIPanel locale={locale} open={open} onClose={handleClose} />}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -45,14 +45,16 @@ const ITEM_BASE =
|
||||
const ITEM_ACTIVE_MOBILE = 'bg-[var(--surface-active)] font-medium text-[var(--text-primary)]'
|
||||
|
||||
const ITEM_DESKTOP =
|
||||
'lg:mb-[0.0625rem] lg:block lg:rounded-lg lg:px-2.5 lg:py-1.5 lg:font-normal lg:text-small lg:leading-tight'
|
||||
'lg:mb-[0.0625rem] lg:block lg:rounded-lg lg:px-2 lg:py-1.5 lg:font-normal lg:text-sm lg:leading-tight'
|
||||
const ITEM_TEXT = 'lg:text-[var(--text-body)]'
|
||||
const ITEM_HOVER = 'lg:hover:bg-[var(--surface-3)]'
|
||||
const ITEM_ACTIVE = 'lg:bg-[var(--surface-active)] lg:font-normal lg:text-[var(--text-body)]'
|
||||
const ITEM_HOVER = 'lg:hover:bg-[var(--surface-active)]'
|
||||
const ITEM_ACTIVE =
|
||||
'lg:bg-[var(--surface-active)] lg:font-normal lg:text-[var(--text-body)] lg:hover:bg-[var(--surface-6)]'
|
||||
|
||||
const FOLDER_TEXT = 'lg:text-[var(--text-body)] lg:font-medium'
|
||||
const FOLDER_HOVER = 'lg:hover:bg-[var(--surface-3)]'
|
||||
const FOLDER_ACTIVE = 'lg:bg-[var(--surface-active)] lg:text-[var(--text-body)]'
|
||||
const FOLDER_HOVER = 'lg:hover:bg-[var(--surface-active)]'
|
||||
const FOLDER_ACTIVE =
|
||||
'lg:bg-[var(--surface-active)] lg:text-[var(--text-body)] lg:hover:bg-[var(--surface-6)]'
|
||||
|
||||
export function SidebarItem({ item }: { item: Item }) {
|
||||
const pathname = usePathname()
|
||||
@@ -133,7 +135,7 @@ export function SidebarFolder({ item, children }: { item: Folder; children: Reac
|
||||
'flex flex-1 items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors',
|
||||
'text-[var(--text-muted)] hover:bg-[var(--surface-active)] hover:text-[var(--text-body)]',
|
||||
active && ITEM_ACTIVE_MOBILE,
|
||||
'lg:block lg:flex-1 lg:rounded-lg lg:px-2.5 lg:py-1.5 lg:text-small lg:leading-tight',
|
||||
'lg:block lg:flex-1 lg:rounded-lg lg:px-2 lg:py-1.5 lg:text-sm lg:leading-tight',
|
||||
FOLDER_TEXT,
|
||||
!active && FOLDER_HOVER,
|
||||
active && FOLDER_ACTIVE
|
||||
@@ -146,7 +148,7 @@ export function SidebarFolder({ item, children }: { item: Folder; children: Reac
|
||||
onClick={toggleOpen}
|
||||
className={cn(
|
||||
'rounded-md p-1 hover:bg-[var(--surface-active)]',
|
||||
'lg:cursor-pointer lg:rounded-md lg:p-1 lg:transition-colors lg:hover:bg-[var(--surface-3)]'
|
||||
'lg:cursor-pointer lg:rounded-md lg:p-1 lg:transition-colors lg:hover:bg-[var(--surface-active)]'
|
||||
)}
|
||||
aria-label={open ? 'Collapse' : 'Expand'}
|
||||
>
|
||||
@@ -160,7 +162,7 @@ export function SidebarFolder({ item, children }: { item: Folder; children: Reac
|
||||
className={cn(
|
||||
'flex flex-1 items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors',
|
||||
'text-[var(--text-muted)] hover:bg-[var(--surface-active)]',
|
||||
'lg:flex lg:w-full lg:cursor-pointer lg:items-center lg:justify-between lg:rounded-lg lg:px-2.5 lg:py-1.5 lg:text-left lg:text-small lg:leading-tight',
|
||||
'lg:flex lg:w-full lg:cursor-pointer lg:items-center lg:justify-between lg:rounded-lg lg:px-2 lg:py-1.5 lg:text-left lg:text-sm lg:leading-tight',
|
||||
FOLDER_TEXT,
|
||||
FOLDER_HOVER
|
||||
)}
|
||||
|
||||
@@ -17,12 +17,9 @@
|
||||
"format:check": "biome format ."
|
||||
},
|
||||
"dependencies": {
|
||||
"@ai-sdk/openai": "2.0.107",
|
||||
"@ai-sdk/react": "2.0.205",
|
||||
"@sim/db": "workspace:*",
|
||||
"@sim/emcn": "workspace:*",
|
||||
"@sim/workflow-renderer": "workspace:*",
|
||||
"ai": "5.0.203",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"drizzle-orm": "^0.45.2",
|
||||
@@ -36,7 +33,6 @@
|
||||
"react-dom": "19.2.4",
|
||||
"remark-breaks": "^4.0.0",
|
||||
"shiki": "4.3.1",
|
||||
"streamdown": "2.5.0",
|
||||
"tailwind-merge": "^3.0.2",
|
||||
"reactflow": "^11.11.4",
|
||||
"framer-motion": "^12.5.0",
|
||||
|
||||
Reference in New Issue
Block a user