Skip to content

fix(scripts): validate mock webview bridge port#3073

Merged
senamakel merged 3 commits into
tinyhumansai:mainfrom
alexzhu0:codex/OH-2611-mock-webview-port-arg
Jun 2, 2026
Merged

fix(scripts): validate mock webview bridge port#3073
senamakel merged 3 commits into
tinyhumansai:mainfrom
alexzhu0:codex/OH-2611-mock-webview-port-arg

Conversation

@alexzhu0
Copy link
Copy Markdown
Contributor

@alexzhu0 alexzhu0 commented May 31, 2026

Summary

  • Makes scripts/mock-webview-bridge.mjs validate the optional positional port before starting the WebSocket server.
  • Adds --help / -h usage output that exits without opening a listener.
  • Adds focused Node tests for help output, invalid ports, out-of-range ports, and extra arguments.

Problem

  • node scripts/mock-webview-bridge.mjs nope currently passes NaN into WebSocketServer.
  • That produces low-level listener errors instead of actionable CLI feedback.
  • In sandboxed or restricted environments, this makes contributor debugging harder because startup failures obscure the malformed argument.

Solution

  • Parse the optional port argument before constructing WebSocketServer.
  • Exit 2 for non-integer, out-of-range, or extra positional arguments.
  • Preserve the existing default 9826 behavior when no port is supplied.

Submission Checklist

If a section does not apply to this change, mark the item as N/A with a one-line reason. Do not delete items.

  • Tests added or updated (happy path + at least one failure / edge case) per Testing Strategy
  • N/A: Diff coverage gate was not run because this is a root helper script change and local Rust tooling is unavailable.
  • N/A: Coverage matrix not affected; this does not add, remove, or rename a product feature.
  • N/A: No affected feature IDs; mock helper CLI only.
  • No new external network dependencies introduced (mock backend used per Testing Strategy)
  • N/A: Manual smoke checklist not affected; this does not touch release-cut surfaces.
  • N/A: Related to [Automated] Weekly code-review report — 2026-05-25 #2611 but does not close it by itself.

Impact

  • Runtime/platform impact: no product runtime change.
  • Developer/test impact: malformed mock webview bridge port arguments now fail fast with usage-oriented errors.

Related


AI Authored PR Metadata (required for Codex/Linear PRs)

Linear Issue

  • Key: N/A
  • URL: N/A

Commit & Branch

  • Branch: codex/OH-2611-mock-webview-port-arg
  • Commit SHA: d63cbc8

Validation Run

  • pnpm --filter openhuman-app format:check (blocked after app Prettier passed; see below)
  • pnpm typecheck
  • Focused tests: node --test scripts/__tests__/mock-webview-bridge-args.test.mjs
  • Rust fmt/check (if changed): N/A, no Rust files changed
  • Tauri fmt/check (if changed): N/A, no Tauri files changed
  • node scripts/mock-webview-bridge.mjs --help
  • node scripts/mock-webview-bridge.mjs nope
  • node scripts/mock-webview-bridge.mjs 9826 ""
  • node scripts/codex-pr-preflight.mjs --lightweight
  • git diff --check

Validation Blocked

  • command: env COREPACK_HOME=/Users/alex/PR/.corepack PNPM_HOME=/Users/alex/PR/.pnpm-home pnpm --filter openhuman-app format:check
  • error: sh: cargo: command not found
  • impact: The app Prettier phase passed, but Rust formatting and the pre-push hook cannot complete in this local environment until Cargo is installed.

Behavior Changes

  • Intended behavior change: invalid explicit mock webview bridge port arguments now exit 2 before startup.
  • User-visible effect: local mock webview bridge invocation errors are clearer for contributors.

Parity Contract

  • Legacy behavior preserved: the default 9826 port is still used when no explicit port is supplied.
  • Guard/fallback/dispatch parity checks: focused tests cover help, invalid ports, out-of-range ports, and extra positional arguments including empty strings.

Duplicate / Superseded PR Handling

  • Duplicate PR(s): none found during triage
  • Canonical PR: this PR
  • Resolution (closed/superseded/updated): N/A

Constraint: The mock webview bridge is a local debugging CLI and should reject malformed ports before constructing the WebSocket server.

Rejected: Let ws validate NaN/out-of-range ports | it emits a low-level stack trace instead of actionable usage feedback.

Confidence: high

Scope-risk: narrow

Directive: Validate contributor-facing script arguments before starting listeners.

Tested: node --test scripts/__tests__/mock-webview-bridge-args.test.mjs; node scripts/mock-webview-bridge.mjs --help; node scripts/mock-webview-bridge.mjs nope; node scripts/codex-pr-preflight.mjs --lightweight; pnpm typecheck; git diff --check

Not-tested: Full format:check/pre-push hook; cargo is not installed in this environment, though the app Prettier phase passed. Did not start the webview bridge because local sandbox listener behavior is restricted.
@alexzhu0 alexzhu0 requested a review from a team May 31, 2026 05:48
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 31, 2026

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds structured command-line argument handling to scripts/mock-webview-bridge.mjs (help flag, integer port validation 1–65535, exit codes 0/2) and a node:test suite that verifies help output and rejects malformed port/argument inputs.

Changes

CLI Argument Handling and Validation

Layer / File(s) Summary
CLI argument validation implementation
scripts/mock-webview-bridge.mjs
Adds usage() and readPortArg() to handle --help/-h, validate port as an integer in range 1–65535 (default 9826), print usage/errors and exit with code 0 or 2, and use the validated port for the WebSocket server startup and listening log.
CLI argument validation tests
scripts/__tests__/mock-webview-bridge-args.test.mjs
Adds tests that run the script with --help (expect exit 0, usage on stdout, no stderr) and parameterized invalid-argument cases (non-numeric, out-of-range, extra/empty args) expecting exit 2 and no ERR_SOCKET_BAD_PORT in stderr.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I hop with keys and tiny code delight,
The bridge now asks for ports that fit just right,
A help flag sings, and bad ones meet a stop,
Tests watch the door — no socket starts to pop,
Cheers from the burrow, arguments tidy and bright.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix(scripts): validate mock webview bridge port' directly and specifically reflects the main change: adding port argument validation to the mock webview bridge script before starting the WebSocket server.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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


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
Copy Markdown
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 current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@scripts/mock-webview-bridge.mjs`:
- Around line 14-22: The current check uses truthiness of extra which fails for
an explicit empty-string positional arg; instead compute args =
process.argv.slice(2) (or use the existing destructured [rawPort, extra]) and
reject by count: if args.length > 1 then print usage and exit with code 2; keep
the help check as if (rawPort === '--help' || rawPort === '-h') using the first
arg. Update the logic around rawPort/extra to rely on args.length rather than
truthiness to ensure cases like "" are treated as extra arguments.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 67a5d300-4552-4477-9785-645afb784a67

📥 Commits

Reviewing files that changed from the base of the PR and between 4e221e9 and 9364ab2.

📒 Files selected for processing (2)
  • scripts/__tests__/mock-webview-bridge-args.test.mjs
  • scripts/mock-webview-bridge.mjs

Comment thread scripts/mock-webview-bridge.mjs Outdated
Constraint: CodeRabbit identified that empty-string extra arguments bypassed truthiness-based validation.

Rejected: Keep checking the destructured extra value | argument presence should be determined by count, not truthiness.

Confidence: high

Scope-risk: narrow

Directive: Validate CLI arity with argument counts before starting local listeners.

Tested: node --test scripts/__tests__/mock-webview-bridge-args.test.mjs; node scripts/mock-webview-bridge.mjs 9826 ""; git diff --check

Not-tested: Full repository format/check; cargo is unavailable locally.
@alexzhu0
Copy link
Copy Markdown
Contributor Author

Thanks for the checks. I rechecked this PR on current state:

  • The only true blocker is Rust Core Coverage (cargo-llvm-cov) failing.
  • Other core checks in this PR pass; remaining failures are likely rerun / shared-suite related.
  • This is likely a shared upstream/core coverage issue across the fix(codex): compare strict preflight paths by realpath #3060-3073 batch, not a regression from this PR's diff.
  • PR Submission Checklist has historical failed/cancelled runs due to workflow re-triggers.

@alexzhu0
Copy link
Copy Markdown
Contributor Author

I reviewed all open PRs from alexzhu0 in this batch (#3060-3073).

Clarification on PR Submission Checklist

Most PR Submission Checklist failure/cancellation entries are historical/retry artifacts rather than new functional regressions:

  • Multiple checklist runs are expected for these PRs because re-runs happen while soft checks are triggered.
  • In the same PRs, CodeRabbit, lint/format, and most pipeline checks are passing.
  • The remaining hard blockers are concentrated in Rust Core Coverage (cargo-llvm-cov) and, for a subset, Frontend Coverage (Vitest) / Playwright web lane 1.

Suggested action

Please treat PR Submission Checklist failures for this batch as noise unless accompanied by a fresh diff-scope failure in core quality gates.

This should help avoid blocking PRs that are not functionally regressed by their own changes.

@sanil-23 sanil-23 assigned sanil-23 and unassigned sanil-23 May 31, 2026
Copy link
Copy Markdown
Contributor

@sanil-23 sanil-23 left a comment

Choose a reason for hiding this comment

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

@alexzhu0 the code looks good — CI has one failing check that needs resolving before I can approve.

The Rust Core Coverage (cargo-llvm-cov) job is failing on inference_provider_admin_round22_raw_coverage_e2e, which is a pre-existing Rust test unrelated to your changes (this PR only touches .mjs files). Once that check goes green (or a maintainer confirms it's a pre-existing flake), I'll come back and approve.

A few notes on the implementation itself:

The CodeRabbit flag about empty-string args ('' being falsy) is already fixed in your final commit — the current code correctly uses args.length > 1 instead of checking truthiness. Good catch and clean fix.

The validation logic is correct: Number.isInteger rejects floats and NaN, the 1–65535 range check is right, and the ?? default preserves existing behavior for no-arg invocations. The help-flag ordering (check before length guard) is also correct — --help as the sole arg exits cleanly.

One minor gap: the test suite covers all invalid paths but doesn't include a happy-path case for a valid non-default port (e.g. node script.mjs 9000 should exit 0). It's not blocking — the underlying WebSocket path is unchanged — but a positive test would complete the coverage story. Up to you whether to add it here or in a follow-up.

Copy link
Copy Markdown
Contributor

@graycyrus graycyrus left a comment

Choose a reason for hiding this comment

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

Code review: 0 critical, 0 major, 0 minor. This is clean.

Summary

This PR adds proper CLI argument validation to mock-webview-bridge.mjs before starting the WebSocket server. Instead of passing NaN into WebSocketServer (which produces cryptic low-level errors), the script now:

  • Validates the optional port argument (must be an integer 1-65535)
  • Supports --help / -h flag
  • Exits with code 2 for invalid input (non-integer, out-of-range, extra args)
  • Preserves the default 9826 port when no arg is supplied

Tests comprehensively cover the negative cases (help, invalid ports, out-of-range, extra args including empty strings).

Code Review

Implementation quality: Solid. The validation logic is correct—Number.isInteger() handles NaN and floats properly, the 1-65535 range is right, and help-flag ordering (checked before length guard) is correct.

Test coverage: Good for negative paths. The test suite covers help output, non-integers, boundaries (0, 65536), and the edge case of empty-string args that CodeRabbit originally flagged. Already fixed in commit d63cbc8 using args.length > 1 instead of truthiness check.

Minor observation (not blocking): No happy-path test for a valid non-default port (e.g. node script.mjs 9000). The underlying WebSocket path is unchanged, so this doesn't affect correctness, but a positive case would round out coverage. Worth adding if you're touching this again, otherwise a follow-up is fine.

AI slop: None detected. Clean, minimal, well-named functions. No excessive comments or over-engineering.

Security: No injection, no secrets, no dynamic code execution. Port validation is correct.

AI Summary

  • What it does: Validates mock bridge port argument before server startup; supports --help; exits cleanly on invalid input with code 2.
  • Breaking risk: Zero (dev tool only).
  • Security risk: Zero.
  • Bottom line: Safe to merge once CI passes.

Blocker

CI is currently failing on "Rust Core Coverage (cargo-llvm-cov)" with a cache error. This is a pre-existing infrastructure issue unrelated to this PR (which only touches .mjs files). @sanil-23 noted the same—once that clears up, this is ready to approve.

—Cyrus

Copy link
Copy Markdown
Contributor

@graycyrus graycyrus left a comment

Choose a reason for hiding this comment

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

Continuation review: New test commit looks solid. The test file properly validates the --help flag and error conditions (invalid ports, extra args). Validation logic is clean and handles edge cases correctly.

Code remains good—awaiting the pending E2E and coverage checks to complete. Once those green, this is ready to go.

@senamakel senamakel merged commit 2a67e6a into tinyhumansai:main Jun 2, 2026
17 of 19 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.

4 participants