Skip to content

feat: Add debug logging toggle#652

Draft
emranemran wants to merge 1 commit intomainfrom
emran/debug-logs
Draft

feat: Add debug logging toggle#652
emranemran wants to merge 1 commit intomainfrom
emran/debug-logs

Conversation

@emranemran
Copy link
Contributor

@emranemran emranemran commented Mar 10, 2026

Summary

  • Add --debug CLI flag and SCOPE_DEBUG env var to start the server with DEBUG-level logging
  • Add GET/PUT /api/v1/logs/debug API endpoints to toggle debug logging at runtime, with @cloud_proxy support so it works in both local and cloud mode
  • Add a Debug ON/OFF toggle button in the log panel toolbar

Test plan

  • Run uv run daydream-scope --debug and verify DEBUG lines appear in the log panel
  • Run normally, open log panel, click "Debug OFF" button — verify it switches to "Debug ON" and DEBUG logs start appearing
  • Verify toggle works in cloud mode (proxied to fal backend)
  • npm run build passes

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • New Features
    • Added runtime debug logging control—toggle verbose logging on/off from the interface without restarting the application
    • New --debug command-line flag enables debug mode during application startup
    • Debug status indicator displays current logging level with real-time synchronization
    • Debug settings persist across application reloads

Add --debug CLI flag and SCOPE_DEBUG env var to enable DEBUG-level
logging at startup. Add runtime toggle via GET/PUT /api/v1/logs/debug
endpoints (with cloud proxy support) and a Debug ON/OFF button in the
log panel toolbar.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Signed-off-by: emranemran <emran.mah@gmail.com>
@coderabbitai
Copy link

coderabbitai bot commented Mar 10, 2026

📝 Walkthrough

Walkthrough

This PR adds runtime DEBUG logging control to both the frontend and backend. The backend implements GET and PUT endpoints for querying and toggling debug logging status, a CLI --debug flag for initialization, and persists the setting via the SCOPE_DEBUG environment variable. The frontend adds a debug toggle button in the LogPanel toolbar that communicates with these endpoints.

Changes

Cohort / File(s) Summary
Debug Logging UI
frontend/src/components/LogPanel.tsx
Adds debugEnabled and debugLoading state, fetches initial debug status on mount, implements handleDebugToggle() via PUT request, and displays a toggleable Debug ON/OFF button in the toolbar with loading state feedback.
Backend Debug Logging Control
src/scope/server/app.py
Introduces DebugLoggingRequest model, implements GET/PUT /api/v1/logs/debug endpoints to report and modify DEBUG logging status at runtime, adds --debug CLI flag to main(), updates root and module loggers dynamically, and persists setting in SCOPE_DEBUG environment variable.

Sequence Diagram

sequenceDiagram
    participant User
    participant UI as LogPanel UI
    participant API as Backend API
    participant Logger as Logger System
    participant Env as Environment

    User->>UI: Mount LogPanel
    UI->>API: GET /api/v1/logs/debug
    API->>Logger: Check if DEBUG enabled
    Logger-->>API: Current state
    API-->>UI: debugEnabled status
    UI->>UI: Set debugEnabled state

    User->>UI: Click Debug Toggle
    UI->>UI: Set debugLoading=true
    UI->>API: PUT /api/v1/logs/debug {enabled: !current}
    API->>Logger: Update loggers to DEBUG/INFO
    API->>Env: Set SCOPE_DEBUG env var
    Env-->>API: Persisted
    API-->>UI: {enabled: newState}
    UI->>UI: Update debugEnabled state
    UI->>UI: Set debugLoading=false
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Poem

🐰 A toggle, a click, and the logs come alive,
Debug mode now dances at runtime, no jive!
Frontend and backend in harmony sing,
Debugging wisdom on DEBUG's wing! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title 'feat: Add debug logging toggle' directly and accurately describes the main change: adding a debug logging toggle feature across the frontend UI, backend API endpoints, and CLI.

✏️ 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 emran/debug-logs

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

@emranemran emranemran marked this pull request as draft March 10, 2026 16:57
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

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

Inline comments:
In `@src/scope/server/app.py`:
- Around line 2769-2771: The --debug flag currently sets
os.environ["SCOPE_DEBUG"] in main() but the module-level logging config
(executed at import) already ran, so debug only takes effect after a reload; to
fix, after setting SCOPE_DEBUG in main() call the same debug-enabling logic that
the module-level code uses (either by extracting that logic into a helper like
enable_scope_debug() and invoking it from both the module-level initialization
and from main(), or by directly re-initializing the module-level logging/config
after setting SCOPE_DEBUG) so that the debug behavior is applied immediately on
first start; reference the main() function, the SCOPE_DEBUG env var, and the
module-level debug configuration code.
- Around line 2159-2164: The get_debug_logging endpoint is decorated with
`@cloud_proxy`() but is missing the cloud_manager dependency used by other
cloud_proxy endpoints; add a cloud_manager parameter (typed as the same
CloudManager type used elsewhere) and inject it via FastAPI's Depends using the
existing cloud_manager dependency provider so the cloud_proxy behavior has the
required dependency (i.e., update the get_debug_logging function signature to
accept cloud_manager via Depends while keeping http_request: Request).
- Around line 2167-2190: The endpoint set_debug_logging uses the `@cloud_proxy`()
decorator but is missing the required cloud_manager dependency parameter; update
the function signature for set_debug_logging to accept a cloud_manager:
CloudManager (or the existing cloud_manager type) injected via Depends (same
pattern used in get_debug_logging), ensure any references keep the parameter
name cloud_manager so the decorator can access it, and import the
CloudManager/Depends symbol if not already imported.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3b4ebfc7-083b-4b93-88c0-b37971264e23

📥 Commits

Reviewing files that changed from the base of the PR and between 5d1800b and 382aee0.

📒 Files selected for processing (2)
  • frontend/src/components/LogPanel.tsx
  • src/scope/server/app.py

Comment on lines +2159 to +2164
@app.get("/api/v1/logs/debug")
@cloud_proxy()
async def get_debug_logging(http_request: Request):
"""Get current debug logging state."""
scope_logger = logging.getLogger("scope.server")
return {"enabled": scope_logger.level <= logging.DEBUG}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Missing cloud_manager dependency for cloud proxy support.

This endpoint uses @cloud_proxy() but lacks the cloud_manager dependency that all other @cloud_proxy decorated endpoints have. This will likely cause the cloud proxy functionality to fail.

🔧 Proposed fix
 `@app.get`("/api/v1/logs/debug")
 `@cloud_proxy`()
-async def get_debug_logging(http_request: Request):
+async def get_debug_logging(
+    http_request: Request,
+    cloud_manager: "CloudConnectionManager" = Depends(get_cloud_connection_manager),
+):
     """Get current debug logging state."""
     scope_logger = logging.getLogger("scope.server")
     return {"enabled": scope_logger.level <= logging.DEBUG}
📝 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
@app.get("/api/v1/logs/debug")
@cloud_proxy()
async def get_debug_logging(http_request: Request):
"""Get current debug logging state."""
scope_logger = logging.getLogger("scope.server")
return {"enabled": scope_logger.level <= logging.DEBUG}
`@app.get`("/api/v1/logs/debug")
`@cloud_proxy`()
async def get_debug_logging(
http_request: Request,
cloud_manager: "CloudConnectionManager" = Depends(get_cloud_connection_manager),
):
"""Get current debug logging state."""
scope_logger = logging.getLogger("scope.server")
return {"enabled": scope_logger.level <= logging.DEBUG}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/scope/server/app.py` around lines 2159 - 2164, The get_debug_logging
endpoint is decorated with `@cloud_proxy`() but is missing the cloud_manager
dependency used by other cloud_proxy endpoints; add a cloud_manager parameter
(typed as the same CloudManager type used elsewhere) and inject it via FastAPI's
Depends using the existing cloud_manager dependency provider so the cloud_proxy
behavior has the required dependency (i.e., update the get_debug_logging
function signature to accept cloud_manager via Depends while keeping
http_request: Request).

Comment on lines +2167 to +2190
@app.put("/api/v1/logs/debug")
@cloud_proxy()
async def set_debug_logging(http_request: Request, body: DebugLoggingRequest):
"""Enable or disable DEBUG-level logging at runtime."""
root_logger = logging.getLogger()
target_level = logging.DEBUG if body.enabled else logging.INFO

# Update all handlers
for handler in root_logger.handlers:
if isinstance(handler, (logging.StreamHandler, RotatingFileHandler)):
handler.setLevel(target_level)

# Update app loggers
for name in ("scope.server", "scope.core", "scope.cloud"):
logging.getLogger(name).setLevel(target_level)

# Persist to env so reload preserves the setting
if body.enabled:
os.environ["SCOPE_DEBUG"] = "1"
else:
os.environ.pop("SCOPE_DEBUG", None)

logger.info(f"Debug logging {'enabled' if body.enabled else 'disabled'}")
return {"enabled": body.enabled}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Missing cloud_manager dependency for cloud proxy support.

Same issue as get_debug_logging - the endpoint uses @cloud_proxy() but lacks the required cloud_manager dependency.

🔧 Proposed fix
 `@app.put`("/api/v1/logs/debug")
 `@cloud_proxy`()
-async def set_debug_logging(http_request: Request, body: DebugLoggingRequest):
+async def set_debug_logging(
+    http_request: Request,
+    body: DebugLoggingRequest,
+    cloud_manager: "CloudConnectionManager" = Depends(get_cloud_connection_manager),
+):
     """Enable or disable DEBUG-level logging at runtime."""
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/scope/server/app.py` around lines 2167 - 2190, The endpoint
set_debug_logging uses the `@cloud_proxy`() decorator but is missing the required
cloud_manager dependency parameter; update the function signature for
set_debug_logging to accept a cloud_manager: CloudManager (or the existing
cloud_manager type) injected via Depends (same pattern used in
get_debug_logging), ensure any references keep the parameter name cloud_manager
so the decorator can access it, and import the CloudManager/Depends symbol if
not already imported.

Comment on lines +2769 to +2771
# Enable debug logging via env var (picked up by module-level config on reload)
if debug:
os.environ["SCOPE_DEBUG"] = "1"
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

--debug flag doesn't enable debug logging on first start.

The module-level debug configuration (lines 179-186) runs during import, before main() sets SCOPE_DEBUG. This means --debug only takes effect on reload, not on the initial start. With reload defaulting to False, the flag effectively does nothing.

🔧 Proposed fix: Enable debug logging immediately after setting the env var
     # Enable debug logging via env var (picked up by module-level config on reload)
     if debug:
         os.environ["SCOPE_DEBUG"] = "1"
+        # Also enable immediately since module-level config has already run
+        root_logger = logging.getLogger()
+        for handler in root_logger.handlers:
+            handler.setLevel(logging.DEBUG)
+        logging.getLogger("scope.server").setLevel(logging.DEBUG)
+        logging.getLogger("scope.core").setLevel(logging.DEBUG)
+        logging.getLogger("scope.cloud").setLevel(logging.DEBUG)

Alternatively, extract the debug-enabling logic into a helper function and call it from both the module-level code and main().

📝 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
# Enable debug logging via env var (picked up by module-level config on reload)
if debug:
os.environ["SCOPE_DEBUG"] = "1"
# Enable debug logging via env var (picked up by module-level config on reload)
if debug:
os.environ["SCOPE_DEBUG"] = "1"
# Also enable immediately since module-level config has already run
root_logger = logging.getLogger()
for handler in root_logger.handlers:
handler.setLevel(logging.DEBUG)
logging.getLogger("scope.server").setLevel(logging.DEBUG)
logging.getLogger("scope.core").setLevel(logging.DEBUG)
logging.getLogger("scope.cloud").setLevel(logging.DEBUG)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/scope/server/app.py` around lines 2769 - 2771, The --debug flag currently
sets os.environ["SCOPE_DEBUG"] in main() but the module-level logging config
(executed at import) already ran, so debug only takes effect after a reload; to
fix, after setting SCOPE_DEBUG in main() call the same debug-enabling logic that
the module-level code uses (either by extracting that logic into a helper like
enable_scope_debug() and invoking it from both the module-level initialization
and from main(), or by directly re-initializing the module-level logging/config
after setting SCOPE_DEBUG) so that the debug behavior is applied immediately on
first start; reference the main() function, the SCOPE_DEBUG env var, and the
module-level debug configuration code.

@github-actions
Copy link
Contributor

🚀 fal.ai Preview Deployment

App ID daydream/scope-pr-652--preview
WebSocket wss://fal.run/daydream/scope-pr-652--preview/ws
Commit 382aee0

Testing

Connect to this preview deployment by running this on your branch:

uv run build && SCOPE_CLOUD_APP_ID="daydream/scope-pr-652--preview/ws" uv run daydream-scope

🧪 E2E tests will run automatically against this deployment.

@github-actions
Copy link
Contributor

✅ E2E Tests passed

Status passed
fal App daydream/scope-pr-652--preview
Run View logs

Test Artifacts

Check the workflow run for screenshots.

@mjh1 mjh1 self-requested a review March 10, 2026 17:21
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.

1 participant