Skip to content

Fix WebUI model menu flickering and improve port scanning#17

Open
scouzi1966 wants to merge 1 commit intomainfrom
fix/webui-model-menu-and-port-scanning
Open

Fix WebUI model menu flickering and improve port scanning#17
scouzi1966 wants to merge 1 commit intomainfrom
fix/webui-model-menu-and-port-scanning

Conversation

@scouzi1966
Copy link
Owner

@scouzi1966 scouzi1966 commented Feb 5, 2026

Summary

  • Fix WebUI model dropdown flickering every 2 seconds in gateway mode (-wg)
  • Improve backend discovery to scan macOS ephemeral ports (49152-65535)
  • Use lsof for faster port scanning instead of TCP connect probes

Changes

WebUI Model Menu Fix

  • Add _selectingModel flag to prevent re-entrant dropdown triggers
  • Add _modelRestorationAttempted flag to only restore preferred model once per page load
  • Remove aggressive auto-switch logic that was causing the 2-second flickering cycle

Port Scanning Improvements

  • Use lsof -iTCP -sTCP:LISTEN -nP to get actually listening ports (instant)
  • Add macOS ephemeral port range (49152-65535) to discoverable ranges
  • Filter listening ports against allowed ranges instead of TCP probing thousands of ports
  • Fix lsof output parsing to correctly extract port numbers from NAME column

Test plan

  • Run afm -wg and verify model dropdown no longer flickers
  • Verify APIs on ephemeral ports (e.g., 56516) are discovered
  • Check logs show "listening port(s)" instead of "open port(s)"

🤖 Generated with Claude Code

Summary by Sourcery

Improve backend discovery performance and accuracy while stabilizing the WebUI model selection menu.

Bug Fixes:

  • Prevent the WebUI model dropdown from repeatedly auto-selecting and flickering by guarding re-entrant selection and limiting model restoration to a single attempt per page load.

Enhancements:

  • Switch backend discovery to use lsof-reported listening TCP ports filtered by configured ranges instead of active TCP probing, including support for macOS ephemeral port range discovery.
  • Refine port scan logging to report discovered listening ports and expand scanning to include dynamic macOS port ranges.

WebUI fixes:
- Add _selectingModel flag to prevent re-entrant dropdown triggers
- Add _modelRestorationAttempted flag to only restore preferred model once
- Remove aggressive auto-switch logic that caused 2-second flickering

Port scanning improvements:
- Use lsof to get actually listening ports instead of TCP connect scanning
- Add macOS ephemeral port range (49152-65535) to scan ranges
- Much faster scanning since we only probe ports that are actually listening
- Fix lsof output parsing to correctly extract port numbers

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@sourcery-ai
Copy link

sourcery-ai bot commented Feb 5, 2026

Reviewer's Guide

Switches backend discovery from TCP probing to lsof-based listening-port detection (including macOS ephemeral ports) and hardens the WebUI model dropdown auto-selection logic to prevent flicker and re-entrancy in gateway mode.

Sequence diagram for lsof-based port scanning in scanOpenPorts

sequenceDiagram
    actor User
    participant BackendDiscoveryService
    participant OS_lsof as lsof
    participant BackendDefinition
    participant Logger

    User->>BackendDiscoveryService: scanOpenPorts()
    BackendDiscoveryService->>BackendDefinition: read allKnown.defaultPort
    BackendDefinition-->>BackendDiscoveryService: knownPorts
    BackendDiscoveryService->>BackendDefinition: read blacklistedPorts
    BackendDefinition-->>BackendDiscoveryService: blacklisted

    BackendDiscoveryService->>OS_lsof: getListeningPorts() via lsof -iTCP -sTCP:LISTEN -nP
    OS_lsof-->>BackendDiscoveryService: stdout with listening sockets
    BackendDiscoveryService->>BackendDiscoveryService: parse NAME column to Set~Int~ listeningPorts

    BackendDiscoveryService->>BackendDiscoveryService: filter listeningPorts by scanPortRanges, selfPort, knownPorts, blacklisted
    BackendDiscoveryService->>Logger: log "Port scan found N listening port(s)"

    BackendDiscoveryService->>BackendDiscoveryService: withTaskGroup for each open port
    BackendDiscoveryService-->>User: discovered backends merged
Loading

Class diagram for BackendDiscoveryService and WebUI model selection flags

classDiagram
    class BackendDiscoveryService {
        - static scanPortRanges : [ClosedRange~Int~]
        - selfPort : Int
        - logger : Logger
        + scanKnownBackends() async
        + scanOpenPorts() async
        - getListeningPorts() Set~Int~
    }

    class BackendDefinition {
        <<static>>
        + allKnown : [BackendDefinition]
        + blacklistedPorts : Set~Int~
        + defaultPort : Int
    }

    class DiscoveredBackend {
        + id : String
        + baseURL : URL
    }

    BackendDiscoveryService --> BackendDefinition : uses
    BackendDiscoveryService --> DiscoveredBackend : discovers

    class Server {
        - _autoSelectDone : Bool
        - _userClickedModel : Bool
        - _isMultiModel : Bool
        - _modelRestorationAttempted : Bool
        - _lastModel : String
        - _selectingModel : Bool
        - _modelsCache : Any
        - _preferredModel : String
        + autoSelectDefault()
        + selectModelByName(name, force)
        + updateInfoStrip()
    }

    Server ..> BackendDiscoveryService : frontends gateway
Loading

State diagram for WebUI model restoration and dropdown selection flags

stateDiagram-v2
    [*] --> Initial

    state Initial {
        [*] --> Idle
        Idle: _selectingModel=false
        Idle: _modelRestorationAttempted=false
    }

    Idle --> NeedRestore : SPA_reset_detected_and_isMultiModel
    NeedRestore: _selectingModel=false
    NeedRestore: _modelRestorationAttempted=false

    NeedRestore --> SelectingPreferredModel : selectModelByName_called
    SelectingPreferredModel: _selectingModel=true

    SelectingPreferredModel --> ModelRestored : preferred_model_found_and_clicked
    SelectingPreferredModel --> ModelRestored : preferred_model_not_found_dropdown_closed

    ModelRestored: _selectingModel=false
    ModelRestored: _modelRestorationAttempted=true

    ModelRestored --> StableSelected : info_strip_updated
    StableSelected: _selectingModel=false
    StableSelected: _modelRestorationAttempted=true

    StableSelected --> StableSelected : user_clicks_model_dropdown_and_changes_model

    Idle --> StableSelected : model_already_selected_on_load

    StableSelected --> [*] : page_unload_or_navigation
Loading

File-Level Changes

Change Details Files
Use lsof to enumerate actually listening ports and filter them by allowed ranges instead of probing large TCP port ranges.
  • Repurpose scanPortRanges to describe filter ranges and extend them to include the macOS ephemeral/dynamic port range 49152-65535.
  • Add getListeningPorts() helper that runs /usr/sbin/lsof -iTCP -sTCP:LISTEN -nP, suppresses stderr, and parses the NAME column to extract port numbers.
  • Update scanOpenPorts() to call getListeningPorts(), filter against scanPortRanges while excluding self, known, and blacklisted ports, and adjust logging text to say "listening port(s)".
Sources/MacLocalAPI/Services/BackendDiscoveryService.swift
Debounce and guard WebUI model auto-selection to avoid re-entrant dropdown operations and one-off restoration behavior in gateway mode.
  • Introduce _selectingModel flag and use it in selectModelByName and updateInfoStrip to prevent overlapping dropdown opens and repeated auto-select during animation.
  • Introduce _modelRestorationAttempted flag to ensure preferred model restoration from SPA resets happens only once per page load and is marked complete once a model is selected.
  • Remove auto-switch logic that continuously forced the preferred model when SPA-driven changes were detected, eliminating the 2-second flicker loop.
Sources/MacLocalAPI/Server.swift

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue, and left some high level feedback:

  • The new getListeningPorts implementation assumes /usr/sbin/lsof exists and succeeds; consider gating this logic by platform and/or falling back to the previous TCP probe approach when the binary is missing or exits non‑zero so discovery does not silently degrade to returning an empty set.
  • getListeningPorts is a synchronous, nonisolated call that runs Process and waitUntilExit(); if invoked from latency‑sensitive paths, consider moving the lsof invocation to a separate async task or background queue to avoid blocking the actor’s caller thread.
  • The lsof parsing loop processes every line, including the header, and matches any column with a colon; to make this more robust, explicitly skip the first header line and narrow the match to the NAME column (e.g., by index) or a stricter regex to avoid accidentally interpreting unrelated fields as ports.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The new `getListeningPorts` implementation assumes `/usr/sbin/lsof` exists and succeeds; consider gating this logic by platform and/or falling back to the previous TCP probe approach when the binary is missing or exits non‑zero so discovery does not silently degrade to returning an empty set.
- `getListeningPorts` is a synchronous, nonisolated call that runs `Process` and `waitUntilExit()`; if invoked from latency‑sensitive paths, consider moving the lsof invocation to a separate async task or background queue to avoid blocking the actor’s caller thread.
- The lsof parsing loop processes every line, including the header, and matches any column with a colon; to make this more robust, explicitly skip the first header line and narrow the match to the NAME column (e.g., by index) or a stricter regex to avoid accidentally interpreting unrelated fields as ports.

## Individual Comments

### Comment 1
<location> `Sources/MacLocalAPI/Services/BackendDiscoveryService.swift:92-97` </location>
<code_context>

+    /// Get all TCP ports currently listening on localhost using lsof.
+    /// This is much faster than attempting TCP connections to thousands of ports.
+    private nonisolated func getListeningPorts() -> Set<Int> {
+        let process = Process()
+        process.executableURL = URL(fileURLWithPath: "/usr/sbin/lsof")
+        process.arguments = ["-iTCP", "-sTCP:LISTEN", "-nP"]
+
+        let pipe = Pipe()
+        process.standardOutput = pipe
+        process.standardError = FileHandle.nullDevice
+
+        do {
+            try process.run()
+            process.waitUntilExit()
+        } catch {
</code_context>

<issue_to_address>
**suggestion (bug_risk):** Consider checking `terminationStatus` and early-returning on lsof failures before parsing stdout.

Currently we only handle the case where `process.run()` throws. If `lsof` runs but exits non‑zero (e.g. permission error, sandboxing, missing binary), we’ll still parse stdout and may treat partial/invalid output as real ports. Instead, after `waitUntilExit()` we should check `terminationStatus == 0` before reading/parsing the pipe, and return `[]` on failure to avoid using erroneous results.

```suggestion
        do {
            try process.run()
            process.waitUntilExit()

            // If lsof exited with a non-zero status, treat it as a failure and return no ports.
            guard process.terminationStatus == 0 else {
                return []
            }
        } catch {
            return []
        }
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +92 to +97
do {
try process.run()
process.waitUntilExit()
} catch {
return []
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (bug_risk): Consider checking terminationStatus and early-returning on lsof failures before parsing stdout.

Currently we only handle the case where process.run() throws. If lsof runs but exits non‑zero (e.g. permission error, sandboxing, missing binary), we’ll still parse stdout and may treat partial/invalid output as real ports. Instead, after waitUntilExit() we should check terminationStatus == 0 before reading/parsing the pipe, and return [] on failure to avoid using erroneous results.

Suggested change
do {
try process.run()
process.waitUntilExit()
} catch {
return []
}
do {
try process.run()
process.waitUntilExit()
// If lsof exited with a non-zero status, treat it as a failure and return no ports.
guard process.terminationStatus == 0 else {
return []
}
} catch {
return []
}

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.

1 participant