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): surface errors, speed up rendering, prevent server stacking
hugohe37ff38557ba93
diff --git a/skills/ppt-master/scripts/svg_editor/server.py b/skills/ppt-master/scripts/svg_editor/server.pyindex acc9b068..6d70997c 100644--- a/skills/ppt-master/scripts/svg_editor/server.py+++ b/skills/ppt-master/scripts/svg_editor/server.py@@ -18,8 +18,12 @@ Dependencies:"""import argparse+import atexit+import json+import loggingimport osimport re+import signalimport sysimport threadingimport time@@ -30,6 +34,12 @@ from typing import Optionalfrom flask import Flask, jsonify, request, send_from_directory+logger = 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'+# Local — sys.path injection for sibling module (code-style.md §3)_SCRIPTS_DIR = Path(__file__).resolve().parentif str(_SCRIPTS_DIR) not in sys.path:@@ -55,30 +65,115 @@ from embed_icons import ( # noqa: E402_ICONS_DIR = _SCRIPTS_DIR.parent.parent / 'templates' / 'icons'_USE_ICON_PATTERN = re.compile(r'<use\s+[^>]*data-icon="[^"]*"[^>]*/>')+# Per-path mtime caches: key = absolute path str, value = (mtime, payload).+# Entry is evicted/replaced when the file's mtime changes, so stale data+# cannot leak. Locks guard concurrent access under Flask's threaded server.+_SLIDE_CACHE_LOCK = threading.Lock()+_SLIDE_CACHE: dict = {} # path -> (mtime, (content, warnings))++_LIST_CACHE_LOCK = threading.Lock()+_LIST_CACHE: dict = {} # path -> (mtime, annotation_count_on_disk)+++def _cache_get(cache: dict, lock: threading.Lock, path: str, mtime: float):+ with lock:+ entry = cache.get(path)+ if entry is None or entry[0] != mtime:+ return None+ return entry[1]+++def _cache_put(cache: dict, lock: threading.Lock, path: str, mtime: float, value) -> None:+ with lock:+ cache[path] = (mtime, value)+-def _inline_icons(content: str) -> str:+def _process_alive(pid: int) -> bool:+ """Return True if a process with this pid is reachable.++ ``os.kill(pid, 0)`` succeeds when the process exists even without+ permission to signal it; ``PermissionError`` therefore still counts+ as alive (a real lock holder owned by another user). ``ESRCH`` /+ other ``OSError`` means the pid is gone.+ """+ if pid <= 0:+ return False+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ except PermissionError:+ return True+ except OSError:+ return False+ return True+++def _read_lock(lock_file: Path) -> Optional[dict]:+ try:+ data = json.loads(lock_file.read_text(encoding='utf-8'))+ return data if isinstance(data, dict) else None+ except (OSError, json.JSONDecodeError):+ return None+++def _claim_lock(lock_file: Path, port: int) -> Optional[dict]:+ """Try to claim the per-project preview slot.++ Returns ``None`` on success. If another live process already holds the+ slot, returns the existing lock dict (caller surfaces it as an error).+ A stale lock (pointing at a dead pid) is silently overwritten.+ """+ existing = _read_lock(lock_file)+ if existing and _process_alive(int(existing.get('pid', 0))):+ return existing+ lock_file.write_text(+ json.dumps({'pid': os.getpid(), 'port': port}),+ encoding='utf-8',+ )+ return None+++def _release_lock(lock_file: Path) -> None:+ """Best-effort cleanup: only delete the lock if it still names *us*."""+ try:+ current = _read_lock(lock_file)+ if current and int(current.get('pid', 0)) == os.getpid():+ lock_file.unlink(missing_ok=True)+ except OSError:+ pass+++def _inline_icons(content: str) -> tuple[str, list[dict]]:"""Replace <use data-icon="..."/> with rendered <g> for browser preview.- Preserves the original <use>'s id on the produced <g> so editor element- targeting (and AI-side annotation lookups against svg_output) stays consistent.+ Returns (rewritten_content, warnings). Each warning is+ ``{"icon": <name>, "reason": <str>}`` so the frontend can surface+ "icon X not found" to the user instead of silently dropping it."""+ warnings: list[dict] = []matches = list(_USE_ICON_PATTERN.finditer(content))if not matches:- return content+ return content, warningsnew_content = contentfor match in reversed(matches):use_str = match.group(0)+ icon_name: str = ''try:attrs = parse_use_element(use_str)- icon_name = attrs.get('icon')+ icon_name = str(attrs.get('icon') or '')if not icon_name:+ warnings.append({'icon': '', 'reason': 'missing data-icon attribute'})continue- icon_path, _ = resolve_icon_path(str(icon_name), _ICONS_DIR)+ icon_path, _ = resolve_icon_path(icon_name, _ICONS_DIR)color = str(attrs.get('fill', '#000000'))elements, style, base_size = extract_paths_from_icon(icon_path, color)- except Exception:+ except Exception as exc:+ warnings.append({'icon': icon_name, 'reason': f'{type(exc).__name__}: {exc}'})+ logger.warning('icon inline failed: name=%r reason=%s', icon_name, exc)continueif not elements:+ warnings.append({'icon': icon_name, 'reason': 'no renderable paths in icon'})continuereplacement = generate_icon_group(attrs, elements, style, base_size)id_match = re.search(r'\bid="([^"]+)"', use_str)@@ -87,10 +182,15 @@ def _inline_icons(content: str) -> str:'<g ', f'<g id="{id_match.group(1)}" data-icon="{icon_name}" ', 1,)new_content = new_content[:match.start()] + replacement + new_content[match.end():]- return new_content+ return new_content, warnings-def create_app(project_dir: str, idle_timeout: int = 900, live: bool = False) -> Flask:+def create_app(+ project_dir: str,+ idle_timeout: int = 900,+ live: bool = False,+ lock_file: Optional[Path] = None,+) -> Flask:"""Create and configure the Flask app for a given project directory."""project_path = Path(project_dir).resolve()svg_dir = project_path / 'svg_output'@@ -101,6 +201,7 @@ def create_app(project_dir: str, idle_timeout: int = 900, live: bool = False) ->app.config['PROJECT_PATH'] = project_pathapp.config['SVG_DIR'] = svg_dirapp.config['LIVE_MODE'] = live+ app.config['LOCK_FILE'] = lock_file# In-memory annotation store: {filename: {element_id: annotation_text}}app.config['ANNOTATIONS'] = {}@@ -112,6 +213,14 @@ def create_app(project_dir: str, idle_timeout: int = 900, live: bool = False) ->def _update_activity():app.config['LAST_REQUEST_TIME'] = time.time()+ def _exit_with_lock_release(code: int = 0) -> None:+ lf = app.config.get('LOCK_FILE')+ if lf is not None:+ _release_lock(lf)+ # os._exit: atexit handlers do not run; we just released the lock+ # manually above so a clean restart still finds the slot free.+ os._exit(code)+def _idle_watchdog():if idle_timeout <= 0:return@@ -119,10 +228,10 @@ def create_app(project_dir: str, idle_timeout: int = 900, live: bool = False) ->time.sleep(10)elapsed = time.time() - app.config['LAST_REQUEST_TIME']if elapsed > idle_timeout:- print(f"SVG Editor idle for {idle_timeout}s, shutting down.")- # os._exit: Flask dev server has no clean shutdown mechanism;- # data is safe because idle timeout only fires when no requests are in flight.- os._exit(0)+ logger.info('idle for %ds, shutting down', idle_timeout)+ # Flask dev server has no clean shutdown; data is safe+ # because idle timeout only fires when no requests are in flight.+ _exit_with_lock_release(0)watchdog = threading.Thread(target=_idle_watchdog, daemon=True)watchdog.start()@@ -134,9 +243,9 @@ def create_app(project_dir: str, idle_timeout: int = 900, live: bool = False) ->def _stop():time.sleep(0.5) # Let HTTP response flush before killing the process- print(f"SVG Editor shutting down ({reason}).")+ logger.info('shutting down (%s)', reason)# os._exit: save-all already wrote to disk; 0.5s delay ensures response is sent.- os._exit(0)+ _exit_with_lock_release(0)threading.Thread(target=_stop, daemon=True).start()return jsonify({'status': 'ok'})@@ -191,20 +300,37 @@ def create_app(project_dir: str, idle_timeout: int = 900, live: bool = False) ->annotations = app.config['ANNOTATIONS']slides = []for svg_file in sorted(svg_dir.glob('*.svg')):- disk_annotations = []+ path_str = str(svg_file)try:- tree = ET.parse(str(svg_file))- disk_annotations = parse_annotations(tree.getroot())- except ET.ParseError:- pass+ mtime = svg_file.stat().st_mtime+ except OSError as exc:+ logger.warning('stat failed: %s: %s', path_str, exc)+ continue++ ok = True+ error_msg: Optional[str] = None+ disk_count = _cache_get(_LIST_CACHE, _LIST_CACHE_LOCK, path_str, mtime)+ if disk_count is None:+ try:+ tree = ET.parse(path_str)+ disk_count = len(parse_annotations(tree.getroot()))+ except ET.ParseError as exc:+ ok = False+ error_msg = f'XML parse error: {exc}'+ disk_count = 0+ logger.warning('slide parse failed: %s: %s', svg_file.name, exc)+ _cache_put(_LIST_CACHE, _LIST_CACHE_LOCK, path_str, mtime, disk_count)mem_count = len(annotations.get(svg_file.name, {}))- annotation_count = max(len(disk_annotations), mem_count)+ annotation_count = max(disk_count, mem_count)slides.append({'name': svg_file.name,'annotated': annotation_count > 0,'annotation_count': annotation_count,+ 'ok': ok,+ 'error': error_msg,+ 'mtime': mtime,})return jsonify({'slides': slides})@@ -230,43 +356,62 @@ def create_app(project_dir: str, idle_timeout: int = 900, live: bool = False) ->if not svg_file.exists():return jsonify({'error': 'Slide not found'}), 404+ path_str = str(svg_file)try:- tree = ET.parse(str(svg_file))- root = tree.getroot()- except ET.ParseError as e:- return jsonify({'error': f'Failed to parse SVG: {e}'}), 500-- assign_temp_ids(root)+ mtime = svg_file.stat().st_mtime+ except OSError as exc:+ logger.warning('stat failed: %s: %s', path_str, exc)+ return jsonify({'error': f'Failed to stat SVG: {exc}'}), 500++ cached = _cache_get(_SLIDE_CACHE, _SLIDE_CACHE_LOCK, path_str, mtime)+ if cached is not None:+ content, warnings, disk_annotations, id_to_tag = cached+ else:+ try:+ tree = ET.parse(path_str)+ root = tree.getroot()+ except ET.ParseError as exc:+ logger.warning('slide parse failed: %s: %s', name, exc)+ return jsonify({'error': f'Failed to parse SVG: {exc}'}), 500- disk_annotations = parse_annotations(root)+ assign_temp_ids(root)+ disk_annotations = parse_annotations(root)+ id_to_tag: dict[str, str] = {}+ for elem in root.iter():+ eid = elem.get('id')+ if eid:+ tag = elem.tag+ if '}' in tag:+ tag = tag.split('}', 1)[1]+ id_to_tag[eid] = tag+ content = ET.tostring(root, encoding='unicode', xml_declaration=False)+ content, warnings = _inline_icons(content)+ _cache_put(+ _SLIDE_CACHE, _SLIDE_CACHE_LOCK, path_str, mtime,+ (content, warnings, disk_annotations, id_to_tag),+ )mem_annotations = app.config['ANNOTATIONS'].get(name, {})- merged = {}+ merged: dict[str, str] = {}for ann in disk_annotations:merged[ann['element_id']] = ann['annotation']merged.update(mem_annotations)- annotations_list = []- for elem in root.iter():- eid = elem.get('id')- if eid and eid in merged:- tag = elem.tag- if '}' in tag:- tag = tag.split('}', 1)[1]- annotations_list.append({- 'element_id': eid,- 'tag': tag,- 'annotation': merged[eid],- })-- content = ET.tostring(root, encoding='unicode', xml_declaration=False)- # Inline <use data-icon> placeholders so the browser can render icons.- content = _inline_icons(content)+ annotations_list = [+ {+ 'element_id': eid,+ 'tag': id_to_tag.get(eid, ''),+ 'annotation': ann_text,+ }+ for eid, ann_text in merged.items()+ ]return jsonify({'name': name,'content': content,'annotations': annotations_list,+ 'warnings': warnings,+ 'mtime': mtime,})@app.route('/api/slide/<name>/annotate', methods=['POST'])@@ -378,7 +523,7 @@ def build_parser() -> argparse.ArgumentParser:'--timeout',type=int,default=None,- help='Idle timeout in seconds (default: 900; live mode default: 0 = disabled)',+ help='Idle timeout in seconds (default: 900; live mode default: 7200; 0 = disabled)',)return parser@@ -387,31 +532,81 @@ def main(argv: Optional[list[str]] = None) -> int:parser = build_parser()args = parser.parse_args(argv)+ logging.basicConfig(+ level=logging.INFO,+ format='[%(asctime)s] [%(levelname)s] svg_editor: %(message)s',+ datefmt='%H:%M:%S',+ )+project_path = Path(args.project_dir).resolve()svg_output = project_path / 'svg_output'if not svg_output.exists():if args.live:svg_output.mkdir(parents=True, exist_ok=True)else:- print(f"Error: {svg_output} does not exist", file=sys.stderr)+ logger.error('%s does not exist', svg_output)return 1elif not svg_output.is_dir():- print(f"Error: {svg_output} is not a directory", file=sys.stderr)+ logger.error('%s is not a directory', svg_output)return 1+ # Per-project mutual exclusion. The major driver of orphaned servers is+ # --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+ existing = _claim_lock(lock_file, args.port)+ if existing:+ 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, click '+ 'Exit preview in the browser, or run: kill %s',+ existing_pid, existing_port, existing_port, existing_pid,+ )+ return 1+ # 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.+ atexit.register(_release_lock, lock_file)++ # SIGTERM would otherwise terminate without running atexit, leaving a+ # stale lock that future launches have to recover from. Translate it+ # into SystemExit so the atexit handler above runs. SIGINT (Ctrl+C) is+ # already handled by werkzeug's reloader-free shutdown path.+ def _on_sigterm(signum: int, _frame) -> None:+ logger.info('received signal %s, exiting', signum)+ sys.exit(0)+ try:+ signal.signal(signal.SIGTERM, _on_sigterm)+ except (ValueError, OSError):+ # ValueError: not in main thread; OSError: unsupported on platform.+ pass+idle_timeout = args.timeoutif idle_timeout is None:- idle_timeout = 0 if args.live else 900-- app = create_app(str(project_path), idle_timeout=idle_timeout, live=args.live)+ # Long but finite default for --live so a forgotten preview eventually+ # dies. Set --timeout 0 to keep the historical never-expire behavior.+ idle_timeout = 7200 if args.live else 900++ app = create_app(+ str(project_path),+ idle_timeout=idle_timeout,+ live=args.live,+ lock_file=lock_file,+ )url = f'http://localhost:{args.port}'if not args.no_browser:webbrowser.open(url)mode = "live preview (auto-startup)" if args.live else "live preview"- print(f"SVG Editor running at {url} ({mode})")- print(f"Project: {project_path}")+ svg_count = len(list(svg_output.glob('*.svg')))+ logger.info('running at %s (%s)', url, mode)+ logger.info('project: %s', project_path)+ logger.info('svg_output: %s (%d slides)', svg_output, svg_count)+ logger.info('idle timeout: %ds (0 = disabled)', idle_timeout)app.run(host='127.0.0.1', port=args.port, debug=False)return 0diff --git a/skills/ppt-master/scripts/svg_editor/static/app.js b/skills/ppt-master/scripts/svg_editor/static/app.jsindex 9ced2237..3dc53fa3 100644--- a/skills/ppt-master/scripts/svg_editor/static/app.js+++ b/skills/ppt-master/scripts/svg_editor/static/app.js@@ -36,6 +36,10 @@err_add_annotation: "Failed to add annotation: ",err_remove_annotation: "Failed to remove annotation: ",err_save: "Save failed: ",+ err_empty_svg: "Slide loaded but the canvas is empty. The SVG may be malformed or missing a root <svg> element.",+ warn_icon_inline: "{count} icon(s) failed to render: {names}",+ slide_error_tooltip: "Failed to parse this slide: ",+ reload_banner: "This slide was updated on disk. Click to reload.",modal_confirm_submit: "Submit annotations to disk?\n\nThe preview service will keep running. Click Exit preview when you want to stop it.",modal_success_submit: "Annotations saved.\n\nReturn to the chat and tell the AI to apply them (e.g. \"apply my annotations\"). The preview service is still running.",modal_confirm_exit: "Exit preview and stop the local server?\n\nUnsaved annotations will be discarded.",@@ -78,6 +82,10 @@err_add_annotation: "添加标注失败:",err_remove_annotation: "删除标注失败:",err_save: "保存失败:",+ err_empty_svg: "幻灯片已加载但画布为空。SVG 可能损坏或缺少根 <svg> 元素。",+ warn_icon_inline: "{count} 个图标渲染失败:{names}",+ slide_error_tooltip: "该幻灯片解析失败:",+ reload_banner: "当前页已在磁盘上更新,点此重新加载。",modal_confirm_submit: "确认将标注保存到磁盘?\n\n预览服务会继续运行。需要关闭时请点击退出预览。",modal_success_submit: "标注已保存。\n\n请回到对话窗口并告诉 AI 应用这些标注(例如\"应用我的标注\")。预览服务仍在运行。",modal_confirm_exit: "退出预览并停止本地服务?\n\n未保存的标注将被丢弃。",@@ -178,6 +186,8 @@var liveMode = false;var slidePollTimer = null;var pendingModalAction = "submit";+ var slideMtimes = {}; // {name: mtime} — last-seen mtime for each slide+ var reloadBannerEl = null; // singleton banner element shown when currentSlide mtime driftsfunction currentSlideIndex() {if (!currentSlide) return -1;@@ -245,10 +255,28 @@}var currentExists = false;+ var currentMtimeChanged = false;slides.forEach(function (s) {- if (s.name === currentSlide) currentExists = true;+ if (s.name === currentSlide) {+ currentExists = true;+ // Compare against the mtime we recorded when we last rendered this slide.+ var lastSeen = slideMtimes[s.name];+ if (lastSeen !== undefined && s.mtime && s.mtime !== lastSeen) {+ currentMtimeChanged = true;+ }+ }+ // Track every slide's mtime for the next poll (only update non-current here;+ // currentSlide's mtime is updated by selectSlide so we can detect drift).+ if (s.name !== currentSlide && s.mtime !== undefined) {+ slideMtimes[s.name] = s.mtime;+ }+var item = document.createElement("div");item.className = "slide-item" + (s.name === currentSlide ? " active" : "");+ if (s.ok === false) {+ item.className += " slide-error";+ item.title = t("slide_error_tooltip") + (s.error || "");+ }item.setAttribute("data-name", s.name);var nameSpan = document.createElement("span");@@ -271,6 +299,8 @@if (!currentSlide || !currentExists) {selectSlide(slides[0].name);+ } else if (currentMtimeChanged) {+ showReloadBanner(currentSlide);}updateNavLabel();})@@ -299,11 +329,15 @@cancelRubberBand();clearSelection();+ // Selecting a slide implicitly dismisses any stale "page updated" banner.+ hideReloadBanner();+fetch("/api/slide/" + encodeURIComponent(name)).then(function (res) { return res.json(); }).then(function (data) {if (data.error) {console.error("selectSlide:", data.error);+ showError(t("err_load_slide") + data.error);if (liveMode) {currentSlide = null;svgPlaceholder.style.display = "block";@@ -317,6 +351,45 @@svgContent.style.display = "block";svgContent.innerHTML = sanitizeSvg(data.content);+ // Empty-canvas guard: surface a clear error if the SVG parsed+ // to nothing renderable (issue #115's silent-blank scenario).+ var rootSvg = svgContent.querySelector("svg");+ var hasContent = false;+ if (rootSvg) {+ var children = rootSvg.querySelectorAll("*");+ for (var i = 0; i < children.length; i++) {+ var ctag = children[i].tagName.toLowerCase();+ if (ctag !== "defs" && ctag !== "style" && ctag !== "title" && ctag !== "desc") {+ hasContent = true;+ break;+ }+ }+ }+ if (!rootSvg || !hasContent) {+ showError(t("err_empty_svg"));+ svgPlaceholder.style.display = "block";+ svgPlaceholder.textContent = t("err_empty_svg");+ svgContent.style.display = "none";+ return;+ }++ // Non-fatal warnings (e.g. icon inline failures): surface as a+ // single combined toast so users know why something looks off.+ if (data.warnings && data.warnings.length > 0) {+ var names = data.warnings.map(function (w) {+ return w.icon || "(unknown)";+ }).join(", ");+ showWarning(t("warn_icon_inline", {+ count: data.warnings.length,+ names: names,+ }));+ }++ // Record the mtime so the next poll can detect on-disk drift.+ if (data.mtime !== undefined) {+ slideMtimes[name] = data.mtime;+ }+// Build annotations map from response(data.annotations || []).forEach(function (a) {slideAnnotations[a.element_id] = a.annotation;@@ -341,27 +414,40 @@var svg = svgContent.querySelector("svg");if (!svg) return;+ // Visual class only — selectability is handled by the delegated handler below.+ // Skipping the per-element addEventListener brings listener-registration time+ // from O(n) to O(1), which matters on decks with hundreds of elements per slide.var allEls = svg.querySelectorAll("*");allEls.forEach(function (el) {var tag = el.tagName.toLowerCase();if (SKIP_TAGS.indexOf(tag) !== -1) return;if (el === svg) return;-el.classList.add("svg-selectable");-- el.addEventListener("click", function (e) {- e.stopPropagation();- selectElement(el, e.ctrlKey || e.metaKey);- });});- // Click on blank area clears selection (skip the synthetic click after rubber band)svg.addEventListener("click", function (e) {+ // Skip the synthetic click that follows a rubber-band drag-release.if (suppressNextSvgClick) {suppressNextSvgClick = false;return;}- if (e.target === svg) clearSelection();+ var target = e.target;+ // Blank-area click on the svg root → clear selection.+ if (target === svg) {+ clearSelection();+ return;+ }+ // Ignore clicks bubbling out of non-interactive subtrees.+ if (target.closest && target.closest("defs, style, title, desc")) return;+ // Backend assign_temp_ids() guarantees every element has an id, so+ // closest("[id]") will always find a hit. The exclusion of `svg`+ // itself routes "click outside any real shape" to clearSelection.+ var picked = target.closest("[id]");+ if (!picked || picked === svg) {+ clearSelection();+ return;+ }+ selectElement(picked, e.ctrlKey || e.metaKey);});}@@ -896,6 +982,42 @@setTimeout(function () { banner.remove(); }, 5000);}+ function showWarning(msg) {+ // Amber, non-fatal counterpart to showError. Stacks below an existing+ // error banner because z-index is identical and DOM order wins.+ var banner = document.createElement("div");+ banner.style.cssText = "position:fixed;top:38px;left:0;right:0;padding:8px 16px;background:#f59e0b;color:#1f1300;font-size:12px;text-align:center;z-index:998;cursor:pointer;";+ banner.textContent = msg;+ banner.onclick = function () { banner.remove(); };+ document.body.appendChild(banner);+ setTimeout(function () { banner.remove(); }, 6000);+ }++ function showReloadBanner(name) {+ // Singleton: replace any prior banner so we never stack reloads.+ hideReloadBanner();+ var banner = document.createElement("div");+ banner.id = "reload-banner";+ banner.style.cssText = "position:fixed;top:0;left:0;right:0;padding:10px 16px;background:#2563eb;color:#fff;font-size:13px;text-align:center;z-index:1000;cursor:pointer;";+ banner.textContent = t("reload_banner");+ banner.onclick = function () {+ hideReloadBanner();+ // Re-fetch via selectSlide so all post-load logic (annotation merge,+ // warnings, mtime update) runs the same way as a manual click.+ var item = slideListEl.querySelector('.slide-item[data-name="' + cssAttr(name) + '"]');+ selectSlide(name, item || undefined);+ };+ document.body.appendChild(banner);+ reloadBannerEl = banner;+ }++ function hideReloadBanner() {+ if (reloadBannerEl) {+ reloadBannerEl.remove();+ reloadBannerEl = null;+ }+ }+function escapeHtml(str) {var d = document.createElement("div");d.appendChild(document.createTextNode(str));diff --git a/skills/ppt-master/scripts/svg_editor/static/style.css b/skills/ppt-master/scripts/svg_editor/static/style.cssindex dc2e79f9..1381d1ec 100644--- a/skills/ppt-master/scripts/svg_editor/static/style.css+++ b/skills/ppt-master/scripts/svg_editor/static/style.css@@ -90,6 +90,19 @@ html, body {border-left-color: #4a9eff;}+.slide-item.slide-error {+ border-left-color: #ef4444;+}++.slide-item.slide-error .slide-name {+ color: #fca5a5;+}++.slide-item.slide-error .slide-name::before {+ content: "⚠ ";+ color: #ef4444;+}+.slide-item .slide-name {flex: 1;white-space: nowrap;diff --git a/skills/ppt-master/workflows/live-preview.md b/skills/ppt-master/workflows/live-preview.mdindex b63bbfc1..63508d74 100644--- a/skills/ppt-master/workflows/live-preview.md+++ b/skills/ppt-master/workflows/live-preview.md@@ -73,9 +73,10 @@ Triggered by the user signals listed in "When to Run".- **UI**: bilingual (EN/中); auto-detects from `navigator.language`, persists in `localStorage`, toggled via the **中 / EN** button on the right panel. Slide navigation: first/prev/next/last buttons at the top of the center panel, plus `←` / `→` / `Home` / `End` (suppressed while typing in the annotation textarea).- **Buttons**: `Add annotation` stages locally; `Submit annotations` writes to disk and keeps the service running; `Exit preview` is the only UI action that stops Flask.-- **Stop conditions**: once started, the service runs until the user clicks **Exit preview** in the browser, or asks in chat to stop it.+- **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`; override with `--port <other>`.-- **Idle timeout**: plain mode `900s`, `--live` mode `0` (disabled); override with `--timeout <seconds>`.+- **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).- **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.