终端模块初版

This commit is contained in:
zhongluofeng committed 2026-09-18 18:28:13 +08:00
1 parent f6c1cc250e
commit b018abd922
63 files changed
+26695 -185

No files matched your search

+928
View File
@@ -0,0 +1,928 @@
//! 终端模块设置的数据模型与默认值。
//!
//! 持久化位置:`{app_data_dir}/terminal/settings.json`(与 translate / music 同一范式)。
//! 容器级 `#[serde(default)]`:新增字段对旧配置文件是**向后兼容**的——缺字段取默认值
//! 而不是让整份设置反序列化失败,避免用户因为一次升级丢掉全部配置。
//!
//! 安全姿态(与 `crate::secrets` 的约定一致):**本结构里不允许出现任何明文凭据**。
//! SSH 密码、私钥 passphrase 一律进系统凭据管理器,本结构只保存它们的引用 id 与
//! 派生展示字段(如 `hasPassphrase`,由命令层回填,不落盘)。
use serde::{Deserialize, Serialize};
use specta::Type;
// ===== 本地 Shell =====
/// 本地 Shell 配置。
///
/// 探测到的 Shell 与用户自定义的 Shell 用同一结构表达:`detected` 为 true 表示
/// 由 [`super::shell::detect_shells`] 自动发现,前端只允许改启动参数而不可改路径
/// (路径已被验证存在,改错会让会话起不来)。
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct ShellProfile {
/// 唯一标识(同时是新建会话时的 shellKey)
pub id: String,
/// 展示名称,如 "PowerShell 7"
pub name: String,
/// 可执行文件绝对路径
pub path: String,
/// 启动参数
pub args: Vec<String>,
/// 启动时的工作目录(空串表示用用户主目录)
pub cwd: String,
/// 环境变量覆盖(键值对;值为空串表示删除该变量)
pub env: Vec<EnvVar>,
/// Shell 类型:"powershell" | "cmd" | "bash" | "wsl"
///
/// 决定三件事:cwd 跟踪 hook 的注入方式、清屏命令、以及 OSC 7 的解析口径。
pub kind: String,
/// 是否由自动探测得到(true 时前端不可编辑 path)
pub detected: bool,
/// 是否在新建会话菜单中显示
pub enabled: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct EnvVar {
pub key: String,
pub value: String,
}
/// 手写 `Default` 而不是 derive:`detected` 与 `enabled` 的默认值必须是
/// `true` / `true`(derive 会给 `false`),而 `#[serde(default)]` 在容器级
/// 要求每个字段类型都实现 `Default`。两者不一致会导致「反序列化出来的
/// Shell 默认禁用」这种隐性 bug。
impl Default for ShellProfile {
fn default() -> Self {
Self {
id: String::new(),
name: String::new(),
path: String::new(),
args: Vec::new(),
cwd: String::new(),
env: Vec::new(),
kind: "bash".to_string(),
detected: true,
enabled: true,
}
}
}
/// 容器级 `#[serde(default)]` 要求字段类型实现 `Default`。
/// `EnvVar` 的「空值」语义就是空键空值,用 derive 的默认即可。
impl Default for EnvVar {
fn default() -> Self {
Self {
key: String::new(),
value: String::new(),
}
}
}
impl ShellProfile {
pub fn new(id: &str, name: &str, path: &str, kind: &str) -> Self {
Self {
id: id.to_string(),
name: name.to_string(),
path: path.to_string(),
args: Vec::new(),
cwd: String::new(),
env: Vec::new(),
kind: kind.to_string(),
detected: true,
enabled: true,
}
}
}
// ===== SSH 主机 =====
/// SSH 主机条目。
///
/// `id` 是凭据键名的一部分(`terminal-ssh-password-{id}`),**创建后不应修改**:
/// 改了会让已存进凭据管理器的密码读不到。前端在编辑态需禁用该字段。
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct SshHost {
pub id: String,
/// 展示别名(列表主标题)
pub name: String,
pub host: String,
pub port: u16,
pub username: String,
/// 认证方式:"key"(公钥,默认)| "password" | "agent"(P1)| "keyboard"(P1)
pub auth_method: String,
/// 公钥认证使用的密钥 id(指向 [`super::keys`] 的密钥库)
pub key_id: String,
/// 分组名(侧栏按此分组)
pub group: String,
/// 备注
pub note: String,
/// 标签色(前端用于状态点/分组标识)
pub color: String,
/// 是否收藏(置顶显示)
pub favorited: bool,
/// 连接超时(毫秒)
pub connect_timeout_ms: u64,
/// keep-alive 间隔(秒,0 表示关闭)
pub keepalive_secs: u64,
/// 启动目录(空串表示登录后进入默认目录)
pub remote_cwd: String,
/// 登录后自动执行的命令
pub startup_command: String,
/// 是否走代理模块(mihomo)。默认关闭:内网主机不该被绕进代理。
pub use_proxy: bool,
/// 跳板机链(ProxyJump):按连接顺序排列的主机 id。
///
/// 每一项引用**本主机列表里的另一台主机**(复用它的地址、账号与凭据),
/// 连接方向为 `本机 → jump_ids[0] → jump_ids[1] → … → 本主机`。
/// 空 = 直连。约束(命令层校验):不能引用自己、不能有环、
/// 链长上限 5、每一跳的认证方式必须是 key/password。
///
/// 用 id 引用而不是内联一份地址+凭据的理由:跳板机自己的密码/密钥
/// 存在凭据管理器里,按 id 复用可以避免同一台跳板机在多处配置里
/// 留下多份凭据副本(改密码时漏改一处就是连接事故)。
pub jump_ids: Vec<String>,
/// 终端的字符编码("utf-8" 默认 | "gbk" 等)。老服务器常见 GBK,中文环境刚需。
pub encoding: String,
}
impl Default for SshHost {
fn default() -> Self {
Self {
id: String::new(),
name: String::new(),
host: String::new(),
port: 22,
username: String::new(),
auth_method: "key".to_string(),
key_id: String::new(),
group: String::new(),
note: String::new(),
color: String::new(),
favorited: false,
connect_timeout_ms: 15_000,
keepalive_secs: 30,
remote_cwd: String::new(),
startup_command: String::new(),
use_proxy: false,
jump_ids: Vec::new(),
encoding: "utf-8".to_string(),
}
}
}
// ===== 外观 =====
/// 终端外观设置。
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct AppearanceSettings {
/// 配色主题 id(内置若干,见前端 terminalThemes.ts)
pub theme: String,
/// 是否跟随应用亮暗主题(开启时 `theme` 只作为亮/暗的取色基准)
pub follow_app_theme: bool,
/// 字体族(逗号分隔的 CSS font-family)
pub font_family: String,
pub font_size: u32,
/// 行高倍数
pub line_height: f64,
/// 字母间距
pub letter_spacing: f64,
/// 光标样式:"block" | "bar" | "underline"
pub cursor_style: String,
/// 光标是否闪烁
pub cursor_blink: bool,
/// 滚动缓冲区行数。上限 200000:再高会显著吃内存且滚动查找变慢。
pub scrollback: u32,
/// 背景不透明度百分比(100 = 不透明)
pub opacity: u32,
/// 是否启用 GPU 渲染(addon-webgl)。极少数显卡驱动下有花屏问题,故给开关。
pub gpu_rendering: bool,
}
impl Default for AppearanceSettings {
fn default() -> Self {
Self {
theme: "thing-dark".to_string(),
follow_app_theme: true,
font_family: "Cascadia Mono, Consolas, Microsoft YaHei Mono, monospace".to_string(),
font_size: 14,
line_height: 1.2,
letter_spacing: 0.0,
cursor_style: "block".to_string(),
cursor_blink: true,
scrollback: 10_000,
opacity: 100,
gpu_rendering: true,
}
}
}
// ===== 快捷键 =====
/// 一条终端内快捷键绑定。
///
/// 只覆盖**终端内**(第二层)快捷键:全局快捷键(第一层)由 `crate::shortcut` 统一
/// 注册并做应用内冲突检测,不走这里;shell 原生快捷键(第三层)不做拦截。
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct ShortcutBinding {
/// 动作标识,见前端 `terminalActions.ts`(如 "copy" / "newTab")
pub action: String,
/// 键位字符串,格式与 `crate::shortcut::parse_shortcut` 一致(如 "Ctrl+Shift+C")
pub keys: String,
/// 是否启用(关掉后该动作无快捷键,但仍可从菜单触发)
pub enabled: bool,
}
impl Default for ShortcutBinding {
fn default() -> Self {
Self {
action: String::new(),
keys: String::new(),
enabled: true,
}
}
}
// ===== 终端内选中行为 =====
/// 终端内选中行为。
///
/// # 为什么叫 `TerminalSelectionSettings` 而不是 `SelectionSettings`
///
/// 与 `translate::settings::SelectionSettings` 撞名。`tauri-specta` 的类型注册表
/// **全局按类型名索引**,重名会让 `export_bindings()` panic
/// (`Detected multiple types with the same name`)。
/// specta 2.0.0-rc.25 的 derive 路径无法重命名导出类型
/// (详见 `history::TerminalHistoryPage` 的注释),只能改 Rust 标识符本身。
///
/// 注意:这是**第二个**独立引入的 `SelectionSettings`。新增跨模块共享名之前,
/// 先确认没有同名 `Type` 已存在 —— 否则会在**运行时启动阶段**才炸,
/// 而不是编译期(见 `TERMINAL_MODULE_PLAN.md` 坑 27)。
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct TerminalSelectionSettings {
/// 选中即复制(受 Linux/macOS 习惯影响的用户会开;默认关,避免误触)
pub copy_on_select: bool,
/// 中键粘贴(X11 习惯;Windows 下默认关)
pub middle_click_paste: bool,
/// 右键行为:"menu"(默认,弹菜单)| "paste"(直接粘贴)| "select-word"
pub right_click: String,
/// 复制时是否去掉尾部空行
pub trim_trailing_newline: bool,
}
impl Default for TerminalSelectionSettings {
fn default() -> Self {
Self {
copy_on_select: false,
middle_click_paste: false,
right_click: "menu".to_string(),
trim_trailing_newline: true,
}
}
}
// ===== 布局 =====
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct LayoutSettings {
/// 关闭标签页时若会话仍有活跃进程,是否二次确认
pub confirm_close_running: bool,
/// 新建标签页时是否继承当前会话的工作目录
pub inherit_cwd: bool,
/// 侧栏默认是否展开
pub sidebar_open: bool,
/// 侧栏宽度(像素)
pub sidebar_width: u32,
/// 是否显示底部状态栏
pub show_status_bar: bool,
/// 分屏上限(1 = 不分屏,2 = 2×1,4 = 2×2)。
/// 上限刻意封在 4:分屏 × 标签 × 会话的组合复杂度会爆炸。
pub max_panes: u32,
}
impl Default for LayoutSettings {
fn default() -> Self {
Self {
confirm_close_running: true,
inherit_cwd: true,
sidebar_open: true,
sidebar_width: 220,
show_status_bar: true,
max_panes: 4,
}
}
}
// ===== 命令片段 =====
/// 一条命令片段。
///
/// # 为什么 `command` 里允许变量占位符
///
/// 常用命令的差异往往只在少数字段(路径、主机名、分支名)。若每条变体都要
/// 单独存一条,片段库会迅速退化成「一堆几乎一样的条目」,反而找不到东西。
/// 因此支持 `${name}` 形式占位符,执行前弹出表单逐个填写。
///
/// 占位符语法刻意用 `${name}` 而不是 `{name}`:shell 自身大量使用 `{}`
/// (`${VAR}`、`awk '{print}'`、brace expansion),单花括号会与用户的正常
/// 命令冲突,导致片段存进去就「被替换掉了」。
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct CommandSnippet {
pub id: String,
/// 展示名称(列表主标题)
pub name: String,
/// 命令内容(可含 `${name}` 占位符)
pub command: String,
/// 说明(列表副标题,讲清这条命令做什么、有什么前提)
pub description: String,
/// 分组名(空串归入「未分组」)
pub group: String,
/// 占位符的默认值:name → 默认值。未列出的占位符默认空串。
pub defaults: std::collections::BTreeMap<String, String>,
/// 适用的 shell kind(空数组表示所有 shell 都适用)。
/// 例:`Get-ChildItem` 只对 powershell 有意义,不该出现在 cmd 的列表里。
pub shell_kinds: Vec<String>,
/// 仅对 SSH 会话显示(如 `sudo systemctl restart` 类远端操作)
pub ssh_only: bool,
/// 是否需要二次确认(危险命令,如 `rm -rf`)
pub confirm: bool,
/// 是否在片段面板中置顶
pub pinned: bool,
/// 创建时间(Unix 毫秒,用于列表排序)
pub created_at: u64,
}
impl Default for CommandSnippet {
fn default() -> Self {
Self {
id: String::new(),
name: String::new(),
command: String::new(),
description: String::new(),
group: String::new(),
defaults: std::collections::BTreeMap::new(),
shell_kinds: Vec::new(),
ssh_only: false,
confirm: false,
pinned: false,
created_at: 0,
}
}
}
/// 从命令文本中提取 `${name}` 占位符名(去重、保持出现顺序)。
///
/// 放在 Rust 侧而不是前端:占位符是**命令语义的一部分**,执行前的替换、
/// 校验与「哪些占位符还没填」的判断必须用同一套解析,
/// 两边各写一遍迟早会在边界情况(`$${x}`、`${a}${b}` 相邻)上分叉。
pub fn snippet_placeholders(command: &str) -> Vec<String> {
let bytes = command.as_bytes();
let mut out: Vec<String> = Vec::new();
let mut i = 0usize;
while i < bytes.len() {
// 找 `${`
if bytes[i] == b'$' && i + 1 < bytes.len() && bytes[i + 1] == b'{' {
// `$${x}` 是字面量 `${x}`(转义),跳过
let escaped = i > 0 && bytes[i - 1] == b'$';
if !escaped {
if let Some(end) = command[i + 2..].find('}') {
let name = &command[i + 2..i + 2 + end];
// 占位符名限定为标识符形态,避免把 `${VAR:-default}` 这类
// shell 参数展开语法误当成占位符
if !name.is_empty()
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
&& !out.iter().any(|x| x == name)
{
out.push(name.to_string());
}
i = i + 2 + end + 1;
continue;
}
}
}
i += 1;
}
out
}
/// 用给定值替换命令里的占位符。
///
/// 未提供的占位符**保持原样**(不替换成空串):静默替换成空串会让
/// `rm -rf ${dir}` 变成 `rm -rf ` —— 一个参数缺失的命令可能比一个
/// 显式报错的命令危险得多。调用方应先校验所有占位符都有值。
pub fn snippet_render(command: &str, values: &std::collections::BTreeMap<String, String>) -> String {
let mut out = String::with_capacity(command.len());
let bytes = command.as_bytes();
let mut i = 0usize;
while i < bytes.len() {
if bytes[i] == b'$' && i + 1 < bytes.len() && bytes[i + 1] == b'{' {
let escaped = i > 0 && bytes[i - 1] == b'$';
if !escaped {
if let Some(end) = command[i + 2..].find('}') {
let name = &command[i + 2..i + 2 + end];
if !name.is_empty()
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
{
match values.get(name) {
Some(v) => out.push_str(v),
None => out.push_str(&command[i..i + 2 + end + 1]),
}
i = i + 2 + end + 1;
continue;
}
}
}
}
// 逐字符拷贝,注意 UTF-8 多字节边界:这里直接按字节推进会让
// 中文字符被切断。故用 chars().next() 取整字符的长度。
let ch = command[i..].chars().next().unwrap_or(' ');
out.push(ch);
i += ch.len_utf8();
}
out
}
// ===== 密钥存储(仅元数据)=====
/// 密钥库的单个条目(元数据,**不含私钥内容**)。
///
/// 私钥本体存放在 `{app_data_dir}/terminal/keys/` 的独立文件里(可能是几 KB,
/// 塞进 Windows 凭据管理器不可靠——单条有大小上限),passphrase 才进凭据管理器。
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct KeyMeta {
pub id: String,
/// 展示名称
pub name: String,
/// 算法:"ed25519" | "rsa" | "ecdsa"
pub algorithm: String,
/// 位数 / 曲线(RSA 2048/3072/4096;ECDSA P-256/P-384/P-521;ed25519 固定空串)
pub bits: u32,
/// 公钥指纹(SHA256,OpenSSH 展示格式 `SHA256:xxxx`)
pub fingerprint: String,
/// 公钥内容(`ssh-ed25519 AAAA... comment`),用于一键复制
pub public_key: String,
/// 注释
pub comment: String,
/// 私钥文件名(`keys/` 目录下,相对名)
pub file_name: String,
/// 创建时间(RFC3339)
pub created_at: String,
/// 是否由 ssh-agent 托管(P1)
pub in_agent: bool,
}
impl Default for KeyMeta {
fn default() -> Self {
Self {
id: String::new(),
name: String::new(),
algorithm: "ed25519".to_string(),
bits: 0,
fingerprint: String::new(),
public_key: String::new(),
comment: String::new(),
file_name: String::new(),
created_at: String::new(),
in_agent: false,
}
}
}
// ===== 安全 =====
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct SecuritySettings {
/// 主机密钥策略:"ask"(默认,首次连接必须显式确认指纹)。
///
/// **不提供 "auto-accept" 选项**:TOFU 静默接受是 MITM 的入口,
/// 属于代码层不该给用户的开关。
pub host_key_policy: String,
/// 指纹变更时是否阻断(**默认 true**)。关掉会让中间人攻击无声通过,
/// 因此前端需以红色风险提示呈现该开关。
pub block_on_fingerprint_change: bool,
/// 是否记录连接审计日志(P2,默认关;开启后输入输出落盘,含脱敏)
pub audit_log: bool,
}
impl Default for SecuritySettings {
fn default() -> Self {
Self {
host_key_policy: "ask".to_string(),
block_on_fingerprint_change: true,
audit_log: false,
}
}
}
// ===== 根结构 =====
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct TerminalSettings {
/// 结构版本号(用于后续迁移判断)
pub version: u32,
/// 本地 Shell 配置(探测结果 + 用户自定义,合并存放)
pub shells: Vec<ShellProfile>,
/// SSH 主机条目
pub hosts: Vec<SshHost>,
/// 密钥元数据
pub keys: Vec<KeyMeta>,
pub appearance: AppearanceSettings,
pub layout: LayoutSettings,
pub shortcuts: Vec<ShortcutBinding>,
pub selection: TerminalSelectionSettings,
pub security: SecuritySettings,
/// 「关闭标签页时确认」等行为的白名单:某些会话可豁免确认
pub close_confirm_exempt: Vec<String>,
/// 上次使用的 Shell id(新建会话时的默认选中项)
pub last_shell_id: String,
/// 命令片段库
pub snippets: Vec<CommandSnippet>,
/// 会话模板(一键拉起一组会话 + 布局)
pub templates: Vec<SessionTemplate>,
}
impl Default for TerminalSettings {
fn default() -> Self {
Self {
version: 2,
shells: Vec::new(),
hosts: Vec::new(),
keys: Vec::new(),
appearance: AppearanceSettings::default(),
layout: LayoutSettings::default(),
shortcuts: default_shortcuts(),
selection: TerminalSelectionSettings::default(),
security: SecuritySettings::default(),
close_confirm_exempt: Vec::new(),
last_shell_id: String::new(),
snippets: Vec::new(),
templates: Vec::new(),
}
}
}
/// 会话模板:一键拉起一组会话并排成布局。
///
/// 拉起语义:`entries[0]` 作为主面板,其余依次以分屏面板加入
/// (受 `layout.maxPanes` 上限约束,超过 4 个的条目被忽略——
/// WebGL 上下文上限决定了可见面板不可能超过 4,见 useSessionStream 说明)。
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct SessionTemplate {
pub id: String,
pub name: String,
/// 创建时间(Unix 毫秒;模板列表按此排序)
pub created_at: u64,
pub entries: Vec<TemplateEntry>,
}
impl Default for SessionTemplate {
fn default() -> Self {
Self {
id: String::new(),
name: String::new(),
created_at: 0,
entries: Vec::new(),
}
}
}
/// 模板中的一个会话条目。
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct TemplateEntry {
/// `"local"`(shell)| `"ssh"`(主机)
pub kind: String,
/// 本地 = shell id;SSH = host id。拉起时实时解析——
/// 模板只存引用,不快照账号密码(那些在凭据管理器里按 id 存取)。
pub target_id: String,
/// 保存时的展示名快照(仅用于模板列表显示;target 失效时前端据此标注)
pub label: String,
}
impl Default for TemplateEntry {
fn default() -> Self {
Self {
kind: "local".to_string(),
target_id: String::new(),
label: String::new(),
}
}
}
/// 默认终端内快捷键。
///
/// 键位选择依据(Windows Terminal 惯例 + 与项目既有全局快捷键避让):
/// - 复制粘贴用 `Ctrl+Shift+C/V` 而**不是** `Ctrl+C/V`:`Ctrl+C` 在终端里必须是
/// SIGINT,任何对它做复制映射的设计都会破坏 `^C` 中断,这是不可接受的。
/// - 新建/关闭标签用 `Ctrl+Shift+T/W`,与浏览器习惯一致。
/// - 跳转标签用 `Alt+1..9`:`Ctrl+数字` 已被翻译模块的 `Ctrl+2`(翻译面板)占用,
/// 而 `Alt+数字` 在终端里通常不产生控制字符,冲突面最小。
pub fn default_shortcuts() -> Vec<ShortcutBinding> {
let pairs: &[(&str, &str)] = &[
("copy", "Ctrl+Shift+C"),
("paste", "Ctrl+Shift+V"),
("newTab", "Ctrl+Shift+T"),
("closeTab", "Ctrl+Shift+W"),
("nextTab", "Ctrl+Tab"),
("prevTab", "Ctrl+Shift+Tab"),
("splitRight", "Ctrl+Shift+D"),
("splitDown", "Ctrl+Shift+E"),
("closePane", "Ctrl+Shift+Q"),
("search", "Ctrl+Shift+F"),
("clear", "Ctrl+Shift+K"),
("fontIncrease", "Ctrl+="),
("fontDecrease", "Ctrl+-"),
("fontReset", "Ctrl+0"),
("toggleSftp", "Ctrl+Shift+P"),
("snippets", "Ctrl+Shift+S"),
// 历史用 H(History)。不与 `Ctrl+Shift+H`(替换)冲突 ——
// 终端里没有「替换」这个动作。
("history", "Ctrl+Shift+H"),
("renameTab", "F2"),
("sessionSwitcher", "Ctrl+Shift+O"),
];
pairs
.iter()
.map(|(action, keys)| ShortcutBinding {
action: action.to_string(),
keys: keys.to_string(),
enabled: true,
})
.collect()
}
impl TerminalSettings {
/// 按 id 找主机。
pub fn host(&self, id: &str) -> Option<&SshHost> {
self.hosts.iter().find(|h| h.id == id)
}
/// 按 id 找 Shell。
pub fn shell(&self, id: &str) -> Option<&ShellProfile> {
self.shells.iter().find(|s| s.id == id)
}
/// 自愈:修复失效引用、补齐缺失的默认值、推进结构版本。
///
/// 沿用 translate 模块确立的 `heal()` 约定:老配置缺字段取默认值,
/// 失效引用自动回落,返回是否发生变更(由调用方决定是否落盘)。
pub fn heal(&mut self) -> bool {
let mut changed = false;
// 快捷键表:补齐新增动作、剔除已废弃动作。用户改过的键位保留。
let defaults = default_shortcuts();
for d in &defaults {
if !self.shortcuts.iter().any(|s| s.action == d.action) {
self.shortcuts.push(d.clone());
changed = true;
}
}
let before = self.shortcuts.len();
// 只保留默认表里存在的 action,避免版本升级后残留无人消费的绑定
self.shortcuts
.retain(|s| defaults.iter().any(|d| d.action == s.action));
if self.shortcuts.len() != before {
changed = true;
}
// 主机的 key_id 指向已删除的密钥 → 清空并退回密码认证的提示由前端给,
// 这里只做数据层清理(不回退 auth_method,避免静默改变用户的认证选择)
let key_ids: Vec<String> = self.keys.iter().map(|k| k.id.clone()).collect();
for host in &mut self.hosts {
if !host.key_id.is_empty() && !key_ids.contains(&host.key_id) {
host.key_id.clear();
changed = true;
}
}
// 主机字段兜底:端口非法、用户名缺失等由前端表单保证,这里只防越界
for host in &mut self.hosts {
if host.port == 0 {
host.port = 22;
changed = true;
}
if host.connect_timeout_ms < 1000 {
host.connect_timeout_ms = 15_000;
changed = true;
}
if host.encoding.trim().is_empty() {
host.encoding = "utf-8".to_string();
changed = true;
}
}
// 外观:滚动缓冲与字体大小越界会直接导致渲染异常
if self.appearance.scrollback < 100 {
self.appearance.scrollback = 10_000;
changed = true;
}
if self.appearance.scrollback > 200_000 {
self.appearance.scrollback = 200_000;
changed = true;
}
if self.appearance.font_size < 8 || self.appearance.font_size > 40 {
self.appearance.font_size = 14;
changed = true;
}
// 布局:分屏上限封顶 4
if self.layout.max_panes == 0 || self.layout.max_panes > 4 {
self.layout.max_panes = 4;
changed = true;
}
// last_shell_id 指向已删除的 Shell → 清空,由前端选第一个可用
if !self.last_shell_id.is_empty() && self.shell(&self.last_shell_id).is_none() {
self.last_shell_id.clear();
changed = true;
}
if self.version < 1 {
self.version = 1;
changed = true;
}
// v2:引入命令片段库。给**空库**塞一批起步片段 ——
// 一个空片段面板对着用户等于没有这个功能,而「自己写第一条」的门槛
// 比「改一条现成的」高得多。只在空库时注入,用户删光后不会被重塞。
if self.version < 2 {
if self.snippets.is_empty() {
self.snippets = default_snippets();
}
self.version = 2;
changed = true;
}
changed
}
}
/// 起步命令片段。
///
/// 选取标准:**跨平台通用、参数化后确有复用价值、且不容易打错**的东西。
/// 刻意不放 `ls`/`cd` 这类过短命令 —— 它们手打比在列表里找更快,
/// 放进片段库只会稀释信噪比。
pub fn default_snippets() -> Vec<CommandSnippet> {
fn mk(
id: &str,
name: &str,
command: &str,
description: &str,
group: &str,
placeholders: &[(&str, &str)],
ssh_only: bool,
confirm: bool,
) -> CommandSnippet {
CommandSnippet {
id: id.to_string(),
name: name.to_string(),
command: command.to_string(),
description: description.to_string(),
group: group.to_string(),
defaults: placeholders
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect(),
shell_kinds: Vec::new(),
ssh_only,
confirm,
pinned: false,
created_at: 0,
}
}
vec![
mk(
"snip-find-large",
"查找大文件",
"find ${dir} -type f -size +${size} -exec ls -lh {} \\;",
"列出指定目录下大于指定体积的文件。size 用 100M / 1G 这类写法。",
"文件",
&[("dir", "/"), ("size", "100M")],
false,
false,
),
mk(
"snip-grep-recursive",
"递归搜索内容",
"grep -rn --include=${pattern} '${keyword}' ${dir}",
"在指定目录下按文件名模式递归搜索关键字。",
"文件",
&[("pattern", "*.log"), ("keyword", ""), ("dir", ".")],
false,
false,
),
mk(
"snip-tar-extract",
"解压 tar.gz",
"tar -xzvf ${file} -C ${target}",
"解压到指定目录。target 留空则解到当前目录。",
"文件",
&[("file", ""), ("target", ".")],
false,
false,
),
mk(
"snip-df",
"磁盘占用概览",
"df -h | sort -k5 -hr | head -20",
"按使用率倒序列出挂载点。排查「磁盘满了」的第一步。",
"诊断",
&[],
false,
false,
),
mk(
"snip-port-owner",
"查端口占用",
"ss -tlnp | grep ${port}",
"查看监听指定端口的进程。老系统若无 ss,改用 netstat -tlnp。",
"诊断",
&[("port", "8080")],
false,
false,
),
mk(
"snip-top-cpu",
"CPU 占用前 10",
"ps aux --sort=-%cpu | head -11",
"按 CPU 占用倒序列出进程(含表头共 11 行)。",
"诊断",
&[],
false,
false,
),
mk(
"snip-tail-follow",
"跟踪日志",
"tail -f ${file}",
"实时跟随文件新增内容。Ctrl+C 退出。",
"运维",
&[("file", "")],
false,
false,
),
mk(
"snip-systemd-status",
"服务状态",
"systemctl status ${service} --no-pager",
"查看 systemd 服务状态。--no-pager 让输出直接落到终端而不是进 less。",
"运维",
&[("service", "")],
true,
false,
),
mk(
"snip-perm-fix",
"递归修正属主",
"chown -R ${owner}:${group} ${dir}",
"递归修改目录属主与属组。",
"运维",
&[("owner", ""), ("group", ""), ("dir", "")],
true,
true,
),
mk(
"snip-ssh-tunnel",
"建立 SSH 隧道",
"ssh -N -L ${localPort}:${remoteHost}:${remotePort} ${user}@${jumpHost}",
"本地端口转发。localPort 是你要在本机访问的端口。",
"网络",
&[
("localPort", "8080"),
("remoteHost", "127.0.0.1"),
("remotePort", "80"),
("user", ""),
("jumpHost", ""),
],
false,
false,
),
mk(
"snip-ssh-keygen",
"生成 SSH 密钥",
"ssh-keygen -t ed25519 -C \"${comment}\" -f ~/.ssh/${name}",
"生成 ed25519 密钥对。ed25519 比 RSA 短且更快,现代环境首选。",
"网络",
&[("comment", ""), ("name", "id_ed25519")],
false,
false,
),
]
}