Skip to content

AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He

fix(ui-runtime): make local server ports project-aware

hugohe315a7847a99b6
diff --git a/skills/ppt-master/scripts/confirm_ui/server.py b/skills/ppt-master/scripts/confirm_ui/server.py
index 1b5ebffc..b83c9cc3 100644
--- a/skills/ppt-master/scripts/confirm_ui/server.py
+++ b/skills/ppt-master/scripts/confirm_ui/server.py
@@ -69,6 +69,7 @@ from server_common import ( # noqa: E402
process_alive as _process_alive,
read_lock as _read_lock,
release_lock as _release_lock,
+ validate_port as _validate_port,
)
configure_utf8_stdio()
@@ -113,10 +114,9 @@ _ICON_PREVIEW_SAMPLES = {
'phosphor-duotone': ('house', 'chart-line', 'users', 'target'),
}
-# Shares port 5050 with the live preview server (svg_editor/server.py). The two
-# never run at once: confirm is Step 4 and shuts down on confirm (or idle),
-# freeing the port before live preview starts at Step 6. One port = one forward
-# rule for the whole pipeline. They still keep separate processes and locks.
+# Prefer the same memorable entry port as live preview. Normal single-project
+# execution releases it between Step 4 and Step 6; concurrent projects advance
+# from this base while explicit ``--port`` remains exact.
DEFAULT_PORT = 5050
PUBLIC_HOST = '127.0.0.1'
STARTUP_TIMEOUT = 10
@@ -172,9 +172,10 @@ def _server_url(port: int, path: str = '') -> str:
def _wait_for_server_ready(
port: int,
proc: subprocess.Popen,
+ project_path: Path,
timeout: int = STARTUP_TIMEOUT,
) -> bool:
- """Wait until the detached child is accepting HTTP requests."""
+ """Wait until this project's detached confirm server is accepting requests."""
deadline = time.time() + timeout
last_error = ''
health_url = _server_url(port, '/api/health')
@@ -185,9 +186,17 @@ def _wait_for_server_ready(
return False
try:
with urllib.request.urlopen(health_url, timeout=1) as resp:
- if 200 <= resp.status < 500:
+ data = json.load(resp)
+ if (
+ resp.status == 200
+ and isinstance(data, dict)
+ and data.get('service') == 'confirm_ui'
+ and data.get('project') == str(project_path)
+ and data.get('pid') == proc.pid
+ ):
return True
- except (OSError, urllib.error.URLError) as exc:
+ last_error = 'health response belongs to another service or project'
+ except (OSError, ValueError, urllib.error.URLError) as exc:
last_error = str(exc)
time.sleep(0.2)
logger.error(
@@ -203,6 +212,7 @@ def _launch_background_server(
project_path: Path,
*,
preferred_port: int,
+ exact_port: bool,
idle_timeout: int,
open_browser: bool,
) -> tuple[subprocess.Popen, int, Path]:
@@ -210,7 +220,7 @@ def _launch_background_server(
confirm_dir = project_path / CONFIRM_DIR_NAME
confirm_dir.mkdir(parents=True, exist_ok=True)
log_path = confirm_dir / 'server.log'
- port = _find_free_port(preferred_port)
+ port = preferred_port if exact_port else _find_free_port(preferred_port)
cmd = [
sys.executable,
str(Path(__file__).resolve()),
@@ -230,7 +240,9 @@ def _launch_background_server(
logger=logger,
)
logger.info('log: %s', log_path)
- if not _wait_for_server_ready(port, proc):
+ if not _wait_for_server_ready(port, proc, project_path):
+ if proc.poll() is None:
+ proc.terminate()
raise RuntimeError(f'confirm UI failed to become reachable: {_server_url(port)}')
_sync_session_state(confirm_dir, server_port=port, event='server-ready')
url = _server_url(port)
@@ -255,9 +267,9 @@ def _preferred_recovery_port(lock_file: Path, fallback: int) -> int:
existing = _read_lock(lock_file)
try:
port = int((existing or {}).get('port', 0) or 0)
+ return _validate_port(port) if port else fallback
except (TypeError, ValueError):
- port = 0
- return port or fallback
+ return fallback
def _open_browser_async(url: str, delay: float = 0.4) -> None:
@@ -1416,11 +1428,9 @@ def _wait_result_status(
def _shutdown_existing(lock_file: Path) -> int:
"""Stop a confirm server left running for this project (idempotent).
- Step 4 always calls this on exit so the page never lingers on the shared
- port 5050 — whether the user clicked **Confirm** (the page already shut the
- server down) or replied in chat instead (the server is still up). Tries a
- graceful ``/api/shutdown`` first, falls back to killing the recorded pid,
- then clears the lock. A no-op when nothing is running.
+ Step 4 always calls this on exit so the page never lingers on its selected
+ port. Tries a graceful ``/api/shutdown`` first, falls back to killing the
+ recorded pid, then clears the lock. A no-op when nothing is running.
"""
existing = _read_lock(lock_file)
if not existing:
@@ -1627,6 +1637,8 @@ def create_app(
rec_ok = False
resp = jsonify({
'status': 'ok',
+ 'service': 'confirm_ui',
+ 'pid': os.getpid(),
'project': str(project_path),
'recommendations': rec_ok,
'stage': stage,
@@ -1891,8 +1903,8 @@ def build_parser() -> argparse.ArgumentParser:
)
parser.add_argument('project_dir', help='Path to project directory')
parser.add_argument(
- '--port', type=int, default=DEFAULT_PORT,
- help=f'Port to listen on (default: {DEFAULT_PORT})',
+ '--port', type=int, default=None,
+ help=f'Exact port to listen on (default: first free port from {DEFAULT_PORT})',
)
parser.add_argument('--no-browser', action='store_true', help='Do not auto-open browser')
parser.add_argument(
@@ -1929,7 +1941,7 @@ def build_parser() -> argparse.ArgumentParser:
'--shutdown', action='store_true',
help='Stop a confirm server left running for this project, then exit '
'(idempotent). Run at the end of Step 4 so the page never lingers '
- 'on the shared port before live preview starts.',
+ 'on its selected port before live preview starts.',
)
return parser
@@ -1944,6 +1956,13 @@ def main(argv: Optional[list[str]] = None) -> int:
datefmt='%H:%M:%S',
)
+ if args.port is not None:
+ try:
+ args.port = _validate_port(args.port)
+ except ValueError as exc:
+ logger.error('%s', exc)
+ return 2
+
project_path = Path(args.project_dir).resolve()
if not project_path.is_dir():
logger.error('%s is not a directory', project_path)
@@ -1975,11 +1994,17 @@ def main(argv: Optional[list[str]] = None) -> int:
rec_file,
)
return 1
- recovery_port = _preferred_recovery_port(lock_file, args.port)
+ exact_port = args.port is not None
+ recovery_port = (
+ args.port
+ if exact_port
+ else _preferred_recovery_port(lock_file, DEFAULT_PORT)
+ )
try:
_, actual_port, _ = _launch_background_server(
project_path,
preferred_port=recovery_port,
+ exact_port=exact_port,
idle_timeout=args.timeout,
open_browser=False,
)
@@ -2028,7 +2053,8 @@ def main(argv: Optional[list[str]] = None) -> int:
try:
proc, port, _ = _launch_background_server(
project_path,
- preferred_port=args.port,
+ preferred_port=args.port if args.port is not None else DEFAULT_PORT,
+ exact_port=args.port is not None,
idle_timeout=args.timeout,
open_browser=not args.no_browser,
)
@@ -2045,10 +2071,16 @@ def main(argv: Optional[list[str]] = None) -> int:
)
return 0
+ try:
+ port = args.port if args.port is not None else _find_free_port(DEFAULT_PORT)
+ except RuntimeError as exc:
+ logger.error('%s', exc)
+ return 1
+
# Per-project mutual exclusion: refuse duplicate launches. Stale locks
# (dead pid) are overwritten by _claim_lock.
lock_file = project_path / LOCK_FILE_NAME
- existing = _claim_lock(lock_file, args.port)
+ existing = _claim_lock(lock_file, port)
if existing:
existing_pid = existing.get('pid', '?')
existing_port = existing.get('port', '?')
@@ -2072,17 +2104,17 @@ def main(argv: Optional[list[str]] = None) -> int:
str(project_path),
idle_timeout=args.timeout,
lock_file=lock_file,
- server_port=args.port,
+ server_port=port,
)
- url = _server_url(args.port)
+ url = _server_url(port)
if not args.no_browser:
_open_browser_async(url)
logger.info('running at %s', url)
logger.info('project: %s', project_path)
logger.info('idle timeout: %ds (0 = disabled)', args.timeout)
- app.run(host=PUBLIC_HOST, port=args.port, debug=False)
+ app.run(host=PUBLIC_HOST, port=port, debug=False)
return 0
diff --git a/skills/ppt-master/scripts/server_common.py b/skills/ppt-master/scripts/server_common.py
index 058b2a94..f4c99ff7 100644
--- a/skills/ppt-master/scripts/server_common.py
+++ b/skills/ppt-master/scripts/server_common.py
@@ -9,7 +9,7 @@ cross-platform process-liveness check and the claim/read/release lock logic so
the two servers cannot drift apart.
Usage:
- from server_common import process_alive, read_lock, lock_pid, claim_lock, release_lock, clear_lock, find_free_port
+ from server_common import find_free_port, validate_port
Dependencies:
None (only uses standard library)
@@ -24,14 +24,33 @@ from pathlib import Path
from typing import Optional
+MIN_PORT = 1
+MAX_PORT = 65535
+
+
+def validate_port(port: int) -> int:
+ """Return a valid TCP port, raising ``ValueError`` outside 1..65535."""
+ if isinstance(port, bool) or not isinstance(port, int):
+ raise ValueError('port must be an integer between 1 and 65535')
+ if not MIN_PORT <= port <= MAX_PORT:
+ raise ValueError(f'port must be between {MIN_PORT} and {MAX_PORT}: {port}')
+ return port
+
+
def find_free_port(preferred: int, host: str = '127.0.0.1', span: int = 50) -> int:
- """Return ``preferred`` if it is bindable, else the next free port within
- ``span``. Lets a new project's UI server coexist with another project's
- server already holding the default port, instead of crashing on bind — each
- project ends up on its own port serving its own data. Falls back to
- ``preferred`` if the whole span is taken (let the caller's bind surface it).
+ """Return the first bindable port from ``preferred`` through its scan span.
+
+ The scan remains sequential so callers can keep 5050 as their preferred
+ port and advance predictably when it is occupied. Invalid ports fail before
+ probing, and an exhausted valid range raises ``RuntimeError`` instead of
+ returning a port already known to be unavailable.
"""
- for port in range(preferred, preferred + span):
+ preferred = validate_port(preferred)
+ if isinstance(span, bool) or not isinstance(span, int) or span <= 0:
+ raise ValueError(f'span must be a positive integer: {span}')
+
+ last_port = min(preferred + span - 1, MAX_PORT)
+ for port in range(preferred, last_port + 1):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
@@ -39,7 +58,9 @@ def find_free_port(preferred: int, host: str = '127.0.0.1', span: int = 50) -> i
return port
except OSError:
continue
- return preferred
+ raise RuntimeError(
+ f'no free TCP port on {host} in range {preferred}..{last_port}'
+ )
def popen_detached(
diff --git a/skills/ppt-master/scripts/svg_editor/server.py b/skills/ppt-master/scripts/svg_editor/server.py
index a130b520..db0c82bb 100644
--- a/skills/ppt-master/scripts/svg_editor/server.py
+++ b/skills/ppt-master/scripts/svg_editor/server.py
@@ -71,6 +71,7 @@ from server_common import ( # noqa: E402
process_alive as _process_alive,
read_lock as _read_lock,
release_lock as _release_lock,
+ validate_port as _validate_port,
)
configure_utf8_stdio()
@@ -506,6 +507,8 @@ def create_app(
slide_count = 0
resp = jsonify({
'status': 'ok',
+ 'service': 'live_preview',
+ 'pid': os.getpid(),
'project': str(project_path),
'live': app.config['LIVE_MODE'],
'svg_output': str(svg_dir),
@@ -1072,9 +1075,10 @@ def _shutdown_existing(project_path: Path) -> int:
def _wait_for_ready(
port: int,
proc: subprocess.Popen,
+ project_path: Path,
timeout: int = STARTUP_TIMEOUT,
) -> bool:
- """Wait until the server responds or the child exits."""
+ """Wait until this project's detached live-preview server responds."""
deadline = time.time() + timeout
health_url = _server_url(port, '/api/health')
last_error = ''
@@ -1084,9 +1088,17 @@ def _wait_for_ready(
return False
try:
with urllib.request.urlopen(health_url, timeout=1) as response:
- if response.status == 200:
+ data = json.load(response)
+ if (
+ response.status == 200
+ and isinstance(data, dict)
+ and data.get('service') == 'live_preview'
+ and data.get('project') == str(project_path)
+ and data.get('pid') == proc.pid
+ ):
return True
- except (urllib.error.URLError, TimeoutError, OSError) as exc:
+ last_error = 'health response belongs to another service or project'
+ except (urllib.error.URLError, TimeoutError, OSError, ValueError) as exc:
last_error = str(exc)
time.sleep(0.25)
logger.error(
@@ -1112,7 +1124,12 @@ def _open_browser(url: str) -> bool:
return False
-def _reuse_running_server(existing: dict, *, open_browser: bool) -> int:
+def _reuse_running_server(
+ existing: dict,
+ *,
+ open_browser: bool,
+ requested_port: Optional[int] = None,
+) -> int:
"""Idempotent relaunch: point at the already-running preview instead of failing.
A relaunch while the server is alive is the normal second-preview flow
@@ -1131,6 +1148,14 @@ def _reuse_running_server(existing: dict, *, open_browser: bool) -> int:
pid,
)
return 1
+ if requested_port is not None and port != requested_port:
+ logger.error(
+ 'live preview is already running for this project on port %s; '
+ 'explicit --port %s cannot reuse it. Run --shutdown, then start again',
+ port,
+ requested_port,
+ )
+ return 1
url = _server_url(port)
logger.info(
'live preview already running for this project (pid=%s), reusing: %s',
@@ -1159,8 +1184,8 @@ def build_parser() -> argparse.ArgumentParser:
parser.add_argument(
'--port',
type=int,
- default=DEFAULT_PORT,
- help=f'Port to listen on (default: {DEFAULT_PORT})',
+ default=None,
+ help=f'Exact port to listen on (default: first free port from {DEFAULT_PORT})',
)
parser.add_argument('--no-browser', action='store_true', help='Do not auto-open browser')
parser.add_argument(
@@ -1197,6 +1222,13 @@ def main(argv: Optional[list[str]] = None) -> int:
datefmt='%H:%M:%S',
)
+ if args.port is not None:
+ try:
+ args.port = _validate_port(args.port)
+ except ValueError as exc:
+ logger.error('%s', exc)
+ return 2
+
project_path = Path(args.project_dir).resolve()
if args.shutdown:
return _shutdown_existing(project_path)
@@ -1214,7 +1246,11 @@ def main(argv: Optional[list[str]] = None) -> int:
legacy_existing = _legacy_live_lock(project_path)
if legacy_existing:
- return _reuse_running_server(legacy_existing, open_browser=not args.no_browser)
+ return _reuse_running_server(
+ legacy_existing,
+ open_browser=not args.no_browser,
+ requested_port=args.port,
+ )
runtime_dir = _runtime_dir(project_path)
lock_file = _lock_file(project_path)
@@ -1222,7 +1258,11 @@ def main(argv: Optional[list[str]] = None) -> int:
if args.daemon:
existing = _read_lock(lock_file)
if existing and _process_alive(_lock_pid(existing)):
- return _reuse_running_server(existing, open_browser=not args.no_browser)
+ return _reuse_running_server(
+ existing,
+ open_browser=not args.no_browser,
+ requested_port=args.port,
+ )
try:
runtime_dir.mkdir(parents=True, exist_ok=True)
@@ -1230,7 +1270,11 @@ def main(argv: Optional[list[str]] = None) -> int:
logger.error('cannot create live preview runtime directory: %s (%s)', runtime_dir, exc)
return 1
log_path = runtime_dir / 'server.log'
- port = _find_free_port(args.port)
+ try:
+ port = args.port if args.port is not None else _find_free_port(DEFAULT_PORT)
+ except RuntimeError as exc:
+ logger.error('%s', exc)
+ return 1
idle_timeout = args.timeout
if idle_timeout is None:
idle_timeout = 7200 if args.live else 900
@@ -1259,7 +1303,9 @@ def main(argv: Optional[list[str]] = None) -> int:
logger.error('cannot write live preview log: %s (%s)', log_path, exc)
return 1
url = _server_url(port)
- if not _wait_for_ready(port, proc):
+ if not _wait_for_ready(port, proc, project_path):
+ if proc.poll() is None:
+ proc.terminate()
logger.error('live preview failed to become reachable: %s (log: %s)', url, log_path)
return 1
logger.info('started live preview in background: %s (pid=%s)', url, proc.pid)
@@ -1271,7 +1317,11 @@ def main(argv: Optional[list[str]] = None) -> int:
# Pick a free port: another project's preview/confirm server may already
# hold the default, so bind the next free one instead of crashing — each
# project then serves its own data on its own port (no cross-project mix-up).
- port = _find_free_port(args.port)
+ try:
+ port = args.port if args.port is not None else _find_free_port(DEFAULT_PORT)
+ except RuntimeError as exc:
+ logger.error('%s', exc)
+ return 1
# Per-project mutual exclusion. The major driver of orphaned servers is
# --live mode (which used to disable idle timeout entirely) combined with
@@ -1285,7 +1335,11 @@ def main(argv: Optional[list[str]] = None) -> int:
return 1
existing = _claim_lock(lock_file, port)
if existing:
- return _reuse_running_server(existing, open_browser=not args.no_browser)
+ return _reuse_running_server(
+ existing,
+ open_browser=not args.no_browser,
+ requested_port=args.port,
+ )
# atexit covers normal interpreter shutdown (Ctrl+C / SystemExit);
# /api/shutdown and idle timeout call _release_lock directly before
# os._exit since atexit handlers do not run on os._exit.
diff --git a/skills/ppt-master/scripts/visual_review.py b/skills/ppt-master/scripts/visual_review.py
index 859f5955..5f862003 100644
--- a/skills/ppt-master/scripts/visual_review.py
+++ b/skills/ppt-master/scripts/visual_review.py
@@ -40,6 +40,7 @@ from contextlib import contextmanager
from pathlib import Path
from console_encoding import configure_utf8_stdio
+from server_common import lock_pid, process_alive, read_lock
from slide_roster import discover_slide_svgs
configure_utf8_stdio()
@@ -210,15 +211,53 @@ def discover_pages(project_path: Path, requested: list[str] | None) -> list[str]
return selected
-def check_server(server_url: str) -> None:
- """Probe server liveness via /api/slides. Raises RuntimeError if down."""
- url = f"{server_url.rstrip('/')}/api/slides"
+def discover_server_url(project_path: Path) -> str:
+ """Return the live-preview URL recorded for one project."""
+ lock_paths = (
+ project_path / 'live_preview' / 'lock.json',
+ project_path / '.live_preview.lock',
+ )
+ for lock_path in lock_paths:
+ lock = read_lock(lock_path)
+ if not lock or not process_alive(lock_pid(lock)):
+ continue
+ try:
+ port = int(lock.get('port', 0) or 0)
+ except (TypeError, ValueError):
+ port = 0
+ if 1 <= port <= 65535:
+ return f'http://127.0.0.1:{port}'
+ raise RuntimeError(
+ f'no running live-preview server recorded for project: {project_path}'
+ )
+
+
+def check_server(server_url: str, project_path: Path) -> None:
+ """Require a live-preview server that belongs to the target project."""
+ url = f"{server_url.rstrip('/')}/api/health"
try:
with urllib.request.urlopen(url, timeout=3.0) as resp:
if resp.status != 200:
raise RuntimeError(f'{url} returned HTTP {resp.status}')
- except urllib.error.URLError as e:
+ data = json.load(resp)
+ except (urllib.error.URLError, OSError, ValueError) as e:
raise RuntimeError(f'live-preview server not reachable at {server_url}: {e}')
+ expected_project = str(project_path)
+ expected_svg_output = str((project_path / 'svg_output').resolve())
+ service = data.get('service') if isinstance(data, dict) else None
+ legacy_live_preview = (
+ service is None
+ and isinstance(data, dict)
+ and data.get('svg_output') == expected_svg_output
+ )
+ if (
+ not isinstance(data, dict)
+ or data.get('project') != expected_project
+ or (service != 'live_preview' and not legacy_live_preview)
+ ):
+ raise RuntimeError(
+ f'URL does not belong to this project live preview: {server_url}'
+ )
def main() -> int:
@@ -232,8 +271,8 @@ def main() -> int:
"Accepts '02', '02_three_steps', or '02_three_steps.svg'.",
)
parser.add_argument(
- '--server-url', default='http://localhost:5050',
- help='Live-preview server URL (default: http://localhost:5050)',
+ '--server-url', default=None,
+ help='Explicit live-preview URL (default: discover it from the project lock)',
)
parser.add_argument(
'--lock-timeout', type=float, default=30.0,
@@ -258,7 +297,8 @@ def main() -> int:
return 3
try:
- check_server(args.server_url)
+ server_url = args.server_url or discover_server_url(project_path)
+ check_server(server_url, project_path)
except RuntimeError as e:
_safe_print(str(e))
_safe_print(
@@ -278,7 +318,7 @@ def main() -> int:
with file_lock(lock_path, timeout=args.lock_timeout):
try:
- records = render_pages(args.server_url, pages, preview_dir)
+ records = render_pages(server_url, pages, preview_dir)
except Exception as e: # noqa: BLE001 — browser launch failure
_safe_print(f'browser session failed: {type(e).__name__}: {e}')
_safe_print(
@@ -294,7 +334,7 @@ def main() -> int:
summary = {
'project': str(project_path),
- 'server_url': args.server_url,
+ 'server_url': server_url,
'rendered': sum(1 for r in records if r['ok']),
'failed': sum(1 for r in records if not r['ok']),
'all_background': sum(1 for r in records if r.get('all_background')),