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
feat(live-preview): daemonize preview runtime history
hugohe3e7fd26dae154
diff --git a/AGENTS.md b/AGENTS.mdindex 8d64ffe5..22c71322 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -80,7 +80,7 @@ python3 skills/ppt-master/scripts/image_gen.py --manifest <project_path>/images/python3 skills/ppt-master/scripts/image_gen.py --render-md <project_path>/images/image_prompts.json# Out-of-pipeline one-off / debug / single-image fixup only (no manifest, no sidecar):python3 skills/ppt-master/scripts/image_gen.py "prompt" --aspect_ratio 16:9 --image_size 1K -o <project_path>/images-python3 skills/ppt-master/scripts/svg_editor/server.py <project_path> --live+python3 skills/ppt-master/scripts/svg_editor/server.py <project_path> --live --daemonpython3 skills/ppt-master/scripts/svg_quality_checker.py <project_path>python3 skills/ppt-master/scripts/animation_config.py scaffold <project_path> # optional, only for custom object-level animationpython3 skills/ppt-master/scripts/animation_config.py validate <project_path> # optional, before re-exportdiff --git a/CLAUDE.md b/CLAUDE.mdindex f46eabf4..0427192d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -84,7 +84,7 @@ python3 skills/ppt-master/scripts/image_gen.py --manifest <project_path>/images/python3 skills/ppt-master/scripts/image_gen.py --render-md <project_path>/images/image_prompts.json# Out-of-pipeline one-off / debug / single-image fixup only (no manifest, no sidecar):python3 skills/ppt-master/scripts/image_gen.py "prompt" --aspect_ratio 16:9 --image_size 1K -o <project_path>/images-python3 skills/ppt-master/scripts/svg_editor/server.py <project_path> --live+python3 skills/ppt-master/scripts/svg_editor/server.py <project_path> --live --daemonpython3 skills/ppt-master/scripts/svg_quality_checker.py <project_path>python3 skills/ppt-master/scripts/animation_config.py scaffold <project_path> # optional, only for custom object-level animationpython3 skills/ppt-master/scripts/animation_config.py validate <project_path> # optional, before re-exportdiff --git a/skills/ppt-master/SKILL.md b/skills/ppt-master/SKILL.mdindex 07d630e1..db0b35b3 100644--- a/skills/ppt-master/SKILL.md+++ b/skills/ppt-master/SKILL.md@@ -520,7 +520,7 @@ Read references/visual-styles/<locked-style>.md # aesthetic (spec_lock.md `vis**Live Preview Auto-Startup (Mandatory)**: before the first SVG, automatically start the browser editor in live mode and keep it running continuously through Executor + Step 7 export:```bash-python3 ${SKILL_DIR}/scripts/svg_editor/server.py <project_path> --live+python3 ${SKILL_DIR}/scripts/svg_editor/server.py <project_path> --live --daemon```- Start it immediately when Executor begins; `svg_output/` may be empty. Editor opens at `http://localhost:5050`; if another project already holds it, the launcher **auto-advances to the next free port** — read the actual URL from the launch log and report that.- Run it as a long-running side process/session; do not wait for it to exit before generating SVG pages. Do not wait for user confirmation after startup.diff --git a/skills/ppt-master/scripts/project_manager.py b/skills/ppt-master/scripts/project_manager.pyindex ca6b7db2..e54d8c9b 100644--- a/skills/ppt-master/scripts/project_manager.py+++ b/skills/ppt-master/scripts/project_manager.py@@ -147,6 +147,7 @@ class ProjectManager:"icons","notes","templates",+ "live_preview",SOURCE_DIRNAME,"analysis","exports",@@ -167,6 +168,7 @@ class ProjectManager:"- `icons/`: project icon set — selected library icons copied in (via icon_sync.py) plus any custom icons you add; embedded from here at export\n""- `notes/`: speaker notes\n""- `templates/`: project templates\n"+ "- `live_preview/`: browser preview runtime files and history (lock.json, server.log, edits.jsonl, annotations.jsonl)\n""- `sources/`: source materials and normalized markdown\n""- `analysis/`: machine-extracted intermediate analysis (PPTX intake, image_analysis.csv) — the pipeline's canonical must-read source/asset facts\n""- `exports/`: main native pptx (timestamped); `_svg.pptx` sibling added when exported with `--svg-snapshot`\n"diff --git a/skills/ppt-master/scripts/svg_editor/server.py b/skills/ppt-master/scripts/svg_editor/server.pyindex a83d026a..796c46f7 100644--- a/skills/ppt-master/scripts/svg_editor/server.py+++ b/skills/ppt-master/scripts/svg_editor/server.py@@ -25,9 +25,12 @@ import loggingimport osimport reimport signal+import subprocessimport sysimport threadingimport time+import urllib.error+import urllib.requestimport webbrowserimport xml.etree.ElementTree as ETfrom pathlib import Path@@ -37,9 +40,10 @@ from flask import Flask, jsonify, request, send_from_directorylogger = logging.getLogger('svg_editor')-# Per-project lock file. Lives at <project_path>/.live_preview.lock and-# matches the *.lock entry already in the repo .gitignore.-LOCK_FILE_NAME = '.live_preview.lock'+# Per-project runtime files live under <project_path>/live_preview/.+LIVE_PREVIEW_DIR_NAME = 'live_preview'+LOCK_FILE_NAME = 'lock.json'+LEGACY_LOCK_FILE_NAME = '.live_preview.lock'# Local — sys.path injection for sibling module (code-style.md §3)_SCRIPTS_DIR = Path(__file__).resolve().parent@@ -217,20 +221,29 @@ def _validate_edit_attrs(attrs: dict, existing_attrs: set[str]) -> Optional[str]return None-_EDIT_LOG_NAME = '.live_edits.jsonl'+EDIT_LOG_NAME = 'edits.jsonl'+ANNOTATION_LOG_NAME = 'annotations.jsonl'-def _append_edit_log(project_path: Path, record: dict) -> None:- """Append one applied edit record (old→new) to the project's history.-- The on-disk JSONL is the durable trail the user can review to see exactly- what changed. Un-applied staged edits stay in memory only.- """+def _append_live_preview_log(project_path: Path, filename: str, record: dict) -> None:+ """Append one live-preview history record under ``live_preview/``."""try:- with open(project_path / _EDIT_LOG_NAME, 'a', encoding='utf-8') as fh:+ log_dir = _runtime_dir(project_path)+ log_dir.mkdir(parents=True, exist_ok=True)+ with open(log_dir / filename, 'a', encoding='utf-8') as fh:fh.write(json.dumps(record, ensure_ascii=False) + '\n')except OSError as exc:- logger.warning('edit log append failed: %s', exc)+ logger.warning('live preview log append failed: %s', exc)+++def _append_edit_log(project_path: Path, record: dict) -> None:+ """Append one applied direct-edit record to the preview history."""+ _append_live_preview_log(project_path, EDIT_LOG_NAME, record)+++def _append_annotation_log(project_path: Path, record: dict) -> None:+ """Append one annotation lifecycle record to the preview history."""+ _append_live_preview_log(project_path, ANNOTATION_LOG_NAME, record)def _find_by_id(root: ET.Element, element_id: str) -> Optional[ET.Element]:@@ -780,6 +793,11 @@ def create_app(if not ok:return jsonify({'error': f'Failed to apply edits in {filename}: {reason}'}), 400+ old_annotations = {+ item['element_id']: item['annotation']+ for item in parse_annotations(root)+ }+# Clear all existing annotations from the file before writing current statefor elem in root.iter():elem.attrib.pop('data-edit-target', None)@@ -796,6 +814,21 @@ def create_app(tree.write(str(svg_file), encoding='UTF-8', xml_declaration=True)ts = time.time()+ for element_id, annotation_text in anns.items():+ old_text = old_annotations.get(element_id)+ action = 'annotation_saved' if old_text is None else 'annotation_updated'+ if old_text == annotation_text:+ action = 'annotation_saved'+ _append_annotation_log(project_path, {+ 'ts': ts, 'file': filename, 'element_id': element_id,+ 'action': action, 'old': old_text, 'new': annotation_text,+ })+ for element_id, old_text in old_annotations.items():+ if element_id not in anns:+ _append_annotation_log(project_path, {+ 'ts': ts, 'file': filename, 'element_id': element_id,+ 'action': 'annotation_removed', 'old': old_text, 'new': None,+ })for edit in edits:for chg in edit.get('changes', []):_append_edit_log(project_path, {@@ -813,6 +846,53 @@ def create_app(return app+def _runtime_dir(project_path: Path) -> Path:+ return project_path / LIVE_PREVIEW_DIR_NAME+++def _lock_file(project_path: Path) -> Path:+ return _runtime_dir(project_path) / LOCK_FILE_NAME+++def _legacy_live_lock(project_path: Path) -> Optional[dict]:+ """Return a live legacy root lock, if one exists."""+ legacy_lock = project_path / LEGACY_LOCK_FILE_NAME+ existing = _read_lock(legacy_lock)+ if existing and _process_alive(int(existing.get('pid', 0))):+ return existing+ return None+++def _wait_for_ready(url: str, proc: subprocess.Popen, timeout: int = 15) -> bool:+ """Wait until the server responds or the child exits."""+ deadline = time.time() + timeout+ health_url = f'{url}/api/config'+ while time.time() < deadline:+ if proc.poll() is not None:+ return False+ try:+ with urllib.request.urlopen(health_url, timeout=1) as response:+ if response.status == 200:+ return True+ except (urllib.error.URLError, TimeoutError, OSError):+ time.sleep(0.25)+ return False+++def _open_browser(url: str) -> bool:+ """Best-effort browser launch after the local server is reachable."""+ try:+ if os.name == 'nt':+ os.startfile(url) # type: ignore[attr-defined]+ return True+ return bool(webbrowser.open(url))+ except OSError as exc:+ logger.warning('browser auto-open failed: %s', exc)+ except webbrowser.Error as exc:+ logger.warning('browser auto-open failed: %s', exc)+ return False++def build_parser() -> argparse.ArgumentParser:parser = argparse.ArgumentParser(description='PPT Master SVG Editor',@@ -821,6 +901,11 @@ def build_parser() -> argparse.ArgumentParser:parser.add_argument('project_dir', help='Path to project directory (contains svg_output/)')parser.add_argument('--port', type=int, default=5050, help='Port to listen on (default: 5050)')parser.add_argument('--no-browser', action='store_true', help='Do not auto-open browser')+ parser.add_argument(+ '--daemon',+ action='store_true',+ help='Start the server in the background and return after it is reachable',+ )parser.add_argument('--live',action='store_true',@@ -857,6 +942,84 @@ def main(argv: Optional[list[str]] = None) -> int:logger.error('%s is not a directory', svg_output)return 1+ legacy_existing = _legacy_live_lock(project_path)+ if legacy_existing:+ existing_pid = legacy_existing.get('pid', '?')+ existing_port = legacy_existing.get('port', '?')+ logger.error(+ 'live preview is already running for this project via legacy lock '+ '(pid=%s, port=%s). Open http://localhost:%s, click '+ 'Exit preview in the browser, or stop pid %s',+ existing_pid, existing_port, existing_port, existing_pid,+ )+ return 1++ runtime_dir = _runtime_dir(project_path)+ lock_file = _lock_file(project_path)++ if args.daemon:+ existing = _read_lock(lock_file)+ if existing and _process_alive(int(existing.get('pid', 0))):+ existing_pid = existing.get('pid', '?')+ existing_port = existing.get('port', '?')+ logger.error(+ 'live preview is already running for this project '+ '(pid=%s, port=%s). Open http://localhost:%s',+ existing_pid, existing_port, existing_port,+ )+ return 1++ try:+ runtime_dir.mkdir(parents=True, exist_ok=True)+ except OSError as exc:+ 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)+ idle_timeout = args.timeout+ if idle_timeout is None:+ idle_timeout = 7200 if args.live else 900+ cmd = [+ sys.executable,+ str(Path(__file__).resolve()),+ str(project_path),+ '--port',+ str(port),+ '--timeout',+ str(idle_timeout),+ '--no-browser',+ ]+ if args.live:+ cmd.append('--live')+ creationflags = 0+ popen_kwargs = {}+ if os.name == 'nt':+ creationflags = subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.DETACHED_PROCESS+ else:+ popen_kwargs['start_new_session'] = True+ try:+ with log_path.open('a', encoding='utf-8') as log:+ proc = subprocess.Popen(+ cmd,+ stdout=log,+ stderr=subprocess.STDOUT,+ stdin=subprocess.DEVNULL,+ creationflags=creationflags,+ **popen_kwargs,+ )+ except OSError as exc:+ logger.error('cannot write live preview log: %s (%s)', log_path, exc)+ return 1+ url = f'http://localhost:{port}'+ if not _wait_for_ready(url, proc):+ 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)+ logger.info('log: %s', log_path)+ if not args.no_browser and not _open_browser(url):+ logger.info('browser did not auto-open; open %s manually', url)+ return 0+# 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).@@ -866,7 +1029,11 @@ def main(argv: Optional[list[str]] = None) -> int:# --live mode (which used to disable idle timeout entirely) combined with# silent restarts; refusing duplicate launches catches the accumulation# at its source. Stale locks (dead pid) are overwritten by _claim_lock.- lock_file = project_path / LOCK_FILE_NAME+ try:+ runtime_dir.mkdir(parents=True, exist_ok=True)+ except OSError as exc:+ logger.error('cannot create live preview runtime directory: %s (%s)', runtime_dir, exc)+ return 1existing = _claim_lock(lock_file, port)if existing:existing_pid = existing.get('pid', '?')@@ -911,7 +1078,7 @@ def main(argv: Optional[list[str]] = None) -> int:url = f'http://localhost:{port}'if not args.no_browser:- webbrowser.open(url)+ _open_browser(url)mode = "live preview (auto-startup)" if args.live else "live preview"svg_count = len(list(svg_output.glob('*.svg')))diff --git a/skills/ppt-master/workflows/live-preview.md b/skills/ppt-master/workflows/live-preview.mdindex 3182c46e..723a0b4c 100644--- a/skills/ppt-master/workflows/live-preview.md+++ b/skills/ppt-master/workflows/live-preview.md@@ -29,15 +29,15 @@ description: Start the browser SVG editor when it is not running, and apply subm**Precondition**: no preview service running on this project.```bash-python3 ${SKILL_DIR}/scripts/svg_editor/server.py <project_path>+python3 ${SKILL_DIR}/scripts/svg_editor/server.py <project_path> --daemon```(Plain mode — no `--live`. The `--live` flag is reserved for Step 6's auto-startup.)-The server binds `127.0.0.1:5050`, opens the browser on a local desktop, and edits `<project_path>/svg_output/` in place. After it prints `SVG Editor running at http://localhost:5050`, tell the user in their language, in one short message:+The launcher binds `127.0.0.1:5050` (or the next free port), starts the server in the background, writes runtime files under `<project_path>/live_preview/`, opens the browser on a local desktop when possible, and edits `<project_path>/svg_output/` in place. After it prints the running URL, tell the user in their language, in one short message:-- editor is at `http://localhost:5050`-- **Direct edit** (deterministic tweaks — wording, color, coordinates, SVG attributes): select an element → change the controls in the right panel → preview updates immediately, but nothing is written to `svg_output/` until **Apply changes**. `Ctrl+Z` or the **Undo** button drops staged edits step by step; applied changes are logged to `<project>/.live_edits.jsonl`. Re-export stays chat-driven: say "re-export" / "重新导出" to refresh the PPTX.+- editor is at the URL reported by the launcher, e.g. `http://localhost:5050`+- **Direct edit** (deterministic tweaks — wording, color, coordinates, SVG attributes): select an element → change the controls in the right panel → preview updates immediately, but nothing is written to `svg_output/` until **Apply changes**. `Ctrl+Z` or the **Undo** button drops staged edits step by step; applied changes are logged to `<project>/live_preview/edits.jsonl`. Re-export stays chat-driven: say "re-export" / "重新导出" to refresh the PPTX.- **Annotate** (changes that need AI judgement / re-layout): select an element → write the instruction → click **Add annotation** to stage it → click **Apply changes** to write annotation markers → return to the chat and say `apply my annotations` (or quote the browser prompt)- to skip the editor, just describe the change in chat@@ -60,6 +60,7 @@ Triggered by the user signals listed in "When to Run".3. For each listed annotation:- Edit the targeted element in `<project_path>/svg_output/<file>` per the annotation text.- Remove `data-edit-target` and `data-edit-annotation` from that element.+ - Append one `annotation_applied` JSONL record to `<project_path>/live_preview/annotations.jsonl` with `ts`, `file`, `element_id`, and the original annotation text.4. Re-export:```bashpython3 ${SKILL_DIR}/scripts/finalize_svg.py <project_path>@@ -78,13 +79,13 @@ Triggered by the user signals listed in "When to Run".- **Drag to move**: press and drag an already-selected element on the canvas to reposition it (selection stays a separate click, so the background is never dragged by accident); the whole selection moves together under multi-select. The pointer delta is mapped through each element's own CTM, so moves track the cursor regardless of viewport scale or group transforms. Each release stages one direct edit per moved element (the same `x`/`y`-or-`transform` write the geometry inputs produce), previewed live and written only on **Apply changes**; dragging on empty canvas is still rubber-band selection. A failed stage rolls the canvas back to the pre-drag position.- **Arrow-key nudge**: with one or more elements selected, `↑ ↓ ← →` moves the selection 1px and `Shift + arrow` moves 10px (suppressed while typing in the annotation box). Arrow keys navigate slides only when nothing is selected. Same staging/coalescing path as drag, so a burst of nudges collapses to one undo step.- **Overlap picker**: right-click anywhere on the canvas to list every selectable element under the pointer (top→bottom), so stacked shapes can be reached without blind cycling. Left-click is unchanged (selects the topmost). Hovering a row highlights that element; clicking it selects it; `Esc` or an outside click closes the list. With exactly one element under the pointer, right-click selects it directly.-- **Undo**: `Ctrl+Z` or the **Undo** button drops the last staged direct edit on the current slide (per-slide LIFO, this session). Consecutive edits to the *same element and same field set* (e.g. nudging one color or coordinate several times) coalesce into a single undo step, keeping the original pre-edit value; switching element or field starts a new step. Applied old→new history is appended to `<project>/.live_edits.jsonl`; un-applied staged edits are in-memory only.+- **Undo**: `Ctrl+Z` or the **Undo** button drops the last staged direct edit on the current slide (per-slide LIFO, this session). Consecutive edits to the *same element and same field set* (e.g. nudging one color or coordinate several times) coalesce into a single undo step, keeping the original pre-edit value; switching element or field starts a new step. Applied old→new history is appended to `<project>/live_preview/edits.jsonl`; annotation save/update/remove history is appended to `<project>/live_preview/annotations.jsonl`; un-applied staged edits are in-memory only.- **Unsaved-work guard**: staged direct edits and annotation changes (added or removed) live in server memory until **Apply changes**; closing the tab triggers the browser's native "leave site?" prompt while any are unapplied, since an idle timeout or process kill would drop them.- **Re-export is chat-driven**: applying changes updates `svg_output/` only. Refreshing the PPTX (finalize + svg_to_pptx) stays a chat step — the editor never runs the export pipeline.- **Stop conditions**: the service stops when the user clicks **Exit preview** in the browser, asks in chat to stop it, the idle timeout fires, or the process is killed externally.- **Port**: default `5050`, auto-advancing to the next free port when another project already holds it (report the actual URL from the launch log); force a specific port with `--port <other>`.- **Idle timeout**: plain mode `900s`, `--live` mode `7200s`; override with `--timeout <seconds>` (`0` disables).-- **Single instance per project**: `<project_path>/.live_preview.lock` records the running pid + port. A second launch against the same project refuses to start and prints the existing URL; stale locks (dead pid) are overwritten on the next launch. Delete the file by hand only if the process is gone but the lock remains (rare — `kill -9` is the only common cause).+- **Single instance per project**: `<project_path>/live_preview/lock.json` records the running pid + port. A second launch against the same project refuses to start and prints the existing URL; stale locks (dead pid) are overwritten on the next launch. Legacy root locks at `<project_path>/.live_preview.lock` are still detected when they point to a live process.- **Transient ids**: each element gets a temporary `_edit_N` id while the editor is running. On save, only annotated elements keep their id; unannotated `_edit_N` ids are stripped before write-back.- **Browser preview**: the server inlines `<use data-icon>` placeholders and serves `images/*` so SVG renders correctly; the on-disk SVG is unchanged by this preview.@@ -95,9 +96,9 @@ Triggered by the user signals listed in "When to Run".If the project lives on a remote Linux server, run with `--no-browser`:```bash-python3 ${SKILL_DIR}/scripts/svg_editor/server.py <project_path> --no-browser+python3 ${SKILL_DIR}/scripts/svg_editor/server.py <project_path> --daemon --no-browser# or for Step 6's auto-startup on a remote host:-python3 ${SKILL_DIR}/scripts/svg_editor/server.py <project_path> --live --no-browser+python3 ${SKILL_DIR}/scripts/svg_editor/server.py <project_path> --live --daemon --no-browser```- **VS Code / Cursor Remote-SSH**: open the **PORTS** panel (`Ctrl+Shift+P` → `Ports: Focus on Ports View`), click **Forward a Port**, enter `5050`. The workspace remembers it.