仰望星辰工作室

miaopanel

miaopanel/ web/src/views/Terminal.vue 16.1 KB · 603 行 原始文件
1<script setup lang="ts">
2import { inject, nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
3import { Terminal } from '@xterm/xterm'
4import { FitAddon } from '@xterm/addon-fit'
5import '@xterm/xterm/css/xterm.css'
6import { api, getCsrf } from '../api'
7import { assistTerminal, interpretTerminal } from '../ai'
8import type { AISettings, AITerminalSuggestion } from '../types'
9
10defineOptions({ name: 'TerminalView' })
11
12const notify = inject<(text: string, kind?: 'ok' | 'error') => void>('notify')!
13const everConnected = ref(false)
14const aiEnabled = ref(false)
15const suggestion = ref<AITerminalSuggestion | null>(null)
16const aiBusy = ref(false)
17const editing = ref(false)
18const editText = ref('')
19const editIndex = ref(0)
20const editEl = ref<HTMLTextAreaElement | null>(null)
21
22const container = ref<HTMLDivElement | null>(null)
23const status = ref<'idle' | 'connecting' | 'connected' | 'closed'>('idle')
24const form = reactive({
25 mode: 'local',
26 host: '',
27 port: 22,
28 user: 'root',
29 password: '',
30 privateKey: '',
31})
32
33let term: Terminal | null = null
34let fit: FitAddon | null = null
35let ws: WebSocket | null = null
36let observer: ResizeObserver | null = null
37let typedLine = ''
38let hasCJK = false
39let outputBuffer = ''
40let lastQuestion = ''
41let followUpArmed = false
42let followUpStart = 0
43let followUpCommand = ''
44let followUpTimer = -1
45
46const CJK_RE = /[\u3000-\u303F\u3400-\u4DBF\u4E00-\u9FFF\uF900-\uFAFF\uFF00-\uFFEF]/
47
48const statusText: Record<string, string> = {
49 idle: '未连接',
50 connecting: '连接中',
51 connected: '已连接',
52 closed: '已断开',
53}
54
55function send(msg: unknown) {
56 if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(msg))
57}
58
59function stripAnsi(input: string): string {
60 return input
61 .replace(/\x1b\][^\x07\x1b]*(\x07|\x1b\\)/g, '')
62 .replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, '')
63 .replace(/\x1b[()][A-Z0-9]/g, '')
64}
65
66function buildContext(): string {
67 const text = stripAnsi(outputBuffer)
68 const lines = text.split('\n').slice(-20).join('\n')
69 return lines.slice(-4000)
70}
71
72function cancelFollowUp() {
73 if (followUpTimer >= 0) {
74 window.clearTimeout(followUpTimer)
75 followUpTimer = -1
76 }
77 followUpArmed = false
78}
79
80// After an approved command finishes, feed its output back to the assistant so
81// the original question gets an answer without asking the user to repeat it.
82async function analyzeOutput() {
83 if (!followUpArmed || !term) return
84 followUpArmed = false
85 followUpTimer = -1
86 if (aiBusy.value) return
87 const output = stripAnsi(outputBuffer.slice(followUpStart)).replace(/\r/g, '').trim()
88 if (output === '') return
89 const question = lastQuestion || '请分析这条命令的输出'
90 aiBusy.value = true
91 term.write('\r\n\x1b[2mAI 正在分析输出…\x1b[0m\r\n')
92 try {
93 const res = await interpretTerminal(question, followUpCommand, output.slice(-3000))
94 const reply = (res.reply || '').replace(/\n/g, '\r\n')
95 if (reply) term.write(`\r\n\x1b[1;36m● AI\x1b[0m ${reply}\r\n`)
96 if (res.commands && res.commands.length > 0) {
97 editing.value = false
98 suggestion.value = res
99 term.write('\x1b[2mCtrl+Y 执行 · Ctrl+E 修改 · Ctrl+X 拒绝\x1b[0m\r\n')
100 }
101 } catch (e) {
102 term.write(`\r\n\x1b[31mAI 分析失败: ${(e as Error).message}\x1b[0m\r\n`)
103 } finally {
104 aiBusy.value = false
105 term.focus()
106 }
107}
108
109function onTermData(data: string) {
110 if (data !== '') cancelFollowUp()
111 if (suggestion.value) {
112 handlePendingKey(data)
113 return
114 }
115 if (data === '\r') {
116 if (hasCJK && typedLine.trim() !== '') {
117 const text = typedLine.trim()
118 typedLine = ''
119 hasCJK = false
120 // Clear the echoed Chinese line before asking the assistant.
121 send({ type: 'input', data: '\x15' })
122 void askAI(text)
123 return
124 }
125 typedLine = ''
126 hasCJK = false
127 send({ type: 'input', data: '\r' })
128 return
129 }
130 if (data === '\x03' || data === '\x15') {
131 typedLine = ''
132 hasCJK = false
133 send({ type: 'input', data })
134 return
135 }
136 for (const ch of data) {
137 if (ch === '\x7f' || ch === '\b') {
138 typedLine = typedLine.slice(0, -1)
139 continue
140 }
141 if (ch === '\x1b' || ch === '\t') continue
142 if (ch >= ' ') {
143 typedLine += ch
144 if (CJK_RE.test(ch)) hasCJK = true
145 }
146 }
147 if (typedLine.length > 2000) typedLine = typedLine.slice(-2000)
148 send({ type: 'input', data })
149}
150
151function handlePendingKey(data: string) {
152 if (data === '\x19') {
153 executeAt(0)
154 return
155 }
156 if (data === '\x05') {
157 startEdit(0)
158 return
159 }
160 if (data === '\x18' || data === '\x1b') {
161 rejectPending()
162 return
163 }
164 // While a confirmation card is open other keys must not reach the shell.
165}
166
167async function askAI(text: string) {
168 if (!term) return
169 if (!aiEnabled.value) {
170 term.write('\r\n\x1b[33mAI 助手未启用,请先在设置中配置并启用。\x1b[0m\r\n')
171 term.focus()
172 return
173 }
174 if (aiBusy.value) return
175 lastQuestion = text
176 aiBusy.value = true
177 term.write('\r\n\x1b[2mAI 正在解析…\x1b[0m\r\n')
178 try {
179 const res = await assistTerminal(text, form.mode, buildContext())
180 const reply = (res.reply || '已收到指令').replace(/\n/g, '\r\n')
181 term.write(`\r\n\x1b[1;36m● AI\x1b[0m ${reply}\r\n`)
182 if (res.commands && res.commands.length > 0) {
183 editing.value = false
184 suggestion.value = res
185 term.write('\x1b[2mCtrl+Y 执行 · Ctrl+E 修改 · Ctrl+X 拒绝\x1b[0m\r\n')
186 } else {
187 term.focus()
188 }
189 } catch (e) {
190 term.write(`\r\n\x1b[31mAI 请求失败: ${(e as Error).message}\x1b[0m\r\n`)
191 term.focus()
192 } finally {
193 aiBusy.value = false
194 }
195}
196
197function executeCommand(command: string) {
198 const cmd = command.trim()
199 if (!cmd) return
200 suggestion.value = null
201 editing.value = false
202 cancelFollowUp()
203 followUpStart = outputBuffer.length
204 followUpCommand = cmd
205 followUpArmed = true
206 send({ type: 'input', data: '\x15' })
207 send({ type: 'input', data: cmd })
208 send({ type: 'input', data: '\r' })
209 term?.focus()
210}
211
212function executeAt(index: number) {
213 const command = suggestion.value?.commands[index]?.command ?? ''
214 executeCommand(command)
215}
216
217function startEdit(index: number) {
218 const command = suggestion.value?.commands[index]?.command ?? ''
219 if (!command) return
220 editIndex.value = index
221 editText.value = command
222 editing.value = true
223 nextTick(() => editEl.value?.focus())
224}
225
226function runEdited() {
227 const cmd = editText.value.trim()
228 if (!cmd) return
229 executeCommand(cmd)
230}
231
232function rejectPending() {
233 suggestion.value = null
234 editing.value = false
235 term?.write('\x1b[2m已取消 AI 建议\x1b[0m\r\n')
236 term?.focus()
237}
238
239async function loadAI() {
240 try {
241 const data = await api.get<AISettings>('api/v1/settings/ai')
242 aiEnabled.value = data.enabled
243 } catch {
244 /* the terminal still works without the assistant */
245 }
246}
247
248function connect() {
249 if (!term || status.value === 'connecting' || status.value === 'connected') return
250 status.value = 'connecting'
251 term.reset()
252 term.writeln('\x1b[2m正在建立会话…\x1b[0m')
253 const proto = location.protocol === 'https:' ? 'wss:' : 'ws:'
254 const base = location.pathname.replace(/\/+$/, '')
255 const url = `${proto}//${location.host}${base}/api/v1/ws/terminal?csrf=${encodeURIComponent(getCsrf())}`
256 ws = new WebSocket(url)
257 ws.onopen = () => {
258 send({
259 type: 'init',
260 mode: form.mode,
261 host: form.host.trim(),
262 port: Number(form.port) || 22,
263 user: form.user.trim(),
264 password: form.password,
265 private_key: form.privateKey,
266 cols: term!.cols,
267 rows: term!.rows,
268 })
269 }
270 ws.onmessage = (ev) => {
271 let msg: { type: string; data?: string; message?: string }
272 try {
273 msg = JSON.parse(ev.data)
274 } catch {
275 return
276 }
277 switch (msg.type) {
278 case 'ready':
279 status.value = 'connected'
280 everConnected.value = true
281 outputBuffer = ''
282 typedLine = ''
283 hasCJK = false
284 suggestion.value = null
285 cancelFollowUp()
286 lastQuestion = ''
287 term?.clear()
288 term?.focus()
289 break
290 case 'data':
291 outputBuffer = (outputBuffer + (msg.data ?? '')).slice(-12000)
292 term?.write(msg.data ?? '')
293 if (followUpArmed) {
294 if (followUpTimer >= 0) window.clearTimeout(followUpTimer)
295 followUpTimer = window.setTimeout(() => {
296 void analyzeOutput()
297 }, 1200)
298 }
299 break
300 case 'exit':
301 status.value = 'closed'
302 term?.writeln('\r\n\x1b[33m会话已结束\x1b[0m')
303 break
304 case 'error':
305 notify(msg.message || '终端错误', 'error')
306 status.value = 'closed'
307 break
308 }
309 }
310 ws.onclose = () => {
311 if (status.value !== 'closed') {
312 status.value = 'closed'
313 term?.writeln('\r\n\x1b[33m连接已关闭\x1b[0m')
314 }
315 }
316 ws.onerror = () => {
317 notify('终端连接失败', 'error')
318 status.value = 'closed'
319 }
320}
321
322function disconnect() {
323 ws?.close()
324 ws = null
325 status.value = 'closed'
326}
327
328function fitNow() {
329 if (!fit || !term) return
330 try {
331 fit.fit()
332 send({ type: 'resize', cols: term.cols, rows: term.rows })
333 } catch {
334 /* container hidden */
335 }
336}
337
338onMounted(() => {
339 if (!container.value) return
340 term = new Terminal({
341 fontSize: 13,
342 fontFamily: '"JetBrains Mono", "Cascadia Code", Consolas, monospace',
343 cursorBlink: true,
344 scrollback: 5000,
345 lineHeight: 1.25,
346 theme: {
347 background: '#f7fcfb',
348 foreground: '#2c5058',
349 cursor: '#10b981',
350 cursorAccent: '#ffffff',
351 selectionBackground: 'rgba(52, 211, 153, 0.28)',
352 black: '#173a43',
353 red: '#ef4444',
354 green: '#10b981',
355 yellow: '#f59e0b',
356 blue: '#0ea5e9',
357 magenta: '#8b5cf6',
358 cyan: '#06b6d4',
359 white: '#e6eef0',
360 },
361 })
362 fit = new FitAddon()
363 term.loadAddon(fit)
364 term.open(container.value)
365 fit.fit()
366 term.writeln('\x1b[1;32mMiaoPanel 终端\x1b[0m')
367 term.writeln('\x1b[2m本机模式以面板进程身份运行;SSH 模式可连接任意可达主机。\x1b[0m')
368 term.writeln('\x1b[2m输入自然语言(中文)或命令,AI 将智能响应,执行前会先让你确认。\x1b[0m')
369 term.writeln('')
370 term.onData(onTermData)
371 observer = new ResizeObserver(() => fitNow())
372 observer.observe(container.value)
373 term.focus()
374 void loadAI()
375})
376
377onBeforeUnmount(() => {
378 observer?.disconnect()
379 ws?.close()
380 term?.dispose()
381 suggestion.value = null
382 cancelFollowUp()
383})
384</script>
385
386<template>
387 <div class="card">
388 <div class="row">
389 <div>
390 <h2>Web 终端</h2>
391 <p class="hint">本机 PTY 或远程 SSH 会话,支持窗口自适应与常用 Ctrl 组合键</p>
392 </div>
393 <div class="spacer"></div>
394 <span class="badge" :class="status === 'connected' ? 'ok' : status === 'connecting' ? '' : 'off'">
395 {{ statusText[status] }}
396 </span>
397 </div>
398
399 <div class="term-form">
400 <select v-model="form.mode" class="select" style="width: 130px" :disabled="status === 'connected'">
401 <option value="local">本机终端</option>
402 <option value="ssh">远程 SSH</option>
403 </select>
404
405 <template v-if="form.mode === 'ssh'">
406 <input v-model="form.host" class="input" style="width: 190px" placeholder="主机地址" :disabled="status === 'connected'" />
407 <input v-model.number="form.port" class="input" style="width: 90px" type="number" placeholder="22" :disabled="status === 'connected'" />
408 <input v-model="form.user" class="input" style="width: 130px" placeholder="用户名" :disabled="status === 'connected'" />
409 <input v-model="form.password" class="input" style="width: 170px" type="password" placeholder="密码" :disabled="status === 'connected'" />
410 </template>
411
412 <div class="spacer"></div>
413 <button v-if="status !== 'connected'" class="btn btn-primary btn-sm" :disabled="status === 'connecting'" @click="connect">
414 <span v-if="status === 'connecting'" class="spin"></span>
415 {{ everConnected ? '重新连接' : '连接' }}
416 </button>
417 <button v-else class="btn btn-danger btn-sm" @click="disconnect">断开</button>
418 </div>
419 <p class="hint" style="margin: -4px 0 10px">
420 切换到其他页面不会中断会话(终端保持挂载);连接断开后可直接点「重新连接」。
421 </p>
422
423 <details v-if="form.mode === 'ssh'" class="key-box">
424 <summary>使用私钥连接(可选,优先于密码)</summary>
425 <textarea v-model="form.privateKey" class="textarea" placeholder="-----BEGIN OPENSSH PRIVATE KEY-----" :disabled="status === 'connected'"></textarea>
426 </details>
427
428 <div class="terminal-wrap">
429 <div ref="container" class="terminal-box"></div>
430
431 <div v-if="suggestion" class="ai-term-card">
432 <div class="ai-term-head">
433 <span class="ai-dot"></span>
434 <b>AI 建议</b>
435 <span class="hint">Ctrl+Y 执行 · Ctrl+E 修改 · Ctrl+X 拒绝</span>
436 <div class="spacer"></div>
437 <button class="icon-btn" title="关闭" @click="rejectPending">×</button>
438 </div>
439
440 <p v-if="suggestion.reply" class="ai-term-reply">{{ suggestion.reply }}</p>
441
442 <div
443 v-for="(cmd, idx) in suggestion.commands"
444 :key="idx"
445 class="ai-term-cmd"
446 :class="{ danger: cmd.risk === 'danger' }"
447 >
448 <pre class="mono">{{ cmd.command }}</pre>
449 <div class="ai-term-cmd-foot">
450 <span class="hint">{{ cmd.note }}</span>
451 <div class="spacer"></div>
452 <button class="btn btn-ghost btn-sm" @click="startEdit(idx)">修改</button>
453 <button
454 class="btn btn-sm"
455 :class="cmd.risk === 'danger' ? 'btn-danger' : 'btn-primary'"
456 @click="executeAt(idx)"
457 >
458 执行
459 </button>
460 </div>
461 </div>
462
463 <div v-if="editing" class="ai-term-edit">
464 <textarea
465 ref="editEl"
466 v-model="editText"
467 class="textarea mono"
468 rows="3"
469 @keydown.enter.exact.prevent="runEdited"
470 ></textarea>
471 <div class="row" style="margin-top: 8px">
472 <div class="spacer"></div>
473 <button class="btn btn-ghost btn-sm" @click="editing = false">取消</button>
474 <button class="btn btn-primary btn-sm" @click="runEdited">执行修改后的命令</button>
475 </div>
476 </div>
477 </div>
478 </div>
479 </div>
480</template>
481
482<style scoped>
483.term-form {
484 display: flex;
485 align-items: center;
486 gap: 8px;
487 flex-wrap: wrap;
488 margin: 6px 0 12px;
489}
490
491.key-box {
492 margin-bottom: 12px;
493 font-size: 12px;
494 color: var(--muted);
495}
496
497.key-box summary {
498 cursor: pointer;
499 padding: 4px 0;
500}
501
502.key-box .textarea {
503 margin-top: 8px;
504 min-height: 110px;
505}
506
507.terminal-wrap {
508 position: relative;
509}
510
511.terminal-box {
512 height: 520px;
513 padding: 10px 12px;
514 border-radius: 12px;
515 border: 1px solid var(--line);
516 background: #f7fcfb;
517 overflow: hidden;
518}
519
520.terminal-box :deep(.xterm) {
521 height: 100%;
522}
523
524.terminal-box :deep(.xterm-viewport) {
525 background: transparent !important;
526}
527
528.ai-term-card {
529 position: absolute;
530 left: 12px;
531 right: 12px;
532 bottom: 12px;
533 z-index: 10;
534 max-height: 70%;
535 overflow-y: auto;
536 padding: 12px 14px;
537 border-radius: 14px;
538 border: 1px solid rgba(14, 165, 233, 0.38);
539 background: rgba(255, 255, 255, 0.97);
540 box-shadow: 0 12px 34px rgba(20, 60, 70, 0.18);
541 backdrop-filter: blur(4px);
542}
543
544.ai-term-head {
545 display: flex;
546 align-items: center;
547 gap: 8px;
548 margin-bottom: 8px;
549}
550
551.ai-dot {
552 width: 8px;
553 height: 8px;
554 border-radius: 50%;
555 background: #0ea5e9;
556}
557
558.ai-term-reply {
559 margin: 0 0 10px;
560 color: #31575f;
561 white-space: pre-wrap;
562 line-height: 1.65;
563}
564
565.ai-term-cmd {
566 margin-top: 8px;
567 padding: 10px 12px;
568 border-radius: 10px;
569 border: 1px solid rgba(52, 211, 153, 0.3);
570 background: #f7fcfb;
571}
572
573.ai-term-cmd.danger {
574 border-color: rgba(239, 68, 68, 0.35);
575 background: #fff6f6;
576}
577
578.ai-term-cmd pre {
579 margin: 0 0 8px;
580 padding: 8px 10px;
581 border-radius: 8px;
582 background: #ffffff;
583 border: 1px solid var(--line);
584 font-size: 12.5px;
585 white-space: pre-wrap;
586 word-break: break-all;
587}
588
589.ai-term-cmd-foot {
590 display: flex;
591 align-items: center;
592 gap: 8px;
593}
594
595.ai-term-edit {
596 margin-top: 10px;
597}
598
599.ai-term-edit textarea {
600 width: 100%;
601 resize: vertical;
602}
603</style>