import { Activity, BookMarked, ChevronDown, Edit2, FileCode, FolderPlus, FolderTree, Key, LayoutGrid, List, Plug, Plus, Search, Settings, TerminalSquare, Trash2, Upload, Zap, } from "lucide-react"; import React, { memo, useCallback, useMemo, useState } from "react"; import { sanitizeHost } from "../domain/host"; import { cn } from "../lib/utils"; import { GroupNode, Host, HostProtocol, KnownHost, SSHKey, ShellHistoryEntry, Snippet, TerminalSession, } from "../types"; import { AppLogo } from "./AppLogo"; import { DistroAvatar } from "./DistroAvatar"; import HostDetailsPanel from "./HostDetailsPanel"; import KeychainManager from "./KeychainManager"; import KnownHostsManager from "./KnownHostsManager"; import PortForwarding from "./PortForwardingNew"; import ProtocolSelectDialog from "./ProtocolSelectDialog"; import QuickConnectWizard, { isQuickConnectInput, parseQuickConnectInput, } from "./QuickConnectWizard"; import SnippetsManager from "./SnippetsManager"; import { Button } from "./ui/button"; import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger, } from "./ui/context-menu"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "./ui/dialog"; import { Dropdown, DropdownContent, DropdownTrigger } from "./ui/dropdown"; import { Input } from "./ui/input"; import { Label } from "./ui/label"; import { SortDropdown, SortMode } from "./ui/sort-dropdown"; import { TagFilterDropdown } from "./ui/tag-filter-dropdown"; type VaultSection = "hosts" | "keys" | "snippets" | "port" | "knownhosts"; // Props without isActive - it's now subscribed internally interface VaultViewProps { hosts: Host[]; keys: SSHKey[]; snippets: Snippet[]; snippetPackages: string[]; customGroups: string[]; knownHosts: KnownHost[]; shellHistory: ShellHistoryEntry[]; sessions: TerminalSession[]; onOpenSettings: () => void; onOpenQuickSwitcher: () => void; onCreateLocalTerminal: () => void; onDeleteHost: (id: string) => void; onConnect: (host: Host) => void; onUpdateHosts: (hosts: Host[]) => void; onUpdateKeys: (keys: SSHKey[]) => void; onUpdateSnippets: (snippets: Snippet[]) => void; onUpdateSnippetPackages: (pkgs: string[]) => void; onUpdateCustomGroups: (groups: string[]) => void; onUpdateKnownHosts: (knownHosts: KnownHost[]) => void; onConvertKnownHost: (knownHost: KnownHost) => void; onRunSnippet?: (snippet: Snippet, targetHosts: Host[]) => void; } const VaultViewInner: React.FC = ({ hosts, keys, snippets, snippetPackages, customGroups, knownHosts, shellHistory, sessions, onOpenSettings, onOpenQuickSwitcher, onCreateLocalTerminal, onDeleteHost, onConnect, onUpdateHosts, onUpdateKeys, onUpdateSnippets, onUpdateSnippetPackages, onUpdateCustomGroups, onUpdateKnownHosts, onConvertKnownHost, onRunSnippet, }) => { const [currentSection, setCurrentSection] = useState("hosts"); const [search, setSearch] = useState(""); const [selectedGroupPath, setSelectedGroupPath] = useState( null, ); const [isNewFolderOpen, setIsNewFolderOpen] = useState(false); const [newFolderName, setNewFolderName] = useState(""); const [targetParentPath, setTargetParentPath] = useState(null); // View mode, sorting, and tag filter state const [viewMode, setViewMode] = useState<"grid" | "list">("grid"); const [sortMode, setSortMode] = useState("az"); const [selectedTags, setSelectedTags] = useState([]); // Host panel state (local to hosts section) const [isHostPanelOpen, setIsHostPanelOpen] = useState(false); const [editingHost, setEditingHost] = useState(null); // Quick connect state const [quickConnectTarget, setQuickConnectTarget] = useState<{ hostname: string; username?: string; port?: number; } | null>(null); const [isQuickConnectOpen, setIsQuickConnectOpen] = useState(false); // Protocol select state (for hosts with multiple protocols) const [protocolSelectHost, setProtocolSelectHost] = useState( null, ); // Check if search input is a quick connect address const isSearchQuickConnect = useMemo(() => { return isQuickConnectInput(search); }, [search]); // Handle connect button click - detect quick connect or regular search const handleConnectClick = useCallback(() => { if (isSearchQuickConnect) { const target = parseQuickConnectInput(search); if (target) { setQuickConnectTarget(target); setIsQuickConnectOpen(true); } } else { onOpenQuickSwitcher(); } }, [isSearchQuickConnect, search, onOpenQuickSwitcher]); // Handle search input keydown for quick connect const handleSearchKeyDown = useCallback( (e: React.KeyboardEvent) => { if (e.key === "Enter" && isSearchQuickConnect) { e.preventDefault(); handleConnectClick(); } }, [isSearchQuickConnect, handleConnectClick], ); // Check if host has multiple protocols enabled const hasMultipleProtocols = useCallback((host: Host) => { let count = 0; // SSH is always available as base protocol (unless explicitly set to something else) if (host.protocol === "ssh" || !host.protocol) count++; // Mosh adds another option if (host.moshEnabled) count++; // Telnet adds another option if (host.telnetEnabled) count++; // If protocol is explicitly telnet (not ssh), count it if (host.protocol === "telnet" && !host.telnetEnabled) count++; return count > 1; }, []); // Handle host connect with protocol selection const handleHostConnect = useCallback( (host: Host) => { if (hasMultipleProtocols(host)) { setProtocolSelectHost(host); } else { onConnect(host); } }, [hasMultipleProtocols, onConnect], ); // Handle protocol selection const handleProtocolSelect = useCallback( (protocol: HostProtocol, port: number) => { if (protocolSelectHost) { const hostWithProtocol: Host = { ...protocolSelectHost, protocol: protocol === "mosh" ? "ssh" : protocol, port, moshEnabled: protocol === "mosh", }; onConnect(hostWithProtocol); setProtocolSelectHost(null); } }, [protocolSelectHost, onConnect], ); // Handle quick connect const handleQuickConnect = useCallback( (host: Host) => { onConnect(host); setIsQuickConnectOpen(false); setQuickConnectTarget(null); setSearch(""); }, [onConnect], ); // Handle quick connect save host const handleQuickConnectSaveHost = useCallback( (host: Host) => { onUpdateHosts([...hosts, host]); }, [hosts, onUpdateHosts], ); const handleNewHost = useCallback(() => { setEditingHost(null); setIsHostPanelOpen(true); }, []); const handleEditHost = useCallback((host: Host) => { setEditingHost(host); setIsHostPanelOpen(true); }, []); const buildGroupTree = useMemo>(() => { const root: Record = {}; const insertPath = (path: string, host?: Host) => { const parts = path.split("/").filter(Boolean); let currentLevel = root; let currentPath = ""; parts.forEach((part, index) => { currentPath = currentPath ? `${currentPath}/${part}` : part; if (!currentLevel[part]) { currentLevel[part] = { name: part, path: currentPath, children: {}, hosts: [], }; } if (host && index === parts.length - 1) currentLevel[part].hosts.push(host); currentLevel = currentLevel[part].children; }); }; customGroups.forEach((path) => insertPath(path)); hosts.forEach((host) => insertPath(host.group || "General", host)); return root; }, [hosts, customGroups]); const findGroupNode = (path: string | null): GroupNode | null => { if (!path) return { name: "root", path: "", children: buildGroupTree, hosts: [], } as GroupNode; const parts = path.split("/").filter(Boolean); let current: { children?: Record; hosts?: Host[] } = { children: buildGroupTree, }; for (const p of parts) { const next = current.children?.[p]; if (!next) return null; current = next; } return current as GroupNode; }; const displayedHosts = useMemo(() => { let filtered = hosts; if (selectedGroupPath) { filtered = filtered.filter((h) => (h.group || "") === selectedGroupPath); } if (search.trim()) { const s = search.toLowerCase(); filtered = filtered.filter( (h) => h.label.toLowerCase().includes(s) || h.hostname.toLowerCase().includes(s) || h.tags.some((t) => t.toLowerCase().includes(s)), ); } // Apply tag filter if (selectedTags.length > 0) { filtered = filtered.filter((h) => selectedTags.some((t) => h.tags?.includes(t)), ); } // Apply sorting filtered = [...filtered].sort((a, b) => { switch (sortMode) { case "az": return a.label.localeCompare(b.label); case "za": return b.label.localeCompare(a.label); case "newest": return (b.createdAt || 0) - (a.createdAt || 0); case "oldest": return (a.createdAt || 0) - (b.createdAt || 0); default: return 0; } }); return filtered; }, [hosts, selectedGroupPath, search, selectedTags, sortMode]); // Compute all unique tags across all hosts const allTags = useMemo(() => { const tagSet = new Set(); hosts.forEach((h) => h.tags?.forEach((t) => tagSet.add(t))); return Array.from(tagSet).sort(); }, [hosts]); // Handle tag edit - rename tag across all hosts const handleEditTag = useCallback( (oldTag: string, newTag: string) => { if (oldTag === newTag) return; const updatedHosts = hosts.map((host) => { if (host.tags?.includes(oldTag)) { const newTags = host.tags.map((t) => (t === oldTag ? newTag : t)); // Remove duplicates in case newTag already exists return { ...host, tags: Array.from(new Set(newTags)) }; } return host; }); onUpdateHosts(updatedHosts); }, [hosts, onUpdateHosts], ); // Handle tag delete - remove tag from all hosts const handleDeleteTag = useCallback( (tag: string) => { const updatedHosts = hosts.map((host) => { if (host.tags?.includes(tag)) { return { ...host, tags: host.tags.filter((t) => t !== tag) }; } return host; }); onUpdateHosts(updatedHosts); }, [hosts, onUpdateHosts], ); const displayedGroups = useMemo(() => { if (!selectedGroupPath) { return (Object.values(buildGroupTree) as GroupNode[]).sort((a, b) => a.name.localeCompare(b.name), ); } const node = findGroupNode(selectedGroupPath); if (!node || !node.children) return []; return (Object.values(node.children) as GroupNode[]).sort((a, b) => a.name.localeCompare(b.name), ); // eslint-disable-next-line react-hooks/exhaustive-deps -- findGroupNode is derived from buildGroupTree }, [buildGroupTree, selectedGroupPath]); // Known Hosts callbacks - use refs to keep stable references // Store latest values in refs so callbacks don't need to depend on them const knownHostsRef = React.useRef(knownHosts); const onUpdateKnownHostsRef = React.useRef(onUpdateKnownHosts); // Keep refs up to date React.useEffect(() => { knownHostsRef.current = knownHosts; onUpdateKnownHostsRef.current = onUpdateKnownHosts; }); // Stable callbacks that read from refs const handleSaveKnownHost = useCallback((kh: KnownHost) => { onUpdateKnownHostsRef.current([...knownHostsRef.current, kh]); }, []); const handleUpdateKnownHost = useCallback((kh: KnownHost) => { onUpdateKnownHostsRef.current( knownHostsRef.current.map((existing) => existing.id === kh.id ? kh : existing, ), ); }, []); const handleDeleteKnownHost = useCallback((id: string) => { onUpdateKnownHostsRef.current( knownHostsRef.current.filter((kh) => kh.id !== id), ); }, []); const handleImportKnownHosts = useCallback((newHosts: KnownHost[]) => { onUpdateKnownHostsRef.current([...knownHostsRef.current, ...newHosts]); }, []); const handleRefreshKnownHosts = useCallback(() => { // Placeholder for system scan }, []); // Memoize the KnownHostsManager element to prevent re-renders when VaultViewInner re-renders const knownHostsManagerElement = useMemo(() => { return ( ); // eslint-disable-next-line react-hooks/exhaustive-deps -- handle* callbacks are stable refs that read from refs }, [knownHosts, hosts, onConvertKnownHost]); const submitNewFolder = () => { if (!newFolderName.trim()) return; const fullPath = targetParentPath ? `${targetParentPath}/${newFolderName.trim()}` : newFolderName.trim(); onUpdateCustomGroups(Array.from(new Set([...customGroups, fullPath]))); setIsNewFolderOpen(false); }; const deleteGroupPath = (path: string) => { const keepGroups = customGroups.filter( (g) => !(g === path || g.startsWith(path + "/")), ); const keepHosts = hosts.map((h) => { const g = h.group || ""; if (g === path || g.startsWith(path + "/")) return { ...h, group: "" }; return h; }); onUpdateCustomGroups(keepGroups); onUpdateHosts(keepHosts); if ( selectedGroupPath && (selectedGroupPath === path || selectedGroupPath.startsWith(path + "/")) ) { setSelectedGroupPath(null); } }; const moveGroup = (sourcePath: string, targetParent: string | null) => { const name = sourcePath.split("/").filter(Boolean).pop() || ""; const newPath = targetParent ? `${targetParent}/${name}` : name; if (newPath === sourcePath || newPath.startsWith(sourcePath + "/")) return; const updatedGroups = customGroups.map((g) => { if (g === sourcePath) return newPath; if (g.startsWith(sourcePath + "/")) return g.replace(sourcePath, newPath); return g; }); const updatedHosts = hosts.map((h) => { const g = h.group || ""; if (g === sourcePath) return { ...h, group: newPath }; if (g.startsWith(sourcePath + "/")) return { ...h, group: g.replace(sourcePath, newPath) }; return h; }); onUpdateCustomGroups(Array.from(new Set(updatedGroups))); onUpdateHosts(updatedHosts); if ( selectedGroupPath && (selectedGroupPath === sourcePath || selectedGroupPath.startsWith(sourcePath + "/")) ) { setSelectedGroupPath(newPath); } }; const moveHostToGroup = (hostId: string, groupPath: string | null) => { onUpdateHosts( hosts.map((h) => h.id === hostId ? { ...h, group: groupPath || "" } : h, ), ); }; // Component no longer handles visibility - that's done by VaultViewWrapper return (
{/* Sidebar */}

Netcatty

{/* Main Area */}
{currentSection === "hosts" && (
setSearch(e.target.value)} onKeyDown={handleSearchKeyDown} /> {isSearchQuickConnect && (
)}
{/* View mode, tag filter, and sort controls */}
{/* New Host split button */}
)} {currentSection !== "port" && currentSection !== "keys" && currentSection !== "knownhosts" && currentSection !== "snippets" && (
{currentSection === "hosts" && ( <>
{selectedGroupPath && selectedGroupPath .split("/") .filter(Boolean) .map((part, idx, arr) => { const crumbPath = arr.slice(0, idx + 1).join("/"); const isLast = idx === arr.length - 1; return ( › ); })}
{displayedGroups.length > 0 && ( <>

Groups

{displayedGroups.length} total
)}
{ e.preventDefault(); }} onDrop={(e) => { e.preventDefault(); e.stopPropagation(); const hostId = e.dataTransfer.getData("host-id"); const groupPath = e.dataTransfer.getData("group-path"); if (hostId) moveHostToGroup(hostId, selectedGroupPath); if (groupPath && selectedGroupPath !== null) moveGroup(groupPath, selectedGroupPath); }} > {displayedGroups.map((node) => (
e.dataTransfer.setData("group-path", node.path) } onDoubleClick={() => setSelectedGroupPath(node.path) } onClick={() => setSelectedGroupPath(node.path)} onDragOver={(e) => { e.preventDefault(); e.stopPropagation(); }} onDrop={(e) => { e.preventDefault(); e.stopPropagation(); const hostId = e.dataTransfer.getData("host-id"); const groupPath = e.dataTransfer.getData("group-path"); if (hostId) moveHostToGroup(hostId, node.path); if (groupPath) moveGroup(groupPath, node.path); }} >
{node.name}
{node.hosts.length} Hosts
{ setTargetParentPath(node.path); setIsNewFolderOpen(true); }} > New Subgroup deleteGroupPath(node.path)} > Delete Group
))}

Hosts

{displayedHosts.length} entries
{sessions.length} live
{displayedHosts.map((host) => { const safeHost = sanitizeHost(host); const distroBadge = { text: (safeHost.os || "L")[0].toUpperCase(), label: safeHost.distro || safeHost.os || "Linux", }; return (
{ e.dataTransfer.effectAllowed = "move"; e.dataTransfer.setData("host-id", host.id); }} onClick={() => handleHostConnect(safeHost)} >
{safeHost.label}
{safeHost.username}@{safeHost.hostname}
{viewMode === "list" && ( <> )}
handleHostConnect(host)} > Connect handleEditHost(host)} > Edit onDeleteHost(host.id)} > Delete
); })} {displayedHosts.length === 0 && (

Set up your hosts

Save hosts to quickly connect to your servers, VMs, and containers.

)}
)}
)} {currentSection === "snippets" && ( onUpdateSnippets( snippets.find((ex) => ex.id === s.id) ? snippets.map((ex) => (ex.id === s.id ? s : ex)) : [...snippets, s], ) } onDelete={(id) => onUpdateSnippets(snippets.filter((s) => s.id !== id)) } onRunSnippet={onRunSnippet} availableKeys={keys} onSaveHost={(host) => onUpdateHosts([...hosts, host])} onCreateGroup={(groupPath) => onUpdateCustomGroups( Array.from(new Set([...customGroups, groupPath])), ) } /> )} {currentSection === "keys" && ( onUpdateKeys([...keys, k])} onUpdate={(k) => onUpdateKeys( keys.map((existing) => (existing.id === k.id ? k : existing)), ) } onDelete={(id) => onUpdateKeys(keys.filter((k) => k.id !== id))} onSaveHost={(host) => { // Update existing host or add new one const existingIndex = hosts.findIndex((h) => h.id === host.id); if (existingIndex >= 0) { onUpdateHosts(hosts.map((h) => (h.id === host.id ? host : h))); } else { onUpdateHosts([...hosts, host]); } }} onCreateGroup={(groupPath) => onUpdateCustomGroups( Array.from(new Set([...customGroups, groupPath])), ) } /> )} {currentSection === "port" && ( onUpdateHosts([...hosts, host])} onCreateGroup={(groupPath) => onUpdateCustomGroups( Array.from(new Set([...customGroups, groupPath])), ) } /> )} {/* Always render KnownHostsManager but hide with CSS to prevent unmounting */}
{knownHostsManagerElement}
{/* Host Details Panel - positioned at VaultView root level for correct top alignment */} {currentSection === "hosts" && isHostPanelOpen && ( h.group || "General"), ]), )} allTags={allTags} allHosts={hosts} onSave={(host) => { onUpdateHosts( editingHost ? hosts.map((h) => (h.id === host.id ? host : h)) : [...hosts, host], ); setIsHostPanelOpen(false); setEditingHost(null); }} onCancel={() => { setIsHostPanelOpen(false); setEditingHost(null); }} onCreateGroup={(groupPath) => { onUpdateCustomGroups( Array.from(new Set([...customGroups, groupPath])), ); }} /> )} {targetParentPath ? `Create Subfolder` : "Create Root Group"} Create a new group for organizing hosts.
setNewFolderName(e.target.value)} placeholder="e.g. Production" autoFocus onKeyDown={(e) => e.key === "Enter" && submitNewFolder()} /> {targetParentPath && (

Parent: {targetParentPath}

)}
{/* Quick Connect Wizard */} {isQuickConnectOpen && quickConnectTarget && ( { setIsQuickConnectOpen(false); setQuickConnectTarget(null); }} /> )} {/* Protocol Select Dialog */} {protocolSelectHost && ( setProtocolSelectHost(null)} /> )}
); }; // Only re-render when data props change - isActive is now managed internally via store subscription const vaultViewAreEqual = ( prev: VaultViewProps, next: VaultViewProps, ): boolean => { const isEqual = prev.hosts === next.hosts && prev.keys === next.keys && prev.snippets === next.snippets && prev.snippetPackages === next.snippetPackages && prev.customGroups === next.customGroups && prev.knownHosts === next.knownHosts && prev.shellHistory === next.shellHistory && prev.sessions === next.sessions; return isEqual; }; const MemoizedVaultViewInner = memo(VaultViewInner, vaultViewAreEqual); // Just export the memoized component directly // Visibility control is handled by parent (App.tsx) export const VaultView = MemoizedVaultViewInner; VaultView.displayName = "VaultView";