Skip to content

Conversation

@mrlitong
Copy link
Collaborator

@mrlitong mrlitong commented Jul 26, 2025

The --plan parameter was being ignored due to disabled CLI parsing in settings_customise_sources. This fix manually parses CLI arguments in load_with_last_used method to ensure command-line parameters take effect properly.

  • Parse CLI arguments manually in load_with_last_used
  • Handle both value parameters and boolean flags correctly
  • Add test case to verify plan parameter parsing
  • Maintain backward compatibility with existing functionality

Fixes the issue where running python3 -m claude_monitor --plan max20 would still show "custom" plan instead of "max20".

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Improved reliability of command-line argument parsing for settings, ensuring correct merging with previously used parameters and accurate handling of flags such as plan selection and clearing settings.
  • Tests

    • Added tests to verify correct parsing of the plan parameter from command-line arguments.

The --plan parameter was being ignored due to disabled CLI parsing
in settings_customise_sources. This fix manually parses CLI arguments
in load_with_last_used method to ensure command-line parameters
take effect properly.

- Parse CLI arguments manually in load_with_last_used
- Handle both value parameters and boolean flags correctly
- Add test case to verify plan parameter parsing
- Maintain backward compatibility with existing functionality

Fixes the issue where running `python3 -m claude_monitor --plan max20`
would still show "custom" plan instead of "max20".

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@coderabbitai
Copy link

coderabbitai bot commented Jul 26, 2025

Walkthrough

The Settings.load_with_last_used method was refactored to manually parse CLI arguments and explicitly merge them with persisted last-used parameters, replacing the previous implicit parsing approach. A new test was added to verify that the plan parameter is correctly parsed from CLI arguments when loading settings.

Changes

File(s) Change Summary
src/claude_monitor/core/settings.py Refactored Settings.load_with_last_used to manually parse CLI arguments and merge with last-used parameters. Removed reliance on internal _cli_parse_args.
src/tests/test_settings.py Added test to verify correct parsing of the plan parameter from CLI arguments in load_with_last_used.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Poem

A bunny with code on its mind,
Hopped through settings, new logic to find.
Now CLI and last-used, together they blend,
With tests for the plan, the bugs met their end.
In burrows of Python, the changes are clear—
This rabbit reviews with a cheer! 🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/cli-plan-parameter-parsing

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@mrlitong
Copy link
Collaborator Author

@Maciek-roboblog This fixes a critical bug where CLI arguments are completely ignored. Would appreciate a priority review as this blocks users from selecting their subscription plans via command line.

Copy link

@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: 0

🧹 Nitpick comments (3)
src/claude_monitor/core/settings.py (2)

272-296: Consider enhancing the CLI argument parser to handle additional scenarios.

The manual CLI parsing implementation works for the basic use case but has several limitations:

  1. Doesn't support equals-sign syntax (e.g., --plan=max20)
  2. No error handling for unrecognized arguments
  3. Doesn't support short flags
  4. The boolean flag detection could misinterpret valid values that start with --

Consider using a more robust parsing approach:

 # Parse CLI arguments manually
 cli_args = {}
 cli_provided_fields = set()
 if argv:
     i = 0
     while i < len(argv):
         arg = argv[i]
         if arg.startswith("--"):
-            field_name = arg[2:].replace("-", "_")
+            # Handle both --key=value and --key value formats
+            if "=" in arg:
+                key, value = arg.split("=", 1)
+                field_name = key[2:].replace("-", "_")
+                if field_name in cls.model_fields:
+                    cli_provided_fields.add(field_name)
+                    cli_args[field_name] = value
+                i += 1
+            else:
+                field_name = arg[2:].replace("-", "_")
             if field_name in cls.model_fields:
                 cli_provided_fields.add(field_name)
                 # Check if this is a boolean flag or requires a value
                 if i + 1 < len(argv) and not argv[i + 1].startswith("--"):
                     # Has a value
                     cli_args[field_name] = argv[i + 1]
                     i += 2
                 else:
                     # Boolean flag
                     cli_args[field_name] = True
                     i += 1
             else:
+                # Log or handle unrecognized arguments
+                logger.debug(f"Unrecognized argument: {arg}")
                 i += 1
         else:
             i += 1

308-310: Document why "plan" is excluded from last_params.

The code excludes "plan" from being loaded from last_params, but the reason isn't documented. This design decision should be explained for future maintainers.

Add a comment explaining the rationale:

 for key, value in last_params.items():
+    # Skip "plan" to ensure it's always explicitly set via CLI or defaults to "custom"
     if key == "plan":
         continue
src/tests/test_settings.py (1)

576-594: Expand test coverage for the CLI plan parsing.

The test validates the basic functionality but could be more comprehensive to ensure robustness.

Consider adding these test cases:

def test_load_with_last_used_plan_parsing_comprehensive(
    self, mock_timezone: Mock, mock_time_format: Mock
) -> None:
    """Test comprehensive plan parameter parsing scenarios."""
    mock_timezone.return_value = "UTC"
    mock_time_format.return_value = "24h"

    with patch("claude_monitor.core.settings.LastUsedParams") as MockLastUsed:
        mock_instance = Mock()
        MockLastUsed.return_value = mock_instance

        # Test all valid plan values including "custom"
        for plan in ["pro", "max5", "max20", "custom"]:
            mock_instance.load.return_value = {}
            settings = Settings.load_with_last_used(["--plan", plan])
            assert settings.plan == plan

        # Test CLI overrides last_used plan
        mock_instance.load.return_value = {"plan": "pro"}  # This should be ignored
        settings = Settings.load_with_last_used(["--plan", "max20"])
        assert settings.plan == "max20"

        # Test without CLI plan argument (should default to "custom")
        mock_instance.load.return_value = {}
        settings = Settings.load_with_last_used([])
        assert settings.plan == "custom"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 06f0fe1 and e0e1585.

📒 Files selected for processing (2)
  • src/claude_monitor/core/settings.py (1 hunks)
  • src/tests/test_settings.py (1 hunks)

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.

2 participants