feat: [ENG-2857] surface port-in-use error in brv webui
Summary
- Replace the generic
Failed to get web UI port. Use \brv restart`...with a specific message that points the user atbrv webui --portwhen the Web UI port (default 7700) is held by another process. Same guidance applies whether the conflict shows up at daemon boot (webui:getPort) or mid-run via--port(webui:setPort`). - New
WebUiPortInUseErrorthrown byWebUiServeronEADDRINUSE. Daemon catches it, tracks the failure, and propagates a typedreasonover the transport instead of swallowing or throwing a plainError. - New
src/shared/transport/events/webui-events.tswithWebuiEventsconstant and discriminated-union response types replacing the inline{port?: number}shapes — TypeScript now narrows the CLI branches automatically. - Daemon log entries tightened so user-actionable guidance (
--port,BRV_WEBUI_PORT) lives only in the CLI message — single source of truth.
Test plan
- [x]
npm run typecheck— passes - [x]
npx eslint src/— 0 errors on touched files - [x]
npx mocha "test/unit/core/domain/errors/webui-error.test.ts" "test/unit/infra/webui/**/*.test.ts"— 21 passing - [x] Manual: hog
127.0.0.1:7700, run./bin/run.js webui→ boot-conflict message fires - [x] Manual: hog
127.0.0.1:9090, run./bin/run.js webui -p 9090→ setPort-conflict message fires - [x] Manual: recovery — after boot conflict,
brv webui --port <free>clears the failure state - [x] Manual: regression — daemon spawn failure still routes through
formatConnectionError(verified withBRV_IAM_BASE_URL='' ./bin/run.js webui)
Claude finished @ncnthien's task in 5m 18s —— View job
Claude PR Review — feat: [ENG-2857] surface port-in-use error in brv webui
- [x] Read PR diff and understand scope
- [x] Review
src/server/core/domain/errors/webui-error.ts - [x] Review
src/server/infra/webui/webui-server.ts - [x] Review
src/server/infra/daemon/brv-server.ts - [x] Review
src/oclif/commands/webui.ts - [x] Review
src/shared/transport/events/webui-events.ts - [x] Review tests
- [x] Post inline comments for findings
- [x] Post summary with score
Summary
Overall: 4 / 5 — Solid, well-scoped UX improvement with proper typed errors and a clean discriminated-union transport contract. One real bug in the setPort failure path (misleading log + stale state) and a handful of small consistency/design polish items, all called out inline.
Highlights (what's good)
- praise: Typed
WebUiPortInUseErrorcarrying the conflictingportcleanly replaces ad-hoc string matching at the daemon boundary, with handlers inbrv-server.tstranslating it into a transport-friendly discriminated response. - praise: Splitting
webui-events.tsout of inline{port?: number}shapes is the right move — single source of truth, narrowing works, and the file slots neatly intoAllEventGroups. - praise: Tests cover the new behavior end-to-end (port-in-use rejection, double-start guard, idempotent stop) and the error class is unit-tested.
- praise: User-actionable guidance (
--port,BRV_WEBUI_PORT) lives only in the CLI message — daemon logs stay terse. Good single-source-of-truth discipline.
Findings (see inline comments)
| # | File | Severity | Issue |
|---|---|---|---|
| 1 | src/server/infra/daemon/brv-server.ts:660–672 |
issue | setPort stops the previous webui server before attempting the new port; on port_in_use the log says "keeping previous configuration" but in reality the daemon is now left with no Web UI running. Plus webuiBootFailure is not cleared on non-EADDRINUSE failures, causing stale port_in_use responses to later getPort calls. |
| 2 | src/server/infra/webui/webui-server.ts:32 |
nit | "Already running" branch throws a plain Error while EADDRINUSE throws WebUiPortInUseError — inconsistent with the typed-error story. |
| 3 | src/oclif/commands/webui.ts:56–65 |
suggestion (style) | resolvePortOrExit doesn't use return this.error(...) like the rest of the file. Also: not_started branch routes the user to brv restart with no log breadcrumb. |
| 4 | src/shared/transport/events/webui-events.ts:6–15 |
suggestion (design) | Implicit discriminant ('port' in result) is fragile; a status: 'ok' | 'port_in_use' | 'not_started' field would survive future success variants. |
| 5 | test/unit/infra/webui/webui-server.test.ts:38–66 |
nit | WebUiServer doesn't clear this.httpServer after the EADDRINUSE rejection — leaked handle until GC. Worth fixing in webui-server.ts and asserting the reset in this test. |
Other notes (no inline)
- Pre-existing:
setupFeatureHandlers({ webuiPort: webuiServer?.getPort() })atbrv-server.ts:733snapshots the port at startup, so a successfulwebui:setPortdoesn't propagate the new port intoPushHandler/StatusHandlerreview URLs. Not introduced by this PR — flagging for follow-up. - The
'error'listener onhttpServer(webui-server.ts:38) isn't removed afterlisten()resolves; post-startup TCP errors will hit a Promise that's already settled. Pre-existing, harmless today, mentioned for completeness.
Verification
- Inspected the diff against
origin/main. Confirmed no other internal call sites consumewebui:getPort/webui:setPortstrings (only the event constants inwebui-events.ts), so the response-shape change is safe. - Did not run typecheck/lint/tests in this review (read-only review). — Branch: feat/ENG-2857
Claude finished @ncnthien's task in 4m 25s —— View job
Claude PR Review — feat: [ENG-2857] surface port-in-use error in brv webui (round 2)
- [x] Read PR diff (commits since prior review)
- [x] Verify prior findings addressed (status discriminator, typed already-running, stale state)
- [x] Re-review
webui-error.ts - [x] Re-review
webui-server.ts(httpServer reset, already-running error type) - [x] Re-review
brv-server.ts(setPort stale-state + log fix) - [x] Re-review
webui.ts(status discriminator usage) - [x] Re-review
webui-events.ts(discriminator design) - [x] Re-review tests
- [x] Post inline comments + summary
Summary
Overall: 4 / 5 — Round 1 feedback is almost fully addressed: explicit status discriminator is in, WebUiServerAlreadyRunningError replaces the plain Error, the misleading "keeping previous configuration" log is now accurate, and webuiBootFailure no longer goes stale on non-EADDRINUSE failures. One real regression introduced by the round-1 leak fix in webui-server.ts, and the deeper UX concern on setPort (probe-first) is still outstanding. Score holds at 4 because the new regression is a fairly narrow edge case.
What was addressed (prior round)
- praise (resolved):
WebUiServerAlreadyRunningErrornow thrown in the "already running" branch — typed-error story is consistent (webui-server.ts:32). - praise (resolved):
resolvePortOrExitnow usesreturn this.error(...)uniformly across all three branches (webui.ts:57–64). Reads cleanly. - praise (resolved): Explicit
status: 'ok' | 'port_in_use' | 'not_started'discriminator replaces the implicit'port' in resultnarrowing (webui-events.ts:6–15). Survives future success variants. - praise (resolved, half): Round-1 finding on
setPort— misleadingkeeping previous configurationlog is now accurate (Web UI unavailable), andwebuiBootFailureis cleared on both success and non-EADDRINUSE failure sogetPortno longer returns stale boot-time port info (brv-server.ts:660–675). - praise (resolved): Tests updated for
WebUiServerAlreadyRunningError; newwebui-error.test.tscovers the typed errors.
Findings this round (see inline comments)
| # | File | Severity | Issue |
|---|---|---|---|
| 1 | src/server/infra/webui/webui-server.ts:39 |
issue (correctness, blocking) | The new this.httpServer = undefined line lives inside a persistent 'error' listener. Post-startup errors will null httpServer while running=true, wedging stop() (which guards on !this.httpServer). Gate the clear behind a resolved flag, or use once('error', ...) for the startup phase only. |
| 2 | src/server/infra/daemon/brv-server.ts:661–672 |
suggestion (non-blocking) | Partial follow-up from round-1. Stale-state + log fixes are in, but the "probe new port before stopping old server" half wasn't picked up. Users running brv webui --port <busy> still lose their working Web UI on the previous port. Probe-first is strictly better; happy to defer. |
Other notes (no inline, pre-existing)
setupFeatureHandlers({webuiPort: webuiServer?.getPort()})at brv-server.ts:734 still snapshots the port at startup. A successfulwebui:setPortdoes not propagate the new port intoPushHandler/StatusHandlerreview URLs. Same call site as round 1 — flagging for follow-up, not introduced here.
Verification
- Inspected the round-2 diff (commit
7045f28) and the current state of every changed file. Searched for any remaining inlinewebui:getPort/webui:setPortstring literals outsidewebui-events.ts— none. Searched for stale'port' in resultnarrowings — none. - Did not run typecheck / lint / test suite (read-only review). PR description states all three pass on the author's machine. — Branch: feat/ENG-2857
Claude finished @ncnthien's task in 1m 57s —— View job
Claude PR Review — feat: [ENG-2857] surface port-in-use error in brv webui (round 3)
- [x] Read latest diff (commit
3b3896d) - [x] Verify round-2 wedge fix in
webui-server.ts(resolved-flag gating) - [x] Verify new unit test asserts post-startup
'error'does NOT clearhttpServer - [x] Re-check
brv-server.tssetPort path and other touched files for regressions - [x] Post summary
Summary
Overall: 5 / 5 — Round-2 blocking issue is cleanly resolved. Score bumps from 4 → 5 because all blockers are now addressed and only the explicitly-deferred UX item remains (probe-then-stop in setPort, which both sides agreed is a follow-up).
What was addressed (round 2)
-
praise (resolved): The
'error'listener at webui-server.ts:39 is now gated behind aresolvedflag that flips insidelisten()'s callback. Post-startup TCP errors no longer nullhttpServerwhilerunning=true, sostop()is no longer wedged. Inverted the EADDRINUSE branch into a cleaner ternary — nice tidy-up.this.httpServer.on('error', (err: NodeJS.ErrnoException) => { if (resolved) return this.httpServer = undefined reject(err.code === 'EADDRINUSE' ? new WebUiPortInUseError(port) : err) }) this.httpServer.listen(port, TRANSPORT_HOST, () => { resolved = true ... }) -
praise (resolved): New unit test at webui-server.test.ts:85–100 asserts the exact scenario from the round-2 finding: after
start()resolves, emitting'error'on the underlying HttpServer does not clearhttpServer,isRunning()staystrue,getPort()is unchanged, andstop()still completes cleanly. Matches the requested coverage 1:1.
Findings this round
None blocking. One small observation, no inline:
- With the gated listener, post-startup server-level errors are now silently swallowed (the listener returns early, no logging). For the
HttpServer-level'error'event this is rare and acceptable (per-connection errors fire elsewhere), and round 2 explicitly called this trade-off out as fine. If observability into late server errors ever matters, a singlelog()call beforereturnwould do it — not a blocker for this PR.
Carried-over (acknowledged out of scope, no action needed)
brv webui --port <busy>still tears down the working server before probing the new port. Both reviewer and author agreed to defer to a follow-up; the L667 log now states reality, so the current behavior is at least honest.setupFeatureHandlers({webuiPort: webuiServer?.getPort()})snapshot at brv-server.ts:734 — pre-existing, not introduced here.
Verification
- Inspected round-3 diff (commit
3b3896d) and current state of every changed file. Confirmed:webui-events.tsproperly registered inAllEventGroups(events/index.ts:95).setPorthandler (brv-server.ts:660–680) correctly clearswebuiBootFailureon success (L675) and on non-port failure (L671), and sets it on port-in-use (L666).resolvePortOrExitusesresult.status === 'ok'narrowing consistently (webui.ts:57).
- Did not run typecheck / lint / tests in this review (read-only). PR description states all pass on the author's machine.
LGTM — ready to ship. — Branch: feat/ENG-2857
Claude finished @ncnthien's task in 1m 24s —— View job
Claude PR Review — feat: [ENG-2857] surface port-in-use error in brv webui (round 4)
- [x] Read latest diff against
origin/main - [x] Verify state of changed files
- [x] Check for regressions since round 3
- [x] Post summary
Summary
Overall: 5 / 5 — Score holds from round 3. This synchronize event was triggered by the merge of main into the branch (commit 96337b3), not by new PR work. None of the PR-specific files changed since round 3 (commit 3b3896d); the diff vs. 3b3896d is entirely upstream main changes (curate telemetry handler + dream/idle dispatch rework in brv-server.ts, MigrateEvents export in events/index.ts).
Verification
git log 3b3896d..HEAD→ only the merge commit (96337b3) and the merged PR (99fc4e5, ENG-2884 tool-mode dream).git diff 3b3896d..HEAD -- <8 PR-touched files>— confirmed:webui-server.ts,webui-events.ts,webui-error.ts,oclif/commands/webui.ts,webui-server.test.ts,webui-error.test.ts— byte-identical to round 3.brv-server.ts— only upstream changes (idle policy simplification, newTaskCurateResultEventhandler). Webui block (L578–625) is byte-identical and still importsWebuiEvents/WebUiPortInUseErrorcorrectly.events/index.ts— only theMigrateEventsexport was added;webui-events.tsstill exported and registered inAllEventGroups.
- No merge conflicts left in the tree;
git statusclean.
Carry-over (already acknowledged, out of scope)
brv webui --port <busy>still tears down the working server before probing the new port (round 2 deferred). The L611 log states the reality (Web UI unavailable), so behavior is honest.setupFeatureHandlers({webuiPort: webuiServer?.getPort()})at brv-server.ts:678 still snapshots the port at startup — pre-existing, not introduced here.
LGTM — still ready to ship. — Branch: feat/ENG-2857
Claude finished @ncnthien's task in 56s —— View job
Claude PR Review — feat: [ENG-2857] surface port-in-use error in brv webui (round 5)
- [x] Read latest diff against
origin/main - [x] Verify state of changed files since round 4
- [x] Check whether this synchronize introduced new PR work
- [x] Post summary
Summary
Overall: 5 / 5 — Score holds from rounds 3 and 4. This synchronize event was triggered by another merge of main into the branch (commit 8838e8e), not by new PR work. None of the 8 PR-touched files changed since round 4 (commit 96337b3).
Verification
git log 96337b3..HEAD→ only8838e8e(merge of main) andc498b2f(the merged sibling PRproj/byterover-tool-mode).git diff --stat 96337b3..HEAD -- <8 PR-touched files>→ empty (zero lines changed across all PR-relevant files).- The 28 files touched by the merge are all unrelated: curate session (
oclif/lib/curate-session.ts), HTML render/reader, prompt/skill templates, and a newwebui/features/migrate/subtree. None of these interact with the webui-server, webui events, or theWebUiPortInUseErrorpaths reviewed in rounds 1–3.
Carried-over (still acknowledged, out of scope)
brv webui --port <busy>still tears down the working server before probing the new port — deferred to a follow-up (round 2). The log atbrv-server.tshonestly states the resulting state ("Web UI unavailable").setupFeatureHandlers({webuiPort: webuiServer?.getPort()})still snapshots the port at startup — pre-existing, not introduced here.
LGTM — still ready to ship. — Branch: feat/ENG-2857
Claude finished @ncnthien's task in 3m 51s —— View job
Claude PR Review — feat: [ENG-2857] surface port-in-use error in brv webui (round 6)
- [x] Identify what changed since round 5 (commit
8838e8e) - [x] Check whether the new commit
6d3fa5dintroduces PR-relevant work - [x] Verify regressions / re-check touched files
- [x] Post inline comments + summary
Summary
Overall: 4 / 5 — Score drops one notch from round 5's 5/5. The new commit 6d3fa5d is a real, scoped feature ("auto-fallback Web UI to next port when default is in use") — implementation is correct and the typed-response surface absorbs the change cleanly, but the commit ships zero new tests, which conflicts directly with CLAUDE.md's "Testing (Strict TDD — MANDATORY)" section and its 80% / critical-paths-must-be-covered rule. There's also one UX design question worth resolving before this is "done done": whether a persisted explicit user preference should auto-fallback the same way the default does.
What this commit adds
- Boot-time loop in
brv-server.ts:241–279trieswebuiPreferredPort + offsetforoffset ∈ [0, 9](10 attempts), stops on first success or non-EADDRINUSE error. - New
webuiRequestedPortstate captures the originally-asked port whenever a fallback fires. WebuiGetPortResponseok variant gains optionalrequestedPort: numberso the CLI can surface "you asked for X, you got Y" to the user.WEBUI_MAX_FALLBACK_ATTEMPTS = 10constant exported fromserver/constants.ts.getConfig()middleware now readswebuiServer?.getPort() ?? webuiPreferredPortso/api/ui/configreports the actual bound port (frontend gets the right Socket.IO host).
Findings (see inline)
| # | File | Severity | Issue |
|---|---|---|---|
| 1 | src/server/infra/daemon/brv-server.ts:241–279 |
issue (blocking per CLAUDE.md) | Auto-fallback loop is the new critical path and has zero new tests. Suggest extracting to a startWebUiWithFallback helper and covering all four branches (success-on-first / success-on-Nth / all-busy / non-EADDRINUSE break). |
| 2 | src/server/infra/daemon/brv-server.ts:219–223 |
suggestion (UX, non-blocking) | webuiPreferredPort conflates default (no intent) with BRV_WEBUI_PORT / persisted preference (explicit intent). A user whose stored preference is 9090 will silently get 9091 on next boot if 9090 is busy — they never asked for any port in [9090, 9099]. Gate fallback on the source. |
| 3 | src/server/infra/daemon/brv-server.ts:262 |
nit (UX) | When all 10 ports are busy, conflictPort: webuiPreferredPort only names the first port, but the CLI message will read "port 7700 is already in use" — true but understates the situation. Consider carrying an attempted range. |
| 4 | src/server/infra/daemon/brv-server.ts:238 |
praise | Reusing one WebUiServer instance across loop iterations works correctly thanks to round-3's httpServer = undefined clear on EADDRINUSE. One-line comment would help future readers. |
| 5 | src/oclif/commands/webui.ts:57–63 |
suggestion (style) | 'requestedPort' in result is unnecessary — requestedPort lives on the ok variant directly, so the status === 'ok' narrowing already covers it. Matches the round-1 "no implicit in narrowing" feedback. |
Carried-over (still acknowledged, out of scope here)
brv webui --port <busy>still tears down the working server before probing — explicitly deferred in round 2. Note that the new feature is intentionally boot-only and does not auto-fallback for--port, which is the right semantics for explicit user intent.setupFeatureHandlers({webuiPort: webuiServer?.getPort()})snapshot at the originalbrv-server.tslocation — pre-existing.
Verification
git log 8838e8e..HEAD→ only the new feature commit6d3fa5d.git diff 8838e8e..HEAD --stat→ 4 source files touched, 0 test files.- Read every changed file in full and
webui-state.tsfor the persistence semantics behind finding #2. — Branch: feat/ENG-2857
Hey @ncnthien , please have a look on port issue that current uses as IPv6 instead of IPv4, that doesn't cover in current code Summarisation & suggestion fix:
| Listener | Bind address | Stack |
|---|---|---|
| Docker container 11111 (host 7700 → Redis 6379) | 0.0.0.0:7700 + [::]:7700 | IPv6 wildcard |
| brv daemon (PID 80926) | 127.0.0.1:7700 | IPv4 only |
brv's webui binds IPv4-only because server/constants.ts:43 sets TRANSPORT_HOST = '127.0.0.1'. Docker holds the IPv6 wildcard [::]:7700. Those two coexist at the OS level — there is no EADDRINUSE — so:
- webuiServer.start(7700) succeeds → GET_PORT returns {port: 7700, status: 'ok'} → CLI prints http://localhost:7700.
- But when your browser opens http://localhost:7700, macOS resolves localhost to both 127.0.0.1 and ::1, and browsers/curl prefer IPv6 ::1 first → they connect to Docker's Redis, not brv → blank/broken page.
Proof from your machine:
curl -4 localhost:7700/api/ui/config → HTTP 200 (brv, works)
curl -6 localhost:7700/api/ui/config → HTTP 000 (Docker, broken)
curl localhost:7700 (browser path)→ ::1, HTTP 000
Why the ENG-2697 fix doesn't catch it
The conflict detection on this branch keys entirely off EADDRINUSE → WebUiPortInUseError → port_in_use (brv-server.ts:236-238, webui-server.ts:42). Because brv binds IPv4-specific and the other app holds the IPv6 wildcard, the OS never raises that error. The fix literally cannot see this collision, so it keeps reporting 7700 as ok.
Fix it now (pick one)
- Move brv off 7700 (persists the choice): brv webui --port 8080
- Free 7700: docker stop 11111 (it's forwarding host 7700 → a Redis on 6379 — you probably didn't intend it on 7700)
- Quick proof it's the IPv6 split: open http://127.0.0.1:7700 instead of localhost — that hits brv directly.
The real code fix
Two complementary options, and the first is small + directly in the spirit of this branch ("use printed webui URL in skill guidance"):
- Print http://127.0.0.1:${port} instead of http://localhost:${port} in webui.ts:26 (and in buildReviewUrl). Since brv binds IPv4-only, the printed URL should target the stack it actually owns — that sidesteps the localhost→::1→Docker ambiguity entirely.
- Make conflict detection probe instead of trusting EADDRINUSE — before/after binding, attempt a connect to the target port and verify the responder is brv (e.g. /api/ui/config); if something foreign answers, fall through to port_in_use (or auto-increment). This catches cross-stack squatters that don't trigger EADDRINUSE.
Want me to implement #1 (the minimal, TDD'd fix), #2, or both?