fix(whatsapp): refresh bridge when source changes

This commit is contained in:
Xubin Ren
2026-04-30 04:18:31 +00:00
parent d23bcae5a3
commit 71eff09653
3 changed files with 70 additions and 23 deletions
+33 -10
View File
@@ -1271,6 +1271,7 @@ def channels_status(
def _get_bridge_dir() -> Path:
"""Get the bridge directory, setting it up if needed."""
import hashlib
import shutil
import subprocess
@@ -1278,16 +1279,7 @@ def _get_bridge_dir() -> Path:
from nanobot.config.paths import get_bridge_install_dir
user_bridge = get_bridge_install_dir()
# Check if already built
if (user_bridge / "dist" / "index.js").exists():
return user_bridge
# Check for npm
npm_path = shutil.which("npm")
if not npm_path:
console.print("[red]npm not found. Please install Node.js >= 18.[/red]")
raise typer.Exit(1)
stamp_file = user_bridge / ".nanobot-bridge-source-hash"
# Find source bridge: first check package data, then source dir
pkg_bridge = Path(__file__).parent.parent / "bridge" # nanobot/bridge (installed)
@@ -1304,6 +1296,36 @@ def _get_bridge_dir() -> Path:
console.print("Try reinstalling: pip install --force-reinstall nanobot")
raise typer.Exit(1)
def source_hash(root: Path) -> str:
digest = hashlib.sha256()
for path in sorted(root.rglob("*")):
if not path.is_file():
continue
rel = path.relative_to(root)
if rel.parts and rel.parts[0] in {"node_modules", "dist"}:
continue
digest.update(rel.as_posix().encode("utf-8"))
digest.update(b"\0")
digest.update(path.read_bytes())
digest.update(b"\0")
return digest.hexdigest()
expected_hash = source_hash(source)
current_hash = stamp_file.read_text().strip() if stamp_file.exists() else None
# Reuse only a bridge built from the currently installed source.
if (user_bridge / "dist" / "index.js").exists() and current_hash == expected_hash:
return user_bridge
if (user_bridge / "dist" / "index.js").exists() and current_hash != expected_hash:
console.print(f"{__logo__} WhatsApp bridge source changed; rebuilding bridge...")
# Check for npm
npm_path = shutil.which("npm")
if not npm_path:
console.print("[red]npm not found. Please install Node.js >= 18.[/red]")
raise typer.Exit(1)
console.print(f"{__logo__} Setting up bridge...")
# Copy to user directory
@@ -1319,6 +1341,7 @@ def _get_bridge_dir() -> Path:
console.print(" Building...")
subprocess.run([npm_path, "run", "build"], cwd=user_bridge, check=True, capture_output=True)
stamp_file.write_text(expected_hash + "\n")
console.print("[green]✓[/green] Bridge ready\n")
except subprocess.CalledProcessError as e: