feat(ai): 全站 AI 助手浮窗(参考 FlowStack 右下角浮空设计)
CI / Backend (go vet + test) (push) Waiting to run
CI / Frontend (lint + build + test) (push) Waiting to run

- POST /ai/chat:多轮对话(messages 透传)+ 页面上下文注入 —— 前端带当前路径,
  后端自动附加该数据源近 15 分钟轻量日志摘要(总量/Top3 应用/告警命中),
  追问「这个报错什么原因」有数据依据;脱敏/每日配额/Pro 闸门与整页分析共用
- AiAssistant 浮球+浮窗挂 Layout:仅 admin+Pro 渲染;消息气泡、Enter 发送、
  上下文随路由自动采集;免费版不显示
This commit is contained in:
opsx committed 2026-10-31 23:46:33 +08:00
1 parent b81b31f322
commit f457d6da09
8 files changed
+249 -1

No files matched your search

+3
View File
@@ -91,4 +91,7 @@ export const aiApi = {
`/ai/runs?page=${page}&pageSize=${pageSize}`,
),
run: (id: number) => http.get<AIRun>(`/ai/runs/${id}`),
chat: (data: { sourceId?: number; history: Array<{ role: 'user' | 'assistant'; content: string }>; page?: string; rangeMinutes?: number }) =>
http.post<{ reply: string }>('/ai/chat', data),
}
+124
View File
@@ -0,0 +1,124 @@
import { memo, useEffect, useRef, useState } from 'react'
import { useLocation } from 'react-router'
import { useTranslation } from 'react-i18next'
import { Loader2, Send, Sparkles, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { aiApi } from '@/api/ai'
import { getUser } from '@/lib/auth-storage'
import { useLicense } from '@/hooks/useLicense'
interface Msg { role: 'user' | 'assistant'; content: string }
/**
* 全站 AI 助手浮窗(参考 FlowStack 右下角浮空设计):
* 仅管理员 + Pro 生效时渲染;对话自动携带当前页面路径作为上下文,
* 后端按需注入当前数据源的日志摘要,让"现在这个报错是什么"有数据依据。
*/
export const AiAssistant = memo(function AiAssistant() {
const { t } = useTranslation('aiops')
const location = useLocation()
const { pro } = useLicense()
const isAdmin = getUser()?.role === 'admin'
const [open, setOpen] = useState(false)
const [messages, setMessages] = useState<Msg[]>([])
const [input, setInput] = useState('')
const [sending, setSending] = useState(false)
const listRef = useRef<HTMLDivElement>(null)
useEffect(() => {
if (listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight
}, [messages, sending])
if (!isAdmin || !pro) return null
const send = async () => {
const text = input.trim()
if (!text || sending) return
const next: Msg[] = [...messages, { role: 'user', content: text }]
setMessages(next)
setInput('')
setSending(true)
try {
const res = await aiApi.chat({
history: next.slice(-20),
page: location.pathname,
rangeMinutes: 15,
})
setMessages(current => [...current, { role: 'assistant', content: res.reply }])
} catch (err) {
setMessages(current => [...current, { role: 'assistant', content: err instanceof Error ? err.message : t('assistant.error') }])
} finally {
setSending(false)
}
}
return (
<>
<button
type="button"
aria-label={open ? t('assistant.close') : t('assistant.open')}
onClick={() => setOpen(!open)}
className="fixed bottom-6 right-6 z-50 flex size-12 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg transition-transform hover:scale-105"
>
{open ? <X className="size-5" /> : <Sparkles className="size-5" />}
</button>
{open && (
<div
className="fixed bottom-20 right-6 z-50 flex h-[520px] w-[min(92vw,400px)] flex-col overflow-hidden rounded-xl border bg-card shadow-2xl"
role="dialog"
aria-label={t('assistant.title')}
>
<div className="flex items-center justify-between border-b px-4 py-2.5">
<span className="flex items-center gap-2 text-sm font-semibold">
<Sparkles className="size-4 text-primary" />
{t('assistant.title')}
</span>
<button type="button" aria-label={t('assistant.close')} onClick={() => setOpen(false)} className="rounded p-1 text-muted-foreground hover:bg-muted">
<X className="size-4" />
</button>
</div>
<div ref={listRef} className="flex-1 space-y-3 overflow-y-auto p-4 text-sm">
{messages.length === 0 && (
<p className="py-8 text-center text-xs text-muted-foreground">{t('assistant.emptyHint')}</p>
)}
{messages.map((m, i) => (
<div key={i} className={m.role === 'user' ? 'flex justify-end' : 'flex justify-start'}>
<div className={
m.role === 'user'
? 'max-w-[85%] rounded-lg bg-primary px-3 py-2 text-primary-foreground'
: 'max-w-[85%] whitespace-pre-wrap rounded-lg bg-muted px-3 py-2'
}>
{m.content}
</div>
</div>
))}
{sending && (
<div className="flex justify-start">
<div className="flex items-center gap-2 rounded-lg bg-muted px-3 py-2 text-xs text-muted-foreground">
<Loader2 className="size-3.5 animate-spin" />
{t('assistant.thinking')}
</div>
</div>
)}
</div>
<div className="flex items-end gap-2 border-t p-3">
<Textarea
rows={1}
value={input}
onChange={e => setInput(e.target.value)}
onKeyDown={e => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); void send() }
}}
placeholder={t('assistant.placeholder')}
className="max-h-28 min-h-9 resize-none text-sm"
/>
<Button size="sm" onClick={() => void send()} disabled={sending || !input.trim()} aria-label={t('assistant.send')}>
<Send className="size-4" />
</Button>
</div>
</div>
)}
</>
)
})
+3 -1
View File
@@ -22,6 +22,7 @@ import { cn } from '@/lib/utils'
import { useIsMobile } from '@/hooks/use-mobile'
import { menuItems, findRouteMeta, findGroupKey } from '@/router/routes'
import { useLicense } from '@/hooks/useLicense'
import { AiAssistant } from '@/components/AiAssistant'
import { Lock } from 'lucide-react'
import { GroupTabs } from './GroupTabs'
import { getUser, clearAuth } from '@/lib/auth-storage'
@@ -265,9 +266,10 @@ const Layout = memo(function Layout({ children }: { children: React.ReactNode })
<main className="flex-1 overflow-auto p-4 md:p-6">
<Suspense fallback={<PageSkeleton />}>{children}</Suspense>
</main>
<AiAssistant />
</div>
</div>
)
})
export default Layout
export default Layout
+11
View File
@@ -1,4 +1,15 @@
export default {
assistant: {
title: 'AI Assistant',
open: 'Open AI assistant',
close: 'Close',
send: 'Send',
thinking: 'Thinking…',
error: 'Request failed',
placeholder: 'Ask about logs, e.g. anything unusual now?',
emptyHint: 'Just ask; I can see the page you are viewing and the last 15 minutes of logs.',
},
title: 'AIOps',
subtitle: 'Let a model read log signals: statistics first, conclusions second — raw logs never leave the platform',
+11
View File
@@ -1,4 +1,15 @@
export default {
assistant: {
title: 'AI 助手',
open: '打开 AI 助手',
close: '关闭',
send: '发送',
thinking: '思考中…',
error: '请求失败',
placeholder: '问问日志的事,如:当前有什么异常?',
emptyHint: '直接提问;我会参考你当前正在查看的页面与近 15 分钟日志概况。',
},
title: '智能运维',
subtitle: '用大模型解读日志信号:先看统计、再看结论,全程不把日志原文发出去',