Skip to content

Improve dev host handling and clarify backend port configuration#532

Open
blackmammoth wants to merge 11 commits intomainfrom
fix/network-setup-improvements
Open

Improve dev host handling and clarify backend port configuration#532
blackmammoth wants to merge 11 commits intomainfrom
fix/network-setup-improvements

Conversation

@blackmammoth
Copy link
Collaborator

@blackmammoth blackmammoth commented Mar 11, 2026

https://cloudcli.ai/docs/network-architecture-guide-how-the-front-and-backend-interact

Why

Before these changes:

  • npm run client always started Vite with --host, which exposed the dev server on all interfaces even when that was not intended.
  • The Express fallback redirect in development always pointed to http://localhost:<vite-port>, which breaks if a user opens the app from another device on the network.
  • Host normalization logic was split across the backend and Vite config, making proxy and URL behavior harder to keep aligned.
  • PORT was ambiguous in a project that already uses VITE_PORT, and some internal server code still depended on that older name.

What Changed

Development host handling

  • package.json

    • Removed the unconditional --host flag from the Vite client script so Vite respects the configured HOST instead of always exposing the dev server.
  • server/index.js

    • Updated the development redirect to use the incoming request hostname and protocol instead of hardcoding localhost.
    • Switched browser-facing server URLs to use normalized, connectable host values.
    • Improved startup logging so development and production entry URLs are clearer.
  • vite.config.js

    • Moved host/proxy behavior to shared helper utilities.
    • Normalized loopback values like localhost, 127.0.0.1, ::1, and [::1] into a consistent browser-facing host.
    • Ensured proxy targets use the connectable backend host instead of raw wildcard bind addresses.
    • Added explanatory comments around loopback and wildcard normalization.
  • shared/networkHosts.js

    • Added shared helpers for:
      • wildcard host detection
      • loopback host detection
      • loopback normalization
      • selecting a browser-safe/connectable host value

Port configuration cleanup

  • server/index.js

    • Renamed backend port usage from PORT to SERVER_PORT.
  • server/cli.js

    • Updated CLI environment handling, status output, and help text to use SERVER_PORT.
    • Kept --port / -p as the CLI flag
  • server/routes/taskmaster.js

    • Updated the internal fallback request path to use SERVER_PORT so server-to-server calls stay aligned with the new configuration name.

Test Plan

  1. Start the app in development with default settings and verify the UI, API proxying, and WebSocket connections still work.
  2. Start with HOST=0.0.0.0 and open the app from another device on the same network; confirm the redirect points to a reachable host instead of localhost.
  3. Set a custom SERVER_PORT and verify:
    • the backend listens on the configured port
    • Vite proxies target the correct backend port
    • CLI status/help output reflects SERVER_PORT
    • TaskMaster fallback requests still succeed
  4. Verify loopback-based setups continue to work with localhost, 127.0.0.1, and IPv6 loopback values.

Summary by CodeRabbit

  • Chores

    • Standardized server port env var from PORT to SERVER_PORT across docs, CLI, and startup output (legacy PORT still supported).
    • Removed explicit host-binding flag from the dev client script.
    • Updated README translations to reflect the new port variable.
    • Dev proxy targets now reference the standardized server port.
  • Refactor

    • Improved host normalization to produce connectable, browser-friendly URLs.
  • New Features

    • Dev startup now initializes project file watchers and plugin servers.

Running `vite --host` exposes the dev server on all interfaces. However,
we should expose it on all interfaces only when `HOST` is set to `0.0.0.0`.
Otherwise, we should assume the user wants to bind to a host of their choice
and not expose the server on the network.
Previously, the server redirected to Vite using `localhost` as the hostname.
Even if the user was using HOST="0.0.0.0", if they connected to server from
another device on the same network using `http://<host_ip>:3001`, the
server would redirect them to `http://localhost:5173`, which would not
work since `localhost` would resolve to the client's machine instead of the server.
- Normalize all localhost variants to 'localhost' for consistent proxy
configuration in Vite and server setup.
- use one source of truth for network hosts functions by moving them to
a shared
- log production and development urls
@blackmammoth blackmammoth requested a review from viper151 March 11, 2026 17:02
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 11, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Rename backend port env var from PORT to SERVER_PORT across configs, docs, CLI, server code, and Vite; add shared host utilities for loopback/wildcard normalization; update server startup to compute display hosts, start plugin servers, and initialize a projects watcher.

Changes

Cohort / File(s) Summary
Configuration & Documentation
\.env.example, README.ja.md, README.ko.md, README.zh-CN.md
Replaced PORT with SERVER_PORT in examples and startup instructions.
Package Scripts
package.json
Changed client script from "vite --host" to "vite".
CLI
server/cli.js
Mapped --port/-p to serverPort; set process.env.SERVER_PORT (fallback from PORT); updated help/status text to reference SERVER_PORT with a LEGACY note for PORT.
Server Startup & Routing
server/index.js
Use SERVER_PORT for listen/logging and redirects; import and use getConnectableHost for display/redirect host resolution; added setupProjectsWatcher() and startEnabledPluginServers(); adjusted dev/prod startup messaging and VITE port handling.
Internal Routes
server/routes/taskmaster.js
Updated internal fallback fetch targets to prefer SERVER_PORT with PORT as fallback.
Vite Config & Dev Proxy
vite.config.js
Removed command param from config factory; import host helpers; compute host/proxy targets using SERVER_PORT (fallback to PORT); updated /api, /ws, /shell proxy targets.
Networking Utilities
shared/networkHosts.js
Added exports: isWildcardHost(), isLoopbackHost(), normalizeLoopbackHost(), getConnectableHost() for consistent host normalization and connectable-host resolution.

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant Server
  participant Watcher
  participant Plugins
  participant Vite
  participant Browser

  CLI->>Server: start (reads SERVER_PORT, HOST, fallbacks)
  Server->>Watcher: setupProjectsWatcher()
  Server->>Plugins: startEnabledPluginServers()
  Server->>Vite: configure dev proxy targets using getConnectableHost(HOST) and SERVER_PORT
  Browser->>Vite: request assets / WS
  Browser->>Server: HTTP request (may be redirected to connectable host:SERVER_PORT)
Loading

Possibly related PRs

Poem

🐰 I hopped from PORT to SERVER_PORT with glee,
I nudged localhost so browsers can see me.
Watchers wake, plugins take their part,
URLs align, and the dev server starts.
A tiny rabbit cheer for every start!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and clearly summarizes the two main aspects of this changeset: improved host handling for LAN access and clarification of backend port configuration through SERVER_PORT rename.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/network-setup-improvements
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
server/cli.js (1)

133-137: ⚠️ Potential issue | 🟡 Minor

cloudcli status can still print a non-working URL.

This stays pinned to localhost, so HOST=192.168.x.x or a custom hostname makes the hint incorrect even though the server is listening elsewhere. Reuse the same host normalization helper here so the CLI output matches the actual bind address.

As per coding guidelines, npm run dev starts both frontend and backend; ensure HOST/port handling aligns with new SERVER_PORT logic.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/cli.js` around lines 133 - 137, The printed UI hint in server/cli.js
currently hardcodes "localhost" and uses process.env.SERVER_PORT || '3001',
which can show an incorrect URL for non-local binds; change the cloudcli status
output to build the host/port using the same host normalization helper used
elsewhere (e.g., normalizeHost or getServerUrl) so it uses process.env.HOST (or
the normalized host) and process.env.SERVER_PORT consistently; update the
console.log line that prints "Access the UI at
http://localhost:${process.env.SERVER_PORT || '3001'}" to call the shared helper
(or compose host = normalizeHost(process.env.HOST) and port =
process.env.SERVER_PORT || '3001') so the hint matches actual bind address.
server/routes/taskmaster.js (1)

530-536: ⚠️ Potential issue | 🟠 Major

Don't keep the fallback pinned to localhost.

When HOST is set to a specific LAN IP/hostname, this self-call can miss the interface the server actually bound to, so the TaskMaster fallback stops working in the remote-access setups this PR is targeting. Reuse the shared host helper here, or better, avoid the HTTP hop and call the task-loading logic directly.

As per coding guidelines, npm run dev starts both frontend and backend; ensure HOST/port handling aligns with new SERVER_PORT logic.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/routes/taskmaster.js` around lines 530 - 536, The fallback should not
hardcode localhost: replace the HTTP self-call (the fetch using
process.env.SERVER_PORT and projectName) by either (A) using the shared host
helper (e.g., getServerHost/getHost) to build the URL instead of `localhost`, or
preferably (B) avoid the HTTP hop entirely by calling the internal task-loading
function directly (e.g., TaskMaster.loadTasks / loadProjectTasks or the module
that returns tasks for projectName) and passing along authorization/context from
req (req.headers.authorization) so auth checks still run; also ensure this
change respects the SERVER_PORT/HOST handling used by npm run dev.
🧹 Nitpick comments (1)
server/index.js (1)

34-34: Remove the temporary env debug print.

This runs on every startup and duplicates the structured readiness logging below. It looks like leftover debugging noise.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/index.js` at line 34, Remove the temporary environment debug print by
deleting the console.log('SERVER_PORT from env:', process.env.SERVER_PORT);
statement in server/index.js so startup doesn't emit duplicate, noisy logs; rely
on the existing structured readiness logging instead.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@README.ko.md`:
- Line 73: Update the README sentence to mention both configured HOST and
SERVER_PORT instead of hardcoding "localhost": change the line that currently
references `http://localhost:3001` to construct the URL using the `HOST` and
`SERVER_PORT` environment variables (e.g., mention "http://<HOST>:<SERVER_PORT>
or http://localhost:<SERVER_PORT> if HOST is unset"), and also add a short note
that `npm run dev` starts both frontend and backend and will respect the HOST/
SERVER_PORT environment variables so host/port handling matches the new
networking behavior.

In `@shared/networkHosts.js`:
- Around line 16-22: getConnectableHost currently returns raw host strings (used
by callers to build http:// and ws:// authorities) which breaks for IPv6
literals like "2001:db8::10"; add a small helper (e.g. formatHostForURL or
bracketIPv6Host) that detects IPv6 literals and wraps them in square brackets
per RFC (and otherwise returns the host unchanged), update all call sites that
interpolate hosts into URLs (startup redirects, proxy targets, dev server URLs)
to call this helper instead of using getConnectableHost directly, and keep
getConnectableHost's behavior for wildcard/loopback detection (isWildcardHost,
isLoopbackHost) unchanged; also verify the host+port assembly at those call
sites uses the new SERVER_PORT handling so HOST and port logic remain consistent
with npm run dev semantics.

---

Outside diff comments:
In `@server/cli.js`:
- Around line 133-137: The printed UI hint in server/cli.js currently hardcodes
"localhost" and uses process.env.SERVER_PORT || '3001', which can show an
incorrect URL for non-local binds; change the cloudcli status output to build
the host/port using the same host normalization helper used elsewhere (e.g.,
normalizeHost or getServerUrl) so it uses process.env.HOST (or the normalized
host) and process.env.SERVER_PORT consistently; update the console.log line that
prints "Access the UI at http://localhost:${process.env.SERVER_PORT || '3001'}"
to call the shared helper (or compose host = normalizeHost(process.env.HOST) and
port = process.env.SERVER_PORT || '3001') so the hint matches actual bind
address.

In `@server/routes/taskmaster.js`:
- Around line 530-536: The fallback should not hardcode localhost: replace the
HTTP self-call (the fetch using process.env.SERVER_PORT and projectName) by
either (A) using the shared host helper (e.g., getServerHost/getHost) to build
the URL instead of `localhost`, or preferably (B) avoid the HTTP hop entirely by
calling the internal task-loading function directly (e.g., TaskMaster.loadTasks
/ loadProjectTasks or the module that returns tasks for projectName) and passing
along authorization/context from req (req.headers.authorization) so auth checks
still run; also ensure this change respects the SERVER_PORT/HOST handling used
by npm run dev.

---

Nitpick comments:
In `@server/index.js`:
- Line 34: Remove the temporary environment debug print by deleting the
console.log('SERVER_PORT from env:', process.env.SERVER_PORT); statement in
server/index.js so startup doesn't emit duplicate, noisy logs; rely on the
existing structured readiness logging instead.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 95d78591-0d28-4f0c-8172-e4c1f828823f

📥 Commits

Reviewing files that changed from the base of the PR and between 621853c and 1995a41.

📒 Files selected for processing (10)
  • .env.example
  • README.ja.md
  • README.ko.md
  • README.zh-CN.md
  • package.json
  • server/cli.js
  • server/index.js
  • server/routes/taskmaster.js
  • shared/networkHosts.js
  • vite.config.js

```

서버가 시작되면 `http://localhost:3001` (또는 설정한 PORT)에서 접근할 수 있습니다.
서버가 시작되면 `http://localhost:3001` (또는 설정한 SERVER_PORT)에서 접근할 수 있습니다.
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Document the host as well as the port.

This sentence still hardcodes localhost, so it becomes inaccurate when HOST is set to a specific LAN IP or hostname. Mention the configured host alongside SERVER_PORT here to match the new networking behavior.

As per coding guidelines, npm run dev starts both frontend and backend; ensure HOST/port handling aligns with new SERVER_PORT logic.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@README.ko.md` at line 73, Update the README sentence to mention both
configured HOST and SERVER_PORT instead of hardcoding "localhost": change the
line that currently references `http://localhost:3001` to construct the URL
using the `HOST` and `SERVER_PORT` environment variables (e.g., mention
"http://<HOST>:<SERVER_PORT> or http://localhost:<SERVER_PORT> if HOST is
unset"), and also add a short note that `npm run dev` starts both frontend and
backend and will respect the HOST/ SERVER_PORT environment variables so
host/port handling matches the new networking behavior.

Comment on lines +16 to +22
// Use localhost for connectable loopback and wildcard addresses in browser-facing URLs.
export function getConnectableHost(host) {
if (!host) {
return 'localhost';
}
return isWildcardHost(host) || isLoopbackHost(host) ? 'localhost' : host;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Bracket IPv6 literals before using these hosts in URLs.

getConnectableHost() returns raw host values, but the callers interpolate them into http:///ws:// URLs. A custom IPv6 host like 2001:db8::10 will produce an invalid authority (http://2001:db8::10:3001), so redirects, startup URLs, and proxy targets still break on IPv6 setups. Add a dedicated URL-formatting helper and use that wherever these hosts are rendered into URLs.

As per coding guidelines, npm run dev starts both frontend and backend; ensure HOST/port handling aligns with new SERVER_PORT logic.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@shared/networkHosts.js` around lines 16 - 22, getConnectableHost currently
returns raw host strings (used by callers to build http:// and ws://
authorities) which breaks for IPv6 literals like "2001:db8::10"; add a small
helper (e.g. formatHostForURL or bracketIPv6Host) that detects IPv6 literals and
wraps them in square brackets per RFC (and otherwise returns the host
unchanged), update all call sites that interpolate hosts into URLs (startup
redirects, proxy targets, dev server URLs) to call this helper instead of using
getConnectableHost directly, and keep getConnectableHost's behavior for
wildcard/loopback detection (isWildcardHost, isLoopbackHost) unchanged; also
verify the host+port assembly at those call sites uses the new SERVER_PORT
handling so HOST and port logic remain consistent with npm run dev semantics.

@viper151
Copy link
Contributor

@blackmammoth as this is a breaking change, would it make sense to have still have the port link to the server_port as a fallback?

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.env.example:
- Line 20: Add back a deprecated PORT entry to the .env.example and a short
migration note, and ensure runtime uses PORT as a fallback by checking
process.env.SERVER_PORT || process.env.PORT || 3001; specifically, restore a
line for PORT with a comment about deprecation next to SERVER_PORT and update
any places that read process.env.SERVER_PORT to fall back to process.env.PORT
(i.e., change usages that currently do process.env.SERVER_PORT || 3001 to
process.env.SERVER_PORT || process.env.PORT || 3001).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 1b4e4b0e-76ab-451c-a537-5cd1a6875c13

📥 Commits

Reviewing files that changed from the base of the PR and between 1995a41 and ea844b1.

📒 Files selected for processing (2)
  • .env.example
  • package.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • package.json

@blackmammoth
Copy link
Collaborator Author

@blackmammoth as this is a breaking change, would it make sense to have still have the port link to the server_port as a fallback?

Every default values have not been changed so it shouldn't have broken any existing functionality. Can you share snippets of the codebase that are breaking changes?

@viper151
Copy link
Contributor

@blackmammoth as this is a breaking change, would it make sense to have still have the port link to the server_port as a fallback?

Every default values have not been changed so it shouldn't have broken any existing functionality. Can you share snippets of the codebase that are breaking changes?

It's not about the default but existing installations where the users might have changed the .env PORT value to something else than the default one

@blackmammoth
Copy link
Collaborator Author

@blackmammoth as this is a breaking change, would it make sense to have still have the port link to the server_port as a fallback?

Every default values have not been changed so it shouldn't have broken any existing functionality. Can you share snippets of the codebase that are breaking changes?

It's not about the default but existing installations where the users might have changed the .env PORT value to something else than the default one

understood. I have added a commit for this. I have also added a TODO comment for removing the PORT variable from a future major release.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@server/cli.js`:
- Around line 289-290: The CLI currently only writes the CLI flag into
process.env.SERVER_PORT (via options.serverPort), which prevents legacy PORT env
vars from reaching code that still reads PORT; update the logic so that when
options.serverPort is provided you set both process.env.SERVER_PORT and
process.env.PORT to that value, and when options.serverPort is not provided but
process.env.PORT exists you propagate process.env.PORT into
process.env.SERVER_PORT (i.e., set SERVER_PORT = PORT) so both old and new
consumers (e.g., server boot logic and vite proxy) see the same port value.
- Line 137: The status output currently hardcodes "localhost" in the
console.log; replace that with the same connectable-host logic used elsewhere so
the printed UI URL matches actual access behavior. Import or require the
existing helper (e.g., connectableHost or getConnectableHost), compute the host
to use (falling back to the same env vars used to start the server), and
substitute that host into the template string in the console.log call instead of
the literal 'localhost'. Ensure the port resolution remains identical to the
existing expression (process.env.SERVER_PORT || process.env.PORT || '3001') so
only the host selection changes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 243e1340-5285-4edf-a43e-966ea7436f32

📥 Commits

Reviewing files that changed from the base of the PR and between ea844b1 and 03269a3.

📒 Files selected for processing (3)
  • server/cli.js
  • server/routes/taskmaster.js
  • vite.config.js
🚧 Files skipped from review as they are similar to previous changes (1)
  • server/routes/taskmaster.js

console.log(` ${c.dim('>')} Use ${c.bright('cloudcli --database-path /path/to/db')} for custom database`);
console.log(` ${c.dim('>')} Run ${c.bright('cloudcli help')} for all options`);
console.log(` ${c.dim('>')} Access the UI at http://localhost:${process.env.PORT || '3001'}\n`);
console.log(` ${c.dim('>')} Access the UI at http://localhost:${process.env.SERVER_PORT || process.env.PORT || '3001'}\n`);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Status output still hardcodes localhost.

With HOST=0.0.0.0 or a LAN address, this prints the wrong URL even though the rest of the PR now normalizes browser-facing hosts. Reuse the same connectable-host logic here so the status command matches actual access behavior.

Proposed fix
+import { getConnectableHost } from '../shared/networkHosts.js';
+    const displayHost = getConnectableHost(process.env.HOST || '0.0.0.0');
-    console.log(`      ${c.dim('>')} Access the UI at http://localhost:${process.env.SERVER_PORT || process.env.PORT || '3001'}\n`);
+    console.log(`      ${c.dim('>')} Access the UI at http://${displayHost}:${process.env.SERVER_PORT || process.env.PORT || '3001'}\n`);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
console.log(` ${c.dim('>')} Access the UI at http://localhost:${process.env.SERVER_PORT || process.env.PORT || '3001'}\n`);
import { getConnectableHost } from '../shared/networkHosts.js';
const displayHost = getConnectableHost(process.env.HOST || '0.0.0.0');
console.log(` ${c.dim('>')} Access the UI at http://${displayHost}:${process.env.SERVER_PORT || process.env.PORT || '3001'}\n`);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/cli.js` at line 137, The status output currently hardcodes "localhost"
in the console.log; replace that with the same connectable-host logic used
elsewhere so the printed UI URL matches actual access behavior. Import or
require the existing helper (e.g., connectableHost or getConnectableHost),
compute the host to use (falling back to the same env vars used to start the
server), and substitute that host into the template string in the console.log
call instead of the literal 'localhost'. Ensure the port resolution remains
identical to the existing expression (process.env.SERVER_PORT ||
process.env.PORT || '3001') so only the host selection changes.

Comment on lines +289 to +290
if (options.serverPort) {
process.env.SERVER_PORT = options.serverPort;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Legacy PORT configs still won't reach the server.

This only forwards the CLI flag into SERVER_PORT. If an existing install sets PORT=4000 in the environment, server/index.js:2494-2519 still binds 3001 because it now reads only SERVER_PORT, while vite.config.js:18 still proxies to PORT. That breaks the legacy custom-port path this PR is trying to preserve.

Proposed fix
 async function main() {
     const args = process.argv.slice(2);
     const { command, options } = parseArgs(args);
+    loadEnvFile();

     // Apply CLI options to environment variables
     if (options.serverPort) {
         process.env.SERVER_PORT = options.serverPort;
+    } else if (!process.env.SERVER_PORT && process.env.PORT) {
+        process.env.SERVER_PORT = process.env.PORT;
     }
     if (options.databasePath) {
         process.env.DATABASE_PATH = options.databasePath;
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/cli.js` around lines 289 - 290, The CLI currently only writes the CLI
flag into process.env.SERVER_PORT (via options.serverPort), which prevents
legacy PORT env vars from reaching code that still reads PORT; update the logic
so that when options.serverPort is provided you set both process.env.SERVER_PORT
and process.env.PORT to that value, and when options.serverPort is not provided
but process.env.PORT exists you propagate process.env.PORT into
process.env.SERVER_PORT (i.e., set SERVER_PORT = PORT) so both old and new
consumers (e.g., server boot logic and vite proxy) see the same port value.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

♻️ Duplicate comments (1)
server/cli.js (1)

289-293: ⚠️ Potential issue | 🟠 Major

Missing loadEnvFile() call before the PORT fallback logic.

The fallback from PORT to SERVER_PORT was added, but .env file values still won't be picked up for the start command. The loadEnvFile() function is only called via getDatabasePath() in showStatus(), not before startServer().

Scenario: User has PORT=4000 in .env, no CLI flag, no shell SERVER_PORT:

  1. main() runs, process.env.PORT is still undefined (.env not loaded)
  2. Fallback on line 291-292 doesn't trigger
  3. startServer() imports server/index.js, which evaluates SERVER_PORT as 3001
Proposed fix
 async function main() {
     const args = process.argv.slice(2);
     const { command, options } = parseArgs(args);
+    
+    // Load .env before applying CLI options so PORT fallback works
+    loadEnvFile();

     // Apply CLI options to environment variables
     if (options.serverPort) {
         process.env.SERVER_PORT = options.serverPort;
     } else if (!process.env.SERVER_PORT && process.env.PORT) {
         process.env.SERVER_PORT = process.env.PORT;
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/cli.js` around lines 289 - 293, Call loadEnvFile() before evaluating
the PORT→SERVER_PORT fallback in main() so .env values are available for
startServer(); specifically, ensure loadEnvFile() is invoked (if not already)
prior to the block that checks options.serverPort and process.env.PORT (the
fallback logic around SERVER_PORT), so startServer() / server/index.js sees the
.env-provided PORT; avoid duplicating loads already done in
getDatabasePath()/showStatus().
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@server/cli.js`:
- Around line 289-293: Call loadEnvFile() before evaluating the PORT→SERVER_PORT
fallback in main() so .env values are available for startServer(); specifically,
ensure loadEnvFile() is invoked (if not already) prior to the block that checks
options.serverPort and process.env.PORT (the fallback logic around SERVER_PORT),
so startServer() / server/index.js sees the .env-provided PORT; avoid
duplicating loads already done in getDatabasePath()/showStatus().

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: de87b84f-7de5-4756-86db-aa6163772dae

📥 Commits

Reviewing files that changed from the base of the PR and between 03269a3 and 22f2b92.

📒 Files selected for processing (1)
  • server/cli.js

@blackmammoth
Copy link
Collaborator Author

@viper151 updated

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
server/index.js (1)

34-34: Remove debug log before merge.

This appears to be leftover debugging code. Consider removing it to keep production logs clean.

🧹 Proposed fix
-console.log('SERVER_PORT from env:', process.env.SERVER_PORT);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/index.js` at line 34, Remove the leftover debug console.log in
server/index.js that prints process.env.SERVER_PORT; locate the
console.log('SERVER_PORT from env:', process.env.SERVER_PORT) statement and
delete it (or replace with a proper logger call at an appropriate log level if
intentional), ensuring no stray debug prints remain before merging.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@server/index.js`:
- Line 2496: Replace the current single-variable fallback for SERVER_PORT with
the same backward-compatible pattern used elsewhere: update the const
declaration for SERVER_PORT to check process.env.SERVER_PORT, then
process.env.PORT, then the numeric fallback (3001); i.e., change the initializer
for the SERVER_PORT variable so it uses process.env.SERVER_PORT ||
process.env.PORT || 3001 to restore compatibility with deployments that only set
PORT.

---

Nitpick comments:
In `@server/index.js`:
- Line 34: Remove the leftover debug console.log in server/index.js that prints
process.env.SERVER_PORT; locate the console.log('SERVER_PORT from env:',
process.env.SERVER_PORT) statement and delete it (or replace with a proper
logger call at an appropriate log level if intentional), ensuring no stray debug
prints remain before merging.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: f5be6ff6-6f84-4d07-beeb-f697a3ecaa4c

📥 Commits

Reviewing files that changed from the base of the PR and between 22f2b92 and 8b53eb6.

📒 Files selected for processing (5)
  • README.ja.md
  • README.ko.md
  • README.zh-CN.md
  • package.json
  • server/index.js
🚧 Files skipped from review as they are similar to previous changes (2)
  • README.zh-CN.md
  • README.ja.md

}

const PORT = process.env.PORT || 3001;
const SERVER_PORT = process.env.SERVER_PORT || 3001;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check how SERVER_PORT and PORT are used across the codebase

echo "=== Files using SERVER_PORT ==="
rg -n 'SERVER_PORT' --type js

echo ""
echo "=== Files using PORT fallback pattern ==="
rg -n 'SERVER_PORT.*PORT|PORT.*SERVER_PORT' --type js

Repository: siteboon/claudecodeui

Length of output: 2819


Inconsistent PORT fallback—server/index.js is missing backward compatibility.

The codebase consistently implements a SERVER_PORT || PORT || fallback pattern for backward compatibility across vite.config.js, server/cli.js, and server/routes/taskmaster.js, but server/index.js:2496 omits the PORT fallback, breaking backward compatibility for deployments using only the PORT environment variable.

🔧 Proposed fix
-const SERVER_PORT = process.env.SERVER_PORT || 3001;
+// TODO: Remove support for legacy PORT variable in a future major release, leaving only SERVER_PORT.
+const SERVER_PORT = process.env.SERVER_PORT || process.env.PORT || 3001;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/index.js` at line 2496, Replace the current single-variable fallback
for SERVER_PORT with the same backward-compatible pattern used elsewhere: update
the const declaration for SERVER_PORT to check process.env.SERVER_PORT, then
process.env.PORT, then the numeric fallback (3001); i.e., change the initializer
for the SERVER_PORT variable so it uses process.env.SERVER_PORT ||
process.env.PORT || 3001 to restore compatibility with deployments that only set
PORT.

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.

3 participants