仰望星辰工作室

miaopanel

miaopanel/ web/src/views/AI.vue 19.3 KB · 801 行 原始文件
1<script setup lang="ts">
2import { computed, inject, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
3import { api } from '../api'
4import { streamChat } from '../ai'
5import { navigate } from '../router'
6import { time } from '../format'
7import type {
8 AIAction,
9 AIMessage,
10 AIMessagePayload,
11 AISession,
12 AISettings,
13 AIToolCall,
14} from '../types'
15import ActionCard from '../components/ai/ActionCard.vue'
16import MarkdownText from '../components/ai/MarkdownText.vue'
17import ConfirmDialog from '../components/ConfirmDialog.vue'
18
19defineOptions({ name: 'AIView' })
20
21const notify = inject<(text: string, kind?: 'ok' | 'error') => void>('notify')!
22
23interface ToolState {
24 id: string
25 name: string
26 args: string
27 status: string
28 result: string
29}
30
31interface ChatItem {
32 key: string
33 role: 'user' | 'assistant' | 'tool'
34 content: string
35 tools: ToolState[]
36 actions: AIAction[]
37 streaming?: boolean
38}
39
40const settings = ref<AISettings | null>(null)
41const sessions = ref<AISession[]>([])
42const items = ref<ChatItem[]>([])
43const sessionId = ref('')
44const input = ref('')
45const streaming = ref(false)
46const loading = ref(true)
47const loadingMessages = ref(false)
48const busyAction = ref('')
49const deleteTarget = ref<AISession | null>(null)
50const bodyEl = ref<HTMLElement | null>(null)
51const inputEl = ref<HTMLTextAreaElement | null>(null)
52
53let abortController: AbortController | null = null
54let currentAssistant: ChatItem | null = null
55let localSeq = 0
56
57const suggestions = [
58 '查看服务器负载情况',
59 '检查 nginx 运行状态',
60 '列出站点和运行状态',
61 '分析最近的 WAF 拦截',
62]
63
64const enabled = computed(() => settings.value?.enabled === true)
65const modelName = computed(() => settings.value?.model || '未配置模型')
66const hasPending = computed(() => items.value.some((item) => item.actions.length > 0))
67const canSend = computed(
68 () => enabled.value && !streaming.value && !hasPending.value && input.value.trim() !== '',
69)
70
71function scrollBottom() {
72 nextTick(() => {
73 const el = bodyEl.value
74 if (el) el.scrollTop = el.scrollHeight
75 })
76}
77
78function prettyArgs(raw: string): string {
79 try {
80 return JSON.stringify(JSON.parse(raw || '{}'), null, 2)
81 } catch {
82 return raw || ''
83 }
84}
85
86function statusLabel(status: string): string {
87 const map: Record<string, string> = {
88 pending: '准备中',
89 running: '执行中',
90 waiting: '等待确认',
91 done: '已完成',
92 ok: '已完成',
93 error: '失败',
94 rejected: '已拒绝',
95 skipped: '已跳过',
96 }
97 return map[status] ?? status
98}
99
100function parseCalls(raw?: string): AIToolCall[] {
101 if (!raw) return []
102 try {
103 const value = JSON.parse(raw)
104 return Array.isArray(value) ? (value as AIToolCall[]) : []
105 } catch {
106 return []
107 }
108}
109
110function buildItems(messages: AIMessage[], actions: AIAction[]): ChatItem[] {
111 const out: ChatItem[] = []
112 const index = new Map<string, { item: ChatItem; tool: ToolState }>()
113 for (const msg of messages) {
114 if (msg.role === 'user') {
115 out.push({ key: `m${msg.id}`, role: 'user', content: msg.content, tools: [], actions: [] })
116 continue
117 }
118 if (msg.role === 'assistant') {
119 const item: ChatItem = {
120 key: `m${msg.id}`,
121 role: 'assistant',
122 content: msg.content,
123 tools: [],
124 actions: [],
125 }
126 for (const call of parseCalls(msg.tool_calls)) {
127 const tool: ToolState = {
128 id: call.id,
129 name: call.function?.name ?? '工具',
130 args: call.function?.arguments ?? '',
131 status: 'pending',
132 result: '',
133 }
134 item.tools.push(tool)
135 index.set(tool.id, { item, tool })
136 }
137 out.push(item)
138 continue
139 }
140 if (msg.role === 'tool') {
141 const hit = msg.tool_call_id ? index.get(msg.tool_call_id) : undefined
142 if (hit) {
143 hit.tool.status =
144 msg.status === 'error' ? 'error' : msg.status === 'skipped' ? 'skipped' : msg.status === 'rejected' ? 'rejected' : 'done'
145 hit.tool.result = msg.content
146 } else if (msg.content) {
147 out.push({ key: `m${msg.id}`, role: 'tool', content: msg.content, tools: [], actions: [] })
148 }
149 }
150 }
151 for (const action of actions) {
152 let hit = index.get(action.tool_call_id)
153 if (!hit) {
154 const item: ChatItem = {
155 key: `a${action.id}`,
156 role: 'assistant',
157 content: '',
158 tools: [],
159 actions: [],
160 }
161 const tool: ToolState = {
162 id: action.tool_call_id,
163 name: action.tool_name,
164 args: action.arguments,
165 status: 'waiting',
166 result: '',
167 }
168 item.tools.push(tool)
169 out.push(item)
170 hit = { item, tool }
171 index.set(tool.id, hit)
172 }
173 hit.tool.status = 'waiting'
174 hit.item.actions.push(action)
175 }
176 return out
177}
178
179async function loadSettings() {
180 settings.value = await api.get<AISettings>('api/v1/settings/ai')
181}
182
183async function loadSessions() {
184 const data = await api.get<{ sessions: AISession[] }>('api/v1/ai/sessions')
185 sessions.value = data.sessions ?? []
186}
187
188async function openSession(session: AISession) {
189 if (streaming.value || session.id === sessionId.value) return
190 loadingMessages.value = true
191 try {
192 const data = await api.get<AIMessagePayload>(`api/v1/ai/sessions/${session.id}/messages`)
193 sessionId.value = session.id
194 currentAssistant = null
195 items.value = buildItems(data.messages ?? [], data.actions ?? [])
196 scrollBottom()
197 } catch (e) {
198 notify((e as Error).message, 'error')
199 } finally {
200 loadingMessages.value = false
201 }
202}
203
204function newChat() {
205 if (streaming.value || hasPending.value) return
206 sessionId.value = ''
207 items.value = []
208 currentAssistant = null
209 input.value = ''
210 inputEl.value?.focus()
211}
212
213async function refreshSessions() {
214 try {
215 await loadSessions()
216 } catch {
217 /* ignore transient list errors */
218 }
219}
220
221function ensureAssistant(): ChatItem {
222 if (currentAssistant) return currentAssistant
223 const item: ChatItem = {
224 key: `s${++localSeq}`,
225 role: 'assistant',
226 content: '',
227 tools: [],
228 actions: [],
229 streaming: true,
230 }
231 items.value.push(item)
232 currentAssistant = item
233 return item
234}
235
236function findTool(id: string): { item: ChatItem; tool: ToolState } | null {
237 for (const item of items.value) {
238 for (const tool of item.tools) {
239 if (tool.id === id) return { item, tool }
240 }
241 }
242 return null
243}
244
245function removeAction(id: string) {
246 for (const item of items.value) {
247 item.actions = item.actions.filter((a) => a.id !== id)
248 }
249}
250
251function handleEvent(event: string, data: any) {
252 switch (event) {
253 case 'meta': {
254 if (data?.session_id && !sessionId.value) sessionId.value = data.session_id
255 break
256 }
257 case 'text': {
258 const item = ensureAssistant()
259 item.content += data?.delta ?? ''
260 scrollBottom()
261 break
262 }
263 case 'tool.start': {
264 const hit = findTool(data?.id ?? '')
265 if (hit) {
266 hit.tool.status = 'running'
267 if (data?.args) hit.tool.args = data.args
268 } else {
269 const item = ensureAssistant()
270 item.tools.push({
271 id: data?.id ?? '',
272 name: data?.name ?? '工具',
273 args: data?.args ?? '',
274 status: 'running',
275 result: '',
276 })
277 }
278 scrollBottom()
279 break
280 }
281 case 'tool.result': {
282 const hit = findTool(data?.id ?? '')
283 if (hit) {
284 hit.tool.status =
285 data?.status === 'error'
286 ? 'error'
287 : data?.status === 'rejected'
288 ? 'rejected'
289 : data?.status === 'skipped'
290 ? 'skipped'
291 : 'done'
292 hit.tool.result = data?.result ?? ''
293 }
294 scrollBottom()
295 break
296 }
297 case 'action.pending': {
298 const toolID = data?.tool_call_id ?? ''
299 const hit = findTool(toolID)
300 const item = hit?.item ?? ensureAssistant()
301 if (hit) hit.tool.status = 'waiting'
302 const action: AIAction = {
303 id: data.id,
304 session_id: sessionId.value,
305 message_id: 0,
306 tool_call_id: toolID,
307 tool_name: data.tool,
308 arguments: data.args ?? '',
309 summary: data.summary ?? '',
310 risk: data.risk ?? 'write',
311 status: 'pending',
312 result: '',
313 created_at: 0,
314 expires_at: 0,
315 decided_at: 0,
316 executed_at: 0,
317 }
318 item.actions.push(action)
319 scrollBottom()
320 break
321 }
322 case 'error': {
323 notify(data?.message || 'AI 处理失败', 'error')
324 break
325 }
326 case 'done': {
327 if (currentAssistant) currentAssistant.streaming = false
328 currentAssistant = null
329 break
330 }
331 }
332}
333
334async function runStream(path: string, body: unknown) {
335 streaming.value = true
336 currentAssistant = null
337 abortController = new AbortController()
338 try {
339 await streamChat(path, body, handleEvent, abortController.signal)
340 } catch (e) {
341 notify((e as Error).message, 'error')
342 } finally {
343 streaming.value = false
344 busyAction.value = ''
345 abortController = null
346 if (currentAssistant) (currentAssistant as ChatItem).streaming = false
347 currentAssistant = null
348 await refreshSessions()
349 }
350}
351
352async function send(text?: string) {
353 if (streaming.value || hasPending.value || !enabled.value) return
354 const content = (text ?? input.value).trim()
355 if (!content) return
356 input.value = ''
357 items.value.push({
358 key: `u${++localSeq}`,
359 role: 'user',
360 content,
361 tools: [],
362 actions: [],
363 })
364 scrollBottom()
365 await runStream('api/v1/ai/chat', { session_id: sessionId.value, content })
366}
367
368async function decide(action: AIAction, approve: boolean) {
369 if (streaming.value) return
370 busyAction.value = action.id
371 removeAction(action.id)
372 await runStream(`api/v1/ai/actions/${action.id}/decide`, {
373 decision: approve ? 'approve' : 'reject',
374 })
375}
376
377function stop() {
378 abortController?.abort()
379}
380
381function onComposerKey(e: KeyboardEvent) {
382 if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) {
383 e.preventDefault()
384 void send()
385 }
386}
387
388function askDelete(session: AISession) {
389 if (streaming.value) return
390 deleteTarget.value = session
391}
392
393async function confirmDelete() {
394 const target = deleteTarget.value
395 deleteTarget.value = null
396 if (!target) return
397 try {
398 await api.del(`api/v1/ai/sessions/${target.id}`)
399 if (target.id === sessionId.value) newChat()
400 await loadSessions()
401 notify('对话已删除')
402 } catch (e) {
403 notify((e as Error).message, 'error')
404 }
405}
406
407async function bootstrap() {
408 loading.value = true
409 try {
410 await loadSettings()
411 if (!enabled.value) return
412 await loadSessions()
413 if (sessions.value.length > 0) {
414 await openSession(sessions.value[0])
415 }
416 } catch (e) {
417 notify((e as Error).message, 'error')
418 } finally {
419 loading.value = false
420 }
421}
422
423onMounted(bootstrap)
424
425onBeforeUnmount(() => {
426 abortController?.abort()
427})
428</script>
429
430<template>
431 <div class="ai-page">
432 <aside class="card ai-side">
433 <div class="ai-side-head">
434 <strong>对话</strong>
435 <div class="spacer"></div>
436 <button class="btn btn-sm btn-primary" :disabled="streaming || hasPending" @click="newChat">新建</button>
437 </div>
438 <div class="session-list">
439 <div
440 v-for="s in sessions"
441 :key="s.id"
442 class="session-item"
443 :class="{ active: s.id === sessionId }"
444 @click="openSession(s)"
445 >
446 <div class="session-text">
447 <b>{{ s.title }}</b>
448 <span>{{ time(s.updated_at) }}</span>
449 </div>
450 <button class="icon-btn session-del" title="删除对话" @click.stop="askDelete(s)">×</button>
451 </div>
452 <p v-if="sessions.length === 0" class="hint session-empty">还没有对话,直接提问即可。</p>
453 </div>
454 </aside>
455
456 <section class="card ai-main">
457 <div class="ai-head">
458 <div>
459 <h2>AI 助手</h2>
460 <p class="hint">可以查询面板状态,也可以在确认后执行运维操作</p>
461 </div>
462 <div class="spacer"></div>
463 <span class="badge" :class="enabled ? 'ok' : 'off'">{{ enabled ? modelName : '未启用' }}</span>
464 </div>
465
466 <div v-if="loading" class="ai-loading"><span class="spin"></span> 正在加载…</div>
467
468 <div v-else-if="!enabled" class="ai-setup">
469 <h3>先配置 AI 接口</h3>
470 <p class="hint">
471 支持任何 OpenAI 兼容接口。填写 Base URL、API Key 和模型后即可在对话中查询并操作面板。
472 </p>
473 <button class="btn btn-primary" @click="navigate('settings')">前往设置</button>
474 </div>
475
476 <template v-else>
477 <div ref="bodyEl" class="ai-body">
478 <div v-if="items.length === 0" class="ai-empty">
479 <h3>有什么我能帮你的吗?</h3>
480 <div class="suggestions">
481 <button
482 v-for="text in suggestions"
483 :key="text"
484 class="chip"
485 :disabled="streaming || hasPending"
486 @click="send(text)"
487 >
488 {{ text }}
489 </button>
490 </div>
491 </div>
492
493 <div v-for="item in items" :key="item.key" class="message" :class="item.role">
494 <div v-if="item.role === 'user'" class="bubble user-bubble">{{ item.content }}</div>
495 <div v-else class="bubble ai-bubble">
496 <MarkdownText v-if="item.content" :text="item.content" />
497 <div v-for="tool in item.tools" :key="tool.id" class="tool-card" :class="tool.status">
498 <div class="tool-head">
499 <b>{{ tool.name }}</b>
500 <span class="tool-status">{{ statusLabel(tool.status) }}</span>
501 </div>
502 <pre v-if="tool.args" class="tool-args mono">{{ prettyArgs(tool.args) }}</pre>
503 <div v-if="tool.result" class="tool-result mono">{{ tool.result }}</div>
504 </div>
505 <ActionCard
506 v-for="action in item.actions"
507 :key="action.id"
508 :action="action"
509 :busy="busyAction === action.id"
510 @decide="(approve: boolean) => decide(action, approve)"
511 />
512 <div v-if="item.streaming && !item.content" class="typing"><span></span><span></span><span></span></div>
513 </div>
514 </div>
515 </div>
516
517 <div class="composer">
518 <textarea
519 ref="inputEl"
520 v-model="input"
521 class="textarea"
522 rows="2"
523 placeholder="描述你的问题或运维任务,Enter 发送,Shift + Enter 换行"
524 :disabled="!enabled"
525 @keydown="onComposerKey"
526 ></textarea>
527 <div class="composer-foot">
528 <span class="hint">{{ hasPending ? '请先执行或拒绝上方的待确认操作' : `${modelName} · 写操作会先让你确认` }}</span>
529 <div class="spacer"></div>
530 <button v-if="streaming" class="btn btn-sm btn-ghost" @click="stop">停止</button>
531 <button v-else class="btn btn-primary btn-sm" :disabled="!canSend" @click="send()">发送</button>
532 </div>
533 </div>
534 </template>
535 </section>
536
537 <ConfirmDialog
538 v-if="deleteTarget"
539 title="删除对话"
540 :message="`确定删除「${deleteTarget.title}」吗?消息记录会一并删除。`"
541 confirm-text="删除"
542 danger
543 @close="deleteTarget = null"
544 @confirm="confirmDelete"
545 />
546 </div>
547</template>
548
549<style scoped>
550.ai-page {
551 display: grid;
552 grid-template-columns: 248px minmax(0, 1fr);
553 gap: 14px;
554 height: calc(100vh - 170px);
555 min-height: 540px;
556}
557.ai-side {
558 display: flex;
559 flex-direction: column;
560 padding: 14px;
561 min-height: 0;
562}
563.ai-side-head {
564 display: flex;
565 align-items: center;
566 gap: 8px;
567 margin-bottom: 10px;
568}
569.session-list {
570 flex: 1;
571 overflow-y: auto;
572 display: flex;
573 flex-direction: column;
574 gap: 4px;
575}
576.session-item {
577 display: flex;
578 align-items: center;
579 gap: 6px;
580 padding: 8px 10px;
581 border-radius: 10px;
582 cursor: pointer;
583}
584.session-item:hover {
585 background: #f4fbf9;
586}
587.session-item.active {
588 background: rgba(52, 211, 153, 0.14);
589}
590.session-text {
591 display: flex;
592 flex-direction: column;
593 min-width: 0;
594 flex: 1;
595}
596.session-text b {
597 font-size: 13px;
598 font-weight: 600;
599 overflow: hidden;
600 text-overflow: ellipsis;
601 white-space: nowrap;
602}
603.session-text span {
604 font-size: 11px;
605 color: var(--muted);
606}
607.session-del {
608 opacity: 0;
609}
610.session-item:hover .session-del {
611 opacity: 1;
612}
613.session-empty {
614 padding: 8px 4px;
615}
616.ai-main {
617 display: flex;
618 flex-direction: column;
619 padding: 16px;
620 min-height: 0;
621}
622.ai-head {
623 display: flex;
624 align-items: flex-start;
625 gap: 10px;
626 margin-bottom: 10px;
627}
628.ai-head h2 {
629 margin: 0;
630}
631.ai-loading,
632.ai-setup {
633 flex: 1;
634 display: flex;
635 flex-direction: column;
636 align-items: center;
637 justify-content: center;
638 gap: 12px;
639 text-align: center;
640}
641.ai-setup h3 {
642 margin: 0;
643}
644.ai-setup p {
645 max-width: 460px;
646}
647.ai-body {
648 flex: 1;
649 min-height: 0;
650 overflow-y: auto;
651 padding: 6px 4px 16px;
652}
653.ai-empty {
654 height: 100%;
655 display: flex;
656 flex-direction: column;
657 align-items: center;
658 justify-content: center;
659 gap: 18px;
660}
661.ai-empty h3 {
662 margin: 0;
663 font-size: 22px;
664}
665.suggestions {
666 display: flex;
667 flex-wrap: wrap;
668 gap: 8px;
669 justify-content: center;
670 max-width: 640px;
671}
672.chip {
673 padding: 8px 14px;
674 border-radius: 999px;
675 border: 1px solid rgba(52, 211, 153, 0.4);
676 background: #f7fcfb;
677 color: #276c5c;
678 cursor: pointer;
679 font-size: 13px;
680}
681.chip:hover {
682 background: rgba(52, 211, 153, 0.12);
683}
684.message {
685 display: flex;
686 margin-bottom: 12px;
687}
688.message.user {
689 justify-content: flex-end;
690}
691.bubble {
692 max-width: min(760px, 88%);
693 padding: 11px 14px;
694 border-radius: 14px;
695}
696.user-bubble {
697 background: rgba(52, 211, 153, 0.16);
698 color: #1f4f46;
699 white-space: pre-wrap;
700}
701.ai-bubble {
702 background: #f7fcfb;
703 border: 1px solid var(--line);
704}
705.tool-card {
706 margin-top: 10px;
707 border-radius: 10px;
708 border: 1px solid var(--line);
709 background: #fbfefd;
710 padding: 10px 12px;
711}
712.tool-card.waiting {
713 border-color: rgba(245, 158, 11, 0.35);
714}
715.tool-card.error {
716 border-color: rgba(239, 68, 68, 0.3);
717}
718.tool-head {
719 display: flex;
720 align-items: center;
721 gap: 8px;
722}
723.tool-status {
724 margin-left: auto;
725 font-size: 11px;
726 color: var(--muted);
727}
728.tool-args {
729 margin: 8px 0 0;
730 padding: 6px 8px;
731 border-radius: 8px;
732 background: #f2faf8;
733 font-size: 12px;
734 white-space: pre-wrap;
735 max-height: 140px;
736 overflow: auto;
737}
738.tool-result {
739 margin-top: 8px;
740 font-size: 12px;
741 color: #31575f;
742 white-space: pre-wrap;
743 max-height: 160px;
744 overflow: auto;
745}
746.typing {
747 display: flex;
748 gap: 4px;
749 padding: 4px 0;
750}
751.typing span {
752 width: 6px;
753 height: 6px;
754 border-radius: 50%;
755 background: rgba(16, 185, 129, 0.5);
756 animation: blink 1.2s infinite;
757}
758.typing span:nth-child(2) {
759 animation-delay: 0.2s;
760}
761.typing span:nth-child(3) {
762 animation-delay: 0.4s;
763}
764@keyframes blink {
765 0%,
766 80%,
767 100% {
768 opacity: 0.25;
769 }
770 40% {
771 opacity: 1;
772 }
773}
774.composer {
775 border-top: 1px solid var(--line);
776 padding-top: 10px;
777}
778.composer textarea {
779 width: 100%;
780 resize: none;
781 min-height: 54px;
782}
783.composer-foot {
784 display: flex;
785 align-items: center;
786 gap: 8px;
787 margin-top: 8px;
788}
789@media (max-width: 860px) {
790 .ai-page {
791 grid-template-columns: 1fr;
792 height: auto;
793 }
794 .ai-side {
795 max-height: 220px;
796 }
797 .ai-main {
798 height: 70vh;
799 }
800}
801</style>