import { AlertTriangle, Check, ChevronDown, Eye, EyeOff, FolderLock, FolderPlus, Forward, Globe, HeartPulse, Key, KeyRound, Link2, MapPin, Palette, Plus, Settings2, Shield, ShieldAlert, Tag, TerminalSquare, User, FileKey, FolderOpen, Trash2, Variable, Wifi, Router, X, } from "lucide-react"; import React, { useEffect, useMemo, useState, useCallback } from "react"; import { useI18n } from "../application/i18n/I18nProvider"; import { useApplicationBackend } from "../application/state/useApplicationBackend"; import { resolveGroupDefaults, resolveGroupTerminalThemeId } from "../domain/groupConfig"; import { getEffectiveHostDistro, LINUX_DISTRO_OPTIONS, normalizePrimaryTelnetState, NETWORK_DEVICE_OPTIONS, } from "../domain/host"; import { isCompleteProxyConfig, normalizeManualProxyConfig } from "../domain/proxyProfiles"; import { customThemeStore } from "../application/state/customThemeStore"; import { clearHostFontSizeOverride, clearHostThemeOverride, hasHostFontSizeOverride, hasHostThemeOverride, resolveHostTerminalFontSize, resolveHostTerminalThemeId, } from "../domain/terminalAppearance"; import { MIN_FONT_SIZE, MAX_FONT_SIZE } from "../infrastructure/config/fonts"; import { cn } from "../lib/utils"; import { EnvVar, GroupConfig, Host, Identity, ManagedSource, ProxyConfig, ProxyProfile, SSHKey } from "../types"; import { DISTRO_COLORS, DISTRO_LOGOS } from "./DistroAvatar"; import { DistroAvatar } from "./DistroAvatar"; import ThemeSelectPanel from "./ThemeSelectPanel"; import { AsidePanel, AsidePanelContent, AsidePanelFooter, type AsidePanelLayout, } from "./ui/aside-panel"; import { Badge } from "./ui/badge"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./ui/tooltip"; import { Button } from "./ui/button"; import { Switch } from "./ui/switch"; import { Card } from "./ui/card"; import { Combobox, ComboboxOption, MultiCombobox } from "./ui/combobox"; import { Input } from "./ui/input"; import { Textarea } from "./ui/textarea"; import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover"; import { ScrollArea } from "./ui/scroll-area"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select"; import { toast } from "./ui/toast"; // Import host-details sub-panels import { ChainPanel, CreateGroupPanel, EnvVarsPanel, ProxyPanel, } from "./host-details"; type CredentialType = "sshid" | "key" | "certificate" | "localKeyFile" | null; type SubPanel = | "none" | "create-group" | "proxy" | "chain" | "env-vars" | "theme-select" | "telnet-theme-select"; export const parseOptionalPortInput = (value: string): number | undefined => value ? Number(value) : undefined; const resolveDetailsTelnetPort = ( host: Host, groupDefaults?: Partial, ): number => { if (host.telnetPort !== undefined && host.telnetPort !== null) return host.telnetPort; if (groupDefaults?.telnetPort !== undefined && groupDefaults.telnetPort !== null) { return groupDefaults.telnetPort; } if (host.protocol === "telnet") { if (host.port !== undefined && host.port !== null) return host.port; if (groupDefaults?.port !== undefined && groupDefaults.port !== null) return groupDefaults.port; } return 23; }; const resolveDetailsTelnetUsername = ( host: Host, groupDefaults?: Partial, ): string => host.telnetUsername !== undefined ? host.telnetUsername : groupDefaults?.telnetUsername !== undefined ? groupDefaults.telnetUsername : host.username ?? groupDefaults?.username ?? ""; const resolveDetailsTelnetPassword = ( host: Host, groupDefaults?: Partial, ): string => host.telnetPassword !== undefined ? host.telnetPassword : groupDefaults?.telnetPassword !== undefined ? groupDefaults.telnetPassword : host.password ?? groupDefaults?.password ?? ""; const LINUX_DISTRO_OPTION_IDS = [ ...LINUX_DISTRO_OPTIONS, ...NETWORK_DEVICE_OPTIONS, ]; interface HostDetailsPanelProps { initialData?: Host | null; availableKeys: SSHKey[]; identities: Identity[]; proxyProfiles?: ProxyProfile[]; groups: string[]; managedSources?: ManagedSource[]; allTags?: string[]; // All available tags for autocomplete allHosts?: Host[]; // All hosts for chain selection defaultGroup?: string | null; // Default group for new hosts (from current navigation) terminalThemeId: string; terminalFontSize: number; onSave: (host: Host) => void; onCancel: () => void; onCreateGroup?: (groupPath: string) => void; // Callback to create a new group onCreateTag?: (tag: string) => void; // Callback to create a new tag groupDefaults?: Partial; groupConfigs?: GroupConfig[]; layout?: AsidePanelLayout; onImportKey?: (draft: Partial) => SSHKey; } const HostDetailsPanel: React.FC = ({ initialData, availableKeys, identities, proxyProfiles = [], groups, managedSources = [], allTags = [], allHosts = [], defaultGroup, terminalThemeId, terminalFontSize, onSave, onCancel, onCreateGroup, onCreateTag, groupDefaults, groupConfigs = [], layout = "overlay", onImportKey, }) => { const { t } = useI18n(); const { checkSshAgent } = useApplicationBackend(); const [form, setForm] = useState( () => (initialData ? normalizePrimaryTelnetState(initialData) : null) || ({ id: crypto.randomUUID(), label: "", hostname: "", port: groupDefaults?.port ? undefined : 22, username: groupDefaults?.username ? "" : "root", protocol: "ssh", tags: [], os: "linux", authMethod: "password", charset: groupDefaults?.charset ? undefined : "UTF-8", distroMode: "auto", createdAt: Date.now(), group: defaultGroup || undefined, // Pre-fill with current navigation group } as Host), ); // Sub-panel state const [activeSubPanel, setActiveSubPanel] = useState("none"); // Credential selection state const [credentialPopoverOpen, setCredentialPopoverOpen] = useState(false); const [selectedCredentialType, setSelectedCredentialType] = useState(null); // Identity suggestion dropdown state (popover anchored to username input) const [identitySuggestionsOpen, setIdentitySuggestionsOpen] = useState(false); // Password visibility state const [showPassword, setShowPassword] = useState(false); // Local key file path input state const [newKeyFilePath, setNewKeyFilePath] = useState(""); const [pendingReferenceKeyPath, setPendingReferenceKeyPath] = useState(null); // New group creation state const [newGroupName, setNewGroupName] = useState(""); const [newGroupParent, setNewGroupParent] = useState(""); // SSH Agent status for Windows (only checked when agentForwarding is enabled) const [sshAgentStatus, setSshAgentStatus] = useState<{ running: boolean; startupType: string | null; error: string | null; } | null>(null); // Check SSH Agent status when agentForwarding is toggled on (Windows only) useEffect(() => { if (form.agentForwarding) { checkSshAgent().then(setSshAgentStatus); } else { setSshAgentStatus(null); } }, [form.agentForwarding, checkSshAgent]); // Group input state for inline creation suggestion const [groupInputValue, setGroupInputValue] = useState(form.group || ""); useEffect(() => { if (initialData) { setForm(normalizePrimaryTelnetState(initialData)); setGroupInputValue(initialData.group || ""); setPendingReferenceKeyPath(null); // Reset password visibility when host changes for privacy setShowPassword(false); } }, [initialData]); const update = (key: K, value: Host[K]) => { setForm((prev) => ({ ...prev, [key]: value })); }; const addLocalKeyFilePath = useCallback((path: string) => { const trimmed = path.trim(); if (!trimmed) return; setForm((prev) => ({ ...prev, identityFilePaths: onImportKey ? [trimmed] : [...(prev.identityFilePaths || []), trimmed], identityFileId: undefined, authMethod: "key", })); setPendingReferenceKeyPath(onImportKey ? trimmed : null); setNewKeyFilePath(""); setSelectedCredentialType(null); }, [onImportKey]); const effectiveGroupDefaults = useMemo(() => { const currentGroupPath = form.group || defaultGroup; if (currentGroupPath && groupConfigs.length > 0) { return resolveGroupDefaults(currentGroupPath, groupConfigs); } return groupDefaults; }, [defaultGroup, form.group, groupConfigs, groupDefaults]); const effectiveThemeId = useMemo( () => resolveHostTerminalThemeId(form, resolveGroupTerminalThemeId(effectiveGroupDefaults, terminalThemeId)), [effectiveGroupDefaults, form, terminalThemeId], ); const effectiveFontSize = useMemo( () => resolveHostTerminalFontSize(form, terminalFontSize), [form, terminalFontSize], ); const hasEffectiveThemeOverride = useMemo( () => hasHostThemeOverride(form), [form], ); const hasEffectiveFontSizeOverride = useMemo( () => hasHostFontSizeOverride(form), [form], ); const effectiveTelnetThemeId = form.protocols?.find((p) => p.protocol === "telnet")?.theme || effectiveThemeId; const effectiveTelnetPort = resolveDetailsTelnetPort(form, effectiveGroupDefaults); const effectiveTelnetUsername = resolveDetailsTelnetUsername(form, effectiveGroupDefaults); const effectiveTelnetPassword = resolveDetailsTelnetPassword(form, effectiveGroupDefaults); const distroOptions = useMemo( () => LINUX_DISTRO_OPTION_IDS.map((value) => ({ value, label: t(`hostDetails.distro.option.${value}`), icon: DISTRO_LOGOS[value], bgClass: DISTRO_COLORS[value] || DISTRO_COLORS.default, })), [t], ); const getDistroOptionLabel = useCallback( (value?: string) => distroOptions.find((option) => option.value === value)?.label || value || t("hostDetails.distro.pending"), [distroOptions, t], ); const effectiveFormDistro = getEffectiveHostDistro(form); const selectedProxyProfile = useMemo( () => proxyProfiles.find((profile) => profile.id === form.proxyProfileId), [form.proxyProfileId, proxyProfiles], ); const hasMissingProxyProfile = Boolean(form.proxyProfileId && !selectedProxyProfile); const proxySummaryType = hasMissingProxyProfile ? t("hostDetails.proxyPanel.missing") : (selectedProxyProfile?.config.type || form.proxyConfig?.type || "http").toUpperCase(); const proxySummaryLabel = hasMissingProxyProfile ? t("hostDetails.proxyPanel.missingSaved") : selectedProxyProfile ? selectedProxyProfile.label : `${form.proxyConfig?.host}:${form.proxyConfig?.port}`; const proxySummaryTooltip = hasMissingProxyProfile ? t("hostDetails.proxyPanel.missingSaved") : selectedProxyProfile ? `${selectedProxyProfile.label} - ${selectedProxyProfile.config.host}:${selectedProxyProfile.config.port}` : `${form.proxyConfig?.type?.toUpperCase()} ${form.proxyConfig?.host}:${form.proxyConfig?.port}`; const handleDistroModeChange = useCallback((mode: "auto" | "manual") => { setForm((prev) => ({ ...prev, distroMode: mode, manualDistro: mode === "manual" ? prev.manualDistro || getEffectiveHostDistro(prev) || "linux" : prev.manualDistro, })); }, []); const updateProxyConfig = useCallback( (field: keyof ProxyConfig, value: string | number) => { setForm((prev) => { const { proxyProfileId: _proxyProfileId, ...rest } = prev; return { ...rest, proxyConfig: { type: prev.proxyConfig?.type || "http", host: prev.proxyConfig?.host || "", port: prev.proxyConfig?.port || 8080, ...prev.proxyConfig, [field]: value, }, } as Host; }); }, [], ); const clearProxyConfig = useCallback(() => { setForm((prev) => { const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, ...rest } = prev; return rest as Host; }); }, []); const selectProxyProfile = useCallback((profileId: string | undefined) => { setForm((prev) => { const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, ...rest } = prev; if (!profileId) return rest as Host; return { ...rest, proxyProfileId: profileId } as Host; }); }, []); const addHostToChain = (hostId: string) => { setForm((prev) => ({ ...prev, hostChain: { hostIds: [...(prev.hostChain?.hostIds || []), hostId], }, })); }; const removeHostFromChain = (index: number) => { setForm((prev) => { const ids = (prev.hostChain?.hostIds || []).filter((_, i) => i !== index); return { ...prev, hostChain: ids.length > 0 ? { hostIds: ids } : undefined }; }); }; const clearHostChain = useCallback(() => { setForm((prev) => { const { hostChain: _hostChain, ...rest } = prev; return rest as Host; }); }, []); // Environment variables state const [newEnvName, setNewEnvName] = useState(""); const [newEnvValue, setNewEnvValue] = useState(""); const addEnvVar = () => { if (!newEnvName.trim()) return; const newVar: EnvVar = { name: newEnvName.trim(), value: newEnvValue }; setForm((prev) => ({ ...prev, environmentVariables: [...(prev.environmentVariables || []), newVar], })); setNewEnvName(""); setNewEnvValue(""); }; const removeEnvVar = (index: number) => { setForm((prev) => { const filtered = (prev.environmentVariables || []).filter((_, i) => i !== index); return { ...prev, environmentVariables: filtered.length > 0 ? filtered : undefined }; }); }; const handleSubmit = () => { if (!form.hostname) return; const normalizedProxyConfig = normalizeManualProxyConfig(form.proxyConfig); if (normalizedProxyConfig && !isCompleteProxyConfig(normalizedProxyConfig)) { toast.error( normalizedProxyConfig.host ? t("proxyProfiles.error.port") : t("hostDetails.proxyPanel.error.required"), ); setActiveSubPanel("proxy"); return; } if (hasMissingProxyProfile) { toast.error(t("hostDetails.proxyPanel.missingSaved")); setActiveSubPanel("proxy"); return; } // If label is empty, use hostname as label let finalLabel = form.label?.trim() || form.hostname; const finalGroup = groupInputValue.trim() || form.group || ""; // Find the most specific (deepest) managed source that matches the group path // This handles nested managed groups correctly by preferring exact matches // and longer paths over shorter prefix matches const targetManagedSource = managedSources .filter(s => finalGroup === s.groupName || finalGroup.startsWith(s.groupName + "/")) .sort((a, b) => b.groupName.length - a.groupName.length)[0]; // Only SSH hosts can be managed (SSH config only supports SSH protocol) const canBeManaged = !form.protocol || form.protocol === "ssh"; // Strip spaces from label only if host can be managed and is in a managed group // (SSH config requires no spaces in Host alias) if (targetManagedSource && canBeManaged) { finalLabel = finalLabel.replace(/\s/g, ''); } // Determine managedSourceId: // - Only SSH hosts can be managed (SSH config only supports SSH protocol) // - If we found a matching managed source, use its id // - If managedSources was not provided (empty array) and host already has managedSourceId, preserve it // - Otherwise, clear it (host is not in a managed group) let finalManagedSourceId: string | undefined; if (targetManagedSource && canBeManaged) { finalManagedSourceId = targetManagedSource.id; } else if (managedSources.length === 0 && form.managedSourceId && canBeManaged) { // managedSources not provided, preserve existing value finalManagedSourceId = form.managedSourceId; } else { finalManagedSourceId = undefined; } const { proxyConfig: _draftProxyConfig, ...formWithoutProxyDraft } = form; const finalPort = form.protocol === "telnet" ? form.port : form.port ?? (groupDefaults?.port ? undefined : 22); let cleaned: Host = { ...formWithoutProxyDraft, ...(normalizedProxyConfig && { proxyConfig: normalizedProxyConfig }), label: finalLabel, group: finalGroup, tags: form.tags || [], port: finalPort, // Clear password if savePassword is explicitly set to false password: form.savePassword === false ? undefined : form.password, managedSourceId: finalManagedSourceId, }; cleaned = normalizePrimaryTelnetState(cleaned); if ( onImportKey && pendingReferenceKeyPath && cleaned.identityFilePaths?.includes(pendingReferenceKeyPath) ) { const fileName = pendingReferenceKeyPath.split('/').pop() || pendingReferenceKeyPath; const key = onImportKey({ source: 'reference', filePath: pendingReferenceKeyPath, label: fileName, privateKey: '', category: 'key', }); cleaned = { ...cleaned, identityFileId: key.id, identityFilePaths: [pendingReferenceKeyPath], authMethod: "key", }; } const preserveLegacyTheme = initialData?.theme != null && cleaned.themeOverride !== false; const preserveLegacyFontFamily = initialData?.fontFamily != null && cleaned.fontFamilyOverride !== false; const preserveLegacyFontSize = initialData?.fontSize != null && cleaned.fontSizeOverride !== false; if (cleaned.themeOverride === false) { delete cleaned.theme; } else if (preserveLegacyTheme && cleaned.theme == null) { cleaned.theme = initialData?.theme; } if (cleaned.fontFamilyOverride === false) { delete cleaned.fontFamily; } else if (preserveLegacyFontFamily && cleaned.fontFamily == null) { cleaned.fontFamily = initialData?.fontFamily; } if (cleaned.fontSizeOverride === false) { delete cleaned.fontSize; } else if (preserveLegacyFontSize && cleaned.fontSize == null) { cleaned.fontSize = initialData?.fontSize; } if ((cleaned.protocol && cleaned.protocol !== "ssh") || cleaned.moshEnabled) { delete cleaned.x11Forwarding; } onSave(cleaned); }; const handleCreateGroup = () => { if (!newGroupName.trim()) return; const fullPath = newGroupParent ? `${newGroupParent}/${newGroupName.trim()}` : newGroupName.trim(); onCreateGroup?.(fullPath); setGroupInputValue(fullPath); update("group", fullPath); setNewGroupName(""); setNewGroupParent(""); setActiveSubPanel("none"); }; // Get available hosts for chain (exclude current host) const availableHostsForChain = useMemo(() => { const chainedIds = new Set(form.hostChain?.hostIds || []); return allHosts.filter((h) => h.id !== form.id && !chainedIds.has(h.id)); }, [allHosts, form.id, form.hostChain?.hostIds]); // Get hosts in chain const chainedHosts = useMemo(() => { const ids = form.hostChain?.hostIds || []; return ids .map((id) => allHosts.find((h) => h.id === id)) .filter(Boolean) as Host[]; }, [allHosts, form.hostChain?.hostIds]); // Compute group options for Combobox const groupOptions: ComboboxOption[] = useMemo(() => { return groups.map((g) => ({ value: g, label: g.includes("/") ? g.split("/").pop()! : g, sublabel: g.includes("/") ? g : undefined, })); }, [groups]); // Compute tag options for MultiCombobox const tagOptions: ComboboxOption[] = useMemo(() => { const allTagSet = new Set([...allTags, ...(form.tags || [])]); return Array.from(allTagSet).map((t) => ({ value: t, label: t })); }, [allTags, form.tags]); // Available keys by category const keysByCategory = useMemo(() => { return { key: availableKeys.filter((k) => k.category === "key"), certificate: availableKeys.filter((k) => k.category === "certificate"), identity: availableKeys.filter((k) => k.category === "identity"), }; }, [availableKeys]); const selectedIdentity = useMemo(() => { if (!form.identityId) return undefined; return identities.find((i) => i.id === form.identityId); }, [form.identityId, identities]); const filteredIdentitySuggestions = useMemo(() => { if (selectedIdentity) return []; const q = (form.username || "").toLowerCase().trim(); const base = identities; const filtered = q ? base.filter( (i) => i.label.toLowerCase().includes(q) || i.username.toLowerCase().includes(q), ) : base; return filtered.slice(0, 6); }, [form.username, identities, selectedIdentity]); useEffect(() => { if (!identitySuggestionsOpen) return; if (filteredIdentitySuggestions.length === 0) { setIdentitySuggestionsOpen(false); } }, [filteredIdentitySuggestions.length, identitySuggestionsOpen]); const applyIdentity = useCallback( (identity: Identity) => { setForm((prev) => ({ ...prev, identityId: identity.id, username: identity.username, authMethod: identity.authMethod, password: undefined, identityFileId: undefined, identityFilePaths: undefined, })); setPendingReferenceKeyPath(null); setSelectedCredentialType(null); setCredentialPopoverOpen(false); setIdentitySuggestionsOpen(false); }, [], ); const clearIdentity = useCallback(() => { setForm((prev) => ({ ...prev, identityId: undefined })); setIdentitySuggestionsOpen(false); }, []); // Render sub-panels if (activeSubPanel === "create-group") { return ( setActiveSubPanel("none")} onCancel={onCancel} layout={layout} /> ); } if (activeSubPanel === "proxy") { return ( setActiveSubPanel("none")} onCancel={onCancel} layout={layout} /> ); } if (activeSubPanel === "chain") { return ( setActiveSubPanel("none")} onCancel={onCancel} layout={layout} /> ); } // Environment Variables sub-panel if (activeSubPanel === "env-vars") { return ( { const newVars = [...(form.environmentVariables || [])]; newVars[index] = { ...newVars[index], [field]: value }; setForm((prev) => ({ ...prev, environmentVariables: newVars })); }} onSave={() => { if (newEnvName.trim()) addEnvVar(); setActiveSubPanel("none"); }} onBack={() => setActiveSubPanel("none")} onCancel={onCancel} layout={layout} /> ); } // Theme selection sub-panel (SSH) if (activeSubPanel === "theme-select") { return ( { if (themeId === effectiveThemeId && !hasEffectiveThemeOverride) { setActiveSubPanel("none"); return; } setForm((prev) => ({ ...prev, theme: themeId, themeOverride: true })); setActiveSubPanel("none"); }} onClose={onCancel} onBack={() => setActiveSubPanel("none")} showBackButton={true} layout={layout} /> ); } // Theme selection sub-panel (Telnet) if (activeSubPanel === "telnet-theme-select") { return ( { // Update telnet protocol theme const telnetConfig = form.protocols?.find( (p) => p.protocol === "telnet", ); if (telnetConfig) { const newProtocols = form.protocols?.map((p) => p.protocol === "telnet" ? { ...p, theme: themeId } : p, ); setForm((prev) => ({ ...prev, protocols: newProtocols })); } else { // Create new telnet protocol config with theme const newProtocols = [ ...(form.protocols || []), { protocol: "telnet" as const, port: effectiveTelnetPort, enabled: true, theme: themeId, }, ]; setForm((prev) => ({ ...prev, protocols: newProtocols })); } setActiveSubPanel("none"); }} onClose={onCancel} onBack={() => setActiveSubPanel("none")} showBackButton={true} layout={layout} /> ); } // Main panel return ( } >

{t("hostDetails.section.general")}

{ let value = e.target.value; // Only strip spaces if the TARGET group belongs to a managed source // (don't use form.managedSourceId as it reflects old state before group change) const targetGroup = groupInputValue.trim() || form.group || ""; const willBeManaged = managedSources.some(s => targetGroup === s.groupName || targetGroup.startsWith(s.groupName + "/") ); // Also check protocol - only SSH hosts can be managed const canBeManaged = !form.protocol || form.protocol === "ssh"; if (willBeManaged && canBeManaged) { value = value.replace(/\s/g, ''); } update("label", value); }} className="h-10" /> {/* Group selection with Combobox */}
{ update("group", val); setGroupInputValue(val); }} placeholder={t("hostDetails.group.placeholder")} allowCreate={true} onCreateNew={(val) => { onCreateGroup?.(val); update("group", val); setGroupInputValue(val); }} createText="Create Group" triggerClassName="flex-1 h-10" />
{/* Tag selection with MultiCombobox */}
update("tags", vals)} placeholder="Add tags..." allowCreate={true} onCreateNew={(val) => onCreateTag?.(val)} createText="Create Tag" triggerClassName="flex-1 min-h-10" />

{t("hostDetails.section.address")}

update("hostname", e.target.value)} className="h-10 flex-1" />

{t("hostDetails.section.portCredentials")}

SSH on
update("port", e.target.value ? Number(e.target.value) : undefined)} placeholder={groupDefaults?.port ? String(groupDefaults.port) : "22"} className="h-8 flex-1 min-w-0 text-center" /> {t("hostDetails.port")}
{selectedIdentity ? (
{selectedIdentity.label}
{t("common.clear")}
) : form.identityId ? (
{t("hostDetails.identity.missing")}
{t("common.clear")}
) : ( (() => { const hasIdentities = identities.length > 0; if (!hasIdentities) { return ( update("username", e.target.value)} className="h-10" /> ); } return ( 0 } onOpenChange={setIdentitySuggestionsOpen} >
{ const next = e.target.value; update("username", next); const q = next.toLowerCase().trim(); const matches = q ? identities.filter( (i) => i.label.toLowerCase().includes(q) || i.username.toLowerCase().includes(q), ) : identities; setIdentitySuggestionsOpen(matches.length > 0); }} onFocus={() => { const q = (form.username || "").toLowerCase().trim(); const matches = q ? identities.filter( (i) => i.label.toLowerCase().includes(q) || i.username.toLowerCase().includes(q), ) : identities; setIdentitySuggestionsOpen(matches.length > 0); }} className="h-10 pr-9" /> {t("hostDetails.identity.suggestions")}
e.preventDefault()} style={{ width: "var(--radix-popover-trigger-width)" }} >
{filteredIdentitySuggestions.length === 0 ? (
{t("common.noResultsFound")}
) : (
{filteredIdentitySuggestions.map((identity) => { const keyLabel = identity.keyId ? availableKeys.find( (k) => k.id === identity.keyId, )?.label : undefined; const methodLabel = identity.authMethod === "certificate" ? t("hostDetails.credential.certificate") : identity.authMethod === "key" ? t("hostDetails.credential.key") : t("keychain.identity.method.passwordOnly"); const summaryParts = [ identity.username, identity.password ? "******" : undefined, keyLabel, ].filter(Boolean); return ( ); })}
)}
); })() )} {!selectedIdentity && !form.identityId && (
update("password", e.target.value)} className="h-10 pr-10" /> {showPassword ? t("hostDetails.password.hide") : t("hostDetails.password.show")}
)} {/* Save Password toggle - shown when password is entered */} {!selectedIdentity && !form.identityId && form.password && (
{t("hostDetails.password.save")} update("savePassword" as keyof Host, val)} />
)} {/* Local key file paths display */} {!selectedIdentity && !form.identityFileId && form.identityFilePaths && form.identityFilePaths.length > 0 && (
{form.identityFilePaths.map((keyPath, idx) => (
{keyPath} {keyPath}
))}
)} {/* Selected credential display */} {!selectedIdentity && form.identityFileId && (
{form.authMethod === "certificate" ? ( ) : ( )} {availableKeys.find((k) => k.id === form.identityFileId) ?.label || "Key"}
)} {/* Credential type selection with inline popover - hidden when credential is selected */} {!selectedIdentity && !form.identityFileId && !selectedCredentialType && (
)} {/* Key selection combobox - appears after selecting "Key" type */} {!selectedIdentity && selectedCredentialType === "key" && !form.identityFileId && (
({ value: k.id, label: k.label, sublabel: `${k.type}${k.keySize ? ` ${k.keySize}` : ""}`, icon: , }))} value={form.identityFileId} onValueChange={(val) => { update("identityFileId", val); update("authMethod", "key"); update("identityFilePaths", undefined); setPendingReferenceKeyPath(null); setSelectedCredentialType(null); }} placeholder={t("hostDetails.keys.search")} emptyText={t("hostDetails.keys.empty")} icon={} className="flex-1" />
)} {/* Certificate selection combobox - appears after selecting "Certificate" type */} {!selectedIdentity && selectedCredentialType === "certificate" && !form.identityFileId && (
({ value: k.id, label: k.label, icon: ( ), }))} value={form.identityFileId} onValueChange={(val) => { update("identityFileId", val); update("authMethod", "certificate"); update("identityFilePaths", undefined); setPendingReferenceKeyPath(null); setSelectedCredentialType(null); }} placeholder={t("hostDetails.certs.search")} emptyText={t("hostDetails.certs.empty")} icon={ } className="flex-1" />
)} {/* Local key file path input - appears after selecting "Local Key File" type */} {!selectedIdentity && selectedCredentialType === "localKeyFile" && !form.identityFileId && (
setNewKeyFilePath(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter" && newKeyFilePath.trim()) { e.preventDefault(); addLocalKeyFilePath(newKeyFilePath); } }} /> {t("hostDetails.credential.browseKeyFile")}
)}

{t("hostDetails.section.sftp")}

{t("hostDetails.sftp.sudo")}
{t("hostDetails.sftp.sudo.desc")}
update("sftpSudo", val)} />
{form.sftpSudo && !form.password && !selectedIdentity?.password && (

{t("hostDetails.sftp.sudo.passwordWarning")}

)}
{t("hostDetails.sftp.encoding")}
{t("hostDetails.sftp.encoding.desc")}
{form.os === "linux" && (
Linux

{t("hostDetails.distro.title")}

{t("hostDetails.distro.desc")}

{t("hostDetails.distro.mode")}
{form.distroMode === "manual" ? (
{t("hostDetails.distro.manualLabel")}
) : (
{t("hostDetails.distro.detectedLabel")}
{effectiveFormDistro ? getDistroOptionLabel(effectiveFormDistro) : t("hostDetails.distro.unknown")}
)}
)}

{t("hostDetails.section.appearance")}

{/* SSH Theme Selection */} {hasEffectiveThemeOverride && ( )} {/* Font Size */}
Font Size: { const val = parseInt(e.target.value); if (val >= MIN_FONT_SIZE && val <= MAX_FONT_SIZE) { setForm((prev) => ({ ...prev, fontSize: val, fontSizeOverride: true, })); } }} className="w-16 text-center h-8" /> pt {hasEffectiveFontSizeOverride && ( )}

{t("hostDetails.section.mosh")}

{ const enabling = !form.moshEnabled; if (enabling) { setForm(prev => ({ ...prev, moshEnabled: true, deviceType: prev.deviceType === 'network' ? undefined : prev.deviceType, x11Forwarding: undefined, })); } else { update("moshEnabled", false); } }} />
{/* Agent Forwarding */}

{t("hostDetails.section.agentForwarding")}

update("agentForwarding", !form.agentForwarding)} />

{t("hostDetails.agentForwarding.desc")}

{form.agentForwarding && sshAgentStatus && !sshAgentStatus.running && (

{t("hostDetails.agentForwarding.agentNotRunning")}

{t("hostDetails.agentForwarding.agentNotRunningHint")}

)}
{/* X11 Forwarding */} {(!form.protocol || form.protocol === "ssh") && !form.moshEnabled && (

{t("hostDetails.section.x11Forwarding")}

update("x11Forwarding", !form.x11Forwarding)} />

{t("hostDetails.x11Forwarding.desc")}

)} {/* Network Device Mode — only for SSH hosts without Mosh (serial already uses raw mode) */} {(!form.protocol || form.protocol === 'ssh') && !form.moshEnabled && (

{t("hostDetails.section.deviceType")}

update("deviceType", form.deviceType === 'network' ? undefined : 'network')} />

{t("hostDetails.deviceType.desc")}

{form.deviceType === 'network' && (

{t("hostDetails.deviceType.warning")}

)}
)} {/* Legacy Algorithms */}

{t("hostDetails.section.legacyAlgorithms")}

update("legacyAlgorithms", !form.legacyAlgorithms)} />

{t("hostDetails.legacyAlgorithms.desc")}

{form.legacyAlgorithms && (

{t("hostDetails.legacyAlgorithms.warning")}

)}

{t("hostDetails.backspaceBehavior")}

{/* Per-host keepalive override */}

{t("hostDetails.section.keepalive")}

{ const next = !form.keepaliveOverride; update("keepaliveOverride", next); // Seed sensible per-host defaults the first time the user // turns the override on so the inputs aren't empty. if (next) { if (form.keepaliveInterval == null) update("keepaliveInterval", 0); if (form.keepaliveCountMax == null) update("keepaliveCountMax", 3); } }} />

{t("hostDetails.keepalive.desc")}

{form.keepaliveOverride && (

{t("hostDetails.keepalive.interval")}

{ const v = parseInt(e.target.value, 10); if (!Number.isFinite(v)) return; if (v < 0 || v > 3600) return; update("keepaliveInterval", v); }} />

{t("hostDetails.keepalive.countMax")}

{ const v = parseInt(e.target.value, 10); if (!Number.isFinite(v)) return; if (v < 1 || v > 100) return; update("keepaliveCountMax", v); }} />
{(form.keepaliveInterval ?? 0) === 0 && (

{t("hostDetails.keepalive.disabledHint")}

)}
)}
{/* Proxy via Hosts (Jump Hosts / ProxyJump) */}

{t("hostDetails.jumpHosts")}

{chainedHosts.length > 0 ? ( {t("hostDetails.jumpHosts.hops", { count: chainedHosts.length })} ) : ( {t("hostDetails.jumpHosts.direct")} )}
{chainedHosts.length > 0 && ( )} {chainedHosts.length === 0 && ( )}
{/* Proxy Configuration */}

{t("hostDetails.proxy")}

{form.proxyConfig?.host || form.proxyProfileId ? (
) : ( )}
{/* Environment Variables */}

{t("hostDetails.envVars")}

{(form.environmentVariables?.length || 0) > 0 ? ( ) : ( )}
{/* Startup Command */}

{t("hostDetails.startupCommand")}