diff --git a/CLAUDE.md b/CLAUDE.md index cbac3a3..0af3ee7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -311,7 +311,11 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li re-read the stored mappings under that lock; unchanged forwards are kept with their connections. Opened after every connect and on a save while connected; closed by every `tunnels::close*` path. A failing mapping is a `workspace-warning` (`topic: "ports"`), and so is a Running project - whose mappings could not be opened at all (no tunnel / tunnel replaced) — never silent. In the + whose mappings could not be opened at all (no tunnel / tunnel replaced) — never silent; a stored + row missing a port (0) is skipped with one too ("incomplete, both ports are needed"). + `PortMappingsEditor` saves only complete rows (half-filled ones stay local, marked), adopts a + stored value only when it differs by value and no field in it has focus, and uses word + placeholders — a "8080" placeholder once read as a typed 8080 → 8080 that was saved as 0 → 0. In the workspace each connection picks `127.0.0.1` or `[::1]` from `/proc/net/tcp{,6}` (`tunnel::mapping_command`; no probe connection), and the first socat "Connection refused" per mapping is a `ports` warning ("nothing is listening on port N"). An idle listener makes no diff --git a/app/src-tauri/src/host/port_forwards.rs b/app/src-tauri/src/host/port_forwards.rs index 21af174..8d689d5 100644 --- a/app/src-tauri/src/host/port_forwards.rs +++ b/app/src-tauri/src/host/port_forwards.rs @@ -150,12 +150,23 @@ fn mapping_problem(m: &PortMapping, gateway_sidecar: bool) -> Option { None } -/// A row the editor saved before both its ports were typed (the editor -/// saves on blur): nothing to check or forward yet, and nothing to say. +/// A row stored without both its ports (an older editor saved a new row as +/// 0 → 0 before anything was typed): nothing to check on save, and nothing +/// to forward — but a connect says so ([`incomplete_warning`]), never silent. fn incomplete(m: &PortMapping) -> bool { m.host_port == 0 || m.container_port == 0 } +/// The `ports` warning line for a stored row a connect skips as incomplete. +pub fn incomplete_warning(m: &PortMapping) -> String { + let port = |p: u16| if p == 0 { "?".to_string() } else { p.to_string() }; + format!( + "{} → {}: incomplete, both ports are needed", + port(m.host_port), + port(m.container_port) + ) +} + /// An AWS project's port mappings, checked in full: TCP only, no reserved /// port (the browser view's two ranges, the agent's port, the gateway /// sidecar's when it runs), and no host port twice. The first problem, @@ -266,8 +277,10 @@ pub async fn open_latest( let mut results: Vec = Vec::new(); let mut wanted: Vec<(usize, u16, u16)> = Vec::new(); let mut taken = HashSet::new(); - for m in mappings.iter().filter(|m| !incomplete(m)) { - let error = if let Some(problem) = mapping_problem(m, gateway_sidecar) { + for m in &mappings { + let error = if incomplete(m) { + Some(incomplete_warning(m)) + } else if let Some(problem) = mapping_problem(m, gateway_sidecar) { Some(problem) } else if !taken.insert(m.host_port) { Some(format!( diff --git a/app/src-tauri/src/host/port_forwards/tests.rs b/app/src-tauri/src/host/port_forwards/tests.rs index 7b60573..7588de5 100644 --- a/app/src-tauri/src/host/port_forwards/tests.rs +++ b/app/src-tauri/src/host/port_forwards/tests.rs @@ -198,7 +198,8 @@ async fn udp_reserved_and_duplicate_mappings_are_refused_per_mapping() { ) .await; let errors: Vec> = results.iter().map(|r| r.error.as_deref()).collect(); - assert_eq!(errors.len(), 6, "an unfinished row is skipped: {errors:?}"); + assert_eq!(errors.len(), 7, "{errors:?}"); + assert_eq!(errors[6], Some("? → ?: incomplete, both ports are needed"), "skipped, not silently"); assert!(errors[0].unwrap().contains("only TCP"), "{errors:?}"); assert!(errors[1].is_none()); assert!(errors[2].unwrap().contains("another mapping"), "{errors:?}"); @@ -435,6 +436,26 @@ async fn a_running_project_whose_mappings_cannot_open_is_never_silent() { assert_eq!(open_for_project(&store, &p, None).await, None); } +#[tokio::test] +async fn a_connect_warns_about_an_incomplete_row_and_opens_the_rest() { + use crate::models::ProjectStatus; + // The reported case: an older editor stored a new row as 0 → 0. The + // connect used to skip it in silence. + let p = pid("incomplete"); + let port = free_port(); + let (_d, store) = + aws_project_in_store(&p, ProjectStatus::Stopped, vec![tcp(0, 0), tcp(port, 8080), tcp(9000, 0)]); + let (_target, _fake, _) = connected_agent(&p).await; + store.update_status(&p, ProjectStatus::Running).unwrap(); + let w = open_for_project(&store, &p, None).await.expect("a ports warning"); + assert_eq!( + w, + "? → ?: incomplete, both ports are needed\n9000 → ?: incomplete, both ports are needed" + ); + assert_eq!(open_ports(&p), vec![port]); + tunnels::close(&p).await; +} + #[tokio::test] async fn a_start_opens_a_listener_for_a_mapping_saved_before_it() { use crate::models::ProjectStatus; diff --git a/app/src/components/projects/PortMappingsEditor.test.tsx b/app/src/components/projects/PortMappingsEditor.test.tsx new file mode 100644 index 0000000..590b063 --- /dev/null +++ b/app/src/components/projects/PortMappingsEditor.test.tsx @@ -0,0 +1,130 @@ +import { describe, it, expect, vi } from "vitest"; +import { render, screen, fireEvent, act } from "@testing-library/react"; +import PortMappingsEditor from "./PortMappingsEditor"; +import type { PortMapping } from "../../lib/types"; + +const tcp = (host_port: number, container_port: number): PortMapping => ({ + host_port, + container_port, + protocol: "tcp", +}); + +function setup(initial: PortMapping[], extra: { tcpOnly?: boolean } = {}) { + const onSave = vi.fn().mockResolvedValue(true); + const view = render( + , + ); + const rerender = (next: PortMapping[]) => + view.rerender( + , + ); + return { onSave, rerender }; +} + +const host = (n = 1) => screen.getByLabelText(`Host port ${n}`) as HTMLInputElement; +const container = (n = 1) => screen.getByLabelText(`Container port ${n}`) as HTMLInputElement; + +function type(el: HTMLInputElement, value: string) { + act(() => el.focus()); + fireEvent.change(el, { target: { value } }); +} + +describe("PortMappingsEditor", () => { + it("keeps typed ports when the project refreshes mid-edit (the reported 0/0 save)", () => { + // A stored half-row, as the old "+ Add" saved it, then a project refresh + // (status event, save response, list reload) hands over a new-but-equal + // array while the user is typing. + const { onSave, rerender } = setup([tcp(0, 0)]); + type(host(), "8080"); + rerender([tcp(0, 0)]); + type(container(), "8080"); + rerender([tcp(0, 0)]); + expect(host().value).toBe("8080"); + expect(container().value).toBe("8080"); + fireEvent.blur(container()); + expect(onSave).toHaveBeenLastCalledWith([tcp(8080, 8080)]); + }); + + it("keeps typed ports when its own earlier save's response arrives mid-edit", () => { + const { onSave, rerender } = setup([]); + fireEvent.click(screen.getByRole("button", { name: /add port mapping/i })); + type(host(), "8080"); + fireEvent.blur(host()); + type(container(), "80"); + // A stale echo of an older stored value must not replace the edit in focus. + rerender([]); + type(container(), "8080"); + fireEvent.blur(container()); + expect(onSave).toHaveBeenLastCalledWith([tcp(8080, 8080)]); + expect(container().value).toBe("8080"); + }); + + it("does not save a newly added empty row", () => { + const { onSave } = setup([]); + fireEvent.click(screen.getByRole("button", { name: /add port mapping/i })); + expect(onSave).not.toHaveBeenCalled(); + expect(host()).toHaveFocus(); + expect(screen.getByText(/fill in both ports/i)).toBeInTheDocument(); + }); + + it("does not present an empty row as a filled-in mapping (no port-number placeholder)", () => { + // The reported case: the empty row's "8080" placeholders read as 8080 → 8080. + setup([]); + fireEvent.click(screen.getByRole("button", { name: /add port mapping/i })); + for (const el of [host(), container()]) { + expect(el.value).toBe(""); + expect(el.placeholder).not.toMatch(/\d/); + } + expect(screen.getByText(/isn't saved or active/i)).toBeInTheDocument(); + }); + + it("never saves a half-filled row, and saves it once both ports are in", () => { + const { onSave } = setup([tcp(3000, 3000)]); + fireEvent.click(screen.getByRole("button", { name: /add port mapping/i })); + type(host(2), "8080"); + fireEvent.blur(host(2)); + expect(onSave).not.toHaveBeenCalled(); + expect(screen.getByText(/fill in both ports/i)).toBeInTheDocument(); + type(container(2), "9090"); + fireEvent.blur(container(2)); + expect(onSave).toHaveBeenLastCalledWith([tcp(3000, 3000), tcp(8080, 9090)]); + expect(screen.queryByText(/fill in both ports/i)).not.toBeInTheDocument(); + }); + + it("shows a stored incomplete row as incomplete", () => { + setup([tcp(0, 0), tcp(8080, 8080)]); + expect(screen.getAllByText(/fill in both ports/i)).toHaveLength(1); + expect(host(1).value).toBe(""); + }); + + it("refuses an out-of-range port without saving it", () => { + const { onSave } = setup([]); + fireEvent.click(screen.getByRole("button", { name: /add port mapping/i })); + type(host(), "70000"); + type(container(), "80"); + fireEvent.blur(container()); + expect(onSave).not.toHaveBeenCalled(); + expect(screen.getByText(/1 and 65535/)).toBeInTheDocument(); + }); + + it("takes a changed stored value once the editor is not being edited", () => { + const { rerender } = setup([tcp(3000, 3000)]); + rerender([tcp(4000, 4000)]); + expect(host().value).toBe("4000"); + }); + + it("removing a row saves the rest; the protocol saves at once (Docker keeps UDP)", () => { + const { onSave } = setup([tcp(3000, 3000), tcp(4000, 4000)]); + fireEvent.change(screen.getByLabelText("Protocol 2"), { target: { value: "udp" } }); + expect(onSave).toHaveBeenLastCalledWith([tcp(3000, 3000), { ...tcp(4000, 4000), protocol: "udp" }]); + fireEvent.click(screen.getByRole("button", { name: "Remove port mapping 1" })); + expect(onSave).toHaveBeenLastCalledWith([{ ...tcp(4000, 4000), protocol: "udp" }]); + }); + + it("does not save when nothing changed", () => { + const { onSave } = setup([tcp(3000, 3000)]); + act(() => host().focus()); + fireEvent.blur(host()); + expect(onSave).not.toHaveBeenCalled(); + }); +}); diff --git a/app/src/components/projects/PortMappingsEditor.tsx b/app/src/components/projects/PortMappingsEditor.tsx index c425040..a11d249 100644 --- a/app/src/components/projects/PortMappingsEditor.tsx +++ b/app/src/components/projects/PortMappingsEditor.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import type { PortMapping } from "../../lib/types"; import Button from "../ui/Button"; import { monoInputClass, selectClass } from "../ui/Field"; @@ -12,43 +12,158 @@ interface Props { onSave: (mappings: PortMapping[]) => Promise; } +/** One row as typed: ports stay text until they are valid, so a half-typed + * row is never turned into a 0. */ +interface Row { + key: number; + host: string; + container: string; + protocol: string; +} + +/** Placeholders are words, not port numbers: a "8080" placeholder in an + * empty row read as a filled-in 8080 → 8080 mapping that was never typed. */ +const placeholderClass = "placeholder:italic placeholder:text-[var(--text-disabled)]"; + +function parsePort(text: string): number | null { + if (!/^\d+$/.test(text.trim())) return null; + const n = Number(text.trim()); + return n >= 1 && n <= 65535 ? n : null; +} + +/** Why a row is not a mapping yet, or `null` when it is one. */ +export function rowProblem(row: Pick): string | null { + if (row.host.trim() === "" || row.container.trim() === "") return "Fill in both ports"; + if (parsePort(row.host) === null || parsePort(row.container) === null) { + return "Ports must be whole numbers between 1 and 65535"; + } + return null; +} + +/** The rows that are complete mappings — the only ones ever saved. */ +function completeMappings(rows: Row[]): PortMapping[] { + return rows.flatMap((r) => { + const host_port = parsePort(r.host); + const container_port = parsePort(r.container); + return host_port !== null && container_port !== null && rowProblem(r) === null + ? [{ host_port, container_port, protocol: r.protocol }] + : []; + }); +} + +let nextKey = 1; +const portText = (n: number) => (n > 0 ? String(n) : ""); +function toRows(mappings: PortMapping[]): Row[] { + return mappings.map((m) => ({ + key: nextKey++, + host: portText(m.host_port), + container: portText(m.container_port), + protocol: m.protocol, + })); +} + export default function PortMappingsEditor({ - portMappings: initial, + portMappings: stored, disabled, disabledReason, tcpOnly = false, onSave, }: Props) { - const [mappings, setMappings] = useState(initial); + const [rows, setRowsState] = useState(() => toRows(stored)); + // The latest rows, for blur handlers that run before a re-render. + const rowsRef = useRef(rows); + const setRows = (next: Row[]) => { + rowsRef.current = next; + setRowsState(next); + }; + + // What is stored, as this editor last loaded or saved it. A project refresh + // hands over a new array on every update (status events, save responses, + // list reloads); only a value that differs from this is a real change. + const storedKey = JSON.stringify(stored); + const syncedKey = useRef(storedKey); + const wrapper = useRef(null); + const [focusLeft, setFocusLeft] = useState(0); + const focusHost = useRef(null); useEffect(() => { - setMappings(initial); - }, [initial]); + if (storedKey === syncedKey.current) return; + // Never replace what the user is typing; this runs again when focus + // leaves the editor. + if (wrapper.current?.contains(document.activeElement)) return; + syncedKey.current = storedKey; + const fresh = toRows(JSON.parse(storedKey) as PortMapping[]); + // Rows still being filled in are not stored; keep them. + const drafts = rowsRef.current.filter((r) => rowProblem(r) !== null); + const freshKeys = new Set(fresh.map((r) => `${r.host}|${r.container}`)); + setRows([...fresh, ...drafts.filter((r) => !freshKeys.has(`${r.host}|${r.container}`))]); + }, [storedKey, focusLeft]); - const updatePort = ( - index: number, - field: "host_port" | "container_port", - value: string, - ) => { - const updated = [...mappings]; - const num = parseInt(value, 10); - updated[index] = { ...updated[index], [field]: isNaN(num) ? 0 : num }; - setMappings(updated); + useEffect(() => { + if (focusHost.current === null) return; + const el = wrapper.current?.querySelector( + `[data-row="${focusHost.current}"][data-field="host"]`, + ); + focusHost.current = null; + el?.focus(); + }, [rows]); + + /** Save the complete rows, if they differ from what is stored. */ + const commit = (next: Row[]) => { + const mappings = completeMappings(next); + const key = JSON.stringify(mappings); + if (key === syncedKey.current) return; + syncedKey.current = key; + void onSave(mappings); + }; + + const edit = (index: number, field: "host" | "container", value: string) => { + const next = [...rowsRef.current]; + next[index] = { ...next[index], [field]: value }; + setRows(next); + }; + + const portInput = (row: Row, i: number, field: "host" | "container") => { + const value = row[field]; + const missing = rowProblem(row) !== null && parsePort(value) === null; + return ( + edit(i, field, e.target.value)} + onBlur={() => commit(rowsRef.current)} + placeholder={field === "host" ? "Host port" : "Container port"} + aria-label={`${field === "host" ? "Host" : "Container"} port ${i + 1}`} + aria-invalid={missing || undefined} + aria-describedby={rowProblem(row) ? `pm-problem-${row.key}` : undefined} + data-row={row.key} + data-field={field} + disabled={disabled} + className={`w-[28%] ${monoInputClass} ${placeholderClass}`} + /> + ); }; return ( -
+
{ + if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setFocusLeft((n) => n + 1); + }} + > {disabled && disabledReason && (

{disabledReason}

)} - {mappings.length === 0 && ( + {rows.length === 0 && (

No port mappings configured.

)} - {mappings.length > 0 && ( + {rows.length > 0 && (
Host port Container port @@ -57,71 +172,58 @@ export default function PortMappingsEditor({
)} - {mappings.map((pm, i) => ( -
- updatePort(i, "host_port", e.target.value)} - onBlur={() => onSave(mappings)} - placeholder="8080" - aria-label={`Host port ${i + 1}`} - disabled={disabled} - className={`w-[28%] ${monoInputClass}`} - /> - updatePort(i, "container_port", e.target.value)} - onBlur={() => onSave(mappings)} - placeholder="8080" - aria-label={`Container port ${i + 1}`} - disabled={disabled} - className={`w-[28%] ${monoInputClass}`} - /> - - -
- ))} + {rows.map((row, i) => { + const problem = rowProblem(row); + return ( +
+
+ {portInput(row, i, "host")} + {portInput(row, i, "container")} + + +
+ {problem && ( +

+ ⚠ {problem} — this mapping isn't saved or active. +

+ )} +
+ ); + })}