Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion powermcp/doctor.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,4 +236,4 @@ def run_doctor(tool: str | None = None) -> None:
)
for note in solver_notes:
console.print(f"[dim]{note}[/]")
console.print(f"\n[dim]Config file: {cfg.config_path()}[/]")
console.print(f"\n[dim]Config file: {escape(str(cfg.config_path()))}[/]", soft_wrap=True)
33 changes: 22 additions & 11 deletions powermcp/wizard.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from pathlib import Path

from rich.console import Console
from rich.markup import escape

from . import config as cfg
from .clients import CLIENT_NAMES, configure
Expand Down Expand Up @@ -135,7 +136,7 @@ def run_wizard(
_capture_paths(selected)
_pip_install(selected, assume_yes=yes, dry_run=dry_run)
_write_clients(selected, client_names, dry_run)
console.print(f"\n[green]Done.[/] PowerMCP config: {cfg.config_path()}")
console.print(f"\n[green]Done.[/] PowerMCP config: {escape(str(cfg.config_path()))}", soft_wrap=True)


def _resolve_selection(
Expand Down Expand Up @@ -163,7 +164,7 @@ def _resolve_selection(
unknown.append(name)
if unknown:
console.print(
f"[red]Unknown tool id(s) ignored:[/] {', '.join(unknown)} "
f"[red]Unknown tool id(s) ignored:[/] {escape(', '.join(unknown))} "
f"(run `powermcp list` for valid ids)"
)
if unavailable:
Expand Down Expand Up @@ -211,7 +212,7 @@ def _interactive_select(client_names: list[str]) -> list[Tool]:
).ask()
except Exception as exc:
console.print(
f"[yellow]Interactive picker unavailable ({exc}); defaulting to core tools. "
f"[yellow]Interactive picker unavailable ({escape(str(exc))}); defaulting to core tools. "
f"Use `--tools <ids>` or `--all`.[/]"
)
return [TOOLS[n] for n in CORE]
Expand Down Expand Up @@ -252,12 +253,12 @@ def _capture_paths(selected: list[Tool]) -> None:
default = existing or detect(t.name, ck.key) or ""
label = f"[{t.display}] {ck.prompt}"
if default and not existing:
console.print(f"[dim] detected: {default}[/]")
console.print(f"[dim] detected: {escape(str(default))}[/]")
try:
answer = questionary.path(label, default=default).ask()
except Exception as exc: # prompt backend unavailable
console.print(
f"[yellow]Could not prompt for {t.name}.{ck.key} ({exc}); "
f"[yellow]Could not prompt for {t.name}.{ck.key} ({escape(str(exc))}); "
f"set it later with `powermcp config set {t.name}.{ck.key} <path>`.[/]"
)
answer = None
Expand Down Expand Up @@ -295,13 +296,20 @@ def _capture_paths(selected: list[Tool]) -> None:
def _pip_install(selected: list[Tool], *, assume_yes: bool = False, dry_run: bool = False) -> None:
extras = sorted({t.extra for t in selected if t.extra})
spec = "powermcp" + (f"[{','.join(extras)}]" if extras else "")
# Rich would read `[andes,ltspice]` as a markup tag and drop it from the hint,
# and would fold a spec wider than the console (80 columns without a TTY)
# across lines; soft_wrap leaves the copyable command on one line.
shown = escape(spec)
if dry_run:
console.print(f"[cyan](dry-run)[/] would run: pip install {spec}")
console.print(f"[cyan](dry-run)[/] would run: pip install {shown}", soft_wrap=True)
return
if assume_yes:
proceed = True
elif not _tty():
console.print(f"[yellow]Non-interactive; skipping dependency install. Run:[/] pip install {spec}")
console.print(
f"[yellow]Non-interactive; skipping dependency install. Run:[/] pip install {shown}",
soft_wrap=True,
)
return
else:
import questionary
Expand All @@ -313,12 +321,15 @@ def _pip_install(selected: list[Tool], *, assume_yes: bool = False, dry_run: boo
except Exception:
proceed = False
if not proceed:
console.print(f"[yellow]Skipped. Install later with:[/] pip install {spec}")
console.print(f"[yellow]Skipped. Install later with:[/] pip install {shown}", soft_wrap=True)
return
console.print(f"[cyan]Installing[/] {spec} ...")
console.print(f"[cyan]Installing[/] {shown} ...", soft_wrap=True)
result = subprocess.run([sys.executable, "-m", "pip", "install", spec], check=False)
if result.returncode != 0:
console.print(f"[red]pip install failed (exit {result.returncode}).[/] Install manually: pip install {spec}")
console.print(
f"[red]pip install failed (exit {result.returncode}).[/] Install manually: pip install {shown}",
soft_wrap=True,
)


def _write_clients(selected: list[Tool], client_names: list[str], dry_run: bool) -> None:
Expand All @@ -339,6 +350,6 @@ def _write_clients(selected: list[Tool], client_names: list[str], dry_run: bool)
results = configure(client_names, tool_names, dry_run=dry_run)
for client, path in results.items():
if path:
console.print(f"[green]Configured {client}:[/] {path}")
console.print(f"[green]Configured {client}:[/] {escape(str(path))}", soft_wrap=True)
elif not dry_run:
console.print(f"[yellow]Skipped {client} (unknown client name).[/]")
79 changes: 79 additions & 0 deletions tests/test_wizard.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,82 @@ def ask(self):
fake_q.checkbox = lambda *a, **k: _Q()
monkeypatch.setitem(sys.modules, "questionary", fake_q)
assert wizard._interactive_select([]) == []


# The pip hint is printed through Rich, which reads `[andes]` as a markup tag
# and drops it, so the hint used to read `pip install powermcp` with no extras.
# Copying it installed nothing the selection needed.
def _andes_selection():
return wizard._resolve_selection(yes=False, tools="andes", select_all=False, client_names=[])


@pytest.mark.parametrize("mode", ["dry_run", "non_tty"])
def test_pip_hint_keeps_extras(monkeypatch, capsys, mode):
monkeypatch.setattr(wizard, "_tty", lambda: False)
monkeypatch.setitem(sys.modules, "questionary", None) # must not prompt
monkeypatch.setattr(wizard.subprocess, "run", lambda *a, **k: pytest.fail("pip must not run"))
wizard._pip_install(_andes_selection(), dry_run=(mode == "dry_run"))
out = capsys.readouterr().out
assert "pip install powermcp[andes]" in out


def test_pip_hint_keeps_extras_when_declined(monkeypatch, capsys):
monkeypatch.setattr(wizard, "_tty", lambda: True)
prompts = []
fake_q = types.ModuleType("questionary")

class _Q:
def ask(self):
return False

def _confirm(message, **kw):
prompts.append(message)
return _Q()

fake_q.confirm = _confirm
monkeypatch.setitem(sys.modules, "questionary", fake_q)
wizard._pip_install(_andes_selection())
assert prompts and "pip install powermcp[andes]" in prompts[0] # questionary prints it verbatim
assert "Install later with: pip install powermcp[andes]" in capsys.readouterr().out


def test_pip_hint_keeps_extras_when_install_fails(monkeypatch, capsys):
calls = []

def _run(cmd, **kw):
calls.append(cmd)
return types.SimpleNamespace(returncode=1)

monkeypatch.setattr(wizard.subprocess, "run", _run)
wizard._pip_install(_andes_selection(), assume_yes=True)
assert calls[0][-1] == "powermcp[andes]" # the real command was never affected
out = capsys.readouterr().out
assert "Installing powermcp[andes]" in out
assert "Install manually: pip install powermcp[andes]" in out


def test_done_line_keeps_bracketed_config_path(monkeypatch, capsys, tmp_path):
from rich.console import Console

home = tmp_path / "cfg[old]" # `[old]` reads as a Rich style tag
monkeypatch.setenv("POWERMCP_HOME", str(home))
monkeypatch.setattr(wizard, "console", Console(width=80)) # the path is wider than this
wizard.run_wizard(yes=False, tools="andes", clients="none", dry_run=True)
out = capsys.readouterr().out
assert f"PowerMCP config: {home / 'config.toml'}" in out
assert "pip install powermcp[andes]" in out


def test_long_pip_hint_stays_on_one_line(monkeypatch, capsys):
# Without a TTY Rich renders at 80 columns and used to fold a wider spec
# (every Windows tool) mid-word, so a copied hint split the spec in two.
from rich.console import Console

monkeypatch.setattr(sys, "platform", "win32")
monkeypatch.setattr(wizard, "_surge_supported", lambda: True)
monkeypatch.setattr(wizard, "console", Console(width=80))
selected = wizard._resolve_selection(yes=False, tools="all", select_all=False, client_names=[])
spec = "powermcp[" + ",".join(sorted({t.extra for t in selected if t.extra})) + "]"
assert len(spec) > 80
wizard._pip_install(selected, dry_run=True)
assert f"pip install {spec}" in capsys.readouterr().out
Loading