Skip to content

Auto-select next free serve port when default (4096) is taken#7

Merged
mtsfoni merged 2 commits intomainfrom
copilot/fix-serve-next-free-port
Mar 12, 2026
Merged

Auto-select next free serve port when default (4096) is taken#7
mtsfoni merged 2 commits intomainfrom
copilot/fix-serve-next-free-port

Conversation

Copy link
Contributor

Copilot AI commented Mar 12, 2026

When --serve-port is omitted and port 4096 is already bound on the host, construct would silently fail when Docker tried to publish the port. This adds a best-effort port scan to pick the next free port and warn the user.

Behaviour

  • Only applies when --serve-port is not specified (explicit ports are used as-is)
  • Scans 127.0.0.1:<port> from 4096 upward, up to 100 ports
  • Prints a yellow diagnostic to stderr if the default was unavailable:
    construct: port 4096 is already in use; using port 4097 instead
    
  • Returns an error if the entire 100-port range is exhausted (uncommon; instructs user to pass --serve-port explicitly)

Changes

  • internal/runner/runner.goisPortFree(port) probes a loopback TCP bind; findFreePort(start) scans up to 100 ports and returns 0 on exhaustion; Run uses these when cfg.ServePort == 0
  • internal/runner/runner_test.go — 5 new unit tests covering free/busy detection and range exhaustion
  • docs/spec/serve-mode.md — documents the auto-fallback behaviour and 100-port search cap
  • CHANGELOG.md — entry under [Unreleased]

Note: There is an inherent TOCTOU race between the port check and Docker binding, but it is negligible in practice — the probe runs immediately before container start.

Original prompt

This section details on the original issue you should resolve

<issue_title>if we call serve without specified port and the port is taken, take the next free higher port.</issue_title>
<issue_description>Don't forget to check/update specs. And Changelog.

It should print that the port was taken and another port was chosen. Maybe yellow and in the error output.</issue_description>

Comments on the Issue (you are @copilot in this section)


💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

Co-authored-by: mtsfoni <80639729+mtsfoni@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix serve command to use next available port Auto-select next free serve port when default (4096) is taken Mar 12, 2026
@mtsfoni mtsfoni marked this pull request as ready for review March 12, 2026 07:17
@mtsfoni mtsfoni merged commit 0dae8af into main Mar 12, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

if we call serve without specified port and the port is taken, take the next free higher port.

2 participants