mirror of
https://github.com/YuzuZensai/Termix.git
synced 2026-09-13 10:49:03 +00:00
* fix: patch critical security vulnerabilities (GHSA-5fqh, GHSA-ccm8, GHSA-wqfw, GHSA-xmjh) - Remove passwordHash from /users/list API response - Require both password and TOTP code for MFA-critical operations - Restrict tunnel kill commands to tunnelMarker-only matching - Add session ownership middleware for file manager endpoints * fix: allow navigating away from split-view to non-pane tabs Show the normal view container on top of the split view when the active tab is not assigned to any pane, so users can switch to dashboard or other tabs while split mode is active. Closes #739 * fix: add inline quick-action buttons on host name row Show Terminal, Files, RDP, and VNC shortcut icons on the host name row on hover, so users can launch connections with a single click without expanding the full action tray. Closes #736 * fix: restore SSH keepalive interval to 30s to prevent random disconnects Revert keepalive defaults from 60s/5 to 30s/3 across terminal, tunnel, and server-stats SSH connections. The 60s interval introduced in 2.3.0 causes firewalls and NAT devices to drop idle connections before the next keepalive probe. Closes #733 * fix: apply guacamole-lite protocol patch in Docker builds The Dockerfile uses --ignore-scripts which skips the postinstall hook that patches guacamole-lite for guacd 1.6.0 protocol VERSION_1_5_0. Without this patch, the timezone handshake instruction is not sent for protocol versions above 1.1.0, causing VNC connections to fail immediately on connect. Closes #734 * fix: show correct icons for network interface types Detect interface type from name pattern and show appropriate icons: WiFi for wlan/wl*, Ethernet (Cable) for eth/en*, Container for docker/bridge/virtual, generic Network for others. Closes #720 * fix: resolve sudo password for shared host users The password endpoint required hosts.userId to match the requesting user, which fails for shared hosts. Now falls back to decrypting with the owner's key when the requesting user doesn't own the host. Closes #717 * fix: use jump hosts for online status check and metrics collection Status polling now pings the first jump host instead of the unreachable target when jump hosts are configured. The /metrics/start endpoint now tunnels through the jump host chain to reach the target host. Closes #716 * fix: broaden sudo prompt detection for newer distros Add patterns for 'password for <user>:' and bare 'Password:' prompts in addition to the existing [sudo] and sudo: patterns. Covers Ubuntu 26.04 and other distros that use different sudo prompt formats. Closes #718 * fix: recalculate terminal layout after web fonts load xterm.js measures character widths at open() time. If custom fonts haven't loaded yet, measurements use the fallback font and spacing becomes incorrect. Now refresh and re-fit the terminal once document.fonts.ready resolves. Closes #710 * fix: improve terminal cwd detection and initial directory command Remove '&& pwd' from initial directory command — the shell prompt shows the new directory naturally. Fixes PowerShell 5.1 which doesn't support '&&' as a statement separator. Prepend Ctrl+U to get_cwd command to clear any pending input before injecting the cwd probe, reducing interference with foreground programs. Closes #713, #714 * fix: decode base64 file content as UTF-8 in file manager Replace bare atob() with TextDecoder('utf-8') for base64 content decoding. atob() only handles Latin-1, so multi-byte UTF-8 characters like 'é' were decoded as 'é'. Closes #719 * fix: normalize lazy import default exports for iOS compatibility Wrap all lazy() imports with explicit .then(m => ({ default: m.default })) to ensure consistent module resolution across platforms. iOS Safari/WebView may handle bare lazy(() => import(...)) differently, returning the module object instead of extracting the default export. Closes #721 * fix: prevent RDP display from snapping back after container resize Remove immediate rescaleDisplay() from ResizeObserver callback. The display.onresize event already triggers rescaling when the RDP server responds with the new resolution. Calling rescaleDisplay before the server responds uses stale display dimensions, causing the bottom of the screen to be truncated. Closes #725 * fix: add portal Desktop DBus permission for Flatpak URL opening Flatpak sandbox blocks window.open() without the portal permission, causing terminal link clicks to open about:blank. Add talk-name for org.freedesktop.portal.Desktop to enable xdg-desktop-portal URL handling. Closes #704 * chore: remove unused code and fix PR checks (#851) * chore: remove unused frontend code * chore: prune unused theme exports * ci: fix pr check failures * chore: reduce lint warnings * feat(oidc): expose admin_group via OIDC_ADMIN_GROUP env var (#828) The admin-group OIDC sync added in 2.3.0 (#782) reads `config.admin_group` to sync the user's admin flag from OIDC group membership on each login. That field is only populated when the OIDC config is stored in the in-app DB — `getOIDCConfigFromEnv()` does not expose it, so deployments using the env-var config path (declarative IaC: Helm/Compose/Puppet) cannot enable the feature without abandoning env vars and pasting the client_secret into the admin UI. Add `admin_group: process.env.OIDC_ADMIN_GROUP || ""` to the env-config return type and object. Backward compatible: when unset, the existing `if (config.admin_group)` guard at users.ts:1336 keeps the sync block skipped, matching today's behavior. * chore: reduce explicit-any warnings * chore: reduce more explicit-any warnings * chore: reduce lint warnings * chore: silence intentional hook dependency warnings * chore: clean dependency tooling * chore: narrow frontend tsconfig scope * chore: reduce type assertion debt * refactor: split host manager components * refactor: split host editor sections * refactor: split api client modules * refactor: split more api clients * refactor: split user settings api clients * refactor: split tab and history api clients * refactor: split tunnel api clients * refactor: split server stats api client * refactor: split file manager data api * refactor: split ssh file operations api * refactor: split host editor general tab * refactor: split host editor guacamole tabs * refactor: split ssh host management api * refactor: split admin general settings sections * refactor: split admin database section * refactor: split admin management sections * refactor: split admin keys and dialogs * refactor: split system status api clients * refactor: split user route helpers * refactor: split host route helpers * refactor: split file manager ssh helpers * refactor: split file manager session helpers * refactor: split file manager listing routes * refactor: split host opkssh routes * refactor: split file manager content routes * refactor: split user api key routes * refactor: split host folder routes * refactor: split user settings routes * refactor: split user totp routes * refactor: split host file manager bookmark routes * refactor: split file manager operation routes * refactor: split server stats settings routes * refactor: split user session routes * refactor: split host command history routes * refactor: split server stats viewer routes * refactor: split docker container routes * refactor: split user oidc account routes * refactor: split host autostart routes * refactor: split host internal routes * refactor: split host network routes * refactor: split user password reset routes * refactor: split user admin routes * refactor: split user data access routes * refactor: split credential key routes * refactor: split credential deploy routes * refactor: split host bulk routes * refactor: split server stats connection helpers * refactor: split tunnel helpers * refactor: split file manager action routes * refactor: split terminal auth helpers * refactor: split terminal jump host helpers * refactor: split tunnel relay helpers * refactor: split tunnel socks relay helpers * refactor: split tunnel c2s relay handlers * refactor: split server stats session helpers * refactor: split terminal presentation helpers * refactor: split file manager presentation helpers * refactor: split file manager toolbar * fix(guacamole-lite): send name instruction for protocol >= 1.3.0 The Guacamole protocol added the `name` handshake instruction in 1.3.0 (an optional human-readable identifier for the joining user). guacd 1.6.0 began requiring it during the VNC handshake even when negotiating older protocol versions, causing connections to silently drop right after the "User joined" log line with no client-visible error. This patch extends scripts/patch-guacamole-lite.cjs with a third idempotent string-replacement that injects the `name` instruction send when guacamole-lite has negotiated protocol VERSION_1_3_0 or VERSION_1_5_0. Verified end-to-end: guacd debug logs now show `Processing instruction: name` and `Client is using protocol version "VERSION_1_5_0"` (previously stuck at VERSION_1_1_0). VNC session connects successfully against guacd 1.5.5 / macOS Tahoe target. Related: Termix-SSH/Support#567, #734 * fix: resolve recent support bugs * fix(admin): wire up OIDC-to-password link dialog submit + visibility The admin user-management UI already shipped a link icon and a "Link Account" dialog, but two things blocked the flow: 1. The submit button had no onClick handler and the username input was uncontrolled (no value/onChange). Clicking "Link Accounts" was a no-op — no network request, no console error, no toast. 2. The link icon's visibility condition was `user.isOidc && !user.passwordHash`, which hid the button on OIDC users that had been auto-provisioned with a passwordHash. Termix's OIDC provisioning sets a passwordHash by default, so the button was hidden on virtually every OIDC-provisioned user. This change: - Adds `linkOIDCToPasswordAccount` to the imports from `@/main-axios`. - Adds two pieces of dialog state: `linkAccountTargetUsername` and `linkAccountSubmitting`. - Makes the dialog's Input field a controlled component. - Wires the submit Button's onClick to call `linkOIDCToPasswordAccount`, emit success/error toasts, refresh the local user list, and close the dialog. - Loosens the visibility condition to `user.isOidc` (the backend handler already enforces all integrity checks). - Adds `linkAccountSuccess`, `linkAccountFailed`, and `linkAccountInProgress` translation keys to `en.json`. Verified locally: full Docker build via docker/Dockerfile passes; `tsc --noEmit` is clean; `prettier --check .` is clean; ESLint produces the same warning count as upstream (16 pre-existing `any`-type warnings, 0 errors). * fix: support native oidc callbacks (#856) * docs: add cloudflare tunnel guidance (#857) * fix: sync appearance preferences (#858) * fix: pass through terminal tab completion (#859) * fix: resolve terminal jump hosts server-side (#860) * fix(electron): auto-allow SSL certificates for private network hosts (#861) Add private network IP detection (RFC 1918, link-local, loopback, IPv6 ULA) to the Electron certificate-error handler so that connections to local/private servers like 192.168.x.x bypass SSL validation automatically. Also add an explicit "Allow invalid certificate" toggle in the server config UI for public HTTPS servers with self-signed certs. * fix: restore host password copy actions (#862) * feat: support single-host direct tunnels (ssh -L style) (#863) Add direct tunnel mode that uses a single SSH host for port forwarding, matching the behavior of ssh -L / ssh -R / ssh -D without requiring a second endpoint host in the Termix database. The Termix server creates a local TCP listener and forwards through the SSH channel directly. * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * fix: backend build errors (Type) * fix: mobile auth failing to login with webview * fix: mobile app geting incorrectly sent auth token * feat: commit existing frontend/backend e2e/unit tests (skipped tests containing private info like OIDC and real server testing) * feat: host-to-host file transfer via server relay * feat: removed host management from command palette, fixed command palette opening wrong protocol, export/import failing for ssh key hosts, docker ssh2 native crypto not compiled, persisted terminal tabs attempt SSh on RDP hosts after migration, improved layout for click to expand hosts, show ip/username without having to hover over hosts * fix: credentials not indexing into host manager until refresh * feat: update credentials lists to match hosts list UI/UX * feat: add rename folder UI * feat: improve transfer to host UI/UX * chore: increment ver * feat: improve transfer to host UI * feat: implement initial auto release system --------- Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com> Co-authored-by: nicodarge <43711429+nicodarge@users.noreply.github.com> Co-authored-by: Raman Gupta <7243222+raman325@users.noreply.github.com> Co-authored-by: luc <luc_cook@hotmail.co.uk>
1282 lines
42 KiB
TypeScript
1282 lines
42 KiB
TypeScript
/* eslint-disable react-refresh/only-export-components */
|
|
/* eslint-disable react-hooks/exhaustive-deps */
|
|
import { toast } from "sonner";
|
|
import { useTranslation } from "react-i18next";
|
|
import { Separator } from "@/components/separator";
|
|
import { Button } from "@/components/button";
|
|
import { Sheet, SheetContent } from "@/components/sheet";
|
|
import { ChevronLeft, ChevronRight, Maximize2 } from "lucide-react";
|
|
import { useState, useRef, useCallback, useEffect, createRef } from "react";
|
|
import { createPortal } from "react-dom";
|
|
import { useIsMobile } from "@/hooks/use-mobile";
|
|
import { MobileBottomBar } from "@/shell/MobileBottomBar";
|
|
import { CommandPalette } from "@/shell/CommandPalette";
|
|
import { AppRail } from "@/sidebar/AppRail";
|
|
import type { RailView } from "@/sidebar/AppRail";
|
|
import { HostsPanel } from "@/sidebar/HostsPanel";
|
|
import { QuickConnectPanel } from "@/sidebar/QuickConnectPanel";
|
|
import { SshToolsPanel } from "@/sidebar/SshToolsPanel";
|
|
import { SnippetsPanel } from "@/sidebar/SnippetsPanel";
|
|
import { HistoryPanel } from "@/sidebar/HistoryPanel";
|
|
import { SplitScreenPanel } from "@/sidebar/SplitScreenPanel";
|
|
import { UserProfilePanel } from "@/sidebar/UserProfilePanel";
|
|
import { AdminSettingsPanel } from "@/sidebar/AdminSettingsPanel";
|
|
import { CredentialsPanel } from "@/sidebar/CredentialsPanel";
|
|
import { SplitView } from "@/shell/SplitView";
|
|
import { renderTabContent } from "@/shell/tabUtils";
|
|
import { TabBar } from "@/shell/TabBar";
|
|
import type {
|
|
Tab,
|
|
TabType,
|
|
Host,
|
|
SplitMode,
|
|
HostFolder,
|
|
ThemeId,
|
|
FontSizeId,
|
|
} from "@/types/ui-types";
|
|
import { applyAccentColor, applyFontSize, PANE_COUNTS } from "@/lib/theme";
|
|
import { useTheme } from "@/components/theme-provider";
|
|
import {
|
|
getSSHHosts,
|
|
getUserInfo,
|
|
getOpenTabs,
|
|
addOpenTab,
|
|
deleteOpenTab,
|
|
patchOpenTab,
|
|
getActiveSessions,
|
|
getUserPreferences,
|
|
type UserPreferences,
|
|
type OpenTabRecord,
|
|
} from "@/main-axios";
|
|
import { dbHealthMonitor } from "@/lib/db-health-monitor";
|
|
import type { SSHHostWithStatus } from "@/main-axios";
|
|
import { ConnectionsPanel } from "@/sidebar/ConnectionsPanel";
|
|
import { TransferMonitor } from "@/features/file-manager/TransferMonitor.tsx";
|
|
|
|
function sshHostToHost(h: SSHHostWithStatus): Host {
|
|
return {
|
|
id: String(h.id),
|
|
name: h.name,
|
|
username: h.username,
|
|
ip: h.ip,
|
|
port: h.port,
|
|
folder: h.folder ?? "",
|
|
online: h.status === "online",
|
|
cpu: 0,
|
|
ram: 0,
|
|
lastAccess: "",
|
|
tags: h.tags ?? [],
|
|
authType: h.authType,
|
|
password: h.password,
|
|
key: typeof h.key === "string" ? h.key : undefined,
|
|
keyPassword: h.keyPassword,
|
|
keyType: h.keyType,
|
|
credentialId: h.credentialId != null ? String(h.credentialId) : undefined,
|
|
notes: h.notes,
|
|
pin: h.pin ?? false,
|
|
macAddress: h.macAddress,
|
|
enableSsh: h.enableSsh ?? (h.connectionType === "ssh" || !h.connectionType),
|
|
enableTerminal: h.enableTerminal ?? true,
|
|
enableTunnel: h.enableTunnel ?? false,
|
|
enableFileManager: h.enableFileManager ?? false,
|
|
enableDocker: h.enableDocker ?? false,
|
|
enableRdp: h.enableRdp ?? h.connectionType === "rdp",
|
|
enableVnc: h.enableVnc ?? h.connectionType === "vnc",
|
|
enableTelnet: h.enableTelnet ?? h.connectionType === "telnet",
|
|
sshPort: h.port,
|
|
rdpPort: 3389,
|
|
vncPort: 5900,
|
|
telnetPort: 23,
|
|
quickActions: (h.quickActions ?? []).map((a) => ({
|
|
name: a.name,
|
|
snippetId: String(a.snippetId),
|
|
})),
|
|
jumpHosts: (h.jumpHosts ?? []).map((j) => ({
|
|
hostId: String(j.hostId),
|
|
})),
|
|
serverTunnels: [],
|
|
defaultPath: h.defaultPath,
|
|
terminalConfig: h.terminalConfig as Host["terminalConfig"],
|
|
useSocks5: h.useSocks5,
|
|
socks5Host: h.socks5Host,
|
|
socks5Port: h.socks5Port,
|
|
socks5Username: h.socks5Username,
|
|
socks5Password: h.socks5Password,
|
|
socks5ProxyChain: h.socks5ProxyChain ?? [],
|
|
};
|
|
}
|
|
|
|
function buildHostTree(hosts: SSHHostWithStatus[]): HostFolder {
|
|
const root: HostFolder = { name: "root", children: [] };
|
|
const folderMap = new Map<string, HostFolder>();
|
|
const getOrCreateFolder = (path: string): HostFolder => {
|
|
if (folderMap.has(path)) return folderMap.get(path)!;
|
|
const parts = path.split(" / ");
|
|
let current = root;
|
|
let accumulated = "";
|
|
for (const part of parts) {
|
|
accumulated = accumulated ? `${accumulated} / ${part}` : part;
|
|
if (!folderMap.has(accumulated)) {
|
|
const folder: HostFolder = { name: part, children: [] };
|
|
folderMap.set(accumulated, folder);
|
|
current.children.push(folder);
|
|
}
|
|
current = folderMap.get(accumulated)!;
|
|
}
|
|
return current;
|
|
};
|
|
for (const h of hosts) {
|
|
const host = sshHostToHost(h);
|
|
if (h.folder) {
|
|
getOrCreateFolder(h.folder).children.push(host);
|
|
} else {
|
|
root.children.push(host);
|
|
}
|
|
}
|
|
return root;
|
|
}
|
|
export { tabIcon, renderTabContent } from "@/shell/tabUtils";
|
|
|
|
// ─── AppShell ────────────────────────────────────────────────────────────────
|
|
|
|
export function AppShell({
|
|
username,
|
|
onLogout,
|
|
}: {
|
|
username: string;
|
|
onLogout: () => void;
|
|
}) {
|
|
const { t, i18n } = useTranslation();
|
|
const { setTheme } = useTheme();
|
|
const [tabs, setTabs] = useState<Tab[]>([
|
|
{
|
|
id: "dashboard",
|
|
instanceId: "dashboard",
|
|
type: "dashboard",
|
|
label: t("nav.dashboard"),
|
|
openedAt: Date.now(),
|
|
},
|
|
]);
|
|
const [activeTabId, setActiveTabId] = useState("dashboard");
|
|
const [userPrefs, setUserPrefs] = useState<UserPreferences>({
|
|
reopenTabsOnLogin: false,
|
|
});
|
|
const [userPrefsLoaded, setUserPrefsLoaded] = useState(false);
|
|
const [hostsLoaded, setHostsLoaded] = useState(false);
|
|
// Flips to true once the initial DB read (restore or skip) is done — sync must not fire before this
|
|
const [tabsReady, setTabsReady] = useState(false);
|
|
const [commandPaletteOpen, setCommandPaletteOpen] = useState(false);
|
|
const [splitMode, setSplitMode] = useState<SplitMode>(
|
|
() => (localStorage.getItem("termix_splitMode") as SplitMode) ?? "none",
|
|
);
|
|
const [paneTabIds, setPaneTabIds] = useState<(string | null)[]>(
|
|
() =>
|
|
JSON.parse(localStorage.getItem("termix_paneTabIds") ?? "null") ??
|
|
Array(6).fill(null),
|
|
);
|
|
const [focusedPaneIndex, setFocusedPaneIndex] = useState<number | null>(null);
|
|
const [realHostTree, setRealHostTree] = useState<HostFolder | null>(null);
|
|
const [hostsLoading, setHostsLoading] = useState(true);
|
|
const [allHosts, setAllHosts] = useState<Host[]>([]);
|
|
const [isAdmin, setIsAdmin] = useState(false);
|
|
const [backgroundTabRecords, setBackgroundTabRecords] = useState<
|
|
OpenTabRecord[]
|
|
>([]);
|
|
|
|
const [sidebarOpen, setSidebarOpen] = useState(true);
|
|
const [railView, setRailView] = useState<RailView>("hosts");
|
|
const [profileDropdownOpen, setProfileDropdownOpen] = useState(false);
|
|
const [sidebarWidth, setSidebarWidth] = useState(() => {
|
|
const saved = localStorage.getItem("termix_sidebarWidth");
|
|
return saved ? parseInt(saved, 10) : 266;
|
|
});
|
|
const [sidebarDragging, setSidebarDragging] = useState(false);
|
|
const [sidebarEditing, setSidebarEditing] = useState(false);
|
|
|
|
useEffect(() => {
|
|
localStorage.setItem("termix_sidebarWidth", String(sidebarWidth));
|
|
}, [sidebarWidth]);
|
|
|
|
useEffect(() => {
|
|
localStorage.setItem("termix_splitMode", splitMode);
|
|
}, [splitMode]);
|
|
|
|
useEffect(() => {
|
|
localStorage.setItem("termix_paneTabIds", JSON.stringify(paneTabIds));
|
|
}, [paneTabIds]);
|
|
|
|
const isMobile = useIsMobile();
|
|
|
|
const sidebarOpenBeforeMobile = useRef(sidebarOpen);
|
|
useEffect(() => {
|
|
if (isMobile) {
|
|
sidebarOpenBeforeMobile.current = sidebarOpen;
|
|
setSidebarOpen(false);
|
|
} else {
|
|
setSidebarOpen(sidebarOpenBeforeMobile.current);
|
|
}
|
|
}, [isMobile]);
|
|
|
|
useEffect(() => {
|
|
getUserInfo()
|
|
.then((info) => setIsAdmin(info.is_admin))
|
|
.catch(() => setIsAdmin(false));
|
|
}, []);
|
|
|
|
const lastShiftTime = useRef(0);
|
|
const [commandPaletteShortcutEnabled, setCommandPaletteShortcutEnabled] =
|
|
useState<boolean>(() => {
|
|
const v = localStorage.getItem("commandPaletteShortcutEnabled");
|
|
return v !== null ? v === "true" : true;
|
|
});
|
|
const terminalRefs = useRef<Map<string, ReturnType<typeof createRef>>>(
|
|
new Map(),
|
|
);
|
|
const [paneContentEls, setPaneContentEls] = useState<
|
|
(HTMLDivElement | null)[]
|
|
>(Array(6).fill(null));
|
|
|
|
// Stable per-tab DOM nodes — created once per tab, never destroyed while the tab lives.
|
|
// We always portal each tab's content into its own node, then move that node between
|
|
// the normal-view container and the pane container via vanilla DOM so React's portal
|
|
// target never changes (changing the target causes a remount).
|
|
const tabNodesRef = useRef<Map<string, HTMLDivElement>>(new Map());
|
|
const normalViewRef = useRef<HTMLDivElement>(null);
|
|
|
|
const getTabNode = useCallback((tabId: string, isTerminal: boolean) => {
|
|
if (!tabNodesRef.current.has(tabId)) {
|
|
const el = document.createElement("div");
|
|
el.style.position = "absolute";
|
|
el.style.inset = "0";
|
|
el.style.overflow = "hidden";
|
|
if (!isTerminal) el.classList.add("bg-background");
|
|
tabNodesRef.current.set(tabId, el);
|
|
}
|
|
return tabNodesRef.current.get(tabId)!;
|
|
}, []);
|
|
|
|
const onPaneContentRef = useCallback(
|
|
(paneIndex: number, el: HTMLDivElement | null) => {
|
|
setPaneContentEls((prev) => {
|
|
if (prev[paneIndex] === el) return prev;
|
|
const next = [...prev];
|
|
next[paneIndex] = el;
|
|
return next;
|
|
});
|
|
},
|
|
[],
|
|
);
|
|
|
|
const sidebarTitle: Record<RailView, string> = {
|
|
hosts: "Hosts",
|
|
credentials: "Credentials",
|
|
"quick-connect": "Quick Connect",
|
|
"ssh-tools": "SSH Tools",
|
|
snippets: "Snippets",
|
|
history: "History",
|
|
"split-screen": "Split Screen",
|
|
connections: t("nav.connections"),
|
|
"user-profile": "User Profile",
|
|
"admin-settings": "Admin Settings",
|
|
};
|
|
|
|
// Double-shift opens command palette
|
|
useEffect(() => {
|
|
const handleKeyDown = (e: KeyboardEvent) => {
|
|
if (e.code === "ShiftLeft" && !e.repeat) {
|
|
const now = Date.now();
|
|
if (now - lastShiftTime.current < 300 && commandPaletteShortcutEnabled)
|
|
setCommandPaletteOpen((prev) => !prev);
|
|
lastShiftTime.current = now;
|
|
}
|
|
};
|
|
window.addEventListener("keydown", handleKeyDown);
|
|
return () => window.removeEventListener("keydown", handleKeyDown);
|
|
}, [commandPaletteShortcutEnabled]);
|
|
|
|
useEffect(() => {
|
|
const handler = () => {
|
|
const v = localStorage.getItem("commandPaletteShortcutEnabled");
|
|
setCommandPaletteShortcutEnabled(v !== null ? v === "true" : true);
|
|
};
|
|
window.addEventListener("commandPaletteShortcutEnabledChanged", handler);
|
|
return () =>
|
|
window.removeEventListener(
|
|
"commandPaletteShortcutEnabledChanged",
|
|
handler,
|
|
);
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
const handle = () => onLogout();
|
|
window.addEventListener("termix:logout", handle);
|
|
return () => window.removeEventListener("termix:logout", handle);
|
|
}, [onLogout]);
|
|
|
|
useEffect(() => {
|
|
const handleSessionExpired = () => onLogout();
|
|
dbHealthMonitor.on("session-expired", handleSessionExpired);
|
|
return () => dbHealthMonitor.off("session-expired", handleSessionExpired);
|
|
}, [onLogout]);
|
|
|
|
useEffect(() => {
|
|
const activeTab = tabs.find((t) => t.id === activeTabId);
|
|
if (!activeTab?.terminalRef) return;
|
|
let innerRafId: number;
|
|
const outerRafId = requestAnimationFrame(() => {
|
|
innerRafId = requestAnimationFrame(() => {
|
|
const ref = activeTab.terminalRef?.current;
|
|
ref?.fit?.();
|
|
ref?.notifyResize?.();
|
|
ref?.refresh?.();
|
|
});
|
|
});
|
|
return () => {
|
|
cancelAnimationFrame(outerRafId);
|
|
cancelAnimationFrame(innerRafId);
|
|
};
|
|
}, [activeTabId]);
|
|
|
|
useEffect(() => {
|
|
const handleDegraded = () => {
|
|
toast.loading(t("common.connectionDegraded"), {
|
|
id: "db-connection-degraded",
|
|
duration: Infinity,
|
|
dismissible: false,
|
|
action: {
|
|
label: t("common.reload"),
|
|
onClick: () => window.location.reload(),
|
|
},
|
|
});
|
|
};
|
|
|
|
const handleRestored = () => {
|
|
toast.dismiss("db-connection-degraded");
|
|
toast.success(t("common.backendReconnected"), { duration: 3000 });
|
|
};
|
|
|
|
dbHealthMonitor.on("database-connection-degraded", handleDegraded);
|
|
dbHealthMonitor.on("database-connection-degraded-cleared", handleRestored);
|
|
|
|
return () => {
|
|
dbHealthMonitor.off("database-connection-degraded", handleDegraded);
|
|
dbHealthMonitor.off(
|
|
"database-connection-degraded-cleared",
|
|
handleRestored,
|
|
);
|
|
};
|
|
}, [t]);
|
|
|
|
useEffect(() => {
|
|
getUserPreferences()
|
|
.then((prefs) => {
|
|
setUserPrefs(prefs);
|
|
if (prefs.theme) setTheme(prefs.theme as ThemeId);
|
|
if (prefs.fontSize) applyFontSize(prefs.fontSize as FontSizeId);
|
|
if (prefs.accentColor) {
|
|
localStorage.setItem("termix-accent", prefs.accentColor);
|
|
applyAccentColor(prefs.accentColor);
|
|
}
|
|
if (prefs.language && prefs.language !== i18n.language) {
|
|
localStorage.setItem("i18nextLng", prefs.language);
|
|
void i18n.changeLanguage(prefs.language);
|
|
}
|
|
})
|
|
.catch(() => {})
|
|
.finally(() => setUserPrefsLoaded(true));
|
|
}, []);
|
|
|
|
// Load real hosts from API
|
|
const loadHosts = useCallback(async () => {
|
|
try {
|
|
const raw = await getSSHHosts();
|
|
const converted = raw.map(sshHostToHost);
|
|
setAllHosts(converted);
|
|
setRealHostTree(buildHostTree(raw));
|
|
} catch {
|
|
// Keep empty state on error
|
|
} finally {
|
|
setHostsLoading(false);
|
|
setHostsLoaded(true);
|
|
}
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
loadHosts();
|
|
}, [loadHosts]);
|
|
|
|
useEffect(() => {
|
|
window.addEventListener("termix:hosts-changed", loadHosts);
|
|
return () => window.removeEventListener("termix:hosts-changed", loadHosts);
|
|
}, [loadHosts]);
|
|
|
|
// Sync tab host data when allHosts updates (e.g. after editing terminal theme in host settings)
|
|
useEffect(() => {
|
|
if (allHosts.length === 0) return;
|
|
setTabs((prev) =>
|
|
prev.map((t) =>
|
|
t.host
|
|
? { ...t, host: allHosts.find((h) => h.id === t.host!.id) ?? t.host }
|
|
: t,
|
|
),
|
|
);
|
|
}, [allHosts]);
|
|
|
|
// Let HostManager trigger tab opens via custom event
|
|
useEffect(() => {
|
|
const handle = (e: Event) => {
|
|
const { hostId, type } = (
|
|
e as CustomEvent<{ hostId: string; type?: TabType }>
|
|
).detail;
|
|
const host = allHosts.find((h) => h.id === hostId);
|
|
if (host) connectHost(host, type);
|
|
};
|
|
window.addEventListener("termix:open-tab", handle);
|
|
return () => window.removeEventListener("termix:open-tab", handle);
|
|
}, [allHosts]);
|
|
|
|
const PERSISTENT_TAB_TYPES: TabType[] = [
|
|
"terminal",
|
|
"rdp",
|
|
"vnc",
|
|
"telnet",
|
|
"files",
|
|
"docker",
|
|
"stats",
|
|
"tunnel",
|
|
];
|
|
|
|
// On load: always read saved tabs from DB so background sessions are preserved across refreshes.
|
|
// If reopenTabsOnLogin is on, also restore them as open tabs in the tab bar.
|
|
const tabRestoreAttemptedRef = useRef(false);
|
|
useEffect(() => {
|
|
if (!hostsLoaded || !userPrefsLoaded) return;
|
|
if (tabRestoreAttemptedRef.current) return;
|
|
tabRestoreAttemptedRef.current = true;
|
|
|
|
async function loadSavedTabs() {
|
|
try {
|
|
const [savedTabs, activeSessions] = await Promise.all([
|
|
getOpenTabs(),
|
|
getActiveSessions(),
|
|
]);
|
|
|
|
if (!Array.isArray(savedTabs) || savedTabs.length === 0) return;
|
|
|
|
const sessionByInstanceId = new Map(
|
|
(Array.isArray(activeSessions) ? activeSessions : [])
|
|
.filter((s) => s.tabInstanceId != null)
|
|
.map((s) => [s.tabInstanceId, s]),
|
|
);
|
|
|
|
if (userPrefs.reopenTabsOnLogin) {
|
|
const hasPersistentTabs = tabs.some((t) =>
|
|
PERSISTENT_TAB_TYPES.includes(t.type),
|
|
);
|
|
if (!hasPersistentTabs) {
|
|
const restoredTabs: Tab[] = [];
|
|
for (const saved of savedTabs as OpenTabRecord[]) {
|
|
const host = saved.hostId
|
|
? allHosts.find((h) => h.id === String(saved.hostId))
|
|
: undefined;
|
|
const hostlessTypes: TabType[] = ["dashboard", "tunnel"];
|
|
if (!host && !hostlessTypes.includes(saved.tabType as TabType))
|
|
continue;
|
|
|
|
if (host) {
|
|
if (saved.tabType === "terminal" && !host.enableSsh) continue;
|
|
if (saved.tabType === "rdp" && !host.enableRdp) continue;
|
|
if (saved.tabType === "vnc" && !host.enableVnc) continue;
|
|
if (saved.tabType === "telnet" && !host.enableTelnet) continue;
|
|
}
|
|
|
|
// Singleton tabs use their type as the stable ID; host-bound tabs get a unique ID
|
|
const tabId = host
|
|
? `${host.name}-${saved.tabType}-${Date.now()}-${saved.tabOrder}`
|
|
: saved.id;
|
|
const liveSession = sessionByInstanceId.get(saved.id);
|
|
const restoredSessionId =
|
|
liveSession?.sessionId ?? saved.backendSessionId ?? null;
|
|
|
|
restoredTabs.push({
|
|
id: tabId,
|
|
instanceId: saved.id,
|
|
type: saved.tabType as TabType,
|
|
label: saved.label,
|
|
host,
|
|
openedAt: new Date(saved.createdAt).getTime(),
|
|
restoredSessionId,
|
|
terminalRef:
|
|
saved.tabType === "terminal" ? createRef() : undefined,
|
|
});
|
|
}
|
|
|
|
if (restoredTabs.length > 0) {
|
|
setTabs((prev) => {
|
|
const existingIds = new Set(prev.map((t) => t.id));
|
|
const newTabs = restoredTabs.filter(
|
|
(t) => !existingIds.has(t.id),
|
|
);
|
|
return newTabs.length > 0 ? [...prev, ...newTabs] : prev;
|
|
});
|
|
setActiveTabId(restoredTabs[0].id);
|
|
}
|
|
// Restored tabs are in the tab bar, not in background records
|
|
}
|
|
} else {
|
|
// Not restoring to tab bar — keep as background records for ConnectionsPanel
|
|
setBackgroundTabRecords(savedTabs as OpenTabRecord[]);
|
|
}
|
|
} catch {
|
|
// silently fail
|
|
} finally {
|
|
setTabsReady(true);
|
|
}
|
|
}
|
|
|
|
loadSavedTabs();
|
|
}, [hostsLoaded, userPrefsLoaded]);
|
|
|
|
// Debounced tab-order sync: when tab order changes, patch each persistent tab's tabOrder in DB.
|
|
const orderSyncTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(
|
|
null,
|
|
);
|
|
const prevTabOrderRef = useRef<string>("");
|
|
useEffect(() => {
|
|
if (!tabsReady) return;
|
|
const persistable = tabs.filter((t) =>
|
|
PERSISTENT_TAB_TYPES.includes(t.type),
|
|
);
|
|
const orderKey = persistable.map((t) => t.instanceId).join(",");
|
|
if (orderKey === prevTabOrderRef.current) return;
|
|
prevTabOrderRef.current = orderKey;
|
|
|
|
if (orderSyncTimeoutRef.current) clearTimeout(orderSyncTimeoutRef.current);
|
|
orderSyncTimeoutRef.current = setTimeout(() => {
|
|
persistable.forEach((t, i) => {
|
|
patchOpenTab(t.instanceId, { tabOrder: i }).catch(() => {});
|
|
});
|
|
}, 500);
|
|
|
|
return () => {
|
|
if (orderSyncTimeoutRef.current)
|
|
clearTimeout(orderSyncTimeoutRef.current);
|
|
};
|
|
}, [tabs, tabsReady]);
|
|
|
|
// ─── Tab management ──────────────────────────────────────────────────────
|
|
|
|
const openTab = useCallback(function openTab(
|
|
host: Host,
|
|
type: TabType,
|
|
restore?: { instanceId: string; restoredSessionId: string | null },
|
|
) {
|
|
const tabId = `${host.name}-${type}-${Date.now()}`;
|
|
const instanceId =
|
|
restore?.instanceId ??
|
|
(typeof crypto.randomUUID === "function"
|
|
? crypto.randomUUID()
|
|
: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`);
|
|
const openedAt = Date.now();
|
|
const ref = type === "terminal" ? createRef() : undefined;
|
|
if (ref) terminalRefs.current.set(tabId, ref);
|
|
|
|
let finalLabel = host.name;
|
|
setTabs((prev) => {
|
|
const same = prev.filter(
|
|
(t) =>
|
|
t.type === type && t.label.replace(/ \(\d+\)$/, "") === host.name,
|
|
);
|
|
finalLabel =
|
|
same.length === 0 ? host.name : `${host.name} (${same.length + 1})`;
|
|
|
|
// Retrofit the first duplicate's label to "(1)" if needed
|
|
const next =
|
|
same.length === 1 && !/\(\d+\)$/.test(same[0].label)
|
|
? prev.map((t) =>
|
|
t.id === same[0].id ? { ...t, label: `${host.name} (1)` } : t,
|
|
)
|
|
: prev;
|
|
|
|
return [
|
|
...next,
|
|
{
|
|
id: tabId,
|
|
instanceId,
|
|
type,
|
|
label: finalLabel,
|
|
host,
|
|
openedAt,
|
|
terminalRef: ref,
|
|
restoredSessionId: restore?.restoredSessionId ?? null,
|
|
},
|
|
];
|
|
});
|
|
setActiveTabId(tabId);
|
|
|
|
if (PERSISTENT_TAB_TYPES.includes(type)) {
|
|
addOpenTab({
|
|
id: instanceId,
|
|
tabType: type,
|
|
hostId: host ? parseInt(host.id) : null,
|
|
label: finalLabel,
|
|
tabOrder: 0,
|
|
}).catch(() => {});
|
|
}
|
|
}, []);
|
|
|
|
function connectHost(host: Host, preferredType?: TabType) {
|
|
const type: TabType =
|
|
preferredType ??
|
|
(host.enableSsh
|
|
? "terminal"
|
|
: host.enableRdp
|
|
? "rdp"
|
|
: host.enableVnc
|
|
? "vnc"
|
|
: host.enableTelnet
|
|
? "telnet"
|
|
: "terminal");
|
|
openTab(host, type);
|
|
}
|
|
|
|
const openSingletonTab = useCallback(
|
|
function openSingletonTab(type: TabType, pendingEvent?: string) {
|
|
if (type === "host-manager") {
|
|
if (pendingEvent === "host-manager:add-credential") {
|
|
setSidebarOpen(true);
|
|
setRailView("credentials");
|
|
setTimeout(
|
|
() =>
|
|
window.dispatchEvent(
|
|
new CustomEvent("host-manager:add-credential"),
|
|
),
|
|
0,
|
|
);
|
|
} else {
|
|
setSidebarOpen(true);
|
|
setRailView("hosts");
|
|
if (pendingEvent) {
|
|
setTimeout(
|
|
() => window.dispatchEvent(new CustomEvent(pendingEvent)),
|
|
0,
|
|
);
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
if (type === "user-profile" || type === "admin-settings") {
|
|
setSidebarEditing(false);
|
|
setRailView(type as RailView);
|
|
setSidebarOpen(true);
|
|
return;
|
|
}
|
|
const id = type;
|
|
const singletonLabels: Partial<Record<TabType, string>> = {
|
|
"host-manager": t("nav.hostManager"),
|
|
docker: t("nav.docker"),
|
|
tunnel: t("nav.tunnels"),
|
|
network_graph: t("nav.networkGraph"),
|
|
};
|
|
setTabs((prev) => {
|
|
if (prev.find((t) => t.id === id)) return prev;
|
|
return [
|
|
...prev,
|
|
{
|
|
id,
|
|
instanceId: id,
|
|
type,
|
|
label: singletonLabels[type] ?? type,
|
|
openedAt: Date.now(),
|
|
},
|
|
];
|
|
});
|
|
setActiveTabId(id);
|
|
if (PERSISTENT_TAB_TYPES.includes(type)) {
|
|
addOpenTab({
|
|
id,
|
|
tabType: type,
|
|
hostId: null,
|
|
label: singletonLabels[type] ?? type,
|
|
tabOrder: 0,
|
|
}).catch(() => {});
|
|
}
|
|
},
|
|
[t],
|
|
);
|
|
|
|
const SESSION_TAB_TYPES: TabType[] = ["terminal", "rdp", "vnc", "telnet"];
|
|
|
|
function doCloseTab(id: string) {
|
|
const tabToClose = tabs.find((t) => t.id === id);
|
|
if (
|
|
tabToClose?.instanceId &&
|
|
PERSISTENT_TAB_TYPES.includes(tabToClose.type)
|
|
) {
|
|
deleteOpenTab(tabToClose.instanceId).catch(() => {});
|
|
}
|
|
|
|
terminalRefs.current.delete(id);
|
|
if (id === activeTabId) {
|
|
const remaining = tabs.filter((t) => t.id !== id);
|
|
setActiveTabId(
|
|
remaining.length > 0 ? remaining[remaining.length - 1].id : "dashboard",
|
|
);
|
|
}
|
|
setPaneTabIds((prev) => prev.map((p) => (p === id ? null : p)));
|
|
setTabs((prev) => {
|
|
const next = prev.filter((t) => t.id !== id);
|
|
if (next.length === 0)
|
|
return [
|
|
{
|
|
id: "dashboard",
|
|
instanceId: "dashboard",
|
|
type: "dashboard",
|
|
label: t("nav.dashboard"),
|
|
openedAt: Date.now(),
|
|
},
|
|
];
|
|
return next;
|
|
});
|
|
}
|
|
|
|
function refreshTab(id: string) {
|
|
const tab = tabs.find((t) => t.id === id);
|
|
if (!tab) return;
|
|
if (tab.type === "terminal") {
|
|
const ref = tab.terminalRef?.current;
|
|
ref?.reconnect?.();
|
|
} else if (["rdp", "vnc", "telnet"].includes(tab.type)) {
|
|
window.dispatchEvent(
|
|
new CustomEvent("termix:refresh-guacamole", { detail: { tabId: id } }),
|
|
);
|
|
}
|
|
}
|
|
|
|
function closeTab(id: string) {
|
|
const tab = tabs.find((t) => t.id === id);
|
|
const confirmEnabled = localStorage.getItem("confirmTabClose") === "true";
|
|
if (tab && SESSION_TAB_TYPES.includes(tab.type) && confirmEnabled) {
|
|
toast(t("nav.confirmClose"), {
|
|
duration: 5000,
|
|
action: {
|
|
label: t("nav.close"),
|
|
onClick: () => doCloseTab(id),
|
|
},
|
|
cancel: {
|
|
label: t("nav.cancel"),
|
|
onClick: () => {},
|
|
},
|
|
});
|
|
return;
|
|
}
|
|
doCloseTab(id);
|
|
}
|
|
|
|
function splitTabQuick(tabId: string, mode: SplitMode) {
|
|
setSplitMode(mode);
|
|
setPaneTabIds(() => {
|
|
const count = PANE_COUNTS[mode];
|
|
const next: (string | null)[] = Array(6).fill(null);
|
|
next[0] = tabId;
|
|
// Fill remaining panes with other non-dashboard tabs in order
|
|
let slot = 1;
|
|
for (const tab of tabs) {
|
|
if (slot >= count) break;
|
|
if (tab.id !== tabId && tab.type !== "dashboard") {
|
|
next[slot] = tab.id;
|
|
slot++;
|
|
}
|
|
}
|
|
return next;
|
|
});
|
|
}
|
|
|
|
function addTabToSplit(tabId: string) {
|
|
setPaneTabIds((prev) => {
|
|
// Remove from any current slot first
|
|
const next = prev.map((p) => (p === tabId ? null : p));
|
|
// Find first empty slot within the current pane count
|
|
const count = PANE_COUNTS[splitMode];
|
|
for (let i = 0; i < count; i++) {
|
|
if (!next[i]) {
|
|
next[i] = tabId;
|
|
break;
|
|
}
|
|
}
|
|
return next;
|
|
});
|
|
}
|
|
|
|
function removeTabFromSplit(tabId: string) {
|
|
setPaneTabIds((prev) => prev.map((p) => (p === tabId ? null : p)));
|
|
}
|
|
|
|
function assignPane(paneIndex: number, tabId: string) {
|
|
setPaneTabIds((prev) => {
|
|
const next = prev.map((p) => (p === tabId ? null : p));
|
|
next[paneIndex] = tabId;
|
|
return next;
|
|
});
|
|
}
|
|
|
|
// ─── Rail / sidebar ──────────────────────────────────────────────────────
|
|
|
|
function handleRailClick(view: RailView) {
|
|
if (railView === view && sidebarOpen) {
|
|
setSidebarOpen(false);
|
|
} else {
|
|
if (view !== railView) setSidebarEditing(false);
|
|
setRailView(view);
|
|
setSidebarOpen(true);
|
|
}
|
|
}
|
|
|
|
function editHostInManager(host: Host) {
|
|
setSidebarOpen(true);
|
|
setRailView("hosts");
|
|
setTimeout(() => {
|
|
window.dispatchEvent(
|
|
new CustomEvent("host-manager:edit-host", { detail: host.id }),
|
|
);
|
|
}, 0);
|
|
}
|
|
|
|
const onSidebarMouseDown = useCallback(
|
|
(e: React.MouseEvent) => {
|
|
e.preventDefault();
|
|
setSidebarDragging(true);
|
|
const startX = e.clientX;
|
|
const startW = sidebarWidth;
|
|
function onMove(ev: MouseEvent) {
|
|
setSidebarWidth(
|
|
Math.max(160, Math.min(480, startW + ev.clientX - startX)),
|
|
);
|
|
}
|
|
function onUp() {
|
|
setSidebarDragging(false);
|
|
window.removeEventListener("mousemove", onMove);
|
|
window.removeEventListener("mouseup", onUp);
|
|
}
|
|
window.addEventListener("mousemove", onMove);
|
|
window.addEventListener("mouseup", onUp);
|
|
},
|
|
[sidebarWidth],
|
|
);
|
|
|
|
// Resize all terminals in panes + active terminal when split mode or sidebar changes
|
|
const resizeAllTerminals = useCallback(() => {
|
|
const id = requestAnimationFrame(() => {
|
|
tabs.forEach((tab) => {
|
|
if (!tab.terminalRef) return;
|
|
const ref = tab.terminalRef.current;
|
|
ref?.fit?.();
|
|
ref?.notifyResize?.();
|
|
});
|
|
});
|
|
return id;
|
|
}, [tabs]);
|
|
|
|
useEffect(() => {
|
|
const id = resizeAllTerminals();
|
|
return () => cancelAnimationFrame(id);
|
|
}, [splitMode, sidebarWidth, sidebarOpen]);
|
|
|
|
const isSplit = splitMode !== "none";
|
|
|
|
// Move each tab's stable DOM node to the right container (pane or normal-view).
|
|
// This is vanilla DOM so React's portal target never changes — changing the portal
|
|
// target causes a remount which is exactly what we're trying to avoid.
|
|
useEffect(() => {
|
|
const normalView = normalViewRef.current;
|
|
if (!normalView) return;
|
|
|
|
const tabIds = new Set(tabs.map((t) => t.id));
|
|
|
|
// Remove nodes for closed tabs
|
|
for (const [id, node] of tabNodesRef.current) {
|
|
if (!tabIds.has(id)) {
|
|
node.remove();
|
|
tabNodesRef.current.delete(id);
|
|
}
|
|
}
|
|
|
|
for (const tab of tabs) {
|
|
const isTerminal = tab.type === "terminal";
|
|
const node = getTabNode(tab.id, isTerminal);
|
|
const paneIdx = isSplit ? paneTabIds.indexOf(tab.id) : -1;
|
|
const inPane = paneIdx !== -1;
|
|
const paneEl = inPane ? paneContentEls[paneIdx] : null;
|
|
const activeInline = !inPane && tab.id === activeTabId;
|
|
|
|
if (inPane && paneEl) {
|
|
if (node.parentElement !== paneEl) paneEl.appendChild(node);
|
|
node.style.visibility = "visible";
|
|
node.style.pointerEvents = "auto";
|
|
node.style.display = "";
|
|
node.style.zIndex = "";
|
|
} else {
|
|
if (node.parentElement !== normalView) normalView.appendChild(node);
|
|
if (isTerminal) {
|
|
node.style.display = "";
|
|
node.style.visibility = activeInline ? "visible" : "hidden";
|
|
node.style.pointerEvents = activeInline ? "auto" : "none";
|
|
node.style.zIndex = activeInline ? "1" : "0";
|
|
} else {
|
|
node.style.visibility = "";
|
|
node.style.pointerEvents = "";
|
|
node.style.zIndex = activeInline ? "2" : "";
|
|
node.style.display = activeInline ? "" : "none";
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
const terminalTabs = tabs.filter((t) => t.type === "terminal");
|
|
|
|
// Sidebar panel content — shared between desktop inline sidebar and mobile sheet
|
|
const sidebarPanelContent = (
|
|
<div className="flex flex-col flex-1 min-h-0 overflow-hidden">
|
|
<div
|
|
className={`flex flex-col flex-1 min-h-0 ${railView === "hosts" ? "" : "hidden"}`}
|
|
>
|
|
<HostsPanel
|
|
onOpenTab={(host, type) => {
|
|
connectHost(host, type);
|
|
if (isMobile) setSidebarOpen(false);
|
|
}}
|
|
onEditHost={editHostInManager}
|
|
hostTree={realHostTree ?? undefined}
|
|
loading={hostsLoading}
|
|
onEditingChange={setSidebarEditing}
|
|
active={railView === "hosts"}
|
|
/>
|
|
</div>
|
|
|
|
<div
|
|
className={`flex flex-col flex-1 min-h-0 ${railView === "credentials" ? "" : "hidden"}`}
|
|
>
|
|
<CredentialsPanel
|
|
onEditingChange={setSidebarEditing}
|
|
active={railView === "credentials"}
|
|
/>
|
|
</div>
|
|
|
|
{railView === "quick-connect" && (
|
|
<QuickConnectPanel
|
|
onConnect={(host, type) => {
|
|
openTab(host, type);
|
|
if (isMobile) setSidebarOpen(false);
|
|
}}
|
|
/>
|
|
)}
|
|
|
|
{railView === "ssh-tools" && (
|
|
<div className="flex-1 min-h-0 overflow-y-auto">
|
|
<SshToolsPanel
|
|
terminalTabs={terminalTabs}
|
|
activeTabId={activeTabId}
|
|
/>
|
|
</div>
|
|
)}
|
|
|
|
{railView === "snippets" && (
|
|
<div className="flex-1 min-h-0 overflow-y-auto">
|
|
<SnippetsPanel
|
|
terminalTabs={terminalTabs}
|
|
activeTabId={activeTabId}
|
|
/>
|
|
</div>
|
|
)}
|
|
|
|
{railView === "history" && (
|
|
<div className="flex flex-col flex-1 min-h-0 overflow-y-auto">
|
|
<HistoryPanel terminalTabs={terminalTabs} activeTabId={activeTabId} />
|
|
</div>
|
|
)}
|
|
|
|
{railView === "split-screen" && (
|
|
<div className="flex-1 min-h-0 overflow-y-auto">
|
|
<SplitScreenPanel
|
|
tabs={tabs}
|
|
splitMode={splitMode}
|
|
setSplitMode={setSplitMode}
|
|
paneTabIds={paneTabIds}
|
|
setPaneTabIds={setPaneTabIds}
|
|
onAssignPane={assignPane}
|
|
/>
|
|
</div>
|
|
)}
|
|
|
|
{railView === "connections" && (
|
|
<div className="flex-1 min-h-0 overflow-y-auto">
|
|
<ConnectionsPanel
|
|
tabs={tabs}
|
|
activeTabId={activeTabId}
|
|
allHosts={allHosts}
|
|
backgroundTabRecords={backgroundTabRecords}
|
|
onSwitchToTab={(tabId) => {
|
|
setActiveTabId(tabId);
|
|
if (isMobile) setSidebarOpen(false);
|
|
}}
|
|
onCloseTab={closeTab}
|
|
onReopenTab={(record, restoredSessionId) => {
|
|
const host = record.hostId
|
|
? allHosts.find((h) => h.id === String(record.hostId))
|
|
: undefined;
|
|
const hostlessTypes: TabType[] = ["tunnel"];
|
|
if (!host && !hostlessTypes.includes(record.tabType as TabType))
|
|
return;
|
|
setBackgroundTabRecords((prev) =>
|
|
prev.filter((r) => r.id !== record.id),
|
|
);
|
|
if (host) {
|
|
const effectiveSessionId =
|
|
restoredSessionId ?? record.backendSessionId ?? null;
|
|
openTab(host, record.tabType as TabType, {
|
|
instanceId: record.id,
|
|
restoredSessionId: effectiveSessionId,
|
|
});
|
|
} else {
|
|
openSingletonTab(record.tabType as TabType);
|
|
}
|
|
if (isMobile) setSidebarOpen(false);
|
|
}}
|
|
onForgetBackground={(recordId) => {
|
|
setBackgroundTabRecords((prev) =>
|
|
prev.filter((r) => r.id !== recordId),
|
|
);
|
|
}}
|
|
/>
|
|
</div>
|
|
)}
|
|
|
|
{railView === "user-profile" && (
|
|
<div className="flex-1 min-h-0 overflow-y-auto">
|
|
<UserProfilePanel
|
|
username={username}
|
|
onLogout={onLogout}
|
|
userPrefs={userPrefs}
|
|
onPrefsChange={setUserPrefs}
|
|
/>
|
|
</div>
|
|
)}
|
|
|
|
{railView === "admin-settings" && isAdmin && (
|
|
<div className="flex-1 min-h-0 overflow-y-auto">
|
|
<AdminSettingsPanel />
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
|
|
// Sidebar header — shared
|
|
const sidebarHeader = (
|
|
<div className="flex flex-row items-center border-b border-border h-12.5 shrink-0">
|
|
<span className="flex-1 text-base font-bold tracking-tight text-foreground px-3">
|
|
{sidebarTitle[railView]}
|
|
</span>
|
|
{!isMobile && (
|
|
<>
|
|
<Separator orientation="vertical" />
|
|
<Button
|
|
variant="ghost"
|
|
size="icon"
|
|
className="h-full w-12.5 border-y-0 border-border rounded-none text-muted-foreground hover:text-foreground"
|
|
title="Reset width"
|
|
onClick={() => setSidebarWidth(266)}
|
|
>
|
|
<Maximize2 className="size-3.5" />
|
|
</Button>
|
|
</>
|
|
)}
|
|
<Separator orientation="vertical" />
|
|
<Button
|
|
variant="ghost"
|
|
size="icon"
|
|
className="h-full w-12.5 rounded-none text-muted-foreground hover:text-foreground"
|
|
onClick={() => setSidebarOpen(false)}
|
|
>
|
|
<ChevronLeft className="size-4" />
|
|
</Button>
|
|
</div>
|
|
);
|
|
|
|
return (
|
|
<>
|
|
<div className="flex w-screen bg-background" style={{ height: "100dvh" }}>
|
|
{/* Skinny icon rail — desktop only, hidden on mobile */}
|
|
<AppRail
|
|
railView={railView}
|
|
sidebarOpen={sidebarOpen}
|
|
splitMode={splitMode}
|
|
username={username}
|
|
isAdmin={isAdmin}
|
|
profileDropdownOpen={profileDropdownOpen}
|
|
onProfileDropdownChange={setProfileDropdownOpen}
|
|
onRailClick={handleRailClick}
|
|
onOpenTab={openSingletonTab}
|
|
onLogout={onLogout}
|
|
/>
|
|
|
|
{/* Desktop: inline resizable sidebar */}
|
|
{!isMobile && (
|
|
<div
|
|
className={`relative flex flex-col bg-sidebar shrink-0 overflow-hidden ${sidebarOpen ? `border-r transition-colors ${sidebarDragging ? "border-accent-brand/60" : "border-border"}` : ""}`}
|
|
style={{
|
|
width: sidebarOpen ? (sidebarEditing ? 560 : sidebarWidth) : 0,
|
|
transition: sidebarDragging ? "none" : "width 0.2s",
|
|
}}
|
|
>
|
|
{sidebarHeader}
|
|
{sidebarPanelContent}
|
|
|
|
{sidebarOpen && !sidebarEditing && (
|
|
<div
|
|
onMouseDown={onSidebarMouseDown}
|
|
className={`absolute right-0 top-0 bottom-0 w-1 cursor-col-resize z-30 transition-colors ${sidebarDragging ? "bg-accent-brand/60" : "hover:bg-accent-brand/40"}`}
|
|
/>
|
|
)}
|
|
</div>
|
|
)}
|
|
|
|
{/* Mobile: sidebar as overlay sheet */}
|
|
{isMobile && (
|
|
<Sheet open={sidebarOpen} onOpenChange={setSidebarOpen}>
|
|
<SheetContent
|
|
side="left"
|
|
showCloseButton={false}
|
|
className="p-0 flex flex-col w-[min(85vw,360px)] max-w-full bg-sidebar border-r border-border gap-0"
|
|
style={{ height: "100dvh" }}
|
|
>
|
|
{sidebarHeader}
|
|
{sidebarPanelContent}
|
|
</SheetContent>
|
|
</Sheet>
|
|
)}
|
|
|
|
{/* Main content area */}
|
|
<div
|
|
className={`relative flex flex-col flex-1 min-w-0 overflow-hidden transition-all duration-200 ${!isMobile && !sidebarOpen ? "pl-6" : ""}`}
|
|
>
|
|
{!isMobile && !sidebarOpen && (
|
|
<button
|
|
onClick={() => setSidebarOpen(true)}
|
|
title="Open Sidebar"
|
|
className="absolute left-0 top-0 bottom-0 z-20 flex items-center justify-center w-6 bg-sidebar border-r border-border text-muted-foreground hover:text-accent-brand hover:bg-accent-brand/5 transition-colors"
|
|
>
|
|
<ChevronRight className="size-3.5" />
|
|
</button>
|
|
)}
|
|
<div className="flex flex-col flex-1 min-w-0 min-h-0 overflow-hidden">
|
|
<TabBar
|
|
tabs={tabs}
|
|
activeTabId={activeTabId}
|
|
splitMode={splitMode}
|
|
paneTabIds={paneTabIds}
|
|
focusedPaneIndex={focusedPaneIndex}
|
|
onSetActiveTab={setActiveTabId}
|
|
onCloseTab={closeTab}
|
|
onRefreshTab={refreshTab}
|
|
onReorderTabs={setTabs}
|
|
onSplitTab={splitTabQuick}
|
|
onAddToSplit={addTabToSplit}
|
|
onRemoveFromSplit={removeTabFromSplit}
|
|
/>
|
|
<div className="relative flex flex-col flex-1 min-h-0 overflow-hidden">
|
|
{/* Split view — always mounted when not mobile, hidden via CSS when inactive */}
|
|
{!isMobile && (
|
|
<div
|
|
className="absolute inset-0"
|
|
style={{
|
|
display: isSplit ? "flex" : "none",
|
|
flexDirection: "column",
|
|
}}
|
|
>
|
|
<SplitView
|
|
tabs={tabs}
|
|
paneTabIds={paneTabIds}
|
|
splitMode={splitMode}
|
|
focusedPaneIndex={focusedPaneIndex}
|
|
onTerminalResize={resizeAllTerminals}
|
|
onPaneContentRef={onPaneContentRef}
|
|
onPaneClick={setFocusedPaneIndex}
|
|
onAssignPane={assignPane}
|
|
/>
|
|
</div>
|
|
)}
|
|
|
|
{/* Normal-view container. Tab nodes are appended here (or to pane elements)
|
|
by the DOM-placement effect above. React portals each tab's content
|
|
into its stable per-tab node so the component is never remounted.
|
|
When split is active, shown on top only if the active tab is not in a pane. */}
|
|
<div
|
|
ref={normalViewRef}
|
|
className="absolute inset-0"
|
|
style={{
|
|
display:
|
|
isSplit && !isMobile && paneTabIds.includes(activeTabId)
|
|
? "none"
|
|
: undefined,
|
|
zIndex:
|
|
isSplit && !paneTabIds.includes(activeTabId)
|
|
? 10
|
|
: undefined,
|
|
}}
|
|
>
|
|
{tabs.map((tab) => {
|
|
const tabNode = getTabNode(tab.id, tab.type === "terminal");
|
|
const paneIdx = isSplit ? paneTabIds.indexOf(tab.id) : -1;
|
|
const inPane = paneIdx !== -1;
|
|
const activeInline = !inPane && tab.id === activeTabId;
|
|
return createPortal(
|
|
renderTabContent(
|
|
tab,
|
|
openSingletonTab,
|
|
openTab,
|
|
closeTab,
|
|
inPane || activeInline,
|
|
),
|
|
tabNode,
|
|
tab.id,
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Bottom nav bar — mobile only */}
|
|
<MobileBottomBar
|
|
railView={railView}
|
|
sidebarOpen={sidebarOpen}
|
|
splitMode={splitMode}
|
|
onRailClick={handleRailClick}
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<CommandPalette
|
|
isOpen={commandPaletteOpen}
|
|
setIsOpen={setCommandPaletteOpen}
|
|
hosts={allHosts}
|
|
onOpenTab={(type, label, pendingEvent) => {
|
|
if (
|
|
[
|
|
"dashboard",
|
|
"host-manager",
|
|
"user-profile",
|
|
"admin-settings",
|
|
].includes(type)
|
|
) {
|
|
openSingletonTab(type, pendingEvent);
|
|
} else if (label) {
|
|
const host = allHosts.find((h) => h.name === label);
|
|
if (host) openTab(host, type);
|
|
}
|
|
}}
|
|
/>
|
|
<TransferMonitor />
|
|
</>
|
|
);
|
|
}
|