Files
Netcatty/components/PortForwardingNew.tsx
T
陈大猫andClaude Opus 4.7 92ecd84edf Fix #939: per-host SSH keepalive override + cloud-friendly defaults (#947)
* fix(ssh): per-host keepalive override + cloud-friendly defaults (#939, #581)

Issues #939 (cloud / Aliyun sessions silently freezing after 15-20 min idle
because no SSH keepalive packets are sent) and #581 (older routers like
NOKIA / ALCATEL being killed by ssh2 after a few unanswered keepalives) are
in direct tension at the global-setting level: cloud users want keepalive
ON, embedded-device users want it OFF, and any single global default hurts
the other group.

Resolves the conflict by moving keepalive to a per-host setting (mirroring
the existing `legacyAlgorithms` per-host pattern), with cloud-friendly
global defaults:

Domain:
  - Host gains `keepaliveOverride?: boolean` + `keepaliveInterval?: number`
    + `keepaliveCountMax?: number`. When override is true, the host's
    values are used; otherwise the global TerminalSettings values apply.
    Per-field fallback so a host can override interval only or countMax only.
  - TerminalSettings gains `keepaliveCountMax: number` so the second knob
    (number of unanswered keepalives before declaring dead) is no longer
    hardcoded at 3 in the bridge.
  - DEFAULT_TERMINAL_SETTINGS: keepaliveInterval bumped from 0 to 30, and
    keepaliveCountMax = 10. Cloud LBs / NAT tables stay populated; brief
    network glitches don't trip the dead-connection check; an actually
    dead session is detected within ~5 minutes. Existing users with 0
    saved keep their value (no migration) — they were the #581 router
    cohort and their setup still works untouched.

Plumbing:
  - domain/host.ts adds resolveHostKeepalive(host, globalSettings) with
    five unit tests covering both directions of the override flag and
    per-field fallback.
  - components/terminal/runtime/createTerminalSessionStarters.ts uses the
    resolver when building startSSHSession options.
  - electron/bridges/sshBridge.cjs reads keepaliveCountMax from options
    (defaulting to 10) at both connection sites (direct + jump host) and
    still routes interval=0 through to a fully disabled keepalive
    (preserving #581's escape hatch).

UI:
  - Settings → Terminal → Connection grows a second input next to the
    existing interval: "Max unanswered keepalives".
  - Host details panel gains a Keepalive section with a "Override global
    keepalive" toggle that, when on, exposes per-host interval +
    countMax inputs and an inline hint when interval = 0 (explaining
    the implications). Same visual pattern as the existing Legacy
    Algorithms section.

Sync:
  - keepaliveCountMax added to SYNCABLE_TERMINAL_KEYS so the new global
    field rides existing sync infrastructure. Per-host fields ride the
    hosts array passthrough automatically (older clients receiving them
    ignore unknown fields, per the existing lenient sync contract).

i18n: en + zh-CN strings for the new settings row, the host section
header, and the override toggle / inputs / disabled hint.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ssh): resolve keepalive per jump host, not just the final target

Addresses codex review on PR #947:
  https://github.com/binaricat/Netcatty/pull/947#discussion_r3217027xxx

The first cut only resolved keepalive for the final target host and
forwarded a single interval/countMax pair across the whole start-SSH
call. connectThroughChain in sshBridge.cjs then applied that one pair
to every hop, so a chain like:

   router (bastion, needs keepalive=0)  →  cloud target (needs 30s)

would either kill the router (with cloud-friendly defaults) or fail
to keep the target alive (with router-friendly 0). The per-host
override was effectively useless for bastion hosts.

Fix:
  - NetcattyJumpHost gains optional keepaliveInterval / keepaliveCountMax.
  - createTerminalSessionStarters runs resolveHostKeepalive() per
    jumpHost when building the chain, so each hop carries its own
    resolved pair.
  - sshBridge.cjs's chain connector reads jump.keepaliveInterval /
    jump.keepaliveCountMax for each hop, falling back to the call's
    target-level options for backward compatibility with older
    serializers that don't yet populate the per-hop fields.

The final target's keepalive path is unchanged — it still reads
options.keepaliveInterval / options.keepaliveCountMax that the
session starter resolves from the target host.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ssh): per-host keepalive for SFTP + port forwarding too

Follow-up to the maintainer review on PR #947 — terminal SSH was the
only path that honored per-host keepalive overrides. SFTP and port
forwarding share the same NetcattyJumpHost type but their builders
weren't resolving keepalive per-hop, and their bridges hardcoded the
old 10s/3 defaults. Net result: a router-as-bastion in a chain still
got killed when reached via the SFTP file panel or a port-forwarding
tunnel, even though the user had toggled per-host override.

Plumbing:
  - useSftpHostCredentials / buildSftpHostCredentials: accept optional
    terminalSettings; call resolveHostKeepalive() for the target and
    each jump entry; emit keepaliveInterval / keepaliveCountMax in the
    returned NetcattySSHOptions.
  - useSftpConnections + useSftpState + SftpStateOptions thread the
    setting down. SftpSidePanel passes the global terminalSettings prop
    it already has from TerminalLayer.
  - portForwardingService.startPortForward: accepts terminalSettings
    as an 8th argument, resolves per-host (target + each jump), and
    populates the bridge payload.
  - usePortForwardingState.startTunnel and usePortForwardingAutoStart
    forward the new parameter; App.tsx supplies terminalSettings (via
    a ref in the once-on-launch auto-start effect so changing global
    keepalive later doesn't re-fire it).

Bridges:
  - sftpBridge.cjs target connect: now also reads keepaliveCountMax
    from options (was hardcoded 3). 10s/3 stays as the bridge-level
    fallback to preserve the #669 protection when the renderer hasn't
    supplied a value.
  - sftpBridge.cjs jump hop: reads jump.keepaliveInterval /
    jump.keepaliveCountMax, then falls back to the target-call options
    (matches the symmetric SSH bridge change).
  - portForwardingBridge.cjs: reads keepaliveInterval /
    keepaliveCountMax from the IPC payload; same 10s/3 fallback.

Types:
  - NetcattyJumpHost already grew keepalive fields earlier; this
    commit also adds them to PortForwardOptions so the IPC contract
    is explicit.

End-to-end: a chain `[router-as-bastion, cloud-host]` with the
router host's keepaliveOverride=true / interval=0 now correctly
disables keepalive on the router hop for terminal SSH AND SFTP AND
port forwarding, while the cloud target still gets the resolved
30s/10 default for each path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ssh): honor explicit keepalive=0 in SFTP + port forwarding bridges

Addresses codex review on PR #947:
  - https://github.com/binaricat/Netcatty/pull/947#discussion_r3217448xxx
  - https://github.com/binaricat/Netcatty/pull/947#discussion_r3217449xxx

The previous follow-up commit (5c8bc923) plumbed per-host keepalive
into SFTP / port forwarding but kept the existing bridge-level
"if interval > 0 use it, else 10s" fallback. That collapsed two
semantically distinct inputs:

  - "user explicitly resolved interval = 0" (host with keepaliveOverride
    + interval=0; the whole point of the override)
  - "no value supplied at all" (legacy serializer)

Both ended up as 10s in the bridge, so a router-as-bastion / direct
router connection through SFTP or a port-forward tunnel still got
ssh2-killed after countMax unanswered probes — exactly the case
per-host override was supposed to fix.

Fix: bridges now distinguish on `== null`:
  - positive value → honor it
  - explicit 0 → truly disabled (0 ms, 0 countMax — ssh2 skips its
    dead-connection check entirely on this connection)
  - undefined / null → fall back to 10s/3 (preserves #669 idle-NAT
    protection for older callers that pre-date per-host plumbing)

Applies to both SFTP target connect and SFTP jump hop builders, plus
the port forwarding target builder. Terminal SSH bridge is unchanged
since it already treated 0 as disabled.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ssh): plumb terminalSettings to all remaining keepalive call sites

Addresses codex review on PR #947:
  - PortForwardingNew + TrayPanel were not passing terminalSettings into
    startTunnel, so tunnels started from the main port-forwarding UI or
    from the tray menu silently used the FALLBACK 30/10 instead of the
    user's actual global keepalive settings. Hosts inheriting global
    policy could see different behavior depending on the entry point.
  - SftpView was not threading terminalSettings into useSftpState, so
    SFTP connections opened from the main tab UI also fell back to the
    same hardcoded default and ignored the user's settings.

Wiring:
  - PortForwardingProps gains `terminalSettings`; VaultView accepts it
    on the same prop and forwards from its own new prop; App.tsx
    supplies it from useSettingsState. The startTunnel call site uses
    it directly and includes it in the useCallback dep list so the
    handler updates when settings change.
  - SftpViewProps gains `terminalSettings`; SftpViewMount accepts and
    forwards it; the sftpOptions memo includes it in its dep list.
  - TrayPanelContent gains a `terminalSettings` prop; the TrayPanel
    wrapper (which already calls useSettingsState for uiLanguage)
    passes it down so the standalone tray window agrees with the main
    window's settings.

Also updates the explicit `startTunnel` signature in
UsePortForwardingStateResult so callers see the new 8th parameter
through the hook's return type, not just through the implementation.

Net result: every place that starts an SSH-derived connection
(terminal session, SFTP browse, port-forward tunnel) now consistently
sees the user's configured global keepalive policy and any per-host
overrides; the FALLBACK_KEEPALIVE constants in the service /
credentials builder are now only reached by genuinely-decoupled call
sites (tests, headless usage) rather than masking missing wiring.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ssh): include terminalSettings keepalive fields in memo comparators

Addresses codex review on PR #947 — all three components that grew a
`terminalSettings` prop (SftpView, SftpSidePanel, VaultView) are wrapped
in React.memo with manual equality comparators, and none of those
comparators were updated to include the new prop. React would skip the
re-render when global keepalive changed, so new SFTP / port-forwarding
connections from those subtrees would silently keep using the old
keepalive policy until some other tracked prop happened to flip.

Each comparator now compares the keepalive fields directly rather than
the whole terminalSettings object — only those two fields drive
connection resolution in this subtree, and ignoring the rest avoids
unnecessary re-renders for unrelated terminal-setting changes (fonts,
themes, etc.) that already have their own targeted comparator entries.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 17:22:12 +08:00

942 lines
28 KiB
TypeScript

import {
AlertTriangle,
Check,
ChevronDown,
Globe,
LayoutGrid,
List as ListIcon,
Search,
Server,
Shuffle,
Zap,
} from "lucide-react";
import React, { useCallback, useMemo, useState } from "react";
import { useI18n } from "../application/i18n/I18nProvider";
import { usePortForwardingState } from "../application/state/usePortForwardingState";
import {
GroupConfig,
Host,
ManagedSource,
PortForwardingRule,
PortForwardingType,
ProxyProfile,
SSHKey,
} from "../domain/models";
import { resolveGroupDefaults, applyGroupDefaults } from "../domain/groupConfig";
import { materializeHostProxyProfile } from "../domain/proxyProfiles";
import { cn } from "../lib/utils";
import SelectHostPanel from "./SelectHostPanel";
import {
AsidePanel,
AsidePanelContent,
AsidePanelFooter,
} from "./ui/aside-panel";
import { Button } from "./ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "./ui/dialog";
import { Dropdown, DropdownContent, DropdownTrigger } from "./ui/dropdown";
import { Input } from "./ui/input";
import { SortDropdown } from "./ui/sort-dropdown";
import { toast } from "./ui/toast";
// Import components and utilities from port-forwarding module
import {
EditPanel,
generateRuleLabel as buildRuleLabel,
getTypeMenuLabel,
NewFormPanel,
RuleCard,
WizardContent,
} from "./port-forwarding";
type WizardStep =
| "type"
| "local-config"
| "remote-host-selection"
| "remote-config"
| "destination"
| "host-selection"
| "label";
interface PortForwardingProps {
hosts: Host[];
keys: SSHKey[];
identities?: import('../domain/models').Identity[];
customGroups: string[];
managedSources?: ManagedSource[];
groupConfigs?: GroupConfig[];
proxyProfiles?: ProxyProfile[];
onNewHost?: () => void;
onSaveHost?: (host: Host) => void;
onCreateGroup?: (groupPath: string) => void;
terminalSettings?: { keepaliveInterval: number; keepaliveCountMax: number };
}
const PortForwarding: React.FC<PortForwardingProps> = ({
hosts,
keys,
identities = [],
customGroups: _customGroups,
managedSources = [],
groupConfigs = [],
proxyProfiles = [],
onNewHost: _onNewHost,
onSaveHost,
onCreateGroup: _onCreateGroup,
terminalSettings,
}) => {
const { t } = useI18n();
const {
rules: _rules,
selectedRuleId,
viewMode,
sortMode,
search,
setSelectedRuleId,
setViewMode,
setSortMode,
setSearch,
addRule,
updateRule,
deleteRule,
duplicateRule,
setRuleStatus,
startTunnel,
stopTunnel,
filteredRules,
selectedRule: _selectedRule,
preferFormMode,
setPreferFormMode,
} = usePortForwardingState();
// Track connecting/stopping states
const [pendingOperations, setPendingOperations] = useState<Set<string>>(
new Set(),
);
const proxyProfileIdSet = useMemo(
() => new Set(proxyProfiles.map((profile) => profile.id)),
[proxyProfiles],
);
const resolveEffectiveHost = useCallback(
(host: Host): Host => {
const withGroupDefaults = host.group
? applyGroupDefaults(host, resolveGroupDefaults(host.group, groupConfigs, { validProxyProfileIds: proxyProfileIdSet }), { validProxyProfileIds: proxyProfileIdSet })
: applyGroupDefaults(host, {}, { validProxyProfileIds: proxyProfileIdSet });
return materializeHostProxyProfile(withGroupDefaults, proxyProfiles);
},
[groupConfigs, proxyProfileIdSet, proxyProfiles],
);
// Start a port forwarding tunnel
const handleStartTunnel = useCallback(
async (rule: PortForwardingRule) => {
const _rawHost = hosts.find((h) => h.id === rule.hostId);
if (!_rawHost) {
setRuleStatus(rule.id, "error", t("pf.error.hostNotFound"));
toast.error(
t("pf.error.hostNotFound"),
t("pf.toast.titleWithLabel", { label: rule.label }),
);
return;
}
const _host = resolveEffectiveHost(_rawHost);
const effectiveHosts = hosts.map((host) => resolveEffectiveHost(host));
setPendingOperations((prev) => new Set([...prev, rule.id]));
let errorShown = false;
try {
const result = await startTunnel(
rule,
_host,
effectiveHosts,
keys,
identities,
(status, error) => {
// Show toast on error (only once)
if (status === "error" && error && !errorShown) {
errorShown = true;
toast.error(
error,
t("pf.toast.titleWithLabel", { label: rule.label }),
);
}
},
rule.autoStart, // Enable reconnect for auto-start rules
terminalSettings,
);
// Show error from result only if not already shown
if (!result.success && result.error && !errorShown) {
errorShown = true;
toast.error(
result.error,
t("pf.toast.titleWithLabel", { label: rule.label }),
);
}
} finally {
setPendingOperations((prev) => {
const next = new Set(prev);
next.delete(rule.id);
return next;
});
}
},
[hosts, identities, keys, resolveEffectiveHost, setRuleStatus, startTunnel, t, terminalSettings],
);
// Stop a port forwarding tunnel
const handleStopTunnel = useCallback(
async (rule: PortForwardingRule) => {
setPendingOperations((prev) => new Set([...prev, rule.id]));
try {
await stopTunnel(rule.id);
} finally {
setPendingOperations((prev) => {
const next = new Set(prev);
next.delete(rule.id);
return next;
});
}
},
[stopTunnel],
);
// Wizard state
const [showWizard, setShowWizard] = useState(false);
const [wizardStep, setWizardStep] = useState<WizardStep>("type");
const [wizardType, setWizardType] = useState<PortForwardingType>("local");
const [draftRule, setDraftRule] = useState<Partial<PortForwardingRule>>({
label: "",
type: "local",
localPort: undefined,
bindAddress: "127.0.0.1",
remoteHost: "",
remotePort: undefined,
hostId: undefined,
});
const [isEditing, setIsEditing] = useState(false);
const [showHostSelector, setShowHostSelector] = useState(false);
// Edit panel state (separate from wizard)
const [showEditPanel, setShowEditPanel] = useState(false);
const [editingRule, setEditingRule] = useState<PortForwardingRule | null>(
null,
);
const [editDraft, setEditDraft] = useState<Partial<PortForwardingRule>>({});
// New forwarding form mode (skip wizard, all-in-one form)
const [showNewForm, setShowNewForm] = useState(false);
const [newFormDraft, setNewFormDraft] = useState<Partial<PortForwardingRule>>(
{
label: "",
type: "local",
localPort: undefined,
bindAddress: "127.0.0.1",
remoteHost: "",
remotePort: undefined,
hostId: undefined,
},
);
// New forwarding menu
const [showNewMenu, setShowNewMenu] = useState(false);
// Delete confirmation dialog state for active tunnels
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [ruleToDelete, setRuleToDelete] = useState<PortForwardingRule | null>(null);
const [isDeleting, setIsDeleting] = useState(false);
// Reset wizard
const resetWizard = () => {
setWizardStep("type");
setWizardType("local");
setDraftRule({
label: "",
type: "local",
localPort: undefined,
bindAddress: "127.0.0.1",
remoteHost: "",
remotePort: undefined,
hostId: undefined,
});
setIsEditing(false);
};
// Reset new form
const resetNewForm = () => {
setNewFormDraft({
label: "",
type: "local",
localPort: undefined,
bindAddress: "127.0.0.1",
remoteHost: "",
remotePort: undefined,
hostId: undefined,
});
};
// Start new rule - wizard or form based on user preference
const startNewRule = (type: PortForwardingType) => {
setShowNewMenu(false);
if (preferFormMode) {
// Form mode: show all-in-one form
resetNewForm();
setNewFormDraft((prev) => ({ ...prev, type }));
setShowNewForm(true);
setShowWizard(false);
} else {
// Wizard mode
resetWizard();
setWizardType(type);
setDraftRule((prev) => ({ ...prev, type }));
setShowWizard(true);
setShowNewForm(false);
setWizardStep("type");
}
};
// Skip wizard and switch to form mode
const skipWizardToForm = () => {
// Save preference
setPreferFormMode(true);
// Transfer current draft to form
setNewFormDraft({
...draftRule,
type: wizardType,
});
setShowWizard(false);
setShowNewForm(true);
};
// Open wizard from form
const openWizardFromForm = () => {
// User opens wizard - prefer wizard mode next time
setPreferFormMode(false);
// Transfer current form draft to wizard
setWizardType(newFormDraft.type || "local");
setDraftRule({ ...newFormDraft });
setShowNewForm(false);
setShowWizard(true);
setWizardStep("type");
};
// Save new rule from form
const saveNewFormRule = () => {
const label =
newFormDraft.label?.trim() ||
(() => {
switch (newFormDraft.type) {
case "local":
return `Local:${newFormDraft.localPort} → ${newFormDraft.remoteHost}:${newFormDraft.remotePort}`;
case "remote":
return `Remote:${newFormDraft.localPort} → ${newFormDraft.remoteHost}:${newFormDraft.remotePort}`;
case "dynamic":
return `SOCKS:${newFormDraft.localPort}`;
default:
return "New Rule";
}
})();
addRule({
label,
type: newFormDraft.type || "local",
localPort: newFormDraft.localPort!,
bindAddress: newFormDraft.bindAddress || "127.0.0.1",
remoteHost: newFormDraft.remoteHost,
remotePort: newFormDraft.remotePort,
hostId: newFormDraft.hostId,
});
setShowNewForm(false);
resetNewForm();
};
// Close new form
const closeNewForm = () => {
setShowNewForm(false);
resetNewForm();
};
// Check if new form is valid
const isNewFormValid = (): boolean => {
if (
!newFormDraft.localPort ||
newFormDraft.localPort <= 0 ||
newFormDraft.localPort >= 65536
)
return false;
if (!newFormDraft.hostId) return false;
if (newFormDraft.type !== "dynamic") {
if (!newFormDraft.remoteHost || !newFormDraft.remotePort) return false;
}
return true;
};
// Edit existing rule - open edit panel
const startEditRule = (rule: PortForwardingRule) => {
setEditingRule(rule);
setEditDraft({ ...rule });
setShowEditPanel(true);
setShowWizard(false);
setShowNewForm(false);
};
// Save edited rule
const saveEditedRule = () => {
if (editingRule && editDraft.id) {
updateRule(editDraft.id, editDraft);
setShowEditPanel(false);
setEditingRule(null);
setEditDraft({});
}
};
// Close edit panel
const closeEditPanel = useCallback(() => {
setShowEditPanel(false);
setEditingRule(null);
setEditDraft({});
setSelectedRuleId(null);
}, [setSelectedRuleId]);
// Handle delete with confirmation for active tunnels
const handleDeleteRule = useCallback(
(rule: PortForwardingRule) => {
// If tunnel is active or connecting, show confirmation dialog
if (rule.status === "active" || rule.status === "connecting") {
setRuleToDelete(rule);
setShowDeleteConfirm(true);
} else {
// If inactive, delete directly
if (editingRule?.id === rule.id) {
closeEditPanel();
}
deleteRule(rule.id);
}
},
[editingRule, deleteRule, closeEditPanel],
);
// Confirm delete of active tunnel: stop first, then delete
const confirmDeleteActiveRule = useCallback(async () => {
if (!ruleToDelete) return;
setIsDeleting(true);
try {
// Stop the tunnel first
await stopTunnel(ruleToDelete.id);
// Then delete the rule
if (editingRule?.id === ruleToDelete.id) {
closeEditPanel();
}
deleteRule(ruleToDelete.id);
} finally {
setIsDeleting(false);
setShowDeleteConfirm(false);
setRuleToDelete(null);
}
}, [ruleToDelete, stopTunnel, deleteRule, editingRule, closeEditPanel]);
// Handle wizard navigation
// Flow for local: type -> local-config -> destination -> host-selection
// Flow for remote: type -> remote-host-selection (select host first) -> remote-config (port on remote) -> destination -> label
// Flow for dynamic: type -> local-config -> host-selection
const getNextStep = (): WizardStep | null => {
switch (wizardStep) {
case "type":
if (wizardType === "dynamic") return "local-config";
if (wizardType === "local") return "local-config";
if (wizardType === "remote") return "remote-host-selection";
return null;
case "local-config":
if (wizardType === "dynamic") return "host-selection";
if (wizardType === "local") return "destination";
return null;
case "remote-host-selection":
return "remote-config";
case "remote-config":
return "destination";
case "destination":
if (wizardType === "remote") return "label";
return "host-selection"; // Host selection is last for local
case "host-selection":
return null;
case "label":
return null;
default:
return null;
}
};
const getPrevStep = (): WizardStep | null => {
switch (wizardStep) {
case "type":
return null;
case "local-config":
return "type";
case "remote-host-selection":
return "type";
case "remote-config":
return "remote-host-selection";
case "destination":
if (wizardType === "local") return "local-config";
if (wizardType === "remote") return "remote-config";
return null;
case "host-selection":
if (wizardType === "dynamic") return "local-config";
return "destination";
case "label":
return "destination";
default:
return null;
}
};
const canProceed = (): boolean => {
switch (wizardStep) {
case "type":
// Type step just shows description, always can proceed
return true;
case "local-config":
return !!(
draftRule.localPort &&
draftRule.localPort > 0 &&
draftRule.localPort < 65536
);
case "remote-host-selection":
return !!draftRule.hostId;
case "remote-config":
return !!(
draftRule.localPort &&
draftRule.localPort > 0 &&
draftRule.localPort < 65536
);
case "destination":
return !!(
draftRule.remoteHost &&
draftRule.remotePort &&
draftRule.remotePort > 0
);
case "host-selection":
return !!draftRule.hostId;
case "label":
return true; // Label is optional
default:
return false;
}
};
const isLastStep = (): boolean => {
return getNextStep() === null;
};
// Save rule
const saveRule = () => {
// Generate label if not provided
const label = draftRule.label?.trim() || generateRuleLabel();
if (isEditing && draftRule.id) {
updateRule(draftRule.id, { ...draftRule, label });
} else {
addRule({
label,
type: wizardType,
localPort: draftRule.localPort!,
bindAddress: draftRule.bindAddress || "127.0.0.1",
remoteHost: draftRule.remoteHost,
remotePort: draftRule.remotePort,
hostId: draftRule.hostId,
});
}
setShowWizard(false);
resetWizard();
};
const generateRuleLabel = (): string => {
return buildRuleLabel(
wizardType,
draftRule.localPort,
draftRule.remoteHost,
draftRule.remotePort,
);
};
// Render wizard panel content
const hasRules = filteredRules.length > 0;
return (
<div className="flex h-full relative">
{/* Main Content */}
<div
className={cn(
"flex-1 flex flex-col min-h-0",
showWizard || showEditPanel || showNewForm ? "mr-[360px]" : "",
)}
>
{/* Toolbar */}
<div className="h-14 px-4 py-2 flex items-center gap-3 bg-secondary/80 supports-[backdrop-filter]:backdrop-blur-sm border-b border-border/50 relative z-20">
<Dropdown open={showNewMenu} onOpenChange={setShowNewMenu}>
<DropdownTrigger asChild>
<Button
variant="secondary"
className="h-10 px-3 gap-2 bg-foreground/5 text-foreground hover:bg-foreground/10 border-border/40"
>
<Zap size={14} />
{t("pf.action.newForwarding")}
<ChevronDown
size={14}
className={cn(
"transition-transform",
showNewMenu ? "rotate-180" : "",
)}
/>
</Button>
</DropdownTrigger>
<DropdownContent className="w-max flex flex-col" align="start" sideOffset={8}>
<Button
variant="ghost"
className="justify-start gap-3 h-10 px-3 whitespace-nowrap"
onClick={() => startNewRule("local")}
>
<Globe size={16} className="text-blue-500" />
{getTypeMenuLabel(t, "local")}
</Button>
<Button
variant="ghost"
className="justify-start gap-3 h-10 px-3 whitespace-nowrap"
onClick={() => startNewRule("remote")}
>
<Server size={16} className="text-orange-500" />
{getTypeMenuLabel(t, "remote")}
</Button>
<Button
variant="ghost"
className="justify-start gap-3 h-10 px-3 whitespace-nowrap"
onClick={() => startNewRule("dynamic")}
>
<Shuffle size={16} className="text-purple-500" />
{getTypeMenuLabel(t, "dynamic")}
</Button>
</DropdownContent>
</Dropdown>
<div className="ml-auto flex items-center gap-2">
<div className="relative">
<Search
size={14}
className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"
/>
<Input
placeholder={t("common.searchPlaceholder")}
className="h-10 pl-9 w-44 bg-secondary border-border/60 text-sm"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</div>
{/* View mode toggle */}
<Dropdown>
<DropdownTrigger asChild>
<Button variant="ghost" size="icon" className="h-10 w-10">
{viewMode === "grid" ? (
<LayoutGrid size={16} />
) : (
<ListIcon size={16} />
)}
<ChevronDown size={10} className="ml-0.5" />
</Button>
</DropdownTrigger>
<DropdownContent className="w-32" align="end">
<Button
variant={viewMode === "grid" ? "secondary" : "ghost"}
className="w-full justify-start gap-2 h-9"
onClick={() => setViewMode("grid")}
>
<LayoutGrid size={14} /> {t("pf.view.grid")}
{viewMode === "grid" && (
<Check size={12} className="ml-auto" />
)}
</Button>
<Button
variant={viewMode === "list" ? "secondary" : "ghost"}
className="w-full justify-start gap-2 h-9"
onClick={() => setViewMode("list")}
>
<ListIcon size={14} /> {t("pf.view.list")}
{viewMode === "list" && (
<Check size={12} className="ml-auto" />
)}
</Button>
</DropdownContent>
</Dropdown>
{/* Sort mode toggle */}
<SortDropdown
value={sortMode}
onChange={setSortMode}
className="h-10 w-10"
/>
</div>
</div>
{/* Rules List */}
<div className="flex-1 overflow-auto p-4">
{!hasRules ? (
<div className="flex flex-col items-center justify-center h-full text-muted-foreground">
<div className="h-16 w-16 rounded-2xl bg-secondary/80 flex items-center justify-center mb-4">
<Zap size={32} className="opacity-60" />
</div>
<h3 className="text-lg font-semibold text-foreground mb-2">
{t("pf.empty.title")}
</h3>
<p className="text-sm text-center max-w-sm">
{t("pf.empty.desc")}
</p>
</div>
) : (
<div className="space-y-3">
<div className="flex items-center justify-between">
<h2 className="text-base font-semibold">{t("pf.title")}</h2>
<span className="text-xs text-muted-foreground">
{t("pf.rulesCount", { count: filteredRules.length })}
</span>
</div>
<div
className={cn(
viewMode === "grid"
? "grid gap-3 grid-cols-1 md:grid-cols-2 lg:grid-cols-3"
: "flex flex-col gap-2.5",
)}
>
{filteredRules.map((rule) => (
<RuleCard
key={rule.id}
rule={rule}
host={hosts.find((h) => h.id === rule.hostId)}
viewMode={viewMode}
isSelected={selectedRuleId === rule.id}
isPending={pendingOperations.has(rule.id)}
onSelect={() => {
setSelectedRuleId(rule.id);
startEditRule(rule);
}}
onEdit={() => startEditRule(rule)}
onDuplicate={() => duplicateRule(rule.id)}
onDelete={() => handleDeleteRule(rule)}
onStart={() => handleStartTunnel(rule)}
onStop={() => handleStopTunnel(rule)}
/>
))}
</div>
</div>
)}
</div>
</div>
{/* Edit Panel - shown when a rule is selected */}
{showEditPanel && editingRule && (
<EditPanel
rule={editingRule}
draft={editDraft}
hosts={hosts}
onDraftChange={(updates) =>
setEditDraft((prev) => ({ ...prev, ...updates }))
}
onSave={saveEditedRule}
onClose={closeEditPanel}
onDuplicate={() => {
duplicateRule(editingRule.id);
closeEditPanel();
}}
onDelete={() => handleDeleteRule(editingRule)}
onOpenHostSelector={() => setShowHostSelector(true)}
/>
)}
{/* Wizard Panel */}
{showWizard && (
<AsidePanel
open={true}
onClose={() => {
setShowWizard(false);
resetWizard();
}}
title={isEditing ? t("pf.wizard.editTitle") : t("pf.wizard.newTitle")}
width="w-[360px]"
showBackButton={!!getPrevStep()}
onBack={
getPrevStep()
? () => {
const prev = getPrevStep();
if (prev) setWizardStep(prev);
}
: undefined
}
>
<AsidePanelContent>
<WizardContent
step={wizardStep}
type={wizardType}
draft={draftRule}
hosts={hosts}
onTypeChange={(type) => {
setWizardType(type);
setDraftRule((prev) => ({ ...prev, type }));
}}
onDraftChange={(updates) =>
setDraftRule((prev) => ({ ...prev, ...updates }))
}
onOpenHostSelector={() => setShowHostSelector(true)}
/>
</AsidePanelContent>
<AsidePanelFooter className="space-y-2">
<Button
className="w-full h-10"
disabled={!canProceed()}
onClick={() => {
if (isLastStep()) {
saveRule();
} else {
const next = getNextStep();
if (next) setWizardStep(next);
}
}}
>
{isLastStep()
? isEditing
? t("pf.wizard.saveChanges")
: t("pf.wizard.done")
: t("pf.wizard.continue")}
</Button>
<Button
variant="ghost"
className="w-full h-10 text-muted-foreground hover:text-foreground hover:bg-foreground/5"
onClick={() => {
if (isEditing) {
setShowWizard(false);
resetWizard();
} else {
skipWizardToForm();
}
}}
>
{isEditing ? t("pf.wizard.cancel") : t("pf.wizard.skipWizard")}
</Button>
</AsidePanelFooter>
</AsidePanel>
)}
{/* Host Selector Overlay */}
{showHostSelector && (
<SelectHostPanel
hosts={hosts}
customGroups={_customGroups}
selectedHostIds={
showEditPanel
? editDraft.hostId
? [editDraft.hostId]
: []
: showNewForm
? newFormDraft.hostId
? [newFormDraft.hostId]
: []
: draftRule.hostId
? [draftRule.hostId]
: []
}
multiSelect={false}
onSelect={(host) => {
if (showEditPanel) {
setEditDraft((prev) => ({ ...prev, hostId: host.id }));
} else if (showNewForm) {
setNewFormDraft((prev) => ({ ...prev, hostId: host.id }));
} else {
setDraftRule((prev) => ({ ...prev, hostId: host.id }));
}
setShowHostSelector(false);
}}
onBack={() => setShowHostSelector(false)}
onContinue={() => setShowHostSelector(false)}
availableKeys={keys}
identities={identities}
proxyProfiles={proxyProfiles}
managedSources={managedSources}
onSaveHost={onSaveHost}
onCreateGroup={_onCreateGroup}
/>
)}
{/* New Form Panel (skip wizard mode) */}
{showNewForm && (
<NewFormPanel
draft={newFormDraft}
hosts={hosts}
onDraftChange={(updates) =>
setNewFormDraft((prev) => ({ ...prev, ...updates }))
}
onSave={saveNewFormRule}
onClose={closeNewForm}
onOpenHostSelector={() => setShowHostSelector(true)}
onOpenWizard={openWizardFromForm}
isValid={isNewFormValid()}
/>
)}
{/* Delete Active Tunnel Confirmation Dialog */}
<Dialog open={showDeleteConfirm} onOpenChange={(open) => {
if (!isDeleting) {
setShowDeleteConfirm(open);
if (!open) setRuleToDelete(null);
}
}}>
<DialogContent className="sm:max-w-[400px]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2 text-destructive">
<AlertTriangle size={20} />
{t("pf.deleteActive.title")}
</DialogTitle>
<DialogDescription>
{t("pf.deleteActive.desc", { label: ruleToDelete?.label ?? "" })}
</DialogDescription>
</DialogHeader>
<DialogFooter className="gap-2 sm:gap-0">
<Button
variant="outline"
onClick={() => {
setShowDeleteConfirm(false);
setRuleToDelete(null);
}}
disabled={isDeleting}
>
{t("common.cancel")}
</Button>
<Button
variant="destructive"
onClick={confirmDeleteActiveRule}
disabled={isDeleting}
>
{t("pf.deleteActive.confirm")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
};
export default PortForwarding;