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(svg-editor): keep unapplied annotations and edits across server restarts
hugohe31fa3768abbcc
diff --git a/skills/ppt-master/scripts/docs/svg_editor.md b/skills/ppt-master/scripts/docs/svg_editor.mdindex f5ba4bdd..cc0d42e3 100644--- a/skills/ppt-master/scripts/docs/svg_editor.md+++ b/skills/ppt-master/scripts/docs/svg_editor.md@@ -18,7 +18,8 @@ The launcher starts the server in the background, waits for `GET /api/health`, r- **Port**: without `--port`, the first free port from `6060`; `--port N` binds strictly and fails if unavailable. Read the actual URL from launch output or `live_preview/lock.json`; never assume `6060`.- **Idle timeout**: plain mode `900s`, `--live` `7200s`; `--timeout <seconds>` overrides (`0` disables).- **Single instance per project**: `live_preview/lock.json` is the discovery source for project-local consumers (including `visual_review.py`). A second launch reuses the live instance unless a different explicit `--port N` was requested — that mismatch fails and needs `--shutdown` first. Stale locks (dead pid) are overwritten; legacy `<project_path>/.live_preview.lock` root locks are still detected when live.-- **Stop conditions**: **Exit preview** in the browser (the only UI action that stops Flask), a chat request to stop, the idle timeout, or an external kill.+- **Stop conditions**: **Exit preview** in the browser (the only UI action that stops Flask), a chat request to stop, the idle timeout, or an external kill. None of them discards unapplied work; see **Draft**.+- **Draft**: every staging change (annotation add/remove, direct edit, undo) rewrites `live_preview/draft.json` before it is acknowledged; the file is removed once nothing is left unapplied. The next start restores each page whose SVG still matches the digest recorded when staging began, and the UI reports the restored pages. A page whose SVG changed meanwhile is not replayed — its draft moves to `live_preview/draft_conflict_<timestamp>.json`, as does an unreadable draft. A failed draft write is reported in the UI; the change then lives in memory only.- **Transient ids**: each element gets a temporary `_edit_N` id while running; on save only annotated elements keep their id.- **Browser preview**: the server inlines `<use data-icon>` placeholders and serves `images/*`; the on-disk SVG is unchanged by preview.- **Re-export is chat-driven**: applying changes updates `svg_output/` only; refreshing the PPTX (`finalize_svg.py` + `svg_to_pptx.py`) is a chat step — the editor never runs the export pipeline.@@ -26,13 +27,13 @@ The launcher starts the server in the background, waits for `GET /api/health`, r## Editing surface- **UI**: four languages (中文 / 繁體中文 / English / 日本語), auto-detected from `navigator.language`, persisted in `localStorage`, switchable from the right panel. The right panel separates direct SVG edits from AI-needed annotations, with a pending-status strip for staged edits and pages with unsaved annotations. Slide navigation: first/prev/next/last buttons plus `←` / `→` / `Home` / `End` (suppressed while typing in the annotation textarea).-- **Buttons**: `Add annotation` stages annotation text in memory; `Apply changes` writes staged direct edits plus annotation markers (`data-edit-target`, `data-edit-annotation`) to disk and keeps the service running; `Exit preview` stops Flask.+- **Buttons**: `Add annotation` stages annotation text in memory; `Apply changes` writes staged direct edits plus annotation markers (`data-edit-target`, `data-edit-annotation`) to disk and keeps the service running; `Exit preview` stops Flask and keeps unapplied work in the draft.- **Direct edit (no AI)**: single element = full inspector (geometry, safe text content, computed text styles for the selected text node or descendant text, raw attributes except protected fields such as `id`, UI `class`, event handlers, hrefs). `<g>` group = group-level surface, selected via `Alt/Option` + click or **Select parent group**. Multi-select = batch editor over top-level objects only: shared x/y plus `fill` / `stroke` / `opacity`; text style fields appear only when every selected object is `text` / `tspan`. Preview updates immediately; disk writes wait for **Apply changes**.- **Drag to move**: press and drag an already-selected element (selection stays a separate click, so the background is never dragged by accident); the whole selection moves together. Pointer delta is mapped through each element's CTM, so moves track the cursor regardless of viewport scale or group transforms. Each release stages one direct edit per moved element; dragging on empty canvas is rubber-band selection; a failed stage rolls the canvas back.- **Arrow-key nudge**: `↑ ↓ ← →` moves the selection 1px, `Shift + arrow` 10px (suppressed while typing); arrow keys navigate slides only when nothing is selected. Same staging/coalescing as drag.- **Overlap picker**: right-click lists every selectable element under the pointer (top→bottom); hovering highlights, clicking selects, `Esc` or an outside click closes; with one element under the pointer, right-click selects it directly. Left-click selects the topmost.-- **Undo**: `Ctrl+Z` or **Undo** drops the last staged direct edit on the current slide (per-slide LIFO, this session). Consecutive edits to the same element and field set coalesce into one step keeping the original pre-edit value. Applied old→new history goes to `live_preview/edits.jsonl`; annotation save/update/remove history to `live_preview/annotations.jsonl`; un-applied staged edits are memory only.-- **Unsaved-work guard**: staged edits and annotation changes live in server memory until **Apply changes**; closing the tab triggers the browser's "leave site?" prompt while any are unapplied.+- **Undo**: `Ctrl+Z` or **Undo** drops the last staged direct edit on the current slide (per-slide LIFO, this session). Consecutive edits to the same element and field set coalesce into one step keeping the original pre-edit value. Applied old→new history goes to `live_preview/edits.jsonl`; annotation save/update/remove history to `live_preview/annotations.jsonl`; un-applied staged edits live in memory plus `live_preview/draft.json`.+- **Unsaved-work guard**: staged edits and annotation changes stay unapplied until **Apply changes**; closing the tab triggers the browser's "leave site?" prompt while any are unapplied. **Apply changes** fails a page, keeping it staged, when an annotated element no longer exists, and the UI flags a submit that finds nothing pending on the server.## Remote accessdiff --git a/skills/ppt-master/scripts/svg_editor/server.py b/skills/ppt-master/scripts/svg_editor/server.pyindex 3d669b43..1c9b544a 100644--- a/skills/ppt-master/scripts/svg_editor/server.py+++ b/skills/ppt-master/scripts/svg_editor/server.py@@ -19,6 +19,8 @@ Dependencies:import argparseimport atexit+import functools+import hashlibimport htmlimport jsonimport logging@@ -44,6 +46,9 @@ logger = logging.getLogger('svg_editor')LIVE_PREVIEW_DIR_NAME = 'live_preview'LOCK_FILE_NAME = 'lock.json'LEGACY_LOCK_FILE_NAME = '.live_preview.lock'+# Unapplied staged work, rewritten after every staging change (issue #319).+DRAFT_FILE_NAME = 'draft.json'+DRAFT_VERSION = 1# Local — sys.path injection for sibling module (code-style.md §3)_SCRIPTS_DIR = Path(__file__).resolve().parent@@ -341,6 +346,25 @@ def _append_annotation_log(project_path: Path, record: dict) -> None:_append_live_preview_log(project_path, ANNOTATION_LOG_NAME, record)+def _file_digest(path: Path) -> str:+ return hashlib.sha256(path.read_bytes()).hexdigest()+++def _atomic_replace(path: Path, write) -> None:+ """Write through ``write(tmp_path)`` and swap the result into ``path``.++ A crash mid-write leaves the original file intact instead of a truncated+ SVG or draft.+ """+ tmp = path.with_name(f'.{path.name}.{os.getpid()}.tmp')+ try:+ write(tmp)+ os.replace(tmp, path)+ except BaseException:+ tmp.unlink(missing_ok=True)+ raise++def _find_by_id(root: ET.Element, element_id: str) -> Optional[ET.Element]:for elem in root.iter():if elem.get('id') == element_id:@@ -452,8 +476,160 @@ def create_app(# but are written to svg_output/ only by /api/save-all.app.config['PENDING_EDITS'] = {}- # Idle timeout: auto-shutdown if no one connects within idle_timeout seconds- app.config['LAST_REQUEST_TIME'] = time.time()+ # Per-file staging baseline: {filename: {'digest': sha256 of the SVG the+ # staged work was built on, 'annotations': its on-disk annotation map}}.+ # The digest keeps a restored draft from replaying onto a changed SVG,+ # where renumbered _edit_N ids would point at different elements.+ app.config['DRAFT_BASES'] = {}++ # Serializes every read-modify-write of the staged state and its draft.+ state_lock = threading.RLock()++ def _with_state_lock(view):+ @functools.wraps(view)+ def wrapper(*args, **kwargs):+ with state_lock:+ return view(*args, **kwargs)+ return wrapper++ def _note_base(name: str, svg_file: Path, disk_annotations: Optional[dict] = None) -> None:+ base = app.config['DRAFT_BASES'].setdefault(name, {'digest': None, 'annotations': None})+ if base['digest'] is None:+ base['digest'] = _file_digest(svg_file)+ if disk_annotations is not None and base['annotations'] is None:+ base['annotations'] = dict(disk_annotations)++ def _draft_pages() -> dict:+ """Pages whose staged state differs from what is on disk."""+ annotations = app.config['ANNOTATIONS']+ pending_edits = app.config['PENDING_EDITS']+ pages = {}+ for name in sorted(set(annotations) | set(pending_edits)):+ base = app.config['DRAFT_BASES'].get(name) or {}+ entry: dict = {}+ if name in annotations and annotations[name] != base.get('annotations'):+ entry['annotations'] = annotations[name]+ if pending_edits.get(name):+ entry['edits'] = pending_edits[name]+ if entry:+ entry['digest'] = base.get('digest')+ pages[name] = entry+ return pages++ def _persist_draft() -> bool:+ """Mirror the staged state to live_preview/draft.json; False on failure."""+ draft_file = _draft_file(project_path)+ pages = _draft_pages()+ try:+ if not pages:+ draft_file.unlink(missing_ok=True)+ return True+ payload = json.dumps(+ {'version': DRAFT_VERSION, 'pages': pages},+ ensure_ascii=False, indent=2,+ ).encode('utf-8')+ draft_file.parent.mkdir(parents=True, exist_ok=True)+ _atomic_replace(draft_file, lambda tmp: tmp.write_bytes(payload))+ except OSError as exc:+ logger.warning('draft save failed: %s', exc)+ return False+ return True++ def _restore_page(name: str, entry) -> Optional[dict]:+ """Load one draft page into memory; None when it no longer applies."""+ if not isinstance(entry, dict) or not isinstance(entry.get('digest'), str):+ return None+ anns = entry.get('annotations')+ edits = entry.get('edits') or []+ if anns is not None and not (+ isinstance(anns, dict)+ and all(isinstance(k, str) and isinstance(v, str) for k, v in anns.items())+ ):+ return None+ if not isinstance(edits, list) or not all(isinstance(e, dict) for e in edits):+ return None+ svg_file = _safe_svg_path(name)+ if svg_file is None or not svg_file.exists():+ return None+ try:+ if _file_digest(svg_file) != entry['digest']:+ return None+ root = ET.parse(str(svg_file)).getroot()+ materialize_inline_geometry_properties(root)+ except (OSError, ET.ParseError, GeometryStyleError):+ return None+ assign_temp_ids(root)+ disk_annotations = {+ item['element_id']: item['annotation']+ for item in parse_annotations(root)+ }+ ok, _reason = _apply_edit_records(root, edits)+ if not ok:+ return None+ app.config['DRAFT_BASES'][name] = {+ 'digest': entry['digest'],+ 'annotations': disk_annotations,+ }+ if anns is not None:+ app.config['ANNOTATIONS'][name] = dict(anns)+ if edits:+ app.config['PENDING_EDITS'][name] = edits+ return {'annotations': anns is not None, 'edits': len(edits)}++ def _restore_draft() -> dict:+ """Reload a draft left by a previous server; set aside what no longer fits."""+ status = {'restored': {}, 'conflicts': [], 'conflict_file': None, 'unreadable': False}+ draft_file = _draft_file(project_path)+ if not draft_file.exists():+ return status+ aside = draft_file.with_name(f'draft_conflict_{time.strftime("%Y%m%d-%H%M%S")}.json')+ try:+ data = json.loads(draft_file.read_text(encoding='utf-8'))+ pages = data.get('pages') if isinstance(data, dict) else None+ if data.get('version') != DRAFT_VERSION or not isinstance(pages, dict):+ raise ValueError('unrecognized draft format')+ except (OSError, ValueError, AttributeError) as exc:+ logger.warning('draft unreadable, set aside as %s: %s', aside.name, exc)+ try:+ os.replace(draft_file, aside)+ status['conflict_file'] = aside.name+ except OSError as move_exc:+ logger.warning('draft set-aside failed: %s', move_exc)+ status['unreadable'] = True+ return status++ conflicts = {}+ for name, entry in pages.items():+ restored = _restore_page(name, entry) if isinstance(name, str) else None+ if restored is None:+ conflicts[name] = entry+ else:+ status['restored'][name] = restored+ if conflicts:+ status['conflicts'] = sorted(str(name) for name in conflicts)+ try:+ payload = json.dumps(+ {'version': DRAFT_VERSION, 'pages': conflicts},+ ensure_ascii=False, indent=2,+ ).encode('utf-8')+ _atomic_replace(aside, lambda tmp: tmp.write_bytes(payload))+ status['conflict_file'] = aside.name+ except OSError as exc:+ # Leave draft.json untouched so the conflicting pages survive.+ logger.warning('draft conflict set-aside failed: %s', exc)+ return status+ if status['restored'] or conflicts:+ logger.info(+ 'draft: restored %d page(s), set aside %d',+ len(status['restored']), len(conflicts),+ )+ _persist_draft()+ return status++ # Idle timeout: auto-shutdown if no one connects within idle_timeout seconds.+ # Monotonic time keeps a wall-clock jump (resume from sleep, NTP step) from+ # counting as idleness on platforms whose monotonic clock pauses in suspend.+ app.config['LAST_REQUEST_TIME'] = time.monotonic()@app.before_requestdef _update_activity():@@ -471,7 +647,7 @@ def create_app(origin_host = Noneif origin_host not in allowed_hosts:return jsonify({'error': 'Forbidden Origin header'}), 403- app.config['LAST_REQUEST_TIME'] = time.time()+ app.config['LAST_REQUEST_TIME'] = time.monotonic()def _exit_with_lock_release(code: int = 0) -> None:lf = app.config.get('LOCK_FILE')@@ -486,11 +662,12 @@ def create_app(returnwhile True:time.sleep(10)- elapsed = time.time() - app.config['LAST_REQUEST_TIME']+ elapsed = time.monotonic() - app.config['LAST_REQUEST_TIME']if elapsed > idle_timeout: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.+ # Flask dev server has no clean shutdown. Every acknowledged+ # staging change is already mirrored to draft.json, so the next+ # start restores it._exit_with_lock_release(0)watchdog = threading.Thread(target=_idle_watchdog, daemon=True)@@ -504,7 +681,8 @@ def create_app(def _stop():time.sleep(0.5) # Let HTTP response flush before killing the processlogger.info('shutting down (%s)', reason)- # os._exit: save-all already wrote to disk; 0.5s delay ensures response is sent.+ # os._exit: unapplied work stays in draft.json for the next start;+ # the 0.5s delay ensures the response is sent._exit_with_lock_release(0)threading.Thread(target=_stop, daemon=True).start()return jsonify({'status': 'ok'})@@ -515,8 +693,16 @@ def create_app(@app.route('/api/config')def get_config():+ with state_lock:+ pending = {+ name: {'annotations': 'annotations' in entry, 'edits': len(entry.get('edits') or [])}+ for name, entry in _draft_pages().items()+ }+ # The startup restore report is shown once, not on every reload.+ startup = app.config.pop('DRAFT_STARTUP', None)return jsonify({'live': app.config['LIVE_MODE'],+ 'draft': {'pending': pending, 'startup': startup},})@app.route('/api/health')@@ -642,6 +828,7 @@ def create_app(item['element_id']: item['annotation']for item in parse_annotations(root)}+ _note_base(name, svg_file, annotations[name])return annotations[name], None@app.route('/api/slide/<name>')@@ -659,7 +846,11 @@ def create_app(logger.warning('stat failed: %s: %s', path_str, exc)return jsonify({'error': f'Failed to stat SVG: {exc}'}), 500- pending_edits = app.config['PENDING_EDITS'].get(name) or []+ with state_lock:+ pending_edits = [dict(r) for r in app.config['PENDING_EDITS'].get(name) or []]+ staged_annotations = app.config['ANNOTATIONS'].get(name)+ if staged_annotations is not None:+ staged_annotations = dict(staged_annotations)cached = None if pending_edits else _cache_get(_SLIDE_CACHE, _SLIDE_CACHE_LOCK, path_str, mtime,)@@ -706,8 +897,8 @@ def create_app((content, warnings, disk_annotations, id_to_tag),)- if name in app.config['ANNOTATIONS']:- merged = dict(app.config['ANNOTATIONS'][name])+ if staged_annotations is not None:+ merged = staged_annotationselse:merged = {ann['element_id']: ann['annotation']@@ -733,6 +924,7 @@ def create_app(})@app.route('/api/slide/<name>/annotate', methods=['POST'])+ @_with_state_lockdef post_annotate(name: str):data = request.get_json()if not data or 'element_id' not in data or 'annotation' not in data:@@ -759,9 +951,11 @@ def create_app(return jsonify({'status': 'ok','annotations_count': len(annotations),+ 'draft_saved': _persist_draft(),})@app.route('/api/slide/<name>/annotate/<element_id>', methods=['DELETE'])+ @_with_state_lockdef delete_annotate(name: str, element_id: str):annotations, error = _get_annotation_snapshot(name)if error is not None:@@ -772,9 +966,11 @@ def create_app(return jsonify({'status': 'ok','annotations_count': len(annotations),+ 'draft_saved': _persist_draft(),})@app.route('/api/slide/<name>/edit', methods=['POST'])+ @_with_state_lockdef post_edit(name: str):"""Stage a direct (AI-free) edit to one element.@@ -885,6 +1081,7 @@ def create_app(staged['promote_tspan'] = promotestaged['changes'] = changes+ _note_base(name, svg_file)pending = app.config['PENDING_EDITS'].setdefault(name, [])# Coalesce a run of edits to the same element+fields into one undo step# so repeated nudges/color tries don't pile up replay work or log noise.@@ -892,9 +1089,14 @@ def create_app(_coalesce_into(pending[-1], staged)else:pending.append(staged)- return jsonify({'status': 'ok', 'undo_depth': len(pending)})+ return jsonify({+ 'status': 'ok',+ 'undo_depth': len(pending),+ 'draft_saved': _persist_draft(),+ })@app.route('/api/slide/<name>/undo', methods=['POST'])+ @_with_state_lockdef post_undo(name: str):"""Drop the most recent staged direct edit on this slide (LIFO)."""svg_file = _safe_svg_path(name)@@ -907,9 +1109,14 @@ def create_app(if not stack:return jsonify({'status': 'empty', 'undo_depth': 0})stack.pop()- return jsonify({'status': 'ok', 'undo_depth': len(stack)})+ return jsonify({+ 'status': 'ok',+ 'undo_depth': len(stack),+ 'draft_saved': _persist_draft(),+ })@app.route('/api/save-all', methods=['POST'])+ @_with_state_lockdef save_all():annotations = app.config['ANNOTATIONS']pending_edits = app.config['PENDING_EDITS']@@ -961,8 +1168,18 @@ def create_app(elem.attrib.pop('data-edit-target', None)elem.attrib.pop('data-edit-annotation', None)- for element_id, annotation_text in anns.items():- set_annotation(root, element_id, annotation_text)+ missing = [+ element_id+ for element_id, annotation_text in anns.items()+ if not set_annotation(root, element_id, annotation_text)+ ]+ if missing:+ # Keep the page staged (and in the draft) instead of dropping+ # annotations whose target element no longer exists.+ failures.append(+ f'{filename}: Annotation target not found: {", ".join(missing)}'+ )+ continue# Strip transient _edit_N ids from elements that are NOT user-annotated.# Only annotated elements need to keep their id so the AI can locate them@@ -971,7 +1188,9 @@ def create_app(strip_unused_temp_ids(root, annotated_ids)try:- tree.write(str(svg_file), encoding='UTF-8', xml_declaration=True)+ _atomic_replace(svg_file, lambda tmp: tree.write(+ str(tmp), encoding='UTF-8', xml_declaration=True,+ ))except OSError as exc:failures.append(f'{filename}: Failed to write SVG: {exc}')continue@@ -1001,14 +1220,20 @@ def create_app(modified.append(filename)annotations.pop(filename, None)pending_edits.pop(filename, None)+ app.config['DRAFT_BASES'].pop(filename, None)+ draft_saved = _persist_draft()if failures:return jsonify({'error': 'Failed to save: ' + '; '.join(failures),'files_modified': modified,+ 'draft_saved': draft_saved,}), 500- return jsonify({'status': 'ok', 'files_modified': modified})+ return jsonify({'status': 'ok', 'files_modified': modified, 'draft_saved': draft_saved})++ # Route helpers above (_safe_svg_path) must exist before the restore runs.+ app.config['DRAFT_STARTUP'] = _restore_draft()return app@@ -1021,6 +1246,10 @@ def _lock_file(project_path: Path) -> Path:return _runtime_dir(project_path) / LOCK_FILE_NAME+def _draft_file(project_path: Path) -> Path:+ return _runtime_dir(project_path) / DRAFT_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_NAMEdiff --git a/skills/ppt-master/scripts/svg_editor/static/app.js b/skills/ppt-master/scripts/svg_editor/static/app.jsindex a2038313..bda82289 100644--- a/skills/ppt-master/scripts/svg_editor/static/app.js+++ b/skills/ppt-master/scripts/svg_editor/static/app.js@@ -70,7 +70,12 @@modal_success_direct_only: "Changes saved to svg_output.\n\nDirect edits are now in the SVG source. Return to the chat and ask to re-export when you want a refreshed PPTX. The preview service is still running.",modal_success_annotations_only: "Annotations saved to svg_output.\n\nReturn to the chat and ask to apply annotations when you want AI to interpret them. The preview service is still running.",modal_success_mixed: "Direct edits and annotations saved to svg_output.\n\nReturn to the chat to apply AI-needed annotations, then re-export the PPTX when ready. The preview service is still running.",- modal_confirm_exit: "Exit preview and stop the local server?\n\nUnapplied edits and annotations will be discarded.",+ modal_confirm_exit: "Exit preview and stop the local server?\n\nUnapplied edits and annotations are kept as a draft and restored the next time the preview opens.",+ modal_nothing_applied: "The server had no pending changes, so nothing was written. It may have restarted since these changes were made; re-check the edits and annotations on each slide.",+ warn_draft_unsaved: "Could not save the draft to disk. This change is staged in memory only and is lost if the server stops before Apply changes.",+ notice_draft_restored: "Restored the unapplied draft for {count} slide(s): {pages}. Click Apply changes when ready.",+ warn_draft_conflict: "{pages} changed on disk after the draft was saved, so that draft was not restored. It is kept in live_preview/{file}.",+ warn_draft_unreadable: "The draft file could not be read. It is kept as live_preview/{file}.",modal_success_exit: "Preview stopped.\n\nYou can close this tab and return to the chat.",modal_stopping: "Stopping preview server...",lang_toggle_title: "Switch language",@@ -144,7 +149,12 @@modal_success_direct_only: "変更を svg_output に保存しました。\n\n直接編集はSVGソースに反映済みです。PPTXを更新したいときは、チャットに戻って再エクスポートを依頼してください。プレビューサーバーは引き続き動作しています。",modal_success_annotations_only: "コメントを svg_output に保存しました。\n\nAIにコメントを解釈・反映させたいときは、チャットに戻ってコメントの適用を依頼してください。プレビューサーバーは引き続き動作しています。",modal_success_mixed: "直接編集とコメントを svg_output に保存しました。\n\nチャットに戻ってAIの判断が必要なコメントの適用を先に依頼し、確認できたらPPTXを再エクスポートしてください。プレビューサーバーは引き続き動作しています。",- modal_confirm_exit: "プレビューを終了してローカルサーバーを停止しますか?\n\n未適用の編集とコメントは破棄されます。",+ modal_confirm_exit: "プレビューを終了してローカルサーバーを停止しますか?\n\n未適用の編集とコメントは下書きとして保持され、次にプレビューを開いたときに復元されます。",+ modal_nothing_applied: "サーバーに未適用の変更がなかったため、何も書き込まれませんでした。変更後にサーバーが再起動した可能性があります。各スライドの編集とコメントを確認してください。",+ warn_draft_unsaved: "下書きをディスクに保存できませんでした。この変更はメモリ上にのみあり、「変更を適用」の前にサーバーが停止すると失われます。",+ notice_draft_restored: "{count} 枚のスライドの未適用の下書きを復元しました:{pages}。準備ができたら「変更を適用」をクリックしてください。",+ warn_draft_conflict: "{pages} は下書きの保存後にディスク上で変更されたため、その下書きは復元されませんでした。live_preview/{file} に保持されています。",+ warn_draft_unreadable: "下書きファイルを読み込めませんでした。live_preview/{file} として保持されています。",modal_success_exit: "プレビューを停止しました。\n\nこのタブを閉じてチャットに戻れます。",modal_stopping: "プレビューサーバーを停止しています…",lang_toggle_title: "言語を切り替え",@@ -218,7 +228,12 @@modal_success_direct_only: "修改已保存到 svg_output。\n\n直接修改已经写入 SVG 源文件;需要刷新 PPTX 时,请回到对话窗口要求重新导出。预览服务仍在运行。",modal_success_annotations_only: "标注已保存到 svg_output。\n\n需要 AI 理解并执行这些标注时,请回到对话窗口要求应用标注。预览服务仍在运行。",modal_success_mixed: "直接修改和标注已保存到 svg_output。\n\n请回到对话窗口先应用需要 AI 判断的标注,确认后再重新导出 PPTX。预览服务仍在运行。",- modal_confirm_exit: "退出预览并停止本地服务?\n\n未应用的修改和标注将被丢弃。",+ modal_confirm_exit: "退出预览并停止本地服务?\n\n未应用的修改和标注会保留为草稿,下次打开预览时自动恢复。",+ modal_nothing_applied: "服务器上没有待应用的修改,本次没有写入任何文件。服务可能在这些修改之后重启过,请逐页检查修改和标注。",+ warn_draft_unsaved: "草稿未能写入磁盘。这次修改只暂存在内存里,点击“应用修改”前服务停止就会丢失。",+ notice_draft_restored: "已恢复 {count} 页未应用的草稿:{pages}。确认后点击“应用修改”。",+ warn_draft_conflict: "{pages} 在草稿保存后已在磁盘上变动,这部分草稿未恢复,已保留在 live_preview/{file}。",+ warn_draft_unreadable: "草稿文件无法读取,已保留为 live_preview/{file}。",modal_success_exit: "预览已停止。\n\n可以关闭本标签页并回到对话窗口。",modal_stopping: "正在停止预览服务……",lang_toggle_title: "切换语言",@@ -292,7 +307,12 @@modal_success_direct_only: "修改已儲存到 svg_output。\n\n直接修改已經寫入 SVG 原始檔;需要更新 PPTX 時,請回到對話視窗要求重新匯出。預覽服務仍在執行。",modal_success_annotations_only: "標註已儲存到 svg_output。\n\n需要 AI 理解並執行這些標註時,請回到對話視窗要求套用標註。預覽服務仍在執行。",modal_success_mixed: "直接修改和標註已儲存到 svg_output。\n\n請回到對話視窗先套用需要 AI 判斷的標註,確認後再重新匯出 PPTX。預覽服務仍在執行。",- modal_confirm_exit: "結束預覽並停止本機服務?\n\n未套用的修改和標註將被捨棄。",+ modal_confirm_exit: "結束預覽並停止本機服務?\n\n未套用的修改和標註會保留為草稿,下次開啟預覽時自動恢復。",+ modal_nothing_applied: "伺服器上沒有待套用的修改,本次沒有寫入任何檔案。服務可能在這些修改之後重新啟動過,請逐頁檢查修改和標註。",+ warn_draft_unsaved: "草稿未能寫入磁碟。這次修改只暫存在記憶體中,點選「套用修改」前服務停止就會遺失。",+ notice_draft_restored: "已恢復 {count} 頁未套用的草稿:{pages}。確認後點選「套用修改」。",+ warn_draft_conflict: "{pages} 在草稿儲存後已在磁碟上變動,這部分草稿未恢復,已保留在 live_preview/{file}。",+ warn_draft_unreadable: "草稿檔案無法讀取,已保留為 live_preview/{file}。",modal_success_exit: "預覽已停止。\n\n可以關閉本分頁並回到對話視窗。",modal_stopping: "正在停止預覽服務……",lang_toggle_title: "切換語言",@@ -514,9 +534,9 @@});}- // Staged edits live in server memory until "Apply changes"; the server can- // still idle-timeout or be killed and drop them. Warn before the tab leaves- // so the user remembers to apply (browsers show their own generic prompt).+ // Staged edits stay unapplied until "Apply changes" (the server mirrors them+ // to live_preview/draft.json). Warn before the tab leaves so the user+ // remembers to apply (browsers show their own generic prompt).function hasUnsavedWork() {if (annotationsDirty) return true;return Object.keys(editStackCount).some(function (k) {@@ -1658,7 +1678,7 @@fetch("/api/slide/" + encodeURIComponent(currentSlide) + "/annotate/" + encodeURIComponent(elementId), {method: "DELETE"})- .then(function (res) { return res.json(); })+ .then(jsonOrThrow).then(function () {delete slideAnnotations[elementId];markAnnotationChanged(currentSlide);@@ -1801,7 +1821,11 @@if (data.error) {modalMessage.textContent = t("err_save") + data.error;} else {- if (hadDirectEdits && hadAnnotationChanges) {+ var nothingApplied = (hadDirectEdits || hadAnnotationChanges) &&+ !(data.files_modified || []).length;+ if (nothingApplied) {+ modalMessage.textContent = t("modal_nothing_applied");+ } else if (hadDirectEdits && hadAnnotationChanges) {modalMessage.textContent = t("modal_success_mixed");} else if (hadDirectEdits) {modalMessage.textContent = t("modal_success_direct_only");@@ -1955,15 +1979,49 @@if (!res.ok || data.error) {throw new Error(data.error || ("Request failed with status " + res.status));}+ if (data.draft_saved === false) showWarning(t("warn_draft_unsaved"));return data;});}+ // Mirror the server's unapplied state (including a draft restored at+ // startup) into the pending-state trackers, so Apply changes, the pending+ // strip and the leave guard see it after a reload or server restart.+ function applyDraftStatus(draft) {+ if (!draft) return;+ var pending = draft.pending || {};+ Object.keys(pending).forEach(function (name) {+ if (pending[name].annotations) {+ annotationEditSlides[name] = true;+ annotationsDirty = true;+ }+ editStackCount[name] = pending[name].edits || 0;+ });+ updatePendingStatus();+ var startup = draft.startup;+ if (!startup) return;+ var names = Object.keys(startup.restored || {}).sort();+ var messages = [];+ if (names.length) {+ messages.push(t("notice_draft_restored", { count: names.length, pages: names.join(", ") }));+ }+ if (startup.unreadable && startup.conflict_file) {+ messages.push(t("warn_draft_unreadable", { file: startup.conflict_file }));+ } else if ((startup.conflicts || []).length && startup.conflict_file) {+ messages.push(t("warn_draft_conflict", {+ pages: startup.conflicts.join(", "),+ file: startup.conflict_file,+ }));+ }+ if (messages.length) showWarning(messages.join(" "));+ }+function loadConfig() {return fetch("/api/config").then(function (res) { return res.json(); }).then(function (data) {liveMode = !!data.live;+ applyDraftStatus(data.draft);}).catch(function () {liveMode = false;diff --git a/skills/ppt-master/scripts/tests/test_svg_editor_server.py b/skills/ppt-master/scripts/tests/test_svg_editor_server.pyindex 45b86486..bfe784b4 100644--- a/skills/ppt-master/scripts/tests/test_svg_editor_server.py+++ b/skills/ppt-master/scripts/tests/test_svg_editor_server.py@@ -65,3 +65,120 @@ class SlideListCacheTests(unittest.TestCase):if __name__ == '__main__':unittest.main()+++SLIDE_SVG = (+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">'+ '<rect id="box" x="0" y="0" width="10" height="10" fill="#000000"/>'+ '</svg>'+)+++class StagingDraftTests(unittest.TestCase):+ """Unapplied staged work survives a server restart (issue #319)."""++ def setUp(self) -> None:+ self.temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self.temporary.cleanup)+ self.root = Path(self.temporary.name)+ svg_dir = self.root / 'svg_output'+ svg_dir.mkdir()+ self.svg_path = svg_dir / '01.svg'+ self.svg_path.write_text(SLIDE_SVG, encoding='utf-8')+ self.draft = self.root / 'live_preview' / 'draft.json'+ for cache in (server._LIST_CACHE, server._SLIDE_CACHE):+ cache_patch = patch.dict(cache, clear=True)+ cache_patch.start()+ self.addCleanup(cache_patch.stop)++ def _client(self):+ with patch.object(server.threading.Thread, 'start'):+ app = server.create_app(str(self.root), idle_timeout=0)+ app.config['TESTING'] = True+ return app.test_client()++ def _stage(self, client) -> None:+ response = client.post('/api/slide/01.svg/annotate', json={+ 'element_id': 'box', 'annotation': 'make it blue',+ })+ self.assertIs(response.get_json()['draft_saved'], True)+ response = client.post('/api/slide/01.svg/edit', json={+ 'element_id': 'box', 'attrs': {'fill': '#ff0000'},+ })+ self.assertIs(response.get_json()['draft_saved'], True)++ def test_restart_restores_staged_annotation_and_edit(self) -> None:+ self._stage(self._client())+ self.assertTrue(self.draft.exists())+ self.assertEqual(self.svg_path.read_text(encoding='utf-8'), SLIDE_SVG)++ client = self._client()+ draft = client.get('/api/config').get_json()['draft']+ restored = {'01.svg': {'annotations': True, 'edits': 1}}+ self.assertEqual(draft['startup']['restored'], restored)+ self.assertEqual(draft['pending'], restored)+ again = client.get('/api/config').get_json()['draft']+ self.assertEqual(again, {'pending': restored, 'startup': None})+ slide = client.get('/api/slide/01.svg').get_json()+ self.assertEqual(slide['undo_depth'], 1)+ self.assertEqual(+ slide['annotations'],+ [{'element_id': 'box', 'tag': 'rect', 'annotation': 'make it blue'}],+ )+ self.assertIn('#ff0000', slide['content'])++ saved = client.post('/api/save-all').get_json()+ self.assertEqual(saved['files_modified'], ['01.svg'])+ self.assertFalse(self.draft.exists())+ self.assertEqual(client.get('/api/config').get_json()['draft']['pending'], {})+ on_disk = self.svg_path.read_text(encoding='utf-8')+ self.assertIn('data-edit-annotation="make it blue"', on_disk)+ self.assertIn('#ff0000', on_disk)++ def test_changed_svg_sets_draft_aside_instead_of_replaying(self) -> None:+ self._stage(self._client())+ self.svg_path.write_text(SLIDE_SVG.replace('width="10"', 'width="20"'), encoding='utf-8')++ client = self._client()+ draft = client.get('/api/config').get_json()['draft']['startup']+ self.assertEqual(draft['restored'], {})+ self.assertEqual(draft['conflicts'], ['01.svg'])+ aside = self.draft.with_name(draft['conflict_file'])+ self.assertIn('make it blue', aside.read_text(encoding='utf-8'))+ self.assertFalse(self.draft.exists())+ self.assertEqual(client.get('/api/slide/01.svg').get_json()['undo_depth'], 0)++ def test_unreadable_draft_is_set_aside(self) -> None:+ self.draft.parent.mkdir()+ self.draft.write_text('{not json', encoding='utf-8')+ draft = self._client().get('/api/config').get_json()['draft']['startup']+ self.assertIs(draft['unreadable'], True)+ self.assertFalse(self.draft.exists())+ aside = self.draft.with_name(draft['conflict_file'])+ self.assertEqual(aside.read_text(encoding='utf-8'), '{not json')++ def test_reverting_all_staged_work_removes_draft(self) -> None:+ client = self._client()+ self._stage(client)+ client.delete('/api/slide/01.svg/annotate/box')+ response = client.post('/api/slide/01.svg/undo').get_json()+ self.assertIs(response['draft_saved'], True)+ self.assertFalse(self.draft.exists())++ def test_missing_annotation_target_keeps_page_staged(self) -> None:+ client = self._client()+ client.post('/api/slide/01.svg/annotate', json={+ 'element_id': 'gone', 'annotation': 'fix this',+ })+ response = client.post('/api/save-all')+ self.assertEqual(response.status_code, 500)+ body = response.get_json()+ self.assertIn('Annotation target not found: gone', body['error'])+ self.assertEqual(body['files_modified'], [])+ self.assertEqual(self.svg_path.read_text(encoding='utf-8'), SLIDE_SVG)+ self.assertIn('fix this', self.draft.read_text(encoding='utf-8'))++ def test_save_with_nothing_staged_writes_nothing(self) -> None:+ body = self._client().post('/api/save-all').get_json()+ self.assertEqual(body, {'status': 'ok', 'files_modified': [], 'draft_saved': True})+ self.assertFalse(self.draft.exists())