diff --git a/extensions/wasm/windterm-importer/extension.json b/extensions/wasm/windterm-importer/extension.json index b9c6303..6898221 100644 --- a/extensions/wasm/windterm-importer/extension.json +++ b/extensions/wasm/windterm-importer/extension.json @@ -2,8 +2,8 @@ "schema_version": 1, "id": "com.onetcli.importer.windterm", "name": "WindTerm Importer", - "description": "从 WindTerm profile 的 user.sessions 文件中发现 SSH 连接,并通过 Rust WASM 导入到 Navop;支持默认、自定义和手动选择的 profile。 Discovers SSH connections from WindTerm profile user.sessions files and imports them into Navop through Rust WASM, including default, custom, and manually selected profiles.", - "version": "0.1.0", + "description": "从 WindTerm 安装目录或 profile 配置中导入 SSH/Telnet 会话、分组、QuickBar 快捷命令及快捷键绑定,通过 Rust WASM 安全运行时导入到 Navop。 Imports SSH/Telnet sessions, groups, QuickBar commands, and keybindings from WindTerm directories or profile files through Rust WASM.", + "version": "0.2.0", "publisher": "Navop", "engines": { "onetcli": ">=0.7.0" @@ -17,7 +17,7 @@ "id": "windterm-importer", "module": "wasm/windterm_importer_wasm.wasm", "kind": "component", - "timeout_ms": 5000, + "timeout_ms": 10000, "max_memory_mb": 64 } ] @@ -32,10 +32,14 @@ "id": "windterm", "runtimeId": "windterm-importer", "displayName": "WindTerm", - "description": "从 WindTerm profiles 配置目录或 user.sessions 文件发现并导入 SSH 连接。 Discover and import SSH connections from WindTerm profiles directories or user.sessions files.", + "description": "从 WindTerm 安装目录、.wind 配置目录或 user.sessions / quickbar.config / wind.keymaps 文件发现并导入 SSH/Telnet 会话、分组、快捷命令及快捷键。 Discover and import SSH/Telnet sessions, groups, QuickBar commands, and keybindings from WindTerm directories or files.", "icon": "terminal", "outputKinds": [ - "ssh" + "ssh", + "telnet", + "quick-command", + "workspace", + "keybinding" ], "platforms": [ "macos", @@ -43,9 +47,9 @@ "linux" ], "manualFilePick": { - "prompt": "选择 WindTerm user.sessions 文件", + "prompt": "选择 WindTerm user.sessions / quickbar.config / wind.keymaps 文件", "supportsDirectories": true, - "directoryPrompt": "选择 WindTerm profiles 配置目录" + "directoryPrompt": "选择 WindTerm 安装目录或 .wind 配置目录" }, "candidateFiles": [ { diff --git a/extensions/wasm/windterm-importer/src/component.rs b/extensions/wasm/windterm-importer/src/component.rs index fda1280..5c49605 100644 --- a/extensions/wasm/windterm-importer/src/component.rs +++ b/extensions/wasm/windterm-importer/src/component.rs @@ -3,31 +3,38 @@ wit_bindgen::generate!({ world: "connection-importer", }); -use onet::extension::{connection_import::CandidateFile, connection_import_host}; +use std::collections::BTreeSet; -struct WindtermImporter; +use onet::extension::{ + connection_import::{CandidateFile, Platform}, + connection_import_host, +}; -struct SessionFile { - candidate_id: String, - path: String, - bytes: Vec, -} +use crate::windterm::{DiscoveredFiles, InputFile, TargetPlatform}; + +struct WindtermImporter; impl Guest for WindtermImporter { fn descriptor() -> String { serde_json::json!({ "id": "windterm", "display_name": "WindTerm", - "description": "Import SSH sessions from WindTerm profiles", + "description": "Import SSH/Telnet sessions, groups, QuickBar commands, and keybindings from WindTerm", "icon": "terminal", "vendor": "Navop", "supported_platforms": ["macos", "windows", "linux"], - "output_kinds": ["ssh"], + "output_kinds": if host_supports_keybindings() { + serde_json::json!(["ssh", "telnet", "quick_command", "workspace", "keybinding"]) + } else { + serde_json::json!(["ssh", "telnet", "quick_command", "workspace"]) + }, "capabilities": { "supports_scan": true, "supports_password_import": false, "supports_manual_file_pick": true, - "manual_file_pick_prompt": "Select a WindTerm user.sessions file", + "supports_manual_directory_pick": true, + "manual_file_pick_prompt": "Select WindTerm user.sessions, quickbar.config, or wind.keymaps", + "manual_directory_pick_prompt": "Select WindTerm installation or .wind profile directory", "supports_incremental_preview": false } }) @@ -35,76 +42,189 @@ impl Guest for WindtermImporter { } fn scan() -> String { + let platform = map_platform(connection_import_host::current_platform()); + let include_keybindings = host_supports_keybindings(); let candidates = connection_import_host::list_candidate_files("windterm"); - let files = read_session_files(&candidates); - let availability = if files.is_empty() { - serde_json::json!("no_data") - } else { - serde_json::json!({ "available": { "estimated_count": null } }) - }; - - serde_json::json!({ - "importer_id": "windterm", - "availability": availability, - "discovered_files": files.iter().map(|file| { - serde_json::json!({ - "candidate_id": file.candidate_id, - "display_path": file.path - }) - }).collect::>(), - "warnings": [] + let files = discover_windterm_files(&candidates); + let report = + crate::windterm::scan_report_from_files(&files, platform, include_keybindings); + serde_json::to_string(&report).unwrap_or_else(|_| { + serde_json::json!({ + "importer_id": "windterm", + "availability": "no_data", + "discovered_files": [], + "warnings": [], + "discovered_workspace_paths": [] + }) + .to_string() }) - .to_string() } fn preview(options: ImportOptions) -> String { + let platform = map_platform(connection_import_host::current_platform()); + let include_keybindings = host_supports_keybindings(); let candidates = connection_import_host::list_candidate_files("windterm"); - let files = read_session_files(&candidates); - let records = crate::windterm::preview_records_from_session_files( - files - .iter() - .map(|file| (file.path.clone(), file.bytes.as_slice())), + let files = discover_windterm_files(&candidates); + let records = crate::windterm::preview_records_from_files( + &files, + platform, options.include_passwords, + include_keybindings, ); serde_json::to_string(&records).unwrap_or_else(|_| "[]".to_string()) } } -fn read_session_files(candidates: &[CandidateFile]) -> Vec { - let mut files = Vec::new(); +fn host_supports_keybindings() -> bool { + std::env::var("NAVOP_IMPORT_CAPABILITIES") + .ok() + .is_some_and(|caps| { + caps.split(',') + .any(|cap| cap.trim().eq_ignore_ascii_case("keybinding")) + }) +} + +fn map_platform(platform: Platform) -> TargetPlatform { + match platform { + Platform::Macos => TargetPlatform::Macos, + Platform::Windows => TargetPlatform::Windows, + Platform::Linux => TargetPlatform::Linux, + } +} + +fn discover_windterm_files(candidates: &[CandidateFile]) -> DiscoveredFiles { + let mut files = DiscoveredFiles::default(); + let mut seen_paths = BTreeSet::new(); + for candidate in candidates { if let Ok(entries) = connection_import_host::read_directory(&candidate.id) { - for entry in entries { - if !entry.is_dir || !safe_profile_name(&entry.name) { - continue; - } - let relative_path = format!("{}/terminal/user.sessions", entry.name); - if let Ok(bytes) = connection_import_host::read_candidate_child_file( - &entry.candidate_id, - &relative_path, - ) { - files.push(SessionFile { - candidate_id: candidate.id.clone(), - path: format!("{}/{}", candidate.path, relative_path), - bytes, - }); - } - } + walk_candidate_dir( + candidate, + "", + entries, + 0, + &mut files, + &mut seen_paths, + ); continue; } if let Ok(bytes) = connection_import_host::read_file(&candidate.id) { - files.push(SessionFile { + let file_name = file_name_of(&candidate.path); + let input = InputFile { candidate_id: candidate.id.clone(), - path: candidate.path.clone(), + display_path: candidate.path.clone(), bytes, - }); + }; + classify_and_push(file_name, input, &mut files, &mut seen_paths); } } + + files.sort_deterministic(); files } -fn safe_profile_name(name: &str) -> bool { +fn walk_candidate_dir( + candidate: &CandidateFile, + relative_prefix: &str, + entries: Vec, + depth: usize, + files: &mut DiscoveredFiles, + seen_paths: &mut BTreeSet, +) { + if depth > 6 { + return; + } + + for entry in entries { + if !safe_entry_name(&entry.name) { + continue; + } + let relative = if relative_prefix.is_empty() { + entry.name.clone() + } else { + format!("{relative_prefix}/{}", entry.name) + }; + + if entry.is_dir { + if should_skip_dir(&entry.name, relative_prefix) { + continue; + } + if let Ok(children) = + connection_import_host::read_candidate_directory(&candidate.id, &relative) + { + walk_candidate_dir(candidate, &relative, children, depth + 1, files, seen_paths); + } + continue; + } + + if !is_windterm_target_file(&entry.name) { + continue; + } + if let Ok(bytes) = + connection_import_host::read_candidate_child_file(&candidate.id, &relative) + { + let display_path = format!( + "{}/{}", + candidate.path.trim_end_matches(['/', '\\']), + relative + ); + let input = InputFile { + candidate_id: candidate.id.clone(), + display_path, + bytes, + }; + classify_and_push(&entry.name, input, files, seen_paths); + } + } +} + +fn classify_and_push( + file_name: &str, + input: InputFile, + files: &mut DiscoveredFiles, + seen_paths: &mut BTreeSet, +) { + let lower = file_name.to_ascii_lowercase(); + let dedup_key = input.display_path.replace('\\', "/"); + if !seen_paths.insert(dedup_key) { + return; + } + if lower == "user.sessions" || lower.ends_with(".sessions") { + files.session_files.push(input); + } else if lower == "quickbar.config" { + files.quickbar_files.push(input); + } else if lower == "wind.keymaps" || lower.ends_with(".keymaps") { + files.keymap_files.push(input); + } +} + +fn is_windterm_target_file(name: &str) -> bool { + let lower = name.to_ascii_lowercase(); + lower == "user.sessions" + || lower == "quickbar.config" + || lower == "wind.keymaps" + || lower.ends_with(".keymaps") +} + +fn should_skip_dir(name: &str, relative_prefix: &str) -> bool { + if matches!( + name, + "logs" | "themes" | "locales" | "schemes" | "vendors" | "plugins" | "palettes" + ) { + return true; + } + if name == ".wind" && relative_prefix.ends_with(".wind") { + return true; + } + false +} + +fn file_name_of(path: &str) -> &str { + path.rsplit(['/', '\\']).next().unwrap_or(path) +} + +fn safe_entry_name(name: &str) -> bool { !name.is_empty() && name != "." && name != ".." && !name.contains(['/', '\\']) } diff --git a/extensions/wasm/windterm-importer/src/windterm.rs b/extensions/wasm/windterm-importer/src/windterm.rs index cd801a8..d0694c3 100644 --- a/extensions/wasm/windterm-importer/src/windterm.rs +++ b/extensions/wasm/windterm-importer/src/windterm.rs @@ -1,6 +1,78 @@ -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use serde::{Deserialize, Serialize}; +use serde_json::Value; + +pub const WINDTERM_IMPORTER_ID: &str = "windterm"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TargetPlatform { + Macos, + Windows, + Linux, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct InputFile { + pub candidate_id: String, + pub display_path: String, + pub bytes: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct DiscoveredFiles { + pub session_files: Vec, + pub quickbar_files: Vec, + pub keymap_files: Vec, +} + +impl DiscoveredFiles { + pub fn is_empty(&self) -> bool { + self.session_files.is_empty() + && self.quickbar_files.is_empty() + && self.keymap_files.is_empty() + } + + pub fn sort_deterministic(&mut self) { + self.session_files.sort_by(|a, b| { + let a_nested = a.display_path.replace('\\', "/").contains(".wind/.wind"); + let b_nested = b.display_path.replace('\\', "/").contains(".wind/.wind"); + (a_nested, &a.display_path).cmp(&(b_nested, &b.display_path)) + }); + self.quickbar_files.sort_by(|a, b| { + let a_nested = a.display_path.replace('\\', "/").contains(".wind/.wind"); + let b_nested = b.display_path.replace('\\', "/").contains(".wind/.wind"); + (a_nested, &a.display_path).cmp(&(b_nested, &b.display_path)) + }); + self.keymap_files.sort_by(|a, b| { + let a_profile = !a.display_path.replace('\\', "/").contains("profiles"); + let b_profile = !b.display_path.replace('\\', "/").contains("profiles"); + (a_profile, &a.display_path).cmp(&(b_profile, &b.display_path)) + }); + } + + pub fn all_files(&self) -> impl Iterator { + self.session_files + .iter() + .chain(self.quickbar_files.iter()) + .chain(self.keymap_files.iter()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct ImportScanReport { + pub importer_id: String, + pub availability: Value, + pub discovered_files: Vec, + pub warnings: Vec, + pub discovered_workspace_paths: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct DiscoveredFile { + pub candidate_id: String, + pub display_path: String, +} #[derive(Clone, Debug, PartialEq, Eq, Serialize)] pub struct ImportRecord { @@ -10,9 +82,17 @@ pub struct ImportRecord { pub source_id: Option, pub kind: String, pub display_name: String, - pub database: Option, + pub database: Option, pub ssh: Option, - pub port_forwarding: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub telnet: Option, + pub port_forwarding: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub quick_command: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub workspace: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub keybinding: Option, pub password_status: String, pub warnings: Vec, } @@ -23,10 +103,71 @@ pub struct SshImportRecord { pub host: String, pub port: Option, pub username: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub group_path: Option, pub auth_method: SshImportAuthMethod, pub init_script: Option, - pub jump_server: Option, - pub proxy: Option, + pub jump_server: Option, + pub proxy: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct TelnetImportRecord { + pub name: String, + pub host: String, + pub port: Option, + pub username: Option, + pub password: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub group_path: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct QuickCommandImportRecord { + pub name: String, + pub command: String, + pub group_name: Option, + pub shortcut: Option, + pub description: Option, + pub sort_order: i32, + pub connection_source_id: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct WorkspaceImportRecord { + pub path: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct KeybindingImportRecord { + pub action_id: String, + pub shortcuts: Vec, + pub source_action: Option, + pub description: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct SshJumpServerImportRecord { + pub host: String, + pub port: u16, + pub username: String, + pub auth_method: SshImportAuthMethod, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct SshProxyImportRecord { + pub kind: SshProxyImportKind, + pub host: String, + pub port: u16, + pub username: Option, + pub password: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum SshProxyImportKind { + Socks5, + Http, } #[derive(Clone, Debug, PartialEq, Eq, Serialize)] @@ -62,33 +203,41 @@ struct WindTermSession { #[serde(rename = "session.target")] target: Option, #[serde(rename = "session.port")] - port: Option, + port: Option, #[serde(rename = "session.user")] user: Option, #[serde(rename = "session.description")] description: Option, #[serde(rename = "session.autoLogin")] - auto_login: Option, + auto_login: Option, #[serde(rename = "ssh.autoLogin")] - ssh_auto_login: Option, + ssh_auto_login: Option, #[serde(rename = "ssh.identityFilePath")] identity_file_path: Option, + #[serde(rename = "ssh.identityFilePath.windows")] + identity_file_path_windows: Option, + #[serde(rename = "ssh.identityFilePath.macos")] + identity_file_path_macos: Option, + #[serde(rename = "ssh.identityFilePath.linux")] + identity_file_path_linux: Option, #[serde(rename = "ssh.agent")] - agent: Option, + agent: Option, #[serde(rename = "ssh.authAgent")] - auth_agent: Option, + auth_agent: Option, #[serde(rename = "ssh.authPassword")] - auth_password: Option, + auth_password: Option, #[serde(rename = "session.autoExecution")] auto_execution: Option, + #[serde(rename = "ssh.autoExecution")] + ssh_auto_execution: Option, #[serde(rename = "session.proxy")] - proxy: Option, + proxy: Option, #[serde(rename = "session.proxyHost")] proxy_host: Option, #[serde(rename = "session.proxyJumpServer1")] - jump_server: Option, + jump_server: Option, #[serde(rename = "ssh.tunnels")] - tunnels: Option, + tunnels: Option, } #[derive(Debug)] @@ -99,80 +248,286 @@ struct ParsedTarget { inline_password_ignored: bool, } -pub fn preview_records_from_session_files<'a, I>( - files: I, +#[derive(Clone, Debug)] +struct NormalizedSession { + uuid: String, + protocol: String, + label: Option, + group: Option, + target: String, + port: Option, + user: Option, + encrypted_auto_login: bool, + identity_file: Option, + use_agent: bool, + auth_password: bool, + init_script: Option, + proxy_value: Option, + proxy_host: Option, + jump_server_ref: Option, + has_tunnels: bool, +} + +pub fn scan_report_from_files( + files: &DiscoveredFiles, + platform: TargetPlatform, + include_keybindings: bool, +) -> ImportScanReport { + if files.is_empty() { + return ImportScanReport { + importer_id: WINDTERM_IMPORTER_ID.to_string(), + availability: serde_json::json!("no_data"), + discovered_files: Vec::new(), + warnings: Vec::new(), + discovered_workspace_paths: Vec::new(), + }; + } + + let mut warnings = Vec::new(); + let mut workspace_paths = BTreeSet::new(); + let mut seen_ids = BTreeSet::new(); + + for file in &files.session_files { + let (records, file_warnings) = + parse_sessions_bytes(&file.display_path, &file.bytes, platform); + for record in records { + if let Some(group) = record + .ssh + .as_ref() + .and_then(|ssh| ssh.group_path.as_deref()) + .or_else(|| { + record + .telnet + .as_ref() + .and_then(|telnet| telnet.group_path.as_deref()) + }) + { + workspace_paths.insert(group.to_string()); + } + seen_ids.insert(record.id); + } + warnings.extend(file_warnings); + } + + for file in &files.quickbar_files { + for record in parse_quickbar_bytes(&file.bytes) { + seen_ids.insert(record.id); + } + } + + if include_keybindings { + if let Some(keymap_file) = files.keymap_files.first() { + if let Ok(text) = std::str::from_utf8(&keymap_file.bytes) { + for record in parse_keymaps_text(text, platform == TargetPlatform::Macos) { + seen_ids.insert(record.id); + } + } + } + } + + let estimated_count = seen_ids.len() as u32; + let availability = if estimated_count > 0 { + serde_json::json!({ "available": { "estimated_count": estimated_count } }) + } else { + serde_json::json!("no_data") + }; + + ImportScanReport { + importer_id: WINDTERM_IMPORTER_ID.to_string(), + availability, + discovered_files: files + .all_files() + .map(|file| DiscoveredFile { + candidate_id: file.candidate_id.clone(), + display_path: file.display_path.clone(), + }) + .collect(), + warnings, + discovered_workspace_paths: workspace_paths.into_iter().collect(), + } +} + +pub fn preview_records_from_files( + files: &DiscoveredFiles, + platform: TargetPlatform, _include_passwords: bool, -) -> Vec -where - I: IntoIterator, -{ + include_keybindings: bool, +) -> Vec { let mut records = Vec::new(); let mut seen_ids = BTreeSet::new(); - for (path, bytes) in files { - let Ok(sessions) = serde_json::from_slice::>(bytes) else { - continue; - }; - for session in sessions { - let Some(record) = record_from_session(&path, session) else { - continue; - }; + + for file in &files.session_files { + let (parsed, _warnings) = parse_sessions_bytes(&file.display_path, &file.bytes, platform); + for record in parsed { + if seen_ids.insert(record.id.clone()) { + records.push(record); + } + } + } + + for file in &files.quickbar_files { + for record in parse_quickbar_bytes(&file.bytes) { if seen_ids.insert(record.id.clone()) { records.push(record); } } } + + if include_keybindings { + if let Some(keymap_file) = files.keymap_files.first() { + if let Ok(text) = std::str::from_utf8(&keymap_file.bytes) { + for record in parse_keymaps_text(text, platform == TargetPlatform::Macos) { + if seen_ids.insert(record.id.clone()) { + records.push(record); + } + } + } + } + } + records } -fn record_from_session(path: &str, session: WindTermSession) -> Option { - if !trimmed(session.protocol.as_deref()).eq_ignore_ascii_case("ssh") { - return None; +pub fn preview_records_from_session_files<'a, I>( + files: I, + include_passwords: bool, +) -> Vec +where + I: IntoIterator, +{ + let discovered = DiscoveredFiles { + session_files: files + .into_iter() + .map(|(display_path, bytes)| InputFile { + candidate_id: String::new(), + display_path, + bytes: bytes.to_vec(), + }) + .collect(), + quickbar_files: Vec::new(), + keymap_files: Vec::new(), + }; + preview_records_from_files(&discovered, TargetPlatform::Linux, include_passwords, false) +} + +pub fn parse_sessions_bytes( + path: &str, + bytes: &[u8], + platform: TargetPlatform, +) -> (Vec, Vec) { + let Ok(sessions) = serde_json::from_slice::>(bytes) else { + return (Vec::new(), Vec::new()); + }; + + let mut normalized = Vec::with_capacity(sessions.len()); + for (index, session) in sessions.into_iter().enumerate() { + let identity_file = extract_identity_file(&session, platform); + let protocol = trimmed(session.protocol.as_deref()).to_string(); + let target = trimmed(session.target.as_deref()).to_string(); + let group = session.group.as_deref().and_then(normalize_group_path); + let port = parse_port(session.port.as_ref()); + let label = non_empty(session.label).or_else(|| non_empty(session.description)); + let uuid = non_empty(session.uuid).unwrap_or_else(|| { + format!( + "{}:{}:{}:{}:{}", + path, + group.as_deref().unwrap_or_default(), + target, + port.unwrap_or(0), + index + ) + }); + let encrypted_auto_login = + has_data(session.auto_login.as_ref()) || has_data(session.ssh_auto_login.as_ref()); + let use_agent = truthy(session.agent.as_ref()) || truthy(session.auth_agent.as_ref()); + let auth_password = truthy(session.auth_password.as_ref()); + let init_script = + non_empty(session.auto_execution).or_else(|| non_empty(session.ssh_auto_execution)); + let jump_server_ref = session + .jump_server + .as_ref() + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty() && !s.eq_ignore_ascii_case("none")) + .map(str::to_string); + let has_tunnels = has_data(session.tunnels.as_ref()); + + normalized.push(NormalizedSession { + uuid, + protocol, + label, + group, + target, + port, + user: non_empty(session.user), + encrypted_auto_login, + identity_file, + use_agent, + auth_password, + init_script, + proxy_value: session.proxy, + proxy_host: non_empty(session.proxy_host), + jump_server_ref, + has_tunnels, + }); } - let target = parse_target(trimmed(session.target.as_deref()))?; - let port = parse_port(session.port.as_ref()) - .or(target.port) - .or(Some(22)); - let username = non_empty(session.user) - .or(target.username) - .unwrap_or_default(); - let label = non_empty(session.label).or_else(|| non_empty(session.description)); - let group = non_empty(session.group); - let display_name = label.unwrap_or_else(|| target.host.clone()); - let source_id = non_empty(session.uuid).unwrap_or_else(|| { - format!( - "{}:{}:{}:{}", - path, - group.as_deref().unwrap_or_default(), - target.host, - port.unwrap_or(22) - ) - }); - let id = format!("windterm:{}", slug(&source_id)); - - let encrypted_auto_login = - has_data(session.auto_login.as_ref()) || has_data(session.ssh_auto_login.as_ref()); - let identity_file_path = non_empty(session.identity_file_path); - let auth_method = if let Some(key_path) = identity_file_path { - SshImportAuthMethod::PrivateKey { - key_path, - passphrase: None, + let ssh_index: HashMap = normalized + .iter() + .filter(|s| s.protocol.eq_ignore_ascii_case("ssh")) + .map(|s| (s.uuid.clone(), s)) + .collect(); + + let mut records = Vec::new(); + let mut skipped_by_protocol: BTreeMap = BTreeMap::new(); + + for raw in &normalized { + if raw.protocol.eq_ignore_ascii_case("ssh") { + if let Some(record) = build_ssh_record(raw, &ssh_index) { + records.push(record); + } + } else if raw.protocol.eq_ignore_ascii_case("telnet") { + if let Some(record) = build_telnet_record(raw) { + records.push(record); + } + } else { + let key = if raw.protocol.is_empty() { + "Unknown".to_string() + } else { + raw.protocol.clone() + }; + *skipped_by_protocol.entry(key).or_insert(0) += 1; } - } else if truthy(session.agent.as_ref()) || truthy(session.auth_agent.as_ref()) { - SshImportAuthMethod::Agent - } else if truthy(session.auth_password.as_ref()) { - SshImportAuthMethod::Password { password: None } - } else { - SshImportAuthMethod::AutoPublicKey - }; + } let mut warnings = Vec::new(); - if encrypted_auto_login { + if !skipped_by_protocol.is_empty() { + let detail = skipped_by_protocol + .into_iter() + .map(|(proto, count)| format!("{proto}: {count}")) + .collect::>() + .join(", "); warnings.push(warning( - "windterm_encrypted_auto_login", - "WindTerm auto-login data is encrypted and was not imported.", + "windterm_skipped_protocols", + &format!("Skipped non-SSH/Telnet WindTerm sessions ({detail})"), )); } + + (records, warnings) +} + +fn build_ssh_record( + raw: &NormalizedSession, + ssh_index: &HashMap, +) -> Option { + let target = parse_target(&raw.target)?; + let port = raw.port.or(target.port).or(Some(22)); + let username = raw.user.clone().or(target.username).unwrap_or_default(); + let display_name = raw.label.clone().unwrap_or_else(|| target.host.clone()); + let id = format!("windterm:{}", slug(&raw.uuid)); + + let (auth_method, password_status, mut warnings) = resolve_ssh_auth(raw); + if target.inline_password_ignored { warnings.push(warning( "windterm_inline_password_ignored", @@ -185,32 +540,26 @@ fn record_from_session(path: &str, session: WindTermSession) -> Option Option Option { - let value = value.trim(); - if value.is_empty() { +fn build_telnet_record(raw: &NormalizedSession) -> Option { + let target = parse_target(&raw.target)?; + let port = raw.port.or(target.port).or(Some(23)); + let username = raw.user.clone().or(target.username); + let display_name = raw.label.clone().unwrap_or_else(|| target.host.clone()); + let id = format!("windterm:telnet:{}", slug(&raw.uuid)); + + let (password_status, warnings) = if raw.encrypted_auto_login { + ( + "unsupported", + vec![warning( + "windterm_encrypted_auto_login", + "WindTerm auto-login data is encrypted and was not imported.", + )], + ) + } else { + ("missing", Vec::new()) + }; + + Some(ImportRecord { + id, + importer_id: WINDTERM_IMPORTER_ID.to_string(), + source_label: "WindTerm".to_string(), + source_id: Some(raw.uuid.clone()), + kind: "telnet".to_string(), + display_name: display_name.clone(), + database: None, + ssh: None, + telnet: Some(TelnetImportRecord { + name: display_name, + host: target.host, + port, + username, + password: None, + group_path: raw.group.clone(), + }), + port_forwarding: None, + quick_command: None, + workspace: None, + keybinding: None, + password_status: password_status.to_string(), + warnings, + }) +} + +fn resolve_ssh_auth(raw: &NormalizedSession) -> (SshImportAuthMethod, &'static str, Vec) { + let mut warnings = Vec::new(); + if raw.encrypted_auto_login { + warnings.push(warning( + "windterm_encrypted_auto_login", + "WindTerm auto-login data is encrypted and was not imported.", + )); + } + + if let Some(key_path) = &raw.identity_file { + return ( + SshImportAuthMethod::PrivateKey { + key_path: key_path.clone(), + passphrase: None, + }, + "unsupported", + warnings, + ); + } + if raw.use_agent { + return (SshImportAuthMethod::Agent, "unsupported", warnings); + } + if raw.auth_password || raw.encrypted_auto_login { + return ( + SshImportAuthMethod::Password { password: None }, + if raw.encrypted_auto_login { + "unsupported" + } else { + "missing" + }, + warnings, + ); + } + + (SshImportAuthMethod::AutoPublicKey, "missing", warnings) +} + +fn resolve_jump_server( + jump_ref: &str, + ssh_index: &HashMap, + warnings: &mut Vec, +) -> Option { + let jump_uuid = jump_ref.split(',').next().map(str::trim).unwrap_or_default(); + let Some(jump_raw) = ssh_index.get(jump_uuid) else { + warnings.push(warning( + "windterm_jump_server_not_found", + &format!("Jump server reference not found: {jump_ref}"), + )); return None; + }; + let target = parse_target(&jump_raw.target)?; + let (auth_method, _, _) = resolve_ssh_auth(jump_raw); + Some(SshJumpServerImportRecord { + host: target.host, + port: jump_raw.port.or(target.port).unwrap_or(22), + username: jump_raw + .user + .clone() + .or(target.username) + .unwrap_or_else(|| "root".to_string()), + auth_method, + }) +} + +fn resolve_proxy( + proxy_value: Option<&Value>, + proxy_host: Option<&str>, + warnings: &mut Vec, +) -> Option { + if let Some(raw_str) = proxy_value.and_then(Value::as_str) { + let trimmed = raw_str.trim(); + if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("none") { + return None; + } + if let Some(parsed) = parse_proxy_url(trimmed, warnings) { + return Some(parsed); + } + } + if has_data(proxy_value) || proxy_host.is_some() { + warnings.push(warning( + "windterm_proxy_not_imported", + "WindTerm proxy settings are not imported yet.", + )); + } + None +} + +fn parse_proxy_url( + proxy_str: &str, + warnings: &mut Vec, +) -> Option { + let (scheme, rest) = proxy_str.split_once("://")?; + let kind = match scheme.to_ascii_lowercase().as_str() { + "socks5" | "socks5h" => SshProxyImportKind::Socks5, + "http" | "https" => SshProxyImportKind::Http, + other => { + warnings.push(warning( + "windterm_unsupported_proxy", + &format!("Unsupported proxy scheme: {other}"), + )); + return None; + } + }; + let authority = rest.split('/').next().unwrap_or(rest); + let (userinfo, host_port) = match authority.rsplit_once('@') { + Some((u, hp)) => (Some(u), hp), + None => (None, authority), + }; + let (username, password) = match userinfo { + Some(u) => match u.split_once(':') { + Some((user, pass)) => ( + (!user.is_empty()).then(|| user.to_string()), + Some(pass.to_string()), + ), + None => ((!u.is_empty()).then(|| u.to_string()), None), + }, + None => (None, None), + }; + let (host, port) = split_host_port(host_port)?; + let default_port = match scheme.to_ascii_lowercase().as_str() { + "https" => 443, + "http" => 80, + _ => 1080, + }; + Some(SshProxyImportRecord { + kind, + host, + port: port.unwrap_or(default_port), + username, + password, + }) +} + +fn extract_identity_file(session: &WindTermSession, platform: TargetPlatform) -> Option { + let candidates = match platform { + TargetPlatform::Windows => [ + session.identity_file_path_windows.as_deref(), + session.identity_file_path.as_deref(), + session.identity_file_path_linux.as_deref(), + session.identity_file_path_macos.as_deref(), + ], + TargetPlatform::Macos => [ + session.identity_file_path_macos.as_deref(), + session.identity_file_path.as_deref(), + session.identity_file_path_linux.as_deref(), + session.identity_file_path_windows.as_deref(), + ], + TargetPlatform::Linux => [ + session.identity_file_path_linux.as_deref(), + session.identity_file_path.as_deref(), + session.identity_file_path_macos.as_deref(), + session.identity_file_path_windows.as_deref(), + ], + }; + + for candidate in candidates.into_iter().flatten() { + let trimmed = candidate.trim(); + if !trimmed.is_empty() { + let normalized = trimmed.replace('\\', "/"); + let cleaned = normalized + .strip_suffix(".pub") + .unwrap_or(&normalized) + .to_string(); + return Some(cleaned); + } + } + None +} + +fn normalize_group_path(raw: &str) -> Option { + let normalized = raw.replace('\\', "/"); + let parts = normalized + .split('/') + .map(str::trim) + .filter(|part| !part.is_empty() && !matches!(*part, "." | "..")) + .collect::>(); + (!parts.is_empty()).then(|| parts.join("/")) +} + +pub fn parse_quickbar_bytes(bytes: &[u8]) -> Vec { + let Ok(value) = serde_json::from_slice::(bytes) else { + return Vec::new(); + }; + let Some(items) = value.as_array() else { + return Vec::new(); + }; + + let mut records = Vec::new(); + for (index, item) in items.iter().enumerate() { + let Some(map) = item.as_object() else { + continue; + }; + let raw_text = map + .get("quick.text") + .and_then(Value::as_str) + .unwrap_or_default(); + let command = normalize_quickbar_command(raw_text); + if command.is_empty() { + continue; + } + let label = map + .get("quick.label") + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) + .unwrap_or_else(|| command.clone()); + let group_name = map + .get("quick.group") + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string); + let uuid = map + .get("quick.uuid") + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) + .unwrap_or_else(|| format!("quickbar-{index}")); + let shortcut = map + .get("quick.shortcut") + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string); + + records.push(ImportRecord { + id: format!("windterm:quick:{uuid}"), + importer_id: WINDTERM_IMPORTER_ID.to_string(), + source_label: "WindTerm".to_string(), + source_id: Some(uuid), + kind: "quick_command".to_string(), + display_name: label.clone(), + database: None, + ssh: None, + telnet: None, + port_forwarding: None, + quick_command: Some(QuickCommandImportRecord { + name: label, + command, + group_name, + shortcut, + description: None, + sort_order: index as i32, + connection_source_id: None, + }), + workspace: None, + keybinding: None, + password_status: "unsupported".to_string(), + warnings: Vec::new(), + }); } - let value = value + records +} + +fn normalize_quickbar_command(raw: &str) -> String { + let mut text = raw + .replace("\\r\\n", "\n") + .replace("\\n", "\n") + .replace("\\r", "\n"); + text = text.replace("\r\n", "\n").replace('\r', "\n"); + text.trim_end_matches('\n').trim().to_string() +} + +pub fn parse_keymaps_text(text: &str, prefer_macos: bool) -> Vec { + let mut bindings: BTreeMap<&'static str, (String, Vec, Vec)> = BTreeMap::new(); + + for block in extract_keymap_blocks(text) { + let Some(keys) = extract_json_string_field(&block, "keys") else { + continue; + }; + let Some(action) = extract_json_string_field(&block, "action") else { + continue; + }; + if let Some(modes) = extract_json_string_field(&block, "modes") { + if (modes.contains("command") || modes.contains("local")) + && !modes.contains("normal") + && !modes.contains("remote") + { + continue; + } + } + let Some((navop_action_id, label)) = map_windterm_action(&action) else { + continue; + }; + let Some(shortcut) = convert_windterm_keys(&keys, prefer_macos) else { + continue; + }; + let entry = bindings + .entry(navop_action_id) + .or_insert_with(|| (label.to_string(), Vec::new(), Vec::new())); + if !entry.1.contains(&shortcut) { + entry.1.push(shortcut); + } + if !entry.2.contains(&action) { + entry.2.push(action); + } + } + + bindings + .into_iter() + .map(|(navop_action_id, (label, shortcuts, source_actions))| ImportRecord { + id: format!("windterm:keybinding:{navop_action_id}"), + importer_id: WINDTERM_IMPORTER_ID.to_string(), + source_label: "WindTerm".to_string(), + source_id: Some(navop_action_id.to_string()), + kind: "keybinding".to_string(), + display_name: label, + database: None, + ssh: None, + telnet: None, + port_forwarding: None, + quick_command: None, + workspace: None, + keybinding: Some(KeybindingImportRecord { + action_id: navop_action_id.to_string(), + shortcuts, + source_action: Some(source_actions.join(", ")), + description: None, + }), + password_status: "unsupported".to_string(), + warnings: Vec::new(), + }) + .collect() +} + +fn extract_keymap_blocks(text: &str) -> Vec { + let mut blocks = Vec::new(); + let mut in_string = false; + let mut escaped = false; + let mut depth: usize = 0; + let mut start: Option = None; + + for (idx, ch) in text.char_indices() { + if in_string { + if escaped { + escaped = false; + } else if ch == '\\' { + escaped = true; + } else if ch == '"' { + in_string = false; + } + continue; + } + match ch { + '"' => in_string = true, + '{' => { + if depth == 0 { + start = Some(idx); + } + depth += 1; + } + '}' => { + if depth > 0 { + depth -= 1; + if depth == 0 { + if let Some(begin) = start.take() { + blocks.push(text[begin..=idx].to_string()); + } + } + } + } + _ => {} + } + } + blocks +} + +fn extract_json_string_field(block: &str, field: &str) -> Option { + let needle = format!("\"{field}\""); + let pos = block.find(&needle)?; + let rest = &block[pos + needle.len()..]; + let colon = rest.find(':')?; + let after_colon = rest[colon + 1..].trim_start(); + let after_quote = after_colon.strip_prefix('"')?; + let mut out = String::new(); + let mut escaped = false; + for ch in after_quote.chars() { + if escaped { + match ch { + 'n' => out.push('\n'), + 'r' => out.push('\r'), + 't' => out.push('\t'), + '\\' => out.push('\\'), + '"' => out.push('"'), + other => out.push(other), + } + escaped = false; + } else if ch == '\\' { + escaped = true; + } else if ch == '"' { + return Some(out); + } else { + out.push(ch); + } + } + None +} + +fn map_windterm_action(action: &str) -> Option<(&'static str, &'static str)> { + match action { + "Window.ToggleFullScreen" => Some(("window.toggle_fullscreen", "Toggle Fullscreen")), + "Window.ActivateNextView" => Some(("app.switch_next_tab", "Switch to Next Tab")), + "Window.ActivatePreviousView" => { + Some(("app.switch_previous_tab", "Switch to Previous Tab")) + } + "Window.CloseActiveView" => Some(("app.close_active_tab", "Close Active Tab")), + "Terminal.DuplicateSession" | "Window.DuplicateView" => { + Some(("app.duplicate_tab", "Duplicate Tab")) + } + "Application.Exit" | "Window.Close" => Some(("app.quit", "Quit Application")), + "Terminal.NewSession" => Some(("home.new_connection", "New Connection")), + "Terminal.OpenSession" | "Window.GotoSession" => { + Some(("home.quick_open", "Quick Open Connection")) + } + "Text.Copy" => Some(("terminal.copy", "Terminal Copy")), + "Text.Paste" => Some(("terminal.paste", "Terminal Paste")), + "Text.SelectAll" | "Terminal.SelectAll" => { + Some(("terminal.select_all", "Terminal Select All")) + } + "Terminal.ClearScreen" => Some(("terminal.clear_screen", "Terminal Clear Screen")), + "Text.Find" => Some(("terminal.search_forward", "Terminal Search Forward")), + "Text.FindPrevious" => Some(("terminal.search_backward", "Terminal Search Backward")), + "Text.ZoomIn" => Some(("terminal.increase_font", "Terminal Increase Font")), + "Text.ZoomOut" => Some(("terminal.decrease_font", "Terminal Decrease Font")), + _ => None, + } +} + +fn convert_windterm_keys(keys: &str, prefer_macos: bool) -> Option { + let trimmed = keys.trim(); + if !trimmed.starts_with('<') || !trimmed.ends_with('>') { + return None; + } + let inner = &trimmed[1..trimmed.len() - 1]; + if inner.contains('<') || inner.contains('>') { + return None; + } + + let mut ctrl = false; + let mut alt = false; + let mut shift = false; + let mut meta = false; + let mut key: Option = None; + + for raw_token in inner.split('+') { + let token = raw_token.trim(); + if token.is_empty() { + continue; + } + match token.to_ascii_lowercase().as_str() { + "ctrl" | "control" => ctrl = true, + "alt" | "option" => alt = true, + "shift" => shift = true, + "meta" | "cmd" | "command" | "super" => meta = true, + other => { + if key.is_some() { + return None; + } + let normalized = match other { + "pgup" | "pageup" => "pageup".to_string(), + "pgdown" | "pagedown" => "pagedown".to_string(), + "esc" => "escape".to_string(), + "ins" => "insert".to_string(), + "del" => "delete".to_string(), + "bs" => "backspace".to_string(), + "return" => "enter".to_string(), + _ => other.to_string(), + }; + if !is_supported_key_name(&normalized) { + return None; + } + key = Some(normalized); + } + } + } + + let key = key?; + if prefer_macos && ctrl && !meta && !shift && !alt { + return None; + } + if !prefer_macos && meta { + return None; + } + + let mut parts = Vec::new(); + if ctrl { + parts.push("ctrl".to_string()); + } + if alt { + parts.push("alt".to_string()); + } + if shift { + parts.push("shift".to_string()); + } + if meta { + parts.push("cmd".to_string()); + } + parts.push(key); + Some(parts.join("-")) +} + +fn is_supported_key_name(key: &str) -> bool { + if key.len() == 1 { + let ch = key.chars().next().unwrap_or_default(); + return ch.is_ascii_alphanumeric() + || matches!( + ch, + '-' | '=' | '[' | ']' | '\\' | ';' | '\'' | ',' | '.' | '/' | '`' + ); + } + matches!( + key, + "enter" + | "escape" + | "backspace" + | "tab" + | "space" + | "insert" + | "delete" + | "home" + | "end" + | "pageup" + | "pagedown" + | "up" + | "down" + | "left" + | "right" + | "f1" + | "f2" + | "f3" + | "f4" + | "f5" + | "f6" + | "f7" + | "f8" + | "f9" + | "f10" + | "f11" + | "f12" + ) +} + +fn parse_target(target: &str) -> Option { + if target.is_empty() { + return None; + } + let without_scheme = target .strip_prefix("ssh://") - .or_else(|| value.strip_prefix("SSH://")) - .unwrap_or(value); - let value = value.split('/').next().unwrap_or(value); - let (user_info, host_port) = value - .rsplit_once('@') - .map_or((None, value), |(user, host)| (Some(user), host)); - let (username, inline_password_ignored) = user_info.map_or((None, false), |user_info| { - let (username, password) = user_info - .split_once(':') - .map_or((user_info, None), |(user, password)| (user, Some(password))); - (non_empty(Some(username.to_string())), password.is_some()) - }); - let (host, port) = parse_host_port(host_port)?; + .or_else(|| target.strip_prefix("SSH://")) + .or_else(|| target.strip_prefix("telnet://")) + .or_else(|| target.strip_prefix("TELNET://")) + .unwrap_or(target); + let authority = without_scheme.split('/').next().unwrap_or(without_scheme); + let (user_part, host_port) = match authority.rsplit_once('@') { + Some((user, host)) => (Some(user), host), + None => (None, authority), + }; + let (username, inline_password_ignored) = match user_part { + Some(user) => match user.split_once(':') { + Some((name, _password)) => (non_empty(Some(name.to_string())), true), + None => (non_empty(Some(user.to_string())), false), + }, + None => (None, false), + }; + let (host, port) = split_host_port(host_port)?; Some(ParsedTarget { host, username, @@ -262,97 +1204,97 @@ fn parse_target(value: &str) -> Option { }) } -fn parse_host_port(value: &str) -> Option<(String, Option)> { - let value = value.trim(); - if let Some(rest) = value.strip_prefix('[') { - let (host, suffix) = rest.split_once(']')?; +fn split_host_port(host_port: &str) -> Option<(String, Option)> { + let trimmed = host_port.trim(); + if trimmed.is_empty() { + return None; + } + if let Some(rest) = trimmed.strip_prefix('[') { + let (host, after) = rest.split_once(']')?; + let host = host.trim(); if host.is_empty() { return None; } - let port = suffix + let port = after .strip_prefix(':') - .and_then(|value| value.parse().ok()); + .and_then(|value| value.parse::().ok()) + .filter(|port| *port > 0); return Some((host.to_string(), port)); } - if value.matches(':').count() == 1 { - let (host, port) = value.rsplit_once(':')?; - if let Ok(port) = port.parse::() { - return non_empty(Some(host.to_string())).map(|host| (host, Some(port))); + if let Some((host, port)) = trimmed.rsplit_once(':') { + if !host.contains(':') { + if let Ok(port) = port.parse::() { + if port > 0 && !host.trim().is_empty() { + return Some((host.trim().to_string(), Some(port))); + } + } } } - non_empty(Some(value.to_string())).map(|host| (host, None)) + Some((trimmed.to_string(), None)) } -fn parse_port(value: Option<&serde_json::Value>) -> Option { +fn parse_port(value: Option<&Value>) -> Option { match value? { - serde_json::Value::Number(number) => { - number.as_u64().and_then(|port| u16::try_from(port).ok()) - } - serde_json::Value::String(value) => value.trim().parse().ok(), + Value::Number(number) => number + .as_u64() + .and_then(|port| u16::try_from(port).ok()) + .filter(|port| *port > 0), + Value::String(text) => text.trim().parse::().ok().filter(|port| *port > 0), _ => None, } } -fn truthy(value: Option<&serde_json::Value>) -> bool { +fn truthy(value: Option<&Value>) -> bool { match value { - Some(serde_json::Value::Bool(value)) => *value, - Some(serde_json::Value::Number(value)) => value.as_u64().is_some_and(|value| value != 0), - Some(serde_json::Value::String(value)) => { - matches!( - value.trim().to_ascii_lowercase().as_str(), - "1" | "true" | "yes" - ) - } + Some(Value::Bool(flag)) => *flag, + Some(Value::Number(number)) => number.as_i64().unwrap_or(0) != 0, + Some(Value::String(text)) => matches!( + text.trim().to_ascii_lowercase().as_str(), + "1" | "true" | "yes" | "on" + ), _ => false, } } -fn has_data(value: Option<&serde_json::Value>) -> bool { +fn has_data(value: Option<&Value>) -> bool { match value { - None | Some(serde_json::Value::Null) => false, - Some(serde_json::Value::Bool(value)) => *value, - Some(serde_json::Value::Number(value)) => value.as_u64().is_some_and(|value| value != 0), - Some(serde_json::Value::String(value)) => !value.trim().is_empty(), - Some(serde_json::Value::Array(value)) => !value.is_empty(), - Some(serde_json::Value::Object(value)) => !value.is_empty(), + None | Some(Value::Null) => false, + Some(Value::Bool(flag)) => *flag, + Some(Value::Number(number)) => number.as_i64().unwrap_or(0) != 0, + Some(Value::String(text)) => { + let trimmed = text.trim(); + !trimmed.is_empty() && !trimmed.eq_ignore_ascii_case("none") + } + Some(Value::Array(items)) => !items.is_empty(), + Some(Value::Object(entries)) => !entries.is_empty(), } } -fn warning(code: &str, message: &str) -> ImportWarning { - ImportWarning { - code: code.to_string(), - message: message.to_string(), - } +fn non_empty(value: Option) -> Option { + value + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()) } fn trimmed(value: Option<&str>) -> &str { - value.unwrap_or_default().trim() + value.map(str::trim).unwrap_or("") } -fn non_empty(value: Option) -> Option { - value - .map(|value| value.trim().to_string()) - .filter(|value| !value.is_empty()) +fn warning(code: &str, message: &str) -> ImportWarning { + ImportWarning { + code: code.to_string(), + message: message.to_string(), + } } fn slug(value: &str) -> String { let mut out = String::new(); - let mut last_dash = false; - for ch in value.chars().flat_map(char::to_lowercase) { + for ch in value.chars() { if ch.is_ascii_alphanumeric() { - out.push(ch); - last_dash = false; - } else if !last_dash && !out.is_empty() { + out.push(ch.to_ascii_lowercase()); + } else if !out.ends_with('-') { out.push('-'); - last_dash = true; } } - while out.ends_with('-') { - out.pop(); - } - if out.is_empty() { - "session".to_string() - } else { - out - } + out.trim_matches('-').to_string() } diff --git a/extensions/wasm/windterm-importer/src/windterm_tests.rs b/extensions/wasm/windterm-importer/src/windterm_tests.rs index 90f2cac..c867d54 100644 --- a/extensions/wasm/windterm-importer/src/windterm_tests.rs +++ b/extensions/wasm/windterm-importer/src/windterm_tests.rs @@ -1,4 +1,7 @@ -use crate::windterm::{SshImportAuthMethod, preview_records_from_session_files}; +use crate::windterm::{ + SshImportAuthMethod, TargetPlatform, parse_keymaps_text, parse_quickbar_bytes, + parse_sessions_bytes, preview_records_from_session_files, +}; const FIXTURE: &[u8] = include_bytes!("../fixtures/user.sessions.json"); @@ -38,6 +41,7 @@ fn parses_windterm_ssh_sessions_and_skips_local_shells() { assert_eq!("api.example.test", ssh.host); assert_eq!(Some(2202), ssh.port); assert_eq!("deploy", ssh.username); + assert_eq!(Some("Production".to_string()), ssh.group_path); assert_eq!( SshImportAuthMethod::Password { password: None }, ssh.auth_method @@ -131,3 +135,119 @@ fn deduplicates_the_same_profile_loaded_from_discovery_and_manual_pick() { assert_eq!(3, records.len()); } + +#[test] +fn parses_groups_jump_servers_windows_keys_quickbar_and_keymaps() { + let sessions_json = r#"[ + { + "session.group": "其他开发机", + "session.label": "mine 101.89", + "session.port": 22, + "session.protocol": "SSH", + "session.target": "user@192.168.101.89", + "session.uuid": "6025bb00-1333-46f8-be58-586908a1f7a8", + "session.autoLogin": "encrypted-blob" + }, + { + "session.group": "竞品卡或其他架构\\平台", + "session.port": 22, + "session.protocol": "SSH", + "session.proxy": "socks5://127.0.0.1:1080", + "session.proxyJumpServer1": "6025bb00-1333-46f8-be58-586908a1f7a8,mine 101.89", + "session.target": "root@10.123.0.141", + "session.uuid": "8134051c-e9e0-4d69-8dd1-be2a62fd38ca", + "ssh.identityFilePath.windows": "~\\.ssh\\id_rsa.pub" + } + ]"# + .as_bytes(); + let (records, _) = parse_sessions_bytes("user.sessions", sessions_json, TargetPlatform::Windows); + assert_eq!(2, records.len()); + let second = records[1].ssh.as_ref().unwrap(); + assert_eq!(Some("竞品卡或其他架构/平台".to_string()), second.group_path); + assert_eq!( + SshImportAuthMethod::PrivateKey { + key_path: "~/.ssh/id_rsa".to_string(), + passphrase: None, + }, + second.auth_method + ); + let jump = second.jump_server.as_ref().unwrap(); + assert_eq!("192.168.101.89", jump.host); + assert_eq!("user", jump.username); + let proxy = second.proxy.as_ref().unwrap(); + assert_eq!("127.0.0.1", proxy.host); + assert_eq!(1080, proxy.port); + + let quickbar_json = r#"[ + { + "quick.group": "快速", + "quick.label": "watch fps", + "quick.text": "sudo watch -n 1 cat /sys/kernel/debug/mtvpu0/info\\n", + "quick.uuid": "54ad536f" + } + ]"# + .as_bytes(); + let quick_records = parse_quickbar_bytes(quickbar_json); + assert_eq!(1, quick_records.len()); + assert_eq!("quick_command", quick_records[0].kind); + assert_eq!( + "sudo watch -n 1 cat /sys/kernel/debug/mtvpu0/info", + quick_records[0].quick_command.as_ref().unwrap().command + ); + + let keymaps = r#"[ + { "keys": "", "action": "Terminal.DuplicateSession" }, + { "keys": "", "action": "Text.Copy" }, + { "keys": "", "action": "Text.Copy" }, + { "keys": "", "action": "Window.ToggleFullScreen" } + ]"#; + let win_bindings = parse_keymaps_text(keymaps, false); + assert_eq!(3, win_bindings.len()); + let dup = win_bindings + .iter() + .find(|r| r.keybinding.as_ref().is_some_and(|k| k.action_id == "app.duplicate_tab")) + .unwrap(); + assert_eq!(vec!["ctrl-shift-d".to_string()], dup.keybinding.as_ref().unwrap().shortcuts); + + let discovered = crate::windterm::DiscoveredFiles { + session_files: vec![crate::windterm::InputFile { + candidate_id: "c1".to_string(), + display_path: "user.sessions".to_string(), + bytes: sessions_json.to_vec(), + }], + quickbar_files: vec![crate::windterm::InputFile { + candidate_id: "c2".to_string(), + display_path: "quickbar.config".to_string(), + bytes: quickbar_json.to_vec(), + }], + keymap_files: vec![crate::windterm::InputFile { + candidate_id: "c3".to_string(), + display_path: "wind.keymaps".to_string(), + bytes: keymaps.as_bytes().to_vec(), + }], + }; + + let legacy_host_records = crate::windterm::preview_records_from_files( + &discovered, + TargetPlatform::Windows, + false, + false, + ); + assert_eq!(3, legacy_host_records.len()); + assert!(legacy_host_records.iter().all(|r| r.kind != "keybinding")); + + let capable_host_records = crate::windterm::preview_records_from_files( + &discovered, + TargetPlatform::Windows, + false, + true, + ); + assert_eq!(6, capable_host_records.len()); + assert_eq!( + 3, + capable_host_records + .iter() + .filter(|r| r.kind == "keybinding") + .count() + ); +} diff --git a/manifest.json b/manifest.json index 7e24712..19c813e 100644 --- a/manifest.json +++ b/manifest.json @@ -259,9 +259,9 @@ "id": "com.onetcli.importer.windterm", "kind": "composite", "name": "WindTerm Importer", - "version": "0.1.0", - "release_tag": "windterm-importer-v0.1.0", - "description": "从 WindTerm profile 的 user.sessions 文件中发现 SSH 连接,并通过 Rust WASM 导入到 Navop;支持默认、自定义和手动选择的 profile。 Discovers SSH connections from WindTerm profile user.sessions files and imports them into Navop through Rust WASM, including default, custom, and manually selected profiles.", + "version": "0.2.0", + "release_tag": "windterm-importer-v0.2.0", + "description": "从 WindTerm 安装目录或 profile 配置中导入 SSH/Telnet 会话、分组、QuickBar 快捷命令及快捷键绑定,通过 Rust WASM 安全运行时导入到 Navop。 Imports SSH/Telnet sessions, groups, QuickBar commands, and keybindings from WindTerm directories or profile files through Rust WASM.", "file_extensions": [], "manifest": "windterm-importer/manifest.json" }, diff --git a/packages/navop-extension-types/schema/extension-manifest.schema.json b/packages/navop-extension-types/schema/extension-manifest.schema.json index 5ddd8ff..daf9b59 100644 --- a/packages/navop-extension-types/schema/extension-manifest.schema.json +++ b/packages/navop-extension-types/schema/extension-manifest.schema.json @@ -280,12 +280,6 @@ "shellApp": { "$ref": "#/definitions/shellApp" }, - "panels": { - "type": "array", - "items": { - "$ref": "#/definitions/panel" - } - }, "commands": { "type": "array", "items": { @@ -305,8 +299,7 @@ "type": "string" }, "icon": { - "type": "string", - "description": "相对扩展根目录的图标(SVG/PNG):命令声明后,DB 树右键菜单项会显示它" + "type": "string" }, "enablement_when": { "type": "string" @@ -316,8 +309,7 @@ "required": [], "properties": { "kind": { - "type": "string", - "description": "builtin(默认,暂不支持)、wasm(headless 动作)或 nsh(打开本扩展的 shell app tab)" + "type": "string" }, "runtime_id": { "type": "string" @@ -327,10 +319,6 @@ "string", "null" ] - }, - "route": { - "type": "string", - "description": "仅 kind == nsh:打开 app 时的初始路由,进 host.params.route" } } } @@ -514,8 +502,7 @@ "type": "string" }, "icon": { - "type": "string", - "description": "相对扩展根目录的图标(SVG/PNG):标签页 + 工具箱卡片;面板图标缺省时也回落它" + "type": "string" }, "entry": { "type": "string", @@ -546,57 +533,9 @@ "blob", "log", "runtime", - "dev", - "app", - "db", - "ui", - "terminal", - "ai" + "dev" ] - }, - "description": "页面可用的宿主模块。resource/job/event/blob/runtime/log/dev 走 host.call 字符串通道;app/ui/terminal/db 走 nsh 的 nativeModule(nativeModule(\"navop\").App 等);ai 授予 navop.ai.*(页面用 host.post 上报 AI 上下文、host.call 唤起侧栏)。未声明的模块在调用时报 PERMISSION_DENIED。" - } - } - }, - "panel": { - "description": "扩展面板:终端侧边栏的第二 surface,要求 shellApp。", - "type": "object", - "required": [ - "id" - ], - "additionalProperties": false, - "properties": { - "id": { - "type": "string", - "minLength": 1, - "maxLength": 64, - "pattern": "^[a-z0-9][a-z0-9._-]*[a-z0-9]$" - }, - "title": { - "type": "string", - "maxLength": 40 - }, - "icon": { - "type": "string", - "minLength": 1, - "description": "相对扩展根目录的图标(SVG/PNG),用作侧栏按钮;缺省回落 shellApp.icon,再没有用通用扩展图标" - }, - "anchor": { - "type": "string", - "enum": [ - "terminal-sidebar", - "db-sidebar" - ], - "default": "terminal-sidebar" - }, - "order": { - "type": "integer", - "minimum": -1000, - "maximum": 1000 - }, - "when": { - "type": "string", - "maxLength": 256 + } } } }, @@ -879,7 +818,8 @@ "telnet", "port-forwarding", "quick-command", - "workspace" + "workspace", + "keybinding" ] } }, diff --git a/tests/scripts.test.mjs b/tests/scripts.test.mjs index e4d5bd2..3dabc1d 100644 --- a/tests/scripts.test.mjs +++ b/tests/scripts.test.mjs @@ -1048,11 +1048,11 @@ test("WindTerm importer is registered as a composite WASM importer", () => { const importer = sourceManifest.contributes.connectionImporters[0]; assert.equal(importer.id, "windterm"); - assert.deepEqual(importer.outputKinds, ["ssh"]); + assert.deepEqual(importer.outputKinds, ["ssh", "telnet", "quick-command", "workspace", "keybinding"]); assert.deepEqual(importer.platforms, ["macos", "windows", "linux"]); - assert.equal(importer.manualFilePick?.prompt, "选择 WindTerm user.sessions 文件"); + assert.equal(importer.manualFilePick?.prompt, "选择 WindTerm user.sessions / quickbar.config / wind.keymaps 文件"); assert.equal(importer.manualFilePick?.supportsDirectories, true); - assert.equal(importer.manualFilePick?.directoryPrompt, "选择 WindTerm profiles 配置目录"); + assert.equal(importer.manualFilePick?.directoryPrompt, "选择 WindTerm 安装目录或 .wind 配置目录"); assert.ok( importer.candidateFiles.some((candidate) => candidate.path === "~/.wind/profiles"), "WindTerm importer should discover Unix profile directories",