Compare commits

..
Author SHA1 Message Date
shadowdaoandClaude Opus 5.5 42c329ed24 fix(ports): keep typed port mappings; never save or skip a half-filled row silently
Secret Scan / scan (push) Successful in 31s
Build App (Preview) / compute-version (pull_request) Successful in 5s
Build App (Preview) / create-release (pull_request) Successful in 3s
Build App (Preview) / build-windows (pull_request) In progress
Secret Scan / scan (pull_request) Successful in 12s
Build App (Preview) / build-linux (pull_request) In progress
Build App (Preview) / build-macos (pull_request) Successful in 7m2s
Build App (Preview) / test (pull_request) Successful in 8m21s
The empty row's "8080" placeholders looked like a typed 8080 -> 8080, and
+ Add saved it as 0 -> 0 at once; a project refresh with a new-but-equal
array also reset in-progress edits. The editor now keeps ports as text,
saves only complete rows, marks incomplete ones inline, uses word
placeholders, and resyncs only on a by-value change while unfocused. A
connect reports a stored incomplete row as a ports warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 14:37:37 -08:00
5 changed files with 354 additions and 84 deletions

No files matched your search

+5 -1
View File
@@ -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
+17 -4
View File
@@ -150,12 +150,23 @@ fn mapping_problem(m: &PortMapping, gateway_sidecar: bool) -> Option<String> {
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<PortForwardResult> = 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!(
+22 -1
View File
@@ -198,7 +198,8 @@ async fn udp_reserved_and_duplicate_mappings_are_refused_per_mapping() {
)
.await;
let errors: Vec<Option<&str>> = 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;
@@ -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(
<PortMappingsEditor portMappings={initial} disabled={false} onSave={onSave} {...extra} />,
);
const rerender = (next: PortMapping[]) =>
view.rerender(
<PortMappingsEditor portMappings={next} disabled={false} onSave={onSave} {...extra} />,
);
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();
});
});
@@ -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<unknown>;
}
/** 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<Row, "host" | "container">): 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<PortMapping[]>(initial);
const [rows, setRowsState] = useState<Row[]>(() => 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<HTMLDivElement>(null);
const [focusLeft, setFocusLeft] = useState(0);
const focusHost = useRef<number | null>(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<HTMLInputElement>(
`[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 (
<input
type="text"
inputMode="numeric"
value={value}
onChange={(e) => 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 (
<div className="space-y-2">
<div
ref={wrapper}
className="space-y-2"
onBlur={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setFocusLeft((n) => n + 1);
}}
>
{disabled && disabledReason && (
<p className="px-2 py-1.5 bg-[var(--warning-muted)] border border-[var(--warning)]/30 rounded-[var(--radius-control)] text-xs text-[var(--warning)]">
{disabledReason}
</p>
)}
{mappings.length === 0 && (
{rows.length === 0 && (
<p className="text-xs text-[var(--text-secondary)]">No port mappings configured.</p>
)}
{mappings.length > 0 && (
{rows.length > 0 && (
<div className="flex gap-2 items-center text-xs text-[var(--text-secondary)] px-0.5">
<span className="w-[28%]">Host port</span>
<span className="w-[28%]">Container port</span>
@@ -57,71 +172,58 @@ export default function PortMappingsEditor({
</div>
)}
{mappings.map((pm, i) => (
<div key={i} className="flex gap-2 items-center">
<input
type="number"
min="1"
max="65535"
value={pm.host_port || ""}
onChange={(e) => updatePort(i, "host_port", e.target.value)}
onBlur={() => onSave(mappings)}
placeholder="8080"
aria-label={`Host port ${i + 1}`}
disabled={disabled}
className={`w-[28%] ${monoInputClass}`}
/>
<input
type="number"
min="1"
max="65535"
value={pm.container_port || ""}
onChange={(e) => updatePort(i, "container_port", e.target.value)}
onBlur={() => onSave(mappings)}
placeholder="8080"
aria-label={`Container port ${i + 1}`}
disabled={disabled}
className={`w-[28%] ${monoInputClass}`}
/>
<select
value={pm.protocol}
aria-label={`Protocol ${i + 1}`}
onChange={(e) => {
const updated = [...mappings];
updated[i] = { ...updated[i], protocol: e.target.value };
setMappings(updated);
onSave(updated);
}}
disabled={disabled}
className={`w-[22%] ${selectClass}`}
>
<option value="tcp">TCP</option>
{(!tcpOnly || pm.protocol === "udp") && <option value="udp">UDP</option>}
</select>
<Button
variant="danger"
disabled={disabled}
aria-label={`Remove port mapping ${i + 1}`}
onClick={() => {
const updated = mappings.filter((_, j) => j !== i);
setMappings(updated);
onSave(updated);
}}
>
Remove
</Button>
</div>
))}
{rows.map((row, i) => {
const problem = rowProblem(row);
return (
<div key={row.key} className="space-y-1">
<div className="flex gap-2 items-center">
{portInput(row, i, "host")}
{portInput(row, i, "container")}
<select
value={row.protocol}
aria-label={`Protocol ${i + 1}`}
onChange={(e) => {
const next = [...rowsRef.current];
next[i] = { ...next[i], protocol: e.target.value };
setRows(next);
commit(next);
}}
disabled={disabled}
className={`w-[22%] ${selectClass}`}
>
<option value="tcp">TCP</option>
{(!tcpOnly || row.protocol === "udp") && <option value="udp">UDP</option>}
</select>
<Button
variant="danger"
disabled={disabled}
aria-label={`Remove port mapping ${i + 1}`}
onClick={() => {
const next = rowsRef.current.filter((_, j) => j !== i);
setRows(next);
commit(next);
}}
>
Remove
</Button>
</div>
{problem && (
<p id={`pm-problem-${row.key}`} className="text-xs text-[var(--warning)] px-0.5">
⚠ {problem} — this mapping isn't saved or active.
</p>
)}
</div>
);
})}
<Button
disabled={disabled}
onClick={() => {
const updated = [
...mappings,
{ host_port: 0, container_port: 0, protocol: "tcp" },
];
setMappings(updated);
onSave(updated);
// Kept here until both ports are filled in: an empty row is never
// saved (it used to be stored as 0 → 0 and silently skipped).
const row: Row = { key: nextKey++, host: "", container: "", protocol: "tcp" };
focusHost.current = row.key;
setRows([...rowsRef.current, row]);
}}
>
+ Add port mapping