feat: seperated out sharing, improved host/credential loading, reduced host manager bloat

This commit is contained in:
LukeGus
2026-05-26 16:57:35 -05:00
parent 4df71e77cb
commit 5c2c9c179e
12 changed files with 2349 additions and 3349 deletions
+1201 -986
View File
File diff suppressed because it is too large Load Diff
+10 -9
View File
@@ -37,6 +37,7 @@
"build:mac-dev": "npm run build && npm run electron:rebuild && npm run electron:patch-builder && electron-builder --mac dir --publish=never" "build:mac-dev": "npm run build && npm run electron:rebuild && npm run electron:patch-builder && electron-builder --mac dir --publish=never"
}, },
"dependencies": { "dependencies": {
"@tanstack/react-virtual": "^3.13.26",
"axios": "^1.15.2", "axios": "^1.15.2",
"bcryptjs": "^3.0.3", "bcryptjs": "^3.0.3",
"better-sqlite3": "^12.9.0", "better-sqlite3": "^12.9.0",
@@ -69,8 +70,8 @@
"@codemirror/search": "^6.7.0", "@codemirror/search": "^6.7.0",
"@codemirror/theme-one-dark": "^6.1.3", "@codemirror/theme-one-dark": "^6.1.3",
"@codemirror/view": "^6.41.1", "@codemirror/view": "^6.41.1",
"@commitlint/cli": "^20.5.0", "@commitlint/cli": "^21.0.1",
"@commitlint/config-conventional": "^20.5.0", "@commitlint/config-conventional": "^21.0.1",
"@deadendjs/swagger-jsdoc": "^8.1.2", "@deadendjs/swagger-jsdoc": "^8.1.2",
"@electron/notarize": "^3.1.1", "@electron/notarize": "^3.1.1",
"@electron/rebuild": "^4.0.4", "@electron/rebuild": "^4.0.4",
@@ -102,7 +103,7 @@
"@types/js-yaml": "^4.0.9", "@types/js-yaml": "^4.0.9",
"@types/jsonwebtoken": "^9.0.10", "@types/jsonwebtoken": "^9.0.10",
"@types/multer": "^2.1.0", "@types/multer": "^2.1.0",
"@types/node": "^24.12.2", "@types/node": "^25.9.1",
"@types/qrcode": "^1.5.6", "@types/qrcode": "^1.5.6",
"@types/react": "^19.2.14", "@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3", "@types/react-dom": "^19.2.3",
@@ -114,16 +115,16 @@
"@uiw/react-codemirror": "^4.25.9", "@uiw/react-codemirror": "^4.25.9",
"@vitejs/plugin-react": "^6.0.1", "@vitejs/plugin-react": "^6.0.1",
"@xterm/addon-clipboard": "^0.2.0", "@xterm/addon-clipboard": "^0.2.0",
"@xterm/addon-fit": "^0.10.0", "@xterm/addon-fit": "^0.11.0",
"@xterm/addon-unicode11": "^0.8.0", "@xterm/addon-unicode11": "^0.9.0",
"@xterm/addon-web-links": "^0.11.0", "@xterm/addon-web-links": "^0.12.0",
"@xterm/xterm": "^5.5.0", "@xterm/xterm": "^6.0.0",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"cmdk": "^1.1.1", "cmdk": "^1.1.1",
"concurrently": "^9.2.1", "concurrently": "^9.2.1",
"cytoscape": "^3.33.2", "cytoscape": "^3.33.2",
"electron": "^41.3.0", "electron": "^42.2.0",
"electron-builder": "^26.8.1", "electron-builder": "^26.8.1",
"eslint": "^9.0.0", "eslint": "^9.0.0",
"eslint-plugin-react-hooks": "^7.1.1", "eslint-plugin-react-hooks": "^7.1.1",
@@ -134,7 +135,7 @@
"husky": "^9.1.7", "husky": "^9.1.7",
"i18next": "^26.0.8", "i18next": "^26.0.8",
"i18next-browser-languagedetector": "^8.2.1", "i18next-browser-languagedetector": "^8.2.1",
"lint-staged": "^16.4.0", "lint-staged": "^17.0.5",
"lucide-react": "^1.11.0", "lucide-react": "^1.11.0",
"prettier": "3.8.3", "prettier": "3.8.3",
"radix-ui": "^1.4.3", "radix-ui": "^1.4.3",
+1 -1
View File
@@ -1451,7 +1451,7 @@ router.post(
const publicKeyString = const publicKeyString =
typeof publicKeyPem === "string" typeof publicKeyPem === "string"
? publicKeyPem ? publicKeyPem
: publicKeyPem.toString("utf8"); : (publicKeyPem as Buffer).toString("utf8");
let keyType = "unknown"; let keyType = "unknown";
const asymmetricKeyType = privateKeyObj.asymmetricKeyType; const asymmetricKeyType = privateKeyObj.asymmetricKeyType;
+12 -4
View File
@@ -133,6 +133,7 @@ export function AppShell({
Array(6).fill(null), Array(6).fill(null),
); );
const [realHostTree, setRealHostTree] = useState<HostFolder | null>(null); const [realHostTree, setRealHostTree] = useState<HostFolder | null>(null);
const [hostsLoading, setHostsLoading] = useState(true);
const [allHosts, setAllHosts] = useState<Host[]>([]); const [allHosts, setAllHosts] = useState<Host[]>([]);
const [isAdmin, setIsAdmin] = useState(false); const [isAdmin, setIsAdmin] = useState(false);
@@ -256,6 +257,8 @@ export function AppShell({
setRealHostTree(buildHostTree(raw)); setRealHostTree(buildHostTree(raw));
} catch { } catch {
// Keep empty state on error // Keep empty state on error
} finally {
setHostsLoading(false);
} }
}, []); }, []);
@@ -482,7 +485,9 @@ export function AppShell({
// Sidebar panel content — shared between desktop inline sidebar and mobile sheet // Sidebar panel content — shared between desktop inline sidebar and mobile sheet
const sidebarPanelContent = ( const sidebarPanelContent = (
<div className="flex flex-col flex-1 min-h-0 overflow-hidden"> <div className="flex flex-col flex-1 min-h-0 overflow-hidden">
{railView === "hosts" && ( <div
className={`flex flex-col flex-1 min-h-0 ${railView === "hosts" ? "" : "hidden"}`}
>
<HostsPanel <HostsPanel
onOpenTab={(host, type) => { onOpenTab={(host, type) => {
connectHost(host, type); connectHost(host, type);
@@ -490,13 +495,16 @@ export function AppShell({
}} }}
onEditHost={editHostInManager} onEditHost={editHostInManager}
hostTree={realHostTree ?? undefined} hostTree={realHostTree ?? undefined}
loading={hostsLoading}
onEditingChange={setSidebarEditing} onEditingChange={setSidebarEditing}
/> />
)} </div>
{railView === "credentials" && ( <div
className={`flex flex-col flex-1 min-h-0 ${railView === "credentials" ? "" : "hidden"}`}
>
<CredentialsPanel onEditingChange={setSidebarEditing} /> <CredentialsPanel onEditingChange={setSidebarEditing} />
)} </div>
{railView === "quick-connect" && ( {railView === "quick-connect" && (
<QuickConnectPanel <QuickConnectPanel
+24 -3
View File
@@ -890,6 +890,10 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
if (isEmbeddedMode()) { if (isEmbeddedMode()) {
baseWsUrl = "ws://127.0.0.1:30002"; baseWsUrl = "ws://127.0.0.1:30002";
const storedJwt = localStorage.getItem("jwt");
if (storedJwt) {
baseWsUrl += `?token=${encodeURIComponent(storedJwt)}`;
}
} else if (!configuredUrl) { } else if (!configuredUrl) {
console.error("No configured server URL available for Electron SSH"); console.error("No configured server URL available for Electron SSH");
setIsConnected(false); setIsConnected(false);
@@ -1864,7 +1868,6 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
terminal.options.fontSize = config.fontSize; terminal.options.fontSize = config.fontSize;
terminal.options.fontFamily = fontFamily; terminal.options.fontFamily = fontFamily;
terminal.options.rightClickSelectsWord = config.rightClickSelectsWord; terminal.options.rightClickSelectsWord = config.rightClickSelectsWord;
terminal.options.fastScrollModifier = config.fastScrollModifier;
terminal.options.fastScrollSensitivity = config.fastScrollSensitivity; terminal.options.fastScrollSensitivity = config.fastScrollSensitivity;
terminal.options.minimumContrastRatio = config.minimumContrastRatio; terminal.options.minimumContrastRatio = config.minimumContrastRatio;
terminal.options.letterSpacing = config.letterSpacing; terminal.options.letterSpacing = config.letterSpacing;
@@ -1934,11 +1937,9 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
fontFamily, fontFamily,
allowTransparency: true, // MUST be set before open() allowTransparency: true, // MUST be set before open()
convertEol: false, convertEol: false,
windowsMode: false,
macOptionIsMeta: false, macOptionIsMeta: false,
macOptionClickForcesSelection: false, macOptionClickForcesSelection: false,
rightClickSelectsWord: config.rightClickSelectsWord, rightClickSelectsWord: config.rightClickSelectsWord,
fastScrollModifier: config.fastScrollModifier,
fastScrollSensitivity: config.fastScrollSensitivity, fastScrollSensitivity: config.fastScrollSensitivity,
allowProposedApi: true, allowProposedApi: true,
minimumContrastRatio: config.minimumContrastRatio, minimumContrastRatio: config.minimumContrastRatio,
@@ -1993,6 +1994,26 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
terminal.open(xtermRef.current); terminal.open(xtermRef.current);
terminal.attachCustomWheelEventHandler((ev) => {
const cfg = {
...DEFAULT_TERMINAL_CONFIG,
...hostConfig.terminalConfig,
};
const mod = cfg.fastScrollModifier;
const modHeld =
(mod === "alt" && ev.altKey) ||
(mod === "ctrl" && ev.ctrlKey) ||
(mod === "shift" && ev.shiftKey);
if (modHeld) {
const lines = Math.round(
(Math.abs(ev.deltaY) / 100) * (cfg.fastScrollSensitivity ?? 5),
);
terminal.scrollLines(ev.deltaY > 0 ? lines : -lines);
return false;
}
return true;
});
fitAddonRef.current?.fit(); fitAddonRef.current?.fit();
if (terminal.cols < 10 || terminal.rows < 3) { if (terminal.cols < 10 || terminal.rows < 3) {
requestAnimationFrame(() => { requestAnimationFrame(() => {
+11
View File
@@ -552,13 +552,24 @@
"failedToDeployKey2": "Failed to deploy key", "failedToDeployKey2": "Failed to deploy key",
"deletedCount": "Deleted {{count}} hosts", "deletedCount": "Deleted {{count}} hosts",
"failedToDeleteCount": "Failed to delete {{count}} hosts", "failedToDeleteCount": "Failed to delete {{count}} hosts",
"duplicatedHost": "Duplicated \"{{name}}\"",
"failedToDuplicateHost": "Failed to duplicate host",
"updatedCount": "Updated {{count}} hosts", "updatedCount": "Updated {{count}} hosts",
"friendlyNameLabel": "Friendly Name", "friendlyNameLabel": "Friendly Name",
"descriptionLabel": "Description", "descriptionLabel": "Description",
"loadingHost": "Loading host...", "loadingHost": "Loading host...",
"loadingHosts": "Loading hosts...",
"loadingCredentials": "Loading credentials...",
"noHostsYet": "No hosts yet",
"noHostsMatchSearch": "No hosts match your search",
"hostNotFound": "Host not found", "hostNotFound": "Host not found",
"searchHosts": "Search hosts...", "searchHosts": "Search hosts...",
"addHost": "Add Host", "addHost": "Add Host",
"shareHost": "Share Host",
"shareHostTitle": "Share: {{name}}",
"sharing": {
"requiresCredential": "This host must use a credential to enable sharing. Edit the host and assign a credential first."
},
"guac": { "guac": {
"connection": "Connection", "connection": "Connection",
"authentication": "Authentication", "authentication": "Authentication",
+4
View File
@@ -2771,6 +2771,10 @@ export async function loginUser(
} }
} }
if (response.data.token) {
localStorage.setItem("jwt", response.data.token);
}
if (response.data.success && !response.data.requires_totp) { if (response.data.success && !response.data.requires_totp) {
markUserAuthenticated(); markUserAuthenticated();
} }
-1
View File
@@ -55,7 +55,6 @@ export function CredentialsPanel({
<div className="flex flex-col flex-1 min-h-0"> <div className="flex flex-col flex-1 min-h-0">
<HostManager <HostManager
initialSection="credentials"
hideListHeader hideListHeader
externalSearch={managerEditing ? undefined : search} externalSearch={managerEditing ? undefined : search}
onEditingChange={handleEditingChange} onEditingChange={handleEditingChange}
File diff suppressed because it is too large Load Diff
+318
View File
@@ -0,0 +1,318 @@
import { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import {
ArrowLeft,
ListChecks,
Plus,
Shield,
User,
Users,
X,
} from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/button";
import { Input } from "@/components/input";
import { SectionCard } from "@/components/section-card";
import {
getHostAccess,
shareHost,
revokeHostAccess,
getUserList,
getRoles,
} from "@/main-axios";
import type { Host } from "@/types/ui-types";
export function HostShareModal({
open,
onClose,
host,
}: {
open: boolean;
onClose: () => void;
host: Host | null;
}) {
const { t } = useTranslation();
const [shareType, setShareType] = useState<"user" | "role">("user");
const [shareGranteeId, setShareGranteeId] = useState("");
const [shareExpiryHours, setShareExpiryHours] = useState("");
const [accessList, setAccessList] = useState<any[]>([]);
const [shareUsers, setShareUsers] = useState<
{ id: string; username: string }[]
>([]);
const [shareRoles, setShareRoles] = useState<{ id: string; name: string }[]>(
[],
);
const [sharingLoaded, setSharingLoaded] = useState(false);
const [sharingLoadError, setSharingLoadError] = useState(false);
useEffect(() => {
if (!open || !host) return;
if (sharingLoaded) return;
setSharingLoaded(true);
Promise.all([
getHostAccess(Number(host.id)).catch(() => ({ accessList: [] })),
getUserList().catch(() => ({ users: [] })),
getRoles().catch(() => ({ roles: [] })),
])
.then(([accessRes, usersRes, rolesRes]) => {
setAccessList((accessRes as any)?.accessList ?? []);
setShareUsers(
((usersRes as any)?.users ?? []).map((u: any) => ({
id: String(u.id ?? u.userId),
username: u.username,
})),
);
setShareRoles(
((rolesRes as any)?.roles ?? []).map((r: any) => ({
id: String(r.id),
name: r.name,
})),
);
})
.catch(() => setSharingLoadError(true));
}, [open, host, sharingLoaded]);
useEffect(() => {
setSharingLoaded(false);
setSharingLoadError(false);
setAccessList([]);
setShareGranteeId("");
setShareExpiryHours("");
setShareType("user");
}, [host?.id]);
async function refreshAccessList() {
if (!host) return;
const res = await getHostAccess(Number(host.id));
setAccessList((res as any)?.accessList ?? []);
}
if (!open) return null;
const hasCredential = !!host?.credentialId;
return (
<div className="absolute inset-0 z-20 flex flex-col bg-sidebar">
{/* Header */}
<div className="flex items-center gap-2 px-3 py-2 shrink-0 border-b border-border text-xs text-muted-foreground hover:text-foreground">
<button
onClick={onClose}
className="flex items-center gap-2 hover:text-foreground transition-colors"
>
<ArrowLeft className="size-3.5 shrink-0" />
<span>{t("hosts.shareHostTitle", { name: host?.name ?? "" })}</span>
</button>
</div>
{/* Scrollable content */}
<div className="flex flex-col flex-1 min-h-0 overflow-y-auto p-3 gap-3">
{!hasCredential && host !== null && (
<div className="flex items-start gap-3 p-3 border border-yellow-500/30 bg-yellow-500/5 text-xs text-yellow-500">
<Shield className="size-3.5 shrink-0 mt-0.5" />
<div>{t("hosts.sharing.requiresCredential")}</div>
</div>
)}
{sharingLoadError && hasCredential && (
<div className="flex items-start gap-3 p-3 border border-destructive/30 bg-destructive/5 text-xs text-destructive">
<Shield className="size-3.5 shrink-0 mt-0.5" />
<div>{t("hosts.guac.sharingLoadError")}</div>
</div>
)}
{hasCredential && (
<>
<SectionCard
title={t("hosts.guac.shareHostSection")}
icon={<Users className="size-3.5" />}
>
<div className="flex flex-col gap-4 py-3">
<div className="flex gap-2">
{(["user", "role"] as const).map((shareTypeOpt) => (
<button
key={shareTypeOpt}
onClick={() => {
setShareType(shareTypeOpt);
setShareGranteeId("");
}}
className={`px-3 py-1.5 text-[10px] font-bold uppercase tracking-widest border transition-colors ${shareType === shareTypeOpt ? "border-accent-brand/40 bg-accent-brand/10 text-accent-brand" : "border-border text-muted-foreground hover:text-foreground"}`}
>
{shareTypeOpt === "user" ? (
<>
<User className="size-3 inline mr-1" />
{t("hosts.guac.shareWithUser")}
</>
) : (
<>
<Shield className="size-3 inline mr-1" />
{t("hosts.guac.shareWithRole")}
</>
)}
</button>
))}
</div>
<div className="flex flex-col gap-1.5">
<label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
{shareType === "user"
? t("hosts.guac.selectUser")
: t("hosts.guac.selectRole")}
</label>
<select
className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
value={shareGranteeId}
onChange={(e) => setShareGranteeId(e.target.value)}
>
<option value="">
{shareType === "user"
? t("hosts.guac.selectUserOption")
: t("hosts.guac.selectRoleOption")}
</option>
{shareType === "user"
? shareUsers.map((u) => (
<option key={u.id} value={u.id}>
{u.username}
</option>
))
: shareRoles.map((r) => (
<option key={r.id} value={r.id}>
{r.name}
</option>
))}
</select>
</div>
<div className="flex flex-col gap-1.5">
<label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
{t("hosts.guac.expiresInHours")}
</label>
<Input
type="number"
placeholder={t("hosts.guac.noExpiryPlaceholder")}
value={shareExpiryHours}
onChange={(e) => setShareExpiryHours(e.target.value)}
className="[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
/>
</div>
<div className="flex justify-end">
<Button
variant="outline"
className="border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
disabled={!shareGranteeId}
onClick={async () => {
try {
await shareHost(Number(host!.id), {
targetType: shareType,
...(shareType === "user"
? { targetUserId: shareGranteeId }
: { targetRoleId: Number(shareGranteeId) }),
permissionLevel: "view",
...(shareExpiryHours
? { durationHours: Number(shareExpiryHours) }
: {}),
});
await refreshAccessList();
setShareGranteeId("");
setShareExpiryHours("");
toast.success(t("hosts.hostSharedSuccessfully"));
} catch {
toast.error(t("hosts.failedToShareHost"));
}
}}
>
<Plus className="size-3.5 mr-1.5" />
{t("hosts.guac.shareBtn")}
</Button>
</div>
</div>
</SectionCard>
<SectionCard
title={t("hosts.guac.currentAccess")}
icon={<ListChecks className="size-3.5" />}
>
<div className="py-2">
{accessList.length === 0 && (
<div className="px-2 py-4 text-xs text-muted-foreground/50 text-center">
{t("hosts.guac.noAccessEntries")}
</div>
)}
{accessList.map((r: any, i: number) => {
const expired =
r.expiresAt && new Date(r.expiresAt) < new Date();
return (
<div
key={i}
className="flex flex-col gap-1 px-2 py-2.5 border-b border-border last:border-0 text-xs"
>
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-1.5 min-w-0">
{r.targetType === "user" ? (
<User className="size-3 text-muted-foreground shrink-0" />
) : (
<Shield className="size-3 text-muted-foreground shrink-0" />
)}
<span className="font-semibold truncate">
{r.username ??
r.roleName ??
r.roleDisplayName ??
r.userId ??
r.roleId}
</span>
<span className="text-muted-foreground capitalize shrink-0">
({r.targetType})
</span>
</div>
<Button
variant="ghost"
size="sm"
className="h-6 text-[10px] px-2 text-destructive hover:bg-destructive/10 shrink-0"
onClick={async () => {
try {
await revokeHostAccess(Number(host!.id), r.id);
setAccessList((prev) =>
prev.filter((_, idx) => idx !== i),
);
toast.success(t("hosts.accessRevoked"));
} catch {
toast.error(t("hosts.failedToRevokeAccess"));
}
}}
>
{t("hosts.guac.revokeBtn")}
</Button>
</div>
<div className="flex items-center gap-3 text-[10px] text-muted-foreground pl-4">
<span>
{t("hosts.guac.grantedByHeader")}:{" "}
<span className="text-foreground/70">
{r.grantedByUsername ?? "—"}
</span>
</span>
<span className={expired ? "text-destructive" : ""}>
{t("hosts.guac.expiresHeader")}:{" "}
{expired ? (
<span className="inline-flex items-center gap-0.5 text-destructive">
<X className="size-3" />
{t("hosts.guac.expiredLabel")}
</span>
) : r.expiresAt ? (
<span className="text-foreground/70">
{new Date(r.expiresAt).toLocaleDateString()}
</span>
) : (
<span className="text-foreground/70">
{t("hosts.guac.neverLabel")}
</span>
)}
</span>
</div>
</div>
);
})}
</div>
</SectionCard>
</>
)}
</div>
</div>
);
}
+266 -22
View File
@@ -1,25 +1,57 @@
import { useState } from "react"; import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { ListChecks, Plus, Search, X } from "lucide-react"; import {
Download,
ListChecks,
Plus,
RefreshCw,
Search,
Upload,
X,
} from "lucide-react";
import { toast } from "sonner";
import { SidebarTree } from "@/sidebar/SidebarTree"; import { SidebarTree } from "@/sidebar/SidebarTree";
import { HostManager } from "@/sidebar/HostManager"; import { HostManager } from "@/sidebar/HostManager";
import { HostShareModal } from "@/sidebar/HostShareModal";
import { Button } from "@/components/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/dropdown-menu";
import { getSSHHosts, bulkImportSSHHosts } from "@/main-axios";
import type { SSHHostWithStatus } from "@/main-axios";
import type { Host, HostFolder, TabType } from "@/types/ui-types"; import type { Host, HostFolder, TabType } from "@/types/ui-types";
export function HostsPanel({ export function HostsPanel({
onOpenTab, onOpenTab,
onEditHost, onEditHost,
hostTree, hostTree,
loading,
onEditingChange, onEditingChange,
}: { }: {
onOpenTab: (host: Host, type: TabType) => void; onOpenTab: (host: Host, type: TabType) => void;
onEditHost: (host: Host) => void; onEditHost: (host: Host) => void;
hostTree?: HostFolder; hostTree?: HostFolder;
loading?: boolean;
onEditingChange?: (editing: boolean) => void; onEditingChange?: (editing: boolean) => void;
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
const [hostSearch, setHostSearch] = useState(""); const [hostSearch, setHostSearch] = useState("");
const [managerEditing, setManagerEditing] = useState(false); const [managerEditing, setManagerEditing] = useState(false);
const [selectionMode, setSelectionMode] = useState(false); const [selectionMode, setSelectionMode] = useState(false);
const [refreshing, setRefreshing] = useState(false);
const [rawHosts, setRawHosts] = useState<SSHHostWithStatus[]>([]);
const [shareModalHost, setShareModalHost] = useState<Host | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const importOverwriteRef = useRef(false);
useEffect(() => {
getSSHHosts()
.then(setRawHosts)
.catch(() => {});
}, []);
function handleEditingChange(editing: boolean) { function handleEditingChange(editing: boolean) {
setManagerEditing(editing); setManagerEditing(editing);
@@ -30,11 +62,99 @@ export function HostsPanel({
setSelectionMode((v) => !v); setSelectionMode((v) => !v);
} }
async function handleRefresh() {
setRefreshing(true);
try {
const hosts = await getSSHHosts();
setRawHosts(hosts);
window.dispatchEvent(new CustomEvent("termix:hosts-changed"));
} catch {
// best-effort
} finally {
setRefreshing(false);
}
}
function handleExportHosts() {
const data = JSON.stringify({ hosts: rawHosts }, null, 2);
const blob = new Blob([data], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "termix-hosts.json";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
toast.success(t("hosts.hostsExported"));
}
function handleDownloadSample() {
const sample = JSON.stringify(
{
hosts: [
{
name: "Web Server (Production)",
ip: "192.168.1.100",
username: "admin",
authType: "password",
password: "your_secure_password_here",
folder: "Production",
tags: ["web", "production", "nginx"],
pin: true,
notes: "Main production web server running Nginx",
enableSsh: true,
enableRdp: false,
enableVnc: false,
enableTelnet: false,
sshPort: 22,
enableTerminal: true,
enableTunnel: false,
enableFileManager: true,
enableDocker: false,
defaultPath: "/var/www",
},
{
name: "Database Server",
ip: "192.168.1.101",
username: "dbadmin",
authType: "key",
key: "-----BEGIN OPENSSH PRIVATE KEY-----\nYour SSH private key content here\n-----END OPENSSH PRIVATE KEY-----",
keyPassword: "optional_key_passphrase",
keyType: "ssh-ed25519",
folder: "Production",
tags: ["database", "production", "postgresql"],
enableSsh: true,
enableRdp: false,
enableVnc: false,
enableTelnet: false,
sshPort: 22,
enableTerminal: true,
enableTunnel: true,
enableFileManager: false,
enableDocker: false,
},
],
},
null,
2,
);
const blob = new Blob([sample], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "termix-hosts-sample.json";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
return ( return (
<div className="flex flex-col flex-1 min-h-0 overflow-hidden"> <div className="relative flex flex-col flex-1 min-h-0 overflow-hidden">
{!managerEditing && ( {!managerEditing && (
<div className="flex items-center gap-1.5 px-2 py-1.5 shrink-0 border-b border-border/60"> <div className="flex flex-col px-2 py-1.5 shrink-0 border-b border-border/60 gap-1.5">
<div className="flex items-center gap-2 px-2.5 h-7 bg-muted/60 border border-border/60 rounded-sm flex-1 min-w-0"> <div className="flex items-center gap-2 px-2.5 h-7 bg-muted/60 border border-border/60 rounded-sm">
<Search className="size-3 text-muted-foreground/60 shrink-0" /> <Search className="size-3 text-muted-foreground/60 shrink-0" />
<input <input
value={hostSearch} value={hostSearch}
@@ -51,23 +171,139 @@ export function HostsPanel({
</button> </button>
)} )}
</div> </div>
<button
title={t("hosts.selectHosts")} <input
onClick={toggleSelectionMode} ref={fileInputRef}
className={`flex items-center justify-center size-7 rounded-sm shrink-0 transition-colors ${selectionMode ? "text-accent-brand bg-accent-brand/10 border border-accent-brand/30" : "text-muted-foreground/60 hover:text-foreground hover:bg-muted/60 border border-transparent"}`} type="file"
> accept=".json"
<ListChecks className="size-3.5" /> className="hidden"
</button> onChange={async (e) => {
<button const file = e.target.files?.[0];
onClick={() => if (!file) return;
window.dispatchEvent(new CustomEvent("host-manager:add-host")) e.target.value = "";
} try {
title={t("hosts.addHost")} const text = await file.text();
className="flex items-center gap-1 h-7 px-2 text-[10px] font-medium text-accent-brand hover:bg-accent-brand/10 border border-accent-brand/30 rounded-sm shrink-0 transition-colors" const parsed = JSON.parse(text);
> const hostsArray = Array.isArray(parsed)
<Plus className="size-3 shrink-0" /> ? parsed
{t("hosts.addHost")} : (parsed.hosts ?? []);
</button> if (!Array.isArray(hostsArray) || hostsArray.length === 0) {
toast.error("No hosts found in file");
return;
}
if (hostsArray.length > 100) {
toast.error("Cannot import more than 100 hosts at once");
return;
}
const normalized = hostsArray.map((h: any) => ({
...h,
port: h.port ?? h.sshPort ?? 22,
enableSsh: h.enableSsh ?? h.connectionType === "ssh",
enableRdp: h.enableRdp ?? h.connectionType === "rdp",
enableVnc: h.enableVnc ?? h.connectionType === "vnc",
enableTelnet: h.enableTelnet ?? h.connectionType === "telnet",
}));
const result = await bulkImportSSHHosts(
normalized,
importOverwriteRef.current,
);
const hosts = await getSSHHosts();
setRawHosts(hosts);
window.dispatchEvent(new CustomEvent("termix:hosts-changed"));
const msg = [
result.success ? `${result.success} imported` : null,
result.updated ? `${result.updated} updated` : null,
result.failed ? `${result.failed} failed` : null,
]
.filter(Boolean)
.join(", ");
toast.success(`Import complete: ${msg}`);
} catch (err: any) {
toast.error(err?.message ?? "Failed to import hosts");
}
}}
/>
<div className="flex items-center gap-1">
<div className="flex items-center gap-0.5 flex-1">
<Button
variant="ghost"
size="icon"
className="size-7 text-muted-foreground hover:text-foreground"
title={t("hosts.refreshBtn2")}
onClick={handleRefresh}
disabled={refreshing}
>
<RefreshCw
className={`size-3.5 ${refreshing ? "animate-spin" : ""}`}
/>
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon"
className="size-7 text-muted-foreground hover:text-foreground"
title={t("hosts.importExportBtn")}
>
<Upload className="size-3.5" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="text-xs">
<DropdownMenuItem
onClick={() => {
importOverwriteRef.current = false;
fileInputRef.current?.click();
}}
>
<Upload className="size-3.5 mr-2" />
{t("hosts.importSkipExisting")}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
importOverwriteRef.current = true;
fileInputRef.current?.click();
}}
>
<Upload className="size-3.5 mr-2" />
{t("hosts.importOverwrite")}
</DropdownMenuItem>
<DropdownMenuItem
onClick={handleExportHosts}
disabled={rawHosts.length === 0}
>
<Download className="size-3.5 mr-2" />
{t("hosts.exportAll")}
</DropdownMenuItem>
<DropdownMenuItem onClick={handleDownloadSample}>
<Download className="size-3.5 mr-2" />
{t("hosts.downloadSample")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<button
title={
selectionMode
? t("hosts.exitSelectionTitle")
: t("hosts.selectHosts")
}
onClick={toggleSelectionMode}
className={`flex items-center justify-center size-7 rounded-sm shrink-0 transition-colors ${selectionMode ? "text-accent-brand bg-accent-brand/10 border border-accent-brand/30" : "text-muted-foreground/60 hover:text-foreground hover:bg-muted/60 border border-transparent"}`}
>
<ListChecks className="size-3.5" />
</button>
</div>
<button
onClick={() =>
window.dispatchEvent(new CustomEvent("host-manager:add-host"))
}
title={t("hosts.addHost")}
className="flex items-center gap-1 h-7 px-2 text-[10px] font-medium text-accent-brand hover:bg-accent-brand/10 border border-accent-brand/30 rounded-sm shrink-0 transition-colors"
>
<Plus className="size-3 shrink-0" />
{t("hosts.addHost")}
</button>
</div>
</div> </div>
)} )}
@@ -78,9 +314,11 @@ export function HostsPanel({
children={hostTree?.children ?? []} children={hostTree?.children ?? []}
onOpenTab={onOpenTab} onOpenTab={onOpenTab}
onEditHost={onEditHost} onEditHost={onEditHost}
onShareHost={(host) => setShareModalHost(host)}
query={hostSearch.trim().toLowerCase()} query={hostSearch.trim().toLowerCase()}
selectionMode={selectionMode} selectionMode={selectionMode}
onToggleSelectionMode={toggleSelectionMode} onToggleSelectionMode={toggleSelectionMode}
loading={loading}
/> />
</div> </div>
@@ -89,6 +327,12 @@ export function HostsPanel({
> >
<HostManager onEditingChange={handleEditingChange} /> <HostManager onEditingChange={handleEditingChange} />
</div> </div>
<HostShareModal
open={shareModalHost !== null}
onClose={() => setShareModalHost(null)}
host={shareModalHost}
/>
</div> </div>
); );
} }
+200 -46
View File
@@ -1,15 +1,18 @@
import { useState } from "react"; import { useRef, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useVirtualizer } from "@tanstack/react-virtual";
import { import {
Box, Box,
Check, Check,
ChevronDown, ChevronDown,
ChevronRight, ChevronRight,
Copy, Copy,
CopyPlus,
Cpu, Cpu,
FolderOpen, FolderOpen,
FolderSearch, FolderSearch,
Link, Link,
Loader2,
MemoryStick, MemoryStick,
Monitor, Monitor,
MoreHorizontal, MoreHorizontal,
@@ -17,6 +20,7 @@ import {
Pencil, Pencil,
Pin, Pin,
Server, Server,
Share2,
Terminal, Terminal,
Trash2, Trash2,
} from "lucide-react"; } from "lucide-react";
@@ -31,7 +35,7 @@ import {
DropdownMenuTrigger, DropdownMenuTrigger,
} from "@/components/dropdown-menu"; } from "@/components/dropdown-menu";
import { toast } from "sonner"; import { toast } from "sonner";
import { bulkUpdateSSHHosts, deleteSSHHost } from "@/main-axios"; import { bulkUpdateSSHHosts, createSSHHost, deleteSSHHost } from "@/main-axios";
import type { Host, HostFolder, TabType } from "@/types/ui-types"; import type { Host, HostFolder, TabType } from "@/types/ui-types";
export function isFolder(item: Host | HostFolder): item is HostFolder { export function isFolder(item: Host | HostFolder): item is HostFolder {
@@ -100,21 +104,26 @@ function folderHasMatch(folder: HostFolder, query: string): boolean {
return false; return false;
} }
type VirtualRow = { item: Host | HostFolder; depth: number };
function collectVisibleRows( function collectVisibleRows(
children: (Host | HostFolder)[], children: (Host | HostFolder)[],
query: string, query: string,
openSet: Set<string>, openSet: Set<string>,
out: (Host | HostFolder)[] = [], out: VirtualRow[] = [],
): (Host | HostFolder)[] { depth = 0,
): VirtualRow[] {
for (const child of children) { for (const child of children) {
if (isFolder(child)) { if (isFolder(child)) {
const visible = query ? folderHasMatch(child, query) : true; const visible = query ? folderHasMatch(child, query) : true;
if (!visible) continue; if (!visible) continue;
out.push(child); out.push({ item: child, depth });
const childOpen = query ? true : openSet.has(child.name); const childOpen = query ? true : openSet.has(child.name);
if (childOpen) collectVisibleRows(child.children, query, openSet, out); if (childOpen)
collectVisibleRows(child.children, query, openSet, out, depth + 1);
} else { } else {
if (!query || hostMatchesQuery(child, query)) out.push(child); if (!query || hostMatchesQuery(child, query))
out.push({ item: child, depth });
} }
} }
return out; return out;
@@ -166,7 +175,9 @@ export function HostItem({
host, host,
onOpenTab, onOpenTab,
onEditHost, onEditHost,
onShareHost,
onDelete, onDelete,
onDuplicate,
query = "", query = "",
stripeIndex = 0, stripeIndex = 0,
selectionMode = false, selectionMode = false,
@@ -178,7 +189,9 @@ export function HostItem({
host: Host; host: Host;
onOpenTab: (type: TabType) => void; onOpenTab: (type: TabType) => void;
onEditHost?: () => void; onEditHost?: () => void;
onShareHost?: () => void;
onDelete: () => void; onDelete: () => void;
onDuplicate: () => void;
query?: string; query?: string;
stripeIndex?: number; stripeIndex?: number;
selectionMode?: boolean; selectionMode?: boolean;
@@ -378,6 +391,21 @@ export function HostItem({
</button> </button>
</> </>
)} )}
{onShareHost && (
<>
<div className="w-px h-3.5 bg-border/60 mx-0.5 shrink-0" />
<button
title={t("hosts.shareHost")}
onClick={(e) => {
e.stopPropagation();
onShareHost();
}}
className="flex items-center justify-center size-7 rounded text-muted-foreground hover:text-accent-brand hover:bg-accent-brand/10 transition-colors"
>
<Share2 className="size-3.5" />
</button>
</>
)}
<DropdownMenu open={isMenuOpen} onOpenChange={onMenuOpenChange}> <DropdownMenu open={isMenuOpen} onOpenChange={onMenuOpenChange}>
<DropdownMenuTrigger asChild> <DropdownMenuTrigger asChild>
<button <button
@@ -522,6 +550,16 @@ export function HostItem({
</DropdownMenuSubContent> </DropdownMenuSubContent>
</DropdownMenuSub> </DropdownMenuSub>
<DropdownMenuSeparator /> <DropdownMenuSeparator />
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
onDuplicate();
}}
>
<CopyPlus className="size-3.5 mr-2" />
{t("hosts.cloneHostAction")}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem <DropdownMenuItem
className="text-destructive focus:text-destructive" className="text-destructive focus:text-destructive"
onClick={(e) => { onClick={(e) => {
@@ -544,9 +582,12 @@ export function HostItem({
export function FolderItem({ export function FolderItem({
folder, folder,
depth = 0, depth = 0,
flat = false,
onOpenTab, onOpenTab,
onEditHost, onEditHost,
onShareHost,
onDeleteHost, onDeleteHost,
onDuplicateHost,
query = "", query = "",
stripeMap, stripeMap,
openFolders, openFolders,
@@ -559,9 +600,12 @@ export function FolderItem({
}: { }: {
folder: HostFolder; folder: HostFolder;
depth?: number; depth?: number;
flat?: boolean;
onOpenTab: (host: Host, type: TabType) => void; onOpenTab: (host: Host, type: TabType) => void;
onEditHost?: (host: Host) => void; onEditHost?: (host: Host) => void;
onShareHost?: (host: Host) => void;
onDeleteHost: (host: Host) => void; onDeleteHost: (host: Host) => void;
onDuplicateHost: (host: Host) => void;
query?: string; query?: string;
stripeMap: Map<Host | HostFolder, number>; stripeMap: Map<Host | HostFolder, number>;
openFolders: Set<string>; openFolders: Set<string>;
@@ -601,7 +645,8 @@ export function FolderItem({
<span className="text-muted-foreground/40">/{total}</span> <span className="text-muted-foreground/40">/{total}</span>
</span> </span>
</button> </button>
{isOpen && ( {/* Children are rendered as separate virtual rows when flat=true */}
{!flat && isOpen && (
<div className="border-l border-border/40 ml-[30px]"> <div className="border-l border-border/40 ml-[30px]">
{folder.children.map((child, i) => {folder.children.map((child, i) =>
isFolder(child) ? ( isFolder(child) ? (
@@ -611,7 +656,9 @@ export function FolderItem({
depth={depth + 1} depth={depth + 1}
onOpenTab={onOpenTab} onOpenTab={onOpenTab}
onEditHost={onEditHost} onEditHost={onEditHost}
onShareHost={onShareHost}
onDeleteHost={onDeleteHost} onDeleteHost={onDeleteHost}
onDuplicateHost={onDuplicateHost}
query={query} query={query}
stripeMap={stripeMap} stripeMap={stripeMap}
openFolders={openFolders} openFolders={openFolders}
@@ -628,7 +675,9 @@ export function FolderItem({
host={child} host={child}
onOpenTab={(t) => onOpenTab(child, t)} onOpenTab={(t) => onOpenTab(child, t)}
onEditHost={onEditHost ? () => onEditHost(child) : undefined} onEditHost={onEditHost ? () => onEditHost(child) : undefined}
onShareHost={onShareHost ? () => onShareHost(child) : undefined}
onDelete={() => onDeleteHost(child)} onDelete={() => onDeleteHost(child)}
onDuplicate={() => onDuplicateHost(child)}
query={query} query={query}
stripeIndex={stripeMap.get(child) ?? 0} stripeIndex={stripeMap.get(child) ?? 0}
selectionMode={selectionMode} selectionMode={selectionMode}
@@ -651,18 +700,23 @@ export function SidebarTree({
children, children,
onOpenTab, onOpenTab,
onEditHost, onEditHost,
onShareHost,
query = "", query = "",
selectionMode, selectionMode,
onToggleSelectionMode, onToggleSelectionMode,
loading = false,
}: { }: {
children: (Host | HostFolder)[]; children: (Host | HostFolder)[];
onOpenTab: (host: Host, type: TabType) => void; onOpenTab: (host: Host, type: TabType) => void;
onEditHost: (host: Host) => void; onEditHost: (host: Host) => void;
onShareHost?: (host: Host) => void;
query?: string; query?: string;
selectionMode: boolean; selectionMode: boolean;
onToggleSelectionMode: () => void; onToggleSelectionMode: () => void;
loading?: boolean;
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
const scrollRef = useRef<HTMLDivElement>(null);
const [openFolders, setOpenFolders] = useState<Set<string>>(new Set()); const [openFolders, setOpenFolders] = useState<Set<string>>(new Set());
const [selectedHostIds, setSelectedHostIds] = useState<Set<string>>( const [selectedHostIds, setSelectedHostIds] = useState<Set<string>>(
new Set(), new Set(),
@@ -704,53 +758,153 @@ export function SidebarTree({
}); });
} }
async function handleDuplicateHost(host: Host) {
try {
const {
id: _id,
online: _online,
cpu: _cpu,
ram: _ram,
lastAccess: _la,
hasKey: _hk,
hasKeyPassword: _hkp,
...rest
} = host as any;
await createSSHHost({
...rest,
name: `${host.name} (copy)`,
key: undefined,
});
window.dispatchEvent(new CustomEvent("termix:hosts-changed"));
toast.success(t("hosts.duplicatedHost", { name: host.name }));
} catch {
toast.error(t("hosts.failedToDuplicateHost"));
}
}
const allHosts = collectAllHosts(children); const allHosts = collectAllHosts(children);
const allFolders = collectAllFolders(children); const allFolders = collectAllFolders(children);
const visibleRows = collectVisibleRows(children, query, openFolders); const visibleRows = collectVisibleRows(children, query, openFolders);
const stripeMap = new Map<Host | HostFolder, number>( const stripeMap = new Map<Host | HostFolder, number>(
visibleRows.map((r, i) => [r, i]), visibleRows.map((r, i) => [r.item, i]),
); );
const virtualizer = useVirtualizer({
count: visibleRows.length,
getScrollElement: () => scrollRef.current,
estimateSize: () => 52,
overscan: 8,
});
if (loading) {
return (
<div className="relative flex flex-col flex-1 min-h-0">
<div className="flex-1 min-h-0 overflow-y-auto px-2 py-2 space-y-1.5">
{[28, 20, 24, 20, 28, 20].map((w, i) => (
<div
key={i}
className={`flex items-center gap-2 px-3 py-2 ${i % 2 === 1 ? "ml-4" : ""}`}
>
<div className="size-3 rounded-sm bg-muted/50 animate-pulse shrink-0" />
<div
className="h-3 rounded bg-muted/50 animate-pulse"
style={{ width: `${w * 3}px` }}
/>
</div>
))}
<div className="flex items-center justify-center gap-2 pt-4 text-muted-foreground/40">
<Loader2 className="size-3.5 animate-spin" />
<span className="text-xs">{t("hosts.loadingHosts")}</span>
</div>
</div>
</div>
);
}
return ( return (
<div className="relative flex flex-col flex-1 min-h-0"> <div className="relative flex flex-col flex-1 min-h-0">
<div className="flex-1 min-h-0 overflow-y-auto"> <div className="flex-1 min-h-0 overflow-y-auto" ref={scrollRef}>
{children.map((child, i) => {visibleRows.length === 0 ? (
isFolder(child) ? ( <div className="flex flex-col items-center justify-center py-12 text-center px-4">
<FolderItem <Server className="size-8 text-muted-foreground/20 mb-2" />
key={i} <span className="text-sm font-semibold text-muted-foreground/60">
folder={child} {query ? t("hosts.noHostsMatchSearch") : t("hosts.noHostsYet")}
onOpenTab={onOpenTab} </span>
onEditHost={onEditHost} </div>
onDeleteHost={handleDeleteHost} ) : (
query={query} <div
stripeMap={stripeMap} style={{
openFolders={openFolders} height: `${virtualizer.getTotalSize()}px`,
onToggleFolder={toggleFolder} position: "relative",
selectionMode={selectionMode} }}
selectedHostIds={selectedHostIds} >
onToggleSelect={toggleSelect} {virtualizer.getVirtualItems().map((vItem) => {
openMenuHostId={openMenuHostId} const { item, depth } = visibleRows[vItem.index];
onMenuOpenChange={setOpenMenuHostId} const stripeIndex = stripeMap.get(item) ?? 0;
/> const indentPx = depth * 16;
) : ( return (
<HostItem <div
key={i} key={vItem.key}
host={child} style={{
onOpenTab={(type) => onOpenTab(child, type)} position: "absolute",
onEditHost={() => onEditHost(child)} top: 0,
onDelete={() => handleDeleteHost(child)} left: 0,
query={query} width: "100%",
stripeIndex={stripeMap.get(child) ?? 0} transform: `translateY(${vItem.start}px)`,
selectionMode={selectionMode} }}
selected={selectedHostIds.has(child.id)} >
onToggleSelect={() => toggleSelect(child.id)} <div
isMenuOpen={openMenuHostId === child.id} style={
onMenuOpenChange={(open) => depth > 0 ? { paddingLeft: `${indentPx}px` } : undefined
setOpenMenuHostId(open ? child.id : null) }
} >
/> {isFolder(item) ? (
), <FolderItem
folder={item}
flat={true}
depth={depth}
onOpenTab={onOpenTab}
onEditHost={onEditHost}
onShareHost={onShareHost}
onDeleteHost={handleDeleteHost}
onDuplicateHost={handleDuplicateHost}
query={query}
stripeMap={stripeMap}
openFolders={openFolders}
onToggleFolder={toggleFolder}
selectionMode={selectionMode}
selectedHostIds={selectedHostIds}
onToggleSelect={toggleSelect}
openMenuHostId={openMenuHostId}
onMenuOpenChange={setOpenMenuHostId}
/>
) : (
<HostItem
host={item}
onOpenTab={(type) => onOpenTab(item, type)}
onEditHost={() => onEditHost(item)}
onShareHost={
onShareHost ? () => onShareHost(item) : undefined
}
onDelete={() => handleDeleteHost(item)}
onDuplicate={() => handleDuplicateHost(item)}
query={query}
stripeIndex={stripeIndex}
selectionMode={selectionMode}
selected={selectedHostIds.has(item.id)}
onToggleSelect={() => toggleSelect(item.id)}
isMenuOpen={openMenuHostId === item.id}
onMenuOpenChange={(open) =>
setOpenMenuHostId(open ? item.id : null)
}
/>
)}
</div>
</div>
);
})}
</div>
)} )}
</div> </div>