An open source, self-hosted, real-time port monitoring and discovery tool.
Feature/allow service rename (#40)
Mostafa Wahied2d6f8a93813d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 53a1506..6bd70b6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,16 @@All notable changes to Portracker will be documented in this file.+## [1.0.7] - 2025-08-19++### Frontend+- **Service renaming**: Allow renaming services from the UI.+- **Batch actions**: Add selection and batch operations for services and ports (ignore, add note, etc.).+- **Internal / Port display fixes**: Fix display issues so internal and published ports are shown correctly; fix select-box overlap.++### Backend+- **Port protocol reporting**: Ensure ports include protocol information so reported mappings are accurate.+## [1.0.6] - 2025-08-15### Frontenddiff --git a/backend/collectors/docker_collector.js b/backend/collectors/docker_collector.jsindex f1165ca..1eec458 100644--- a/backend/collectors/docker_collector.js+++ b/backend/collectors/docker_collector.js@@ -164,7 +164,7 @@ class DockerCollector extends BaseCollector {const dockerPorts = await this._getDockerContainerPorts();dockerPorts.forEach((port) => {- const key = `${port.host_ip}:${port.host_port}`;+ const key = `${port.host_ip}:${port.host_port}:${port.protocol}`;if (!dockerPortsMap.has(key)) {if (port.container_id) {port.created = containerCreationTimeMap.get(port.container_id) || null;@@ -184,8 +184,8 @@ class DockerCollector extends BaseCollector {if (container.internalPorts && container.internalPorts.length > 0) {container.internalPorts.forEach((internalPort) => {- const publishedKey = `${internalPort.host_ip}:${internalPort.host_port}`;- const internalKey = `${internalPort.host_ip}:${internalPort.host_port}:${container.id}:internal`;+ const publishedKey = `${internalPort.host_ip}:${internalPort.host_port}:${internalPort.protocol}`;+ const internalKey = `${internalPort.host_ip}:${internalPort.host_port}:${internalPort.protocol}:${container.id}:internal`;if (!dockerPortsMap.has(publishedKey) && !dockerPortsMap.has(internalKey)) {internalPort.created = containerCreationTimeMap.get(container.id) || null;@@ -344,7 +344,6 @@ class DockerCollector extends BaseCollector {const containerId = container.ID;const containerName = container.Names;const image = container.Image;-try {const [inspection, pids] = await Promise.all([this.dockerApi.inspectContainer(containerId),@@ -360,7 +359,7 @@ class DockerCollector extends BaseCollector {const [port, protocol] = portDef.split('/');const portNum = parseInt(port, 10);if (!isNaN(portNum)) {- internalPorts.push({+ const internalPort = {source: "docker",owner: containerName,protocol: protocol || "tcp",@@ -370,7 +369,8 @@ class DockerCollector extends BaseCollector {container_id: containerId,app_id: containerName,internal: true- });+ };+ internalPorts.push(internalPort);}});}diff --git a/backend/db.js b/backend/db.jsindex bf7e558..42eebf3 100644--- a/backend/db.js+++ b/backend/db.js@@ -41,9 +41,13 @@ if (!tableExists) {server_id TEXT NOT NULL,host_ip TEXT NOT NULL,host_port INTEGER NOT NULL,+ protocol TEXT NOT NULL DEFAULT 'tcp',+ container_id TEXT,+ internal INTEGER DEFAULT 0,note TEXT NOT NULL,created_at DATETIME DEFAULT CURRENT_TIMESTAMP,- PRIMARY KEY (server_id, host_ip, host_port),+ updated_at DATETIME,+ PRIMARY KEY (server_id, host_ip, host_port, protocol, container_id, internal),FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE CASCADE);`);@@ -66,11 +70,33 @@ if (!tableExists) {server_id TEXT NOT NULL,host_ip TEXT NOT NULL,host_port INTEGER NOT NULL,- PRIMARY KEY (server_id, host_ip, host_port),+ protocol TEXT NOT NULL DEFAULT 'tcp',+ container_id TEXT,+ internal INTEGER DEFAULT 0,+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (server_id, host_ip, host_port, protocol, container_id, internal),FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE CASCADE);`);createIgnoresTable.run();++ const createCustomServiceNamesTable = db.prepare(`+ CREATE TABLE IF NOT EXISTS custom_service_names (+ server_id TEXT NOT NULL,+ host_ip TEXT NOT NULL,+ host_port INTEGER NOT NULL,+ protocol TEXT NOT NULL DEFAULT 'tcp',+ container_id TEXT,+ internal INTEGER DEFAULT 0,+ custom_name TEXT NOT NULL,+ original_name TEXT,+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (server_id, host_ip, host_port, protocol, container_id, internal),+ FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE CASCADE+ );+`);+ createCustomServiceNamesTable.run();} else {try {const notesColumns = db.prepare("PRAGMA table_info(notes)").all();@@ -158,6 +184,296 @@ if (!tableExists) {).run();}}++ const customServiceNamesTableExists = db+ .prepare(+ "SELECT name FROM sqlite_master WHERE type='table' AND name='custom_service_names'"+ )+ .get();++ if (!customServiceNamesTableExists) {+ logger.info('Schema migration: Creating "custom_service_names" table');+ db.exec(`+ CREATE TABLE custom_service_names (+ server_id TEXT NOT NULL,+ host_ip TEXT NOT NULL,+ host_port INTEGER NOT NULL,+ container_id TEXT,+ internal INTEGER DEFAULT 0,+ custom_name TEXT NOT NULL,+ original_name TEXT,+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (server_id, host_ip, host_port, container_id, internal),+ FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE CASCADE+ );+ `);+ } else {+ const customServiceNamesColumns = db.prepare("PRAGMA table_info(custom_service_names)").all();+ if (!customServiceNamesColumns.some((col) => col.name === "container_id")) {+ logger.info('Schema migration: Adding "container_id" column to "custom_service_names" table');++ db.exec(`+ ALTER TABLE custom_service_names ADD COLUMN container_id TEXT;++ CREATE TABLE custom_service_names_new (+ server_id TEXT NOT NULL,+ host_ip TEXT NOT NULL,+ host_port INTEGER NOT NULL,+ container_id TEXT,+ internal INTEGER DEFAULT 0,+ custom_name TEXT NOT NULL,+ original_name TEXT,+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (server_id, host_ip, host_port, container_id, internal),+ FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE CASCADE+ );++ INSERT INTO custom_service_names_new+ SELECT server_id, host_ip, host_port, NULL as container_id, 0 as internal, custom_name, original_name, created_at, updated_at+ FROM custom_service_names;++ DROP TABLE custom_service_names;+ ALTER TABLE custom_service_names_new RENAME TO custom_service_names;+ `);++ logger.info('Schema migration: custom_service_names table updated with container_id and internal support');+ } else if (!customServiceNamesColumns.some((col) => col.name === "internal")) {+ logger.info('Schema migration: Adding "internal" column to "custom_service_names" table');++ db.exec(`+ CREATE TABLE custom_service_names_new (+ server_id TEXT NOT NULL,+ host_ip TEXT NOT NULL,+ host_port INTEGER NOT NULL,+ container_id TEXT,+ internal INTEGER DEFAULT 0,+ custom_name TEXT NOT NULL,+ original_name TEXT,+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (server_id, host_ip, host_port, container_id, internal),+ FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE CASCADE+ );++ INSERT INTO custom_service_names_new+ SELECT server_id, host_ip, host_port, container_id, 0 as internal, custom_name, original_name, created_at, updated_at+ FROM custom_service_names;++ DROP TABLE custom_service_names;+ ALTER TABLE custom_service_names_new RENAME TO custom_service_names;+ `);++ logger.info('Schema migration: custom_service_names table updated with internal support');+ }+ }++ const ignoresTableExists = db+ .prepare(+ "SELECT name FROM sqlite_master WHERE type='table' AND name='ignores'"+ )+ .get();++ if (ignoresTableExists) {+ const ignoresColumns = db.prepare("PRAGMA table_info(ignores)").all();+ if (!ignoresColumns.some((col) => col.name === "container_id")) {+ logger.info('Schema migration: Adding "container_id" column to "ignores" table');++ db.exec(`+ CREATE TABLE ignores_new (+ server_id TEXT NOT NULL,+ host_ip TEXT NOT NULL,+ host_port INTEGER NOT NULL,+ container_id TEXT,+ internal INTEGER DEFAULT 0,+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (server_id, host_ip, host_port, container_id, internal),+ FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE CASCADE+ );++ INSERT INTO ignores_new (server_id, host_ip, host_port, container_id, internal)+ SELECT server_id, host_ip, host_port, NULL as container_id, 0 as internal+ FROM ignores;++ DROP TABLE ignores;+ ALTER TABLE ignores_new RENAME TO ignores;+ `);++ logger.info('Schema migration: ignores table updated with container_id and internal support');+ } else if (!ignoresColumns.some((col) => col.name === "internal")) {+ logger.info('Schema migration: Adding "internal" column to "ignores" table');++ db.exec(`+ CREATE TABLE ignores_new (+ server_id TEXT NOT NULL,+ host_ip TEXT NOT NULL,+ host_port INTEGER NOT NULL,+ container_id TEXT,+ internal INTEGER DEFAULT 0,+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (server_id, host_ip, host_port, container_id, internal),+ FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE CASCADE+ );++ INSERT INTO ignores_new (server_id, host_ip, host_port, container_id, internal)+ SELECT server_id, host_ip, host_port, container_id, 0 as internal+ FROM ignores;++ DROP TABLE ignores;+ ALTER TABLE ignores_new RENAME TO ignores;+ `);++ logger.info('Schema migration: ignores table updated with internal support');+ }+ }++ const notesTableInfo = db.prepare("PRAGMA table_info(notes)").all();+ if (!notesTableInfo.some((col) => col.name === "container_id")) {+ logger.info('Schema migration: Adding "container_id" column to "notes" table');++ db.exec(`+ CREATE TABLE notes_new (+ server_id TEXT NOT NULL,+ host_ip TEXT NOT NULL,+ host_port INTEGER NOT NULL,+ container_id TEXT,+ internal INTEGER DEFAULT 0,+ note TEXT NOT NULL,+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ updated_at DATETIME,+ PRIMARY KEY (server_id, host_ip, host_port, container_id, internal),+ FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE CASCADE+ );++ INSERT INTO notes_new (server_id, host_ip, host_port, container_id, internal, note, created_at, updated_at)+ SELECT server_id, host_ip, host_port, NULL as container_id, 0 as internal, note, created_at, updated_at+ FROM notes;++ DROP TABLE notes;+ ALTER TABLE notes_new RENAME TO notes;+ `);++ logger.info('Schema migration: notes table updated with container_id and internal support');+ } else if (!notesTableInfo.some((col) => col.name === "internal")) {+ logger.info('Schema migration: Adding "internal" column to "notes" table');++ db.exec(`+ CREATE TABLE notes_new (+ server_id TEXT NOT NULL,+ host_ip TEXT NOT NULL,+ host_port INTEGER NOT NULL,+ container_id TEXT,+ internal INTEGER DEFAULT 0,+ note TEXT NOT NULL,+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ updated_at DATETIME,+ PRIMARY KEY (server_id, host_ip, host_port, container_id, internal),+ FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE CASCADE+ );++ INSERT INTO notes_new (server_id, host_ip, host_port, container_id, internal, note, created_at, updated_at)+ SELECT server_id, host_ip, host_port, container_id, 0 as internal, note, created_at, updated_at+ FROM notes;++ DROP TABLE notes;+ ALTER TABLE notes_new RENAME TO notes;+ `);++ logger.info('Schema migration: notes table updated with internal support');+ }++ logger.info('Checking for protocol column migration...');++ const ignoresColumnsForProtocol = db.prepare("PRAGMA table_info(ignores)").all();+ if (!ignoresColumnsForProtocol.some((col) => col.name === "protocol")) {+ logger.info('Schema migration: Adding "protocol" column to "ignores" table');++ db.exec(`+ CREATE TABLE ignores_new (+ server_id TEXT NOT NULL,+ host_ip TEXT NOT NULL,+ host_port INTEGER NOT NULL,+ protocol TEXT NOT NULL DEFAULT 'tcp',+ container_id TEXT,+ internal INTEGER DEFAULT 0,+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (server_id, host_ip, host_port, protocol, container_id, internal),+ FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE CASCADE+ );++ INSERT INTO ignores_new (server_id, host_ip, host_port, protocol, container_id, internal, created_at)+ SELECT server_id, host_ip, host_port, 'tcp' as protocol, container_id, internal, created_at+ FROM ignores;++ DROP TABLE ignores;+ ALTER TABLE ignores_new RENAME TO ignores;+ `);++ logger.info('Schema migration: ignores table updated with protocol support');+ }++ const notesColumnsForProtocol = db.prepare("PRAGMA table_info(notes)").all();+ if (!notesColumnsForProtocol.some((col) => col.name === "protocol")) {+ logger.info('Schema migration: Adding "protocol" column to "notes" table');++ db.exec(`+ CREATE TABLE notes_new (+ server_id TEXT NOT NULL,+ host_ip TEXT NOT NULL,+ host_port INTEGER NOT NULL,+ protocol TEXT NOT NULL DEFAULT 'tcp',+ container_id TEXT,+ internal INTEGER DEFAULT 0,+ note TEXT NOT NULL,+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ updated_at DATETIME,+ PRIMARY KEY (server_id, host_ip, host_port, protocol, container_id, internal),+ FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE CASCADE+ );++ INSERT INTO notes_new (server_id, host_ip, host_port, protocol, container_id, internal, note, created_at, updated_at)+ SELECT server_id, host_ip, host_port, 'tcp' as protocol, container_id, internal, note, created_at, updated_at+ FROM notes;++ DROP TABLE notes;+ ALTER TABLE notes_new RENAME TO notes;+ `);++ logger.info('Schema migration: notes table updated with protocol support');+ }++ const customServiceNamesColumnsForProtocol = db.prepare("PRAGMA table_info(custom_service_names)").all();+ if (!customServiceNamesColumnsForProtocol.some((col) => col.name === "protocol")) {+ logger.info('Schema migration: Adding "protocol" column to "custom_service_names" table');++ db.exec(`+ CREATE TABLE custom_service_names_new (+ server_id TEXT NOT NULL,+ host_ip TEXT NOT NULL,+ host_port INTEGER NOT NULL,+ protocol TEXT NOT NULL DEFAULT 'tcp',+ container_id TEXT,+ internal INTEGER DEFAULT 0,+ custom_name TEXT NOT NULL,+ original_name TEXT,+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (server_id, host_ip, host_port, protocol, container_id, internal),+ FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE CASCADE+ );++ INSERT INTO custom_service_names_new (server_id, host_ip, host_port, protocol, container_id, internal, custom_name, original_name, created_at, updated_at)+ SELECT server_id, host_ip, host_port, 'tcp' as protocol, container_id, internal, custom_name, original_name, created_at, updated_at+ FROM custom_service_names;++ DROP TABLE custom_service_names;+ ALTER TABLE custom_service_names_new RENAME TO custom_service_names;+ `);++ logger.info('Schema migration: custom_service_names table updated with protocol support');+ }+} catch (migrationError) {logger.error("FATAL: Database schema migration failed:",diff --git a/backend/index.js b/backend/index.jsindex 95e5850..8a9ae8a 100644--- a/backend/index.js+++ b/backend/index.js@@ -584,7 +584,7 @@ app.get("/api/ports", async (req, res) => {const normalized = entries.filter((e) => e.host_port && e.host_ip).reduce((acc, entry) => {- const key = `${entry.host_ip}:${entry.host_port}`;+ const key = `${entry.host_ip}:${entry.host_port}:${entry.protocol}`;if (!acc[key]) {acc[key] = {...entry,@@ -731,16 +731,17 @@ app.get("/api/servers/:id/scan", async (req, res) => {if (collectData.ports && Array.isArray(collectData.ports)) {const enrichedPorts = collectData.ports.map((port) => {+ const internalFlag = port.internal ? 1 : 0;const noteEntry = db.prepare(- "SELECT note FROM notes WHERE server_id = 'local' AND host_ip = ? AND host_port = ?"+ "SELECT note FROM notes WHERE server_id = 'local' AND host_ip = ? AND host_port = ? AND protocol = ? AND (container_id = ? OR (container_id IS NULL AND ? IS NULL)) AND internal = ?")- .get(port.host_ip, port.host_port);+ .get(port.host_ip, port.host_port, port.protocol, port.container_id || null, port.container_id || null, internalFlag);const ignoreEntry = db.prepare(- "SELECT 1 FROM ignores WHERE server_id = 'local' AND host_ip = ? AND host_port = ?"+ "SELECT 1 FROM ignores WHERE server_id = 'local' AND host_ip = ? AND host_port = ? AND protocol = ? AND (container_id = ? OR (container_id IS NULL AND ? IS NULL)) AND internal = ?")- .get(port.host_ip, port.host_port);+ .get(port.host_ip, port.host_port, port.protocol, port.container_id || null, port.container_id || null, internalFlag);return {...port,note: noteEntry ? noteEntry.note : null,@@ -800,6 +801,7 @@ app.get("/api/servers/:id/scan", async (req, res) => {}const peerScanData = await peerResponse.json();+logger.debug(`Peer scan complete: ${server.label} (${serverId})`);return res.json(peerScanData);} catch (fetchError) {@@ -898,7 +900,7 @@ function validateServerInput(req, res, next) {}function validateNoteInput(req, res, next) {- const { server_id, host_ip, host_port } = req.body;+ const { server_id, host_ip, host_port, protocol, container_id, internal } = req.body;if (!server_id || typeof server_id !== "string") {return res.status(400)@@ -931,6 +933,33 @@ function validateNoteInput(req, res, next) {field: "host_port",});}+ if (!protocol || typeof protocol !== "string" || (protocol !== "tcp" && protocol !== "udp")) {+ return res+ .status(400)+ .json({+ error: "Validation failed",+ details: "Field 'protocol' is required and must be either 'tcp' or 'udp'",+ field: "protocol",+ });+ }+ if (container_id !== undefined && container_id !== null && (typeof container_id !== "string" || container_id.trim() === "")) {+ return res+ .status(400)+ .json({+ error: "Invalid input for note entry",+ details: "container_id must be a non-empty string when provided",+ field: "container_id",+ });+ }+ if (internal !== undefined && internal !== null && typeof internal !== "boolean") {+ return res+ .status(400)+ .json({+ error: "Invalid input for note entry",+ details: "internal must be a boolean when provided",+ field: "internal",+ });+ }const serverExists = db.prepare("SELECT id FROM servers WHERE id = ?").get(server_id);@@ -969,6 +998,236 @@ function validateServerIdParam(req, res, next) {next();}+/**+ * Middleware that validates input for custom service name operations.+ * Validates server_id, host_ip, host_port, custom_name, and container_id fields.+ */+function validateCustomServiceNameInput(req, res, next) {+ const { server_id, host_ip, host_port, protocol, custom_name, container_id, internal } = req.body;++ if (!server_id || typeof server_id !== "string" || server_id.trim().length === 0) {+ return res+ .status(400)+ .json({+ error: "Validation failed",+ details: "server_id is required and must be a non-empty string",+ field: "server_id",+ });+ }++ if (!host_ip || typeof host_ip !== "string" || host_ip.trim().length === 0) {+ return res+ .status(400)+ .json({+ error: "Validation failed",+ details: "host_ip is required and must be a non-empty string",+ field: "host_ip",+ });+ }++ if (host_port == null || !Number.isInteger(host_port) || host_port <= 0 || host_port > 65535) {+ return res+ .status(400)+ .json({+ error: "Validation failed",+ details: "host_port is required and must be a valid port number (1-65535)",+ field: "host_port",+ });+ }++ if (!protocol || typeof protocol !== "string" || (protocol !== "tcp" && protocol !== "udp")) {+ return res+ .status(400)+ .json({+ error: "Validation failed",+ details: "Field 'protocol' is required and must be either 'tcp' or 'udp'",+ field: "protocol",+ });+ }++ if (custom_name != null && (typeof custom_name !== "string" || custom_name.trim().length === 0)) {+ return res+ .status(400)+ .json({+ error: "Validation failed",+ details: "custom_name must be a non-empty string when provided",+ field: "custom_name",+ });+ }++ if (container_id != null && (typeof container_id !== "string" || container_id.trim().length === 0)) {+ return res+ .status(400)+ .json({+ error: "Validation failed",+ details: "container_id must be a non-empty string when provided",+ field: "container_id",+ });+ }++ if (internal !== undefined && internal !== null && typeof internal !== "boolean") {+ return res+ .status(400)+ .json({+ error: "Validation failed",+ details: "internal must be a boolean when provided",+ field: "internal",+ });+ }++ next();+}++/**+ * Middleware that validates input for ignore operations.+ * Validates server_id, host_ip, host_port, protocol, ignored, and container_id fields.+ */+function validateIgnoreInput(req, res, next) {+ const { server_id, host_ip, host_port, protocol, ignored, container_id, internal } = req.body;++ if (!server_id || typeof server_id !== "string" || server_id.trim().length === 0) {+ return res+ .status(400)+ .json({+ error: "Validation failed",+ details: "server_id is required and must be a non-empty string",+ field: "server_id",+ });+ }++ if (!host_ip || typeof host_ip !== "string" || host_ip.trim().length === 0) {+ return res+ .status(400)+ .json({+ error: "Validation failed",+ details: "host_ip is required and must be a non-empty string",+ field: "host_ip",+ });+ }++ if (host_port == null || !Number.isInteger(host_port) || host_port <= 0 || host_port > 65535) {+ return res+ .status(400)+ .json({+ error: "Validation failed",+ details: "host_port is required and must be a valid port number (1-65535)",+ field: "host_port",+ });+ }++ if (!protocol || typeof protocol !== "string" || (protocol !== "tcp" && protocol !== "udp")) {+ return res+ .status(400)+ .json({+ error: "Validation failed",+ details: "Field 'protocol' is required and must be either 'tcp' or 'udp'",+ field: "protocol",+ });+ }++ if (typeof ignored !== "boolean") {+ return res+ .status(400)+ .json({+ error: "Validation failed",+ details: "ignored is required and must be a boolean",+ field: "ignored",+ });+ }++ if (container_id != null && (typeof container_id !== "string" || container_id.trim().length === 0)) {+ return res+ .status(400)+ .json({+ error: "Validation failed",+ details: "container_id must be a non-empty string when provided",+ field: "container_id",+ });+ }++ if (internal !== undefined && internal !== null && typeof internal !== "boolean") {+ return res+ .status(400)+ .json({+ error: "Validation failed",+ details: "internal must be a boolean when provided",+ field: "internal",+ });+ }++ next();+}++/**+ * Middleware that validates input for custom service name delete operations.+ * Validates server_id, host_ip, host_port, protocol, and container_id fields.+ */+function validateCustomServiceNameDeleteInput(req, res, next) {+ const { server_id, host_ip, host_port, protocol, container_id, internal } = req.body;++ if (!server_id || typeof server_id !== "string" || server_id.trim().length === 0) {+ return res+ .status(400)+ .json({+ error: "Validation failed",+ details: "server_id is required and must be a non-empty string",+ field: "server_id",+ });+ }++ if (!host_ip || typeof host_ip !== "string" || host_ip.trim().length === 0) {+ return res+ .status(400)+ .json({+ error: "Validation failed",+ details: "host_ip is required and must be a non-empty string",+ field: "host_ip",+ });+ }++ if (host_port == null || !Number.isInteger(host_port) || host_port <= 0 || host_port > 65535) {+ return res+ .status(400)+ .json({+ error: "Validation failed",+ details: "host_port is required and must be a valid port number (1-65535)",+ field: "host_port",+ });+ }++ if (!protocol || typeof protocol !== "string" || (protocol !== "tcp" && protocol !== "udp")) {+ return res+ .status(400)+ .json({+ error: "Validation failed",+ details: "Field 'protocol' is required and must be either 'tcp' or 'udp'",+ field: "protocol",+ });+ }++ if (container_id != null && (typeof container_id !== "string" || container_id.trim().length === 0)) {+ return res+ .status(400)+ .json({+ error: "Validation failed",+ details: "container_id must be a non-empty string when provided",+ field: "container_id",+ });+ }++ if (internal !== undefined && internal !== null && typeof internal !== "boolean") {+ return res+ .status(400)+ .json({+ error: "Validation failed",+ details: "internal must be a boolean when provided",+ field: "internal",+ });+ }++ next();+}+app.get("/api/servers", (req, res) => {logger.debug("GET /api/servers");try {@@ -1133,37 +1392,38 @@ app.delete("/api/servers/:id", validateServerIdParam, (req, res) => {});app.post("/api/notes", validateNoteInput, (req, res) => {- const { server_id, host_ip, host_port, note } = req.body;+ const { server_id, host_ip, host_port, protocol, note, container_id, internal } = req.body;const currentDebug = req.query.debug === "true";const noteTrimmed = note ? note.trim() : "";+ const internalFlag = internal ? 1 : 0;if (currentDebug) logger.setDebugEnabled(true);- logger.debug(`POST /api/notes for ${server_id} ${host_ip}:${host_port}. Note: "${noteTrimmed}"`);+ logger.debug(`POST /api/notes for ${server_id} ${host_ip}:${host_port}/${protocol}${container_id ? ` (container: ${container_id})` : ''} (internal: ${internalFlag}). Note: "${noteTrimmed}"`);try {const existing = db.prepare(- "SELECT server_id FROM notes WHERE server_id = ? AND host_ip = ? AND host_port = ?"+ "SELECT server_id FROM notes WHERE server_id = ? AND host_ip = ? AND host_port = ? AND protocol = ? AND (container_id = ? OR (container_id IS NULL AND ? IS NULL)) AND internal = ?")- .get(server_id, host_ip, host_port);+ .get(server_id, host_ip, host_port, protocol, container_id || null, container_id || null, internalFlag);if (existing) {if (noteTrimmed === "") {db.prepare(- "DELETE FROM notes WHERE server_id = ? AND host_ip = ? AND host_port = ?"- ).run(server_id, host_ip, host_port);- logger.info(`Note deleted for ${server_id} ${host_ip}:${host_port}`);+ "DELETE FROM notes WHERE server_id = ? AND host_ip = ? AND host_port = ? AND protocol = ? AND (container_id = ? OR (container_id IS NULL AND ? IS NULL)) AND internal = ?"+ ).run(server_id, host_ip, host_port, protocol, container_id || null, container_id || null, internalFlag);+ logger.info(`Note deleted for ${server_id} ${host_ip}:${host_port}/${protocol}${container_id ? ` (container: ${container_id})` : ''} (internal: ${internalFlag})`);} else {db.prepare(- "UPDATE notes SET note = ?, updated_at = datetime('now') WHERE server_id = ? AND host_ip = ? AND host_port = ?"- ).run(noteTrimmed, server_id, host_ip, host_port);- logger.info(`Note updated for ${server_id} ${host_ip}:${host_port}`);+ "UPDATE notes SET note = ?, updated_at = datetime('now') WHERE server_id = ? AND host_ip = ? AND host_port = ? AND protocol = ? AND (container_id = ? OR (container_id IS NULL AND ? IS NULL)) AND internal = ?"+ ).run(noteTrimmed, server_id, host_ip, host_port, protocol, container_id || null, container_id || null, internalFlag);+ logger.info(`Note updated for ${server_id} ${host_ip}:${host_port}/${protocol}${container_id ? ` (container: ${container_id})` : ''} (internal: ${internalFlag})`);}} else if (noteTrimmed !== "") {db.prepare(- "INSERT INTO notes (server_id, host_ip, host_port, note) VALUES (?, ?, ?, ?)"- ).run(server_id, host_ip, host_port, noteTrimmed);- logger.info(`Note created for ${server_id} ${host_ip}:${host_port}`);+ "INSERT INTO notes (server_id, host_ip, host_port, protocol, container_id, internal, note) VALUES (?, ?, ?, ?, ?, ?, ?)"+ ).run(server_id, host_ip, host_port, protocol, container_id || null, internalFlag, noteTrimmed);+ logger.info(`Note created for ${server_id} ${host_ip}:${host_port}/${protocol}${container_id ? ` (container: ${container_id})` : ''} (internal: ${internalFlag})`);}res.status(200).json({ success: true, message: "Note saved successfully" });} catch (err) {@@ -1196,7 +1456,7 @@ app.get("/api/notes", (req, res) => {try {const notes = db- .prepare("SELECT host_ip, host_port, note FROM notes WHERE server_id = ?")+ .prepare("SELECT host_ip, host_port, protocol, container_id, internal, note FROM notes WHERE server_id = ?").all(server_id);res.json(notes);} catch (err) {@@ -1213,51 +1473,39 @@ app.get("/api/notes", (req, res) => {}});-app.post("/api/ignores", (req, res) => {- const { server_id, host_ip, host_port, ignored } = req.body;+app.post("/api/ignores", validateIgnoreInput, (req, res) => {+ const { server_id, host_ip, host_port, protocol, ignored, container_id, internal } = req.body;const currentDebug = req.query.debug === "true";if (currentDebug) logger.setDebugEnabled(true);- logger.debug(`POST /api/ignores for ${server_id} ${host_ip}:${host_port}. Ignored: ${ignored}`);-- if (- !server_id ||- typeof server_id !== "string" ||- !host_ip ||- typeof host_ip !== "string" ||- host_port === undefined ||- host_port === null ||- !Number.isInteger(Number(host_port)) ||- typeof ignored !== "boolean"- ) {- return res.status(400).json({ error: "Invalid input for ignore entry" });- }+ const internalFlag = internal ? 1 : 0;+ logger.debug(`POST /api/ignores for ${server_id} ${host_ip}:${host_port}/${protocol}${container_id ? ` (container: ${container_id})` : ''} (internal: ${internalFlag}). Ignored: ${ignored}`);try {const existing = db.prepare(- "SELECT server_id FROM ignores WHERE server_id = ? AND host_ip = ? AND host_port = ?"+ "SELECT server_id FROM ignores WHERE server_id = ? AND host_ip = ? AND host_port = ? AND protocol = ? AND (container_id = ? OR (container_id IS NULL AND ? IS NULL)) AND internal = ?")- .get(server_id, host_ip, host_port);+ .get(server_id, host_ip, host_port, protocol, container_id || null, container_id || null, internalFlag);if (ignored) {if (!existing) {db.prepare(- "INSERT INTO ignores (server_id, host_ip, host_port) VALUES (?, ?, ?)"- ).run(server_id, host_ip, host_port);- logger.info(`Port ignored for ${server_id} ${host_ip}:${host_port}`);+ "INSERT INTO ignores (server_id, host_ip, host_port, protocol, container_id, internal) VALUES (?, ?, ?, ?, ?, ?)"+ ).run(server_id, host_ip, host_port, protocol, container_id || null, internalFlag);+ logger.info(`Port ignored for ${server_id} ${host_ip}:${host_port}/${protocol}${container_id ? ` (container: ${container_id})` : ''} (internal: ${internalFlag})`);} else {- logger.debug(`Port already ignored for ${server_id} ${host_ip}:${host_port}, no change.`);+ logger.debug(`Port already ignored for ${server_id} ${host_ip}:${host_port}/${protocol}${container_id ? ` (container: ${container_id})` : ''} (internal: ${internalFlag}), no change.`);}} else {if (existing) {db.prepare(- "DELETE FROM ignores WHERE server_id = ? AND host_ip = ? AND host_port = ?"- ).run(server_id, host_ip, host_port);- logger.info(`Port un-ignored for ${server_id} ${host_ip}:${host_port}`);+ "DELETE FROM ignores WHERE server_id = ? AND host_ip = ? AND host_port = ? AND protocol = ? AND (container_id = ? OR (container_id IS NULL AND ? IS NULL)) AND internal = ?"+ ).run(server_id, host_ip, host_port, protocol, container_id || null, container_id || null, internalFlag);+ logger.info(`Port un-ignored for ${server_id} ${host_ip}:${host_port}/${protocol}${container_id ? ` (container: ${container_id})` : ''} (internal: ${internalFlag})`);} else {- logger.debug(`Port already not ignored for ${server_id} ${host_ip}:${host_port}, no change.`);+ logger.debug(`Port already not ignored for ${server_id} ${host_ip}:${host_port}/${protocol}${container_id ? ` (container: ${container_id})` : ''} (internal: ${internalFlag}), no change.`);}}res.status(200).json({ success: true, message: "Ignore status updated" });@@ -1291,7 +1539,7 @@ app.get("/api/ignores", (req, res) => {try {const ignores = db- .prepare("SELECT host_ip, host_port FROM ignores WHERE server_id = ?")+ .prepare("SELECT host_ip, host_port, protocol, container_id, internal FROM ignores WHERE server_id = ?").all(server_id);res.json(ignores.map((item) => ({ ...item, ignored: true })));} catch (err) {@@ -1309,6 +1557,413 @@ app.get("/api/ignores", (req, res) => {}});+app.post("/api/custom-service-names", validateCustomServiceNameInput, (req, res) => {+ const { server_id, host_ip, host_port, protocol, custom_name, original_name, container_id, internal } = req.body;+ const currentDebug = req.query.debug === "true";++ if (currentDebug) logger.setDebugEnabled(true);++ const internalFlag = internal ? 1 : 0;+ logger.debug(`POST /api/custom-service-names for ${server_id} ${host_ip}:${host_port}/${protocol}${container_id ? ` (container: ${container_id})` : ''} (internal: ${internalFlag}). Custom name: "${custom_name}"`);++ try {+ const existing = db+ .prepare(+ "SELECT server_id FROM custom_service_names WHERE server_id = ? AND host_ip = ? AND host_port = ? AND protocol = ? AND (container_id = ? OR (container_id IS NULL AND ? IS NULL)) AND internal = ?"+ )+ .get(server_id, host_ip, host_port, protocol, container_id || null, container_id || null, internalFlag);++ if (existing) {+ db.prepare(+ "UPDATE custom_service_names SET custom_name = ?, original_name = ?, updated_at = datetime('now') WHERE server_id = ? AND host_ip = ? AND host_port = ? AND protocol = ? AND (container_id = ? OR (container_id IS NULL AND ? IS NULL)) AND internal = ?"+ ).run(custom_name, original_name || null, server_id, host_ip, host_port, protocol, container_id || null, container_id || null, internalFlag);+ logger.info(`Custom service name updated for ${server_id} ${host_ip}:${host_port}/${protocol}${container_id ? ` (container: ${container_id})` : ''} (internal: ${internalFlag})`);+ } else {+ db.prepare(+ "INSERT INTO custom_service_names (server_id, host_ip, host_port, protocol, container_id, internal, custom_name, original_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"+ ).run(server_id, host_ip, host_port, protocol, container_id || null, internalFlag, custom_name, original_name || null);+ logger.info(`Custom service name created for ${server_id} ${host_ip}:${host_port}/${protocol}${container_id ? ` (container: ${container_id})` : ''} (internal: ${internalFlag})`);+ }++ if (!container_id && !internal && host_ip === "0.0.0.0") {+ const ipv6Existing = db+ .prepare(+ "SELECT server_id FROM custom_service_names WHERE server_id = ? AND host_ip = '::' AND host_port = ? AND protocol = ? AND container_id IS NULL AND internal = 0"+ )+ .get(server_id, host_port, protocol);++ if (ipv6Existing) {+ db.prepare(+ "UPDATE custom_service_names SET custom_name = ?, original_name = ?, updated_at = datetime('now') WHERE server_id = ? AND host_ip = '::' AND host_port = ? AND protocol = ? AND container_id IS NULL AND internal = 0"+ ).run(custom_name, original_name || null, server_id, host_port, protocol);+ logger.info(`Custom service name updated for ${server_id} [::]:${host_port}/${protocol} (IPv6 variant)`);+ } else {+ try {+ db.prepare(+ "INSERT INTO custom_service_names (server_id, host_ip, host_port, protocol, container_id, internal, custom_name, original_name) VALUES (?, '::', ?, ?, ?, ?, ?, ?)"+ ).run(server_id, host_port, protocol, null, 0, custom_name, original_name || null);+ logger.info(`Custom service name created for ${server_id} [::]:${host_port}/${protocol} (IPv6 variant)`);+ } catch (insertError) {+ logger.debug(`Could not create IPv6 variant for ${server_id} [::]:${host_port}/${protocol}: ${insertError.message}`);+ }+ }+ } else if (!container_id && !internal && host_ip === "::") {+ const ipv4Existing = db+ .prepare(+ "SELECT server_id FROM custom_service_names WHERE server_id = ? AND host_ip = '0.0.0.0' AND host_port = ? AND protocol = ? AND container_id IS NULL AND internal = 0"+ )+ .get(server_id, host_port, protocol);++ if (ipv4Existing) {+ db.prepare(+ "UPDATE custom_service_names SET custom_name = ?, original_name = ?, updated_at = datetime('now') WHERE server_id = ? AND host_ip = '0.0.0.0' AND host_port = ? AND protocol = ? AND container_id IS NULL AND internal = 0"+ ).run(custom_name, original_name || null, server_id, host_port, protocol);+ logger.info(`Custom service name updated for ${server_id} 0.0.0.0:${host_port}/${protocol} (IPv4 variant)`);+ } else {+ try {+ db.prepare(+ "INSERT INTO custom_service_names (server_id, host_ip, host_port, protocol, container_id, internal, custom_name, original_name) VALUES (?, '0.0.0.0', ?, ?, ?, ?, ?, ?)"+ ).run(server_id, host_port, protocol, null, 0, custom_name, original_name || null);+ logger.info(`Custom service name created for ${server_id} 0.0.0.0:${host_port}/${protocol} (IPv4 variant)`);+ } catch (insertError) {+ logger.debug(`Could not create IPv4 variant for ${server_id} 0.0.0.0:${host_port}/${protocol}: ${insertError.message}`);+ }+ }+ }++ responseCache.delete('endpoint:ports:local');++ res.status(200).json({ success: true, message: "Custom service name saved successfully" });+ } catch (err) {+ logger.error(`Database error in POST /api/custom-service-names: ${err.message}`);+ logger.debug("Stack trace:", err.stack || "");+ res+ .status(500)+ .json({+ error: "Database operation failed",+ details: "Unable to save custom service name",+ });+ } finally {+ if (currentDebug) logger.setDebugEnabled(process.env.DEBUG === 'true');+ }+});++app.get("/api/custom-service-names", (req, res) => {+ const { server_id } = req.query;+ const currentDebug = req.query.debug === "true";++ if (currentDebug) logger.setDebugEnabled(true);++ logger.debug(`GET /api/custom-service-names for server_id: ${server_id}`);++ if (!server_id) {+ return res+ .status(400)+ .json({ error: "server_id query parameter is required" });+ }++ try {+ const customNames = db+ .prepare("SELECT host_ip, host_port, protocol, container_id, internal, custom_name, original_name FROM custom_service_names WHERE server_id = ?")+ .all(server_id);+ res.json(customNames);+ } catch (err) {+ logger.error(`Database error in GET /api/custom-service-names: ${err.message}`);+ logger.debug("Stack trace:", err.stack || "");+ res+ .status(500)+ .json({+ error: "Database operation failed",+ details: "Unable to retrieve custom service names",+ });+ } finally {+ if (currentDebug) logger.setDebugEnabled(process.env.DEBUG === 'true');+ }+});++app.delete("/api/custom-service-names", validateCustomServiceNameDeleteInput, (req, res) => {+ const { server_id, host_ip, host_port, protocol, container_id, internal } = req.body;+ const currentDebug = req.query.debug === "true";++ if (currentDebug) logger.setDebugEnabled(true);++ const internalFlag = internal ? 1 : 0;+ logger.debug(`DELETE /api/custom-service-names for ${server_id} ${host_ip}:${host_port}/${protocol}${container_id ? ` (container: ${container_id})` : ''} (internal: ${internalFlag})`);++ try {+ const result = db+ .prepare("DELETE FROM custom_service_names WHERE server_id = ? AND host_ip = ? AND host_port = ? AND protocol = ? AND (container_id = ? OR (container_id IS NULL AND ? IS NULL)) AND internal = ?")+ .run(server_id, host_ip, host_port, protocol, container_id || null, container_id || null, internalFlag);++ let deletedCount = result.changes;++ /**+ * If no rows were deleted and we have a container_id, try deleting without container_id+ * This handles legacy records that were created before container_id support+ */+ if (deletedCount === 0 && container_id) {+ const legacyResult = db+ .prepare("DELETE FROM custom_service_names WHERE server_id = ? AND host_ip = ? AND host_port = ? AND protocol = ? AND container_id IS NULL AND internal = ?")+ .run(server_id, host_ip, host_port, protocol, internalFlag);+ deletedCount += legacyResult.changes;+ if (legacyResult.changes > 0) {+ logger.info(`Custom service name deleted for ${server_id} ${host_ip}:${host_port}/${protocol} (legacy record without container_id)`);+ }+ }++ if (!container_id && !internal && host_ip === "0.0.0.0") {+ const ipv6Result = db+ .prepare("DELETE FROM custom_service_names WHERE server_id = ? AND host_ip = '::' AND host_port = ? AND protocol = ? AND container_id IS NULL AND internal = 0")+ .run(server_id, host_port, protocol);+ deletedCount += ipv6Result.changes;+ if (ipv6Result.changes > 0) {+ logger.info(`Custom service name deleted for ${server_id} [::]:${host_port}/${protocol} (IPv6 variant)`);+ }+ } else if (!container_id && !internal && host_ip === "::") {+ const ipv4Result = db+ .prepare("DELETE FROM custom_service_names WHERE server_id = ? AND host_ip = '0.0.0.0' AND host_port = ? AND protocol = ? AND container_id IS NULL AND internal = 0")+ .run(server_id, host_port, protocol);+ deletedCount += ipv4Result.changes;+ if (ipv4Result.changes > 0) {+ logger.info(`Custom service name deleted for ${server_id} 0.0.0.0:${host_port}/${protocol} (IPv4 variant)`);+ }+ }++ if (deletedCount > 0) {+ logger.info(`Custom service name deleted for ${server_id} ${host_ip}:${host_port}/${protocol}${container_id ? ` (container: ${container_id})` : ''}`);++ responseCache.delete('endpoint:ports:local');++ res.status(200).json({ success: true, message: "Custom service name deleted successfully" });+ } else {+ res.status(404).json({ error: "Custom service name not found" });+ }+ } catch (err) {+ logger.error(`Database error in DELETE /api/custom-service-names: ${err.message}`);+ logger.debug("Stack trace:", err.stack || "");+ res+ .status(500)+ .json({+ error: "Database operation failed",+ details: "Unable to delete custom service name",+ });+ } finally {+ if (currentDebug) logger.setDebugEnabled(process.env.DEBUG === 'true');+ }+});++app.post("/api/custom-service-names/batch", (req, res) => {+ const { server_id, operations } = req.body;+ const currentDebug = req.query.debug === "true";++ if (currentDebug) logger.setDebugEnabled(true);++ logger.debug(`POST /api/custom-service-names/batch for ${server_id}. Operations: ${operations?.length || 0}`);++ if (!server_id || typeof server_id !== "string" || server_id.trim().length === 0) {+ return res+ .status(400)+ .json({ error: "server_id is required and must be a non-empty string" });+ }++ if (!operations || !Array.isArray(operations) || operations.length === 0) {+ return res+ .status(400)+ .json({ error: "operations array is required and must not be empty" });+ }++ for (let i = 0; i < operations.length; i++) {+ const op = operations[i];+ if (!op || typeof op !== "object") {+ return res+ .status(400)+ .json({ error: `Operation at index ${i} must be an object` });+ }++ const { action, host_ip, host_port, protocol, custom_name, container_id, internal } = op;++ if (!["set", "delete"].includes(action)) {+ return res+ .status(400)+ .json({ error: `Operation at index ${i}: action must be "set" or "delete"` });+ }++ if (!host_ip || typeof host_ip !== "string" || host_ip.trim().length === 0) {+ return res+ .status(400)+ .json({ error: `Operation at index ${i}: host_ip is required and must be a non-empty string` });+ }++ if (host_port == null || !Number.isInteger(host_port) || host_port <= 0 || host_port > 65535) {+ return res+ .status(400)+ .json({ error: `Operation at index ${i}: host_port must be a valid port number (1-65535)` });+ }++ if (!protocol || typeof protocol !== "string" || (protocol !== "tcp" && protocol !== "udp")) {+ return res+ .status(400)+ .json({ error: `Operation at index ${i}: protocol is required and must be either 'tcp' or 'udp'` });+ }++ if (action === "set" && (custom_name == null || typeof custom_name !== "string" || custom_name.trim().length === 0)) {+ return res+ .status(400)+ .json({ error: `Operation at index ${i}: custom_name is required for "set" action` });+ }++ if (container_id != null && (typeof container_id !== "string" || container_id.trim().length === 0)) {+ return res+ .status(400)+ .json({ error: `Operation at index ${i}: container_id must be a non-empty string when provided` });+ }++ if (internal !== undefined && internal !== null && typeof internal !== "boolean") {+ return res+ .status(400)+ .json({ error: `Operation at index ${i}: internal must be a boolean when provided` });+ }+ }++ try {+ const results = [];++ for (const op of operations) {+ const { action, host_ip, host_port, protocol, custom_name, original_name, container_id, internal } = op;++ if (action === "set") {+ const existing = db+ .prepare(+ "SELECT server_id FROM custom_service_names WHERE server_id = ? AND host_ip = ? AND host_port = ? AND protocol = ? AND (container_id = ? OR (container_id IS NULL AND ? IS NULL)) AND internal = ?"+ )+ .get(server_id, host_ip, host_port, protocol, container_id || null, container_id || null, internal ? 1 : 0);++ if (existing) {+ db.prepare(+ "UPDATE custom_service_names SET custom_name = ?, original_name = ?, updated_at = datetime('now') WHERE server_id = ? AND host_ip = ? AND host_port = ? AND protocol = ? AND (container_id = ? OR (container_id IS NULL AND ? IS NULL)) AND internal = ?"+ ).run(custom_name, original_name || null, server_id, host_ip, host_port, protocol, container_id || null, container_id || null, internal ? 1 : 0);+ results.push({ host_ip, host_port, protocol, container_id, action: "updated" });+ } else {+ db.prepare(+ "INSERT INTO custom_service_names (server_id, host_ip, host_port, protocol, container_id, internal, custom_name, original_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"+ ).run(server_id, host_ip, host_port, protocol, container_id || null, internal ? 1 : 0, custom_name, original_name || null);+ results.push({ host_ip, host_port, protocol, container_id, action: "created" });+ }+ } else if (action === "delete") {+ const result = db+ .prepare("DELETE FROM custom_service_names WHERE server_id = ? AND host_ip = ? AND host_port = ? AND protocol = ? AND (container_id = ? OR (container_id IS NULL AND ? IS NULL)) AND internal = ?")+ .run(server_id, host_ip, host_port, protocol, container_id || null, container_id || null, internal ? 1 : 0);++ results.push({+ host_ip,+ host_port,+ protocol,+ container_id,+ action: result.changes > 0 ? "deleted" : "not_found"+ });+ }+ }++ logger.info(`Batch custom service name operation completed for ${server_id}. ${results.length} operations processed.`);++ responseCache.delete('endpoint:ports:local');++ res.status(200).json({ success: true, results });+ } catch (err) {+ logger.error(`Database error in POST /api/custom-service-names/batch: ${err.message}`);+ logger.debug("Stack trace:", err.stack || "");+ res+ .status(500)+ .json({+ error: "Database operation failed",+ details: "Unable to process batch custom service name operations",+ });+ } finally {+ if (currentDebug) logger.setDebugEnabled(process.env.DEBUG === 'true');+ }+});++app.post("/api/notes/batch", (req, res) => {+ const { server_id, operations } = req.body;+ const currentDebug = req.query.debug === "true";++ if (currentDebug) logger.setDebugEnabled(true);++ logger.debug(`POST /api/notes/batch for ${server_id}. Operations: ${operations?.length || 0}`);++ if (!server_id || !Array.isArray(operations)) {+ return res.status(400).json({ error: "server_id and operations array are required" });+ }++ try {+ const results = [];++ for (const operation of operations) {+ const { action, host_ip, host_port, protocol, note, container_id, internal } = operation;++ if (!action || !host_ip || host_port == null) {+ results.push({ success: false, error: "Missing required fields: action, host_ip, host_port" });+ continue;+ }++ if (!Number.isInteger(host_port) || host_port <= 0 || host_port > 65535) {+ results.push({ success: false, error: "host_port must be a valid port number (1-65535)" });+ continue;+ }++ if (!protocol || typeof protocol !== "string" || (protocol !== "tcp" && protocol !== "udp")) {+ results.push({ success: false, error: "protocol is required and must be either 'tcp' or 'udp'" });+ continue;+ }++ const internalFlag = internal ? 1 : 0;++ try {+ if (action === "set" && note) {+ const noteTrimmed = note.trim();+ if (noteTrimmed) {+ const existingNote = db+ .prepare("SELECT server_id FROM notes WHERE server_id = ? AND host_ip = ? AND host_port = ? AND protocol = ? AND (container_id = ? OR (container_id IS NULL AND ? IS NULL)) AND internal = ?")+ .get(server_id, host_ip, host_port, protocol, container_id || null, container_id || null, internalFlag);++ if (existingNote) {+ db.prepare("UPDATE notes SET note = ?, updated_at = CURRENT_TIMESTAMP WHERE server_id = ? AND host_ip = ? AND host_port = ? AND protocol = ? AND (container_id = ? OR (container_id IS NULL AND ? IS NULL)) AND internal = ?")+ .run(noteTrimmed, server_id, host_ip, host_port, protocol, container_id || null, container_id || null, internalFlag);+ } else {+ db.prepare("INSERT INTO notes (server_id, host_ip, host_port, protocol, container_id, internal, note, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)")+ .run(server_id, host_ip, host_port, protocol, container_id || null, internalFlag, noteTrimmed);+ }+ results.push({ success: true, action: "set", host_ip, host_port, container_id, internal: internalFlag });+ }+ } else if (action === "delete") {+ const result = db+ .prepare("DELETE FROM notes WHERE server_id = ? AND host_ip = ? AND host_port = ? AND protocol = ? AND (container_id = ? OR (container_id IS NULL AND ? IS NULL)) AND internal = ?")+ .run(server_id, host_ip, host_port, protocol, container_id || null, container_id || null, internalFlag);+ results.push({ success: true, action: "delete", host_ip, host_port, container_id, internal: internalFlag, deletedCount: result.changes });+ }+ } catch (opError) {+ logger.error(`Error in batch note operation: ${opError.message}`);+ results.push({ success: false, error: opError.message, host_ip, host_port, container_id });+ }+ }++ responseCache.delete('endpoint:ports:local');++ logger.info(`Batch note operation completed for ${server_id}. ${results.length} operations processed.`);+ res.status(200).json({ success: true, results });++ } catch (err) {+ logger.error(`Database error in POST /api/notes/batch: ${err.message}`);+ logger.debug("Stack trace:", err.stack || "");+ res.status(500).json({+ error: "Database operation failed",+ details: "Unable to process batch note operations",+ });+ } finally {+ if (currentDebug) logger.setDebugEnabled(process.env.DEBUG === 'true');+ }+});+app.get("/api/ping", async (req, res) => {const { host_ip, host_port, target_server_url, owner, internal, container_id } = req.query;const serverId = req.query.server_id;diff --git a/eslint.config.cjs b/eslint.config.cjsindex aabb605..cfde90b 100644--- a/eslint.config.cjs+++ b/eslint.config.cjs@@ -1,6 +1,3 @@-// Root ESLint flat config – single place to manage all rules (backend + frontend)-// Minimal, self-contained, and includes inline logging policy rules.-const js = require('@eslint/js');const globals = require('globals');let reactHooks;@@ -8,20 +5,16 @@ try { reactHooks = require('eslint-plugin-react-hooks'); } catch { reactHooks =let reactPlugin;try { reactPlugin = require('eslint-plugin-react'); } catch { reactPlugin = null; }-// Inline custom plugins-// 1) `logs` – logging hygiene-// 2) `codebase` – repo-wide style rules (comments, etc.)const logsPlugin = {rules: {- // Disallow any line comments beginning with // (except whitelisted directives)'no-line-comments': {meta: { type: 'problem', docs: { description: 'Disallow // line comments; use block comments or remove' } },create(context) {const allowList = [- /^eslint[- ]/i, // eslint directives- /^ts[- ]/i, // ts-ignore/expect-error (if present in mixed envs)+ /^eslint[- ]/i,+ /^ts[- ]/i,/^istanbul ignore/i,- /^region\b/i, // region markers if used+ /^region\b/i,/^endregion\b/i,];return {@@ -44,12 +37,10 @@ const logsPlugin = {};},},- // Disallow emojis in any logger.* arguments'no-emoji-in-logs': {meta: { type: 'problem', docs: { description: 'Disallow emojis in log messages' } },create(context) {- // Use Extended_Pictographic to avoid false positives from variation selectors/ZWJ- const EMOJI_RE = /\p{Extended_Pictographic}/u;+ const EMOJI_RE = /\p{Extended_Pictographic}/u;function hasEmoji(node) {if (!node) return false;if (node.type === 'Literal' && typeof node.value === 'string') return EMOJI_RE.test(node.value);@@ -77,8 +68,7 @@ const logsPlugin = {},},- // Disallow gating info/warn behind debug checks- 'no-debug-gated-info-warn': {+ 'no-debug-gated-info-warn': {meta: { type: 'problem', docs: { description: 'info/warn should not be gated by debug checks' } },create(context) {function isInfoWarnCall(node) {@@ -160,7 +150,6 @@ const logsPlugin = {},},- // Prefer message + metadata object (soft)'logger-requires-metadata': {meta: { type: 'suggestion', docs: { description: 'Prefer passing metadata object with logs' } },create(context) {@@ -190,7 +179,6 @@ const logsPlugin = {},},- // Encourage including an Error object or { err } when logging errors'error-object-in-logger-error': {meta: { type: 'suggestion', docs: { description: 'Include Error object or { err } in logger.error' } },create(context) {@@ -230,8 +218,7 @@ const logsPlugin = {},},- // Avoid logging raw req/res objects and request bodies/headers- 'no-raw-req-res-body-logging': {+ 'no-raw-req-res-body-logging': {meta: { type: 'suggestion', docs: { description: 'Avoid logging raw req/res or req.body/headers' } },create(context) {function isLogCall(node) {@@ -293,8 +280,6 @@ const logsPlugin = {const codebasePlugin = {rules: {- // Disallow all line comments (// ...) except ESLint directives- // Rationale: keep comments to essential block docs only; use JSDoc when necessary.'no-line-comments-except-directives': {meta: { type: 'problem', docs: { description: 'Disallow // line comments except ESLint directives' } },create(context) {@@ -318,7 +303,6 @@ const codebasePlugin = {};module.exports = [- // Global ignores{ ignores: ['**/node_modules/**', '**/dist/**', '**/build/**', '**/*.min.js', '**/*.bundle.js', 'portracker.tar', 'scripts/**'] },// Backend (Node.js, CJS)@@ -332,9 +316,8 @@ module.exports = [plugins: { logs: logsPlugin, codebase: codebasePlugin },rules: {...js.configs.recommended.rules,- 'no-console': 'error',- // Eliminate warnings across the codebase (temporarily disable noisy rules)- 'no-unused-vars': ['warn', { args: 'after-used', argsIgnorePattern: '^_', varsIgnorePattern: '^(React|_)', caughtErrors: 'none' }],+ 'no-console': 'error',+ 'no-unused-vars': ['warn', { args: 'after-used', argsIgnorePattern: '^_', varsIgnorePattern: '^(React|_)', caughtErrors: 'none' }],'no-useless-escape': 'warn','no-empty': ['warn', { allowEmptyCatch: true }],'logs/no-debug-gated-info-warn': 'warn',@@ -344,7 +327,6 @@ module.exports = [},},- // Frontend (browser, ESM + JSX){files: ['frontend/**/*.{js,jsx}'],languageOptions: {@@ -372,10 +354,8 @@ module.exports = [},},- // Allow console in logger implementation files{files: ['backend/lib/logger.js', 'frontend/src/lib/logger.js'],- // Disable console rule and custom logging plugin rules so logger impls don't self-flagrules: {'no-console': 'off','logs/no-emoji-in-logs': 'off',diff --git a/frontend/postcss.config.cjs b/frontend/postcss.config.cjsindex 703816a..75566d6 100644--- a/frontend/postcss.config.cjs+++ b/frontend/postcss.config.cjs@@ -1,4 +1,3 @@-// postcss.config.cjsmodule.exports = {plugins: [require('@tailwindcss/postcss')({diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 12e50c7..77b4a9d 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -17,9 +17,19 @@ import { Label } from "@/components/ui/label";import { DashboardLayout } from "./components/layout/DashboardLayout";import { MultipleServerSkeleton } from "./components/server/MultipleServerSkeleton";import { WhatsNewModal } from "./components/ui/WhatsNewModal";+import { ServiceRenameModal } from "./components/server/ServiceRenameModal";+import { BatchOperationsBar } from "./components/server/BatchOperationsBar";+import { BatchRenameModal } from "./components/server/BatchRenameModal";+import { BatchHideModal } from "./components/server/BatchHideModal";+import { BatchNotesModal } from "./components/server/BatchNotesModal";import { BarChart3 } from "lucide-react";import Logger from "./lib/logger";-import { useWhatsNew } from "./lib/hooks/useWhatsNew";const keyOf = (srvId, p) => `${srvId}-${p.host_ip}-${p.host_port}`;+import { useWhatsNew } from "./lib/hooks/useWhatsNew";+import { saveCustomServiceName, deleteCustomServiceName, getCustomServiceNames, batchCustomServiceNames } from "./lib/api/customServiceNames";+import { batchNotes, saveNote } from "./lib/api/notes";+import { generatePortKey } from "./lib/utils/portUtils";++const keyOf = (srvId, p) => generatePortKey(srvId, p);const logger = new Logger('App');@@ -36,6 +46,16 @@ export default function App() {const [modalPort, setModalPort] = useState(null);const [draftNote, setDraftNote] = useState("");+ const [renameModalOpen, setRenameModalOpen] = useState(false);+ const [renameSrvId, setRenameSrvId] = useState("");+ const [renamePort, setRenamePort] = useState(null);++ const [batchRenameModalOpen, setBatchRenameModalOpen] = useState(false);+ const [batchHideModalOpen, setBatchHideModalOpen] = useState(false);+ const [batchNotesModalOpen, setBatchNotesModalOpen] = useState(false);+ const [batchLoading, setBatchLoading] = useState(false);+ const [renameLoading, setRenameLoading] = useState(false);+const [actionFeedback, setActionFeedback] = useState({copy: null,edit: null,@@ -134,6 +154,9 @@ export default function App() {const [deepLinkServer, setDeepLinkServer] = useState(null);const [appliedDeepLink, setAppliedDeepLink] = useState(false);+ const [selectionMode, setSelectionMode] = useState(false);+ const [selectedPorts, setSelectedPorts] = useState(new Set());+useEffect(() => {if (isDarkMode) {document.documentElement.classList.add("dark");@@ -233,7 +256,7 @@ export default function App() {}, []);const transformCollectorData = useCallback(- async (collectorData, serverId) => {+ async (collectorData, serverId, serverUrl = null) => {if (!collectorData.ports || !Array.isArray(collectorData.ports)) {logger.warn(`transformCollectorData: No ports array in collectorData for serverId ${serverId}`,@@ -273,9 +296,7 @@ export default function App() {const seenKeys = new Set();transformedPorts.forEach((port) => {- const key = port.internal- ? `${port.container_id || port.app_id}:${port.host_port}:internal`- : `${port.host_ip}:${port.host_port}:${port.owner}`;+ const key = generatePortKey(serverId, port);if (!seenKeys.has(key)) {seenKeys.add(key);uniquePorts.push(port);@@ -284,11 +305,53 @@ export default function App() {}});+ let customServiceNames = [];+ try {+ customServiceNames = await getCustomServiceNames(serverId, serverUrl);+ logger.debug(`Loaded ${customServiceNames.length} custom service names for ${serverId}`);+ } catch (error) {+ logger.warn(`Failed to load custom service names for ${serverId}:`, error);+ }++ const customNameMap = new Map();+ customServiceNames.forEach(item => {+ const key = `${item.host_ip}:${item.host_port}:${item.container_id || ''}:${item.internal || 0}`;+ customNameMap.set(key, {+ customServiceName: item.custom_name,+ originalServiceName: item.original_name+ });+ });+const groupMap = new Map();uniquePorts.forEach((port) => {+ let customNameData = null;++ const customNameKey = `${port.host_ip}:${port.host_port}:${port.container_id || ''}:${port.internal || false ? 1 : 0}`;+ customNameData = customNameMap.get(customNameKey);++ if (!customNameData) {+ const fallbackKeys = [+ `0.0.0.0:${port.host_port}:${port.container_id || ''}:${port.internal || false ? 1 : 0}`,+ `[::]:${port.host_port}:${port.container_id || ''}:${port.internal || false ? 1 : 0}`,+ `host.docker.internal:${port.host_port}:${port.container_id || ''}:${port.internal || false ? 1 : 0}`+ ];++ for (const key of fallbackKeys) {+ customNameData = customNameMap.get(key);+ if (customNameData) {+ break;+ }+ }+ }++ if (customNameData) {+ port.customServiceName = customNameData.customServiceName;+ port.originalServiceName = customNameData.originalServiceName;+ }+if (port.source === "docker") {- const groupKey = port.container_id || port.app_id || port.owner;+ const groupKey = `${port.container_id || port.app_id || port.owner}${port.internal ? '-internal' : ''}`;if (!groupMap.has(groupKey)) {groupMap.set(groupKey, []);}@@ -354,7 +417,8 @@ export default function App() {const scanData = await scanResponse.json();const transformedPorts = await transformCollectorData(scanData,- server.id+ server.id,+ null);return {id: server.id,@@ -413,7 +477,8 @@ export default function App() {const scanData = await scanResponse.json();const transformedPorts = await transformCollectorData(scanData,- server.id+ server.id,+ server.url);return {id: server.id,@@ -579,7 +644,19 @@ export default function App() {const toggleIgnore = useCallback((srvId, p) => {+const newIgnoredState = !p.ignored;+ const portKey = generatePortKey(srvId, p);+ const actionType = newIgnoredState ? 'hide' : 'unhide';++ if (actionFeedback[actionType]?.id === portKey) {+ return;+ }++ setActionFeedback(prev => ({+ ...prev,+ [actionType]: { id: portKey, status: 'loading' }+ }));setGroups((currentGroups) =>currentGroups.map((group) => {@@ -587,7 +664,9 @@ export default function App() {const updatedData = group.data.map((port) => {if (port.host_ip === p.host_ip &&- port.host_port === p.host_port+ port.host_port === p.host_port &&+ (port.container_id || null) === (p.container_id || null) &&+ (port.internal || false) === (p.internal || false)) {return { ...port, ignored: newIgnoredState };}@@ -617,22 +696,48 @@ export default function App() {server_id: isPeer ? "local" : srvId,host_ip: p.host_ip,host_port: p.host_port,+ protocol: p.protocol,+ container_id: p.container_id || null,+ internal: p.internal || false,ignored: newIgnoredState,}),}).then((response) => {if (!response.ok)throw new Error("Failed to update ignore status on backend.");++ setActionFeedback(prev => ({+ ...prev,+ [actionType]: { id: portKey, status: 'success' }+ }));++ setTimeout(() => setActionFeedback(prev => ({+ ...prev,+ [actionType]: null+ })), 2000);}).catch((error) => {logger.error("Error toggling ignore:", error);++ setActionFeedback(prev => ({+ ...prev,+ [actionType]: { id: portKey, status: 'error' }+ }));++ setTimeout(() => setActionFeedback(prev => ({+ ...prev,+ [actionType]: null+ })), 3000);+setGroups((currentGroups) =>currentGroups.map((group) => {if (group.id === srvId) {const revertedData = group.data.map((port) => {if (port.host_ip === p.host_ip &&- port.host_port === p.host_port+ port.host_port === p.host_port &&+ (port.container_id || null) === (p.container_id || null) &&+ (port.internal || false) === (p.internal || false)) {return { ...port, ignored: p.ignored };}@@ -645,7 +750,7 @@ export default function App() {);});},- [servers]+ [servers, actionFeedback, setGroups, setActionFeedback]);const openNoteModal = useCallback((srvId, p) => {@@ -655,7 +760,13 @@ export default function App() {setNoteModalOpen(true);}, []);- const saveNote = useCallback(() => {+ const openRenameModal = useCallback((srvId, p) => {+ setRenameSrvId(srvId);+ setRenamePort(p);+ setRenameModalOpen(true);+ }, []);++ const saveNoteModal = useCallback(() => {if (!modalPort) return;const originalNote = modalPort.note || "";@@ -665,7 +776,9 @@ export default function App() {const updatedData = group.data.map((port) => {if (port.host_ip === modalPort.host_ip &&- port.host_port === modalPort.host_port+ port.host_port === modalPort.host_port &&+ (port.container_id || null) === (modalPort.container_id || null) &&+ (port.internal || false) === (modalPort.internal || false)) {return { ...port, note: draftNote };}@@ -678,31 +791,11 @@ export default function App() {);setNoteModalOpen(false);- let targetUrl = "/api/notes";- let isPeer = false;const currentServerIdForNote = modalSrvId;+ const serverForNote = servers.find((s) => s.id === currentServerIdForNote);+ const serverUrl = currentServerIdForNote !== "local" && serverForNote ? serverForNote.url : null;- if (currentServerIdForNote !== "local") {- const server = servers.find((s) => s.id === currentServerIdForNote);- if (server && server.url) {- targetUrl = `${server.url.replace(/\/+$/, "")}/api/notes`;- isPeer = true;- }- }-- fetch(targetUrl, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- server_id: isPeer ? "local" : currentServerIdForNote,- host_ip: modalPort.host_ip,- host_port: modalPort.host_port,- note: draftNote,- }),- })- .then((response) => {- if (!response.ok) throw new Error("Failed to save note on backend.");- })+ saveNote(currentServerIdForNote, modalPort.host_ip, modalPort.host_port, modalPort.protocol, draftNote, serverUrl, modalPort.container_id, modalPort.internal).catch((error) => {logger.error("Error saving note:", error);setGroups((currentGroups) =>@@ -711,7 +804,9 @@ export default function App() {const revertedData = group.data.map((port) => {if (port.host_ip === modalPort.host_ip &&- port.host_port === modalPort.host_port+ port.host_port === modalPort.host_port &&+ (port.container_id || null) === (modalPort.container_id || null) &&+ (port.internal || false) === (modalPort.internal || false)) {return { ...port, note: originalNote };}@@ -725,6 +820,380 @@ export default function App() {});}, [modalSrvId, modalPort, draftNote, servers]);+ const handleServiceRename = useCallback(async (renameData) => {+ const { serverId, hostIp, hostPort, customName, originalName, serverUrl, isReset, containerId, internal } = renameData;++ setRenameLoading(true);++ try {+ if (isReset || !customName) {+ try {+ await deleteCustomServiceName(serverId, hostIp, hostPort, renameData.protocol, serverUrl, containerId, internal || false);+ } catch (error) {+ if (!error.message.includes('not found')) {+ throw error;+ }+ logger.info('Custom service name already deleted or did not exist, proceeding with reset');+ }++ setGroups((currentGroups) =>+ currentGroups.map((group) => {+ if (group.id === serverId) {+ const updatedData = group.data.map((port) => {+ const matchesPort = port.host_ip === hostIp && port.host_port === hostPort;+ const matchesContainer = containerId ? port.container_id === containerId : !port.container_id;+ const matchesInternal = (port.internal || false) === (internal || false);++ if (matchesPort && matchesContainer && matchesInternal) {+ return {+ ...port,+ customServiceName: null,+ originalServiceName: null+ };+ }+ return port;+ });+ return { ...group, data: updatedData };+ }+ return group;+ })+ );+ } else {+ await saveCustomServiceName(serverId, hostIp, hostPort, renameData.protocol, customName, originalName, serverUrl, containerId, internal || false);++ setGroups((currentGroups) =>+ currentGroups.map((group) => {+ if (group.id === serverId) {+ const updatedData = group.data.map((port) => {+ const matchesPort = port.host_ip === hostIp && port.host_port === hostPort;+ const matchesContainer = containerId ? port.container_id === containerId : !port.container_id;+ const matchesInternal = (port.internal || false) === (internal || false);++ if (matchesPort && matchesContainer && matchesInternal) {+ return {+ ...port,+ customServiceName: customName,+ originalServiceName: originalName || port.owner+ };+ }+ return port;+ });+ return { ...group, data: updatedData };+ }+ return group;+ })+ );+ }++ setRenameModalOpen(false);+ } catch (error) {+ logger.error("Error updating service name:", error);+ } finally {+ setRenameLoading(false);+ }+ }, []);++ const clearSelection = useCallback(() => {+ setSelectedPorts(new Set());+ setSelectionMode(false);+ }, []);++ const handleBatchRenameSave = useCallback(async (data) => {+ const { customName, selectedPorts, isReset } = data;+ setBatchLoading(true);++ try {+ const portsByServer = new Map();++ selectedPorts.forEach(portKey => {+ const parts = portKey.split('-');+ if (parts.length < 3) return;++ const serverId = parts[0];+ const isInternal = parts[parts.length - 1] === 'internal';+ const containerIdIndex = isInternal ? parts.length - 2 : parts.length - 1;+ const hostPortIndex = isInternal ? parts.length - 3 : parts.length - 2;++ const containerId = parts[containerIdIndex];+ const hostPort = parts[hostPortIndex];+ const hostIp = parts.slice(1, hostPortIndex).join('-');++ if (!portsByServer.has(serverId)) {+ portsByServer.set(serverId, []);+ }++ const server = groups.find(g => g.id === serverId);+ const port = server?.data.find(p =>+ p.host_ip === hostIp &&+ p.host_port === parseInt(hostPort) &&+ (p.container_id || '') === (containerId || '') &&+ (p.internal || false) === isInternal+ );++ if (port) {+ portsByServer.get(serverId).push({+ action: isReset ? "delete" : "set",+ host_ip: hostIp,+ host_port: parseInt(hostPort),+ protocol: port.protocol,+ custom_name: isReset ? null : customName,+ original_name: port.originalServiceName || port.owner,+ container_id: containerId || null,+ internal: isInternal,+ });++ if (!port.internal) {+ const relatedPorts = server.data.filter(p =>+ p.host_port === parseInt(hostPort) &&+ p.owner === port.owner &&+ (p.container_id || '') === (containerId || '') &&+ p.host_ip !== hostIp &&+ !p.internal+ );++ relatedPorts.forEach(relatedPort => {+ portsByServer.get(serverId).push({+ action: isReset ? "delete" : "set",+ host_ip: relatedPort.host_ip,+ host_port: parseInt(hostPort),+ protocol: relatedPort.protocol,+ custom_name: isReset ? null : customName,+ original_name: relatedPort.originalServiceName || relatedPort.owner,+ container_id: containerId || null,+ internal: false,+ });+ });+ }+ }+ });++ const serverUrl = groups.find(g => g.id !== 'local')?.serverUrl;++ for (const [serverId, operations] of portsByServer) {+ await batchCustomServiceNames(serverId, operations, serverUrl);+ }++ setGroups((currentGroups) =>+ currentGroups.map((group) => {+ const serverPorts = portsByServer.get(group.id);+ if (!serverPorts) return group;++ const updatedData = group.data.map((port) => {+ const operation = serverPorts.find(op =>+ op.host_ip === port.host_ip &&+ op.host_port === port.host_port &&+ op.protocol === port.protocol &&+ (op.container_id || '') === (port.container_id || '') &&+ (op.internal || false) === (port.internal || false)+ );++ if (operation) {+ return {+ ...port,+ customServiceName: isReset ? null : customName,+ originalServiceName: isReset ? null : (operation.original_name || port.owner)+ };+ }+ return port;+ });++ return { ...group, data: updatedData };+ })+ );++ setBatchRenameModalOpen(false);+ clearSelection();+ } catch (error) {+ logger.error("Error updating service names:", error);+ } finally {+ setBatchLoading(false);+ }+ }, [groups, clearSelection]);++ const handleBatchHideSave = useCallback(async (data) => {+ const { selectedPorts, action } = data;+ setBatchLoading(true);++ try {+ const portsByServer = new Map();++ selectedPorts.forEach(portKey => {+ const parts = portKey.split('-');+ if (parts.length < 3) return;++ const serverId = parts[0];+ const isInternal = parts[parts.length - 1] === 'internal';+ const containerIdIndex = isInternal ? parts.length - 2 : parts.length - 1;+ const hostPortIndex = isInternal ? parts.length - 3 : parts.length - 2;++ const containerId = parts[containerIdIndex];+ const hostPort = parts[hostPortIndex];+ const hostIp = parts.slice(1, hostPortIndex).join('-');++ if (!portsByServer.has(serverId)) {+ portsByServer.set(serverId, []);+ }++ const server = groups.find(g => g.id === serverId);+ const port = server?.data.find(p =>+ p.host_ip === hostIp &&+ p.host_port === parseInt(hostPort) &&+ (p.container_id || '') === (containerId || '') &&+ (p.internal || false) === isInternal+ );++ if (port) {+ portsByServer.get(serverId).push(port);+ }+ });++ setGroups((currentGroups) =>+ currentGroups.map((group) => {+ const serverPorts = portsByServer.get(group.id);+ if (!serverPorts) return group;++ const updatedData = group.data.map((port) => {+ const shouldHide = serverPorts.some(sp =>+ sp.host_ip === port.host_ip &&+ sp.host_port === port.host_port &&+ (sp.container_id || '') === (port.container_id || '') &&+ (sp.internal || false) === (port.internal || false)+ );++ if (shouldHide) {+ return {+ ...port,+ ignored: action === 'hide'+ };+ }+ return port;+ });++ return { ...group, data: updatedData };+ })+ );++ const promises = [];+ for (const [serverId, serverPorts] of portsByServer) {+ for (const port of serverPorts) {+ let targetUrl = "/api/ignores";+ let isPeer = false;++ if (serverId !== "local") {+ const server = servers.find((s) => s.id === serverId);+ if (server && server.url) {+ targetUrl = `${server.url.replace(/\/+$/, "")}/api/ignores`;+ isPeer = true;+ }+ }++ const promise = fetch(targetUrl, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ server_id: isPeer ? "local" : serverId,+ host_ip: port.host_ip,+ host_port: port.host_port,+ protocol: port.protocol,+ container_id: port.container_id || null,+ internal: port.internal || false,+ ignored: action === 'hide',+ }),+ });+ promises.push(promise);+ }+ }++ await Promise.all(promises);++ setBatchHideModalOpen(false);+ clearSelection();+ } catch (error) {+ logger.error(`Error ${action}ing ports:`, error);+ } finally {+ setBatchLoading(false);+ }+ }, [groups, servers, clearSelection]);++ const handleBatchNotesSave = useCallback(async (data) => {+ const { note, selectedPorts, isClear } = data;+ setBatchLoading(true);++ try {+ const portsByServer = new Map();++ selectedPorts.forEach(portKey => {+ let matchedPort = null;+ let serverId = null;++ for (const group of groups) {+ const port = group.data.find(p => generatePortKey(group.id, p) === portKey);+ if (port) {+ matchedPort = port;+ serverId = group.id;+ break;+ }+ }++ if (!matchedPort || !serverId) return;++ if (!portsByServer.has(serverId)) {+ portsByServer.set(serverId, []);+ }++ portsByServer.get(serverId).push({+ action: isClear ? "delete" : "set",+ host_ip: matchedPort.host_ip,+ host_port: matchedPort.host_port,+ protocol: matchedPort.protocol || "tcp",+ note: isClear ? null : note,+ container_id: matchedPort.container_id || null,+ internal: matchedPort.internal || false,+ });+ });++ const serverUrl = groups.find(g => g.id !== 'local')?.serverUrl;++ for (const [serverId, operations] of portsByServer) {+ await batchNotes(serverId, operations, serverUrl);+ }++ setGroups((currentGroups) =>+ currentGroups.map((group) => {+ const serverPorts = portsByServer.get(group.id);+ if (!serverPorts) return group;++ const updatedData = group.data.map((port) => {+ const operation = serverPorts.find(op =>+ op.host_ip === port.host_ip &&+ op.host_port === port.host_port &&+ op.protocol === port.protocol &&+ (op.container_id || '') === (port.container_id || '') &&+ (op.internal || false) === (port.internal || false)+ );++ if (operation) {+ return {+ ...port,+ note: isClear ? null : note+ };+ }+ return port;+ });++ return { ...group, data: updatedData };+ })+ );++ setBatchNotesModalOpen(false);+ clearSelection();+ } catch (error) {+ logger.error("Error updating port notes:", error);+ } finally {+ setBatchLoading(false);+ }+ }, [groups, clearSelection]);+const fetchServers = useCallback(() => {fetch("/api/servers").then((r) => r.json())@@ -818,7 +1287,8 @@ export default function App() {const scanData = await scanResponse.json();const transformedPorts = await transformCollectorData(scanData,- serverData.id+ serverData.id,+ serverData.url);const finalServerData = {@@ -903,6 +1373,55 @@ export default function App() {[servers, groups, selectedServer, fetchServers]);+ const toggleServerSelectionMode = useCallback((_serverId) => {+ if (selectionMode) {+ setSelectionMode(false);+ setSelectedPorts(new Set());+ } else {+ setSelectionMode(true);+ }+ }, [selectionMode]);++ const togglePortSelection = useCallback((port, serverId) => {+ const portKey = generatePortKey(serverId, port);+ setSelectedPorts(prev => {+ const newSet = new Set(prev);+ if (newSet.has(portKey)) {+ newSet.delete(portKey);+ } else {+ newSet.add(portKey);+ }++ if (newSet.size === 0) {+ setSelectionMode(false);+ }++ return newSet;+ });+ }, []);++ const selectAllPortsForServer = useCallback((serverId, ports) => {+ const portKeys = ports.map(port => generatePortKey(serverId, port));+ setSelectedPorts(prev => {+ const newSet = new Set(prev);+ portKeys.forEach(key => newSet.add(key));+ return newSet;+ });+ setSelectionMode(true);+ }, []);++ const handleBatchRename = useCallback(() => {+ setBatchRenameModalOpen(true);+ }, []);++ const handleBatchHide = useCallback(() => {+ setBatchHideModalOpen(true);+ }, []);++ const handleBatchNote = useCallback(() => {+ setBatchNotesModalOpen(true);+ }, []);+useEffect(() => {fetchServers();}, [fetchServers]);@@ -923,6 +1442,7 @@ export default function App() {return (port.host_port.toString().includes(searchLower) ||(port.owner && port.owner.toLowerCase().includes(searchLower)) ||+ (port.customServiceName && port.customServiceName.toLowerCase().includes(searchLower)) ||(port.host_ip && port.host_ip.includes(searchLower)) ||port.target?.includes?.(searchLower) ||(port.note && port.note.toLowerCase().includes(searchLower))@@ -951,6 +1471,7 @@ export default function App() {actionFeedback={actionFeedback}onNote={openNoteModal}onToggleIgnore={toggleIgnore}+ onRename={openRenameModal}onCopy={(p, portProtocol) => {let hostForCopy;if (server.id === "local" &&@@ -1020,6 +1541,11 @@ export default function App() {deepLinkContainerId={selectedServer === server.id ? deepLinkContainer : null}onOpenContainerDetails={(containerId) => handleContainerOpen(server.id, containerId)}onCloseContainerDetails={handleContainerClose}+ selectionMode={selectionMode}+ selectedPorts={selectedPorts}+ onToggleSelection={togglePortSelection}+ onToggleServerSelectionMode={() => toggleServerSelectionMode(server.id)}+ onSelectAllPorts={(ports) => selectAllPortsForServer(server.id, ports)}/>);}@@ -1160,7 +1686,7 @@ export default function App() {<Button variant="outline" onClick={() => setNoteModalOpen(false)}>Cancel</Button>- <Button onClick={saveNote}>Save</Button>+ <Button onClick={saveNoteModal}>Save</Button></DialogFooter></DialogContent></Dialog>@@ -1168,6 +1694,98 @@ export default function App() {<WhatsNewModal{...getWhatsNewModalProps()}/>++ <ServiceRenameModal+ isOpen={renameModalOpen}+ onClose={() => setRenameModalOpen(false)}+ port={renamePort}+ serverId={renameSrvId}+ serverUrl={groups.find(g => g.id === renameSrvId)?.url}+ onSave={handleServiceRename}+ loading={renameLoading}+ />++ <BatchRenameModal+ isOpen={batchRenameModalOpen}+ onClose={() => setBatchRenameModalOpen(false)}+ selectedPorts={selectedPorts}+ onSave={handleBatchRenameSave}+ loading={batchLoading}+ />++ <BatchHideModal+ isOpen={batchHideModalOpen}+ onClose={() => setBatchHideModalOpen(false)}+ selectedPorts={selectedPorts}+ onConfirm={handleBatchHideSave}+ loading={batchLoading}+ action="hide"+ />++ <BatchNotesModal+ isOpen={batchNotesModalOpen}+ onClose={() => setBatchNotesModalOpen(false)}+ selectedPorts={selectedPorts}+ onSave={handleBatchNotesSave}+ loading={batchLoading}+ />++ <BatchOperationsBar+ selectedCount={selectedPorts.size}+ onBatchRename={handleBatchRename}+ onBatchHide={handleBatchHide}+ onBatchNote={handleBatchNote}+ onClearSelection={clearSelection}+ onSelectAll={() => {+ const currentGroup = selectedServer+ ? groups.find(g => g.id === selectedServer)+ : null;++ if (currentGroup) {+ let showInternal = false;+ try {+ const saved = localStorage.getItem(`showInternalPorts:${currentGroup.id}`);+ showInternal = saved ? JSON.parse(saved) : false;+ } catch {+ showInternal = false;+ }++ const filteredPorts = filterPorts(currentGroup).data || [];+ const visiblePorts = filteredPorts.filter(port =>+ !port.ignored && (showInternal || !port.internal)+ );++ const portKeys = visiblePorts.map(port =>+ generatePortKey(currentGroup.id, port)+ );+ setSelectedPorts(new Set(portKeys));+ setSelectionMode(true);+ }+ }}+ showSelectAll={(() => {+ const currentGroup = selectedServer+ ? groups.find(g => g.id === selectedServer)+ : null;++ if (!currentGroup) return false;++ let showInternal = false;+ try {+ const saved = localStorage.getItem(`showInternalPorts:${currentGroup.id}`);+ showInternal = saved ? JSON.parse(saved) : false;+ } catch {+ showInternal = false;+ }++ const filteredPorts = filterPorts(currentGroup).data || [];+ const visiblePortsCount = filteredPorts.filter(port =>+ !port.ignored && (showInternal || !port.internal)+ ).length;++ return selectedPorts.size > 0 && selectedPorts.size < visiblePortsCount;+ })()}+ loading={false}+ /></TooltipProvider>);diff --git a/frontend/src/components/server/ActionButton.jsx b/frontend/src/components/server/ActionButton.jsxindex 42dbfdf..5535061 100644--- a/frontend/src/components/server/ActionButton.jsx+++ b/frontend/src/components/server/ActionButton.jsx@@ -43,8 +43,9 @@ export function ActionButton({<TooltipTrigger asChild><buttononClick={onClick}- className={`${baseClasses} ${colorClasses} ${sizeClasses[size]}`}+ className={`${baseClasses} ${colorClasses} ${sizeClasses[size]} focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1`}disabled={wasClicked || isLoading}+ tabIndex={0}><spanclassName={diff --git a/frontend/src/components/server/BatchHideModal.jsx b/frontend/src/components/server/BatchHideModal.jsxnew file mode 100644index 0000000..53e3981--- /dev/null+++ b/frontend/src/components/server/BatchHideModal.jsx@@ -0,0 +1,88 @@+import React from "react";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogFooter,+ DialogTitle,+ DialogDescription,+} from "@/components/ui/dialog";+import { Button } from "@/components/ui/button";+import { Loader2, Eye, EyeOff } from "lucide-react";++/**+ * Modal component for batch hiding/showing multiple ports+ * Allows users to hide or show all selected ports at once+ */+export function BatchHideModal({+ isOpen,+ onClose,+ selectedPorts,+ onConfirm,+ loading = false,+ action = "hide",+}) {+ const handleConfirm = () => {+ onConfirm({+ selectedPorts: Array.from(selectedPorts),+ action,+ });+ };++ const portCount = selectedPorts?.size || 0;+ const isHiding = action === "hide";+ const actionText = isHiding ? "Hide" : "Show";+ const actionDescription = isHiding+ ? "Hidden ports will no longer appear in the main view but can be accessed through the hidden ports drawer."+ : "These ports will be restored to the main view.";++ return (+ <Dialog open={isOpen} onOpenChange={onClose}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2">+ {isHiding ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}+ {actionText} {portCount} Port{portCount !== 1 ? 's' : ''}+ </DialogTitle>+ <DialogDescription>+ {actionDescription}+ </DialogDescription>+ </DialogHeader>++ <div className="py-4">+ <p className="text-sm text-slate-600 dark:text-slate-400">+ Are you sure you want to {action} {portCount} selected port{portCount !== 1 ? 's' : ''}?+ </p>+ </div>++ <DialogFooter className="flex gap-2">+ <Button+ variant="outline"+ onClick={onClose}+ disabled={loading}+ >+ Cancel+ </Button>+ <Button+ onClick={handleConfirm}+ disabled={loading}+ variant={isHiding ? "destructive" : "default"}+ className="min-w-16"+ >+ {loading ? (+ <>+ <Loader2 className="h-4 w-4 mr-2 animate-spin" />+ {actionText}ing...+ </>+ ) : (+ <>+ {isHiding ? <EyeOff className="h-4 w-4 mr-2" /> : <Eye className="h-4 w-4 mr-2" />}+ {actionText} {portCount} Port{portCount !== 1 ? 's' : ''}+ </>+ )}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}\ No newline at end of filediff --git a/frontend/src/components/server/BatchNotesModal.jsx b/frontend/src/components/server/BatchNotesModal.jsxnew file mode 100644index 0000000..f6dfc75--- /dev/null+++ b/frontend/src/components/server/BatchNotesModal.jsx@@ -0,0 +1,136 @@+import React, { useState, useEffect } from "react";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogFooter,+ DialogTitle,+ DialogDescription,+} from "@/components/ui/dialog";+import { Button } from "@/components/ui/button";+import { Label } from "@/components/ui/label";+import { Loader2, FileText, Trash2 } from "lucide-react";++/**+ * Modal component for batch adding/editing notes for multiple ports+ * Allows users to set the same note for all selected ports+ */+export function BatchNotesModal({+ isOpen,+ onClose,+ selectedPorts,+ onSave,+ loading = false,+}) {+ const [note, setNote] = useState("");+ const [isDirty, setIsDirty] = useState(false);++ useEffect(() => {+ if (isOpen) {+ setNote("");+ setIsDirty(false);+ }+ }, [isOpen]);++ useEffect(() => {+ setIsDirty(note.trim().length > 0);+ }, [note]);++ const handleSave = () => {+ onSave({+ note: note.trim() || null,+ selectedPorts: Array.from(selectedPorts),+ });+ };++ const handleClear = () => {+ onSave({+ note: null,+ selectedPorts: Array.from(selectedPorts),+ isClear: true,+ });+ };++ const handleKeyDown = (e) => {+ if (e.key === "Enter" && e.ctrlKey && note.trim()) {+ e.preventDefault();+ handleSave();+ }+ };++ const portCount = selectedPorts?.size || 0;++ return (+ <Dialog open={isOpen} onOpenChange={onClose}>+ <DialogContent className="sm:max-w-lg">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2">+ <FileText className="h-5 w-5" />+ Batch Add Notes+ </DialogTitle>+ <DialogDescription>+ Add a note to {portCount} selected port{portCount !== 1 ? 's' : ''}.+ </DialogDescription>+ </DialogHeader>++ <div className="space-y-4 py-4">+ <div className="space-y-2">+ <Label htmlFor="batch-note">Note</Label>+ <textarea+ id="batch-note"+ value={note}+ onChange={(e) => setNote(e.target.value)}+ onKeyDown={handleKeyDown}+ placeholder="Enter a note for all selected ports..."+ className="w-full min-h-[100px] p-3 border border-slate-200 dark:border-slate-700 rounded-md bg-white dark:bg-slate-900 text-slate-900 dark:text-slate-100 placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-vertical"+ disabled={loading}+ autoFocus+ />+ <p className="text-xs text-slate-500 dark:text-slate-400">+ This note will be applied to all {portCount} selected ports. Press Ctrl+Enter to save.+ </p>+ </div>+ </div>++ <DialogFooter className="flex-col sm:flex-row gap-2">+ <div className="flex gap-2 sm:order-1">+ <Button+ variant="outline"+ onClick={onClose}+ disabled={loading}+ >+ Cancel+ </Button>+ <Button+ onClick={handleSave}+ disabled={loading}+ className="min-w-16"+ >+ {loading ? (+ <>+ <Loader2 className="h-4 w-4 mr-2 animate-spin" />+ Saving...+ </>+ ) : (+ <>+ <FileText className="h-4 w-4 mr-2" />+ {isDirty ? `Add Note to ${portCount} Port${portCount !== 1 ? 's' : ''}` : 'Save'}+ </>+ )}+ </Button>+ </div>++ <Button+ variant="ghost"+ onClick={handleClear}+ disabled={loading}+ className="sm:order-0 text-slate-600 hover:text-slate-800 dark:text-slate-400 dark:hover:text-slate-200"+ >+ <Trash2 className="h-4 w-4 mr-2" />+ Clear All Notes+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}\ No newline at end of filediff --git a/frontend/src/components/server/BatchOperationsBar.jsx b/frontend/src/components/server/BatchOperationsBar.jsxnew file mode 100644index 0000000..e0b1e4e--- /dev/null+++ b/frontend/src/components/server/BatchOperationsBar.jsx@@ -0,0 +1,94 @@+import React from "react";+import { Button } from "@/components/ui/button";+import { Edit3, EyeOff, StickyNote, X, CheckSquare } from "lucide-react";++/**+ * Floating action bar for batch operations on selected ports+ * Appears at bottom of screen when ports are selected+ */+export function BatchOperationsBar({+ selectedCount,+ onBatchRename,+ onBatchHide,+ onBatchNote,+ onClearSelection,+ onSelectAll,+ showSelectAll = false,+ loading = false,+}) {+ if (selectedCount === 0) return null;++ return (+ <div className="fixed bottom-6 left-1/2 transform -translate-x-1/2 z-50 animate-in slide-in-from-bottom-2 duration-200">+ <div className="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-lg shadow-lg px-4 py-3 flex items-center space-x-2">+ <div className="flex items-center space-x-3">+ <span className="text-sm font-medium text-slate-700 dark:text-slate-300">+ {selectedCount} port{selectedCount !== 1 ? 's' : ''} selected+ </span>++ <div className="w-px h-6 bg-slate-200 dark:bg-slate-700" />++ <div className="flex items-center space-x-1">+ {showSelectAll && (+ <Button+ variant="ghost"+ size="sm"+ onClick={onSelectAll}+ disabled={loading}+ className="h-8 px-2"+ >+ <CheckSquare className="h-4 w-4 mr-1" />+ All+ </Button>+ )}++ <Button+ variant="ghost"+ size="sm"+ onClick={onBatchRename}+ disabled={loading}+ className="h-8 px-2"+ >+ <Edit3 className="h-4 w-4 mr-1" />+ Rename+ </Button>++ <Button+ variant="ghost"+ size="sm"+ onClick={onBatchHide}+ disabled={loading}+ className="h-8 px-2"+ >+ <EyeOff className="h-4 w-4 mr-1" />+ Hide+ </Button>++ <Button+ variant="ghost"+ size="sm"+ onClick={onBatchNote}+ disabled={loading}+ className="h-8 px-2"+ >+ <StickyNote className="h-4 w-4 mr-1" />+ Note+ </Button>++ <div className="w-px h-6 bg-slate-200 dark:bg-slate-700" />++ <Button+ variant="ghost"+ size="sm"+ onClick={onClearSelection}+ disabled={loading}+ className="h-8 px-2 text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200"+ >+ <X className="h-4 w-4" />+ </Button>+ </div>+ </div>+ </div>+ </div>+ );+}\ No newline at end of filediff --git a/frontend/src/components/server/BatchRenameModal.jsx b/frontend/src/components/server/BatchRenameModal.jsxnew file mode 100644index 0000000..085ecdb--- /dev/null+++ b/frontend/src/components/server/BatchRenameModal.jsx@@ -0,0 +1,136 @@+import React, { useState, useEffect } from "react";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogFooter,+ DialogTitle,+ DialogDescription,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Button } from "@/components/ui/button";+import { Label } from "@/components/ui/label";+import { Loader2, RotateCcw } from "lucide-react";++/**+ * Modal component for batch renaming multiple services+ * Allows users to set the same custom name for all selected ports+ */+export function BatchRenameModal({+ isOpen,+ onClose,+ selectedPorts,+ onSave,+ loading = false,+}) {+ const [customName, setCustomName] = useState("");+ const [isDirty, setIsDirty] = useState(false);++ useEffect(() => {+ if (isOpen) {+ setCustomName("");+ setIsDirty(false);+ }+ }, [isOpen]);++ useEffect(() => {+ setIsDirty(customName.trim().length > 0);+ }, [customName]);++ const handleSave = () => {+ if (!customName.trim()) return;++ onSave({+ customName: customName.trim(),+ selectedPorts: Array.from(selectedPorts),+ });+ };++ const handleReset = () => {+ onSave({+ customName: null,+ selectedPorts: Array.from(selectedPorts),+ isReset: true,+ });+ };++ const handleKeyDown = (e) => {+ if (e.key === "Enter" && !e.shiftKey && isDirty && customName.trim()) {+ e.preventDefault();+ handleSave();+ }+ };++ const portCount = selectedPorts?.size || 0;++ return (+ <Dialog open={isOpen} onOpenChange={onClose}>+ <DialogContent className="sm:max-w-lg">+ <DialogHeader>+ <DialogTitle>Batch Rename Services</DialogTitle>+ <DialogDescription>+ Set a custom service name for {portCount} selected port{portCount !== 1 ? 's' : ''}.+ </DialogDescription>+ </DialogHeader>++ <div className="space-y-4 py-4">+ <div className="space-y-2">+ <Label htmlFor="batch-service-name">Service Name</Label>+ <Input+ id="batch-service-name"+ value={customName}+ onChange={(e) => setCustomName(e.target.value)}+ onKeyDown={handleKeyDown}+ placeholder="Enter custom service name..."+ className="w-full"+ disabled={loading}+ autoFocus+ />+ <p className="text-xs text-slate-500 dark:text-slate-400">+ This name will be applied to all {portCount} selected services.+ </p>+ </div>+ </div>++ <DialogFooter>+ <div className="flex flex-col gap-2 w-full">+ <div className="flex gap-2">+ <Button+ variant="outline"+ onClick={onClose}+ disabled={loading}+ className="flex-1"+ >+ Cancel+ </Button>+ <Button+ onClick={handleSave}+ disabled={!isDirty || loading}+ className="flex-1"+ >+ {loading ? (+ <>+ <Loader2 className="h-4 w-4 mr-2 animate-spin" />+ Saving...+ </>+ ) : (+ `Rename ${portCount}`+ )}+ </Button>+ </div>++ <Button+ variant="outline"+ onClick={handleReset}+ disabled={loading}+ className="w-full"+ >+ <RotateCcw className="h-4 w-4 mr-2" />+ Reset All to Original+ </Button>+ </div>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}\ No newline at end of filediff --git a/frontend/src/components/server/HiddenPortsDrawer.jsx b/frontend/src/components/server/HiddenPortsDrawer.jsxindex 5a9a060..966d4ee 100644--- a/frontend/src/components/server/HiddenPortsDrawer.jsx+++ b/frontend/src/components/server/HiddenPortsDrawer.jsx@@ -1,9 +1,15 @@import { Eye, EyeOff, ChevronDown } from "lucide-react";import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";+import { Button } from "@/components/ui/button";+import { generatePortKey } from "../../lib/utils/portUtils";-export function HiddenPortsDrawer({ hiddenPorts, onUnhide, serverId }) {+export function HiddenPortsDrawer({ hiddenPorts, onUnhide, onUnhideAll, serverId }) {if (hiddenPorts.length === 0) return null;+ const handleUnhideAll = () => {+ onUnhideAll(hiddenPorts);+ };+return (<div className="p-4"><details className="group">@@ -12,32 +18,50 @@ export function HiddenPortsDrawer({ hiddenPorts, onUnhide, serverId }) {<span>Hidden Ports ({hiddenPorts.length})</span><ChevronDown className="w-4 h-4 ml-auto transition-transform group-open:rotate-180" /></summary>- <ul className="mt-3 space-y-2 pl-6 border-l border-slate-200 dark:border-slate-700 ml-2">- {hiddenPorts.map((p) => (- <li- key={`${serverId}-${p.host_ip}-${p.host_port}-hidden`}- className="flex items-center justify-between p-2 bg-slate-50 dark:bg-slate-800/50 rounded-md"++ <div className="mt-3 pl-6 border-l border-slate-200 dark:border-slate-700 ml-2">+ {/**+ * Unhide all button+ */}+ <div className="mb-3">+ <Button+ variant="outline"+ size="sm"+ onClick={handleUnhideAll}+ className="text-xs h-7">- <div className="text-sm text-slate-700 dark:text-slate-300">- <span className="font-mono">{p.host_port}</span> —{" "}- <span className="truncate">{p.owner}</span>- </div>- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <button- onClick={() => onUnhide(p)}- className="p-1.5 rounded-lg text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors"- >- <Eye className="w-4 h-4" />- </button>- </TooltipTrigger>- <TooltipContent>Unhide port</TooltipContent>- </Tooltip>- </TooltipProvider>- </li>- ))}- </ul>+ <Eye className="w-3 h-3 mr-1" />+ Unhide All ({hiddenPorts.length})+ </Button>+ </div>++ <ul className="space-y-2">+ {hiddenPorts.map((p) => (+ <li+ key={generatePortKey(serverId, p)}+ className="flex items-center justify-between p-2 bg-slate-50 dark:bg-slate-800/50 rounded-md"+ >+ <div className="text-sm text-slate-700 dark:text-slate-300">+ <span className="font-mono">{p.host_port}</span> —{" "}+ <span className="truncate">{p.owner}</span>+ </div>+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ onClick={() => onUnhide(p)}+ className="p-1.5 rounded-lg text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors"+ >+ <Eye className="w-4 h-4" />+ </button>+ </TooltipTrigger>+ <TooltipContent>Unhide port</TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </li>+ ))}+ </ul>+ </div></details></div>);diff --git a/frontend/src/components/server/PortCard.jsx b/frontend/src/components/server/PortCard.jsxindex 9b9c1a5..37ba986 100644--- a/frontend/src/components/server/PortCard.jsx+++ b/frontend/src/components/server/PortCard.jsx@@ -1,5 +1,5 @@import React, { useState } from "react";-import { ExternalLink, Lock } from "lucide-react";+import { ExternalLink, Lock, Tag } from "lucide-react";import {Tooltip,TooltipContent,@@ -8,6 +8,7 @@ import {} from "@/components/ui/tooltip";import { PortStatusIndicator } from "./PortStatusIndicator";import { PortActions } from "./PortActions";+import { ActionButton } from "./ActionButton";import { InternalPortDetails } from "./InternalPortDetails";import {formatCreatedDate,@@ -34,6 +35,10 @@ const renderHighlightedText = (content) => {);};+const getDisplayServiceName = (port) => {+ return port.customServiceName || port.owner || "Unknown Service";+};+function PortCardComponent({port,itemKey,@@ -42,11 +47,15 @@ function PortCardComponent({onCopy,onEdit,onToggleIgnore,+ onRename,serverId,serverUrl,forceOpenDetails,notifyOpenDetails,notifyCloseDetails,+ selectionMode = false,+ isSelected = false,+ onToggleSelection,}) {const [protocol, setProtocol] = useState("http");const [showDetails, setShowDetails] = useState(false);@@ -76,8 +85,21 @@ function PortCardComponent({return (<litabIndex="0"- className="flex items-center justify-between p-4 hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors group focus:outline-none focus:bg-slate-50 dark:focus:bg-slate-800/50"+ className={`flex items-center justify-between p-4 hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors group focus:outline-none focus:bg-slate-50 dark:focus:bg-slate-800/50 ${+ isSelected ? 'bg-blue-50 dark:bg-blue-900/20 border-l-4 border-blue-500' : ''+ }`}>+ {selectionMode && (+ <div className="flex items-center mr-3">+ <input+ type="checkbox"+ checked={isSelected}+ onChange={() => onToggleSelection?.(port, serverId)}+ className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-slate-300 dark:border-slate-600 rounded cursor-pointer"+ />+ </div>+ )}+<div className="flex items-center space-x-4 flex-1 min-w-0"><div className="flex items-center space-x-2"><PortStatusIndicator@@ -157,7 +179,7 @@ function PortCardComponent({<div className="space-y-1 flex-1 min-w-0"><div className="flex items-center justify-between">- <div className="text-sm font-semibold text-slate-900 dark:text-slate-100 truncate flex items-center">+ <div className="text-sm font-semibold text-slate-900 dark:text-slate-100 truncate flex items-center space-x-1">{canShowDetails ? (<TooltipProvider><Tooltip>@@ -172,9 +194,9 @@ function PortCardComponent({>{shouldHighlight? renderHighlightedText(- highlightText(port.owner, searchTerm)+ highlightText(getDisplayServiceName(port), searchTerm))- : port.owner}+ : getDisplayServiceName(port)}</button></TooltipTrigger><TooltipContent>Open container details</TooltipContent>@@ -184,11 +206,22 @@ function PortCardComponent({<span className="truncate inline-flex items-center">{shouldHighlight? renderHighlightedText(- highlightText(port.owner, searchTerm)+ highlightText(getDisplayServiceName(port), searchTerm))- : port.owner}+ : getDisplayServiceName(port)}</span>)}+ <div className="opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity">+ <ActionButton+ type="rename"+ itemKey={itemKey}+ actionFeedback={actionFeedback}+ onClick={() => onRename(serverId, port)}+ icon={Tag}+ title="Rename service"+ size="sm"+ />+ </div></div></div><div className="flex items-center space-x-2 text-xs text-slate-500 dark:text-slate-400">@@ -246,7 +279,7 @@ function PortCardComponent({</div></div>- <div className="opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity">+ <div className="opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 group-active:opacity-100 [@media(hover:none)]:group-active:opacity-100 [@media(hover:none)]:opacity-0 transition-opacity"><PortActionsport={port}itemKey={itemKey}diff --git a/frontend/src/components/server/PortGridItem.jsx b/frontend/src/components/server/PortGridItem.jsxindex 0d029c0..5e3e463 100644--- a/frontend/src/components/server/PortGridItem.jsx+++ b/frontend/src/components/server/PortGridItem.jsx@@ -1,5 +1,5 @@import React, { useState } from "react";-import { ExternalLink, Lock } from "lucide-react";+import { ExternalLink, Lock, Tag } from "lucide-react";import {Tooltip,TooltipContent,@@ -8,6 +8,7 @@ import {} from "@/components/ui/tooltip";import { PortStatusIndicator } from "./PortStatusIndicator";import { PortActions } from "./PortActions";+import { ActionButton } from "./ActionButton";import { InternalPortDetails } from "./InternalPortDetails";import {formatCreatedDate,@@ -15,6 +16,7 @@ import {getSearchMatches,highlightText,} from "@/lib/utils";+import { generatePortKey } from "../../lib/utils/portUtils";const renderHighlightedText = (content) => {if (typeof content === "string") return content;@@ -34,6 +36,10 @@ const renderHighlightedText = (content) => {);};+const getDisplayServiceName = (port) => {+ return port.customServiceName || port.owner || "Unknown Service";+};+/*** Displays detailed information and interactive actions for a network port, with optional search term highlighting.*@@ -48,9 +54,13 @@ export function PortGridItem({onCopy,onNote,onToggleIgnore,+ onRename,forceOpenDetails,notifyOpenDetails,notifyCloseDetails,+ selectionMode = false,+ isSelected = false,+ onToggleSelection,}) {const [protocol, setProtocol] = useState("http");const [showDetails, setShowDetails] = useState(false);@@ -80,10 +90,23 @@ export function PortGridItem({return (<divtabIndex="0"- className="group relative border border-slate-200 dark:border-slate-700 rounded-lg p-4 hover:shadow-lg hover:border-slate-300 dark:hover:border-slate-600 transition-all duration-200 min-h-[120px] flex flex-col justify-between bg-white dark:bg-slate-900 focus:outline-none focus:ring-2 focus:ring-indigo-500"+ className={`group relative border border-slate-200 dark:border-slate-700 rounded-lg p-4 hover:shadow-lg hover:border-slate-300 dark:hover:border-slate-600 transition-all duration-200 min-h-[120px] flex flex-col justify-between bg-white dark:bg-slate-900 focus:outline-none focus:ring-2 focus:ring-indigo-500 ${+ isSelected ? 'border-blue-500 dark:border-blue-400 bg-blue-50 dark:bg-blue-900/20 shadow-md' : ''+ }`}>+ {selectionMode && (+ <div className="absolute top-2 left-2 z-10">+ <input+ type="checkbox"+ checked={isSelected}+ onChange={() => onToggleSelection?.(port, serverId)}+ className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-slate-300 dark:border-slate-600 rounded cursor-pointer"+ />+ </div>+ )}+<div className="flex items-start justify-between mb-3">- <div className="flex items-center space-x-2 min-w-0 flex-1">+ <div className={`flex items-center space-x-2 min-w-0 flex-1 ${selectionMode ? 'ml-6' : ''}`}><PortStatusIndicatorserverId={serverId}serverUrl={serverUrl}@@ -148,14 +171,10 @@ export function PortGridItem({</div></div>- <div className="flex items-center space-x-0.5 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity ml-2">+ <div className="flex items-center space-x-0.5 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 group-active:opacity-100 [@media(hover:none)]:group-active:opacity-100 [@media(hover:none)]:opacity-0 transition-opacity ml-2"><PortActionsport={port}- itemKey={- port.internal- ? `${serverId}-${port.container_id || port.app_id}-${port.host_port}-internal`- : `${serverId}-${port.host_ip}-${port.host_port}`- }+ itemKey={generatePortKey(serverId, port)}actionFeedback={actionFeedback}onCopy={() => onCopy(port, protocol)}onEdit={() => onNote(serverId, port)}@@ -178,33 +197,46 @@ export function PortGridItem({<div className="mb-2 flex-1"><h4 className="font-semibold text-sm text-slate-900 dark:text-slate-100 break-words leading-tight">- {canShowDetails ? (- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <button- type="button"- onClick={() => {- setShowDetails(true);- if (notifyOpenDetails && port.container_id) notifyOpenDetails(port.container_id);- }}- className="inline-flex items-center w-fit whitespace-nowrap cursor-pointer rounded-md px-1.5 py-0.5 transition-colors hover:bg-slate-100/70 dark:hover:bg-slate-800/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500/40"- >- {shouldHighlight- ? renderHighlightedText(highlightText(port.owner, searchTerm))- : port.owner}- </button>- </TooltipTrigger>- <TooltipContent>Open container details</TooltipContent>- </Tooltip>- </TooltipProvider>- ) : (- <span className="truncate inline-flex items-center">- {shouldHighlight- ? renderHighlightedText(highlightText(port.owner, searchTerm))- : port.owner}- </span>- )}+ <div className="flex items-center space-x-1">+ {canShowDetails ? (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ onClick={() => {+ setShowDetails(true);+ if (notifyOpenDetails && port.container_id) notifyOpenDetails(port.container_id);+ }}+ className="inline-flex items-center w-fit whitespace-nowrap cursor-pointer rounded-md px-1.5 py-0.5 transition-colors hover:bg-slate-100/70 dark:hover:bg-slate-800/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500/40"+ >+ {shouldHighlight+ ? renderHighlightedText(highlightText(getDisplayServiceName(port), searchTerm))+ : getDisplayServiceName(port)}+ </button>+ </TooltipTrigger>+ <TooltipContent>Open container details</TooltipContent>+ </Tooltip>+ </TooltipProvider>+ ) : (+ <span className="truncate inline-flex items-center">+ {shouldHighlight+ ? renderHighlightedText(highlightText(getDisplayServiceName(port), searchTerm))+ : getDisplayServiceName(port)}+ </span>+ )}+ <div className="opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity">+ <ActionButton+ type="rename"+ itemKey={generatePortKey(serverId, port)}+ actionFeedback={actionFeedback}+ onClick={() => onRename(serverId, port)}+ icon={Tag}+ title="Rename service"+ size="sm"+ />+ </div>+ </div></h4>{port.note && (<TooltipProvider>diff --git a/frontend/src/components/server/PortTable.jsx b/frontend/src/components/server/PortTable.jsxindex b6fe5a9..9238a44 100644--- a/frontend/src/components/server/PortTable.jsx+++ b/frontend/src/components/server/PortTable.jsx@@ -1,5 +1,6 @@import { ArrowUpDown, ArrowUp, ArrowDown } from "lucide-react";import { PortTableRow } from "./PortTableRow";+import { generatePortKey } from "../../lib/utils/portUtils";/*** Renders a sortable table displaying a list of ports with associated details and actions.@@ -15,11 +16,16 @@ export function PortTable({onCopy,onNote,onToggleIgnore,+ onRename,sortConfig,onSort,deepLinkContainerId,onOpenContainerDetails,onCloseContainerDetails,+ selectionMode = false,+ selectedPorts,+ onToggleSelection,+ onSelectAllPorts,}) {const getSortIcon = (column) => {if (sortConfig.key !== column) {@@ -36,11 +42,48 @@ export function PortTable({onSort(column);};+ const allSelected = ports.length > 0 && ports.every(port =>+ selectedPorts?.has(generatePortKey(serverId, port))+ );++ const someSelected = ports.some(port =>+ selectedPorts?.has(generatePortKey(serverId, port))+ );++ const handleSelectAll = () => {+ if (allSelected) {+ ports.forEach(port => {+ if (selectedPorts?.has(generatePortKey(serverId, port))) {+ onToggleSelection?.(port, serverId);+ }+ });+ } else {+ onSelectAllPorts?.(ports);+ }+ };+return (<div className="overflow-x-auto"><table className="min-w-full"><thead className="bg-slate-50 dark:bg-slate-800/50"><tr>+ {selectionMode && (+ <th+ scope="col"+ className="px-4 py-3 text-center text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider"+ >+ <input+ type="checkbox"+ checked={allSelected}+ ref={input => {+ if (input) input.indeterminate = someSelected && !allSelected;+ }}+ onChange={handleSelectAll}+ className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-slate-300 dark:border-slate-600 rounded cursor-pointer"+ />+ </th>+ )}+<thscope="col"className="px-4 py-3 text-center text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider"@@ -106,11 +149,7 @@ export function PortTable({<tbody className="divide-y divide-slate-100 dark:divide-slate-800 bg-white dark:bg-slate-900">{ports.map((port) => (<PortTableRow- key={- port.internal- ? `${serverId}-${port.container_id || port.app_id}-${port.host_port}-internal`- : `${serverId}-${port.host_ip}-${port.host_port}`- }+ key={generatePortKey(serverId, port)}port={port}serverId={serverId}serverUrl={serverUrl}@@ -119,9 +158,13 @@ export function PortTable({onCopy={onCopy}onNote={onNote}onToggleIgnore={onToggleIgnore}+ onRename={onRename}forceOpenDetails={deepLinkContainerId && port.container_id === deepLinkContainerId}notifyOpenDetails={(cid) => onOpenContainerDetails && onOpenContainerDetails(cid)}notifyCloseDetails={() => onCloseContainerDetails && onCloseContainerDetails()}+ selectionMode={selectionMode}+ isSelected={selectedPorts?.has(generatePortKey(serverId, port))}+ onToggleSelection={onToggleSelection}/>))}</tbody>diff --git a/frontend/src/components/server/PortTableRow.jsx b/frontend/src/components/server/PortTableRow.jsxindex e28c9e3..3aa3028 100644--- a/frontend/src/components/server/PortTableRow.jsx+++ b/frontend/src/components/server/PortTableRow.jsx@@ -1,5 +1,5 @@import React, { useState } from "react";-import { ExternalLink, Lock } from "lucide-react";+import { ExternalLink, Lock, Tag } from "lucide-react";import {Tooltip,TooltipContent,@@ -8,6 +8,7 @@ import {} from "@/components/ui/tooltip";import { PortStatusIndicator } from "./PortStatusIndicator";import { PortActions } from "./PortActions";+import { ActionButton } from "./ActionButton";import { InternalPortDetails } from "./InternalPortDetails";import {formatCreatedDate,@@ -15,6 +16,7 @@ import {getSearchMatches,highlightText,} from "@/lib/utils";+import { generatePortKey } from "../../lib/utils/portUtils";const renderHighlightedText = (content) => {if (typeof content === "string") return content;@@ -34,6 +36,10 @@ const renderHighlightedText = (content) => {);};+const getDisplayServiceName = (port) => {+ return port.customServiceName || port.owner || "Unknown Service";+};+function PortTableRowComponent({port,serverId,@@ -43,9 +49,13 @@ function PortTableRowComponent({onCopy,onNote,onToggleIgnore,+ onRename,forceOpenDetails,notifyOpenDetails,notifyCloseDetails,+ selectionMode = false,+ isSelected = false,+ onToggleSelection,}) {const [protocol, setProtocol] = useState("http");const [showDetails, setShowDetails] = useState(false);@@ -71,13 +81,25 @@ function PortTableRowComponent({hostForUi = port.host_ip;}- const itemKey = `${serverId}-${port.host_ip}-${port.host_port}`;+ const itemKey = generatePortKey(serverId, port);return (<trtabIndex="0"- className="group hover:bg-slate-50 dark:hover:bg-slate-800/50 focus:outline-none focus:bg-slate-50 dark:focus:bg-slate-800/50"+ className={`group hover:bg-slate-50 dark:hover:bg-slate-800/50 focus:outline-none focus:bg-slate-50 dark:focus:bg-slate-800/50 ${+ isSelected ? 'bg-blue-50 dark:bg-blue-900/20 border-l-4 border-blue-500' : ''+ }`}>+ {selectionMode && (+ <td className="px-4 py-3 text-center">+ <input+ type="checkbox"+ checked={isSelected}+ onChange={() => onToggleSelection?.(port, serverId)}+ className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-slate-300 dark:border-slate-600 rounded cursor-pointer"+ />+ </td>+ )}<td className="px-4 py-3 text-center"><div className="flex justify-center">@@ -167,28 +189,54 @@ function PortTableRowComponent({<td className="px-4 py-3 text-sm text-slate-600 dark:text-slate-300"><div className="flex flex-col space-y-1">{canShowDetails ? (- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <button- type="button"- onClick={() => setShowDetails(true)}- className="inline-flex items-center w-fit whitespace-nowrap cursor-pointer rounded-md px-1.5 py-0.5 transition-colors hover:bg-slate-100/70 dark:hover:bg-slate-800/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500/40"- >- {shouldHighlight- ? renderHighlightedText(highlightText(port.owner, searchTerm))- : port.owner}- </button>- </TooltipTrigger>- <TooltipContent>Open container details</TooltipContent>- </Tooltip>- </TooltipProvider>+ <div className="flex items-center space-x-1">+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ onClick={() => setShowDetails(true)}+ className="inline-flex items-center w-fit whitespace-nowrap cursor-pointer rounded-md px-1.5 py-0.5 transition-colors hover:bg-slate-100/70 dark:hover:bg-slate-800/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500/40"+ >+ {shouldHighlight+ ? renderHighlightedText(highlightText(getDisplayServiceName(port), searchTerm))+ : getDisplayServiceName(port)}+ </button>+ </TooltipTrigger>+ <TooltipContent>Open container details</TooltipContent>+ </Tooltip>+ </TooltipProvider>+ <div className="opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity">+ <ActionButton+ type="rename"+ itemKey={itemKey}+ actionFeedback={actionFeedback}+ onClick={() => onRename(serverId, port)}+ icon={Tag}+ title="Rename service"+ size="sm"+ />+ </div>+ </div>) : (- <span className="truncate inline-flex items-center">- {shouldHighlight- ? renderHighlightedText(highlightText(port.owner, searchTerm))- : port.owner}- </span>+ <div className="flex items-center space-x-1">+ <span className="truncate inline-flex items-center">+ {shouldHighlight+ ? renderHighlightedText(highlightText(getDisplayServiceName(port), searchTerm))+ : getDisplayServiceName(port)}+ </span>+ <div className="opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity">+ <ActionButton+ type="rename"+ itemKey={itemKey}+ actionFeedback={actionFeedback}+ onClick={() => onRename(serverId, port)}+ icon={Tag}+ title="Rename service"+ size="sm"+ />+ </div>+ </div>)}{port.note && (<TooltipProvider>@@ -247,7 +295,7 @@ function PortTableRowComponent({<td className="px-4 py-3 text-right">- <div className="opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity">+ <div className="opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 group-active:opacity-100 [@media(hover:none)]:group-active:opacity-100 [@media(hover:none)]:opacity-0 transition-opacity"><PortActionsport={port}itemKey={itemKey}diff --git a/frontend/src/components/server/SelectionActionButton.jsx b/frontend/src/components/server/SelectionActionButton.jsxnew file mode 100644index 0000000..19d32e8--- /dev/null+++ b/frontend/src/components/server/SelectionActionButton.jsx@@ -0,0 +1,47 @@+import { CheckSquare, Square } from "lucide-react";+import { ActionButton } from "./ActionButton";++/**+ * Selection action button that integrates with existing action button pattern+ * Shows different icons based on selection state+ */+export function SelectionActionButton({+ port,+ serverId,+ itemKey,+ actionFeedback,+ selectionMode,+ isSelected,+ onToggleSelection,+ size = "sm"+}) {+ const handleClick = () => {+ onToggleSelection?.(port, serverId);+ };++ const getIcon = () => {+ if (selectionMode) {+ return isSelected ? CheckSquare : Square;+ }+ return CheckSquare;+ };++ const getTitle = () => {+ if (selectionMode) {+ return isSelected ? "Deselect port" : "Select port";+ }+ return "Select port";+ };++ return (+ <ActionButton+ type="select"+ itemKey={itemKey}+ actionFeedback={actionFeedback}+ onClick={handleClick}+ icon={getIcon()}+ title={getTitle()}+ size={size}+ />+ );+}\ No newline at end of filediff --git a/frontend/src/components/server/ServerSection.jsx b/frontend/src/components/server/ServerSection.jsxindex 427e92a..30b516d 100644--- a/frontend/src/components/server/ServerSection.jsx+++ b/frontend/src/components/server/ServerSection.jsx@@ -13,6 +13,7 @@ import {Rows,Info,Lock,+ CheckSquare,} from "lucide-react";import { PortCard } from "./PortCard";import { PortGridItem } from "./PortGridItem";@@ -21,6 +22,7 @@ import { HiddenPortsDrawer } from "./HiddenPortsDrawer";import { SystemInfoCard } from "./SystemInfoCard";import Logger from "../../lib/logger";import { VMsCard } from "./VMsCard";+import { generatePortKey } from "../../lib/utils/portUtils";import {Accordion,AccordionContent,@@ -49,6 +51,7 @@ function ServerSectionComponent({actionFeedback,onNote,onToggleIgnore,+ onRename,onCopy,serverUrl,platformName,@@ -65,6 +68,11 @@ function ServerSectionComponent({deepLinkContainerId,onOpenContainerDetails,onCloseContainerDetails,+ selectionMode = false,+ selectedPorts,+ onToggleSelection,+ onToggleServerSelectionMode,+ onSelectAllPorts,}) {const logger = useMemo(() => new Logger('ServerSection'), []);@@ -572,6 +580,27 @@ function ServerSectionComponent({</Tooltip></TooltipProvider></div>++ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ onClick={onToggleServerSelectionMode}+ className={`p-1.5 sm:p-2 rounded-md transition-colors ${+ selectionMode+ ? "bg-blue-100 dark:bg-blue-800/50 text-blue-700 dark:text-blue-300 shadow-sm"+ : "bg-slate-100 text-slate-600 hover:bg-slate-200 hover:text-slate-700 dark:bg-slate-700 dark:text-slate-300 dark:hover:bg-slate-600 dark:hover:text-slate-200"+ }`}+ >+ <CheckSquare className="h-4 w-4" />+ </button>+ </TooltipTrigger>+ <TooltipContent>+ {selectionMode ? "Exit selection mode" : "Select ports"}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+{sortedPorts.length > 8 && portLayout !== "grid" && (<buttononClick={onToggleExpanded}@@ -597,90 +626,148 @@ function ServerSectionComponent({</div>{ok && visiblePorts.length > 0 && (- <div>+ <div className={selectionMode ? "pb-20" : ""}>{portLayout === "list" && (- <ul className="space-y-2">- {portsToDisplay.map((port) => (- <PortCard- key={- port.internal- ? `${id}-${port.container_id || port.app_id}-${port.host_port}-internal`- : `${id}-${port.host_ip}-${port.host_port}`- }- port={port}- itemKey={- port.internal- ? `${id}-${port.container_id || port.app_id}-${port.host_port}-internal`- : `${id}-${port.host_ip}-${port.host_port}`- }- searchTerm={searchTerm}- actionFeedback={actionFeedback}- onCopy={onCopy}- onEdit={onNote}- onToggleIgnore={onToggleIgnore}- serverId={id}- serverUrl={serverUrl}- forceOpenDetails={deepLinkContainerId && port.container_id === deepLinkContainerId}- notifyOpenDetails={(cid) => onOpenContainerDetails && onOpenContainerDetails(cid)}- notifyCloseDetails={() => onCloseContainerDetails && onCloseContainerDetails()}- />- ))}- </ul>- )}-- {portLayout === "card" && (- <ul className="space-y-2">+ <>+ {/**+ * Select all header for non-table views+ */}+ {selectionMode && (+ <div className="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-800/50 border-b border-slate-200 dark:border-slate-700">+ <div className="flex items-center space-x-3">+ <input+ type="checkbox"+ checked={portsToDisplay.length > 0 && portsToDisplay.every(port =>+ selectedPorts?.has(generatePortKey(id, port))+ )}+ ref={input => {+ if (input) {+ const allSelected = portsToDisplay.length > 0 && portsToDisplay.every(port =>+ selectedPorts?.has(generatePortKey(id, port))+ );+ const someSelected = portsToDisplay.some(port =>+ selectedPorts?.has(generatePortKey(id, port))+ );+ input.indeterminate = someSelected && !allSelected;+ }+ }}+ onChange={() => {+ const allSelected = portsToDisplay.every(port =>+ selectedPorts?.has(generatePortKey(id, port))+ );+ if (allSelected) {+ portsToDisplay.forEach(port => {+ if (selectedPorts?.has(generatePortKey(id, port))) {+ onToggleSelection?.(port, id);+ }+ });+ } else {+ onSelectAllPorts?.(portsToDisplay);+ }+ }}+ className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-slate-300 dark:border-slate-600 rounded cursor-pointer"+ />+ <span className="text-sm font-medium text-slate-700 dark:text-slate-300">+ Select All ({portsToDisplay.length})+ </span>+ </div>+ </div>+ )}+ <ul className="space-y-2">{portsToDisplay.map((port) => (<PortCard- key={- port.internal- ? `${id}-${port.container_id || port.app_id}-${port.host_port}-internal`- : `${id}-${port.host_ip}-${port.host_port}`- }+ key={generatePortKey(id, port)}port={port}- itemKey={- port.internal- ? `${id}-${port.container_id || port.app_id}-${port.host_port}-internal`- : `${id}-${port.host_ip}-${port.host_port}`- }+ itemKey={generatePortKey(id, port)}searchTerm={searchTerm}actionFeedback={actionFeedback}onCopy={onCopy}onEdit={onNote}onToggleIgnore={onToggleIgnore}+ onRename={onRename}serverId={id}serverUrl={serverUrl}forceOpenDetails={deepLinkContainerId && port.container_id === deepLinkContainerId}notifyOpenDetails={(cid) => onOpenContainerDetails && onOpenContainerDetails(cid)}notifyCloseDetails={() => onCloseContainerDetails && onCloseContainerDetails()}- />- ))}- </ul>+ selectionMode={selectionMode}+ isSelected={selectedPorts?.has(generatePortKey(id, port))}+ onToggleSelection={onToggleSelection}+ />)+ )}+ </ul>+ </>)}{portLayout === "grid" && (- <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">+ <>+ {/**+ * Select all header for grid view+ */}+ {selectionMode && (+ <div className="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-800/50 border-b border-slate-200 dark:border-slate-700 mb-4">+ <div className="flex items-center space-x-3">+ <input+ type="checkbox"+ checked={portsToDisplay.length > 0 && portsToDisplay.every(port =>+ selectedPorts?.has(generatePortKey(id, port))+ )}+ ref={input => {+ if (input) {+ const allSelected = portsToDisplay.length > 0 && portsToDisplay.every(port =>+ selectedPorts?.has(generatePortKey(id, port))+ );+ const someSelected = portsToDisplay.some(port =>+ selectedPorts?.has(generatePortKey(id, port))+ );+ input.indeterminate = someSelected && !allSelected;+ }+ }}+ onChange={() => {+ const allSelected = portsToDisplay.every(port =>+ selectedPorts?.has(generatePortKey(id, port))+ );+ if (allSelected) {+ portsToDisplay.forEach(port => {+ if (selectedPorts?.has(generatePortKey(id, port))) {+ onToggleSelection?.(port, id);+ }+ });+ } else {+ onSelectAllPorts?.(portsToDisplay);+ }+ }}+ className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-slate-300 dark:border-slate-600 rounded cursor-pointer"+ />+ <span className="text-sm font-medium text-slate-700 dark:text-slate-300">+ Select All ({portsToDisplay.length})+ </span>+ </div>+ </div>+ )}+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">{portsToDisplay.map((port) => (<PortGridItem- key={- port.internal- ? `${id}-${port.container_id || port.app_id}-${port.host_port}-internal`- : `${id}-${port.host_ip}-${port.host_port}`- }+ key={generatePortKey(id, port)}port={port}searchTerm={searchTerm}actionFeedback={actionFeedback}onCopy={onCopy}onNote={onNote}onToggleIgnore={onToggleIgnore}+ onRename={onRename}serverId={id}serverUrl={serverUrl}forceOpenDetails={deepLinkContainerId && port.container_id === deepLinkContainerId}notifyOpenDetails={(cid) => onOpenContainerDetails && onOpenContainerDetails(cid)}notifyCloseDetails={() => onCloseContainerDetails && onCloseContainerDetails()}+ selectionMode={selectionMode}+ isSelected={selectedPorts?.has(generatePortKey(id, port))}+ onToggleSelection={onToggleSelection}/>))}- </div>+ </div>+ </>)}{portLayout === "table" && (<PortTable@@ -692,6 +779,7 @@ function ServerSectionComponent({onCopy={onCopy}onNote={onNote}onToggleIgnore={onToggleIgnore}+ onRename={onRename}sortConfig={sortConfig}onSort={(key) =>setSortConfig((prev) => ({@@ -705,6 +793,10 @@ function ServerSectionComponent({deepLinkContainerId={deepLinkContainerId}onOpenContainerDetails={onOpenContainerDetails}onCloseContainerDetails={onCloseContainerDetails}+ selectionMode={selectionMode}+ selectedPorts={selectedPorts}+ onToggleSelection={onToggleSelection}+ onSelectAllPorts={onSelectAllPorts}/>)}@@ -738,6 +830,7 @@ function ServerSectionComponent({<HiddenPortsDrawerhiddenPorts={hiddenPorts}onUnhide={(p) => onToggleIgnore(id, p)}+ onUnhideAll={(ports) => ports.forEach(p => onToggleIgnore(id, p))}serverId={id}/></div>diff --git a/frontend/src/components/server/ServiceRenameModal.jsx b/frontend/src/components/server/ServiceRenameModal.jsxnew file mode 100644index 0000000..75ba7e1--- /dev/null+++ b/frontend/src/components/server/ServiceRenameModal.jsx@@ -0,0 +1,163 @@+import React, { useState, useEffect } from "react";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogFooter,+ DialogTitle,+ DialogDescription,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Button } from "@/components/ui/button";+import { Label } from "@/components/ui/label";+import { Loader2, RotateCcw } from "lucide-react";++/**+ * Modal component for renaming service names+ * Allows users to set custom names and reset to original names+ */+export function ServiceRenameModal({+ isOpen,+ onClose,+ port,+ serverId,+ serverUrl,+ onSave,+ loading = false,+}) {+ const [customName, setCustomName] = useState("");+ const [isDirty, setIsDirty] = useState(false);++ useEffect(() => {+ if (isOpen && port) {+ setCustomName(port.customServiceName || port.owner || "");+ setIsDirty(false);+ }+ }, [isOpen, port]);++ useEffect(() => {+ if (port) {+ const currentName = port.customServiceName || port.owner || "";+ setIsDirty(customName !== currentName);+ }+ }, [customName, port]);++ const handleSave = () => {+ if (!port || !customName.trim()) return;++ onSave({+ serverId,+ hostIp: port.host_ip,+ hostPort: port.host_port,+ protocol: port.protocol,+ customName: customName.trim(),+ originalName: port.originalServiceName || port.owner,+ serverUrl,+ containerId: port.container_id,+ internal: port.internal || false,+ });+ };++ const handleReset = () => {+ if (!port) return;++ onSave({+ serverId,+ hostIp: port.host_ip,+ hostPort: port.host_port,+ protocol: port.protocol,+ customName: null,+ originalName: port.originalServiceName || port.owner,+ serverUrl,+ isReset: true,+ containerId: port.container_id,+ internal: port.internal || false,+ });+ };++ const handleKeyDown = (e) => {+ if (e.key === "Enter" && !e.shiftKey && isDirty && customName.trim()) {+ e.preventDefault();+ handleSave();+ }+ };++ if (!port) return null;++ const displayedServiceName = port.customServiceName || port.owner || "Unknown Service";+ const hasCustomName = !!port.customServiceName;+ const canReset = hasCustomName;+ const canSave = isDirty && customName.trim() && customName.trim() !== displayedServiceName;++ return (+ <Dialog open={isOpen} onOpenChange={onClose}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>Rename Service</DialogTitle>+ <DialogDescription>+ Customize the display name for this service on port {port.host_port}.+ </DialogDescription>+ </DialogHeader>++ <div className="space-y-4 py-4">+ <div className="space-y-2">+ <Label htmlFor="service-name">Service Name</Label>+ <Input+ id="service-name"+ value={customName}+ onChange={(e) => setCustomName(e.target.value)}+ onKeyDown={handleKeyDown}+ placeholder="Enter custom service name..."+ className="w-full"+ disabled={loading}+ autoFocus+ />+ {hasCustomName && (+ <p className="text-xs text-slate-500 dark:text-slate-400">+ Original: {port.originalServiceName || port.owner}+ </p>+ )}+ </div>+ </div>++ <DialogFooter className="flex-col sm:flex-row gap-2">+ <div className="flex gap-2 sm:order-1">+ <Button+ variant="outline"+ onClick={onClose}+ disabled={loading}+ >+ Cancel+ </Button>+ <Button+ onClick={handleSave}+ disabled={!canSave || loading}+ className="min-w-16"+ >+ {loading ? (+ <>+ <Loader2 className="h-4 w-4 mr-2 animate-spin" />+ Saving...+ </>+ ) : (+ "Save"+ )}+ </Button>+ </div>++ {canReset && (+ <Button+ variant="ghost"+ onClick={handleReset}+ disabled={loading}+ className="sm:order-0 text-slate-600 hover:text-slate-800 dark:text-slate-400 dark:hover:text-slate-200"+ >+ <RotateCcw className="h-4 w-4 mr-2" />+ Reset to Original+ </Button>+ )}+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}\ No newline at end of filediff --git a/frontend/src/lib/api/customServiceNames.js b/frontend/src/lib/api/customServiceNames.jsnew file mode 100644index 0000000..0219867--- /dev/null+++ b/frontend/src/lib/api/customServiceNames.js@@ -0,0 +1,160 @@+/**+ * API client for custom service name operations+ * Handles CRUD operations for renaming service names with database persistence+ */++/**+ * Saves a custom service name for a specific port+ * @param {string} serverId - The server ID+ * @param {string} hostIp - The host IP address+ * @param {number} hostPort - The host port number+ * @param {string} protocol - The protocol (tcp or udp)+ * @param {string} customName - The custom service name+ * @param {string} originalName - The original service name (for reset functionality)+ * @param {string} serverUrl - Optional server URL for peer servers+ * @param {string} containerId - Optional container ID for internal ports+ * @param {boolean} internal - Whether this is an internal port+ * @returns {Promise<Object>} Response from the API+ */+export async function saveCustomServiceName(serverId, hostIp, hostPort, protocol, customName, originalName, serverUrl = null, containerId = null, internal = false) {+ let targetUrl = "/api/custom-service-names";+ let requestServerId = serverId;++ if (serverId !== "local" && serverUrl) {+ targetUrl = `${serverUrl.replace(/\/+$/, "")}/api/custom-service-names`;+ requestServerId = "local";+ }++ const body = {+ server_id: requestServerId,+ host_ip: hostIp,+ host_port: hostPort,+ protocol: protocol,+ custom_name: customName,+ original_name: originalName,+ internal: internal,+ };++ if (containerId) {+ body.container_id = containerId;+ }++ const response = await fetch(targetUrl, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ });++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({ error: "Request failed" }));+ throw new Error(errorData.error || `HTTP ${response.status}: ${response.statusText}`);+ }++ return response.json();+}++/**+ * Deletes a custom service name for a specific port (resets to original)+ * @param {string} serverId - The server ID+ * @param {string} hostIp - The host IP address+ * @param {number} hostPort - The host port number+ * @param {string} protocol - The protocol (tcp or udp)+ * @param {string} serverUrl - Optional server URL for peer servers+ * @param {string} containerId - Optional container ID for internal ports+ * @param {boolean} internal - Whether this is an internal port+ * @returns {Promise<Object>} Response from the API+ */+export async function deleteCustomServiceName(serverId, hostIp, hostPort, protocol, serverUrl = null, containerId = null, internal = false) {+ let targetUrl = "/api/custom-service-names";+ let requestServerId = serverId;++ if (serverId !== "local" && serverUrl) {+ targetUrl = `${serverUrl.replace(/\/+$/, "")}/api/custom-service-names`;+ requestServerId = "local";+ }++ const body = {+ server_id: requestServerId,+ host_ip: hostIp,+ host_port: hostPort,+ protocol: protocol,+ internal: internal,+ };++ if (containerId) {+ body.container_id = containerId;+ }++ const response = await fetch(targetUrl, {+ method: "DELETE",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ });++ if (response.status === 404) {+ return { success: true, message: "Custom service name already deleted or did not exist" };+ }++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({ error: "Request failed" }));+ throw new Error(errorData.error || `HTTP ${response.status}: ${response.statusText}`);+ }++ return response.json();+}++/**+ * Retrieves all custom service names for a server+ * @param {string} serverId - The server ID+ * @param {string} serverUrl - Optional server URL for peer servers+ * @returns {Promise<Array>} Array of custom service names+ */+export async function getCustomServiceNames(serverId, serverUrl = null) {+ let targetUrl = `/api/custom-service-names?server_id=${serverId}`;++ if (serverId !== "local" && serverUrl) {+ targetUrl = `${serverUrl.replace(/\/+$/, "")}/api/custom-service-names?server_id=local`;+ }++ const response = await fetch(targetUrl);++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({ error: "Request failed" }));+ throw new Error(errorData.error || `HTTP ${response.status}: ${response.statusText}`);+ }++ return response.json();+}++/**+ * Performs batch operations on custom service names+ * @param {string} serverId - The server ID+ * @param {Array} operations - Array of operations {action: "set"|"delete", host_ip, host_port, custom_name?, original_name?}+ * @param {string} serverUrl - Optional server URL for peer servers+ * @returns {Promise<Object>} Response from the API+ */+export async function batchCustomServiceNames(serverId, operations, serverUrl = null) {+ let targetUrl = "/api/custom-service-names/batch";+ let requestServerId = serverId;++ if (serverId !== "local" && serverUrl) {+ targetUrl = `${serverUrl.replace(/\/+$/, "")}/api/custom-service-names/batch`;+ requestServerId = "local";+ }++ const response = await fetch(targetUrl, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ server_id: requestServerId,+ operations: operations,+ }),+ });++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({ error: "Request failed" }));+ throw new Error(errorData.error || `HTTP ${response.status}: ${response.statusText}`);+ }++ return response.json();+}\ No newline at end of filediff --git a/frontend/src/lib/api/notes.js b/frontend/src/lib/api/notes.jsnew file mode 100644index 0000000..51de1d1--- /dev/null+++ b/frontend/src/lib/api/notes.js@@ -0,0 +1,85 @@+/**+ * API client for notes operations+ * Handles CRUD operations for port notes with database persistence+ */++/**+ * Saves a note for a specific port+ * @param {string} serverId - The server ID+ * @param {string} hostIp - The host IP address+ * @param {number} hostPort - The host port number+ * @param {string} protocol - The protocol (tcp or udp)+ * @param {string} note - The note content+ * @param {string} serverUrl - Optional server URL for peer servers+ * @param {string} containerId - Optional container ID for internal ports+ * @param {boolean} internal - Whether this is an internal port+ * @returns {Promise<Object>} Response from the API+ */+export async function saveNote(serverId, hostIp, hostPort, protocol, note, serverUrl = null, containerId = null, internal = false) {+ let targetUrl = "/api/notes";+ let requestServerId = serverId;++ if (serverId !== "local" && serverUrl) {+ targetUrl = `${serverUrl.replace(/\/+$/, "")}/api/notes`;+ requestServerId = "local";+ }++ const body = {+ server_id: requestServerId,+ host_ip: hostIp,+ host_port: hostPort,+ protocol: protocol,+ note: note,+ internal: internal,+ };++ if (containerId) {+ body.container_id = containerId;+ }++ const response = await fetch(targetUrl, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ });++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({ error: "Request failed" }));+ throw new Error(errorData.error || `HTTP ${response.status}: ${response.statusText}`);+ }++ return response.json();+}++/**+ * Performs batch operations on notes+ * @param {string} serverId - The server ID+ * @param {Array} operations - Array of operations {action: "set"|"delete", host_ip, host_port, note?, container_id?}+ * @param {string} serverUrl - Optional server URL for peer servers+ * @returns {Promise<Object>} Response from the API+ */+export async function batchNotes(serverId, operations, serverUrl = null) {+ let targetUrl = "/api/notes/batch";+ let requestServerId = serverId;++ if (serverId !== "local" && serverUrl) {+ targetUrl = `${serverUrl.replace(/\/+$/, "")}/api/notes/batch`;+ requestServerId = "local";+ }++ const response = await fetch(targetUrl, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ server_id: requestServerId,+ operations: operations,+ }),+ });++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({ error: "Request failed" }));+ throw new Error(errorData.error || `HTTP ${response.status}: ${response.statusText}`);+ }++ return response.json();+}\ No newline at end of filediff --git a/frontend/src/lib/hooks/useLongPress.js b/frontend/src/lib/hooks/useLongPress.jsnew file mode 100644index 0000000..083732b--- /dev/null+++ b/frontend/src/lib/hooks/useLongPress.js@@ -0,0 +1,57 @@+import { useCallback, useRef } from 'react';++/**+ * Custom hook for long press detection+ * Handles both mouse and touch events for cross-platform support+ */+export function useLongPress(callback, { threshold = 500, onStart, onFinish, onCancel } = {}) {+ const timerRef = useRef();+ const isLongPressing = useRef(false);++ const start = useCallback(+ (event) => {+ const isRightClick = event.button === 2;+ if (isRightClick) return;++ onStart?.(event);+ isLongPressing.current = false;++ timerRef.current = setTimeout(() => {+ isLongPressing.current = true;+ callback(event);+ onFinish?.(event);+ }, threshold);+ },+ [callback, threshold, onStart, onFinish]+ );++ const clear = useCallback(+ (event, shouldTriggerOnCancel = true) => {+ clearTimeout(timerRef.current);+ if (shouldTriggerOnCancel && !isLongPressing.current) {+ onCancel?.(event);+ }+ },+ [onCancel]+ );++ const clickHandler = useCallback(+ (event) => {+ if (isLongPressing.current) {+ event.preventDefault();+ event.stopPropagation();+ isLongPressing.current = false;+ }+ },+ []+ );++ return {+ onMouseDown: start,+ onMouseUp: clear,+ onMouseLeave: clear,+ onTouchStart: start,+ onTouchEnd: clear,+ onClick: clickHandler,+ };+}\ No newline at end of filediff --git a/frontend/src/lib/hooks/useWhatsNew.js b/frontend/src/lib/hooks/useWhatsNew.jsindex 0a38703..4533d37 100644--- a/frontend/src/lib/hooks/useWhatsNew.js+++ b/frontend/src/lib/hooks/useWhatsNew.js@@ -148,7 +148,7 @@ export function useWhatsNew() {};initializeWhatsNew();- }, []);+ }, [isDismissed]);const getModalProps = () => {const version = newVersions.length > 1diff --git a/frontend/src/lib/utils.js b/frontend/src/lib/utils.jsindex 05b0227..7b35cba 100644--- a/frontend/src/lib/utils.js+++ b/frontend/src/lib/utils.js@@ -138,6 +138,7 @@ export function getSearchMatches(port, searchTerm) {return {hostPort: port.host_port.toString().includes(searchLower),owner: port.owner && port.owner.toLowerCase().includes(searchLower),+ customServiceName: port.customServiceName && port.customServiceName.toLowerCase().includes(searchLower),hostIp: port.host_ip && port.host_ip.includes(searchLower),target: port.target && port.target.includes && port.target.includes(searchLower),note: port.note && port.note.toLowerCase().includes(searchLower)diff --git a/frontend/src/lib/utils/portUtils.js b/frontend/src/lib/utils/portUtils.jsnew file mode 100644index 0000000..2b97084--- /dev/null+++ b/frontend/src/lib/utils/portUtils.js@@ -0,0 +1,26 @@+/**+ * Utility functions for port-related operations+ */++/**+ * Generates a unique key for a port selection+ * @param {string} serverId - The server ID+ * @param {Object} port - The port object+ * @returns {string} Unique port key+ */+export function generatePortKey(serverId, port) {+ const internalSuffix = port.internal ? '-internal' : '';+ return `${serverId}-${port.host_ip}-${port.host_port}-${port.container_id || ''}${internalSuffix}`;+}++/**+ * Generates display key for port (used for itemKey props)+ * @param {string} serverId - The server ID+ * @param {Object} port - The port object+ * @returns {string} Display key+ */+export function generatePortDisplayKey(serverId, port) {+ return port.internal+ ? `${serverId}-${port.container_id || port.app_id}-${port.host_port}-internal`+ : `${serverId}-${port.host_ip}-${port.host_port}`;+}\ No newline at end of filediff --git a/package.json b/package.jsonindex c4cbc7f..436ec9d 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "portracker",- "version": "1.0.6",+ "version": "1.0.7","description": "A multi-platform port-tracking dashboard","main": "backend/index.js","scripts": {