终端模块初版
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,252 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 终端独立窗口。
|
||||
*
|
||||
* # 与主窗口的关系
|
||||
*
|
||||
* 同一个 `sessionId` 可以同时被两个窗口订阅输出 —— 这不是设计缺陷,而是
|
||||
* 「分离标签」的应有语义:独立窗口打开后,主窗口那侧的面板仍然保留(
|
||||
* 内容同步更新),只是标记为 detached,用户随时可以收回来。
|
||||
*
|
||||
* 因此本窗口**不新建会话、也不接管生命周期**,它只是一个**附加的视图**:
|
||||
* 订阅同一份输出、写入同一个 PTY、在关闭时把 detached 置回 false。
|
||||
*
|
||||
* # 为什么这里可以安全地装一个独立 Pinia
|
||||
*
|
||||
* Pinia 是**窗口级**的:每个 WebView 窗口有自己的 JS 运行时,各自的 store
|
||||
* 实例互不可见,但**后端状态是共享的**(都通过 IPC 打到同一个 `TerminalManager`)。
|
||||
* 所以这里 `createPinia()` 不会造成状态分裂 —— 分叉的只是「前端缓存」,
|
||||
* 而事件监听的幂等保护(`store.ensureListeners` 里的 `listening` 标志)
|
||||
* 恰好保证了每个窗口只注册一份自己的监听。
|
||||
*
|
||||
* # 为什么必须自己注册事件监听
|
||||
*
|
||||
* 输出事件是**窗口广播**(Rust 侧 `app.emit` 发到所有窗口),主窗口的监听器
|
||||
* 管不到本窗口。这正是「独立窗口能收到输出」的实现基础。
|
||||
*/
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { getCurrentWindow } from '@tauri-apps/api/window'
|
||||
import { AlertTriangle, Loader2, Menu, Minus, Square, X } from '@lucide/vue'
|
||||
import { useTerminalStore } from '@/stores/terminalStore'
|
||||
import { useTerminalStream } from '@/composables/useSessionStream'
|
||||
import { useTerminalKeys } from '@/composables/useTerminalKeys'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import TerminalPane from './components/TerminalPane.vue'
|
||||
import TerminalStatusBar from './components/TerminalStatusBar.vue'
|
||||
import HostKeyPromptDialog from './components/HostKeyPromptDialog.vue'
|
||||
|
||||
const logger = createLogger('terminal')
|
||||
|
||||
// ===== 从 URL hash 解析会话 id:#terminal-window/{session_id} =====
|
||||
//
|
||||
// 用路径段而不是 query 参数:会话 id 是后端生成的短串(如 `t1758...`),
|
||||
// 放在路径里读起来更像「标识」,且与截图模块的 `#screenshot-overlay/0` 一致。
|
||||
const hash = window.location.hash
|
||||
const sessionId = hash.replace('#terminal-window/', '').replace('#terminal-window', '')
|
||||
if (!sessionId) {
|
||||
logger.error('终端独立窗口缺少 sessionId 参数')
|
||||
}
|
||||
|
||||
const win = getCurrentWindow()
|
||||
|
||||
const store = useTerminalStore()
|
||||
const stream = useTerminalStream({ fixedSessionId: ref(sessionId) })
|
||||
const { effectiveAppearance, bumpFont, resetFont, bindings, init } = stream
|
||||
|
||||
const session = computed(() => store.sessionById(sessionId))
|
||||
|
||||
// ===== 面板引用 =====
|
||||
|
||||
const paneRef = ref<InstanceType<typeof TerminalPane> | null>(null)
|
||||
|
||||
// ===== 生命周期 =====
|
||||
|
||||
const ready = ref(false)
|
||||
const fatal = ref('')
|
||||
|
||||
onMounted(async () => {
|
||||
if (!sessionId) {
|
||||
fatal.value = '缺少会话 ID,无法确定要显示哪个会话'
|
||||
ready.value = true
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await init()
|
||||
// 会话可能已经被关闭(窗口是异步创建的,这中间有窗口期)
|
||||
if (!store.sessionById(sessionId)) {
|
||||
fatal.value = '该会话已结束或不存在'
|
||||
ready.value = true
|
||||
// 会话没了,本窗口没有意义 —— 给用户一点时间看到提示再关闭
|
||||
setTimeout(() => void win.close(), 1800)
|
||||
return
|
||||
}
|
||||
// 把标题设成会话名,方便任务栏与窗口列表识别
|
||||
const info = store.sessionById(sessionId)
|
||||
if (info?.title) {
|
||||
void win.setTitle(`${info.title} · 终端`)
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error(`独立窗口初始化失败:${String(e)}`)
|
||||
fatal.value = `初始化失败:${String(e)}`
|
||||
} finally {
|
||||
ready.value = true
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* 窗口关闭时把会话的 detached 置回 false。
|
||||
*
|
||||
* 这是**必须**做的:detached 标记决定了主窗口是否显示「已在独立窗口打开」的提示条。
|
||||
* 若窗口被用户拖到任务栏关掉而不重置,主窗口会一直以为这个会话还在独立窗口里,
|
||||
* 显示一个永远点不动的提示,且用户没有任何办法消除它。
|
||||
*
|
||||
* 用 `onBeforeUnmount` 而不是监听 Tauri 的 close 事件:WebView 卸载时
|
||||
* `invoke` 仍可发出(IPC 通道在窗口销毁前还有效),这是最后一个可靠时机。
|
||||
*/
|
||||
onBeforeUnmount(() => {
|
||||
if (!sessionId) return
|
||||
void store.attachSession(sessionId).catch(e => {
|
||||
logger.warn(`重置 detached 标记失败:${String(e)}`)
|
||||
})
|
||||
})
|
||||
|
||||
// ===== 快捷键(独立窗口内只保留与本会话相关的动作) =====
|
||||
|
||||
useTerminalKeys({
|
||||
bindings: () => bindings.value,
|
||||
onAction: actionId => {
|
||||
switch (actionId) {
|
||||
case 'copy': {
|
||||
const text = paneRef.value?.getSelection?.()
|
||||
if (text) void navigator.clipboard.writeText(text.replace(/\n+$/, ''))
|
||||
break
|
||||
}
|
||||
case 'paste':
|
||||
void navigator.clipboard
|
||||
.readText()
|
||||
.then(text => (text ? store.write(sessionId, text) : undefined))
|
||||
.catch(e => logger.error(`粘贴失败:${String(e)}`))
|
||||
break
|
||||
case 'clear':
|
||||
paneRef.value?.clear?.()
|
||||
break
|
||||
case 'fontIncrease':
|
||||
void bumpFont(1)
|
||||
break
|
||||
case 'fontDecrease':
|
||||
void bumpFont(-1)
|
||||
break
|
||||
case 'fontReset':
|
||||
resetFont()
|
||||
break
|
||||
// 标签类/分屏类动作在独立窗口里没有意义,静默忽略
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// ===== 无边框窗口的自定义标题栏 =====
|
||||
|
||||
/**
|
||||
* 无边框窗口需要自己实现拖拽与最小化/最大化/关闭。
|
||||
*
|
||||
* 但本窗口**不实现拖拽区域**:终端面板占满整个窗口,若在顶部加拖拽条,
|
||||
* 用户会失去一块垂直空间;而拖拽整个窗口的需求可以通过系统的方式完成
|
||||
* (Alt+Space、或拖窗口边缘)。这里只保留最小化/最大化/关闭三个按钮。
|
||||
*/
|
||||
async function minimize() {
|
||||
await win.minimize()
|
||||
}
|
||||
async function toggleMaximize() {
|
||||
await win.toggleMaximize()
|
||||
}
|
||||
async function closeWindow() {
|
||||
await win.close()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col h-screen w-screen overflow-hidden bg-background">
|
||||
<!-- 标题栏 -->
|
||||
<div
|
||||
class="shrink-0 h-8 flex items-center gap-2 px-2 border-b border-border select-none"
|
||||
data-tauri-drag-region
|
||||
>
|
||||
<Menu class="size-3.5 text-muted-foreground shrink-0 pointer-events-none" />
|
||||
<span class="text-xs truncate flex-1 pointer-events-none">
|
||||
{{ session?.title || '终端' }}
|
||||
</span>
|
||||
|
||||
<button
|
||||
class="size-6 flex items-center justify-center rounded hover:bg-accent transition-colors"
|
||||
title="最小化"
|
||||
@click="minimize"
|
||||
>
|
||||
<Minus class="size-3" />
|
||||
</button>
|
||||
<button
|
||||
class="size-6 flex items-center justify-center rounded hover:bg-accent transition-colors"
|
||||
title="最大化"
|
||||
@click="toggleMaximize"
|
||||
>
|
||||
<Square class="size-2.5" />
|
||||
</button>
|
||||
<button
|
||||
class="size-6 flex items-center justify-center rounded hover:bg-destructive
|
||||
hover:text-destructive-foreground transition-colors"
|
||||
title="关闭窗口(会话保留)"
|
||||
@click="closeWindow"
|
||||
>
|
||||
<X class="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 主体 -->
|
||||
<div class="flex-1 min-h-0 relative">
|
||||
<div v-if="!ready" class="absolute inset-0 flex items-center justify-center">
|
||||
<div class="flex flex-col items-center gap-3">
|
||||
<Loader2 class="size-5 animate-spin text-muted-foreground" />
|
||||
<p class="text-xs text-muted-foreground">正在加载会话…</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="fatal" class="absolute inset-0 flex items-center justify-center p-8">
|
||||
<div class="flex flex-col items-center gap-3 text-center">
|
||||
<AlertTriangle class="size-8 text-destructive/60" />
|
||||
<p class="text-sm text-muted-foreground">{{ fatal }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TerminalPane
|
||||
v-else
|
||||
ref="paneRef"
|
||||
:session-id="sessionId"
|
||||
:appearance="effectiveAppearance"
|
||||
:visible="true"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- 状态栏 -->
|
||||
<TerminalStatusBar
|
||||
v-if="ready && !fatal"
|
||||
:session="session"
|
||||
:font-size="effectiveAppearance?.fontSize ?? 14"
|
||||
:cols="session?.cols"
|
||||
:rows="session?.rows"
|
||||
/>
|
||||
|
||||
<!-- 主机密钥确认:独立窗口也可能触发(用户直接从这个窗口发起连接时) -->
|
||||
<HostKeyPromptDialog />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 独立窗口无边框,禁止整页滚动与选中,贴近原生窗口行为 */
|
||||
:global(html),
|
||||
:global(body) {
|
||||
overflow: hidden;
|
||||
margin: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,211 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* AI 命令助手面板(P2)。
|
||||
*
|
||||
* # 引擎来源
|
||||
*
|
||||
* 复用**翻译模块**的 AI 引擎配置(Base URL / 模型 / 密钥)——用户配置一份 API
|
||||
* 即可在两处使用。没有可用引擎时展示引导文案而不是让用户点了「生成」才报错。
|
||||
*
|
||||
* # 交互与片段库同一套安全语义
|
||||
*
|
||||
* 建议默认「填入命令行」(用户自己按回车),「直接执行」是显式第二动作。
|
||||
* 理由与 SnippetPanel 一致:命令被自动执行与等待用户确认,在心理上完全不同;
|
||||
* 而且模型的建议未经本地验证,用户应当有机会先看一眼再回车。
|
||||
*
|
||||
* # 上下文
|
||||
*
|
||||
* 「带上下文」开关取终端当前**选中文本**(用户选中一段报错再点生成,
|
||||
* 模型能理解「接着这个修」)。没有选区时不传上下文——把整个屏幕
|
||||
* 内容都塞给模型既稀释意图又增加 token 费用。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { Sparkles, Square, TerminalSquare } from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { useTerminalStore } from '@/stores/terminalStore'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from '@/components/ui/dialog'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import type { AiEngineOption, CommandSuggestion } from '@/types/terminal'
|
||||
|
||||
const logger = createLogger('terminal')
|
||||
const store = useTerminalStore()
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
/** 当前会话(填入/执行的目标;null 时只能看不能填) */
|
||||
sessionId: string | null
|
||||
/** 取终端上下文(选中文本等),由 TerminalModule 提供 */
|
||||
getContext: () => string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ (e: 'update:open', v: boolean): void }>()
|
||||
|
||||
const engines = ref<AiEngineOption[]>([])
|
||||
const engineId = ref('')
|
||||
const intent = ref('')
|
||||
const useContext = ref(false)
|
||||
const loadingEngines = ref(false)
|
||||
const generating = ref(false)
|
||||
const suggestions = ref<CommandSuggestion[]>([])
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
async v => {
|
||||
if (!v) return
|
||||
suggestions.value = []
|
||||
loadingEngines.value = true
|
||||
try {
|
||||
engines.value = await store.aiEngines()
|
||||
// 默认选第一个(后端已按优先级排序);保留用户上次的选择
|
||||
if (engineId.value && engines.value.some(e => e.id === engineId.value)) {
|
||||
// keep
|
||||
} else {
|
||||
engineId.value = engines.value[0]?.id ?? ''
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error(`加载 AI 引擎列表失败:${String(e)}`)
|
||||
toast.error(`加载引擎列表失败:${String(e)}`)
|
||||
} finally {
|
||||
loadingEngines.value = false
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
const canGenerate = computed(
|
||||
() => !!engineId.value && intent.value.trim().length > 0 && !generating.value
|
||||
)
|
||||
|
||||
async function generate() {
|
||||
if (!canGenerate.value) return
|
||||
generating.value = true
|
||||
try {
|
||||
const ctx = useContext.value ? props.getContext() : ''
|
||||
suggestions.value = await store.aiSuggest(engineId.value, intent.value, ctx)
|
||||
if (suggestions.value.length === 0) {
|
||||
toast.info('模型没有给出建议,试着换个描述')
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(`生成失败:${String(e)}`)
|
||||
} finally {
|
||||
generating.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 填入 / 执行。
|
||||
*
|
||||
* 两条路径都把命令字节写进 PTY stdin;区别只是要不要带回车(0x0D)。
|
||||
* 「填入」让用户保留最后的确认权——模型的建议可能差一个参数。
|
||||
*/
|
||||
async function deliver(cmd: string, execute: boolean) {
|
||||
if (!props.sessionId) {
|
||||
toast.error('当前没有可写入的会话')
|
||||
return
|
||||
}
|
||||
try {
|
||||
const payload = execute ? `${cmd}\r` : cmd
|
||||
await store.write(props.sessionId, new TextEncoder().encode(payload))
|
||||
if (!execute) emit('update:open', false) // 填入后回到终端看命令
|
||||
} catch (e) {
|
||||
toast.error(`写入终端失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 引擎展示名(含模型,方便多引擎用户区分) */
|
||||
function engineLabel(e: AiEngineOption): string {
|
||||
return e.model ? `${e.name}(${e.model})` : e.name
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog :open="open" @update:open="v => emit('update:open', v)">
|
||||
<DialogContent class="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle class="flex items-center gap-2 text-base">
|
||||
<Sparkles class="size-4" />AI 命令助手
|
||||
</DialogTitle>
|
||||
<DialogDescription class="text-xs">
|
||||
复用翻译设置里的 AI 引擎。建议默认只填入命令行,由你确认后执行。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<!-- 引擎选择 -->
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">引擎</Label>
|
||||
<p v-if="loadingEngines" class="text-xs text-muted-foreground">加载中…</p>
|
||||
<template v-else-if="engines.length > 0">
|
||||
<Select v-model="engineId">
|
||||
<SelectTrigger class="h-8 text-xs">
|
||||
<SelectValue placeholder="选择引擎" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="e in engines" :key="e.id" :value="e.id">
|
||||
{{ engineLabel(e) }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</template>
|
||||
<p v-else class="text-xs text-muted-foreground">
|
||||
还没有可用的 AI 引擎。请到
|
||||
<span class="text-foreground font-medium">翻译模块 → 设置 → 引擎</span>
|
||||
配置一个(DeepSeek / OpenAI / Ollama 等 OpenAI 兼容服务均可),配置后回到这里刷新。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- 意图 -->
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">你想做什么</Label>
|
||||
<Input
|
||||
v-model="intent"
|
||||
placeholder="例如:找出占用磁盘最大的 10 个目录"
|
||||
class="h-8 text-sm"
|
||||
@keydown.enter="generate"
|
||||
/>
|
||||
<label class="flex items-center gap-1.5 text-[11px] text-muted-foreground cursor-pointer select-none">
|
||||
<input v-model="useContext" type="checkbox" class="accent-primary" />
|
||||
带上终端选中的文本作为上下文
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<Button size="sm" class="w-full gap-1.5 text-xs" :disabled="!canGenerate" @click="generate">
|
||||
<Sparkles class="size-3.5" />{{ generating ? '生成中…' : '生成建议' }}
|
||||
</Button>
|
||||
|
||||
<!-- 建议 -->
|
||||
<div v-if="suggestions.length > 0" class="space-y-1.5">
|
||||
<div
|
||||
v-for="(s, i) in suggestions"
|
||||
:key="i"
|
||||
class="rounded border border-border px-2.5 py-1.5 space-y-1"
|
||||
>
|
||||
<p class="text-xs font-mono break-all">{{ s.command }}</p>
|
||||
<p class="text-[11px] text-muted-foreground">{{ s.description }}</p>
|
||||
<div class="flex gap-1.5 justify-end">
|
||||
<Button variant="outline" size="sm" class="h-6 gap-1 px-2 text-[11px]" :disabled="!sessionId" @click="deliver(s.command, false)">
|
||||
<TerminalSquare class="size-3" />填入命令行
|
||||
</Button>
|
||||
<Button size="sm" class="h-6 gap-1 px-2 text-[11px]" :disabled="!sessionId" @click="deliver(s.command, true)">
|
||||
<Square class="size-3" />直接执行
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,253 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 端口转发面板(P2)。
|
||||
*
|
||||
* # 交互形态的取舍
|
||||
*
|
||||
* 用**对话框**而不是 SFTP 那样的停靠面板:转发是「配置一次就忘」的低频操作,
|
||||
* 不值得长期占据一块屏幕区域;对话框随开随关,与工具栏按钮的生命周期一致。
|
||||
*
|
||||
* # 两个方向的语义(UI 文案要写对,这是最容易配错的地方)
|
||||
*
|
||||
* - 本地转发(-L):「访问**我本机**的 A 端口 = 访问**服务器看到的** B 服务」。
|
||||
* 典型:本机 13306 → 服务器视角的数据库 3306。
|
||||
* - 远程转发(-R):「访问**服务器**的 A 端口 = 回到**我本机**的 B 服务」。
|
||||
* 典型:在服务器上访问 18080 = 访问我本机跑着的开发服务器。
|
||||
*
|
||||
* 规则挂在会话上不持久化:会话关闭全部失效(与 ssh 客户端直觉一致)。
|
||||
*/
|
||||
import { ref, watch } from 'vue'
|
||||
import { Network, Plus, Trash2 } from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { useTerminalStore } from '@/stores/terminalStore'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from '@/components/ui/dialog'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import type { ForwardView } from '@/types/terminal'
|
||||
|
||||
const logger = createLogger('terminal')
|
||||
const store = useTerminalStore()
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
sessionId: string | null
|
||||
/** 会话标题(显示当前操作对象) */
|
||||
sessionLabel: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ (e: 'update:open', v: boolean): void }>()
|
||||
|
||||
const forwards = ref<ForwardView[]>([])
|
||||
const loading = ref(false)
|
||||
const busy = ref(false)
|
||||
|
||||
// ===== 新增表单 =====
|
||||
|
||||
const formKind = ref<'local' | 'remote'>('local')
|
||||
const formBindHost = ref('127.0.0.1')
|
||||
const formBindPort = ref('' as string | number)
|
||||
const formTargetHost = ref('127.0.0.1')
|
||||
const formTargetPort = ref('' as string | number)
|
||||
|
||||
/** 打开时拉取一次列表;之后靠本地操作同步(转发只在别处被会话关闭清除) */
|
||||
watch(
|
||||
() => props.open,
|
||||
async v => {
|
||||
if (!v) return
|
||||
forwards.value = []
|
||||
if (!props.sessionId) return
|
||||
loading.value = true
|
||||
try {
|
||||
forwards.value = await store.listForwards(props.sessionId)
|
||||
} catch (e) {
|
||||
logger.error(`加载转发列表失败:${String(e)}`)
|
||||
toast.error(`加载转发列表失败:${String(e)}`)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
function portOf(v: string | number): number {
|
||||
const n = Number(v)
|
||||
return Number.isInteger(n) ? n : 0
|
||||
}
|
||||
|
||||
/** 新增端口语义随方向变化,切换类型时给出合理默认值 */
|
||||
watch(formKind, k => {
|
||||
if (k === 'remote') {
|
||||
// 服务器上开 18080,回连本机 8080 是常见形态
|
||||
if (!formBindPort.value) formBindPort.value = 18080
|
||||
formTargetHost.value = '127.0.0.1'
|
||||
if (!formTargetPort.value) formTargetPort.value = 8080
|
||||
} else {
|
||||
if (!formBindPort.value) formBindPort.value = 13306
|
||||
if (!formTargetPort.value) formTargetPort.value = 3306
|
||||
}
|
||||
})
|
||||
|
||||
async function submitAdd() {
|
||||
if (!props.sessionId) return
|
||||
const bp = portOf(formBindPort.value)
|
||||
const tp = portOf(formTargetPort.value)
|
||||
if (!bp || bp > 65535) {
|
||||
toast.error('监听端口需在 1–65535 之间')
|
||||
return
|
||||
}
|
||||
if (!formTargetHost.value.trim()) {
|
||||
toast.error('请填写目标地址')
|
||||
return
|
||||
}
|
||||
if (!tp || tp > 65535) {
|
||||
toast.error('目标端口需在 1–65535 之间')
|
||||
return
|
||||
}
|
||||
|
||||
busy.value = true
|
||||
try {
|
||||
forwards.value = await store.addForward(props.sessionId, {
|
||||
kind: formKind.value,
|
||||
bindHost: formBindHost.value.trim(),
|
||||
bindPort: bp,
|
||||
targetHost: formTargetHost.value.trim(),
|
||||
targetPort: tp
|
||||
})
|
||||
toast.success('转发已建立')
|
||||
// 清空端口便于连续添加,保留类型与地址习惯
|
||||
formBindPort.value = ''
|
||||
formTargetPort.value = ''
|
||||
} catch (e) {
|
||||
toast.error(`${String(e)}`)
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function removeOne(f: ForwardView) {
|
||||
if (!props.sessionId) return
|
||||
try {
|
||||
forwards.value = await store.removeForward(props.sessionId, f.id)
|
||||
} catch (e) {
|
||||
toast.error(`删除失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 方向描述(表格首列):一眼看懂流量从哪到哪 */
|
||||
function directionText(f: ForwardView): string {
|
||||
return f.kind === 'local'
|
||||
? `本机:${f.bindPort} → ${f.targetHost}:${f.targetPort}(经服务器)`
|
||||
: `服务器:${f.bindPort} → ${f.targetHost}:${f.targetPort}(回本机)`
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog :open="open" @update:open="v => emit('update:open', v)">
|
||||
<DialogContent class="max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle class="flex items-center gap-2 text-base">
|
||||
<Network class="size-4" />端口转发
|
||||
</DialogTitle>
|
||||
<DialogDescription class="text-xs">
|
||||
会话「{{ sessionLabel }}」。规则在会话存活期间有效,断开后自动失效。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<!-- ===== 已有规则 ===== -->
|
||||
<div class="space-y-1.5 min-h-[60px]">
|
||||
<p v-if="loading" class="text-xs text-muted-foreground">加载中…</p>
|
||||
<p v-else-if="forwards.length === 0" class="text-xs text-muted-foreground">
|
||||
还没有转发规则。常见用法:本地转发本机 13306 → 服务器视角的 127.0.0.1:3306,
|
||||
即可在本机用数据库客户端直连服务器内网数据库。
|
||||
</p>
|
||||
<div
|
||||
v-for="f in forwards"
|
||||
:key="f.id"
|
||||
class="flex items-center gap-2 rounded border border-border px-2.5 py-1.5"
|
||||
>
|
||||
<span
|
||||
class="shrink-0 rounded px-1.5 py-0.5 text-[10px]"
|
||||
:class="f.kind === 'local' ? 'bg-primary/10 text-primary' : 'bg-blue-500/10 text-blue-500'"
|
||||
>
|
||||
{{ f.kind === 'local' ? '本地' : '远程' }}
|
||||
</span>
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="text-xs font-mono truncate">{{ directionText(f) }}</p>
|
||||
<p
|
||||
class="text-[10px] truncate"
|
||||
:class="f.status === 'error' ? 'text-destructive' : 'text-muted-foreground'"
|
||||
>
|
||||
{{ f.detail }}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-7 w-7 p-0 text-destructive hover:text-destructive shrink-0"
|
||||
title="删除此转发"
|
||||
@click="removeOne(f)"
|
||||
>
|
||||
<Trash2 class="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== 新增 ===== -->
|
||||
<div class="space-y-2 rounded-md border border-border p-3">
|
||||
<div class="flex items-center gap-2">
|
||||
<Label class="text-xs shrink-0">方向</Label>
|
||||
<Select v-model="formKind">
|
||||
<SelectTrigger class="h-8 text-xs flex-1">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="local">本地转发(-L):本机端口 → 经服务器到达目标</SelectItem>
|
||||
<SelectItem value="remote">远程转发(-R):服务器端口 → 回连本机目标</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-2">
|
||||
<div class="space-y-1">
|
||||
<Label class="text-[11px] text-muted-foreground">
|
||||
{{ formKind === 'local' ? '本机监听' : '服务器监听' }}(地址 : 端口)
|
||||
</Label>
|
||||
<div class="flex gap-1">
|
||||
<Input v-model="formBindHost" class="h-8 text-xs font-mono flex-1" />
|
||||
<Input v-model="formBindPort" placeholder="端口" class="h-8 text-xs font-mono w-[88px]" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="space-y-1">
|
||||
<Label class="text-[11px] text-muted-foreground">
|
||||
{{ formKind === 'local' ? '目标(服务器视角)' : '目标(回本机)' }}(地址 : 端口)
|
||||
</Label>
|
||||
<div class="flex gap-1">
|
||||
<Input v-model="formTargetHost" class="h-8 text-xs font-mono flex-1" />
|
||||
<Input v-model="formTargetPort" placeholder="端口" class="h-8 text-xs font-mono w-[88px]" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end">
|
||||
<Button size="sm" class="h-7 gap-1 text-xs" :disabled="busy" @click="submitAdd">
|
||||
<Plus class="size-3.5" />{{ busy ? '建立中…' : '建立转发' }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,443 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 命令历史面板(浮层)。
|
||||
*
|
||||
* # 交互模型:搜索即过滤、单击填入、双击执行
|
||||
*
|
||||
* 历史与片段不同:片段是「我准备好要用的」,历史是「我已经用过的」。
|
||||
* 后者的使用模式是**快速找回**,因此搜索框默认聚焦、输入即过滤、
|
||||
* 键盘上下键可直接选中。
|
||||
*
|
||||
* 单击 = 填入命令行(不执行),双击或 `Enter` = 填入并执行。
|
||||
* 这个区分的必要性在于:历史里躺着用户过去敲过的所有命令,包括
|
||||
* `rm -rf`、`DROP TABLE`。默认执行会让「翻历史」变成一件危险的事。
|
||||
*
|
||||
* # 为什么「只显示当前会话来源」不做默认
|
||||
*
|
||||
* 有人按主机筛选(「那台机器上我跑过什么」),也有人跨主机找同一条命令
|
||||
* (「上次那条 rsync 参数是怎么写的」)。默认全量 + 可选筛选比反向合理 ——
|
||||
* 前者只需点一下筛选,后者要清空筛选才能看到全部。
|
||||
*/
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import {
|
||||
ArrowDownToLine,
|
||||
Check,
|
||||
Clock,
|
||||
Copy,
|
||||
FolderOpen,
|
||||
History,
|
||||
Loader2,
|
||||
Play,
|
||||
Search,
|
||||
Star,
|
||||
Trash2,
|
||||
X
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { useTerminalStore } from '@/stores/terminalStore'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import type { CommandHistoryItem, SessionInfo } from '@/types/terminal'
|
||||
|
||||
const props = defineProps<{
|
||||
sessionId: string | null
|
||||
session: SessionInfo | undefined
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'close'): void
|
||||
}>()
|
||||
|
||||
const store = useTerminalStore()
|
||||
|
||||
// ===== 筛选状态 =====
|
||||
|
||||
const keyword = ref('')
|
||||
const hostFilter = ref('')
|
||||
const favoritedOnly = ref(false)
|
||||
/** 选中项(用于键盘导航与详情) */
|
||||
const selectedId = ref<number | null>(null)
|
||||
|
||||
const items = computed(() => store.historyPage.items)
|
||||
const total = computed(() => store.historyPage.total)
|
||||
|
||||
/** 当前会话的来源 id(用于「只看本会话」快捷筛选) */
|
||||
const currentHostId = computed(() => props.session?.targetId ?? '')
|
||||
|
||||
/**
|
||||
* 加载历史。
|
||||
*
|
||||
* `force` 为 false 时不重复请求(浮层首次打开才拉,其余靠筛选变化触发)——
|
||||
* 浮层每次开关都重拉会让「刚删掉的记录因为重拉又出现」这种错觉出现,
|
||||
* 而实际是删成功了、只是列表被刷新回旧快照(请求早于删除返回)。
|
||||
*/
|
||||
async function reload(force = false) {
|
||||
try {
|
||||
await store.loadHistory({
|
||||
keyword: keyword.value,
|
||||
hostId: hostFilter.value,
|
||||
favoritedOnly: favoritedOnly.value
|
||||
})
|
||||
if (force) await store.loadHistorySources()
|
||||
} catch (e) {
|
||||
toast.error(`加载历史失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await reload(true)
|
||||
})
|
||||
|
||||
// 筛选变化即重查。搜索框用 200ms 防抖:输入过程中每个字符都发请求
|
||||
// 会让 IPC 通道被无效查询占满(store 里已有请求序号防乱序,但少发总比多发好)。
|
||||
let searchTimer: ReturnType<typeof setTimeout> | null = null
|
||||
watch([keyword, favoritedOnly], () => {
|
||||
if (searchTimer) clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(() => void reload(), 200)
|
||||
})
|
||||
// 来源筛选是离散选择,无需防抖
|
||||
watch(hostFilter, () => void reload())
|
||||
|
||||
// 卸载时清掉未触发的防抖:面板关掉后定时器仍会发一次无主查询
|
||||
onBeforeUnmount(() => {
|
||||
if (searchTimer) clearTimeout(searchTimer)
|
||||
})
|
||||
|
||||
// ===== 操作 =====
|
||||
|
||||
/** 把命令填入会话命令行(不执行) */
|
||||
async function useCommand(item: CommandHistoryItem, submit = false) {
|
||||
if (!props.sessionId) {
|
||||
toast.info('当前没有活跃会话')
|
||||
return
|
||||
}
|
||||
try {
|
||||
const r = await store.runHistory(props.sessionId, item.command, submit)
|
||||
if (r.ok) {
|
||||
// 填入成功后关闭浮层:用户的下一步是看命令行并按回车,
|
||||
// 浮层挡在那里没有价值
|
||||
if (!submit) emit('close')
|
||||
else toast.success(r.message)
|
||||
} else {
|
||||
toast.error(r.message)
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(`操作失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function copyCommand(item: CommandHistoryItem) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(item.command)
|
||||
toast.success('已复制到剪贴板')
|
||||
} catch (e) {
|
||||
toast.error(`复制失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleFavorite(item: CommandHistoryItem) {
|
||||
try {
|
||||
await store.toggleHistoryFavorite(item.id)
|
||||
} catch (e) {
|
||||
toast.error(`操作失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function removeItem(item: CommandHistoryItem) {
|
||||
try {
|
||||
const r = await store.deleteHistory(item.id)
|
||||
if (!r.ok) toast.info(r.message)
|
||||
if (selectedId.value === item.id) selectedId.value = null
|
||||
} catch (e) {
|
||||
toast.error(`删除失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function clearAll() {
|
||||
// 二次确认,且默认只清非收藏 —— 破坏性操作的默认值应当是最保守的那个。
|
||||
// 用 window.confirm 而不是弹 Dialog:这是浮层里的浮层,
|
||||
// 嵌一个 Radix Dialog 会带来焦点陷阱与层级(z-index)的两难。
|
||||
const ok = window.confirm(
|
||||
'确定清空命令历史吗?\n\n收藏的记录会保留(如需连同收藏一起清空,请先取消收藏)。'
|
||||
)
|
||||
if (!ok) return
|
||||
try {
|
||||
const r = await store.clearHistory(true)
|
||||
toast.success(r.message)
|
||||
} catch (e) {
|
||||
toast.error(`清空失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 键盘导航 =====
|
||||
|
||||
/**
|
||||
* 上下键移动选中项,Enter 执行。
|
||||
*
|
||||
* 只在列表为空时不处理;其余一律 `preventDefault` —— 否则方向键会
|
||||
* 同时滚动容器,选中项移出可视区。
|
||||
*/
|
||||
function onKeydown(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') {
|
||||
emit('close')
|
||||
return
|
||||
}
|
||||
if (items.value.length === 0) return
|
||||
|
||||
const idx = items.value.findIndex(i => i.id === selectedId.value)
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault()
|
||||
const next = idx < 0 ? 0 : Math.min(items.value.length - 1, idx + 1)
|
||||
selectedId.value = items.value[next].id
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
e.preventDefault()
|
||||
const next = idx <= 0 ? 0 : idx - 1
|
||||
selectedId.value = items.value[next].id
|
||||
} else if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
const item = items.value.find(i => i.id === selectedId.value)
|
||||
if (item) void useCommand(item, false)
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 展示辅助 =====
|
||||
|
||||
/** 相对时间(历史列表里「3 分钟前」比精确时间戳更有信息量) */
|
||||
function relTime(ts: number): string {
|
||||
const diff = Date.now() - ts
|
||||
if (diff < 60_000) return '刚刚'
|
||||
if (diff < 3_600_000) return `${Math.floor(diff / 60_000)} 分钟前`
|
||||
if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)} 小时前`
|
||||
if (diff < 2_592_000_000) return `${Math.floor(diff / 86_400_000)} 天前`
|
||||
return new Date(ts).toLocaleDateString('zh-CN')
|
||||
}
|
||||
|
||||
/**
|
||||
* 目录缩略:只显示最后一级。
|
||||
*
|
||||
* 完整路径会占满一行且把命令挤到看不见的位置,而用户分辨「在哪个项目里跑的」
|
||||
* 只需要最后一级。完整路径放在 `title` 里悬停可看。
|
||||
*/
|
||||
function cwdTail(cwd: string): string {
|
||||
if (!cwd) return ''
|
||||
const parts = cwd.split(/[\\/]/).filter(Boolean)
|
||||
return parts.length > 0 ? parts[parts.length - 1] : cwd
|
||||
}
|
||||
|
||||
/** 退出码非 0 时给视觉提示(用户找的常常正是「刚才那条报错的命令」) */
|
||||
function isFailed(item: CommandHistoryItem): boolean {
|
||||
return item.exitCode !== null && item.exitCode !== 0
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- 作为模块 Tab 内容渲染(根不再是居中对话框) -->
|
||||
<div
|
||||
class="h-full flex flex-col rounded-lg border border-border bg-background overflow-hidden"
|
||||
@keydown="onKeydown"
|
||||
>
|
||||
<!-- ===== 头部:搜索 + 筛选 ===== -->
|
||||
<div class="shrink-0 border-b border-border">
|
||||
<div class="flex items-center gap-2 px-3 h-11">
|
||||
<History class="size-4 text-muted-foreground shrink-0" />
|
||||
<span class="text-sm font-medium shrink-0">命令历史</span>
|
||||
<span class="text-xs text-muted-foreground shrink-0">
|
||||
共 {{ total }} 条{{ hostFilter || favoritedOnly || keyword ? '(已筛选)' : '' }}
|
||||
</span>
|
||||
|
||||
<div class="flex-1" />
|
||||
|
||||
<div class="relative">
|
||||
<Search class="size-3.5 absolute left-2 top-1/2 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
v-model="keyword"
|
||||
placeholder="搜索命令…"
|
||||
class="h-7 w-[240px] pl-7 text-xs"
|
||||
autofocus
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-7 text-xs shrink-0"
|
||||
title="清空历史(保留收藏)"
|
||||
@click="clearAll"
|
||||
>
|
||||
<Trash2 class="size-3.5" />
|
||||
</Button>
|
||||
|
||||
<Button variant="ghost" size="sm" class="h-7 text-xs shrink-0" title="关闭" @click="emit('close')">
|
||||
<X class="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- 筛选行 -->
|
||||
<div class="flex items-center gap-2 px-3 pb-2 text-xs">
|
||||
<button
|
||||
class="h-6 px-2 rounded border transition-colors"
|
||||
:class="hostFilter === '' && !favoritedOnly
|
||||
? 'border-primary/50 bg-primary/10 text-foreground'
|
||||
: 'border-border text-muted-foreground hover:bg-accent'"
|
||||
@click="hostFilter = ''; favoritedOnly = false"
|
||||
>
|
||||
全部来源
|
||||
</button>
|
||||
<button
|
||||
v-if="currentHostId"
|
||||
class="h-6 px-2 rounded border transition-colors"
|
||||
:class="hostFilter === currentHostId
|
||||
? 'border-primary/50 bg-primary/10 text-foreground'
|
||||
: 'border-border text-muted-foreground hover:bg-accent'"
|
||||
:title="`只看本会话(${store.sessionLabel(session)})`"
|
||||
@click="hostFilter = currentHostId; favoritedOnly = false"
|
||||
>
|
||||
仅本会话
|
||||
</button>
|
||||
<button
|
||||
class="h-6 px-2 rounded border transition-colors inline-flex items-center gap-1"
|
||||
:class="favoritedOnly
|
||||
? 'border-primary/50 bg-primary/10 text-foreground'
|
||||
: 'border-border text-muted-foreground hover:bg-accent'"
|
||||
@click="favoritedOnly = !favoritedOnly"
|
||||
>
|
||||
<Star class="size-3" /> 收藏
|
||||
</button>
|
||||
|
||||
<!-- 其他来源(只列有历史的,避免显示一堆空来源) -->
|
||||
<div class="flex-1" />
|
||||
<select
|
||||
v-if="store.historySources.length > 1"
|
||||
:value="hostFilter"
|
||||
class="h-6 px-1 rounded border border-border bg-transparent text-xs max-w-[200px]"
|
||||
@change="hostFilter = ($event.target as HTMLSelectElement).value"
|
||||
>
|
||||
<option value="">按来源筛选…</option>
|
||||
<option v-for="s in store.historySources" :key="s.hostId" :value="s.hostId">
|
||||
{{ s.hostName }}({{ s.count }})
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== 列表 ===== -->
|
||||
<div class="flex-1 min-h-0 overflow-y-auto">
|
||||
<div v-if="store.historyLoading && items.length === 0" class="flex items-center justify-center h-full">
|
||||
<Loader2 class="size-5 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
|
||||
<div v-else-if="items.length === 0" class="flex flex-col items-center justify-center h-full gap-2 text-muted-foreground">
|
||||
<History class="size-8 opacity-40" />
|
||||
<span class="text-sm">
|
||||
{{ keyword || hostFilter || favoritedOnly ? '没有匹配的命令' : '还没有命令历史' }}
|
||||
</span>
|
||||
<span v-if="!(keyword || hostFilter || favoritedOnly)" class="text-xs opacity-70 max-w-[320px] text-center">
|
||||
命令由 shell 集成 hook 上报。新开的会话执行命令后即可在此查看。
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-else class="divide-y divide-border/60">
|
||||
<div
|
||||
v-for="item in items"
|
||||
:key="item.id"
|
||||
class="group flex items-start gap-2 px-3 py-2 cursor-pointer transition-colors"
|
||||
:class="selectedId === item.id ? 'bg-accent' : 'hover:bg-accent/50'"
|
||||
@click="selectedId = item.id"
|
||||
@dblclick="useCommand(item, false)"
|
||||
>
|
||||
<!-- 收藏 -->
|
||||
<button
|
||||
class="shrink-0 mt-0.5 size-4 flex items-center justify-center transition-colors"
|
||||
:class="item.favorited ? 'text-amber-500' : 'text-muted-foreground/40 hover:text-amber-500'"
|
||||
:title="item.favorited ? '取消收藏' : '收藏(不参与容量淘汰)'"
|
||||
@click.stop="toggleFavorite(item)"
|
||||
>
|
||||
<Star class="size-3.5" :fill="item.favorited ? 'currentColor' : 'none'" />
|
||||
</button>
|
||||
|
||||
<!-- 主体 -->
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-center gap-2">
|
||||
<code
|
||||
class="text-xs font-mono truncate"
|
||||
:class="isFailed(item) ? 'text-red-600 dark:text-red-400' : 'text-foreground'"
|
||||
:title="item.command"
|
||||
>
|
||||
{{ item.command }}
|
||||
</code>
|
||||
<!-- 执行次数:>1 说明是反复用到的命令,值得优先看 -->
|
||||
<span
|
||||
v-if="item.count > 1"
|
||||
class="shrink-0 text-[10px] px-1 rounded bg-muted text-muted-foreground"
|
||||
:title="`执行过 ${item.count} 次`"
|
||||
>
|
||||
×{{ item.count }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-3 mt-0.5 text-[10px] text-muted-foreground">
|
||||
<span class="inline-flex items-center gap-0.5 shrink-0">
|
||||
<Clock class="size-2.5" />{{ relTime(item.ts) }}
|
||||
</span>
|
||||
<span v-if="item.cwd" class="inline-flex items-center gap-0.5 min-w-0" :title="item.cwd">
|
||||
<FolderOpen class="size-2.5 shrink-0" />
|
||||
<span class="truncate max-w-[140px]">{{ cwdTail(item.cwd) }}</span>
|
||||
</span>
|
||||
<span class="truncate max-w-[180px]">{{ item.hostName }}</span>
|
||||
<span v-if="isFailed(item)" class="text-red-600 dark:text-red-400 shrink-0">
|
||||
退出码 {{ item.exitCode }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 行操作(悬停出现,避免列表视觉噪音) -->
|
||||
<div class="shrink-0 flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<button
|
||||
class="size-6 rounded flex items-center justify-center text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
title="填入命令行(不执行)"
|
||||
@click.stop="useCommand(item, false)"
|
||||
>
|
||||
<ArrowDownToLine class="size-3.5" />
|
||||
</button>
|
||||
<button
|
||||
class="size-6 rounded flex items-center justify-center text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
title="填入并执行"
|
||||
@click.stop="useCommand(item, true)"
|
||||
>
|
||||
<Play class="size-3.5" />
|
||||
</button>
|
||||
<button
|
||||
class="size-6 rounded flex items-center justify-center text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
title="复制"
|
||||
@click.stop="copyCommand(item)"
|
||||
>
|
||||
<Copy class="size-3.5" />
|
||||
</button>
|
||||
<button
|
||||
class="size-6 rounded flex items-center justify-center text-muted-foreground hover:bg-accent hover:text-red-600"
|
||||
title="删除这条"
|
||||
@click.stop="removeItem(item)"
|
||||
>
|
||||
<Trash2 class="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== 底部提示 ===== -->
|
||||
<div class="shrink-0 h-7 flex items-center gap-4 px-3 border-t border-border text-[10px] text-muted-foreground">
|
||||
<span class="inline-flex items-center gap-1">
|
||||
<ArrowDownToLine class="size-3" /> 单击 / Enter = 填入
|
||||
</span>
|
||||
<span class="inline-flex items-center gap-1">
|
||||
<Play class="size-3" /> 双击 = 填入并执行
|
||||
</span>
|
||||
<span class="inline-flex items-center gap-1">
|
||||
<Check class="size-3" /> 上/下键导航,Esc 关闭
|
||||
</span>
|
||||
<div class="flex-1" />
|
||||
<span v-if="total > items.length">显示 {{ items.length }} / {{ total }} 条</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,202 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* SSH 主机密钥确认对话框。
|
||||
*
|
||||
* # 这是模块里安全权重最高的 UI
|
||||
*
|
||||
* 它在 **MITM 攻击**的防线正中间:若用户被诱导接受了攻击者的主机密钥,
|
||||
* 之后所有流量(含密码、私钥操作)都会被中间人解开。因此这里做了三件事:
|
||||
*
|
||||
* 1. **首次连接与指纹变更走完全不同的视觉与文案**。前者是中性确认
|
||||
* (只提示「这是第一次连接」),后者是红色阻断(坚持要求用户去核对指纹)。
|
||||
* 若两者长得一样,用户会养成「无脑点确定」的习惯,防线形同虚设。
|
||||
*
|
||||
* 2. **把指纹放在最大字号、等宽字体、可选中**的位置。用户需要用
|
||||
* `ssh-keyscan | ssh-keygen -lf -` 在别处核对,所以必须能复制。
|
||||
*
|
||||
* 3. **不提供「记住并继续」以外的快捷操作**(如「本次接受」)。
|
||||
* 只有「接受并记录」与「取消」两个选项——模糊的中间选项会让用户
|
||||
* 在不理解后果的情况下点下去。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { Copy, Check, ShieldAlert, ShieldCheck } from '@lucide/vue'
|
||||
import { useTerminalStore } from '@/stores/terminalStore'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
|
||||
const logger = createLogger('terminal')
|
||||
const store = useTerminalStore()
|
||||
|
||||
const open = computed({
|
||||
get: () => store.hostKeyPrompt !== null,
|
||||
set: v => {
|
||||
if (!v) void store.confirmHostKey(false)
|
||||
}
|
||||
})
|
||||
|
||||
const prompt = computed(() => store.hostKeyPrompt)
|
||||
|
||||
/** 「与记录不符」= 高危,需要红色阻断式呈现 */
|
||||
const isChanged = computed(() => prompt.value?.reason === 'changed')
|
||||
|
||||
const copied = ref(false)
|
||||
/** 变更场景下强制用户勾选「我已核对」才允许继续 —— 防手滑 */
|
||||
const acknowledged = ref(false)
|
||||
|
||||
// 每次弹出新请求时重置勾选状态,避免上一次的勾选被继承(那会导致误接受)
|
||||
watch(
|
||||
() => prompt.value?.sessionId,
|
||||
() => {
|
||||
acknowledged.value = false
|
||||
copied.value = false
|
||||
}
|
||||
)
|
||||
|
||||
async function copyFingerprint() {
|
||||
const fp = prompt.value?.fingerprint
|
||||
if (!fp) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(fp)
|
||||
copied.value = true
|
||||
setTimeout(() => (copied.value = false), 1500)
|
||||
} catch (e) {
|
||||
logger.warn(`复制指纹失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
function accept() {
|
||||
void store.confirmHostKey(true)
|
||||
}
|
||||
|
||||
function reject() {
|
||||
void store.confirmHostKey(false)
|
||||
}
|
||||
|
||||
const canAccept = computed(() => !isChanged.value || acknowledged.value)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog v-model:open="open">
|
||||
<!-- 不显示右上角关闭按钮:这个决定必须通过底部的显式选择做出,
|
||||
点 X 走的是「关闭 = 拒绝」,但用户会以为只是收起对话框 -->
|
||||
<DialogContent class="max-w-lg" :show-close-button="false">
|
||||
<DialogHeader>
|
||||
<div class="flex items-center gap-2.5">
|
||||
<div
|
||||
class="size-9 rounded-full flex items-center justify-center shrink-0"
|
||||
:class="
|
||||
isChanged
|
||||
? 'bg-red-500/15 text-red-600 dark:text-red-400'
|
||||
: 'bg-primary/15 text-primary'
|
||||
"
|
||||
>
|
||||
<ShieldAlert v-if="isChanged" class="size-5" />
|
||||
<ShieldCheck v-else class="size-5" />
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<DialogTitle class="text-base">
|
||||
{{ isChanged ? '主机密钥已变更' : '首次连接此主机' }}
|
||||
</DialogTitle>
|
||||
<DialogDescription class="text-xs">
|
||||
{{ prompt?.host }}<span v-if="prompt && prompt.port !== 22">:{{ prompt.port }}</span>
|
||||
</DialogDescription>
|
||||
</div>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
<!-- 高危警告:指纹变更几乎只有两种可能 —— 服务器重装,或有人在中间 -->
|
||||
<div
|
||||
v-if="isChanged"
|
||||
class="rounded-md border border-red-500/40 bg-red-500/10 px-3 py-2.5 text-xs leading-relaxed text-red-700 dark:text-red-300"
|
||||
>
|
||||
<p class="font-medium mb-1">这可能意味着有人在窃听你的连接。</p>
|
||||
<p>
|
||||
服务器的主机密钥与之前记录的不一致。常见原因是服务器重装或更换了密钥;
|
||||
但也可能是中间人攻击。请通过其他可信渠道(如服务器管理后台)
|
||||
核对下方指纹后再决定。
|
||||
</p>
|
||||
</div>
|
||||
<div v-else class="rounded-md border border-border bg-muted/40 px-3 py-2.5 text-xs leading-relaxed text-muted-foreground">
|
||||
这是你第一次连接这台主机。接受后密钥指纹会被记录,之后若发生变化会再次警告。
|
||||
</div>
|
||||
|
||||
<!-- 指纹对比区 -->
|
||||
<div class="space-y-2">
|
||||
<div v-if="isChanged && prompt?.previousFingerprint">
|
||||
<div class="text-[10px] font-medium text-muted-foreground mb-1 uppercase tracking-wide">
|
||||
已记录的指纹
|
||||
</div>
|
||||
<div
|
||||
class="px-2.5 py-1.5 rounded bg-muted font-mono text-[11px] break-all line-through opacity-70"
|
||||
>
|
||||
{{ prompt.previousFingerprint }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div class="text-[10px] font-medium text-muted-foreground mb-1 uppercase tracking-wide">
|
||||
服务器出示的指纹({{ prompt?.keyType }})
|
||||
</div>
|
||||
<div class="flex items-start gap-2">
|
||||
<div
|
||||
class="flex-1 px-2.5 py-2 rounded font-mono text-[12px] break-all select-all leading-relaxed"
|
||||
:class="
|
||||
isChanged
|
||||
? 'bg-red-500/10 border border-red-500/30'
|
||||
: 'bg-muted border border-border'
|
||||
"
|
||||
>
|
||||
{{ prompt?.fingerprint }}
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
class="size-8 shrink-0"
|
||||
:title="copied ? '已复制' : '复制指纹'"
|
||||
@click="copyFingerprint"
|
||||
>
|
||||
<Check v-if="copied" class="size-3.5 text-emerald-500" />
|
||||
<Copy v-else class="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 变更场景的强制确认 -->
|
||||
<label
|
||||
v-if="isChanged"
|
||||
class="flex items-start gap-2 cursor-pointer select-none rounded-md px-1 py-1
|
||||
hover:bg-accent/40 transition-colors"
|
||||
>
|
||||
<input
|
||||
v-model="acknowledged"
|
||||
type="checkbox"
|
||||
class="mt-0.5 size-3.5 rounded border-border accent-red-500 cursor-pointer"
|
||||
/>
|
||||
<span class="text-xs leading-relaxed">
|
||||
我已在其他可信渠道核对了上述指纹,确认一致
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<DialogFooter class="gap-2">
|
||||
<Button variant="outline" size="sm" @click="reject">取消连接</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
:variant="isChanged ? 'destructive' : 'default'"
|
||||
:disabled="!canAccept"
|
||||
@click="accept"
|
||||
>
|
||||
{{ isChanged ? '仍然接受并更新记录' : '接受并记录' }}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,671 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* SSH 主机管理。
|
||||
*
|
||||
* # 两个刻意的取舍
|
||||
*
|
||||
* 1. **密码与配置分开保存**。配置走 `terminal_save_host`(落 settings.json),
|
||||
* 密码走 `terminal_set_host_password`(落系统凭据管理器)。看似麻烦,
|
||||
* 但这是唯一能保证「密码永不明文落盘」的路子——合并成一个保存动作时,
|
||||
* 前端必须把密码回传给后端,而那个 payload 会经过 IPC、可能进日志。
|
||||
*
|
||||
* 2. **新建时先向要一个 id**。密码按 hostId 存取,若等 save_host 之后再生成 id,
|
||||
* 用户在新建对话框里填的密码就没有归属。因此用 `terminal_new_host_id`
|
||||
* 预取 id,使「新建」与「编辑」走完全相同的流程。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { open as openDialog, save as saveDialog } from '@tauri-apps/plugin-dialog'
|
||||
import {
|
||||
ArrowDown,
|
||||
ArrowUp,
|
||||
Download,
|
||||
Eye,
|
||||
EyeOff,
|
||||
Globe,
|
||||
KeyRound,
|
||||
Loader2,
|
||||
Pencil,
|
||||
Plus,
|
||||
Star,
|
||||
Trash2,
|
||||
Upload
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { useTerminalStore } from '@/stores/terminalStore'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from '@/components/ui/dialog'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { blankHost, type SshHost } from './hostForm'
|
||||
import type { HostView } from '@/types/terminal'
|
||||
|
||||
const logger = createLogger('terminal')
|
||||
const store = useTerminalStore()
|
||||
|
||||
const emit = defineEmits<{ (e: 'close'): void; (e: 'connect', hostId: string): void }>()
|
||||
|
||||
// ===== 编辑对话框 =====
|
||||
|
||||
const dialogOpen = ref(false)
|
||||
const editing = ref<SshHost | null>(null)
|
||||
/** 编辑中的密码(空串 = 不修改;新建时为用户输入的初值) */
|
||||
const password = ref('')
|
||||
const showPassword = ref(false)
|
||||
const saving = ref(false)
|
||||
const isNew = ref(false)
|
||||
|
||||
/** 表单校验错误(按字段) */
|
||||
const errors = ref<Record<string, string>>({})
|
||||
|
||||
function validate(h: SshHost): boolean {
|
||||
const e: Record<string, string> = {}
|
||||
if (!h.name.trim()) e.name = '请填写显示名称'
|
||||
if (!h.host.trim()) e.host = '请填写主机地址'
|
||||
else if (/\s/.test(h.host.trim())) e.host = '主机地址不能包含空格'
|
||||
if (!h.username.trim()) e.username = '请填写登录用户名'
|
||||
if (h.port < 1 || h.port > 65535) e.port = '端口需在 1–65535 之间'
|
||||
if (h.authMethod === 'key' && !h.keyId) e.keyId = '请选择用于认证的密钥'
|
||||
// 跳板链:与后端 validate_jump_refs 的规则保持一致(不自引用、不成环)
|
||||
if (h.jumpIds.some(id => id === h.id)) e.jumpIds = '跳板链不能包含主机自身'
|
||||
else if (new Set(h.jumpIds).size !== h.jumpIds.length) e.jumpIds = '跳板链中有重复项'
|
||||
errors.value = e
|
||||
return Object.keys(e).length === 0
|
||||
}
|
||||
|
||||
async function openNew() {
|
||||
try {
|
||||
const id = await store.newHostId()
|
||||
editing.value = blankHost(id)
|
||||
isNew.value = true
|
||||
password.value = ''
|
||||
errors.value = {}
|
||||
dialogOpen.value = true
|
||||
} catch (e) {
|
||||
toast.error(`生成主机 ID 失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
function openEdit(hostId: string) {
|
||||
const v = store.hosts.find(h => h.config.id === hostId)
|
||||
if (!v) return
|
||||
// 深拷贝:取消时不能污染 store 中的原对象
|
||||
editing.value = JSON.parse(JSON.stringify(v.config)) as SshHost
|
||||
isNew.value = false
|
||||
// 已有密码时留空表示「不修改」,避免用户误以为要重新输入
|
||||
password.value = ''
|
||||
errors.value = {}
|
||||
dialogOpen.value = true
|
||||
}
|
||||
|
||||
/** 下拉选择密钥时,把 SSH 认证方式自动切到 key(用户选了密钥却还用密码认证是矛盾的) */
|
||||
watch(
|
||||
() => editing.value?.keyId,
|
||||
v => {
|
||||
if (v && editing.value && editing.value.authMethod !== 'key') {
|
||||
editing.value.authMethod = 'key'
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
async function save() {
|
||||
const h = editing.value
|
||||
if (!h || !validate(h)) return
|
||||
saving.value = true
|
||||
try {
|
||||
await store.saveHost(h)
|
||||
// 密码单独保存:仅当用户实际输入了内容
|
||||
if (password.value) {
|
||||
const r = await store.setHostPassword(h.id, password.value)
|
||||
if (!r.ok) {
|
||||
toast.warning(`主机已保存,但密码未能写入凭据管理器:${r.message}`)
|
||||
} else {
|
||||
toast.success(isNew.value ? '主机已添加' : '主机已更新')
|
||||
}
|
||||
} else {
|
||||
toast.success(isNew.value ? '主机已添加' : '主机已更新')
|
||||
}
|
||||
dialogOpen.value = false
|
||||
} catch (e) {
|
||||
logger.error(`保存主机失败:${String(e)}`)
|
||||
toast.error(`保存失败:${String(e)}`)
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(v: HostView) {
|
||||
const ok = await confirmRemove(v)
|
||||
if (!ok) return
|
||||
try {
|
||||
await store.deleteHost(v.config.id)
|
||||
toast.success(`已删除主机「${v.config.name || v.config.host}」`)
|
||||
} catch (e) {
|
||||
toast.error(`删除失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 删除确认(用简单的模态状态而非 window.confirm:后者在 WebView 里样式不可控) */
|
||||
const pendingRemove = ref<HostView | null>(null)
|
||||
function confirmRemove(v: HostView): Promise<boolean> {
|
||||
return new Promise(resolve => {
|
||||
pendingRemove.value = v
|
||||
removeResolve = resolve
|
||||
})
|
||||
}
|
||||
let removeResolve: ((ok: boolean) => void) | null = null
|
||||
function resolveRemove(ok: boolean) {
|
||||
removeResolve?.(ok)
|
||||
removeResolve = null
|
||||
pendingRemove.value = null
|
||||
}
|
||||
|
||||
async function importConfig() {
|
||||
try {
|
||||
const r = await store.importSshConfig()
|
||||
if (r.ok) toast.success(r.message)
|
||||
else toast.error(r.message)
|
||||
} catch (e) {
|
||||
toast.error(`导入失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出主机配置(JSON,不含密码与私钥)。
|
||||
*
|
||||
* 路径交给系统保存对话框(前端选路径、后端写内容——与其他文件
|
||||
* 写出操作的分工一致)。导出提示里明确说「密码不在备份内」,
|
||||
* 避免用户以为换机后不用重填凭据。
|
||||
*/
|
||||
async function exportHosts() {
|
||||
try {
|
||||
const stamp = new Date().toISOString().slice(0, 10)
|
||||
const path = await saveDialog({
|
||||
title: '导出主机配置',
|
||||
defaultPath: `terminal-hosts-${stamp}.json`,
|
||||
filters: [{ name: 'JSON', extensions: ['json'] }]
|
||||
})
|
||||
if (typeof path !== 'string') return
|
||||
const r = await store.exportHosts(path)
|
||||
if (r.ok) toast.success(r.message)
|
||||
else toast.warning(r.message)
|
||||
} catch (e) {
|
||||
toast.error(`导出失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 从 JSON 备份导入主机(自动重编 id、重写跳板链、去重) */
|
||||
async function importHosts() {
|
||||
try {
|
||||
const picked = await openDialog({
|
||||
multiple: false,
|
||||
directory: false,
|
||||
filters: [{ name: '主机备份', extensions: ['json'] }]
|
||||
})
|
||||
if (typeof picked !== 'string') return
|
||||
const r = await store.importHosts(picked)
|
||||
if (r.ok) toast.success(r.message)
|
||||
else toast.warning(r.message)
|
||||
} catch (e) {
|
||||
toast.error(`导入失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleFavorite(v: HostView) {
|
||||
try {
|
||||
await store.saveHost({ ...v.config, favorited: !v.config.favorited })
|
||||
} catch (e) {
|
||||
toast.error(`更新收藏状态失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 可用密钥(供认证方式下拉使用) */
|
||||
const availableKeys = computed(() => store.keys.filter(k => k.fileExists))
|
||||
|
||||
// ===== 跳板机链(ProxyJump)=====
|
||||
|
||||
/**
|
||||
* 跳板候选:除正在编辑的主机外的全部主机。
|
||||
*
|
||||
* 候选直接复用既有主机条目(地址+账号+凭据),而不是让用户在表单里
|
||||
* 重新抄一遍跳板机的地址密码 —— 后者会造成同一台跳板机多份凭据副本,
|
||||
* 改密码时漏改一处就是连接事故(与后端 `jump_ids` 的设计注释一致)。
|
||||
*/
|
||||
const hopCandidates = computed(() =>
|
||||
store.hosts.filter(v => v.config.id !== editing.value?.id)
|
||||
)
|
||||
|
||||
function hostLabel(id: string): string {
|
||||
const v = store.hosts.find(x => x.config.id === id)
|
||||
if (!v) return '(已删除的主机)'
|
||||
return `${v.config.name || v.config.host}(${v.config.username}@${v.config.host})`
|
||||
}
|
||||
|
||||
function addHop() {
|
||||
if (!editing.value) return
|
||||
// 默认选第一个还没被用掉的候选,省一次点击
|
||||
const used = new Set(editing.value.jumpIds)
|
||||
const next = hopCandidates.value.find(v => !used.has(v.config.id))
|
||||
if (!next) return
|
||||
editing.value.jumpIds.push(next.config.id)
|
||||
}
|
||||
|
||||
function removeHop(i: number) {
|
||||
editing.value?.jumpIds.splice(i, 1)
|
||||
}
|
||||
|
||||
/** 上移/下移:链的顺序就是连接顺序,靠前的先连 */
|
||||
function moveHop(i: number, dir: -1 | 1) {
|
||||
const arr = editing.value?.jumpIds
|
||||
if (!arr) return
|
||||
const j = i + dir
|
||||
if (j < 0 || j >= arr.length) return
|
||||
;[arr[i], arr[j]] = [arr[j], arr[i]]
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col h-full">
|
||||
<!-- 头部 -->
|
||||
<div class="shrink-0 flex items-center gap-2 px-4 h-12 border-b border-border">
|
||||
<Globe class="size-4 text-muted-foreground" />
|
||||
<h3 class="text-sm font-medium">SSH 主机</h3>
|
||||
<span class="text-xs text-muted-foreground">({{ store.hosts.length }})</span>
|
||||
<div class="flex-1" />
|
||||
<Button variant="outline" size="sm" class="h-7 gap-1.5 text-xs" @click="importHosts">
|
||||
<Upload class="size-3.5" />导入备份
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" class="h-7 gap-1.5 text-xs" @click="exportHosts">
|
||||
<Download class="size-3.5" />导出
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" class="h-7 gap-1.5 text-xs" @click="importConfig">
|
||||
<Download class="size-3.5" />导入 ~/.ssh/config
|
||||
</Button>
|
||||
<Button size="sm" class="h-7 gap-1.5 text-xs" @click="openNew">
|
||||
<Plus class="size-3.5" />新建主机
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- 列表 -->
|
||||
<div class="flex-1 min-h-0 overflow-y-auto p-3">
|
||||
<div v-if="store.hosts.length === 0" class="py-16 text-center">
|
||||
<Globe class="size-8 mx-auto text-muted-foreground/30 mb-3" />
|
||||
<p class="text-sm text-muted-foreground mb-1">还没有配置 SSH 主机</p>
|
||||
<p class="text-xs text-muted-foreground/70 mb-4">
|
||||
可以手工新建,也可以直接从 <code class="px-1 rounded bg-muted">~/.ssh/config</code> 导入
|
||||
</p>
|
||||
<div class="flex items-center justify-center gap-2">
|
||||
<Button size="sm" class="gap-1.5" @click="openNew">
|
||||
<Plus class="size-3.5" />新建主机
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" class="gap-1.5" @click="importConfig">
|
||||
<Download class="size-3.5" />导入配置
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-1">
|
||||
<div
|
||||
v-for="v in store.hosts"
|
||||
:key="v.config.id"
|
||||
class="group flex items-center gap-3 px-3 py-2 rounded-md border border-border
|
||||
hover:border-primary/40 hover:bg-accent/30 transition-colors"
|
||||
>
|
||||
<button
|
||||
class="shrink-0 size-6 rounded flex items-center justify-center transition-colors"
|
||||
:class="
|
||||
v.config.favorited
|
||||
? 'text-amber-500'
|
||||
: 'text-muted-foreground/30 hover:text-amber-500'
|
||||
"
|
||||
:title="v.config.favorited ? '取消收藏' : '收藏'"
|
||||
@click="toggleFavorite(v)"
|
||||
>
|
||||
<Star class="size-3.5" :class="{ 'fill-current': v.config.favorited }" />
|
||||
</button>
|
||||
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-sm font-medium truncate">
|
||||
{{ v.config.name || v.config.host }}
|
||||
</span>
|
||||
<span v-if="v.config.group" class="text-[10px] px-1.5 py-0.5 rounded bg-muted shrink-0">
|
||||
{{ v.config.group }}
|
||||
</span>
|
||||
<!-- 不可连接时给出明确原因,而不是让用户点下去才发现失败 -->
|
||||
<span
|
||||
v-if="!v.ready"
|
||||
class="text-[10px] px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-600 dark:text-amber-400 shrink-0"
|
||||
:title="v.issue ?? ''"
|
||||
>
|
||||
{{ v.issue || '配置不完整' }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="text-xs text-muted-foreground truncate mt-0.5">
|
||||
{{ v.config.username }}@{{ v.config.host
|
||||
}}<span v-if="v.config.port !== 22">:{{ v.config.port }}</span>
|
||||
<span class="mx-1.5">·</span>
|
||||
<span v-if="v.config.authMethod === 'key' && v.config.keyId">
|
||||
<KeyRound class="inline size-2.5 -mt-0.5" />
|
||||
{{ store.keys.find(k => k.meta.id === v.config.keyId)?.meta.name ?? '密钥' }}
|
||||
</span>
|
||||
<span v-else-if="v.config.authMethod === 'password'">
|
||||
<!-- 不回显掩码:密码不是 API key,保留前 3 后 4 也是在泄露真实内容;
|
||||
是否已保存由 hasPassword 表达,明文/掩码一律不出现在列表 -->
|
||||
{{ v.hasPassword ? '密码已保存' : '密码未保存' }}
|
||||
</span>
|
||||
<span v-else>{{ v.config.authMethod }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="shrink-0 flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<Button
|
||||
size="sm"
|
||||
class="h-7 text-xs"
|
||||
:disabled="!v.ready"
|
||||
:title="v.ready ? '连接' : (v.issue ?? '')"
|
||||
@click="emit('connect', v.config.id)"
|
||||
>
|
||||
连接
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" class="size-7" title="编辑" @click="openEdit(v.config.id)">
|
||||
<Pencil class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="size-7 text-destructive hover:text-destructive"
|
||||
title="删除"
|
||||
@click="remove(v)"
|
||||
>
|
||||
<Trash2 class="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== 编辑对话框 ===== -->
|
||||
<Dialog v-model:open="dialogOpen">
|
||||
<DialogContent class="max-w-xl max-h-[85vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{{ isNew ? '新建 SSH 主机' : '编辑 SSH 主机' }}</DialogTitle>
|
||||
<DialogDescription class="text-xs">
|
||||
密码保存在系统凭据管理器中,不会写入配置文件。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div v-if="editing" class="space-y-4">
|
||||
<!-- 基本信息 -->
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">显示名称</Label>
|
||||
<Input v-model="editing.name" placeholder="生产服务器" class="h-8 text-sm" />
|
||||
<p v-if="errors.name" class="text-[11px] text-destructive">{{ errors.name }}</p>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">分组</Label>
|
||||
<Input v-model="editing.group" placeholder="工作 / 个人(留空为未分组)" class="h-8 text-sm" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-[1fr_100px] gap-3">
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">主机地址</Label>
|
||||
<Input
|
||||
v-model="editing.host"
|
||||
placeholder="192.168.1.10 或 example.com"
|
||||
class="h-8 text-sm font-mono"
|
||||
/>
|
||||
<p v-if="errors.host" class="text-[11px] text-destructive">{{ errors.host }}</p>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">端口</Label>
|
||||
<Input v-model.number="editing.port" type="number" class="h-8 text-sm font-mono" />
|
||||
<p v-if="errors.port" class="text-[11px] text-destructive">{{ errors.port }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">登录用户名</Label>
|
||||
<Input v-model="editing.username" placeholder="root" class="h-8 text-sm font-mono" />
|
||||
<p v-if="errors.username" class="text-[11px] text-destructive">{{ errors.username }}</p>
|
||||
</div>
|
||||
|
||||
<!-- 认证 -->
|
||||
<div class="space-y-3 rounded-md border border-border p-3">
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">认证方式</Label>
|
||||
<Select v-model="editing.authMethod">
|
||||
<SelectTrigger class="h-8 text-sm">
|
||||
<SelectValue placeholder="选择认证方式" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="key">密钥认证(推荐)</SelectItem>
|
||||
<SelectItem value="password">密码认证</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div v-if="editing.authMethod === 'key'" class="space-y-1.5">
|
||||
<Label class="text-xs">使用密钥</Label>
|
||||
<Select v-model="editing.keyId">
|
||||
<SelectTrigger class="h-8 text-sm">
|
||||
<SelectValue placeholder="选择密钥" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="k in availableKeys" :key="k.meta.id" :value="k.meta.id">
|
||||
{{ k.meta.name }} · {{ k.meta.algorithm
|
||||
}}{{ k.meta.bits ? ` ${k.meta.bits}` : '' }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p v-if="errors.keyId" class="text-[11px] text-destructive">{{ errors.keyId }}</p>
|
||||
<p v-if="availableKeys.length === 0" class="text-[11px] text-amber-600 dark:text-amber-400">
|
||||
还没有可用密钥,请先到「密钥管理」生成或导入
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div v-if="editing.authMethod === 'password'" class="space-y-1.5">
|
||||
<Label class="text-xs">
|
||||
密码
|
||||
<span class="text-muted-foreground font-normal">(留空表示不修改)</span>
|
||||
</Label>
|
||||
<div class="relative">
|
||||
<Input
|
||||
v-model="password"
|
||||
:type="showPassword ? 'text' : 'password'"
|
||||
placeholder="写入系统凭据管理器"
|
||||
class="h-8 text-sm pr-8"
|
||||
/>
|
||||
<button
|
||||
class="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
type="button"
|
||||
@click="showPassword = !showPassword"
|
||||
>
|
||||
<Eye v-if="showPassword" class="size-3.5" />
|
||||
<EyeOff v-else class="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 高级 -->
|
||||
<details class="rounded-md border border-border">
|
||||
<summary class="px-3 py-2 text-xs cursor-pointer select-none hover:bg-accent/40">
|
||||
高级选项
|
||||
</summary>
|
||||
<div class="px-3 pb-3 pt-1 space-y-3">
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">连接超时(毫秒)</Label>
|
||||
<Input v-model.number="editing.connectTimeoutMs" type="number" class="h-8 text-sm" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">心跳间隔(秒,0 = 关闭)</Label>
|
||||
<Input v-model.number="editing.keepaliveSecs" type="number" class="h-8 text-sm" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">登录后执行(可选)</Label>
|
||||
<Input
|
||||
v-model="editing.startupCommand"
|
||||
placeholder="cd /var/log && ls -al"
|
||||
class="h-8 text-sm font-mono"
|
||||
/>
|
||||
<p class="text-[11px] text-muted-foreground">
|
||||
会在交互式 shell 建立后发送,适合固定进入某目录
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">远端工作目录(可选)</Label>
|
||||
<Input v-model="editing.remoteCwd" placeholder="/home/user" class="h-8 text-sm font-mono" />
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">远端编码</Label>
|
||||
<Select v-model="editing.encoding">
|
||||
<SelectTrigger class="h-8 text-sm">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="utf-8">UTF-8(默认)</SelectItem>
|
||||
<SelectItem value="gbk">GBK(部分老系统中文环境)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<!-- 跳板机链(ProxyJump):候选复用既有主机条目,凭据跟着条目走 -->
|
||||
<div class="space-y-1.5">
|
||||
<div class="flex items-center justify-between">
|
||||
<Label class="text-xs">跳板机链</Label>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-6 gap-1 px-1.5 text-[11px] text-muted-foreground hover:text-foreground"
|
||||
:disabled="hopCandidates.length === 0 || editing.jumpIds.length >= 5"
|
||||
@click="addHop"
|
||||
>
|
||||
<Plus class="size-3" />添加跳板
|
||||
</Button>
|
||||
</div>
|
||||
<p v-if="editing.jumpIds.length === 0" class="text-[11px] text-muted-foreground">
|
||||
不经过跳板,直连目标主机。需要经堡垒机/跳板机中转时从这里添加。
|
||||
</p>
|
||||
<div v-else class="space-y-1.5">
|
||||
<div
|
||||
v-for="(id, i) in editing.jumpIds"
|
||||
:key="i"
|
||||
class="flex items-center gap-1.5"
|
||||
>
|
||||
<span class="text-[11px] text-muted-foreground w-10 shrink-0">
|
||||
第{{ i + 1 }}跳
|
||||
</span>
|
||||
<Select v-model="editing.jumpIds[i]">
|
||||
<SelectTrigger class="h-8 text-xs flex-1">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem
|
||||
v-for="v in hopCandidates"
|
||||
:key="v.config.id"
|
||||
:value="v.config.id"
|
||||
>
|
||||
{{ v.config.name || v.config.host }}({{ v.config.username }}@{{ v.config.host }})
|
||||
</SelectItem>
|
||||
<!-- 当前值对应的主机可能已被删除,仍要能显示出来 -->
|
||||
<SelectItem v-if="!hopCandidates.some(v => v.config.id === id)" :value="id">
|
||||
{{ hostLabel(id) }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-7 w-7 p-0"
|
||||
:disabled="i === 0"
|
||||
@click="moveHop(i, -1)"
|
||||
>
|
||||
<ArrowUp class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-7 w-7 p-0"
|
||||
:disabled="i === editing.jumpIds.length - 1"
|
||||
@click="moveHop(i, 1)"
|
||||
>
|
||||
<ArrowDown class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-7 w-7 p-0 text-destructive hover:text-destructive"
|
||||
@click="removeHop(i)"
|
||||
>
|
||||
<Trash2 class="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
<p class="text-[11px] text-muted-foreground">
|
||||
连接方向:本机 → 第1跳 → … → 目标主机。每一跳使用对应主机条目里保存的账号与凭据。
|
||||
</p>
|
||||
</div>
|
||||
<p v-if="errors.jumpIds" class="text-[11px] text-destructive">{{ errors.jumpIds }}</p>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<Label class="text-xs">收藏</Label>
|
||||
<p class="text-[11px] text-muted-foreground">置顶显示在侧栏</p>
|
||||
</div>
|
||||
<Switch v-model="editing.favorited" />
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" size="sm" @click="dialogOpen = false">取消</Button>
|
||||
<Button size="sm" :disabled="saving" @click="save">
|
||||
<Loader2 v-if="saving" class="size-3.5 mr-1.5 animate-spin" />
|
||||
{{ isNew ? '添加' : '保存' }}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<!-- ===== 删除确认 ===== -->
|
||||
<Dialog :open="pendingRemove !== null" @update:open="v => !v && resolveRemove(false)">
|
||||
<DialogContent class="max-w-sm" :show-close-button="false">
|
||||
<DialogHeader>
|
||||
<DialogTitle class="text-base">删除主机</DialogTitle>
|
||||
<DialogDescription class="text-xs">
|
||||
将删除「{{ pendingRemove?.config.name || pendingRemove?.config.host }}」的配置
|
||||
与已保存的密码。此操作不可撤销。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" size="sm" @click="resolveRemove(false)">取消</Button>
|
||||
<Button variant="destructive" size="sm" @click="resolveRemove(true)">删除</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,774 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* SSH 密钥管理。
|
||||
*
|
||||
* # 三个刻意的取舍
|
||||
*
|
||||
* 1. **私钥内容永不回显**。列表里只有元数据(算法、位数、指纹、公钥),
|
||||
* 私钥只在后端密钥目录里。界面上没有任何「查看私钥」入口 —— 这不是疏漏,
|
||||
* 而是有意为之:一旦能把私钥显示到屏幕上,它就会进入截图、剪贴板、
|
||||
* 会话录制。需要私钥时用户应该去密钥目录,那是本机文件系统的事。
|
||||
*
|
||||
* 2. **passphrase 是「修改」而非「查看」**。改 passphrase 需要先验证旧值,
|
||||
* 这保证了「能改密码的人一定知道原密码」—— 若允许无验证直接改,
|
||||
* 任何能碰到这个界面的人都能夺走密钥的使用权。
|
||||
*
|
||||
* 3. **公钥一键复制**。这是本面板最高频的动作:用户生成密钥后要做的唯一
|
||||
* 一件事就是把它贴到服务器的 `authorized_keys`。为此在列表行上直接给
|
||||
* 复制按钮,而不是藏进详情页。
|
||||
*/
|
||||
import { computed, ref } from 'vue'
|
||||
import { open as openDialog } from '@tauri-apps/plugin-dialog'
|
||||
import {
|
||||
AlertTriangle,
|
||||
Check,
|
||||
ClipboardCopy,
|
||||
Download,
|
||||
FileKey,
|
||||
FolderOpen,
|
||||
KeyRound,
|
||||
Loader2,
|
||||
Lock,
|
||||
Pencil,
|
||||
Plus,
|
||||
ShieldCheck,
|
||||
Trash2,
|
||||
Unlock
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { useTerminalStore } from '@/stores/terminalStore'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from '@/components/ui/dialog'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import type { KeyGenParams, KeyView } from '@/types/terminal'
|
||||
|
||||
const logger = createLogger('terminal')
|
||||
const store = useTerminalStore()
|
||||
|
||||
// ===== 生成 =====
|
||||
|
||||
const genOpen = ref(false)
|
||||
const genBusy = ref(false)
|
||||
const genForm = ref<KeyGenParams>({
|
||||
name: '',
|
||||
algorithm: 'ed25519',
|
||||
bits: 0,
|
||||
comment: '',
|
||||
passphrase: ''
|
||||
})
|
||||
const genErrors = ref<Record<string, string>>({})
|
||||
|
||||
/** 各算法的可选位数(ed25519 定长,无位数概念) */
|
||||
const BIT_OPTIONS: Record<string, number[]> = {
|
||||
rsa: [2048, 3072, 4096],
|
||||
ecdsa: [256, 384, 521],
|
||||
ed25519: []
|
||||
}
|
||||
|
||||
const bitOptions = computed(() => BIT_OPTIONS[genForm.value.algorithm] ?? [])
|
||||
|
||||
/** 切换算法时把位数对齐到该算法的合法值,避免留下 RSA 4096 配 ed25519 这种无效组合 */
|
||||
function onAlgorithmChange(algo: string) {
|
||||
genForm.value.algorithm = algo
|
||||
const opts = BIT_OPTIONS[algo] ?? []
|
||||
genForm.value.bits = opts.length > 0 ? opts[0] : 0
|
||||
}
|
||||
|
||||
function openGenerate() {
|
||||
genForm.value = { name: '', algorithm: 'ed25519', bits: 0, comment: '', passphrase: '' }
|
||||
genErrors.value = {}
|
||||
genOpen.value = true
|
||||
}
|
||||
|
||||
async function submitGenerate() {
|
||||
const f = genForm.value
|
||||
const e: Record<string, string> = {}
|
||||
if (!f.name.trim()) e.name = '请填写密钥名称'
|
||||
if (f.algorithm === 'rsa' && ![2048, 3072, 4096].includes(f.bits)) {
|
||||
e.bits = 'RSA 位数需为 2048 / 3072 / 4096'
|
||||
}
|
||||
genErrors.value = e
|
||||
if (Object.keys(e).length > 0) return
|
||||
|
||||
genBusy.value = true
|
||||
try {
|
||||
const [view, outcome] = await store.generateKey({ ...f, name: f.name.trim() })
|
||||
if (outcome.ok) toast.success(outcome.message || `密钥「${view.meta.name}」已生成`)
|
||||
else toast.warning(outcome.message)
|
||||
genOpen.value = false
|
||||
} catch (err) {
|
||||
logger.error(`生成密钥失败:${String(err)}`)
|
||||
toast.error(`生成失败:${String(err)}`)
|
||||
} finally {
|
||||
genBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 导入 =====
|
||||
|
||||
const importOpen = ref(false)
|
||||
const importBusy = ref(false)
|
||||
const importName = ref('')
|
||||
const importContent = ref('')
|
||||
const importPassphrase = ref('')
|
||||
const importErrors = ref<Record<string, string>>({})
|
||||
|
||||
function openImport() {
|
||||
importName.value = ''
|
||||
importContent.value = ''
|
||||
importPassphrase.value = ''
|
||||
importErrors.value = {}
|
||||
importOpen.value = true
|
||||
}
|
||||
|
||||
/**
|
||||
* 从本地文件读取私钥内容。
|
||||
*
|
||||
* 读文件这件事交给**后端**:`terminal_import_key` 已支持直接接收文件路径
|
||||
* (`keys.rs::import` 里的路径分支),前端不碰文件系统。
|
||||
* 这样做既避开了 WebView 的本地文件读取限制,也保证「路径 → 内容」的
|
||||
* 编码判断只有一处实现(.ppk 与 PEM 都是纯文本,但第三方工具偶尔写出
|
||||
* 带 BOM 的文件,后端统一处理更稳)。
|
||||
*
|
||||
* 选完文件后只把**路径**写进内容框,由用户确认后再提交——
|
||||
* 不自动提交,因为导入是写操作,用户可能只是想看一眼选了哪个文件。
|
||||
*/
|
||||
async function pickKeyFile() {
|
||||
try {
|
||||
const picked = await openDialog({
|
||||
multiple: false,
|
||||
directory: false,
|
||||
filters: [
|
||||
{ name: 'SSH 私钥', extensions: ['ppk', 'key', 'pem', 'openssh', 'priv', 'rsa', 'ed25519'] },
|
||||
{ name: '全部文件', extensions: ['*'] }
|
||||
]
|
||||
})
|
||||
if (typeof picked !== 'string') return
|
||||
|
||||
importContent.value = picked
|
||||
// 文件名兜底填名称,省得用户手打(用户多半会改成更易记的名字)
|
||||
if (!importName.value.trim()) {
|
||||
importName.value = picked.replace(/\\/g, '/').split('/').pop()?.replace(/\.[^.]+$/, '') ?? ''
|
||||
}
|
||||
importErrors.value = {}
|
||||
} catch (err) {
|
||||
logger.error(`选择密钥文件失败:${String(err)}`)
|
||||
toast.error(`选择文件失败:${String(err)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function submitImport() {
|
||||
const e: Record<string, string> = {}
|
||||
if (!importName.value.trim()) e.name = '请填写密钥名称'
|
||||
|
||||
const text = importContent.value
|
||||
if (!text.trim()) e.content = '请粘贴私钥内容'
|
||||
// 与服务端 `terminal/keys.rs::is_ppk` 的判定保持一致:PPK 头部必须在首行。
|
||||
// 前端只做「是不是明显不对」的拦截,真正的解析一律交给后端——
|
||||
// 前端做格式解析迟早会与后端分叉(见 SnippetPanel 里同样的取舍)。
|
||||
else if (!text.includes('PRIVATE KEY') && !/^\s*PuTTY-User-Key-File-\d+:/m.test(text)) {
|
||||
e.content = '内容看起来不是私钥(需为 OpenSSH 私钥或 PuTTY .ppk)'
|
||||
}
|
||||
importErrors.value = e
|
||||
if (Object.keys(e).length > 0) return
|
||||
|
||||
importBusy.value = true
|
||||
try {
|
||||
const [view, outcome] = await store.importKey(
|
||||
importName.value.trim(),
|
||||
importContent.value,
|
||||
importPassphrase.value
|
||||
)
|
||||
if (outcome.ok) toast.success(outcome.message || `密钥「${view.meta.name}」已导入`)
|
||||
else toast.warning(outcome.message)
|
||||
importOpen.value = false
|
||||
} catch (err) {
|
||||
logger.error(`导入密钥失败:${String(err)}`)
|
||||
toast.error(`导入失败:${String(err)}`)
|
||||
} finally {
|
||||
importBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 复制公钥 =====
|
||||
|
||||
/** 刚复制过的密钥 id(用于按钮短暂显示对勾,给出「确实复制了」的确认) */
|
||||
const copiedId = ref<string | null>(null)
|
||||
let copiedTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
async function copyPublic(k: KeyView) {
|
||||
try {
|
||||
// 重新向后端取一次,而不是用列表里的 meta.publicKey:
|
||||
// 列表数据可能是几分钟前拉的,而用户此刻要的一定是当前真实内容
|
||||
const text = await store.keyPublic(k.meta.id)
|
||||
await navigator.clipboard.writeText(text)
|
||||
copiedId.value = k.meta.id
|
||||
if (copiedTimer) clearTimeout(copiedTimer)
|
||||
copiedTimer = setTimeout(() => (copiedId.value = null), 1800)
|
||||
toast.success('公钥已复制')
|
||||
} catch (e) {
|
||||
toast.error(`复制失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制为 `authorized_keys` 可用的形式。
|
||||
*
|
||||
* 与「复制公钥」的区别:服务器上的 `authorized_keys` 每行只能有一个密钥,
|
||||
* 且行尾必须是注释。如果用户从详情里复制到的是带换行的完整文本,
|
||||
* 粘到服务器上会变成多行、破坏文件。这里压成单行并补上注释。
|
||||
*/
|
||||
async function copyForAuthorizedKeys(k: KeyView) {
|
||||
try {
|
||||
const text = await store.keyPublic(k.meta.id)
|
||||
const parts = text.trim().split(/\s+/)
|
||||
const body = parts.slice(0, 2).join(' ')
|
||||
const comment = parts.slice(2).join(' ') || k.meta.name
|
||||
const line = `${body} ${comment}`
|
||||
await navigator.clipboard.writeText(line)
|
||||
toast.success('已复制为单行 authorized_keys 格式')
|
||||
} catch (e) {
|
||||
toast.error(`复制失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 重命名 =====
|
||||
|
||||
const renameTarget = ref<KeyView | null>(null)
|
||||
const renameValue = ref('')
|
||||
const renameBusy = ref(false)
|
||||
|
||||
function openRename(k: KeyView) {
|
||||
renameTarget.value = k
|
||||
renameValue.value = k.meta.name
|
||||
}
|
||||
|
||||
async function submitRename() {
|
||||
const k = renameTarget.value
|
||||
const name = renameValue.value.trim()
|
||||
if (!k) return
|
||||
if (!name) {
|
||||
toast.error('名称不能为空')
|
||||
return
|
||||
}
|
||||
renameBusy.value = true
|
||||
try {
|
||||
await store.renameKey(k.meta.id, name)
|
||||
toast.success('已重命名')
|
||||
renameTarget.value = null
|
||||
} catch (e) {
|
||||
toast.error(`重命名失败:${String(e)}`)
|
||||
} finally {
|
||||
renameBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ===== passphrase =====
|
||||
|
||||
const passTarget = ref<KeyView | null>(null)
|
||||
const oldPass = ref('')
|
||||
const newPass = ref('')
|
||||
const confirmPass = ref('')
|
||||
const passBusy = ref(false)
|
||||
const passError = ref('')
|
||||
|
||||
function openPassphrase(k: KeyView) {
|
||||
passTarget.value = k
|
||||
oldPass.value = ''
|
||||
newPass.value = ''
|
||||
confirmPass.value = ''
|
||||
passError.value = ''
|
||||
}
|
||||
|
||||
async function submitPassphrase() {
|
||||
const k = passTarget.value
|
||||
if (!k) return
|
||||
passError.value = ''
|
||||
|
||||
if (newPass.value !== confirmPass.value) {
|
||||
passError.value = '两次输入的新 passphrase 不一致'
|
||||
return
|
||||
}
|
||||
if (k.hasPassphrase && !oldPass.value) {
|
||||
passError.value = '该密钥已有 passphrase,需填写当前值以验证身份'
|
||||
return
|
||||
}
|
||||
if (!k.hasPassphrase && !newPass.value) {
|
||||
passError.value = '请填写要设置的 passphrase'
|
||||
return
|
||||
}
|
||||
// 空串是合法输入(表示移除 passphrase),所以这里不能靠空串判断「无操作」,
|
||||
// 改为显式比较:只有用户确实改动了才提交
|
||||
if (k.hasPassphrase && newPass.value === oldPass.value && newPass.value !== '') {
|
||||
passError.value = '新 passphrase 与当前值相同,无需修改'
|
||||
return
|
||||
}
|
||||
|
||||
passBusy.value = true
|
||||
try {
|
||||
const r = await store.setKeyPassphrase(k.meta.id, oldPass.value, newPass.value)
|
||||
if (r.ok) {
|
||||
toast.success(r.message || (newPass.value ? 'passphrase 已更新' : 'passphrase 已移除'))
|
||||
passTarget.value = null
|
||||
} else {
|
||||
passError.value = r.message
|
||||
}
|
||||
} catch (e) {
|
||||
const msg = String(e)
|
||||
logger.error(`修改 passphrase 失败:${msg}`)
|
||||
// 「解密失败」等价于旧密码错 —— 翻译成用户能理解的说法
|
||||
passError.value = /passphrase|解密|decrypt/i.test(msg) ? '当前 passphrase 不正确' : msg
|
||||
} finally {
|
||||
passBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 删除 =====
|
||||
|
||||
const pendingDelete = ref<KeyView | null>(null)
|
||||
const deleteBusy = ref(false)
|
||||
|
||||
/** 受该密钥影响的主机(删除前必须让用户看到代价) */
|
||||
const affectedHosts = computed(() => {
|
||||
const k = pendingDelete.value
|
||||
if (!k) return []
|
||||
return store.hosts.filter(h => h.config.keyId === k.meta.id)
|
||||
})
|
||||
|
||||
async function submitDelete() {
|
||||
const k = pendingDelete.value
|
||||
if (!k) return
|
||||
deleteBusy.value = true
|
||||
try {
|
||||
await store.deleteKey(k.meta.id)
|
||||
toast.success(`密钥「${k.meta.name}」已删除`)
|
||||
pendingDelete.value = null
|
||||
} catch (e) {
|
||||
toast.error(`删除失败:${String(e)}`)
|
||||
} finally {
|
||||
deleteBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 展示辅助 =====
|
||||
|
||||
function algorithmLabel(a: string): string {
|
||||
switch (a) {
|
||||
case 'ed25519':
|
||||
return 'Ed25519'
|
||||
case 'rsa':
|
||||
return 'RSA'
|
||||
case 'ecdsa':
|
||||
return 'ECDSA'
|
||||
case 'dsa':
|
||||
return 'DSA'
|
||||
default:
|
||||
return a || '未知'
|
||||
}
|
||||
}
|
||||
|
||||
function formatDate(rfc3339: string): string {
|
||||
if (!rfc3339) return '—'
|
||||
const d = new Date(rfc3339)
|
||||
if (Number.isNaN(d.getTime())) return rfc3339
|
||||
return d.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' })
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col h-full">
|
||||
<!-- 头部 -->
|
||||
<div class="shrink-0 flex items-center gap-2 px-4 h-12 border-b border-border">
|
||||
<KeyRound class="size-4 text-muted-foreground" />
|
||||
<h3 class="text-sm font-medium">SSH 密钥</h3>
|
||||
<span class="text-xs text-muted-foreground">({{ store.keys.length }})</span>
|
||||
<div class="flex-1" />
|
||||
<Button variant="outline" size="sm" class="h-7 gap-1.5 text-xs" @click="openImport">
|
||||
<Download class="size-3.5" />导入密钥
|
||||
</Button>
|
||||
<Button size="sm" class="h-7 gap-1.5 text-xs" @click="openGenerate">
|
||||
<Plus class="size-3.5" />生成密钥
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- 列表 -->
|
||||
<div class="flex-1 min-h-0 overflow-y-auto p-3">
|
||||
<div v-if="store.keys.length === 0" class="py-16 text-center">
|
||||
<FileKey class="size-8 mx-auto text-muted-foreground/30 mb-3" />
|
||||
<p class="text-sm text-muted-foreground mb-1">还没有 SSH 密钥</p>
|
||||
<p class="text-xs text-muted-foreground/70 mb-4">
|
||||
推荐生成 Ed25519 —— 更短、更快、安全性优于同强度的 RSA
|
||||
</p>
|
||||
<div class="flex items-center justify-center gap-2">
|
||||
<Button size="sm" class="gap-1.5" @click="openGenerate">
|
||||
<Plus class="size-3.5" />生成密钥
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" class="gap-1.5" @click="openImport">
|
||||
<Download class="size-3.5" />导入已有密钥
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-1.5">
|
||||
<div
|
||||
v-for="k in store.keys"
|
||||
:key="k.meta.id"
|
||||
class="group rounded-md border border-border px-3 py-2.5
|
||||
hover:border-primary/40 hover:bg-accent/30 transition-colors"
|
||||
>
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="shrink-0 mt-0.5">
|
||||
<Lock v-if="k.hasPassphrase" class="size-4 text-emerald-600 dark:text-emerald-400" />
|
||||
<Unlock v-else class="size-4 text-muted-foreground/50" />
|
||||
</div>
|
||||
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<span class="text-sm font-medium truncate">{{ k.meta.name }}</span>
|
||||
<span class="text-[10px] px-1.5 py-0.5 rounded bg-muted font-mono shrink-0">
|
||||
{{ algorithmLabel(k.meta.algorithm) }}{{ k.meta.bits ? ` ${k.meta.bits}` : '' }}
|
||||
</span>
|
||||
<span
|
||||
v-if="k.hasPassphrase"
|
||||
class="text-[10px] px-1.5 py-0.5 rounded bg-emerald-500/15 text-emerald-700 dark:text-emerald-400 shrink-0"
|
||||
>
|
||||
已加密
|
||||
</span>
|
||||
<!-- 私钥文件丢失时明确告警:主机配置还指向它,但已经连不上了 -->
|
||||
<span
|
||||
v-if="!k.fileExists"
|
||||
class="text-[10px] px-1.5 py-0.5 rounded bg-destructive/15 text-destructive inline-flex items-center gap-0.5 shrink-0"
|
||||
>
|
||||
<AlertTriangle class="size-2.5" />私钥文件缺失
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="mt-1 text-xs text-muted-foreground">
|
||||
<span class="font-mono truncate block" :title="k.meta.fingerprint">
|
||||
{{ k.meta.fingerprint }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="mt-1 flex items-center gap-3 text-[11px] text-muted-foreground/80">
|
||||
<span v-if="k.meta.comment" class="truncate">{{ k.meta.comment }}</span>
|
||||
<span>创建于 {{ formatDate(k.meta.createdAt) }}</span>
|
||||
<span v-if="k.meta.fileName" class="font-mono truncate">{{ k.meta.fileName }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="shrink-0 flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="size-7"
|
||||
:title="copiedId === k.meta.id ? '已复制' : '复制公钥'"
|
||||
@click="copyPublic(k)"
|
||||
>
|
||||
<Check v-if="copiedId === k.meta.id" class="size-3.5 text-emerald-600" />
|
||||
<ClipboardCopy v-else class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="size-7 opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
title="复制为 authorized_keys 单行格式"
|
||||
@click="copyForAuthorizedKeys(k)"
|
||||
>
|
||||
<ShieldCheck class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="size-7 opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
title="修改 passphrase"
|
||||
@click="openPassphrase(k)"
|
||||
>
|
||||
<Lock class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="size-7 opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
title="重命名"
|
||||
@click="openRename(k)"
|
||||
>
|
||||
<Pencil class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="size-7 opacity-0 group-hover:opacity-100 transition-opacity
|
||||
text-destructive hover:text-destructive"
|
||||
title="删除"
|
||||
@click="pendingDelete = k"
|
||||
>
|
||||
<Trash2 class="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== 生成 ===== -->
|
||||
<Dialog v-model:open="genOpen">
|
||||
<DialogContent class="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>生成 SSH 密钥</DialogTitle>
|
||||
<DialogDescription class="text-xs">
|
||||
私钥保存在本机密钥目录,公钥可直接复制到服务器的 authorized_keys。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div class="space-y-3">
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">名称</Label>
|
||||
<Input v-model="genForm.name" placeholder="例如:生产服务器" class="h-8 text-sm" />
|
||||
<p v-if="genErrors.name" class="text-[11px] text-destructive">{{ genErrors.name }}</p>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">算法</Label>
|
||||
<Select
|
||||
:model-value="genForm.algorithm"
|
||||
@update:model-value="(v: any) => onAlgorithmChange(String(v))"
|
||||
>
|
||||
<SelectTrigger class="h-8 text-sm">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="ed25519">Ed25519(推荐)</SelectItem>
|
||||
<SelectItem value="rsa">RSA</SelectItem>
|
||||
<SelectItem value="ecdsa">ECDSA</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">位数</Label>
|
||||
<!-- ed25519 是定长算法:禁用而非隐藏,让用户看到「这里确实没有可选项」 -->
|
||||
<Select :model-value="String(genForm.bits)" :disabled="bitOptions.length === 0">
|
||||
<SelectTrigger class="h-8 text-sm">
|
||||
<SelectValue :placeholder="bitOptions.length === 0 ? '定长' : '选择位数'" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="b in bitOptions" :key="b" :value="String(b)">{{ b }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p v-if="genErrors.bits" class="text-[11px] text-destructive">{{ genErrors.bits }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">注释(可选)</Label>
|
||||
<Input
|
||||
v-model="genForm.comment"
|
||||
placeholder="user@host(会作为公钥行尾注释)"
|
||||
class="h-8 text-sm font-mono"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">
|
||||
Passphrase
|
||||
<span class="text-muted-foreground font-normal">(可选,推荐设置)</span>
|
||||
</Label>
|
||||
<Input v-model="genForm.passphrase" type="password" placeholder="留空表示不加密" class="h-8 text-sm" />
|
||||
<p class="text-[11px] text-muted-foreground">
|
||||
设置后每次使用密钥都需输入;请自行妥善保管,遗失无法找回。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" size="sm" @click="genOpen = false">取消</Button>
|
||||
<Button size="sm" :disabled="genBusy" @click="submitGenerate">
|
||||
<Loader2 v-if="genBusy" class="size-3.5 mr-1.5 animate-spin" />
|
||||
生成
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<!-- ===== 导入 ===== -->
|
||||
<Dialog v-model:open="importOpen">
|
||||
<DialogContent class="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>导入 SSH 私钥</DialogTitle>
|
||||
<DialogDescription class="text-xs">
|
||||
支持 OpenSSH 私钥与 PuTTY <span class="font-mono">.ppk</span>(v2 / v3,含加密)。
|
||||
导入后统一转存为 OpenSSH 格式,可直接被 ssh / git 引用。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div class="space-y-3">
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">名称</Label>
|
||||
<Input v-model="importName" placeholder="例如:GitHub" class="h-8 text-sm" />
|
||||
<p v-if="importErrors.name" class="text-[11px] text-destructive">{{ importErrors.name }}</p>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<div class="flex items-center justify-between">
|
||||
<Label class="text-xs">私钥内容</Label>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-6 gap-1 px-1.5 text-[11px] text-muted-foreground hover:text-foreground"
|
||||
@click="pickKeyFile"
|
||||
>
|
||||
<FolderOpen class="size-3" />选择文件
|
||||
</Button>
|
||||
</div>
|
||||
<Textarea
|
||||
v-model="importContent"
|
||||
placeholder="-----BEGIN OPENSSH PRIVATE KEY----- … 或 PuTTY-User-Key-File-3: ssh-ed25519 … 也可直接粘贴文件路径"
|
||||
class="font-mono text-xs min-h-[140px] resize-y"
|
||||
/>
|
||||
<p v-if="importErrors.content" class="text-[11px] text-destructive">
|
||||
{{ importErrors.content }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">
|
||||
原 Passphrase
|
||||
<span class="text-muted-foreground font-normal">(若该密钥已加密则必填)</span>
|
||||
</Label>
|
||||
<Input v-model="importPassphrase" type="password" class="h-8 text-sm" />
|
||||
<p class="text-[11px] text-muted-foreground">
|
||||
密钥将以相同的 passphrase 重新加密后保存。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" size="sm" @click="importOpen = false">取消</Button>
|
||||
<Button size="sm" :disabled="importBusy" @click="submitImport">
|
||||
<Loader2 v-if="importBusy" class="size-3.5 mr-1.5 animate-spin" />
|
||||
导入
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<!-- ===== 重命名 ===== -->
|
||||
<Dialog :open="renameTarget !== null" @update:open="v => !v && (renameTarget = null)">
|
||||
<DialogContent class="max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle class="text-base">重命名密钥</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Input v-model="renameValue" class="h-8 text-sm" @keydown.enter="submitRename" />
|
||||
<DialogFooter>
|
||||
<Button variant="outline" size="sm" @click="renameTarget = null">取消</Button>
|
||||
<Button size="sm" :disabled="renameBusy" @click="submitRename">保存</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<!-- ===== passphrase ===== -->
|
||||
<Dialog :open="passTarget !== null" @update:open="v => !v && (passTarget = null)">
|
||||
<DialogContent class="max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle class="text-base">修改 Passphrase</DialogTitle>
|
||||
<DialogDescription class="text-xs">
|
||||
{{ passTarget?.meta.name }}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div class="space-y-3">
|
||||
<div v-if="passTarget?.hasPassphrase" class="space-y-1.5">
|
||||
<Label class="text-xs">当前 Passphrase</Label>
|
||||
<Input v-model="oldPass" type="password" class="h-8 text-sm" />
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">
|
||||
新 Passphrase
|
||||
<span class="text-muted-foreground font-normal">(留空表示移除加密)</span>
|
||||
</Label>
|
||||
<Input v-model="newPass" type="password" class="h-8 text-sm" />
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">确认新 Passphrase</Label>
|
||||
<Input v-model="confirmPass" type="password" class="h-8 text-sm" />
|
||||
</div>
|
||||
|
||||
<p v-if="passError" class="text-[11px] text-destructive">{{ passError }}</p>
|
||||
|
||||
<!-- 移除加密是有实际风险的操作,给一次明确提示 -->
|
||||
<div
|
||||
v-if="passTarget?.hasPassphrase && !newPass"
|
||||
class="flex items-start gap-2 p-2 rounded bg-amber-500/10 text-[11px] text-amber-700 dark:text-amber-400"
|
||||
>
|
||||
<AlertTriangle class="size-3.5 shrink-0 mt-0.5" />
|
||||
<span>新 passphrase 留空将移除加密,此后该私钥以明文形式存放在磁盘上。</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" size="sm" @click="passTarget = null">取消</Button>
|
||||
<Button size="sm" :disabled="passBusy" @click="submitPassphrase">
|
||||
<Loader2 v-if="passBusy" class="size-3.5 mr-1.5 animate-spin" />
|
||||
确认
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<!-- ===== 删除确认 ===== -->
|
||||
<Dialog :open="pendingDelete !== null" @update:open="v => !v && (pendingDelete = null)">
|
||||
<DialogContent class="max-w-sm" :show-close-button="false">
|
||||
<DialogHeader>
|
||||
<DialogTitle class="text-base">删除密钥</DialogTitle>
|
||||
<DialogDescription class="text-xs">
|
||||
将删除「{{ pendingDelete?.meta.name }}」的私钥与公钥文件。此操作不可撤销。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<!-- 让用户看到代价:哪些主机配置正在用这个密钥 -->
|
||||
<div
|
||||
v-if="affectedHosts.length > 0"
|
||||
class="rounded-md border border-destructive/40 bg-destructive/5 p-2.5 space-y-1"
|
||||
>
|
||||
<p class="text-[11px] font-medium text-destructive flex items-center gap-1">
|
||||
<AlertTriangle class="size-3" />
|
||||
有 {{ affectedHosts.length }} 台主机正在使用该密钥
|
||||
</p>
|
||||
<ul class="text-[11px] text-muted-foreground space-y-0.5 pl-4">
|
||||
<li v-for="h in affectedHosts" :key="h.config.id" class="truncate">
|
||||
{{ h.config.name || h.config.host }}
|
||||
</li>
|
||||
</ul>
|
||||
<p class="text-[11px] text-muted-foreground">删除后这些主机将无法通过密钥方式连接。</p>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" size="sm" @click="pendingDelete = null">取消</Button>
|
||||
<Button variant="destructive" size="sm" :disabled="deleteBusy" @click="submitDelete">
|
||||
删除
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,453 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* known_hosts 管理。
|
||||
*
|
||||
* # 设计立场
|
||||
*
|
||||
* 这个面板的存在理由只有一个:**让「忘记某台主机」这件事变得容易**。
|
||||
*
|
||||
* 主机密钥校验是 SSH 抵御中间人的核心机制,但它的最大敌人不是攻击者,
|
||||
* 而是用户自己被卡住时的挫败感 ——「指纹变了,连不上,怎么办?」。
|
||||
* 如果这时唯一的出路是去翻文档、找 known_hosts 文件、手工删行,
|
||||
* 用户就会转向「关闭校验」这种彻底破坏安全性的做法。
|
||||
*
|
||||
* 所以这里提供两条路:
|
||||
* - 单条遗忘(服务器重装后重新握手)——正常流程。
|
||||
* - 全部清空(最后手段,带明确警告)。
|
||||
*
|
||||
* # 指纹变更历史为什么单独展示
|
||||
*
|
||||
* 一条**已接受**的变更(服务器重装、管理员换密钥)和一条**刚发生**的变更,
|
||||
* 对用户的意义完全不同。只显示「最新指纹」会丢掉这个上下文,
|
||||
* 让用户误以为「这台机器一直没问题」——而实际上它已经换过密钥。
|
||||
*/
|
||||
import { computed, ref } from 'vue'
|
||||
import {
|
||||
AlertTriangle,
|
||||
Check,
|
||||
ClipboardPaste,
|
||||
Download,
|
||||
History,
|
||||
Loader2,
|
||||
Server,
|
||||
ShieldCheck,
|
||||
Trash2
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { useTerminalStore } from '@/stores/terminalStore'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from '@/components/ui/dialog'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import type { KnownHost } from '@/types/terminal'
|
||||
|
||||
const logger = createLogger('terminal')
|
||||
const store = useTerminalStore()
|
||||
|
||||
const search = ref('')
|
||||
|
||||
const filtered = computed(() => {
|
||||
const q = search.value.trim().toLowerCase()
|
||||
if (!q) return store.knownHosts
|
||||
return store.knownHosts.filter(
|
||||
h =>
|
||||
h.host.toLowerCase().includes(q) ||
|
||||
h.fingerprint.toLowerCase().includes(q) ||
|
||||
h.keyType.toLowerCase().includes(q)
|
||||
)
|
||||
})
|
||||
|
||||
/** 曾发生过指纹变更的主机数量(用于顶部的风险提示) */
|
||||
const changedCount = computed(() => store.knownHosts.filter(h => h.history.length > 0).length)
|
||||
|
||||
/** 展开查看变更历史的主机 key */
|
||||
const expanded = ref<string | null>(null)
|
||||
|
||||
function hostKey(h: KnownHost): string {
|
||||
return `${h.host}:${h.port}/${h.keyType}`
|
||||
}
|
||||
|
||||
function toggleExpand(h: KnownHost) {
|
||||
const k = hostKey(h)
|
||||
expanded.value = expanded.value === k ? null : k
|
||||
}
|
||||
|
||||
// ===== 单条遗忘 =====
|
||||
|
||||
const pendingForget = ref<KnownHost | null>(null)
|
||||
const forgetBusy = ref(false)
|
||||
|
||||
async function submitForget() {
|
||||
const h = pendingForget.value
|
||||
if (!h) return
|
||||
forgetBusy.value = true
|
||||
try {
|
||||
await store.forgetHost(h.host, h.port, h.keyType)
|
||||
toast.success(`已忘记 ${h.host}:${h.port}`)
|
||||
pendingForget.value = null
|
||||
} catch (e) {
|
||||
toast.error(`操作失败:${String(e)}`)
|
||||
} finally {
|
||||
forgetBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 全部清空 =====
|
||||
|
||||
const clearOpen = ref(false)
|
||||
const clearBusy = ref(false)
|
||||
/** 清空是破坏性操作:要求用户输入确认词,避免误点 */
|
||||
const clearConfirmText = ref('')
|
||||
const CLEAR_KEYWORD = '清空'
|
||||
|
||||
async function submitClear() {
|
||||
if (clearConfirmText.value.trim() !== CLEAR_KEYWORD) return
|
||||
clearBusy.value = true
|
||||
try {
|
||||
await store.clearKnownHosts()
|
||||
toast.success('已清空全部已知主机')
|
||||
clearOpen.value = false
|
||||
clearConfirmText.value = ''
|
||||
} catch (e) {
|
||||
toast.error(`清空失败:${String(e)}`)
|
||||
} finally {
|
||||
clearBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 导入 / 导出 =====
|
||||
|
||||
const copied = ref(false)
|
||||
let copiedTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
async function copyAll() {
|
||||
try {
|
||||
const text = await store.exportKnownHosts()
|
||||
if (!text.trim()) {
|
||||
toast.info('没有可导出的记录')
|
||||
return
|
||||
}
|
||||
await navigator.clipboard.writeText(text)
|
||||
copied.value = true
|
||||
if (copiedTimer) clearTimeout(copiedTimer)
|
||||
copiedTimer = setTimeout(() => (copied.value = false), 1800)
|
||||
toast.success('已复制到剪贴板')
|
||||
} catch (e) {
|
||||
toast.error(`导出失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
const importOpen = ref(false)
|
||||
const importText = ref('')
|
||||
const importBusy = ref(false)
|
||||
|
||||
function openImport() {
|
||||
importText.value = ''
|
||||
importOpen.value = true
|
||||
}
|
||||
|
||||
async function submitImport() {
|
||||
const text = importText.value.trim()
|
||||
if (!text) {
|
||||
toast.error('请粘贴 known_hosts 内容')
|
||||
return
|
||||
}
|
||||
importBusy.value = true
|
||||
try {
|
||||
const r = await store.importKnownHosts(text)
|
||||
if (r.ok) {
|
||||
toast.success(r.message)
|
||||
importOpen.value = false
|
||||
} else {
|
||||
toast.error(r.message)
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error(`导入 known_hosts 失败:${String(e)}`)
|
||||
toast.error(`导入失败:${String(e)}`)
|
||||
} finally {
|
||||
importBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 展示辅助 =====
|
||||
|
||||
function formatDate(rfc3339: string): string {
|
||||
if (!rfc3339) return '—'
|
||||
const d = new Date(rfc3339)
|
||||
if (Number.isNaN(d.getTime())) return rfc3339
|
||||
return d.toLocaleString('zh-CN', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
})
|
||||
}
|
||||
|
||||
function keyTypeLabel(t: string): string {
|
||||
const map: Record<string, string> = {
|
||||
'ssh-ed25519': 'Ed25519',
|
||||
'ssh-rsa': 'RSA',
|
||||
'ecdsa-sha2-nistp256': 'ECDSA 256',
|
||||
'ecdsa-sha2-nistp384': 'ECDSA 384',
|
||||
'ecdsa-sha2-nistp521': 'ECDSA 521',
|
||||
'ssh-dss': 'DSA'
|
||||
}
|
||||
return map[t] ?? t
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col h-full">
|
||||
<!-- 头部 -->
|
||||
<div class="shrink-0 flex items-center gap-2 px-4 h-12 border-b border-border">
|
||||
<ShieldCheck class="size-4 text-muted-foreground" />
|
||||
<h3 class="text-sm font-medium">已知主机</h3>
|
||||
<span class="text-xs text-muted-foreground">({{ store.knownHosts.length }})</span>
|
||||
<div class="flex-1" />
|
||||
<Button variant="outline" size="sm" class="h-7 gap-1.5 text-xs" @click="openImport">
|
||||
<ClipboardPaste class="size-3.5" />导入
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" class="h-7 gap-1.5 text-xs" @click="copyAll">
|
||||
<Check v-if="copied" class="size-3.5 text-emerald-600" />
|
||||
<Download v-else class="size-3.5" />
|
||||
导出
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="h-7 gap-1.5 text-xs text-destructive hover:text-destructive"
|
||||
:disabled="store.knownHosts.length === 0"
|
||||
@click="clearOpen = true"
|
||||
>
|
||||
<Trash2 class="size-3.5" />清空
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- 风险提示:有变更历史时始终可见 -->
|
||||
<div
|
||||
v-if="changedCount > 0"
|
||||
class="shrink-0 mx-3 mt-3 flex items-start gap-2 p-2.5 rounded-md
|
||||
border border-amber-500/40 bg-amber-500/10"
|
||||
>
|
||||
<AlertTriangle class="size-3.5 shrink-0 mt-0.5 text-amber-600 dark:text-amber-400" />
|
||||
<div class="text-[11px] text-amber-700 dark:text-amber-400">
|
||||
<p class="font-medium">{{ changedCount }} 台主机曾发生指纹变更</p>
|
||||
<p class="mt-0.5 opacity-90">
|
||||
若不是您本人重装或更换了服务器密钥,请联系管理员核实。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 搜索 -->
|
||||
<div v-if="store.knownHosts.length > 0" class="shrink-0 px-3 pt-3">
|
||||
<input
|
||||
v-model="search"
|
||||
placeholder="搜索主机、指纹或类型…"
|
||||
class="w-full h-7 px-2.5 rounded-md border border-border bg-transparent
|
||||
text-xs outline-none focus:border-primary/50 placeholder:text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- 列表 -->
|
||||
<div class="flex-1 min-h-0 overflow-y-auto p-3">
|
||||
<div v-if="store.knownHosts.length === 0" class="py-16 text-center">
|
||||
<ShieldCheck class="size-8 mx-auto text-muted-foreground/30 mb-3" />
|
||||
<p class="text-sm text-muted-foreground mb-1">还没有已知主机记录</p>
|
||||
<p class="text-xs text-muted-foreground/70">
|
||||
首次连接某台 SSH 主机时,会请您核对并保存其密钥指纹
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div v-else-if="filtered.length === 0" class="py-12 text-center">
|
||||
<p class="text-sm text-muted-foreground">没有匹配「{{ search }}」的记录</p>
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-1.5">
|
||||
<div
|
||||
v-for="h in filtered"
|
||||
:key="hostKey(h)"
|
||||
class="group rounded-md border border-border overflow-hidden
|
||||
hover:border-primary/40 transition-colors"
|
||||
:class="h.history.length > 0 ? 'border-amber-500/40' : ''"
|
||||
>
|
||||
<div class="flex items-start gap-3 px-3 py-2.5">
|
||||
<Server class="size-4 shrink-0 mt-0.5 text-muted-foreground" />
|
||||
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<span class="text-sm font-medium font-mono truncate">
|
||||
{{ h.host }}<span v-if="h.port !== 22" class="text-muted-foreground">:{{ h.port }}</span>
|
||||
</span>
|
||||
<span class="text-[10px] px-1.5 py-0.5 rounded bg-muted shrink-0">
|
||||
{{ keyTypeLabel(h.keyType) }}
|
||||
</span>
|
||||
<button
|
||||
v-if="h.history.length > 0"
|
||||
class="text-[10px] px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-700
|
||||
dark:text-amber-400 shrink-0 inline-flex items-center gap-0.5
|
||||
hover:bg-amber-500/25 transition-colors"
|
||||
@click="toggleExpand(h)"
|
||||
>
|
||||
<History class="size-2.5" />
|
||||
变更过 {{ h.history.length }} 次
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="mt-1 text-xs font-mono text-muted-foreground truncate"
|
||||
:title="h.fingerprint"
|
||||
>
|
||||
{{ h.fingerprint }}
|
||||
</div>
|
||||
|
||||
<div class="mt-1 flex items-center gap-3 text-[11px] text-muted-foreground/80">
|
||||
<span>首次 {{ formatDate(h.firstSeen) }}</span>
|
||||
<span>最近确认 {{ formatDate(h.lastConfirmed) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="size-7 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity
|
||||
text-destructive hover:text-destructive"
|
||||
title="忘记该主机"
|
||||
@click="pendingForget = h"
|
||||
>
|
||||
<Trash2 class="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- 变更历史 -->
|
||||
<div
|
||||
v-if="expanded === hostKey(h)"
|
||||
class="border-t border-border bg-muted/30 px-3 py-2 space-y-1.5"
|
||||
>
|
||||
<p class="text-[10px] uppercase tracking-wide text-muted-foreground">指纹变更历史</p>
|
||||
<div
|
||||
v-for="(c, i) in h.history"
|
||||
:key="i"
|
||||
class="flex items-start gap-2 text-[11px]"
|
||||
>
|
||||
<span
|
||||
class="shrink-0 mt-0.5 size-1.5 rounded-full"
|
||||
:class="c.accepted ? 'bg-amber-500' : 'bg-muted-foreground/40'"
|
||||
/>
|
||||
<div class="min-w-0">
|
||||
<span class="text-muted-foreground">{{ formatDate(c.changedAt) }}</span>
|
||||
<span class="mx-1.5">·</span>
|
||||
<span :class="c.accepted ? 'text-amber-700 dark:text-amber-400' : 'text-muted-foreground'">
|
||||
{{ c.accepted ? '已接受变更' : '已拒绝变更' }}
|
||||
</span>
|
||||
<div class="font-mono text-muted-foreground/70 truncate" :title="c.oldFingerprint">
|
||||
原指纹 {{ c.oldFingerprint }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== 忘记单条 ===== -->
|
||||
<Dialog :open="pendingForget !== null" @update:open="v => !v && (pendingForget = null)">
|
||||
<DialogContent class="max-w-sm" :show-close-button="false">
|
||||
<DialogHeader>
|
||||
<DialogTitle class="text-base">忘记该主机</DialogTitle>
|
||||
<DialogDescription class="text-xs">
|
||||
将删除 <span class="font-mono">{{ pendingForget?.host }}:{{ pendingForget?.port }}</span>
|
||||
的密钥指纹记录。下次连接时将重新提示核对。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div class="flex items-start gap-2 p-2 rounded bg-muted text-[11px] text-muted-foreground">
|
||||
<AlertTriangle class="size-3.5 shrink-0 mt-0.5" />
|
||||
<span>仅在确认该主机密钥确实已更换时执行。若出于「连不上就删掉」的动机,请先核实原因。</span>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" size="sm" @click="pendingForget = null">取消</Button>
|
||||
<Button variant="destructive" size="sm" :disabled="forgetBusy" @click="submitForget">
|
||||
忘记
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<!-- ===== 清空全部 ===== -->
|
||||
<Dialog v-model:open="clearOpen">
|
||||
<DialogContent class="max-w-sm" :show-close-button="false">
|
||||
<DialogHeader>
|
||||
<DialogTitle class="text-base text-destructive">清空全部已知主机</DialogTitle>
|
||||
<DialogDescription class="text-xs">
|
||||
将删除全部 {{ store.knownHosts.length }} 条记录。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div class="rounded-md border border-destructive/40 bg-destructive/5 p-2.5">
|
||||
<p class="text-[11px] text-destructive font-medium flex items-center gap-1 mb-1">
|
||||
<AlertTriangle class="size-3" />这会降低连接安全性
|
||||
</p>
|
||||
<p class="text-[11px] text-muted-foreground">
|
||||
清空后,所有主机的密钥校验都需要重新人工核对。在核对前,
|
||||
连接可能被中间人攻击劫持而您不会收到提示。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<p class="text-xs text-muted-foreground">
|
||||
请输入 <span class="font-mono font-semibold text-foreground">{{ CLEAR_KEYWORD }}</span> 以确认
|
||||
</p>
|
||||
<input
|
||||
v-model="clearConfirmText"
|
||||
class="w-full h-8 px-2.5 rounded-md border border-border bg-transparent
|
||||
text-sm outline-none focus:border-destructive/60"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" size="sm" @click="clearOpen = false">取消</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
:disabled="clearBusy || clearConfirmText.trim() !== CLEAR_KEYWORD"
|
||||
@click="submitClear"
|
||||
>
|
||||
<Loader2 v-if="clearBusy" class="size-3.5 mr-1.5 animate-spin" />
|
||||
清空全部
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<!-- ===== 导入 ===== -->
|
||||
<Dialog v-model:open="importOpen">
|
||||
<DialogContent class="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>导入 known_hosts</DialogTitle>
|
||||
<DialogDescription class="text-xs">
|
||||
粘贴 <span class="font-mono">~/.ssh/known_hosts</span> 的内容,或从其它设备导出的记录。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<Textarea
|
||||
v-model="importText"
|
||||
placeholder="example.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA…"
|
||||
class="font-mono text-xs min-h-[180px] resize-y"
|
||||
/>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" size="sm" @click="importOpen = false">取消</Button>
|
||||
<Button size="sm" :disabled="importBusy" @click="submitImport">
|
||||
<Loader2 v-if="importBusy" class="size-3.5 mr-1.5 animate-spin" />
|
||||
导入
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,811 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* SFTP 双栏文件管理面板。
|
||||
*
|
||||
* # 为什么是双栏而不是单栏 + 上传/下载按钮
|
||||
*
|
||||
* 传输任务的本质是「把 A 处的这个东西放到 B 处」。单栏形态下用户必须:
|
||||
* 先在远端浏览到目标目录 → 记住路径 → 打开本地文件对话框 → 逐级点到源文件。
|
||||
* 双栏把这个心智模型直接画出来:左边本地、右边远端,拖过去就行。
|
||||
*
|
||||
* # 左右栏的分工是有意不对称的
|
||||
*
|
||||
* 远端栏是**完整实现**(浏览、新建、删除、重命名、符号链接解析、跟随终端 cwd);
|
||||
* 本地栏只做「定位与选取」——它有真实的系统文件管理器在旁边,
|
||||
* 在 WebView 里重造一个更差的资源管理器(缩略图、右键菜单、拖放剪贴板互操作)
|
||||
* 是纯粹的浪费。因此本地栏刻意只给:路径输入 + 快捷位置 + 系统对话框选择。
|
||||
*
|
||||
* # 一次只服务一个会话
|
||||
*
|
||||
* 面板绑定 `sessionId`,不自己持有 SFTP 通道句柄——通道由 store 按会话管理
|
||||
* (见 `SftpRegistry`)。会话断开时面板自动收起,不留一个指向死通道的空壳。
|
||||
*/
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { open as openDialog, save as saveDialog } from '@tauri-apps/plugin-dialog'
|
||||
import {
|
||||
ArrowDownToLine,
|
||||
ArrowUpFromLine,
|
||||
ChevronRight,
|
||||
CornerUpLeft,
|
||||
ExternalLink,
|
||||
File as FileIcon,
|
||||
Folder,
|
||||
FolderOpen,
|
||||
FolderPlus,
|
||||
HardDrive,
|
||||
Link2,
|
||||
Loader2,
|
||||
RefreshCw,
|
||||
Server,
|
||||
Trash2,
|
||||
X
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { useTerminalStore } from '@/stores/terminalStore'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import type { RemoteEntry } from '@/types/terminal'
|
||||
|
||||
const props = defineProps<{
|
||||
sessionId: string
|
||||
/** 会话显示名(面板标题用,避免面板自己再查一次 store) */
|
||||
sessionLabel: string
|
||||
/** 终端当前工作目录,用于「跟随终端目录」 */
|
||||
terminalCwd: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'close'): void
|
||||
}>()
|
||||
|
||||
const logger = createLogger('terminal')
|
||||
|
||||
const store = useTerminalStore()
|
||||
|
||||
// ===== 远端栏状态 =====
|
||||
|
||||
const remoteCwd = ref('')
|
||||
const remoteEntries = ref<RemoteEntry[]>([])
|
||||
const remoteLoading = ref(false)
|
||||
const remoteError = ref('')
|
||||
|
||||
/** 选中项(单选用它;多选留给 P2 的批量操作) */
|
||||
const selectedRemote = ref<RemoteEntry | null>(null)
|
||||
|
||||
const remoteFilter = ref('')
|
||||
|
||||
const filteredRemote = computed(() => {
|
||||
const kw = remoteFilter.value.trim().toLowerCase()
|
||||
if (!kw) return remoteEntries.value
|
||||
return remoteEntries.value.filter(e => e.name.toLowerCase().includes(kw))
|
||||
})
|
||||
|
||||
/** 面包屑:把 `/a/b/c` 拆成可点击的逐级路径 */
|
||||
const crumbs = computed(() => {
|
||||
const p = remoteCwd.value
|
||||
if (!p) return []
|
||||
const parts = p.split('/').filter(Boolean)
|
||||
const out: Array<{ name: string; path: string }> = []
|
||||
let acc = ''
|
||||
for (const part of parts) {
|
||||
acc += `/${part}`
|
||||
out.push({ name: part, path: acc })
|
||||
}
|
||||
return out
|
||||
})
|
||||
|
||||
async function loadRemote(path: string) {
|
||||
if (!path) return
|
||||
remoteLoading.value = true
|
||||
remoteError.value = ''
|
||||
try {
|
||||
const dir = await store.sftpList(props.sessionId, path)
|
||||
// 用服务端返回的 cwd 而不是请求的 path:符号链接目录下两者不同,
|
||||
// 显示真实位置才能解释「为什么我看的内容和路径不像」
|
||||
remoteCwd.value = dir.cwd || path
|
||||
remoteEntries.value = dir.entries
|
||||
selectedRemote.value = null
|
||||
} catch (e) {
|
||||
remoteError.value = String(e)
|
||||
logger.error(`列举远端目录 ${path} 失败:${String(e)}`)
|
||||
} finally {
|
||||
remoteLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function goUp() {
|
||||
try {
|
||||
const parent = await store.sftpParent(remoteCwd.value)
|
||||
if (parent === remoteCwd.value) return
|
||||
await loadRemote(parent)
|
||||
} catch (e) {
|
||||
toast.error(`无法返回上一级:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function enterRemote(entry: RemoteEntry) {
|
||||
if (entry.kind === 'dir') {
|
||||
await loadRemote(entry.path)
|
||||
return
|
||||
}
|
||||
if (entry.kind === 'symlink') {
|
||||
// 符号链接指向目录时应该「进去」而不是报错。判断方式:读目标再试一次列举。
|
||||
try {
|
||||
const dir = await store.sftpList(props.sessionId, entry.path)
|
||||
remoteCwd.value = dir.cwd || entry.path
|
||||
remoteEntries.value = dir.entries
|
||||
selectedRemote.value = null
|
||||
return
|
||||
} catch {
|
||||
// 不是目录(或链接已失效)——退回「选中」,让用户自己决定下一步
|
||||
selectedRemote.value = entry
|
||||
toast.info(`符号链接指向 ${entry.linkTarget}(不是目录或不可访问)`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 跟随终端当前目录 */
|
||||
async function followTerminalCwd() {
|
||||
if (!props.terminalCwd) {
|
||||
toast.info('终端尚未上报工作目录(该 shell 可能不支持 OSC 7)')
|
||||
return
|
||||
}
|
||||
await loadRemote(props.terminalCwd)
|
||||
}
|
||||
|
||||
// ===== 远端编辑操作 =====
|
||||
|
||||
const newDirName = ref('')
|
||||
const showNewDir = ref(false)
|
||||
|
||||
async function createFolder() {
|
||||
const name = newDirName.value.trim()
|
||||
if (!name || name.includes('/')) {
|
||||
toast.error('目录名不能为空,且不能包含 /')
|
||||
return
|
||||
}
|
||||
try {
|
||||
// 用 store.sftpParent 拼接而不是前端拼 `/`:远端是 POSIX 语义,
|
||||
// 根目录下的拼接结果与 Windows 侧的习惯不同(避免出现 `//new`)
|
||||
await store.sftpMkdir(props.sessionId, joinRemote(remoteCwd.value, name))
|
||||
showNewDir.value = false
|
||||
newDirName.value = ''
|
||||
await loadRemote(remoteCwd.value)
|
||||
toast.success(`已创建 ${name}`)
|
||||
} catch (e) {
|
||||
toast.error(`创建目录失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 远端路径拼接。
|
||||
*
|
||||
* 与 Rust 侧 `join_remote` 同一套规则。前端这边**只在展示与提交时**用,
|
||||
* 真实解析仍以服务端 `cwd` 为准——若两边规则有出入,服务端是权威。
|
||||
*/
|
||||
function joinRemote(base: string, name: string): string {
|
||||
if (!base) return `/${name}`
|
||||
if (base === '/') return `/${name}`
|
||||
return `${base.replace(/\/+$/, '')}/${name}`
|
||||
}
|
||||
|
||||
async function removeRemote() {
|
||||
const e = selectedRemote.value
|
||||
if (!e) return
|
||||
const isDir = e.kind === 'dir'
|
||||
const hint = isDir ? '及其全部内容' : ''
|
||||
if (!window.confirm(`确定删除「${e.name}」${hint}?此操作不可恢复。`)) return
|
||||
try {
|
||||
const r = await store.sftpDelete(props.sessionId, e.path, isDir)
|
||||
toast.success(r.message)
|
||||
await loadRemote(remoteCwd.value)
|
||||
} catch (err) {
|
||||
toast.error(`删除失败:${String(err)}`)
|
||||
}
|
||||
}
|
||||
|
||||
const renaming = ref(false)
|
||||
const renameValue = ref('')
|
||||
|
||||
function startRename() {
|
||||
const e = selectedRemote.value
|
||||
if (!e) return
|
||||
renameValue.value = e.name
|
||||
renaming.value = true
|
||||
}
|
||||
|
||||
async function submitRename() {
|
||||
const e = selectedRemote.value
|
||||
if (!e) return
|
||||
const name = renameValue.value.trim()
|
||||
if (!name || name === e.name) {
|
||||
renaming.value = false
|
||||
return
|
||||
}
|
||||
if (name.includes('/')) {
|
||||
toast.error('名称不能包含 /')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await store.sftpRename(props.sessionId, e.path, joinRemote(remoteCwd.value, name))
|
||||
renaming.value = false
|
||||
await loadRemote(remoteCwd.value)
|
||||
} catch (err) {
|
||||
toast.error(`重命名失败:${String(err)}`)
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 本地栏状态 =====
|
||||
|
||||
/**
|
||||
* 本地目录**不由前端列举**。
|
||||
*
|
||||
* 理由:WebView 里没有可靠的方式读本地目录(FS Access API 在 Tauri 的
|
||||
* http://tauri.localhost 源下支持情况不稳定,而为了列目录去引一个
|
||||
* fs 插件权限太重)。本机已经有资源管理器,因此本地栏的定位入口是
|
||||
* **系统文件对话框** ——用户本来就更习惯用它。
|
||||
*/
|
||||
const localDir = ref('')
|
||||
const localFiles = ref<string[]>([])
|
||||
|
||||
async function pickLocalDir() {
|
||||
try {
|
||||
const picked = await openDialog({ directory: true, multiple: false })
|
||||
if (typeof picked !== 'string') return
|
||||
localDir.value = picked
|
||||
localFiles.value = []
|
||||
} catch (e) {
|
||||
toast.error(`选择目录失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function pickLocalFiles() {
|
||||
try {
|
||||
const picked = await openDialog({ multiple: true, directory: false })
|
||||
if (!picked) return
|
||||
const list = Array.isArray(picked) ? picked : [picked]
|
||||
localFiles.value = list
|
||||
// 把目录同步成首个文件的所在目录,让「上传」的目标路径有参照
|
||||
if (list.length > 0) {
|
||||
const first = list[0].replace(/\\/g, '/')
|
||||
localDir.value = first.slice(0, first.lastIndexOf('/')) || localDir.value
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(`选择文件失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
function clearLocalFiles() {
|
||||
localFiles.value = []
|
||||
}
|
||||
|
||||
/** 本地文件名的展示形态(去掉目录部分) */
|
||||
function baseName(path: string): string {
|
||||
const p = path.replace(/\\/g, '/')
|
||||
return p.slice(p.lastIndexOf('/') + 1)
|
||||
}
|
||||
|
||||
// ===== 传输 =====
|
||||
|
||||
const uploading = ref(false)
|
||||
const downloading = ref(false)
|
||||
|
||||
/** 进行中的传输(按 id 去重后展示进度条) */
|
||||
const activeTransfers = computed(() =>
|
||||
store.transfers.filter(t => t.sessionId === props.sessionId)
|
||||
)
|
||||
|
||||
async function uploadSelected() {
|
||||
if (localFiles.value.length === 0) {
|
||||
toast.info('请先选择要上传的本地文件')
|
||||
return
|
||||
}
|
||||
uploading.value = true
|
||||
let ok = 0
|
||||
const failed: string[] = []
|
||||
// 串行上传:并发多个大文件会把受控并发的闸门(4)占满,
|
||||
// 而文件名顺序错乱的进度条比「一个一个来」更难读
|
||||
for (const file of localFiles.value) {
|
||||
try {
|
||||
const r = await store.sftpUpload(
|
||||
props.sessionId,
|
||||
file,
|
||||
joinRemote(remoteCwd.value, baseName(file))
|
||||
)
|
||||
if (r.ok) ok += 1
|
||||
else failed.push(`${baseName(file)}:${r.message}`)
|
||||
} catch (e) {
|
||||
failed.push(`${baseName(file)}:${String(e)}`)
|
||||
}
|
||||
}
|
||||
uploading.value = false
|
||||
await loadRemote(remoteCwd.value)
|
||||
|
||||
if (failed.length === 0) {
|
||||
toast.success(`已上传 ${ok} 个文件`)
|
||||
} else if (ok > 0) {
|
||||
toast.warning(`上传完成 ${ok} 个,失败 ${failed.length} 个:${failed.join(';')}`)
|
||||
} else {
|
||||
toast.error(`上传失败:${failed.join(';')}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadSelected() {
|
||||
const e = selectedRemote.value
|
||||
if (!e) {
|
||||
toast.info('请先选择要下载的远端文件')
|
||||
return
|
||||
}
|
||||
if (e.kind === 'dir') {
|
||||
toast.info('目录下载属 P2;请进入目录后逐个下载文件')
|
||||
return
|
||||
}
|
||||
try {
|
||||
const suggested = localDir.value
|
||||
? `${localDir.value.replace(/\\/g, '/').replace(/\/+$/, '')}/${e.name}`
|
||||
: e.name
|
||||
const target = await saveDialog({ defaultPath: suggested })
|
||||
if (!target) return
|
||||
downloading.value = true
|
||||
const r = await store.sftpDownload(props.sessionId, e.path, target)
|
||||
toast.success(r.message)
|
||||
} catch (err) {
|
||||
toast.error(`下载失败:${String(err)}`)
|
||||
} finally {
|
||||
downloading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 下载到本地目录(不弹保存框,直接用当前本地目录 + 原文件名) */
|
||||
async function downloadToLocalDir() {
|
||||
const e = selectedRemote.value
|
||||
if (!e) {
|
||||
toast.info('请先选择要下载的远端文件')
|
||||
return
|
||||
}
|
||||
if (!localDir.value) {
|
||||
toast.info('请先选择本地目录')
|
||||
return
|
||||
}
|
||||
if (e.kind === 'dir') {
|
||||
toast.info('目录下载属 P2')
|
||||
return
|
||||
}
|
||||
try {
|
||||
downloading.value = true
|
||||
const sep = localDir.value.includes('\\') ? '\\' : '/'
|
||||
const target = `${localDir.value.replace(/[\\/]+$/, '')}${sep}${e.name}`
|
||||
const r = await store.sftpDownload(props.sessionId, e.path, target)
|
||||
toast.success(r.message)
|
||||
} catch (err) {
|
||||
toast.error(`下载失败:${String(err)}`)
|
||||
} finally {
|
||||
downloading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openLocal(path: string) {
|
||||
void store.openLocalPath(path).catch(e => toast.error(`打开失败:${String(e)}`))
|
||||
}
|
||||
|
||||
function revealLocal(path: string) {
|
||||
void store.revealLocalPath(path).catch(e => toast.error(`定位失败:${String(e)}`))
|
||||
}
|
||||
|
||||
// ===== 展示辅助 =====
|
||||
|
||||
/** 字节数的人类可读形态 */
|
||||
function humanSize(n: number): string {
|
||||
if (n < 1024) return `${n} B`
|
||||
const units = ['KB', 'MB', 'GB', 'TB']
|
||||
let v = n / 1024
|
||||
let i = 0
|
||||
while (v >= 1024 && i < units.length - 1) {
|
||||
v /= 1024
|
||||
i += 1
|
||||
}
|
||||
return `${v < 10 ? v.toFixed(1) : Math.round(v)} ${units[i]}`
|
||||
}
|
||||
|
||||
function fmtTime(ms?: number | null): string {
|
||||
if (!ms) return ''
|
||||
const d = new Date(ms)
|
||||
const pad = (x: number) => String(x).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
|
||||
}
|
||||
|
||||
function entryIcon(e: RemoteEntry) {
|
||||
if (e.kind === 'dir') return Folder
|
||||
if (e.kind === 'symlink') return Link2
|
||||
return FileIcon
|
||||
}
|
||||
|
||||
// ===== 生命周期 =====
|
||||
|
||||
let disposed = false
|
||||
|
||||
watch(
|
||||
() => props.sessionId,
|
||||
async id => {
|
||||
if (!id || disposed) return
|
||||
try {
|
||||
await store.sftpOpen(id)
|
||||
// 初始目录:优先会话的 remoteCwd / 终端 cwd,都由调用方通过 props 给到
|
||||
await loadRemote(props.terminalCwd || '.')
|
||||
} catch (e) {
|
||||
remoteError.value = String(e)
|
||||
toast.error(`打开文件管理器失败:${String(e)}`)
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
// 终端 cd 之后,若用户开着「跟随」就自动同步
|
||||
const following = ref(false)
|
||||
watch(
|
||||
() => props.terminalCwd,
|
||||
cwd => {
|
||||
if (following.value && cwd) void loadRemote(cwd)
|
||||
}
|
||||
)
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
// 显式关通道:让服务端立刻回收句柄,而不是等 TCP 超时。
|
||||
// 不 await —— 卸载路径上等异步会让面板关闭出现可见延迟。
|
||||
void store.sftpClose(props.sessionId).catch(() => {
|
||||
/* 会话可能已断开,忽略 */
|
||||
})
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col h-full min-h-0 bg-background">
|
||||
<!-- ===== 头部 ===== -->
|
||||
<div class="shrink-0 flex items-center gap-2 px-2.5 h-9 border-b border-border">
|
||||
<HardDrive class="size-3.5 text-muted-foreground shrink-0" />
|
||||
<span class="text-xs font-medium truncate" :title="sessionLabel">{{ sessionLabel }}</span>
|
||||
<span class="text-[10px] text-muted-foreground font-mono truncate">
|
||||
{{ remoteCwd || '—' }}
|
||||
</span>
|
||||
<div class="flex-1" />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-6 px-1.5 text-[11px]"
|
||||
:disabled="!terminalCwd"
|
||||
title="定位到终端当前目录"
|
||||
@click="followTerminalCwd"
|
||||
>
|
||||
跟随终端
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" class="h-6 w-6 p-0" title="关闭面板" @click="emit('close')">
|
||||
<X class="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- ===== 主体:左右双栏 ===== -->
|
||||
<div class="flex-1 min-h-0 flex">
|
||||
<!-- ---------- 本地栏 ---------- -->
|
||||
<section class="w-[38%] min-w-[220px] flex flex-col border-r border-border">
|
||||
<div class="shrink-0 h-7 px-2 flex items-center gap-1.5 border-b border-border bg-muted/40">
|
||||
<HardDrive class="size-3 text-muted-foreground" />
|
||||
<span class="text-[11px] font-medium">本地</span>
|
||||
</div>
|
||||
|
||||
<div class="shrink-0 p-2 space-y-1.5 border-b border-border">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="w-full h-7 text-[11px] justify-start gap-1.5"
|
||||
@click="pickLocalDir"
|
||||
>
|
||||
<FolderOpen class="size-3" />选择目录
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="w-full h-7 text-[11px] justify-start gap-1.5"
|
||||
@click="pickLocalFiles"
|
||||
>
|
||||
<FileIcon class="size-3" />选择文件…
|
||||
</Button>
|
||||
<div v-if="localDir" class="text-[10px] text-muted-foreground truncate font-mono px-0.5" :title="localDir">
|
||||
{{ localDir }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex-1 min-h-0 overflow-auto">
|
||||
<div v-if="localFiles.length === 0" class="p-3 text-center">
|
||||
<p class="text-[11px] text-muted-foreground/70 leading-relaxed">
|
||||
选择本地文件后点「上传」。<br />
|
||||
本地目录浏览请用系统资源管理器 —— 在 WebView 里重造一个更差的资源管理器没有意义。
|
||||
</p>
|
||||
</div>
|
||||
<ul v-else class="py-1">
|
||||
<li
|
||||
v-for="f in localFiles"
|
||||
:key="f"
|
||||
class="group px-2 py-1 flex items-center gap-1.5 text-[11px] hover:bg-accent cursor-default"
|
||||
:title="f"
|
||||
>
|
||||
<FileIcon class="size-3 shrink-0 text-muted-foreground" />
|
||||
<span class="truncate flex-1">{{ baseName(f) }}</span>
|
||||
<button
|
||||
class="opacity-0 group-hover:opacity-100 text-muted-foreground hover:text-foreground"
|
||||
title="用默认程序打开"
|
||||
@click="openLocal(f)"
|
||||
>
|
||||
<ExternalLink class="size-3" />
|
||||
</button>
|
||||
<button
|
||||
class="opacity-0 group-hover:opacity-100 text-muted-foreground hover:text-foreground"
|
||||
title="在资源管理器中显示"
|
||||
@click="revealLocal(f)"
|
||||
>
|
||||
<FolderOpen class="size-3" />
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="shrink-0 p-2 border-t border-border flex items-center gap-1.5">
|
||||
<Button
|
||||
size="sm"
|
||||
class="flex-1 h-7 text-[11px] gap-1.5"
|
||||
:disabled="uploading || localFiles.length === 0"
|
||||
@click="uploadSelected"
|
||||
>
|
||||
<Loader2 v-if="uploading" class="size-3 animate-spin" />
|
||||
<ArrowUpFromLine v-else class="size-3" />
|
||||
上传{{ localFiles.length > 1 ? ` (${localFiles.length})` : '' }}
|
||||
</Button>
|
||||
<Button
|
||||
v-if="localFiles.length > 0"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-7 px-1.5 text-[11px]"
|
||||
@click="clearLocalFiles"
|
||||
>
|
||||
清空
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ---------- 远端栏 ---------- -->
|
||||
<section class="flex-1 min-w-0 flex flex-col">
|
||||
<div class="shrink-0 h-7 px-2 flex items-center gap-1.5 border-b border-border bg-muted/40">
|
||||
<Server class="size-3 text-muted-foreground" />
|
||||
<span class="text-[11px] font-medium">远端</span>
|
||||
<div class="flex-1" />
|
||||
<label class="flex items-center gap-1 text-[10px] text-muted-foreground cursor-pointer select-none">
|
||||
<input v-model="following" type="checkbox" class="size-3 accent-primary" />
|
||||
跟随 cd
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<!-- 工具条 -->
|
||||
<div class="shrink-0 px-2 py-1.5 flex items-center gap-1 border-b border-border">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-6 w-6 p-0"
|
||||
title="上一级"
|
||||
:disabled="remoteCwd === '/' || !remoteCwd"
|
||||
@click="goUp"
|
||||
>
|
||||
<CornerUpLeft class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-6 w-6 p-0"
|
||||
title="刷新"
|
||||
@click="loadRemote(remoteCwd)"
|
||||
>
|
||||
<RefreshCw class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-6 w-6 p-0"
|
||||
title="新建目录"
|
||||
@click="showNewDir = !showNewDir"
|
||||
>
|
||||
<FolderPlus class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-6 w-6 p-0"
|
||||
title="重命名"
|
||||
:disabled="!selectedRemote"
|
||||
@click="startRename"
|
||||
>
|
||||
<FileIcon class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-6 w-6 p-0 text-destructive"
|
||||
title="删除"
|
||||
:disabled="!selectedRemote"
|
||||
@click="removeRemote"
|
||||
>
|
||||
<Trash2 class="size-3.5" />
|
||||
</Button>
|
||||
<div class="flex-1" />
|
||||
<Input
|
||||
v-model="remoteFilter"
|
||||
placeholder="筛选…"
|
||||
class="h-6 w-32 text-[11px]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- 新建目录输入 -->
|
||||
<div v-if="showNewDir" class="shrink-0 px-2 py-1.5 flex items-center gap-1.5 border-b border-border">
|
||||
<Input
|
||||
v-model="newDirName"
|
||||
placeholder="新目录名"
|
||||
class="h-6 flex-1 text-[11px]"
|
||||
@keydown.enter="createFolder"
|
||||
@keydown.esc="showNewDir = false"
|
||||
/>
|
||||
<Button size="sm" class="h-6 text-[11px]" @click="createFolder">创建</Button>
|
||||
</div>
|
||||
|
||||
<!-- 面包屑 -->
|
||||
<div class="shrink-0 px-2 py-1 flex items-center gap-0.5 text-[11px] border-b border-border overflow-x-auto whitespace-nowrap">
|
||||
<button class="hover:text-primary shrink-0" @click="loadRemote('/')">/</button>
|
||||
<template v-for="c in crumbs" :key="c.path">
|
||||
<ChevronRight class="size-3 shrink-0 text-muted-foreground/50" />
|
||||
<button class="hover:text-primary shrink-0" @click="loadRemote(c.path)">{{ c.name }}</button>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- 列表 -->
|
||||
<div class="flex-1 min-h-0 overflow-auto">
|
||||
<div v-if="remoteLoading" class="p-4 flex items-center justify-center gap-2">
|
||||
<Loader2 class="size-3.5 animate-spin text-muted-foreground" />
|
||||
<span class="text-[11px] text-muted-foreground">正在读取…</span>
|
||||
</div>
|
||||
<div v-else-if="remoteError" class="p-4">
|
||||
<p class="text-[11px] text-destructive break-all">{{ remoteError }}</p>
|
||||
</div>
|
||||
<div v-else-if="filteredRemote.length === 0" class="p-4 text-center">
|
||||
<p class="text-[11px] text-muted-foreground/70">
|
||||
{{ remoteEntries.length === 0 ? '空目录' : '无匹配项' }}
|
||||
</p>
|
||||
</div>
|
||||
<table v-else class="w-full text-[11px] border-collapse">
|
||||
<thead class="sticky top-0 bg-background z-10">
|
||||
<tr class="text-muted-foreground text-left">
|
||||
<th class="font-normal px-2 py-1 border-b border-border">名称</th>
|
||||
<th class="font-normal px-2 py-1 border-b border-border w-20 text-right">大小</th>
|
||||
<th class="font-normal px-2 py-1 border-b border-border w-28 hidden md:table-cell">修改时间</th>
|
||||
<th class="font-normal px-2 py-1 border-b border-border w-14 text-right">权限</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="e in filteredRemote"
|
||||
:key="e.path"
|
||||
class="hover:bg-accent cursor-default select-none"
|
||||
:class="selectedRemote?.path === e.path ? 'bg-accent' : ''"
|
||||
@click="selectedRemote = e"
|
||||
@dblclick="enterRemote(e)"
|
||||
>
|
||||
<td class="px-2 py-1">
|
||||
<div class="flex items-center gap-1.5 min-w-0">
|
||||
<component
|
||||
:is="entryIcon(e)"
|
||||
class="size-3 shrink-0"
|
||||
:class="e.kind === 'dir' ? 'text-amber-500' : 'text-muted-foreground'"
|
||||
/>
|
||||
<template v-if="renaming && selectedRemote?.path === e.path">
|
||||
<input
|
||||
v-model="renameValue"
|
||||
class="flex-1 h-5 px-1 text-[11px] rounded border border-primary/60 bg-transparent outline-none"
|
||||
@click.stop
|
||||
@keydown.enter="submitRename"
|
||||
@keydown.esc="renaming = false"
|
||||
/>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span class="truncate" :title="e.kind === 'symlink' ? `${e.path} → ${e.linkTarget}` : e.path">
|
||||
{{ e.name }}
|
||||
</span>
|
||||
<span
|
||||
v-if="e.kind === 'symlink' && e.linkTarget"
|
||||
class="text-muted-foreground/60 truncate shrink-0 max-w-[40%]"
|
||||
>
|
||||
→ {{ e.linkTarget }}
|
||||
</span>
|
||||
</template>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-2 py-1 text-right text-muted-foreground tabular-nums">
|
||||
{{ e.kind === 'dir' ? '—' : humanSize(e.size) }}
|
||||
</td>
|
||||
<td class="px-2 py-1 text-muted-foreground hidden md:table-cell tabular-nums">
|
||||
{{ fmtTime(e.modifiedAt) }}
|
||||
</td>
|
||||
<td class="px-2 py-1 text-right text-muted-foreground font-mono">
|
||||
{{ e.permissions || '—' }}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- 远端操作条 -->
|
||||
<div class="shrink-0 p-2 border-t border-border flex items-center gap-1.5">
|
||||
<span class="text-[10px] text-muted-foreground truncate flex-1" :title="selectedRemote?.path">
|
||||
{{ selectedRemote ? selectedRemote.path : `共 ${filteredRemote.length} 项` }}
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="h-7 text-[11px] gap-1.5"
|
||||
:disabled="downloading || !selectedRemote || selectedRemote.kind === 'dir'"
|
||||
@click="downloadSelected"
|
||||
>
|
||||
<Loader2 v-if="downloading" class="size-3 animate-spin" />
|
||||
<ArrowDownToLine v-else class="size-3" />
|
||||
另存为…
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
class="h-7 text-[11px] gap-1.5"
|
||||
:disabled="downloading || !selectedRemote || selectedRemote.kind === 'dir' || !localDir"
|
||||
@click="downloadToLocalDir"
|
||||
>
|
||||
<ArrowDownToLine class="size-3" />
|
||||
下载到本地目录
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<!-- ===== 传输进度 ===== -->
|
||||
<div v-if="activeTransfers.length > 0" class="shrink-0 border-t border-border max-h-28 overflow-auto">
|
||||
<div
|
||||
v-for="t in activeTransfers"
|
||||
:key="t.id"
|
||||
class="px-2.5 py-1.5 flex items-center gap-2 text-[11px] border-b border-border/50 last:border-b-0"
|
||||
>
|
||||
<component
|
||||
:is="t.direction === 'upload' ? ArrowUpFromLine : ArrowDownToLine"
|
||||
class="size-3 shrink-0"
|
||||
:class="t.state === 'failed' ? 'text-destructive' : 'text-muted-foreground'"
|
||||
/>
|
||||
<span class="truncate flex-1" :title="`${t.source} → ${t.target}`">
|
||||
{{ baseName(t.source) }}
|
||||
<span class="text-muted-foreground/60">→ {{ baseName(t.target) }}</span>
|
||||
</span>
|
||||
<div v-if="t.state === 'running'" class="w-24 h-1 rounded-full bg-muted overflow-hidden shrink-0">
|
||||
<div
|
||||
class="h-full bg-primary transition-[width] duration-200"
|
||||
:style="{ width: t.total > 0 ? `${Math.min(100, (t.transferred / t.total) * 100)}%` : '0%' }"
|
||||
/>
|
||||
</div>
|
||||
<span class="text-muted-foreground tabular-nums shrink-0 w-24 text-right">
|
||||
<template v-if="t.state === 'running'">
|
||||
{{ t.total > 0 ? `${humanSize(t.transferred)} / ${humanSize(t.total)}` : humanSize(t.transferred) }}
|
||||
</template>
|
||||
<span v-else-if="t.state === 'done'" class="text-emerald-600">完成</span>
|
||||
<span v-else-if="t.state === 'failed'" class="text-destructive" :title="t.error ?? ''">失败</span>
|
||||
<span v-else>{{ t.state }}</span>
|
||||
</span>
|
||||
<button
|
||||
class="text-muted-foreground hover:text-foreground shrink-0"
|
||||
title="从列表移除"
|
||||
@click="store.dismissTransfer(t.id)"
|
||||
>
|
||||
<X class="size-3" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,573 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 命令片段面板(浮层)。
|
||||
*
|
||||
* # 交互模型:先填参数、再决定是否执行
|
||||
*
|
||||
* 带占位符的片段走「填写 → 预览 → 执行」三步。预览这一步不是装饰:
|
||||
* 用户能在这里看到**渲染后的真实命令**,而执行按钮分两个——
|
||||
* 「填入命令行」(不回车)与「直接执行」。危险片段(`confirm` 为 true)
|
||||
* 默认只做前者:让用户自己按回车,与命令被自动执行在心理上完全不同。
|
||||
*
|
||||
* # 为什么占位符列表来自后端
|
||||
*
|
||||
* 解析规则(`$${x}` 转义、`${VAR:-default}` 排除、名称字符集)由 Rust 的
|
||||
* `snippet_placeholders` 单独实现一份。前端若自己写正则,两边在边界情况上
|
||||
* 迟早分叉 —— 而「预览显示的命令」与「实际执行的命令」不一致是最坏的结果。
|
||||
*/
|
||||
import { computed, ref } from 'vue'
|
||||
import { open as openDialog } from '@tauri-apps/plugin-dialog'
|
||||
import {
|
||||
BookMarked,
|
||||
Play,
|
||||
Pin,
|
||||
Plus,
|
||||
RotateCcw,
|
||||
Search,
|
||||
ShieldAlert,
|
||||
Terminal,
|
||||
Trash2,
|
||||
X
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { useTerminalStore } from '@/stores/terminalStore'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import type { CommandSnippet, SessionInfo, SnippetView } from '@/types/terminal'
|
||||
|
||||
const props = defineProps<{
|
||||
sessionId: string | null
|
||||
session: SessionInfo | undefined
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'close'): void
|
||||
}>()
|
||||
|
||||
const logger = createLogger('terminal')
|
||||
const store = useTerminalStore()
|
||||
|
||||
const filter = ref('')
|
||||
const selected = ref<SnippetView | null>(null)
|
||||
|
||||
/** 会话是 SSH 还是本地(决定哪些片段可见) */
|
||||
const sessionKind = computed<'local' | 'ssh'>(() => props.session?.kind ?? 'local')
|
||||
|
||||
/** 本地会话对应的 shell kind(用于 `shellKinds` 过滤) */
|
||||
const shellKind = computed(() => store.shellOf(props.session)?.kind)
|
||||
|
||||
/** 当前会话可用的片段 */
|
||||
const available = computed(() => store.snippetsForSession(sessionKind.value, shellKind.value))
|
||||
|
||||
const filtered = computed(() => {
|
||||
const kw = filter.value.trim().toLowerCase()
|
||||
if (!kw) return available.value
|
||||
return available.value.filter(
|
||||
s =>
|
||||
s.name.toLowerCase().includes(kw) ||
|
||||
s.command.toLowerCase().includes(kw) ||
|
||||
s.description.toLowerCase().includes(kw)
|
||||
)
|
||||
})
|
||||
|
||||
/** 按分组归类(保持 store 的排序:置顶优先 + 名称序) */
|
||||
const grouped = computed(() => {
|
||||
const map = new Map<string, SnippetView[]>()
|
||||
for (const s of filtered.value) {
|
||||
const g = s.group.trim() || '未分组'
|
||||
if (!map.has(g)) map.set(g, [])
|
||||
map.get(g)!.push(s)
|
||||
}
|
||||
return [...map.entries()]
|
||||
})
|
||||
|
||||
// ===== 参数填写 =====
|
||||
|
||||
/** 占位符名 → 当前填写值 */
|
||||
const values = ref<Record<string, string>>({})
|
||||
|
||||
/** 渲染后的命令(每次 preview 后更新) */
|
||||
const preview = ref('')
|
||||
const rendering = ref(false)
|
||||
|
||||
function select(s: SnippetView) {
|
||||
selected.value = s
|
||||
preview.value = ''
|
||||
// 预填默认值:大多数情况下用户只需要改其中一两个
|
||||
const v: Record<string, string> = {}
|
||||
for (const k of s.placeholders) v[k] = s.defaults[k] ?? ''
|
||||
values.value = v
|
||||
}
|
||||
|
||||
const missing = computed(() => {
|
||||
const s = selected.value
|
||||
if (!s) return []
|
||||
return s.placeholders.filter(k => !(values.value[k] ?? '').trim())
|
||||
})
|
||||
|
||||
async function doRender() {
|
||||
const s = selected.value
|
||||
if (!s) return
|
||||
if (missing.value.length > 0) {
|
||||
toast.error(`还有 ${missing.value.length} 个占位符未填写`)
|
||||
return
|
||||
}
|
||||
rendering.value = true
|
||||
try {
|
||||
preview.value = await store.renderSnippet(s.id, values.value)
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
preview.value = ''
|
||||
} finally {
|
||||
rendering.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行片段。
|
||||
*
|
||||
* `submit = true` 直接回车执行;否则只写到命令行上。
|
||||
* 危险片段(`confirm`)在界面上不提供「直接执行」按钮,
|
||||
* 但这里仍做一层兜底——见下面对 `mustConfirm` 的判断。
|
||||
*/
|
||||
async function run(submit: boolean) {
|
||||
const s = selected.value
|
||||
if (!s || !props.sessionId) {
|
||||
toast.info('请先打开一个会话')
|
||||
return
|
||||
}
|
||||
if (missing.value.length > 0) {
|
||||
toast.error('请先填写全部占位符')
|
||||
return
|
||||
}
|
||||
// 先确保预览与实际一致:渲染在命令层统一做,前端不自己拼
|
||||
try {
|
||||
const rendered = await store.renderSnippet(s.id, values.value)
|
||||
preview.value = rendered
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const r = await store.runSnippet(props.sessionId, s.id, values.value, submit)
|
||||
if (submit) toast.success(r.message)
|
||||
else toast.info(r.message)
|
||||
} catch (e) {
|
||||
toast.error(`执行失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 危险片段强制执行一次确认(界面已限制,这是兜底) */
|
||||
function confirmThenRun() {
|
||||
const s = selected.value
|
||||
if (!s) return
|
||||
if (s.confirm && !window.confirm(`「${s.name}」被标记为需要确认的命令,确定执行?`)) return
|
||||
void run(true)
|
||||
}
|
||||
|
||||
// ===== 编辑 =====
|
||||
|
||||
const editing = ref(false)
|
||||
const draft = ref<CommandSnippet | null>(null)
|
||||
|
||||
function newSnippet() {
|
||||
draft.value = {
|
||||
id: '',
|
||||
name: '',
|
||||
command: '',
|
||||
description: '',
|
||||
group: '',
|
||||
defaults: {},
|
||||
shellKinds: [],
|
||||
sshOnly: false,
|
||||
confirm: false,
|
||||
pinned: false,
|
||||
createdAt: 0
|
||||
}
|
||||
editing.value = true
|
||||
}
|
||||
|
||||
function editSelected() {
|
||||
const s = selected.value
|
||||
if (!s) return
|
||||
// 去掉后端附加的 placeholders 字段 —— 它不是 CommandSnippet 的一部分,
|
||||
// 带着它回传会在 save 时触发未知字段告警(serde 默认忽略,但没必要)
|
||||
const { placeholders: _p, ...rest } = s
|
||||
draft.value = { ...rest }
|
||||
editing.value = true
|
||||
}
|
||||
|
||||
async function submitDraft() {
|
||||
const d = draft.value
|
||||
if (!d) return
|
||||
if (!d.name.trim()) {
|
||||
toast.error('名称不能为空')
|
||||
return
|
||||
}
|
||||
if (!d.command.trim()) {
|
||||
toast.error('命令内容不能为空')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await store.saveSnippet(d)
|
||||
editing.value = false
|
||||
toast.success('已保存')
|
||||
// 保存后刷新选中项(占位符可能变了)
|
||||
const fresh = store.snippets.find(s => s.id === (d.id || store.snippets[store.snippets.length - 1]?.id))
|
||||
if (fresh) select(fresh)
|
||||
} catch (e) {
|
||||
toast.error(`保存失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function removeSelected() {
|
||||
const s = selected.value
|
||||
if (!s) return
|
||||
if (!window.confirm(`确定删除片段「${s.name}」?`)) return
|
||||
try {
|
||||
await store.deleteSnippet(s.id)
|
||||
selected.value = null
|
||||
toast.success('已删除')
|
||||
} catch (e) {
|
||||
toast.error(`删除失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function togglePin() {
|
||||
const s = selected.value
|
||||
if (!s) return
|
||||
try {
|
||||
const { placeholders: _p, ...rest } = s
|
||||
await store.saveSnippet({ ...rest, pinned: !s.pinned })
|
||||
const fresh = store.snippets.find(x => x.id === s.id)
|
||||
if (fresh) select(fresh)
|
||||
} catch (e) {
|
||||
toast.error(`操作失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function restoreDefaults() {
|
||||
if (!window.confirm('将补回缺失的内置片段(不会覆盖你已有的条目),继续?')) return
|
||||
try {
|
||||
await store.restoreDefaultSnippets()
|
||||
toast.success('已恢复内置片段')
|
||||
} catch (e) {
|
||||
toast.error(`恢复失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 从本地文件导入命令文本(省去逐字敲长命令) */
|
||||
async function importFromFile() {
|
||||
try {
|
||||
const picked = await openDialog({
|
||||
multiple: false,
|
||||
directory: false,
|
||||
filters: [{ name: '文本/脚本', extensions: ['txt', 'sh', 'bash', 'zsh', 'ps1', 'cmd', 'bat'] }]
|
||||
})
|
||||
if (typeof picked !== 'string') return
|
||||
// 前端不直接读文件(CSP 下 WebView 读本地文件受限),
|
||||
// 让用户把内容粘进来 —— 这个流程在 P2 会改为走后端读文件。
|
||||
draft.value = {
|
||||
id: '',
|
||||
name: picked.replace(/\\/g, '/').split('/').pop() ?? '导入的片段',
|
||||
command: '',
|
||||
description: `待粘贴内容(来源:${picked})`,
|
||||
group: '导入',
|
||||
defaults: {},
|
||||
shellKinds: [],
|
||||
sshOnly: false,
|
||||
confirm: true,
|
||||
pinned: false,
|
||||
createdAt: 0
|
||||
}
|
||||
editing.value = true
|
||||
toast.info('请把命令内容粘贴到「命令」框中')
|
||||
void logger
|
||||
} catch (e) {
|
||||
toast.error(`导入失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- 作为模块 Tab 内容渲染(根不再是全屏浮层) -->
|
||||
<div class="flex flex-col h-full">
|
||||
<!-- ===== 头部 ===== -->
|
||||
<div class="shrink-0 flex items-center gap-2 px-3 h-9 border-b border-border">
|
||||
<Button variant="ghost" size="sm" class="h-7 text-xs" @click="emit('close')">返回终端</Button>
|
||||
<div class="w-px h-4 bg-border" />
|
||||
<BookMarked class="size-3.5 text-muted-foreground" />
|
||||
<span class="text-xs font-medium">命令片段</span>
|
||||
<span class="text-[10px] text-muted-foreground">
|
||||
{{ session ? `作用于 ${store.sessionLabel(session)}` : '未选择会话' }}
|
||||
</span>
|
||||
<div class="flex-1" />
|
||||
<Button variant="outline" size="sm" class="h-7 text-xs gap-1.5" @click="importFromFile">
|
||||
从文件导入
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" class="h-7 text-xs gap-1.5" @click="restoreDefaults">
|
||||
<RotateCcw class="size-3" />恢复内置
|
||||
</Button>
|
||||
<Button size="sm" class="h-7 text-xs gap-1.5" @click="newSnippet">
|
||||
<Plus class="size-3" />新建片段
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div class="flex-1 min-h-0 flex">
|
||||
<!-- ===== 左:列表 ===== -->
|
||||
<section class="w-[300px] shrink-0 border-r border-border flex flex-col">
|
||||
<div class="shrink-0 p-2 border-b border-border">
|
||||
<div class="relative">
|
||||
<Search class="absolute left-2 top-1/2 -translate-y-1/2 size-3 text-muted-foreground" />
|
||||
<Input v-model="filter" placeholder="搜索片段…" class="h-7 pl-7 text-xs" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex-1 min-h-0 overflow-auto">
|
||||
<div v-if="filtered.length === 0" class="p-4 text-center">
|
||||
<p class="text-[11px] text-muted-foreground/70">
|
||||
{{ available.length === 0 ? '当前会话没有可用的片段' : '无匹配项' }}
|
||||
</p>
|
||||
</div>
|
||||
<template v-else>
|
||||
<div v-for="[group, list] in grouped" :key="group">
|
||||
<div class="px-2.5 py-1 text-[10px] font-medium text-muted-foreground bg-muted/40 sticky top-0">
|
||||
{{ group }}
|
||||
</div>
|
||||
<button
|
||||
v-for="s in list"
|
||||
:key="s.id"
|
||||
class="w-full text-left px-2.5 py-1.5 hover:bg-accent border-l-2 transition-colors"
|
||||
:class="selected?.id === s.id ? 'bg-accent border-primary' : 'border-transparent'"
|
||||
@click="select(s)"
|
||||
>
|
||||
<div class="flex items-center gap-1.5">
|
||||
<Pin v-if="s.pinned" class="size-2.5 text-amber-500 shrink-0" />
|
||||
<span class="text-[11px] font-medium truncate">{{ s.name }}</span>
|
||||
<ShieldAlert v-if="s.confirm" class="size-2.5 text-destructive shrink-0" />
|
||||
</div>
|
||||
<div class="text-[10px] text-muted-foreground truncate font-mono mt-0.5">
|
||||
{{ s.command }}
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ===== 右:详情 / 参数填写 / 编辑 ===== -->
|
||||
<section class="flex-1 min-w-0 flex flex-col overflow-auto">
|
||||
<!-- ---------- 编辑态 ---------- -->
|
||||
<div v-if="editing && draft" class="p-4 space-y-3 max-w-2xl">
|
||||
<h3 class="text-sm font-medium">{{ draft.id ? '编辑片段' : '新建片段' }}</h3>
|
||||
|
||||
<label class="block space-y-1">
|
||||
<span class="text-[11px] text-muted-foreground">名称</span>
|
||||
<Input v-model="draft.name" class="h-7 text-xs" placeholder="如:查找大文件" />
|
||||
</label>
|
||||
|
||||
<label class="block space-y-1">
|
||||
<span class="text-[11px] text-muted-foreground">
|
||||
命令(用 <code class="font-mono">${name}</code> 表示占位符;
|
||||
需要字面量时写 <code class="font-mono">$${name}</code>)
|
||||
</span>
|
||||
<textarea
|
||||
v-model="draft.command"
|
||||
rows="3"
|
||||
class="w-full px-2 py-1.5 rounded-md border border-border bg-transparent
|
||||
text-xs font-mono outline-none focus:border-primary/60 resize-y"
|
||||
placeholder="find ${dir} -type f -size +${size}"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label class="block space-y-1">
|
||||
<span class="text-[11px] text-muted-foreground">说明(讲清做什么、有什么前提)</span>
|
||||
<Input v-model="draft.description" class="h-7 text-xs" />
|
||||
</label>
|
||||
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<label class="block space-y-1">
|
||||
<span class="text-[11px] text-muted-foreground">分组</span>
|
||||
<Input v-model="draft.group" class="h-7 text-xs" placeholder="如:文件 / 运维" />
|
||||
</label>
|
||||
<label class="block space-y-1">
|
||||
<span class="text-[11px] text-muted-foreground">
|
||||
适用 shell(逗号分隔,留空表示全部)
|
||||
</span>
|
||||
<Input
|
||||
:model-value="draft.shellKinds.join(',')"
|
||||
class="h-7 text-xs"
|
||||
placeholder="powershell,bash"
|
||||
@update:model-value="v => draft && (draft.shellKinds = String(v).split(',').map(x => x.trim()).filter(Boolean))"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-4 text-[11px]">
|
||||
<label class="flex items-center gap-1.5 cursor-pointer select-none">
|
||||
<input v-model="draft.sshOnly" type="checkbox" class="size-3 accent-primary" />
|
||||
仅 SSH 会话可用
|
||||
</label>
|
||||
<label class="flex items-center gap-1.5 cursor-pointer select-none">
|
||||
<input v-model="draft.confirm" type="checkbox" class="size-3 accent-primary" />
|
||||
执行前需确认(危险命令)
|
||||
</label>
|
||||
<label class="flex items-center gap-1.5 cursor-pointer select-none">
|
||||
<input v-model="draft.pinned" type="checkbox" class="size-3 accent-primary" />
|
||||
置顶
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="draft.confirm"
|
||||
class="flex items-start gap-2 p-2 rounded border border-destructive/40 bg-destructive/5"
|
||||
>
|
||||
<ShieldAlert class="size-3.5 text-destructive shrink-0 mt-0.5" />
|
||||
<p class="text-[11px] text-muted-foreground leading-relaxed">
|
||||
标记为「需确认」的片段默认只会**填入命令行**,不会自动执行 ——
|
||||
用户需要自己按回车。这避免了参数误填时立刻造成破坏。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2 pt-1">
|
||||
<Button size="sm" class="h-7 text-xs" @click="submitDraft">保存</Button>
|
||||
<Button variant="outline" size="sm" class="h-7 text-xs" @click="editing = false">取消</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ---------- 详情态 ---------- -->
|
||||
<div v-else-if="selected" class="p-4 space-y-3 max-w-2xl">
|
||||
<div class="flex items-center gap-2">
|
||||
<h3 class="text-sm font-medium">{{ selected.name }}</h3>
|
||||
<button
|
||||
class="text-muted-foreground hover:text-foreground"
|
||||
:title="selected.pinned ? '取消置顶' : '置顶'"
|
||||
@click="togglePin"
|
||||
>
|
||||
<Pin class="size-3.5" :class="selected.pinned ? 'text-amber-500' : ''" />
|
||||
</button>
|
||||
<div class="flex-1" />
|
||||
<Button variant="ghost" size="sm" class="h-6 text-[11px]" @click="editSelected">编辑</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-6 text-[11px] text-destructive"
|
||||
@click="removeSelected"
|
||||
>
|
||||
<Trash2 class="size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<p v-if="selected.description" class="text-[11px] text-muted-foreground leading-relaxed">
|
||||
{{ selected.description }}
|
||||
</p>
|
||||
|
||||
<div class="rounded-md border border-border bg-muted/30 p-2">
|
||||
<div class="text-[10px] text-muted-foreground mb-1">命令模板</div>
|
||||
<pre class="text-[11px] font-mono whitespace-pre-wrap break-all">{{ selected.command }}</pre>
|
||||
</div>
|
||||
|
||||
<!-- 占位符填写 -->
|
||||
<div v-if="selected.placeholders.length > 0" class="space-y-2">
|
||||
<div class="text-[11px] font-medium">参数</div>
|
||||
<div
|
||||
v-for="p in selected.placeholders"
|
||||
:key="p"
|
||||
class="flex items-center gap-2"
|
||||
>
|
||||
<span class="text-[11px] font-mono text-muted-foreground w-24 shrink-0 truncate" :title="p">
|
||||
${ {{ p }} }
|
||||
</span>
|
||||
<Input
|
||||
v-model="values[p]"
|
||||
class="h-7 text-xs font-mono flex-1"
|
||||
:placeholder="selected.defaults[p] || '(必填)'"
|
||||
@keydown.enter="doRender"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 预览 -->
|
||||
<div class="space-y-1.5">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-[11px] font-medium">预览</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="h-6 text-[11px]"
|
||||
:disabled="rendering"
|
||||
@click="doRender"
|
||||
>
|
||||
生成预览
|
||||
</Button>
|
||||
<span v-if="missing.length > 0" class="text-[10px] text-amber-600">
|
||||
还有 {{ missing.length }} 个未填写
|
||||
</span>
|
||||
</div>
|
||||
<pre
|
||||
v-if="preview"
|
||||
class="rounded-md border border-border bg-muted/30 p-2 text-[11px] font-mono
|
||||
whitespace-pre-wrap break-all"
|
||||
>{{ preview }}</pre>
|
||||
<p v-else class="text-[11px] text-muted-foreground/60">点「生成预览」查看实际会执行的命令</p>
|
||||
</div>
|
||||
|
||||
<!-- 执行 -->
|
||||
<div class="flex items-center gap-2 pt-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="h-7 text-xs gap-1.5"
|
||||
:disabled="!sessionId"
|
||||
@click="run(false)"
|
||||
>
|
||||
<Terminal class="size-3" />填入命令行
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
class="h-7 text-xs gap-1.5"
|
||||
:disabled="!sessionId || selected.confirm"
|
||||
:title="selected.confirm ? '该片段被标记为需确认,请用「确认并执行」' : ''"
|
||||
@click="run(true)"
|
||||
>
|
||||
<Play class="size-3" />直接执行
|
||||
</Button>
|
||||
<Button
|
||||
v-if="selected.confirm"
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
class="h-7 text-xs gap-1.5"
|
||||
:disabled="!sessionId"
|
||||
@click="confirmThenRun"
|
||||
>
|
||||
<ShieldAlert class="size-3" />确认并执行
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ---------- 空态 ---------- -->
|
||||
<div v-else class="flex-1 flex items-center justify-center">
|
||||
<div class="text-center">
|
||||
<BookMarked class="size-10 text-muted-foreground/20 mx-auto mb-3" />
|
||||
<p class="text-xs text-muted-foreground mb-1">从左侧选择一个片段</p>
|
||||
<p class="text-[11px] text-muted-foreground/60">
|
||||
或点「新建片段」加入自己的常用命令
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<!-- 悬浮关闭按钮(右上角已有「返回终端」,这里给键盘外的第二入口) -->
|
||||
<button
|
||||
class="absolute top-2 right-2 size-6 rounded flex items-center justify-center
|
||||
text-muted-foreground hover:text-foreground"
|
||||
title="关闭"
|
||||
@click="emit('close')"
|
||||
>
|
||||
<X class="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,184 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 会话模板面板(P2):一键拉起一组会话 + 布局。
|
||||
*
|
||||
* # 模板的捕获语义
|
||||
*
|
||||
* 「保存当前布局」捕获的是**当前可见的面板集合**(`paneIds`),
|
||||
* 而不是全部会话 —— 用户对着屏幕说「我要的就是现在这个样子」,
|
||||
* 屏幕上看得见的就是全部语义。拉起时按相同顺序重建:
|
||||
* 第 1 个作主面板,其余加分屏(超上限的条目被忽略)。
|
||||
*
|
||||
* # 为什么拉起逻辑在 TerminalModule 而不在这里
|
||||
*
|
||||
* 开会话(newSshTab / newLocalTab)与布局(addPane / resetPanesTo)
|
||||
* 都是编排组合函数的状态,归 TerminalModule 所有;本组件只负责
|
||||
* 模板的增删与展示,`apply` 事件把模板交回去。
|
||||
*/
|
||||
import { computed, ref } from 'vue'
|
||||
import { LayoutTemplate, Play, Plus, Trash2 } from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { useTerminalStore } from '@/stores/terminalStore'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from '@/components/ui/dialog'
|
||||
import type { SessionTemplate, TemplateEntry } from '@/types/terminal'
|
||||
|
||||
const store = useTerminalStore()
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
/** 当前可见面板的会话 id(用于「保存当前布局」),按显示顺序 */
|
||||
paneIds: string[]
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:open', v: boolean): void
|
||||
/** 用户点击「拉起」:交出模板,由 TerminalModule 执行开会话 + 布局 */
|
||||
(e: 'apply', template: SessionTemplate): void
|
||||
}>()
|
||||
|
||||
const templates = computed(() => store.settings?.templates ?? [])
|
||||
|
||||
const newName = ref('')
|
||||
const saving = ref(false)
|
||||
|
||||
/** 从当前可见面板构造条目(会话不存在时跳过并提示) */
|
||||
function captureEntries(): TemplateEntry[] | null {
|
||||
const out: TemplateEntry[] = []
|
||||
for (const id of props.paneIds) {
|
||||
const s = store.sessionById(id)
|
||||
if (!s) continue
|
||||
out.push({
|
||||
kind: s.kind,
|
||||
targetId: s.targetId,
|
||||
label: s.title
|
||||
})
|
||||
}
|
||||
if (out.length === 0) {
|
||||
toast.error('当前没有可捕获的会话面板')
|
||||
return null
|
||||
}
|
||||
if (out.length > 4) {
|
||||
toast.error('当前布局超过 4 个面板,无法保存为模板(上限 4)')
|
||||
return null
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
async function saveCurrent() {
|
||||
const entries = captureEntries()
|
||||
if (!entries) return
|
||||
const name = newName.value.trim()
|
||||
if (!name) {
|
||||
toast.error('请填写模板名称')
|
||||
return
|
||||
}
|
||||
saving.value = true
|
||||
try {
|
||||
await store.saveTemplate({ id: '', name, createdAt: 0, entries })
|
||||
newName.value = ''
|
||||
toast.success(`模板「${name}」已保存`)
|
||||
} catch (e) {
|
||||
toast.error(`保存失败:${String(e)}`)
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function removeOne(t: SessionTemplate) {
|
||||
try {
|
||||
await store.deleteTemplate(t.id)
|
||||
toast.success(`模板「${t.name}」已删除`)
|
||||
} catch (e) {
|
||||
toast.error(`删除失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
function apply(t: SessionTemplate) {
|
||||
emit('apply', t)
|
||||
emit('update:open', false)
|
||||
}
|
||||
|
||||
/** 条目展示名:target 失效时给出可辨识的标注(拉起时该条目会失败) */
|
||||
function entryLabel(t: SessionTemplate): string {
|
||||
return t.entries
|
||||
.map(e => {
|
||||
const alive =
|
||||
e.kind === 'ssh'
|
||||
? store.hosts.some(h => h.config.id === e.targetId)
|
||||
: store.shells.some(sh => sh.id === e.targetId)
|
||||
return alive ? e.label : `${e.label || '未知目标'}(已失效)`
|
||||
})
|
||||
.join(' + ')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog :open="open" @update:open="v => emit('update:open', v)">
|
||||
<DialogContent class="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle class="flex items-center gap-2 text-base">
|
||||
<LayoutTemplate class="size-4" />会话模板
|
||||
</DialogTitle>
|
||||
<DialogDescription class="text-xs">
|
||||
把常用的一组会话存成模板,一键拉起并自动排好布局。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<!-- ===== 模板列表 ===== -->
|
||||
<div class="space-y-1.5 min-h-[60px]">
|
||||
<p v-if="templates.length === 0" class="text-xs text-muted-foreground">
|
||||
还没有模板。先摆好想要的分屏布局,然后在下方保存为模板。
|
||||
</p>
|
||||
<div
|
||||
v-for="t in templates"
|
||||
:key="t.id"
|
||||
class="flex items-center gap-2 rounded border border-border px-2.5 py-1.5"
|
||||
>
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="text-xs font-medium truncate">{{ t.name }}</p>
|
||||
<p class="text-[10px] text-muted-foreground truncate">{{ entryLabel(t) }}</p>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" class="h-7 gap-1 text-xs shrink-0" @click="apply(t)">
|
||||
<Play class="size-3" />拉起
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-7 w-7 p-0 text-destructive hover:text-destructive shrink-0"
|
||||
title="删除模板"
|
||||
@click="removeOne(t)"
|
||||
>
|
||||
<Trash2 class="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== 保存当前布局 ===== -->
|
||||
<div class="space-y-2 rounded-md border border-border p-3">
|
||||
<Label class="text-[11px] text-muted-foreground">
|
||||
保存当前布局({{ paneIds.length }} 个面板,取前 4 个)
|
||||
</Label>
|
||||
<div class="flex gap-1.5">
|
||||
<Input
|
||||
v-model="newName"
|
||||
placeholder="模板名称,例如:开发环境"
|
||||
class="h-8 text-sm flex-1"
|
||||
@keydown.enter="saveCurrent"
|
||||
/>
|
||||
<Button size="sm" class="h-8 gap-1 text-xs shrink-0" :disabled="saving" @click="saveCurrent">
|
||||
<Plus class="size-3.5" />{{ saving ? '保存中…' : '保存' }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,217 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 终端面板:一个 xterm 实例 ↔ 一个会话。
|
||||
*
|
||||
* 这是整条链路的汇合点——Rust 的字节流、xterm 的渲染、键盘输入的回传
|
||||
* 都在这里对接。其余组件(标签栏、侧栏、工具栏)都只是它的外围装饰。
|
||||
*
|
||||
* # 为什么不在卸载时关闭会话
|
||||
*
|
||||
* 组件卸载的触发场景很多(切标签、切模块、关闭独立窗口),但**没有一个是
|
||||
* 「用户想结束这个会话」**。真正的结束只有两条路径:显式点关闭按钮、
|
||||
* 或 shell 自己退出。把组件生命周期与会话生命周期绑定,会导致切标签就断连。
|
||||
*/
|
||||
import { computed, onMounted, ref, toRef, watch, nextTick } from 'vue'
|
||||
import { useTerminalStore } from '@/stores/terminalStore'
|
||||
import { useXterm } from '@/composables/useXterm'
|
||||
import { resolveTheme } from '@/lib/terminalThemes'
|
||||
import type { AppearanceSettings } from '@/types/terminal'
|
||||
|
||||
const props = defineProps<{
|
||||
sessionId: string
|
||||
appearance: AppearanceSettings | null
|
||||
/** 面板是否可见(非激活标签为 false;不可见时应挂起渲染压力) */
|
||||
visible: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
/** 面板内的右键菜单请求(由父组件统一渲染菜单位置) */
|
||||
(e: 'contextmenu', payload: { sessionId: string; x: number; y: number }): void
|
||||
/** 面板获得焦点(父组件据此更新 activeSessionId) */
|
||||
(e: 'focus', sessionId: string): void
|
||||
}>()
|
||||
|
||||
const store = useTerminalStore()
|
||||
|
||||
const containerRef = ref<HTMLElement | null>(null)
|
||||
|
||||
const sessionInfo = computed(() => store.sessionById(props.sessionId))
|
||||
/** 会话已结束 → 面板转为只读回放 */
|
||||
const isReadonly = computed(() => {
|
||||
const s = sessionInfo.value?.state
|
||||
return s === 'closed' || s === 'failed'
|
||||
})
|
||||
|
||||
const {
|
||||
hasOutput,
|
||||
createTerminal,
|
||||
focus,
|
||||
fit,
|
||||
getSelection,
|
||||
clear,
|
||||
scrollToBottom,
|
||||
selectAll,
|
||||
selectWordAt,
|
||||
findNext,
|
||||
findPrevious,
|
||||
clearSearch
|
||||
} = useXterm({
|
||||
container: containerRef,
|
||||
sessionId: toRef(props, 'sessionId'),
|
||||
appearance: toRef(props, 'appearance'),
|
||||
readonly: isReadonly
|
||||
})
|
||||
|
||||
// ===== 挂载 =====
|
||||
|
||||
onMounted(async () => {
|
||||
// nextTick:父组件用 v-if 控制面板时,挂载瞬间容器可能还没进 DOM
|
||||
await nextTick()
|
||||
createTerminal()
|
||||
})
|
||||
|
||||
// 容器从隐藏变可见时必须重新 fit:
|
||||
// 隐藏时 offsetWidth/offsetHeight 都是 0,fit 会算出 0 列 0 行(或被跳过),
|
||||
// 导致切回来时终端显示成一条细线。
|
||||
watch(
|
||||
() => props.visible,
|
||||
async v => {
|
||||
if (!v) return
|
||||
await nextTick()
|
||||
fit()
|
||||
focus()
|
||||
}
|
||||
)
|
||||
|
||||
// ===== 交互 =====
|
||||
|
||||
function onMouseDown() {
|
||||
emit('focus', props.sessionId)
|
||||
}
|
||||
|
||||
function onContextMenu(e: MouseEvent) {
|
||||
e.preventDefault()
|
||||
emit('contextmenu', { sessionId: props.sessionId, x: e.clientX, y: e.clientY })
|
||||
}
|
||||
|
||||
/** 状态徽标文案与配色 */
|
||||
const stateBadge = computed(() => {
|
||||
const s = sessionInfo.value?.state
|
||||
switch (s) {
|
||||
case 'connecting':
|
||||
return { text: '连接中', cls: 'bg-amber-500/15 text-amber-600 dark:text-amber-400' }
|
||||
case 'authenticating':
|
||||
return { text: '认证中', cls: 'bg-amber-500/15 text-amber-600 dark:text-amber-400' }
|
||||
case 'established':
|
||||
return { text: '已连接', cls: 'bg-emerald-500/15 text-emerald-600 dark:text-emerald-400' }
|
||||
case 'degraded':
|
||||
return { text: '不稳定', cls: 'bg-orange-500/15 text-orange-600 dark:text-orange-400' }
|
||||
case 'closed':
|
||||
return { text: '已结束', cls: 'bg-muted text-muted-foreground' }
|
||||
case 'failed':
|
||||
return { text: '失败', cls: 'bg-red-500/15 text-red-600 dark:text-red-400' }
|
||||
default:
|
||||
return { text: '空闲', cls: 'bg-muted text-muted-foreground' }
|
||||
}
|
||||
})
|
||||
|
||||
/** 失败原因(展示在面板中央,比只在日志里更有用) */
|
||||
const errorText = computed(() => sessionInfo.value?.error ?? '')
|
||||
|
||||
/**
|
||||
* 面板背景色 = 当前终端主题的 background。
|
||||
*
|
||||
* 之前 `--terminal-bg` 只在 CSS 里给了一个近黑色的回退值而**从未被赋值**:
|
||||
* 浅色主题下 xterm 屏幕是浅色,但容器的 padding(上 4px/左 6px)与行列取整
|
||||
* 的边缘露出的是这个深色底 —— 表现为终端四周固定的黑线。跟随主题后,
|
||||
* 露出的部分与屏幕同色,视觉上无缝。
|
||||
*/
|
||||
const paneBackground = computed(() => {
|
||||
const theme = resolveTheme(props.appearance?.theme ?? 'vscode-dark')
|
||||
return theme.background ?? '#1e1e1e'
|
||||
})
|
||||
|
||||
defineExpose({
|
||||
focus,
|
||||
fit,
|
||||
getSelection,
|
||||
clear,
|
||||
scrollToBottom,
|
||||
/** 全选当前缓冲内容(右键菜单用) */
|
||||
selectAll,
|
||||
/** 选中指定屏幕坐标处的词(右键「选择词语」用) */
|
||||
selectWordAt,
|
||||
/** 在滚动缓冲里查找(返回是否命中),供工具栏搜索使用 */
|
||||
findNext,
|
||||
findPrevious,
|
||||
clearSearch
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="relative h-full w-full overflow-hidden"
|
||||
:style="{ backgroundColor: paneBackground }"
|
||||
@mousedown="onMouseDown"
|
||||
@contextmenu="onContextMenu"
|
||||
>
|
||||
<!-- xterm 挂载点。不加 padding:xterm 自己会算内边距,
|
||||
外面套 padding 会让 fit 算出的行列数与实际渲染尺寸不一致,导致右侧被裁切 -->
|
||||
<div ref="containerRef" class="h-full w-full" />
|
||||
|
||||
<!-- 连接中/首个输出未到的加载态:盖在终端上,避免用户看到一片空白 -->
|
||||
<div
|
||||
v-if="!hasOutput && sessionInfo && sessionInfo.state !== 'established'"
|
||||
class="absolute inset-0 flex items-center justify-center pointer-events-none"
|
||||
>
|
||||
<div class="flex flex-col items-center gap-3 px-6 text-center">
|
||||
<div
|
||||
class="size-5 rounded-full border-2 border-muted-foreground/30 border-t-foreground animate-spin"
|
||||
/>
|
||||
<p class="text-xs text-muted-foreground">
|
||||
{{ sessionInfo.state === 'failed' ? '连接失败' : '正在建立连接…' }}
|
||||
</p>
|
||||
<p v-if="errorText" class="max-w-md text-xs text-red-500 leading-relaxed">
|
||||
{{ errorText }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 会话已结束的角标(保留回放内容,提示这是因为进程退出而非断线) -->
|
||||
<div
|
||||
v-if="isReadonly && hasOutput"
|
||||
class="absolute top-2 right-2 px-2 py-0.5 rounded text-[10px] pointer-events-none"
|
||||
:class="stateBadge.cls"
|
||||
>
|
||||
{{ stateBadge.text }}
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* xterm v6 把主题背景色注入到内层 .xterm-scrollable-element,而外层
|
||||
.xterm-viewport 仍是 xterm.css 的默认 background-color:#000,且不再被
|
||||
主题覆盖 —— 网格未覆盖的边缘(padding、行列取整)露出这层纯黑,浅色
|
||||
主题下表现为固定的黑线,粗细随行列取整变化。置为透明后由面板根元素
|
||||
(已绑定主题 background)透出,任意主题下无缝。 */
|
||||
:deep(.xterm-viewport) {
|
||||
background-color: transparent !important;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
:deep(.xterm-viewport)::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
:deep(.xterm-viewport)::-webkit-scrollbar-thumb {
|
||||
background: color-mix(in srgb, currentColor 25%, transparent);
|
||||
border-radius: 4px;
|
||||
}
|
||||
:deep(.xterm-viewport)::-webkit-scrollbar-thumb:hover {
|
||||
background: color-mix(in srgb, currentColor 40%, transparent);
|
||||
}
|
||||
/* xterm 的 screen 默认会撑出父容器,这里强制贴合 */
|
||||
:deep(.xterm) {
|
||||
height: 100%;
|
||||
padding: 4px 0 4px 6px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,922 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 终端设置面板。
|
||||
*
|
||||
* # 五个分区的划分依据
|
||||
*
|
||||
* | 分区 | 回答的问题 |
|
||||
* |---|---|
|
||||
* | 外观 | 「终端长什么样」 |
|
||||
* | 行为 | 「终端和鼠标/剪贴板怎么互动」 |
|
||||
* | 布局 | 「窗口怎么组织」 |
|
||||
* | 快捷键 | 「键盘能做什么」 |
|
||||
* | 安全 | 「什么情况下应该拦住我」 |
|
||||
*
|
||||
* # 保存策略:分区独立落盘 + 即时生效
|
||||
*
|
||||
* 每个分区调各自的后端命令(`save_appearance` / `save_layout` / …),
|
||||
* 而不是攒成一份完整设置一次提交。理由:
|
||||
* 1. 后端各分区是独立的 Mutex 保护单元,合并提交需要前端持有完整快照,
|
||||
* 而快照可能与后端正在被其它窗口改的状态冲突(谁后写谁赢,丢失更新)。
|
||||
* 2. 用户在「外观」里调字号,不应该因为「快捷键」区有一处未填完而保存失败。
|
||||
*
|
||||
* 无保存按钮:本地草稿 + 深度 watch + 400ms 防抖写回(与其他模块的
|
||||
* 「设置即时生效」规范一致),成功不提示、仅失败提示。
|
||||
*
|
||||
* # 快捷键录制
|
||||
*
|
||||
* 录制时必须**阻止默认行为**(`preventDefault`)——否则按 `Ctrl+Shift+T`
|
||||
* 想绑到「新建标签」时,浏览器/WebView 会先执行自己的动作。
|
||||
* 同时用捕获阶段监听,抢在 xterm 的输入处理之前拿到事件。
|
||||
*/
|
||||
import { computed, nextTick, onBeforeUnmount, reactive, ref, watch } from 'vue'
|
||||
import {
|
||||
AlertTriangle,
|
||||
Keyboard,
|
||||
Layout,
|
||||
Monitor,
|
||||
MousePointerClick,
|
||||
Palette,
|
||||
RefreshCw,
|
||||
RotateCcw,
|
||||
ShieldAlert,
|
||||
Trash2
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { useTerminalStore } from '@/stores/terminalStore'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Slider } from '@/components/ui/slider'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from '@/components/ui/dialog'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { ACTION_GROUPS, ACTION_MAP, eventToShortcut, TERMINAL_ACTIONS } from '@/lib/terminalActions'
|
||||
import { TERMINAL_THEME_OPTIONS } from '@/lib/terminalThemes'
|
||||
import type {
|
||||
AppearanceSettings,
|
||||
LayoutSettings,
|
||||
SecuritySettings,
|
||||
SelectionSettings,
|
||||
ShellProfile,
|
||||
ShortcutBinding
|
||||
} from '@/types/terminal'
|
||||
|
||||
const logger = createLogger('terminal')
|
||||
const store = useTerminalStore()
|
||||
|
||||
type Section = 'appearance' | 'behavior' | 'layout' | 'shortcuts' | 'security' | 'shells'
|
||||
|
||||
const section = ref<Section>('appearance')
|
||||
|
||||
const SECTIONS: Array<{ id: Section; label: string; icon: unknown }> = [
|
||||
{ id: 'appearance', label: '外观', icon: Palette },
|
||||
{ id: 'behavior', label: '行为', icon: MousePointerClick },
|
||||
{ id: 'layout', label: '布局', icon: Layout },
|
||||
{ id: 'shells', label: 'Shell', icon: Monitor },
|
||||
{ id: 'shortcuts', label: '快捷键', icon: Keyboard },
|
||||
{ id: 'security', label: '安全', icon: ShieldAlert }
|
||||
]
|
||||
|
||||
// ===== 本地草稿 =====
|
||||
//
|
||||
// 不直接 v-model 到 store.settings:后端保存是异步的,若直接绑在 store 上,
|
||||
// 每次拖滑块都会发一次 IPC。这里用本地草稿 + 显式保存按钮(滑块用防抖)。
|
||||
|
||||
const appearance = reactive<AppearanceSettings>({
|
||||
theme: 'vscode-dark',
|
||||
followAppTheme: true,
|
||||
fontFamily: '',
|
||||
fontSize: 14,
|
||||
lineHeight: 1.2,
|
||||
letterSpacing: 0,
|
||||
cursorStyle: 'block',
|
||||
cursorBlink: true,
|
||||
scrollback: 10000,
|
||||
opacity: 100,
|
||||
gpuRendering: true
|
||||
})
|
||||
|
||||
const layout = reactive<LayoutSettings>({
|
||||
confirmCloseRunning: true,
|
||||
inheritCwd: false,
|
||||
sidebarOpen: true,
|
||||
sidebarWidth: 240,
|
||||
showStatusBar: true,
|
||||
maxPanes: 1
|
||||
})
|
||||
|
||||
const selection = reactive<SelectionSettings>({
|
||||
copyOnSelect: false,
|
||||
middleClickPaste: true,
|
||||
rightClick: 'menu',
|
||||
trimTrailingNewline: true
|
||||
})
|
||||
|
||||
const security = reactive<SecuritySettings>({
|
||||
hostKeyPolicy: 'ask',
|
||||
blockOnFingerprintChange: true,
|
||||
auditLog: true
|
||||
})
|
||||
|
||||
/** 快捷键草稿(数组需整体替换才能触发响应) */
|
||||
const shortcuts = ref<ShortcutBinding[]>([])
|
||||
|
||||
/** store → 草稿同步期间为 true:此时触发的 watch 是回声,不能写回 */
|
||||
const syncing = ref(false)
|
||||
|
||||
/** 把 store 里的设置同步到本地草稿 */
|
||||
function syncFromStore() {
|
||||
const s = store.settings
|
||||
if (!s) return
|
||||
syncing.value = true
|
||||
Object.assign(appearance, s.appearance)
|
||||
Object.assign(layout, s.layout)
|
||||
Object.assign(selection, s.selection)
|
||||
Object.assign(security, s.security)
|
||||
// 后端可能缺少某些动作的绑定(旧版本设置文件),用前端默认值补齐
|
||||
const byAction = new Map(s.shortcuts.map(b => [b.action, b]))
|
||||
shortcuts.value = TERMINAL_ACTIONS.map(a => {
|
||||
const existing = byAction.get(a.id)
|
||||
return existing
|
||||
? { ...existing }
|
||||
: { action: a.id, keys: a.defaultKeys, enabled: true }
|
||||
})
|
||||
// 回声保护:深度 watch 的回调在本轮 flush(渲染前)执行,届时 syncing 必须仍为
|
||||
// true 才会被跳过;nextTick 回调排在 flush 之后,用来复位。
|
||||
nextTick(() => {
|
||||
syncing.value = false
|
||||
})
|
||||
}
|
||||
|
||||
watch(() => store.settings, syncFromStore, { immediate: true, deep: false })
|
||||
|
||||
// ===== 保存:即时生效(本地草稿 + 400ms 防抖写回) =====
|
||||
//
|
||||
// 与 proxy/clipboard/downloader 模块的规范一致:无保存按钮,改动落进草稿后
|
||||
// 由深度 watch 防抖写回后端;成功不提示,仅失败提示。
|
||||
// 拖动滑块会连续触发几十次变更,防抖把「每步一次 IPC + 落盘」收敛为停手后一次。
|
||||
|
||||
/** 各分区的防抖计时器(互不干扰:改外观不会顺带重写行为设置) */
|
||||
const saveTimers = new Map<Section, ReturnType<typeof setTimeout>>()
|
||||
|
||||
function debouncedSave(sectionId: Section, fn: () => Promise<unknown>) {
|
||||
const old = saveTimers.get(sectionId)
|
||||
if (old) clearTimeout(old)
|
||||
saveTimers.set(
|
||||
sectionId,
|
||||
setTimeout(() => {
|
||||
saveTimers.delete(sectionId)
|
||||
fn().catch(e => {
|
||||
logger.error(`保存设置失败(${sectionId}):${String(e)}`)
|
||||
toast.error(`保存失败:${String(e)}`)
|
||||
})
|
||||
}, 400)
|
||||
)
|
||||
}
|
||||
|
||||
watch(
|
||||
appearance,
|
||||
() => {
|
||||
if (syncing.value) return
|
||||
debouncedSave('appearance', () => store.saveAppearance({ ...appearance }))
|
||||
},
|
||||
{ deep: true }
|
||||
)
|
||||
|
||||
watch(
|
||||
layout,
|
||||
() => {
|
||||
if (syncing.value) return
|
||||
debouncedSave('layout', () => store.saveLayout({ ...layout }))
|
||||
},
|
||||
{ deep: true }
|
||||
)
|
||||
|
||||
watch(
|
||||
selection,
|
||||
() => {
|
||||
if (syncing.value) return
|
||||
debouncedSave('behavior', () => store.saveSelection({ ...selection }))
|
||||
},
|
||||
{ deep: true }
|
||||
)
|
||||
|
||||
watch(
|
||||
security,
|
||||
() => {
|
||||
if (syncing.value) return
|
||||
debouncedSave('security', () => store.saveSecurity({ ...security }))
|
||||
},
|
||||
{ deep: true }
|
||||
)
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
for (const t of saveTimers.values()) clearTimeout(t)
|
||||
saveTimers.clear()
|
||||
})
|
||||
|
||||
/** 快捷键:每次变更立即写回(低频且键位改动需要立刻反馈冲突检测的结果) */
|
||||
function persistShortcuts() {
|
||||
store.saveShortcuts(shortcuts.value.map(b => ({ ...b }))).catch(e => {
|
||||
logger.error(`保存快捷键失败:${String(e)}`)
|
||||
toast.error(`保存失败:${String(e)}`)
|
||||
})
|
||||
}
|
||||
|
||||
// ===== 快捷键录制 =====
|
||||
|
||||
/** 正在录制的动作 id */
|
||||
const recording = ref<string | null>(null)
|
||||
/** 录制中检测到的冲突 */
|
||||
const conflictOf = ref<string | null>(null)
|
||||
|
||||
async function startRecording(actionId: string) {
|
||||
recording.value = actionId
|
||||
conflictOf.value = null
|
||||
await nextTick()
|
||||
// 在 document 捕获阶段监听,抢在 xterm 与浏览器默认行为之前
|
||||
document.addEventListener('keydown', onRecordKey, true)
|
||||
}
|
||||
|
||||
function stopRecording() {
|
||||
recording.value = null
|
||||
conflictOf.value = null
|
||||
document.removeEventListener('keydown', onRecordKey, true)
|
||||
}
|
||||
|
||||
function onRecordKey(e: KeyboardEvent) {
|
||||
// 录制期间吞掉一切按键,包括 Esc(Esc 单独处理为取消)
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
|
||||
if (e.key === 'Escape') {
|
||||
stopRecording()
|
||||
return
|
||||
}
|
||||
|
||||
const keys = eventToShortcut(e)
|
||||
// 只按了修饰键:继续等待,不产出绑定
|
||||
if (!keys) return
|
||||
|
||||
const actionId = recording.value
|
||||
if (!actionId) return
|
||||
|
||||
// 冲突检测:同一键位已被别的动作占用
|
||||
const clash = shortcuts.value.find(b => b.action !== actionId && b.enabled && b.keys === keys)
|
||||
if (clash) {
|
||||
const other = ACTION_MAP[clash.action]
|
||||
conflictOf.value = `该键位已被「${other?.label ?? clash.action}」占用`
|
||||
// 不立即停止录制,让用户直接再按一个键
|
||||
return
|
||||
}
|
||||
|
||||
shortcuts.value = shortcuts.value.map(b => (b.action === actionId ? { ...b, keys } : b))
|
||||
stopRecording()
|
||||
persistShortcuts()
|
||||
}
|
||||
|
||||
function clearBinding(actionId: string) {
|
||||
shortcuts.value = shortcuts.value.map(b => (b.action === actionId ? { ...b, keys: '' } : b))
|
||||
persistShortcuts()
|
||||
}
|
||||
|
||||
function toggleBinding(actionId: string, enabled: boolean) {
|
||||
shortcuts.value = shortcuts.value.map(b => (b.action === actionId ? { ...b, enabled } : b))
|
||||
persistShortcuts()
|
||||
}
|
||||
|
||||
function resetShortcuts() {
|
||||
shortcuts.value = TERMINAL_ACTIONS.map(a => ({ action: a.id, keys: a.defaultKeys, enabled: true }))
|
||||
persistShortcuts()
|
||||
}
|
||||
|
||||
onBeforeUnmount(stopRecording)
|
||||
|
||||
/** 按分组组织快捷键(组内保持 TERMINAL_ACTIONS 的定义顺序) */
|
||||
const shortcutGroups = computed(() =>
|
||||
ACTION_GROUPS.map(g => ({
|
||||
group: g,
|
||||
items: shortcuts.value.filter(b => ACTION_MAP[b.action]?.group === g)
|
||||
})).filter(g => g.items.length > 0)
|
||||
)
|
||||
|
||||
/** 有效设置里是否有未绑定(keys 为空)的动作 */
|
||||
const unboundCount = computed(() => shortcuts.value.filter(b => !b.keys).length)
|
||||
|
||||
// ===== Shell 管理 =====
|
||||
|
||||
const pendingShellDelete = ref<ShellProfile | null>(null)
|
||||
const detecting = ref(false)
|
||||
|
||||
async function refreshShells() {
|
||||
detecting.value = true
|
||||
try {
|
||||
await store.refreshShells()
|
||||
toast.success('已重新探测系统 Shell')
|
||||
} catch (e) {
|
||||
toast.error(`探测失败:${String(e)}`)
|
||||
} finally {
|
||||
detecting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleShellEnabled(s: ShellProfile) {
|
||||
try {
|
||||
await store.saveShell({ ...s, enabled: !s.enabled })
|
||||
} catch (e) {
|
||||
toast.error(`操作失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function testShell(s: ShellProfile) {
|
||||
try {
|
||||
const r = await store.testShell(s.id)
|
||||
if (r.ok) toast.success(r.message)
|
||||
else toast.error(r.message)
|
||||
} catch (e) {
|
||||
toast.error(`测试失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function submitShellDelete() {
|
||||
const s = pendingShellDelete.value
|
||||
if (!s) return
|
||||
try {
|
||||
await store.deleteShell(s.id)
|
||||
toast.success(`已删除「${s.name}」`)
|
||||
pendingShellDelete.value = null
|
||||
} catch (e) {
|
||||
toast.error(`删除失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 外观预设 =====
|
||||
|
||||
/** 字体族预设(Windows 上可用的等宽字体) */
|
||||
/**
|
||||
* 「系统默认字体」在 Select 里的哨兵值。
|
||||
*
|
||||
* reka-ui 的 SelectItem **拒绝空字符串 value**(空串被保留用于「清空选择、
|
||||
* 显示 placeholder」语义,传入即抛错并中断组件更新——设置页整个失去响应)。
|
||||
* 因此草稿里的 `fontFamily: ''` 与 Select 的值之间用哨兵映射。
|
||||
*/
|
||||
const SYSTEM_FONT_VALUE = '__system_default__'
|
||||
|
||||
const FONT_PRESETS = [
|
||||
{ label: 'Cascadia Code(Windows Terminal 默认)', value: "'Cascadia Code', 'Cascadia Mono', Consolas, monospace" },
|
||||
{ label: 'Consolas', value: "Consolas, 'Courier New', monospace" },
|
||||
{ label: 'JetBrains Mono', value: "'JetBrains Mono', Consolas, monospace" },
|
||||
{ label: 'Fira Code', value: "'Fira Code', Consolas, monospace" },
|
||||
{ label: '等宽宋体 / 中易宋体', value: "'SimSun', 'NSimSun', monospace" },
|
||||
{ label: '系统默认', value: SYSTEM_FONT_VALUE }
|
||||
]
|
||||
|
||||
/** Select 绑定:'' ↔ 哨兵值的双向映射 */
|
||||
const fontFamilyValue = computed({
|
||||
get: () => appearance.fontFamily || SYSTEM_FONT_VALUE,
|
||||
set: (v: string) => {
|
||||
appearance.fontFamily = v === SYSTEM_FONT_VALUE ? '' : v
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-full">
|
||||
<!-- 分区导航 -->
|
||||
<aside class="w-40 shrink-0 border-r border-border py-2">
|
||||
<button
|
||||
v-for="s in SECTIONS"
|
||||
:key="s.id"
|
||||
class="w-full flex items-center gap-2 px-3 py-2 text-xs text-left transition-colors"
|
||||
:class="
|
||||
section === s.id
|
||||
? 'bg-accent text-accent-foreground font-medium'
|
||||
: 'text-muted-foreground hover:bg-accent/50 hover:text-foreground'
|
||||
"
|
||||
@click="section = s.id"
|
||||
>
|
||||
<component :is="s.icon" class="size-3.5 shrink-0" />
|
||||
{{ s.label }}
|
||||
</button>
|
||||
</aside>
|
||||
|
||||
<!-- 分区内容 -->
|
||||
<div class="flex-1 min-w-0 overflow-y-auto p-5">
|
||||
<!-- ===== 外观 ===== -->
|
||||
<div v-if="section === 'appearance'" class="space-y-5 max-w-2xl">
|
||||
<div>
|
||||
<h3 class="text-sm font-medium mb-1">外观</h3>
|
||||
<p class="text-xs text-muted-foreground">控制终端的配色、字体与渲染方式。</p>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">配色主题</Label>
|
||||
<Select v-model="appearance.theme">
|
||||
<SelectTrigger class="h-8 text-sm"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="t in TERMINAL_THEME_OPTIONS" :key="t.value" :value="t.value">
|
||||
{{ t.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div class="flex items-center justify-between pt-1.5">
|
||||
<div>
|
||||
<Label class="text-xs">跟随应用主题</Label>
|
||||
<p class="text-[11px] text-muted-foreground">
|
||||
应用切换到浅色/深色时,终端自动跟随(选择「跟随系统」时生效)
|
||||
</p>
|
||||
</div>
|
||||
<Switch v-model="appearance.followAppTheme" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">字体</Label>
|
||||
<Select v-model="fontFamilyValue">
|
||||
<SelectTrigger class="h-8 text-sm"><SelectValue placeholder="系统默认" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="f in FONT_PRESETS" :key="f.label" :value="f.value">
|
||||
{{ f.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p class="text-[11px] text-muted-foreground font-mono truncate">
|
||||
{{ appearance.fontFamily || '(系统默认等宽字体)' }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<div class="flex items-center justify-between">
|
||||
<Label class="text-xs">字号</Label>
|
||||
<span class="text-xs font-mono text-muted-foreground">{{ appearance.fontSize }} px</span>
|
||||
</div>
|
||||
<Slider
|
||||
:model-value="[appearance.fontSize]"
|
||||
:min="6"
|
||||
:max="48"
|
||||
:step="1"
|
||||
@update:model-value="(v: any) => { appearance.fontSize = Array.isArray(v) ? v[0] : Number(v) }"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<div class="flex items-center justify-between">
|
||||
<Label class="text-xs">行高</Label>
|
||||
<span class="text-xs font-mono text-muted-foreground">{{ appearance.lineHeight.toFixed(2) }}</span>
|
||||
</div>
|
||||
<Slider
|
||||
:model-value="[appearance.lineHeight]"
|
||||
:min="1"
|
||||
:max="2"
|
||||
:step="0.05"
|
||||
@update:model-value="(v: any) => { appearance.lineHeight = Array.isArray(v) ? v[0] : Number(v) }"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<div class="flex items-center justify-between">
|
||||
<Label class="text-xs">字间距</Label>
|
||||
<span class="text-xs font-mono text-muted-foreground">{{ appearance.letterSpacing }} px</span>
|
||||
</div>
|
||||
<Slider
|
||||
:model-value="[appearance.letterSpacing]"
|
||||
:min="-2"
|
||||
:max="4"
|
||||
:step="0.5"
|
||||
@update:model-value="(v: any) => { appearance.letterSpacing = Array.isArray(v) ? v[0] : Number(v) }"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-4">
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">光标样式</Label>
|
||||
<Select v-model="appearance.cursorStyle">
|
||||
<SelectTrigger class="h-8 text-sm"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="block">方块</SelectItem>
|
||||
<SelectItem value="bar">竖线</SelectItem>
|
||||
<SelectItem value="underline">下划线</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div class="flex items-end pb-1.5">
|
||||
<div class="flex items-center justify-between w-full">
|
||||
<Label class="text-xs">光标闪烁</Label>
|
||||
<Switch v-model="appearance.cursorBlink" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<div class="flex items-center justify-between">
|
||||
<Label class="text-xs">背景不透明度</Label>
|
||||
<span class="text-xs font-mono text-muted-foreground">{{ appearance.opacity }}%</span>
|
||||
</div>
|
||||
<Slider
|
||||
:model-value="[appearance.opacity]"
|
||||
:min="30"
|
||||
:max="100"
|
||||
:step="1"
|
||||
@update:model-value="(v: any) => { appearance.opacity = Array.isArray(v) ? v[0] : Number(v) }"
|
||||
/>
|
||||
<p v-if="appearance.opacity < 70" class="text-[11px] text-amber-600 dark:text-amber-400">
|
||||
过低的不透明度会让文字与背景内容混在一起,影响可读性。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-4">
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">回滚缓冲行数</Label>
|
||||
<Input v-model.number="appearance.scrollback" type="number" class="h-8 text-sm font-mono" />
|
||||
<p class="text-[11px] text-muted-foreground">内存占用与此成正比</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<Label class="text-xs">GPU 渲染(WebGL)</Label>
|
||||
<p class="text-[11px] text-muted-foreground">
|
||||
显著提升滚动流畅度;驱动异常时自动回退到 Canvas
|
||||
</p>
|
||||
</div>
|
||||
<Switch v-model="appearance.gpuRendering" />
|
||||
</div>
|
||||
<!-- 保存按钮已移除:改动经 400ms 防抖自动写回(即时生效) -->
|
||||
</div>
|
||||
|
||||
<!-- ===== 行为 ===== -->
|
||||
<div v-else-if="section === 'behavior'" class="space-y-5 max-w-2xl">
|
||||
<div>
|
||||
<h3 class="text-sm font-medium mb-1">行为</h3>
|
||||
<p class="text-xs text-muted-foreground">鼠标与剪贴板的交互方式。</p>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<Label class="text-xs">选中即复制</Label>
|
||||
<p class="text-[11px] text-muted-foreground">用鼠标选中文本后立即写入剪贴板(X11 习惯)</p>
|
||||
</div>
|
||||
<Switch v-model="selection.copyOnSelect" />
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<Label class="text-xs">中键粘贴</Label>
|
||||
<p class="text-[11px] text-muted-foreground">点击鼠标中键粘贴剪贴板内容</p>
|
||||
</div>
|
||||
<Switch v-model="selection.middleClickPaste" />
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">右键行为</Label>
|
||||
<Select v-model="selection.rightClick">
|
||||
<SelectTrigger class="h-8 text-sm"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="menu">弹出菜单</SelectItem>
|
||||
<SelectItem value="paste">粘贴</SelectItem>
|
||||
<SelectItem value="select-word">选中光标下的词</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<Label class="text-xs">复制时去掉行尾换行</Label>
|
||||
<p class="text-[11px] text-muted-foreground">
|
||||
复制单行命令时不带末尾换行,粘贴到 shell 不会立即执行
|
||||
</p>
|
||||
</div>
|
||||
<Switch v-model="selection.trimTrailingNewline" />
|
||||
</div>
|
||||
<!-- 保存按钮已移除:改动经 400ms 防抖自动写回(即时生效) -->
|
||||
</div>
|
||||
|
||||
<!-- ===== 布局 ===== -->
|
||||
<div v-else-if="section === 'layout'" class="space-y-5 max-w-2xl">
|
||||
<div>
|
||||
<h3 class="text-sm font-medium mb-1">布局</h3>
|
||||
<p class="text-xs text-muted-foreground">窗口与面板的组织方式。</p>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<Label class="text-xs">显示状态栏</Label>
|
||||
<p class="text-[11px] text-muted-foreground">底部显示会话、工作目录与终端尺寸</p>
|
||||
</div>
|
||||
<Switch v-model="layout.showStatusBar" />
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<Label class="text-xs">新会话继承当前目录</Label>
|
||||
<p class="text-[11px] text-muted-foreground">
|
||||
新建本地标签时,从当前会话的工作目录启动(需 shell 支持 OSC 7 上报)
|
||||
</p>
|
||||
</div>
|
||||
<Switch v-model="layout.inheritCwd" />
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<Label class="text-xs">关闭运行中的会话前确认</Label>
|
||||
<p class="text-[11px] text-muted-foreground">
|
||||
强烈建议保持开启 —— 一个正在跑的编译或部署任务被误关会很难受
|
||||
</p>
|
||||
</div>
|
||||
<Switch v-model="layout.confirmCloseRunning" />
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">面板数量上限</Label>
|
||||
<Select :model-value="String(layout.maxPanes)">
|
||||
<SelectTrigger class="h-8 text-sm"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="1">1(不分屏)</SelectItem>
|
||||
<SelectItem value="2">2</SelectItem>
|
||||
<SelectItem value="3">3</SelectItem>
|
||||
<SelectItem value="4">4</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p class="text-[11px] text-muted-foreground">
|
||||
分屏功能在后续版本提供,此处先确定上限
|
||||
</p>
|
||||
</div>
|
||||
<!-- 保存按钮已移除:改动经 400ms 防抖自动写回(即时生效) -->
|
||||
</div>
|
||||
|
||||
<!-- ===== Shell ===== -->
|
||||
<div v-else-if="section === 'shells'" class="space-y-5 max-w-3xl">
|
||||
<div class="flex items-start justify-between">
|
||||
<div>
|
||||
<h3 class="text-sm font-medium mb-1">本地 Shell</h3>
|
||||
<p class="text-xs text-muted-foreground">
|
||||
自动探测系统中可用的 Shell。禁用的 Shell 不会出现在新建会话的列表中。
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" class="h-7 gap-1.5 text-xs shrink-0" :disabled="detecting" @click="refreshShells">
|
||||
<RefreshCw class="size-3.5" :class="{ 'animate-spin': detecting }" />
|
||||
重新探测
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div v-if="store.shells.length === 0" class="py-12 text-center border border-dashed border-border rounded-md">
|
||||
<Monitor class="size-7 mx-auto text-muted-foreground/30 mb-2" />
|
||||
<p class="text-sm text-muted-foreground">未探测到可用 Shell</p>
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-1.5">
|
||||
<div
|
||||
v-for="s in store.shells"
|
||||
:key="s.id"
|
||||
class="group flex items-start gap-3 px-3 py-2.5 rounded-md border border-border
|
||||
hover:border-primary/40 transition-colors"
|
||||
>
|
||||
<Monitor class="size-4 shrink-0 mt-0.5 text-muted-foreground" />
|
||||
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<span class="text-sm font-medium truncate">{{ s.name }}</span>
|
||||
<span class="text-[10px] px-1.5 py-0.5 rounded bg-muted shrink-0">{{ s.kind }}</span>
|
||||
<span
|
||||
v-if="s.detected"
|
||||
class="text-[10px] px-1.5 py-0.5 rounded bg-sky-500/15 text-sky-700 dark:text-sky-400 shrink-0"
|
||||
>
|
||||
自动探测
|
||||
</span>
|
||||
<span
|
||||
v-if="s.id === store.settings?.lastShellId"
|
||||
class="text-[10px] px-1.5 py-0.5 rounded bg-emerald-500/15 text-emerald-700 dark:text-emerald-400 shrink-0"
|
||||
>
|
||||
默认
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-1 text-[11px] text-muted-foreground font-mono truncate" :title="s.path">
|
||||
{{ s.path }}
|
||||
<span v-if="s.args.length > 0" class="opacity-70">{{ s.args.join(' ') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="shrink-0 flex items-center gap-2">
|
||||
<Button
|
||||
v-if="s.id !== store.settings?.lastShellId"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-7 text-[11px] opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
title="设为默认 Shell"
|
||||
@click="store.setLastShell(s.id)"
|
||||
>
|
||||
设为默认
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-7 text-[11px] opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
@click="testShell(s)"
|
||||
>
|
||||
测试
|
||||
</Button>
|
||||
<Switch :model-value="s.enabled" @update:model-value="() => toggleShellEnabled(s)" />
|
||||
<Button
|
||||
v-if="!s.detected"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="size-7 opacity-0 group-hover:opacity-100 transition-opacity
|
||||
text-destructive hover:text-destructive"
|
||||
title="删除"
|
||||
@click="pendingShellDelete = s"
|
||||
>
|
||||
<Trash2 class="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="text-[11px] text-muted-foreground">
|
||||
自动探测到的 Shell 无法删除,只能禁用 —— 它们的路径来自系统,删掉也会在下次探测时重新出现。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- ===== 快捷键 ===== -->
|
||||
<div v-else-if="section === 'shortcuts'" class="space-y-5 max-w-3xl">
|
||||
<div class="flex items-start justify-between">
|
||||
<div>
|
||||
<h3 class="text-sm font-medium mb-1">终端内快捷键</h3>
|
||||
<p class="text-xs text-muted-foreground">
|
||||
仅在焦点位于终端面板内时生效。点击键位后按下新组合键即可修改。
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" class="h-7 gap-1.5 text-xs shrink-0" @click="resetShortcuts">
|
||||
<RotateCcw class="size-3.5" />恢复默认
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- 硬约束说明:这是最容易引起困惑的地方,必须显式写在界面上 -->
|
||||
<div class="flex items-start gap-2 p-2.5 rounded-md bg-muted text-[11px] text-muted-foreground">
|
||||
<AlertTriangle class="size-3.5 shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p>
|
||||
<span class="font-medium text-foreground">Ctrl+C 与 Ctrl+V 不可被占用</span>
|
||||
—— 终端中它们是「中断当前命令」与 shell 的粘贴键,映射成其它功能会导致无法中止任务。
|
||||
</p>
|
||||
<p class="mt-1">复制粘贴请使用 Ctrl+Shift+C / Ctrl+Shift+V。</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p v-if="unboundCount > 0" class="text-[11px] text-muted-foreground">
|
||||
有 {{ unboundCount }} 个动作未绑定键位。
|
||||
</p>
|
||||
|
||||
<div v-for="g in shortcutGroups" :key="g.group" class="space-y-1">
|
||||
<p class="text-[10px] uppercase tracking-wide text-muted-foreground px-1">{{ g.group }}</p>
|
||||
|
||||
<div
|
||||
v-for="b in g.items"
|
||||
:key="b.action"
|
||||
class="flex items-center gap-3 px-3 py-2 rounded-md border border-border"
|
||||
:class="recording === b.action ? 'border-primary bg-accent/40' : 'border-border'"
|
||||
>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="text-xs font-medium">{{ ACTION_MAP[b.action]?.label ?? b.action }}</div>
|
||||
<div class="text-[11px] text-muted-foreground truncate">
|
||||
{{ ACTION_MAP[b.action]?.description }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 键位录制按钮 -->
|
||||
<button
|
||||
class="shrink-0 min-w-[132px] h-7 px-2.5 rounded-md border text-[11px] font-mono
|
||||
transition-colors"
|
||||
:class="
|
||||
recording === b.action
|
||||
? 'border-primary bg-primary/10 text-primary'
|
||||
: b.keys
|
||||
? 'border-border hover:border-primary/50 hover:bg-accent/50'
|
||||
: 'border-dashed border-muted-foreground/40 text-muted-foreground hover:border-primary/50'
|
||||
"
|
||||
@click="recording === b.action ? stopRecording() : startRecording(b.action)"
|
||||
>
|
||||
<template v-if="recording === b.action">
|
||||
<span class="animate-pulse">按下组合键…</span>
|
||||
</template>
|
||||
<template v-else-if="b.keys">{{ b.keys }}</template>
|
||||
<template v-else>未绑定</template>
|
||||
</button>
|
||||
|
||||
<Button
|
||||
v-if="b.keys"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="size-7 shrink-0 text-muted-foreground"
|
||||
title="清除绑定"
|
||||
@click="clearBinding(b.action)"
|
||||
>
|
||||
<RotateCcw class="size-3.5" />
|
||||
</Button>
|
||||
<div v-else class="size-7 shrink-0" />
|
||||
|
||||
<Switch
|
||||
:model-value="b.enabled"
|
||||
class="shrink-0"
|
||||
@update:model-value="(v: boolean) => toggleBinding(b.action, v)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 录制冲突提示 -->
|
||||
<div
|
||||
v-if="conflictOf"
|
||||
class="fixed bottom-6 left-1/2 -translate-x-1/2 px-3 py-2 rounded-md
|
||||
bg-destructive text-destructive-foreground text-xs shadow-lg z-50"
|
||||
>
|
||||
{{ conflictOf }},请换一个键位
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== 安全 ===== -->
|
||||
<div v-else-if="section === 'security'" class="space-y-5 max-w-2xl">
|
||||
<div>
|
||||
<h3 class="text-sm font-medium mb-1">安全</h3>
|
||||
<p class="text-xs text-muted-foreground">主机密钥校验与审计。</p>
|
||||
</div>
|
||||
|
||||
<div class="rounded-md border border-border p-3 space-y-3">
|
||||
<div>
|
||||
<Label class="text-xs">主机密钥策略</Label>
|
||||
<p class="text-[11px] text-muted-foreground mt-0.5">
|
||||
本项目<span class="font-medium text-foreground">不提供「自动接受」</span>选项。
|
||||
首次连接必须人工核对指纹 —— 这是抵御中间人攻击的唯一有效手段。
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 px-2.5 py-2 rounded bg-muted">
|
||||
<ShieldAlert class="size-3.5 text-emerald-600 dark:text-emerald-400 shrink-0" />
|
||||
<span class="text-xs">询问并核对指纹(唯一策略)</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<Label class="text-xs">指纹变更时阻断连接</Label>
|
||||
<p class="text-[11px] text-muted-foreground">
|
||||
已记录的主机换了密钥时,默认拒绝连接,需用户显式核对后放行
|
||||
</p>
|
||||
</div>
|
||||
<Switch v-model="security.blockOnFingerprintChange" />
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<Label class="text-xs">记录安全事件</Label>
|
||||
<p class="text-[11px] text-muted-foreground">
|
||||
把主机密钥确认、指纹变更等事件写入日志,便于事后追溯
|
||||
</p>
|
||||
</div>
|
||||
<Switch v-model="security.auditLog" />
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="!security.blockOnFingerprintChange"
|
||||
class="flex items-start gap-2 p-2.5 rounded-md border border-amber-500/40 bg-amber-500/10"
|
||||
>
|
||||
<AlertTriangle class="size-3.5 shrink-0 mt-0.5 text-amber-600 dark:text-amber-400" />
|
||||
<p class="text-[11px] text-amber-700 dark:text-amber-400">
|
||||
关闭阻断后,主机密钥变更将不再自动拦截。若服务器被中间人替换,
|
||||
您可能在毫无提示的情况下连接到了错误的机器。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- 保存按钮已移除:改动经 400ms 防抖自动写回(即时生效) -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== Shell 删除确认 ===== -->
|
||||
<Dialog :open="pendingShellDelete !== null" @update:open="(v: boolean) => !v && (pendingShellDelete = null)">
|
||||
<DialogContent class="max-w-sm" :show-close-button="false">
|
||||
<DialogHeader>
|
||||
<DialogTitle class="text-base">删除 Shell</DialogTitle>
|
||||
<DialogDescription class="text-xs">
|
||||
将从列表中移除「{{ pendingShellDelete?.name }}」。这不影响系统上实际的可执行文件。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" size="sm" @click="pendingShellDelete = null">取消</Button>
|
||||
<Button variant="destructive" size="sm" @click="submitShellDelete">删除</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,190 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 终端状态栏:把「当前会话的客观事实」摆在最下面一行。
|
||||
*
|
||||
* 为什么需要它:终端是全屏沉浸式的界面,用户容易忘记自己在哪台机器、
|
||||
* 用哪个 shell、当前目录是什么。状态栏用最低的视觉权重承担这个职责。
|
||||
*
|
||||
* 设计取舍:这里**只放只读事实 + 一个例外**(编码选择器)。
|
||||
* 编码之所以破例:它是「读出来的事实」(当前用什么编码)和「需要就地改的开关」
|
||||
* (看到乱码要立刻切)这两重身份的合体。若挪进设置页,用户在 GBK 服务器上看到
|
||||
* 乱码时得先想「设置在哪」,而这个动作天然是「就在我看到乱码的那一行下面改」。
|
||||
* 其余任何可写设置都不该进状态栏 —— 那会让它退化成一个迷你设置面板。
|
||||
*/
|
||||
import { computed, ref } from 'vue'
|
||||
import { Globe, TerminalSquare, FolderOpen, Hash, Wifi, WifiOff, Cpu, Languages, Loader2 } from '@lucide/vue'
|
||||
import { useTerminalStore } from '@/stores/terminalStore'
|
||||
import { toast } from 'vue-sonner'
|
||||
import {
|
||||
ENCODING_OPTIONS,
|
||||
encodingShortLabel,
|
||||
isNonDefaultEncoding,
|
||||
type SessionInfo
|
||||
} from '@/types/terminal'
|
||||
|
||||
const store = useTerminalStore()
|
||||
|
||||
const props = defineProps<{
|
||||
session: SessionInfo | undefined
|
||||
/** 当前字号(含临时覆盖) */
|
||||
fontSize: number
|
||||
/** 终端实际行列数(由 xterm 上报,父组件透传) */
|
||||
cols?: number
|
||||
rows?: number
|
||||
}>()
|
||||
|
||||
const isSsh = computed(() => props.session?.kind === 'ssh')
|
||||
|
||||
const stateText = computed(() => {
|
||||
switch (props.session?.state) {
|
||||
case 'connecting':
|
||||
return '连接中'
|
||||
case 'authenticating':
|
||||
return '认证中'
|
||||
case 'established':
|
||||
return '已连接'
|
||||
case 'degraded':
|
||||
return '连接不稳定'
|
||||
case 'closed':
|
||||
return '已断开'
|
||||
case 'failed':
|
||||
return '连接失败'
|
||||
default:
|
||||
return '空闲'
|
||||
}
|
||||
})
|
||||
|
||||
const stateColor = computed(() => {
|
||||
switch (props.session?.state) {
|
||||
case 'established':
|
||||
return 'text-emerald-600 dark:text-emerald-400'
|
||||
case 'connecting':
|
||||
case 'authenticating':
|
||||
case 'degraded':
|
||||
return 'text-amber-600 dark:text-amber-400'
|
||||
case 'failed':
|
||||
return 'text-red-600 dark:text-red-400'
|
||||
default:
|
||||
return 'text-muted-foreground'
|
||||
}
|
||||
})
|
||||
|
||||
/** 会话标题(与标签栏一致的口径,统一走 store 的解析) */
|
||||
const title = computed(() => store.sessionLabel(props.session) || '无会话')
|
||||
|
||||
/** SSH 目标串 / 本地 shell 名 */
|
||||
const target = computed(() => store.sessionTarget(props.session))
|
||||
|
||||
// ===== 编码选择器 =====
|
||||
|
||||
/** 当前会话的编码(缺省按 utf-8 显示,避免旧会话快照没有该字段时闪空) */
|
||||
const encoding = computed(() => props.session?.encoding || 'utf-8')
|
||||
|
||||
/** 非默认编码时给视觉提示 —— 见 `isNonDefaultEncoding` 的说明 */
|
||||
const encodingAlert = computed(() => isNonDefaultEncoding(encoding.value))
|
||||
|
||||
/** 切换中(防止连点造成多次广播与状态错乱) */
|
||||
const switching = ref(false)
|
||||
|
||||
/**
|
||||
* 切换编码。
|
||||
*
|
||||
* 成功后**不清屏**:已渲染的历史字符是旧编码的解释结果,重绘需要后端保留的
|
||||
* 原始字节缓冲配合(当前 `OutputBatch` 的 ring buffer 尚未接到前端),
|
||||
* 所以新编码只对「之后的输出」生效。这一点必须让用户知道 ——
|
||||
* 否则他会看到「切了还是乱码」并认为功能坏了。
|
||||
*/
|
||||
async function onEncodingChange(value: unknown) {
|
||||
const sid = props.session?.id
|
||||
const next = String(value ?? '')
|
||||
if (!sid || !next || next === encoding.value) return
|
||||
|
||||
switching.value = true
|
||||
try {
|
||||
const norm = await store.setEncoding(sid, next)
|
||||
toast.success(`编码已切换为 ${norm}`, {
|
||||
description: '新编码对之后的输出生效;已显示的历史内容不会自动重绘,可执行 clear 后重新查看'
|
||||
})
|
||||
} catch (e) {
|
||||
// 失败时不改本地状态:后端返回的是权威值,UI 跟着后端走
|
||||
toast.error(`切换编码失败:${String(e)}`)
|
||||
} finally {
|
||||
switching.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="shrink-0 h-6 flex items-center gap-3 px-2.5 border-t border-border bg-card/20
|
||||
text-[10px] text-muted-foreground select-none"
|
||||
>
|
||||
<div class="flex items-center gap-1.5 min-w-0">
|
||||
<component :is="isSsh ? Globe : TerminalSquare" class="size-3 shrink-0" />
|
||||
<span class="truncate max-w-[200px]">{{ title }}</span>
|
||||
</div>
|
||||
|
||||
<span v-if="target" class="truncate max-w-[220px] opacity-80">{{ target }}</span>
|
||||
|
||||
<!-- shrink-0 + nowrap:状态栏 flex 项多,不加会被压缩到「已连接」逐字换行成竖排 -->
|
||||
<div class="flex items-center gap-1 shrink-0 whitespace-nowrap">
|
||||
<Wifi v-if="session?.state === 'established'" class="size-3" />
|
||||
<WifiOff v-else class="size-3 opacity-50" />
|
||||
<span :class="stateColor">{{ stateText }}</span>
|
||||
</div>
|
||||
|
||||
<div class="flex-1" />
|
||||
|
||||
<!--
|
||||
编码选择器:非默认编码时整块变琥珀色。
|
||||
只换文字不够 —— 「GBK」和「UTF-8」在 10px 字号下形状差异不明显,
|
||||
用户扫一眼不会注意到自己正在用非默认编码。
|
||||
-->
|
||||
<div
|
||||
v-if="session"
|
||||
class="flex items-center gap-0.5 shrink-0 rounded px-1 -mx-0.5 transition-colors"
|
||||
:class="encodingAlert
|
||||
? 'bg-amber-500/15 text-amber-700 dark:text-amber-400'
|
||||
: 'text-muted-foreground'"
|
||||
:title="encodingAlert
|
||||
? `当前使用非默认编码 ${encoding},中文乱码时可在此切换`
|
||||
: '切换字符编码'"
|
||||
>
|
||||
<Loader2 v-if="switching" class="size-3 animate-spin" />
|
||||
<Languages v-else class="size-3" />
|
||||
<!--
|
||||
用原生 select 而不是 shadcn 的 Select:后者是 Radix 实现,会在 body 末尾
|
||||
挂一个 portal 浮层,而状态栏处在终端容器的裁剪区内。10px 字号 + 状态栏
|
||||
这种「工具条」语境下,原生 select 的外观差异可以接受,换来的是不受
|
||||
浮层层级与裁剪影响 —— 这是稳定性优先于观感的一处取舍。
|
||||
-->
|
||||
<select
|
||||
:value="encoding"
|
||||
:disabled="switching"
|
||||
class="bg-transparent border-0 outline-none cursor-pointer appearance-none
|
||||
text-[10px] text-inherit pr-0.5 disabled:cursor-wait"
|
||||
@change="onEncodingChange(($event.target as HTMLSelectElement).value)"
|
||||
>
|
||||
<option v-for="opt in ENCODING_OPTIONS" :key="opt.value" :value="opt.value">
|
||||
{{ opt.label }}
|
||||
</option>
|
||||
</select>
|
||||
<span class="tabular-nums opacity-70">{{ encodingShortLabel(encoding) }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="session?.cwd" class="flex items-center gap-1 min-w-0 max-w-[45%]">
|
||||
<FolderOpen class="size-3 shrink-0" />
|
||||
<span class="truncate" :title="session.cwd">{{ session.cwd }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="cols && rows" class="flex items-center gap-1 shrink-0">
|
||||
<Hash class="size-3" />
|
||||
<span>{{ cols }}×{{ rows }}</span>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-1 shrink-0">
|
||||
<Cpu class="size-3" />
|
||||
<span>{{ fontSize }}px</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,219 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 终端标签栏。
|
||||
*
|
||||
* 职责:展示会话列表、切换、关闭、拖动重排、新建。
|
||||
* 不含任何终端渲染逻辑——标签只是会话的「视图句柄」。
|
||||
*/
|
||||
import { ref, watch } from 'vue'
|
||||
import { Plus, X, TerminalSquare, Lock, Loader2, AlertTriangle } from '@lucide/vue'
|
||||
import { VueDraggable } from 'vue-draggable-plus'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
import { useTerminalStore } from '@/stores/terminalStore'
|
||||
import type { SessionInfo } from '@/types/terminal'
|
||||
|
||||
const store = useTerminalStore()
|
||||
|
||||
const props = defineProps<{
|
||||
sessions: SessionInfo[]
|
||||
activeId: string | null
|
||||
/** 有新输出但未被查看的会话 id 集合 */
|
||||
unread?: Set<string>
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'select', id: string): void
|
||||
(e: 'close', id: string): void
|
||||
(e: 'new'): void
|
||||
(e: 'reorder', ids: string[]): void
|
||||
}>()
|
||||
|
||||
/**
|
||||
* 拖动重排用的本地副本。
|
||||
*
|
||||
* # 为什么不用 `computed({ get: () => props.sessions, set })`
|
||||
*
|
||||
* `VueDraggable` 的 `v-model` 是**就地改写数组**(内部 `splice`),而不是派发一个
|
||||
* 新数组。若 getter 直接返回 `props.sessions`,就会去改**父组件传下来的 prop**,
|
||||
* 触发 Vue 的「不要直接修改 prop」告警,且改动依赖父组件恰好用同一个数组引用。
|
||||
*
|
||||
* 这里改用本地 `ref` 镜像:
|
||||
* - `props.sessions` 变化 → 同步到本地(含新增/删除/重命名)
|
||||
* - 用户拖动 → `VueDraggable` 改本地数组 → watch 派发 `reorder` 给父组件落库
|
||||
* 两边都只碰自己的数据,没有跨组件写。
|
||||
*/
|
||||
const localList = ref<SessionInfo[]>([...props.sessions])
|
||||
|
||||
watch(
|
||||
// 用 id 序列化做比较:会话对象每次都是新引用(store 重建),直接 watch(props.sessions)
|
||||
// 会在每次轮询/状态刷新时都判定为「变化」,把用户正在进行的拖动顺序冲掉。
|
||||
() => props.sessions.map(s => s.id).join(','),
|
||||
() => {
|
||||
localList.value = [...props.sessions]
|
||||
}
|
||||
)
|
||||
|
||||
// 状态/标题变化不改变 id 列表,上面的 watch 不会触发——若不处理,标签上会
|
||||
// 一直显示旧状态(典型表现:SSH 已连接但标签还在转圈)。这里就地合并展示
|
||||
// 字段:保持数组顺序不变(不干扰可能的拖动),只替换为新的会话对象。
|
||||
watch(
|
||||
() =>
|
||||
props.sessions
|
||||
.map(s => `${s.id}:${s.state}:${s.title}:${s.detached ? 1 : 0}`)
|
||||
.join(','),
|
||||
() => {
|
||||
const byId = new Map(props.sessions.map(s => [s.id, s]))
|
||||
localList.value = localList.value.map(old => byId.get(old.id) ?? old)
|
||||
}
|
||||
)
|
||||
|
||||
/** 拖动结束:把顺序写回父组件(父组件会做「过滤已消失会话并补齐」的校验) */
|
||||
function onDragUpdate() {
|
||||
emit(
|
||||
'reorder',
|
||||
localList.value.map(s => s.id)
|
||||
)
|
||||
}
|
||||
|
||||
/** 当前正在被鼠标悬停的标签(用于 alway 显示关闭按钮 vs 仅悬停显示) */
|
||||
const hoveredId = ref<string | null>(null)
|
||||
|
||||
function stateIcon(s: SessionInfo) {
|
||||
if (s.state === 'connecting' || s.state === 'authenticating') return Loader2
|
||||
if (s.state === 'failed') return AlertTriangle
|
||||
return null
|
||||
}
|
||||
|
||||
function isBusy(s: SessionInfo) {
|
||||
return s.state === 'connecting' || s.state === 'authenticating'
|
||||
}
|
||||
|
||||
/** 标签主标题:优先用户重命名的 title,其次 shell/主机名,最后退化到 id */
|
||||
function labelOf(s: SessionInfo) {
|
||||
return store.sessionLabel(s)
|
||||
}
|
||||
|
||||
/** 副标题:展示 cwd(本地)或 user@host(SSH),提供「我在哪」的一眼信息 */
|
||||
function subtitleOf(s: SessionInfo) {
|
||||
return store.sessionSubtitle(s)
|
||||
}
|
||||
|
||||
/** 会话类型图标:SSH 加锁标记,本地用终端标记 */
|
||||
function kindIcon(s: SessionInfo) {
|
||||
return s.kind === 'ssh' ? Lock : TerminalSquare
|
||||
}
|
||||
|
||||
/** Tooltip 全文:标题 + 副标题(cwd / user@host),替代标签内的两行排版 */
|
||||
function tooltipText(s: SessionInfo) {
|
||||
const sub = subtitleOf(s)
|
||||
return sub ? `${labelOf(s)}\n${sub}` : labelOf(s)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- shrink-0 而不是 flex-1:主区是纵向 flex,标签行是固定高度的头部,
|
||||
用 flex-1 会与下方面板区平分剩余高度,标签芯片垂直悬在拉高出
|
||||
的空白中间(窗口栏高度异常的根因) -->
|
||||
<div class="flex items-center gap-1 min-w-0 shrink-0">
|
||||
<!--
|
||||
不要加 `target=".tab-track"`。
|
||||
|
||||
`target` 是给**跨容器拖拽**用的(把元素从 A 列表拖到 B 列表),它会被解析成
|
||||
`$el.querySelector(target)`(见 vue-draggable-plus 源码 `R(v)` / `Sn(t, e)`)。
|
||||
`querySelector` **只搜后代,不匹配元素自身** —— 而 `.tab-track` 正是这个组件
|
||||
根元素自己的类名,所以必然返回 `null`,继而 `new Sortable(null)` 抛
|
||||
「`el` must be an HTMLElement, not [object Null]」。
|
||||
|
||||
单容器内排序**本来就不需要 target**:`v-model` 绑定的数组顺序就是拖拽结果。
|
||||
项目内其他三处 VueDraggable(monitor ×2、settings ×1)也都没传它。
|
||||
-->
|
||||
<VueDraggable
|
||||
v-model="localList"
|
||||
:animation="150"
|
||||
class="tab-track flex items-center gap-1 min-w-0 overflow-x-auto scrollbar-none"
|
||||
@update:model-value="onDragUpdate"
|
||||
>
|
||||
<!--
|
||||
标签只显示单行标题;完整信息(标题 + cwd/user@host 副标题)放 Tooltip,
|
||||
与其他模块的悬停提示范式一致。此前副标题直接排在标签里,标签变成两行高。
|
||||
-->
|
||||
<Tooltip v-for="s in localList" :key="s.id">
|
||||
<TooltipTrigger as-child>
|
||||
<div
|
||||
class="group relative flex items-center gap-1.5 shrink-0 max-w-[220px] px-2.5 py-1.5
|
||||
rounded-md cursor-pointer select-none transition-colors"
|
||||
:class="
|
||||
s.id === activeId
|
||||
? 'bg-accent text-accent-foreground'
|
||||
: 'text-muted-foreground hover:bg-accent/50 hover:text-foreground'
|
||||
"
|
||||
@click="emit('select', s.id)"
|
||||
@mouseenter="hoveredId = s.id"
|
||||
@mouseleave="hoveredId = null"
|
||||
>
|
||||
<!-- 类型图标 / 状态指示:连接中用旋转的 loader,失败用警告三角 -->
|
||||
<component
|
||||
:is="stateIcon(s) || kindIcon(s)"
|
||||
class="size-3.5 shrink-0"
|
||||
:class="{
|
||||
'animate-spin': isBusy(s),
|
||||
'text-red-500': s.state === 'failed',
|
||||
'text-muted-foreground/60': s.state === 'closed'
|
||||
}"
|
||||
/>
|
||||
|
||||
<span class="text-xs truncate">{{ labelOf(s) }}</span>
|
||||
|
||||
<!-- 未读小圆点:有输出但当前未激活 -->
|
||||
<span
|
||||
v-if="unread?.has(s.id) && s.id !== activeId"
|
||||
class="size-1.5 rounded-full bg-primary shrink-0"
|
||||
/>
|
||||
|
||||
<!-- 独立窗口标记:该会话已被拖出到独立窗口 -->
|
||||
<span
|
||||
v-if="s.detached"
|
||||
class="text-[9px] px-1 rounded bg-primary/15 text-primary shrink-0"
|
||||
>
|
||||
独立
|
||||
</span>
|
||||
|
||||
<!-- 关闭按钮:始终占位(避免悬停时标签宽度跳动),非悬停时透明 -->
|
||||
<button
|
||||
class="shrink-0 size-4 rounded flex items-center justify-center transition-opacity
|
||||
hover:bg-background/60"
|
||||
:class="hoveredId === s.id || s.id === activeId ? 'opacity-100' : 'opacity-0'"
|
||||
@click.stop="emit('close', s.id)"
|
||||
>
|
||||
<X class="size-3" />
|
||||
</button>
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom" class="max-w-[360px]">
|
||||
<!-- break-all:会话标题/路径是不含空格的长串,默认断行规则整行溢出 -->
|
||||
<p class="text-xs whitespace-pre-line break-all">{{ tooltipText(s) }}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</VueDraggable>
|
||||
|
||||
<!-- 新建按钮:固定在标签滚动区之外,避免被长标签列表挤到看不见 -->
|
||||
<button
|
||||
class="shrink-0 size-6 rounded flex items-center justify-center text-muted-foreground
|
||||
hover:bg-accent hover:text-foreground transition-colors"
|
||||
title="新建本地会话"
|
||||
@click="emit('new')"
|
||||
>
|
||||
<Plus class="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 标签栏横向滚动但不显示滚动条:滚动条会吃掉 8px 高度,让标签栏显得脏 */
|
||||
.scrollbar-none {
|
||||
scrollbar-width: none;
|
||||
}
|
||||
.scrollbar-none::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,277 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 终端工具栏:包裹当前会话的常用动作。
|
||||
*
|
||||
* 设计原则:**只放「标签栏放不下的会话级动作」**。新建/关闭/切换在标签栏已有,
|
||||
* 这里不重复;放的是搜索、字号、清屏、独立窗口这类低频但需要显式入口的操作。
|
||||
*/
|
||||
import { ref } from 'vue'
|
||||
import {
|
||||
ExternalLink,
|
||||
FileText,
|
||||
FolderOpen,
|
||||
FolderTree,
|
||||
LayoutTemplate,
|
||||
Minus,
|
||||
Network,
|
||||
Plus,
|
||||
RotateCcw,
|
||||
Search,
|
||||
Eraser,
|
||||
Sparkles,
|
||||
X,
|
||||
ChevronDown,
|
||||
ChevronUp
|
||||
} from '@lucide/vue'
|
||||
import { Input } from '@/components/ui/input'
|
||||
|
||||
// 模板中直接使用 `sessionId` / `title` / `searching` 等,script 内无需局部变量
|
||||
defineProps<{
|
||||
sessionId: string | null
|
||||
/** 会话标题(用于显示「当前操作对象」) */
|
||||
title: string
|
||||
/** 搜索面板是否展开 */
|
||||
searching: boolean
|
||||
/** 是否有匹配结果的反馈文案(由父组件在搜索后设置) */
|
||||
searchHint?: string
|
||||
/** 当前会话是否为 SSH(决定是否显示文件面板按钮) */
|
||||
isSsh: boolean
|
||||
/** 文件面板是否展开 */
|
||||
sftpVisible: boolean
|
||||
/** 当前会话是否正在记录日志 */
|
||||
logging: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'toggle-search'): void
|
||||
/** 关键词随事件传出(工具栏是关键词的唯一持有者) */
|
||||
(e: 'search', keyword: string): void
|
||||
(e: 'search-next', keyword: string): void
|
||||
(e: 'search-prev', keyword: string): void
|
||||
(e: 'font', delta: number): void
|
||||
(e: 'font-reset'): void
|
||||
(e: 'clear'): void
|
||||
(e: 'detach'): void
|
||||
(e: 'toggle-sftp'): void
|
||||
/** 打开端口转发对话框(仅 SSH 会话显示按钮) */
|
||||
(e: 'open-forwards'): void
|
||||
/** 开关当前会话的日志记录 */
|
||||
(e: 'toggle-logging'): void
|
||||
/** 在文件管理器中显示日志文件 */
|
||||
(e: 'open-log-dir'): void
|
||||
/** 打开会话模板对话框 */
|
||||
(e: 'open-templates'): void
|
||||
/** 打开 AI 命令助手对话框 */
|
||||
(e: 'open-ai'): void
|
||||
}>()
|
||||
|
||||
/** 搜索输入(受控于工具栏,回车触发) */
|
||||
const keyword = ref('')
|
||||
|
||||
/**
|
||||
* 每次查找都要把关键词随事件带出去。
|
||||
*
|
||||
* 早期版本只发 `search-next`(不带参数),依赖父组件「记住上次的关键词」——
|
||||
* 但父组件并不持有工具栏的输入框内容,导致首次按 Enter 时搜索栏是空的、
|
||||
* 什么都不会发生。关键词是工具栏的局部状态,只有这里知道它是什么,
|
||||
* 因此必须由这里显式传出。
|
||||
*/
|
||||
function onSearchNext() {
|
||||
const k = keyword.value.trim()
|
||||
if (k) emit('search', k)
|
||||
}
|
||||
|
||||
function onSearchPrev() {
|
||||
const k = keyword.value.trim()
|
||||
if (k) emit('search-prev', k)
|
||||
}
|
||||
|
||||
function closeSearch() {
|
||||
keyword.value = ''
|
||||
emit('toggle-search')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="shrink-0 flex items-center gap-1 px-2 h-9 border-b border-border bg-card/20">
|
||||
<!-- 当前会话标识:工具栏的动作都作用于它,必须显式写出来 -->
|
||||
<div class="flex items-center gap-1.5 min-w-0 px-1">
|
||||
<span class="text-xs font-medium truncate max-w-[220px]">{{ title || '无会话' }}</span>
|
||||
<span v-if="sessionId" class="text-[10px] text-muted-foreground/60 shrink-0">
|
||||
{{ sessionId }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="flex-1" />
|
||||
|
||||
<!-- ===== 搜索 ===== -->
|
||||
<div v-if="searching" class="flex items-center gap-1">
|
||||
<div class="relative">
|
||||
<Input
|
||||
v-model="keyword"
|
||||
placeholder="查找…"
|
||||
class="h-6 w-[160px] text-xs"
|
||||
autofocus
|
||||
@keydown.enter="onSearchNext"
|
||||
@keydown.shift.enter="onSearchPrev"
|
||||
@keydown.esc="closeSearch"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
class="size-6 rounded flex items-center justify-center text-muted-foreground hover:bg-accent"
|
||||
title="上一个(Shift+Enter)"
|
||||
@click="onSearchPrev"
|
||||
>
|
||||
<ChevronUp class="size-3.5" />
|
||||
</button>
|
||||
<button
|
||||
class="size-6 rounded flex items-center justify-center text-muted-foreground hover:bg-accent"
|
||||
title="下一个(Enter)"
|
||||
@click="onSearchNext"
|
||||
>
|
||||
<ChevronDown class="size-3.5" />
|
||||
</button>
|
||||
<button
|
||||
class="size-6 rounded flex items-center justify-center text-muted-foreground hover:bg-accent"
|
||||
title="关闭搜索"
|
||||
@click="closeSearch"
|
||||
>
|
||||
<X class="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
v-else
|
||||
class="size-7 rounded flex items-center justify-center text-muted-foreground
|
||||
hover:bg-accent hover:text-foreground transition-colors"
|
||||
title="搜索"
|
||||
@click="emit('toggle-search')"
|
||||
>
|
||||
<Search class="size-3.5" />
|
||||
</button>
|
||||
|
||||
<div class="w-px h-4 bg-border mx-0.5" />
|
||||
|
||||
<!-- ===== 字号 ===== -->
|
||||
<button
|
||||
class="size-7 rounded flex items-center justify-center text-muted-foreground
|
||||
hover:bg-accent hover:text-foreground transition-colors"
|
||||
title="缩小字号"
|
||||
@click="emit('font', -1)"
|
||||
>
|
||||
<Minus class="size-3.5" />
|
||||
</button>
|
||||
<button
|
||||
class="size-7 rounded flex items-center justify-center text-muted-foreground
|
||||
hover:bg-accent hover:text-foreground transition-colors"
|
||||
title="放大字号"
|
||||
@click="emit('font', 1)"
|
||||
>
|
||||
<Plus class="size-3.5" />
|
||||
</button>
|
||||
<button
|
||||
class="size-7 rounded flex items-center justify-center text-muted-foreground
|
||||
hover:bg-accent hover:text-foreground transition-colors"
|
||||
title="重置字号"
|
||||
@click="emit('font-reset')"
|
||||
>
|
||||
<RotateCcw class="size-3.5" />
|
||||
</button>
|
||||
|
||||
<div class="w-px h-4 bg-border mx-0.5" />
|
||||
|
||||
<!-- 会话模板:不依赖当前会话(可以没有会话时先拉起一组) -->
|
||||
<button
|
||||
class="size-7 rounded flex items-center justify-center text-muted-foreground
|
||||
hover:bg-accent hover:text-foreground transition-colors"
|
||||
title="会话模板"
|
||||
@click="emit('open-templates')"
|
||||
>
|
||||
<LayoutTemplate class="size-3.5" />
|
||||
</button>
|
||||
|
||||
<!-- AI 命令助手 -->
|
||||
<button
|
||||
class="size-7 rounded flex items-center justify-center text-muted-foreground
|
||||
hover:bg-accent hover:text-foreground transition-colors disabled:opacity-40"
|
||||
:disabled="!sessionId"
|
||||
title="AI 命令助手"
|
||||
@click="emit('open-ai')"
|
||||
>
|
||||
<Sparkles class="size-3.5" />
|
||||
</button>
|
||||
|
||||
<!--
|
||||
文件面板:只对 SSH 会话显示。
|
||||
本地会话不给这个按钮,而不是给了再报错 —— 「看得见但点不动」比
|
||||
「看不见」更让人困惑。
|
||||
-->
|
||||
<button
|
||||
v-if="isSsh"
|
||||
class="size-7 rounded flex items-center justify-center transition-colors
|
||||
disabled:opacity-40"
|
||||
:class="'text-muted-foreground hover:bg-accent hover:text-foreground'"
|
||||
:disabled="!sessionId"
|
||||
title="端口转发(-L / -R)"
|
||||
@click="emit('open-forwards')"
|
||||
>
|
||||
<Network class="size-3.5" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
v-if="isSsh"
|
||||
class="size-7 rounded flex items-center justify-center transition-colors
|
||||
disabled:opacity-40"
|
||||
:class="sftpVisible
|
||||
? 'bg-accent text-foreground'
|
||||
: 'text-muted-foreground hover:bg-accent hover:text-foreground'"
|
||||
:disabled="!sessionId"
|
||||
:title="sftpVisible ? '隐藏文件面板' : '显示文件面板'"
|
||||
@click="emit('toggle-sftp')"
|
||||
>
|
||||
<FolderTree class="size-3.5" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
class="size-7 rounded flex items-center justify-center transition-colors
|
||||
disabled:opacity-40"
|
||||
:class="logging
|
||||
? 'bg-primary/15 text-primary'
|
||||
: 'text-muted-foreground hover:bg-accent hover:text-foreground'"
|
||||
:disabled="!sessionId"
|
||||
:title="logging ? '停止记录会话日志' : '开始记录会话日志'"
|
||||
@click="emit('toggle-logging')"
|
||||
>
|
||||
<FileText class="size-3.5" />
|
||||
</button>
|
||||
<!-- 打开日志文件:只在记录中显示(日志路径此时才有意义) -->
|
||||
<button
|
||||
v-if="logging"
|
||||
class="size-7 rounded flex items-center justify-center text-muted-foreground
|
||||
hover:bg-accent hover:text-foreground transition-colors"
|
||||
title="在文件管理器中显示日志文件"
|
||||
@click="emit('open-log-dir')"
|
||||
>
|
||||
<FolderOpen class="size-3.5" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
class="size-7 rounded flex items-center justify-center text-muted-foreground
|
||||
hover:bg-accent hover:text-foreground transition-colors disabled:opacity-40"
|
||||
:disabled="!sessionId"
|
||||
title="清屏"
|
||||
@click="emit('clear')"
|
||||
>
|
||||
<Eraser class="size-3.5" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
class="size-7 rounded flex items-center justify-center text-muted-foreground
|
||||
hover:bg-accent hover:text-foreground transition-colors disabled:opacity-40"
|
||||
:disabled="!sessionId"
|
||||
title="在独立窗口中打开"
|
||||
@click="emit('detach')"
|
||||
>
|
||||
<ExternalLink class="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* SSH 主机表单的默认值与规整。
|
||||
*
|
||||
* 抽成独立模块而不是写在 `HostManager.vue` 里,是因为「新建主机的默认值」
|
||||
* 有两个使用场景:主机管理面板(`HostManager.vue`)与侧栏的快速新建入口。
|
||||
* 若各写一份,两处的默认端口、默认超时迟早会不一致——而这种不一致
|
||||
* 极难被发现,只会表现为「从这里建的主机连不上,从那里建的可以」。
|
||||
*
|
||||
* 默认值的选取依据:
|
||||
* - `port: 22` —— SSH 标准端口,覆盖绝大多数场景。
|
||||
* - `connectTimeoutMs: 15000` —— 跨公网 + 需要 DNS 解析时,10 秒常不够;
|
||||
* 30 秒又让用户在网络不通时等太久。15 秒是「能容忍慢链路,又不至于
|
||||
* 像卡死」的折中值。
|
||||
* - `keepaliveSecs: 30` —— 小于多数家用路由/NAT 的 60 秒空闲回收阈值,
|
||||
* 足以穿透常见 NAT 超时,同时心跳包本身开销可忽略。
|
||||
* - `encoding: 'utf-8'` —— 现代 Linux 发行版默认 locale;GBK 只留给老系统。
|
||||
*/
|
||||
|
||||
import type { SshHost } from '@/types/terminal'
|
||||
|
||||
export type { SshHost }
|
||||
|
||||
/**
|
||||
* 构造一个空白主机配置。
|
||||
*
|
||||
* `id` 由调用方提供 —— 必须来自后端 `terminal_new_host_id`,
|
||||
* 不能在前端自行生成。原因见 `HostManager.vue` 的文件头说明:
|
||||
* 密码在系统凭据管理器里按 hostId 存取,id 必须与后端规则一致。
|
||||
*/
|
||||
export function blankHost(id: string): SshHost {
|
||||
return {
|
||||
id,
|
||||
name: '',
|
||||
host: '',
|
||||
port: 22,
|
||||
username: '',
|
||||
authMethod: 'key',
|
||||
keyId: '',
|
||||
group: '',
|
||||
note: '',
|
||||
color: '',
|
||||
favorited: false,
|
||||
connectTimeoutMs: 15000,
|
||||
keepaliveSecs: 30,
|
||||
remoteCwd: '',
|
||||
startupCommand: '',
|
||||
useProxy: false,
|
||||
jumpIds: [],
|
||||
encoding: 'utf-8'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 补齐缺失字段的主机配置。
|
||||
*
|
||||
* 用于编辑历史配置:早先版本保存的 `SshHost` 可能缺少后来新增的字段
|
||||
* (如 `encoding`、`useProxy`)。直接绑到表单上,缺失字段会是 `undefined`,
|
||||
* 而 `<Input v-model.number>` 拿到 `undefined` 会显示成空串并可能在
|
||||
* 失焦时写回 `NaN`——反而把好配置改坏。这里统一补齐。
|
||||
*/
|
||||
export function normalizeHost(raw: Partial<SshHost>, id: string): SshHost {
|
||||
const base = blankHost(raw.id || id)
|
||||
return {
|
||||
...base,
|
||||
...raw,
|
||||
// 数值字段单独兜底:`NaN` 是合法 number,不会触发 `??` 的默认值,
|
||||
// 但塞进 `port` 会让后端校验失败,且表单上显示为空,用户看不出问题所在。
|
||||
port: Number.isFinite(raw.port) ? (raw.port as number) : base.port,
|
||||
connectTimeoutMs: Number.isFinite(raw.connectTimeoutMs)
|
||||
? (raw.connectTimeoutMs as number)
|
||||
: base.connectTimeoutMs,
|
||||
keepaliveSecs: Number.isFinite(raw.keepaliveSecs)
|
||||
? (raw.keepaliveSecs as number)
|
||||
: base.keepaliveSecs,
|
||||
authMethod: raw.authMethod || base.authMethod,
|
||||
// 数组字段单独兜底:旧配置没有该字段时是 undefined,直接展开会盖掉 base 的 []
|
||||
jumpIds: Array.isArray(raw.jumpIds) ? raw.jumpIds : base.jumpIds,
|
||||
encoding: raw.encoding || base.encoding
|
||||
}
|
||||
}
|
||||
|
||||
/** 认证方式的中文展示名 */
|
||||
export function authMethodLabel(method: string): string {
|
||||
switch (method) {
|
||||
case 'key':
|
||||
return '密钥认证'
|
||||
case 'password':
|
||||
return '密码认证'
|
||||
case 'agent':
|
||||
return 'SSH Agent'
|
||||
case 'keyboard':
|
||||
return '键盘交互'
|
||||
default:
|
||||
return method || '未设置'
|
||||
}
|
||||
}
|
||||
|
||||
/** 是否是可用的认证方式(P0 只实现 key 与 password) */
|
||||
export function isSupportedAuthMethod(method: string): boolean {
|
||||
return method === 'key' || method === 'password'
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { ModuleConfig } from '@/types/module'
|
||||
import type { SearchIndexItem } from '@/stores/searchIndex'
|
||||
|
||||
const searchItems: SearchIndexItem[] = [
|
||||
{
|
||||
title: '终端',
|
||||
description: 'SSH 与本地 Shell 多会话终端',
|
||||
keywords: ['终端', 'terminal', 'shell', '命令行', 'console', '控制台', 'bash', 'ssh'],
|
||||
tab: 'terminal'
|
||||
},
|
||||
{
|
||||
title: '新建本地会话',
|
||||
description: '打开 PowerShell / cmd / Git Bash / WSL',
|
||||
keywords: ['新建', '本地', 'powershell', 'pwsh', 'cmd', 'git bash', 'wsl', '会话', '标签'],
|
||||
tab: 'terminal'
|
||||
},
|
||||
{
|
||||
title: 'SSH 主机',
|
||||
description: '管理 SSH 主机连接(含跳板机与自动登录)',
|
||||
keywords: ['ssh', '主机', '服务器', '远程', '连接', 'host', '远程登录'],
|
||||
tab: 'hosts'
|
||||
},
|
||||
{
|
||||
title: 'SSH 密钥管理',
|
||||
description: '生成、导入与管理 SSH 密钥,passphrase 存入系统凭据管理器',
|
||||
keywords: ['密钥', 'key', '私钥', '公钥', 'ed25519', 'rsa', 'ecdsa', 'passphrase', '指纹'],
|
||||
tab: 'keys'
|
||||
},
|
||||
{
|
||||
title: '已知主机(known_hosts)',
|
||||
description: '查看与清理主机密钥指纹记录,导出供审阅',
|
||||
keywords: ['known_hosts', '指纹', '主机密钥', '信任', 'host key', '安全'],
|
||||
tab: 'knownHosts'
|
||||
},
|
||||
{
|
||||
title: '终端外观设置',
|
||||
description: '主题、字体、光标、滚动缓冲与 GPU 渲染',
|
||||
keywords: ['外观', '主题', '字体', '字号', '光标', '滚动', '颜色', '透明度'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '终端快捷键',
|
||||
description: '自定义终端内快捷键(复制粘贴、标签、分屏、搜索)',
|
||||
keywords: ['快捷键', '热键', 'shortcut', 'keybinding', '复制', '粘贴', '分屏'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '终端独立窗口',
|
||||
description: '把会话拖出主窗口,独立窗口承载单个会话',
|
||||
keywords: ['独立窗口', '分离', 'detach', '新窗口', '多屏'],
|
||||
tab: 'settings'
|
||||
}
|
||||
]
|
||||
|
||||
export const moduleConfig: ModuleConfig = {
|
||||
id: 'terminal',
|
||||
name: '终端',
|
||||
icon: 'terminal',
|
||||
description: 'SSH 与本地 Shell 多会话终端(密钥管理 + 主机密钥校验 + 独立窗口)',
|
||||
category: 'tool',
|
||||
defaultEnabled: true,
|
||||
loader: () => import('./TerminalModule.vue'),
|
||||
searchItems,
|
||||
lifecycle: {
|
||||
// 模块启用:拉取一次会话列表(会话在 Rust 侧存活,模块被禁用期间不会中断)
|
||||
onEnable: async () => {
|
||||
// 动态导入避免 index.ts 直接依赖 store(会形成循环依赖,参见 music 模块的处理)
|
||||
try {
|
||||
const { useTerminalStore } = await import('@/stores/terminalStore')
|
||||
const store = useTerminalStore()
|
||||
await store.init()
|
||||
} catch (e) {
|
||||
console.error('[terminal] onEnable 初始化失败:', e)
|
||||
}
|
||||
},
|
||||
onDisable: () => {
|
||||
// 刻意**不**关闭会话:用户禁用模块通常是暂时的(排查冲突),
|
||||
// 若此时杀掉正在跑长任务的 SSH 连接,代价远大于保留几个空闲会话。
|
||||
// 真正的清理在应用退出时由 Rust 侧 cleanup_on_exit 统一处理。
|
||||
}
|
||||
},
|
||||
// 排在音乐(15)之后、剪贴板(20)之前:终端是高频入口,应靠前
|
||||
order: 18
|
||||
}
|
||||
Reference in New Issue
Block a user