An AI Agent that interacts with Windows OS at GUI level.
Python
feat(cli): add persistent logging level configuration
kittupriyatham81d212e7c46f
diff --git a/README.md b/README.mdindex e2f1918..be52fe2 100644--- a/README.md+++ b/README.md@@ -129,7 +129,15 @@ windows-use--model, -m LLM model to use--provider, -p LLM provider--max-steps Max steps per task (default: 200)---debug, -d Enable debug logging+--debug, -d Enable debug logging for the current session+```++**Persistent logging level:**++```bash+windows-use logging # Show current persisted log level+windows-use logging debug # Persist DEBUG (or 'verbose') to ~/.windows-use/logging_config.json+windows-use logging info # Restore default INFO level```**In-session commands:**diff --git a/tests/unit/cli/test_logging_config.py b/tests/unit/cli/test_logging_config.pynew file mode 100644index 0000000..ff94e77--- /dev/null+++ b/tests/unit/cli/test_logging_config.py@@ -0,0 +1,68 @@+import json+import logging++import pytest+from typer.testing import CliRunner++from windows_use.cli import __main__ as cli_main+from windows_use.cli import config as cli_config+++def isolated_logging_config(tmp_path, monkeypatch):+ config_dir = tmp_path / ".windows-use"+ config_file = config_dir / "logging_config.json"+ monkeypatch.setattr(cli_config, "WINDOWS_USE_DIR", config_dir)+ monkeypatch.setattr(cli_config, "LOGGING_CONFIG_FILE", config_file)+ monkeypatch.setattr(cli_main, "LOGGING_CONFIG_FILE", config_file)+ return config_file+++def test_default_logging_level_is_info(isolated_logging_config):+ assert cli_config.get_logging_config() == {"level": "INFO"}+ assert cli_config.get_log_level() == "INFO"+++def test_save_logging_config_accepts_verbose_alias(isolated_logging_config):+ saved = cli_config.save_logging_config("verbose")+ assert saved == {"level": "DEBUG"}+ assert json.loads(isolated_logging_config.read_text(encoding="utf-8")) == {"level": "DEBUG"}+ assert cli_config.get_log_level() == "DEBUG"+++def test_save_logging_config_rejects_invalid_level(isolated_logging_config):+ with pytest.raises(ValueError, match="Invalid log level"):+ cli_config.save_logging_config("loud")+++def test_invalid_file_falls_back_to_info(isolated_logging_config):+ isolated_logging_config.parent.mkdir(parents=True, exist_ok=True)+ isolated_logging_config.write_text("{not json", encoding="utf-8")+ assert cli_config.get_log_level() == "INFO"+++def test_apply_logging_config_updates_loggers(isolated_logging_config):+ cli_config.save_logging_config("debug")+ numeric = cli_config.apply_logging_config()+ assert numeric == logging.DEBUG+ assert logging.getLogger("windows_use").level == logging.DEBUG+ assert logging.getLogger("windows_use.speech.service").level == logging.DEBUG++ cli_config.apply_logging_config("INFO")+ assert logging.getLogger("windows_use").level == logging.INFO+++def test_cli_logging_command_persists_and_shows_level(isolated_logging_config):+ runner = CliRunner()++ res_show = runner.invoke(cli_main.app, ["logging"])+ assert res_show.exit_code == 0+ assert "INFO" in res_show.stdout++ res_set = runner.invoke(cli_main.app, ["logging", "verbose"])+ assert res_set.exit_code == 0+ assert "DEBUG" in res_set.stdout+ assert cli_config.get_log_level() == "DEBUG"++ res_bad = runner.invoke(cli_main.app, ["logging", "bogus"])+ assert res_bad.exit_code == 1diff --git a/windows_use/agent/service.py b/windows_use/agent/service.pyindex 1e58234..53d160f 100644--- a/windows_use/agent/service.py+++ b/windows_use/agent/service.py@@ -27,6 +27,7 @@ from windows_use.agent.views import AgentResult, AgentStatefrom windows_use.agent.watchdog.service import WatchDogfrom windows_use.messages import AIMessage, HumanMessage, ImageMessage, SystemMessage, ToolMessagefrom windows_use.providers.events import LLMEventType+from windows_use.cli.config import apply_logging_configfrom windows_use.telemetry.service import ProductTelemetryfrom windows_use.telemetry.views import AgentTelemetryEvent@@ -34,7 +35,7 @@ if TYPE_CHECKING:from windows_use.providers.base import BaseChatLLMlogger = logging.getLogger("windows_use")-logger.setLevel(logging.INFO)+apply_logging_config()handler = logging.StreamHandler()formatter = logging.Formatter("[%(levelname)s] %(message)s")handler.setFormatter(formatter)diff --git a/windows_use/cli/__main__.py b/windows_use/cli/__main__.pyindex 5a6a388..6e06c06 100644--- a/windows_use/cli/__main__.py+++ b/windows_use/cli/__main__.py@@ -12,7 +12,13 @@ from dotenv import load_dotenvfrom prompt_toolkit import PromptSessionfrom prompt_toolkit.completion import Completer, Completion-from windows_use.cli.config import get_active_config+from windows_use.cli.config import (+ LOGGING_CONFIG_FILE,+ apply_logging_config,+ get_active_config,+ get_log_level,+ save_logging_config,+)from windows_use.cli.registry import PROVIDER_DISPLAY, get_provider_displayload_dotenv()@@ -139,8 +145,7 @@ def _callback(),) -> None:"""Interactive CLI: accept tasks, execute them, show intermediates, wait for next."""- if debug:- logging.getLogger("windows_use.speech.service").setLevel(logging.DEBUG)+ apply_logging_config("DEBUG" if debug else None)if version_flag:typer.echo("Windows-Use ", nl=False)typer.secho(f"v{_version()}", fg="green", nl=False)@@ -154,6 +159,31 @@ def _callback(_run_interactive(provider=provider_key, model=model_id, max_steps=max_steps, debug=debug)[email protected]("logging")+def logging_cmd(+ level: str | None = typer.Argument(+ None,+ help="Log level to persist (debug, verbose, info, warning, error, critical). Omit to show current.",+ ),+) -> None:+ """View or persist the default logging level in ~/.windows-use/logging_config.json."""+ if level is None:+ typer.echo(f"Current logging level: {get_log_level()} ({LOGGING_CONFIG_FILE})")+ return++ try:+ cfg = save_logging_config(level)+ except ValueError as exc:+ typer.secho(str(exc), fg="red", err=True)+ raise typer.Exit(code=1) from exc++ apply_logging_config(cfg["level"])+ typer.secho(+ f"Saved logging level: {cfg['level']} ({LOGGING_CONFIG_FILE})",+ fg="green",+ )++# Commands available when typing \ (backslash): (command, description)_CLI_COMMANDS = (("\\quit", "Exit the session"),@@ -195,7 +225,13 @@ def _clear_screen() -> None:def _run_interactive(provider: str, model: str, max_steps: int, debug: bool = False) -> None:"""Run the interactive task loop."""from windows_use.agent import Agent, Browser- from windows_use.cli.config import get_active_config+ from windows_use.cli.config import (+ LOGGING_CONFIG_FILE,+ apply_logging_config,+ get_active_config,+ get_log_level,+ save_logging_config,+)from windows_use.cli.setup import (create_llm,create_stt_provider,diff --git a/windows_use/cli/config.py b/windows_use/cli/config.pyindex 90adcf7..6545b5f 100644--- a/windows_use/cli/config.py+++ b/windows_use/cli/config.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport base64import json+import loggingfrom pathlib import Pathfrom typing import Any@@ -19,7 +20,10 @@ from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMACWINDOWS_USE_DIR = Path.home() / ".windows-use"CONFIG_FILE = WINDOWS_USE_DIR / "config.json"SPEECH_CONFIG_FILE = WINDOWS_USE_DIR / "speech_config.json"+LOGGING_CONFIG_FILE = WINDOWS_USE_DIR / "logging_config.json"_ENC_SALT = b"windows-use-cli-v1"+VALID_LOG_LEVELS = ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL")+_LOG_LEVEL_ALIASES = {"VERBOSE": "DEBUG"}def _get_fernet() -> Fernet:@@ -237,3 +241,57 @@ def save_speech_config(cfg["tts"] = entryWINDOWS_USE_DIR.mkdir(parents=True, exist_ok=True)SPEECH_CONFIG_FILE.write_text(json.dumps(cfg, indent=2), encoding="utf-8")+++# --- Logging config ---+++def normalize_log_level(level: str) -> str:+ """Normalize and validate a log level name (accepts 'verbose' as alias for 'DEBUG')."""+ normalized = level.strip().upper()+ normalized = _LOG_LEVEL_ALIASES.get(normalized, normalized)+ if normalized not in VALID_LOG_LEVELS:+ valid = ", ".join(VALID_LOG_LEVELS)+ raise ValueError(f"Invalid log level '{level}'. Choose one of: {valid} (or verbose).")+ return normalized+++def get_logging_config() -> dict[str, Any]:+ """Load logging config. Returns {'level': 'INFO'} if missing or invalid."""+ if not LOGGING_CONFIG_FILE.exists():+ return {"level": "INFO"}+ try:+ raw = json.loads(LOGGING_CONFIG_FILE.read_text(encoding="utf-8"))+ except (json.JSONDecodeError, OSError):+ return {"level": "INFO"}+ if isinstance(raw, dict):+ level = raw.get("level", "INFO")+ if isinstance(level, str):+ try:+ return {"level": normalize_log_level(level)}+ except ValueError:+ pass+ return {"level": "INFO"}+++def get_log_level() -> str:+ """Return the persisted log level name (defaults to 'INFO')."""+ return str(get_logging_config()["level"])+++def save_logging_config(level: str) -> dict[str, Any]:+ """Persist the log level to ~/.windows-use/logging_config.json."""+ normalized = normalize_log_level(level)+ cfg = {"level": normalized}+ WINDOWS_USE_DIR.mkdir(parents=True, exist_ok=True)+ LOGGING_CONFIG_FILE.write_text(json.dumps(cfg, indent=2), encoding="utf-8")+ return cfg+++def apply_logging_config(level: str | None = None) -> int:+ """Apply the given or persisted log level to Windows-Use loggers."""+ resolved = normalize_log_level(level) if level is not None else get_log_level()+ numeric_level = getattr(logging, resolved, logging.INFO)+ logging.getLogger("windows_use").setLevel(numeric_level)+ logging.getLogger("windows_use.speech.service").setLevel(numeric_level)+ return numeric_level