Skip to content

Conversation

loRes228
Copy link

@loRes228 loRes228 commented Aug 26, 2025

Add total parameter to Progress widget and update percentage calculation to use absolute values.

Summary by CodeRabbit

  • New Features

    • Progress widget now supports a configurable total value (default 100), allowing progress to be computed from arbitrary counts.
  • Refactor

    • Unified percent calculation between preview and runtime for consistent progress rendering; no expected visual change.

Copy link

coderabbitai bot commented Aug 26, 2025

Walkthrough

Adds a total parameter to Progress, stores it on the instance, and unifies percentage computation by deriving percent from value/total in _render_text for both preview and runtime paths.

Changes

Cohort / File(s) Summary of changes
Progress widget API and render logic
src/aiogram_dialog/widgets/text/progress.py
Added constructor parameter total: int = 100 and self.total. Refactored _render_text to set value (15 in preview, data.get(self.field) otherwise) and then compute percent = (value / self.total) * 100. Rendered output remains based on the computed percent.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Caller
  participant Progress
  participant Data as Data Context

  Caller->>Progress: init(field, width, total, filled, empty, when)
  Note right of Progress#lightgreen: Store `total` on instance

  Caller->>Progress: _render_text(data, manager)\npreview or runtime
  alt Preview mode
    Progress->>Progress: value = 15
  else Runtime mode
    Progress->>Data: get(field)
    Data-->>Progress: value
  end
  Progress->>Progress: percent = (value / total) * 100
  Progress-->>Caller: Rendered bar string
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I nibbled code like clover sprigs,
Tucked total in my handy digs;
Value set, then percent is born,
Bars now scale from dusk to morn.
Hop-hop, the progress rabbit grins—🥕✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between e2e84f2 and cf9890a.

📒 Files selected for processing (1)
  • src/aiogram_dialog/widgets/text/progress.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/aiogram_dialog/widgets/text/progress.py
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

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: 2

🧹 Nitpick comments (2)
src/aiogram_dialog/widgets/text/progress.py (2)

27-29: Preview semantics likely shifted; confirm intended behavior

With value = 15 and new percent computed as (value / self.total) * 100, preview percent now depends on total. Previously preview was 15% (effectively), now it is 15/total * 100. If total != 100, preview no longer shows a stable 15% bar.

If the goal is a consistent preview of 15%, compute value from total.

-        if manager.is_preview():
-            value = 15
+        if manager.is_preview():
+            # keep preview at a stable 15% regardless of total
+            value = self.total * 0.15

24-36: Add tests covering total, clamping, and preview behavior

Please add unit tests that verify:

  • Backward compatibility for positional args when total is moved to the end.
  • total <= 0 raises ValueError.
  • Missing field defaults to 0% without raising.
  • Negative value is rendered as positive percent (abs applied) and clamped to 100% for large values.
  • Preview displays a stable 15% (if you accept the preview refactor).

I can draft tests for these scenarios once you confirm the desired preview semantics and final constructor signature.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 8da6e9d and e2e84f2.

📒 Files selected for processing (1)
  • src/aiogram_dialog/widgets/text/progress.py (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/aiogram_dialog/widgets/text/progress.py (4)
src/aiogram_dialog/widgets/text/base.py (4)
  • _render_text (32-38)
  • _render_text (74-77)
  • _render_text (86-90)
  • _render_text (128-135)
src/aiogram_dialog/manager/manager.py (1)
  • is_preview (135-136)
src/aiogram_dialog/tools/preview.py (1)
  • is_preview (153-154)
src/aiogram_dialog/manager/sub_manager.py (1)
  • is_preview (65-66)
🔇 Additional comments (1)
src/aiogram_dialog/widgets/text/progress.py (1)

8-16: I’m running a quick grep sweep to confirm the constructor signature and existing usages of Progress—I’ll follow up once we see where and how it’s instantiated to decide if we should move total.

Comment on lines 17 to 22
super().__init__(when)
self.field = field
self.width = width
self.total = total
self.filled = filled
self.empty = empty
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Validate total to prevent division-by-zero and invalid input

total can be 0 or negative, causing a ZeroDivisionError or nonsensical output. Add a guard.

         self.field = field
         self.width = width
-        self.total = total
+        if total <= 0:
+            raise ValueError("Progress.total must be a positive number")
+        self.total = total
         self.filled = filled
         self.empty = empty
📝 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
super().__init__(when)
self.field = field
self.width = width
self.total = total
self.filled = filled
self.empty = empty
super().__init__(when)
self.field = field
self.width = width
if total <= 0:
raise ValueError("Progress.total must be a positive number")
self.total = total
self.filled = filled
self.empty = empty
🤖 Prompt for AI Agents
In src/aiogram_dialog/widgets/text/progress.py around lines 17 to 22, the
constructor accepts a total that may be zero or negative which can lead to
ZeroDivisionError or invalid output; add an explicit guard that validates total
is a positive integer (e.g. if not isinstance(total, int) or total <= 0: raise
ValueError("total must be a positive integer")), and update any callers/tests
accordingly so the widget never proceeds with total <= 0.

Comment on lines 28 to 33
value = 15
else:
percent = data.get(self.field)
value = data.get(self.field)
percent = (value / self.total) * 100
done = round((self.width * percent) / 100)
rest = self.width - done
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Handle missing/non-numeric values and clamp percent to [0, 100]; apply abs() as per PR description

  • data.get(self.field) may return None, leading to TypeError on division.
  • The PR description says “use absolute values”, but abs() isn’t applied.
  • Large or negative values can produce bars longer than width or negative segments. Clamp percent to [0, 100] to keep the bar stable.
-        else:
-            value = data.get(self.field)
-        percent = (value / self.total) * 100
-        done = round((self.width * percent) / 100)
+        else:
+            raw = data.get(self.field, 0)
+            try:
+                value = float(raw)
+            except (TypeError, ValueError):
+                value = 0.0
+        percent = max(0.0, min(100.0, (abs(value) / self.total) * 100))
+        done = round((self.width * percent) / 100)
         rest = self.width - done

Notes:

  • This keeps rendering within width and aligns with the “absolute values” intent.
  • If you prefer integer-only arithmetic, we can cast early and keep the same behavior.

🏁 Script executed:

#!/bin/bash
# Verify percent calculation and value assignment in src/aiogram_dialog/widgets/text/progress.py
rg -n -C3 'percent\s*=' src/aiogram_dialog/widgets/text/progress.py
rg -n -C3 'value\s*=' src/aiogram_dialog/widgets/text/progress.py

Length of output: 701


🏁 Script executed:

sed -n '1,200p' src/aiogram_dialog/widgets/text/progress.py

Length of output: 1015


Ensure robust handling of progress values in Progress._render_text

The current implementation will raise a TypeError if data.get(self.field) returns None, and negative or oversized values can produce invalid bar lengths. Per the PR description, values should be treated absolutely and confined to the [0,100] range. Update the assignment and calculation as follows:

• File: src/aiogram_dialog/widgets/text/progress.py, method _render_text (around lines 28–33)

-        if manager.is_preview():
-            value = 15
-        else:
-            value = data.get(self.field)
-        percent = (value / self.total) * 100
-        done = round((self.width * percent) / 100)
-        rest = self.width - done
+        if manager.is_preview():
+            value = 15.0
+        else:
+            raw = data.get(self.field, 0)
+            try:
+                value = float(raw)
+            except (TypeError, ValueError):
+                value = 0.0
+        # Use absolute value and clamp percent to [0,100] to avoid overflows
+        percent = max(0.0, min(100.0, (abs(value) / self.total) * 100))
+        done = round((self.width * percent) / 100)
+        rest = self.width - done

• Fallback non-numeric or missing inputs to 0.0
• Apply abs() to match PR intent
• Clamp percent between 0.0 and 100.0 to guarantee bar stability

📝 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
value = 15
else:
percent = data.get(self.field)
value = data.get(self.field)
percent = (value / self.total) * 100
done = round((self.width * percent) / 100)
rest = self.width - done
if manager.is_preview():
value = 15.0
else:
raw = data.get(self.field, 0)
try:
value = float(raw)
except (TypeError, ValueError):
value = 0.0
# Use absolute value and clamp percent to [0,100] to avoid overflows
percent = max(0.0, min(100.0, (abs(value) / self.total) * 100))
done = round((self.width * percent) / 100)
rest = self.width - done

@loRes228 loRes228 requested a review from Tishka17 August 30, 2025 21:29
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