Skip to content

Conversation

@Adez017
Copy link
Contributor

@Adez017 Adez017 commented Aug 8, 2025

Hi @Hiteshydv001 , as per requested in #21 , i had added the necessary changes . please take a look

Summary by CodeRabbit

  • New Features

    • Agent cards now display a visual badge indicating the agent's current call status.
    • The agent's call status is dynamically updated and tracked throughout the call lifecycle.
    • The phone number input and call button are disabled when the agent is busy.
    • Agent call status is included in API responses.
  • Chores

    • Added a script to set the default call status for existing agents in the database.

@Adez017
Copy link
Contributor Author

Adez017 commented Aug 8, 2025

Also worth to mentioned you need to execute

cd backend
python migration_add_agent_status.py

and you can check by :

docker-compose up -d

to verify the calls we can visit :

curl http://localhost:8000/api/v1/agents/

curl -X PUT "http://localhost:8000/api/v1/agents/1/status?status=completed

@Adez017
Copy link
Contributor Author

Adez017 commented Aug 8, 2025

i cant able to run the migration file as i had some version conflict on my system

@coderabbitai
Copy link

coderabbitai bot commented Aug 8, 2025

Walkthrough

The changes implement a comprehensive agent call status tracking system across the backend and frontend. The backend now updates and persists an agent's last_call_status throughout the call lifecycle, including in campaign operations. The frontend displays this status with a badge and disables call controls when the agent is busy. A migration script initializes the new status field for existing agents.

Changes

Cohort / File(s) Change Summary
Frontend Agent Status Display
frontend/src/components/AgentCard.jsx
Enhanced the AgentCard component to show a badge indicating the agent's current call status, with dynamic color, text, and icon. Disabled call controls when the agent is busy, and updated call button text based on status. Refactored layout and removed debug code.
Backend Agent Status Tracking
backend/src/api/routes/calls.py
backend/src/services/campaign_service.py
Updated agent's last_call_status at all key points in call and campaign lifecycles: set to "calling" when a call starts, "completed" or "failed" based on outcomes, and reset to "idle" after completion. Status changes are committed to the database and logged. Error handling ensures status reflects failures. No changes to public API signatures.
Agent Schema Update
backend/src/schemas/agent.py
Added an optional last_call_status string field to the Agent schema, defaulting to "idle", to include status in serialized API responses.
Agent Status Migration Script
backend/set_default_agent_status.py
Introduced a standalone script to set last_call_status to "idle" for existing agents missing this field. Iterates over agents, updates status, commits changes, and provides summary output. Designed for one-time use after schema update.

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.


🪧 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.
  • 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.

Support

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

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 sequence diagram to generate a sequence diagram of the changes in 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.

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)
frontend/src/components/StatusBadge.jsx (1)

37-41: Clarify time-zone handling for lastCallTime.

new Date(timeString).toLocaleString() uses the client’s locale/time-zone, which can confuse users distributed across regions. Consider formatting on the server or using toUTCString()/Intl.DateTimeFormat with an explicit zone so everyone sees the same reference.

frontend/src/components/AgentCard.jsx (1)

39-53: Minor UX tweak: prevent header wrap jitter on narrow screens.

Long agent names push the badge to a second line, causing layout jump. Adding flex-shrink:0 on the badge (or white-space:nowrap on the name) keeps the row stable:

-<StatusBadge 
-  status={agent.last_call_status || 'idle'} 
-  lastCallTime={agent.last_call_time}
/>
+<StatusBadge
+  style={{ flexShrink: 0 }}
+  status={agent.last_call_status || 'idle'}
+  lastCallTime={agent.last_call_time}
/>

Purely cosmetic, but improves readability on mobile.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ac78c31 and 5031be9.

📒 Files selected for processing (3)
  • backend/migration_add_agent_status.py (1 hunks)
  • frontend/src/components/AgentCard.jsx (2 hunks)
  • frontend/src/components/StatusBadge.jsx (1 hunks)

@213sanjana 213sanjana added GSSoc'25 Level 2 Intermediate difficulty. Needs some experience. labels Aug 8, 2025
@213sanjana
Copy link
Collaborator

@Adez017 Can you provide a demo video

@Adez017
Copy link
Contributor Author

Adez017 commented Aug 9, 2025

No need for any demo, just the thing is i can't able to run the

cd backend
python migration_add_agent_status.py

as there is version conflict for python in my environment

@Adez017
Copy link
Contributor Author

Adez017 commented Aug 9, 2025

when you run the file i twill update the schema in the DB and the frontend part will be reflected

@Adez017
Copy link
Contributor Author

Adez017 commented Aug 9, 2025

image

see the issue , i had all the things are installed and after that the things are conflciting , because i had two python installed that makes all the root issue . it would be great if anyone could help out

@213sanjana
Copy link
Collaborator

I think theres no pip installed in it

Try

For this
C:\msys64\ucrt64\bin\python.exe
You can install pip into it manually.

  1. Install pip for this Python

python -m ensurepip --upgrade

This will bootstrap pip in that specific Python environment.

  1. Upgrade pip

python -m pip install --upgrade pip

  1. Install SQLAlchemy

python -m pip install sqlalchemy

@Hiteshydv001
Copy link
Member

what changes have you done with UI as this pr pr was regarding UI update

@Hiteshydv001
Copy link
Member

You have also removed this thing

image

@Hiteshydv001
Copy link
Member

image

You have also removed delete contact button

@Hiteshydv001
Copy link
Member

image

Original one

@Adez017
Copy link
Contributor Author

Adez017 commented Aug 10, 2025

let me revert back the changes

@Adez017
Copy link
Contributor Author

Adez017 commented Aug 10, 2025

Hi @Hiteshydv001 @213sanjana , i had made the correct chnages, i guess i mixed up some ither repo changes there. Sorry for the inconvenience, just one work to do , only one time we need to run the file :

set_default_agent_status.py

to get teh chnages reflected in DB. please look aournd if git any issues let me know

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

🧹 Nitpick comments (3)
backend/src/services/campaign_service.py (2)

7-10: Drop unused imports flagged by Ruff

campaign_schema and agent_service aren’t referenced in this module.

-from ..schemas import campaign as campaign_schema
-from .agent_service import agent_service

127-132: Agent may remain non-idle after campaign ends

The reset to "idle" triggers only if the last status was still "calling". After a successful or failed final call, the agent remains "completed" / "failed", leaving the UI in a busy state.

Consider unconditionally resetting, or adding a configurable post-campaign status policy.

backend/src/api/routes/calls.py (1)

51-59: Preserve traceback when re-raising HTTP errors

Ruff B904: use exception chaining for clarity.

-    except Exception as e:
-        db_agent.last_call_status = "failed"
-        db.commit()
-        raise HTTPException(status_code=500, detail=f"Failed to initiate call. Error: {str(e)}")
+    except Exception as e:
+        db_agent.last_call_status = "failed"
+        db.commit()
+        raise HTTPException(status_code=500,
+                            detail="Failed to initiate call.") from e
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5031be9 and b0d698f.

📒 Files selected for processing (5)
  • backend/set_default_agent_status.py.py (1 hunks)
  • backend/src/api/routes/calls.py (5 hunks)
  • backend/src/schemas/agent.py (1 hunks)
  • backend/src/services/campaign_service.py (7 hunks)
  • frontend/src/components/AgentCard.jsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/src/components/AgentCard.jsx
🧰 Additional context used
🧬 Code Graph Analysis (2)
backend/src/schemas/agent.py (1)
backend/src/models/agent.py (1)
  • Agent (5-11)
backend/set_default_agent_status.py.py (2)
backend/src/schemas/agent.py (1)
  • Agent (12-18)
backend/src/models/agent.py (1)
  • Agent (5-11)
🪛 Ruff (0.12.2)
backend/src/services/campaign_service.py

8-8: ..schemas.campaign imported but unused

Remove unused import: ..schemas.campaign

(F401)


10-10: .agent_service.agent_service imported but unused

Remove unused import: .agent_service.agent_service

(F401)

backend/src/api/routes/calls.py

54-54: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

🔇 Additional comments (1)
backend/set_default_agent_status.py.py (1)

29-31: Attribute check will still fail without mapped column

hasattr(..., 'last_call_status') is true only if the ORM model already defines the column. Without it (see previous comment) the assignment here will raise. Merge this script after the model & Alembic migration are in place.

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 (3)
backend/set_default_agent_status.py (3)

10-12: Prefer robust import pathing; avoid brittle sys.path hacks

Using pathlib is more robust and cross-platform. Alternatively, run the script with PYTHONPATH or package entry-points.

Apply:

+from pathlib import Path
@@
-# Add the src directory to the Python path
-sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
+# Add the src directory to the Python path
+sys.path.insert(0, str(Path(__file__).resolve().parent / 'src'))

33-41: Guard potentially sensitive output and large dumps behind a verbosity flag

Printing all agent names/statuses may leak PII and spam logs for large datasets. Make it opt-in.

@@
-        # Show current status of all agents
-        print("\n📋 Current agent statuses:")
-        for agent in agents:
-            print(f"  Agent {agent.id} ({agent.name}): {agent.last_call_status}")
+        if os.getenv("VERBOSE", "0") == "1":
+            print("\n📋 Current agent statuses:")
+            # Optionally cap to first N rows
+            N = int(os.getenv("PRINT_LIMIT", "50"))
+            rows = db.query(Agent.id, Agent.name, Agent.last_call_status).limit(N).all()
+            for agent_id, agent_name, status in rows:
+                print(f"  Agent {agent_id} ({agent_name}): {status}")
+            remaining = db.query(Agent).count() - len(rows)
+            if remaining > 0:
+                print(f"  ... and {remaining} more")

42-46: Exit non-zero on failure and include traceback for easier debugging

Catching Exception and printing a line hides the stacktrace and returns 0. Return an error code and print the traceback.

+import traceback
@@
-    except Exception as e:
-        print(f"❌ Error updating agents: {e}")
-        db.rollback()
+    except Exception as e:
+        print(f"❌ Error updating agents: {e}")
+        traceback.print_exc()
+        db.rollback()
+        sys.exit(1)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b0d698f and 28cda01.

📒 Files selected for processing (1)
  • backend/set_default_agent_status.py (1 hunks)
🔇 Additional comments (1)
backend/set_default_agent_status.py (1)

21-35: Use a single bulk UPDATE for scalability

Fetching and updating every Agent in Python loads all rows into memory and incurs extra round-trips. Replace the per-row loop with one SQL UPDATE statement.

• File to update: backend/set_default_agent_status.py

Choose the implementation that matches your SQLAlchemy version:

Option A – ORM-style bulk UPDATE (works in SQLAlchemy 1.4+):

 from sqlalchemy import or_
@@
-    db = SessionLocal()
-    try:
-        # Get all agents
-        agents = db.query(Agent).all()
-        
-        updated_count = 0
-        for agent in agents:
-            # Set to idle if no status or empty status
-            if not hasattr(agent, 'last_call_status') or not agent.last_call_status:
-                agent.last_call_status = 'idle'
-                updated_count += 1
-        
-        db.commit()
-        print(f"✅ Updated {updated_count} agents to 'idle' status")
-        print(f"📊 Total agents in database: {len(agents)}")
+    db = SessionLocal()
+    try:
+        updated_count = (
+            db.query(Agent)
+              .filter(or_(Agent.last_call_status == None, Agent.last_call_status == ""))
+              .update({Agent.last_call_status: "idle"}, synchronize_session=False)
+        )
+        db.commit()
+        total = db.query(Agent).count()
+        print(f"✅ Updated {updated_count} agents to 'idle' status")
+        print(f"📊 Total agents in database: {total}")

Option B – Core UPDATE (SQLAlchemy 2.x style):

 from sqlalchemy import or_, update, select
@@
-    db = SessionLocal()
-    try:
-        # Get all agents
-        agents = db.query(Agent).all()
-        
-        updated_count = 0
-        for agent in agents:
-            # Set to idle if no status or empty status
-            if not hasattr(agent, 'last_call_status') or not agent.last_call_status:
-                agent.last_call_status = 'idle'
-                updated_count += 1
-        
-        db.commit()
-        print(f"✅ Updated {updated_count} agents to 'idle' status")
-        print(f"📊 Total agents in database: {len(agents)}")
+    db = SessionLocal()
+    try:
+        result = db.execute(
+            update(Agent)
+            .where(or_(Agent.last_call_status == None, Agent.last_call_status == ""))
+            .values(last_call_status="idle")
+        )
+        db.commit()
+        updated_count = result.rowcount or 0
+        total = db.execute(select(Agent).count()).scalar_one()
+        print(f"✅ Updated {updated_count} agents to 'idle' status")
+        print(f"📊 Total agents in database: {total}")

To determine which option to apply, check your installed SQLAlchemy version:

python -c "import sqlalchemy; print(sqlalchemy.__version__)"

If you’re not pinning a version, consider adding one (e.g., sqlalchemy>=1.4,<2.0 or sqlalchemy>=2.0) in backend/requirements.txt.

@Adez017
Copy link
Contributor Author

Adez017 commented Aug 12, 2025

Hi @Hiteshydv001 . please look into it

@Hiteshydv001
Copy link
Member

@Adez017 attach a video and try to build the project with docker

@Hiteshydv001
Copy link
Member

How uch more time will be required

@Hiteshydv001
Copy link
Member

because it take a lot of time to test it on codespace due to less cloud storage

@Hiteshydv001
Copy link
Member

Any updates @Adez017 ??

@Adez017
Copy link
Contributor Author

Adez017 commented Aug 23, 2025

Any updates @Adez017 ??

does we have any simpler sample code to test it , if possible we can proceed with that

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

GSSoc'25 Level 2 Intermediate difficulty. Needs some experience.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants