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: template install is staged with rollback and a machine receipt; Confirm UI freezes selected-root snapshots, accepts several explicit roots, and verifies the installation before handoff; structured export keeps custom placeholder faces and re-skins master backgrounds from public pages; template preview compiles typed chart/table slots natively

hugohe36de7939956d4
diff --git a/skills/ppt-master/scripts/apply_template.py b/skills/ppt-master/scripts/apply_template.py
index f15a1ab4..315c1eda 100644
--- a/skills/ppt-master/scripts/apply_template.py
+++ b/skills/ppt-master/scripts/apply_template.py
@@ -22,10 +22,13 @@ from __future__ import annotations
import argparse
import filecmp
+import hashlib
import json
+import os
import shutil
import subprocess
import sys
+import tempfile
from dataclasses import dataclass, field
from pathlib import Path
@@ -51,12 +54,13 @@ CHECKER = SCRIPT_DIR / "svg_quality_checker.py"
KINDS = ("brand", "style", "layout", "deck")
STRUCTURAL_KINDS = ("layout", "deck")
ASSET_DIRS = ("images", "icons")
+INSTALL_RECEIPT_NAME = "template_install.json"
BITMAP_SUFFIXES = {
".bmp", ".gif", ".jpeg", ".jpg", ".png", ".tif", ".tiff", ".webp",
}
-class ApplyTemplateError(Exception):
+class ApplyTemplateError(ValueError):
"""A contract violation that blocks installation."""
@@ -109,6 +113,8 @@ class InstallPlan:
owner_kind: str | None
mappings: list[Mapping] = field(default_factory=list)
removals: list[Path] = field(default_factory=list)
+ root_snapshots: list[dict] = field(default_factory=list)
+ selection_sha256: str | None = None
@property
def installed_specs(self) -> list[str]:
@@ -378,17 +384,202 @@ def _preflight(plan: InstallPlan) -> None:
# ---------------------------------------------------------------------------
-def _write(plan: InstallPlan) -> None:
- for path in plan.removals:
- path.unlink()
- for mapping in plan.mappings:
- if mapping.status == "identical":
+def _file_sha256(path: Path) -> str:
+ with path.open("rb") as stream:
+ digest = hashlib.sha256()
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def _workspace_files(root: Path) -> dict[str, str]:
+ return {
+ path.relative_to(root).as_posix(): _file_sha256(path)
+ for name in ("templates", *ASSET_DIRS)
+ for path in _iter_files(root / name)
+ }
+
+
+def _root_snapshots(roots: list[RootRecord]) -> list[dict]:
+ return [{
+ "workspace_root": str(record.root),
+ "source": record.source,
+ "kinds": sorted(record.kinds),
+ "specs": [{
+ "kind": spec.kind,
+ "id": spec.template_id,
+ "path": spec.path.relative_to(record.root).as_posix(),
+ } for spec in sorted(record.specs, key=lambda spec: spec.kind)],
+ "files": _workspace_files(record.root),
+ } for record in sorted(roots, key=lambda record: str(record.root))]
+
+
+def snapshot_template_roots(project: Path, root_args: list[str]) -> list[dict]:
+ """Freeze the selected roots, kinds, spec identities, and portable file bytes."""
+ roots = [_load_root(arg, project) for arg in root_args]
+ return _root_snapshots(roots)
+
+
+def _install_contract(snapshots: list[dict]) -> tuple[list[str], dict | None, set[str]]:
+ specs = sorted(
+ f"design_spec.{spec['kind']}.{spec['id']}.md"
+ for root in snapshots for spec in root["specs"]
+ )
+ paths = {f"templates/{name}" for name in specs}
+ for root in snapshots:
+ paths.update(name for name in root["files"] if name.startswith(("images/", "icons/")))
+ owner = next((root for root in snapshots if "layout" in root["kinds"]), None)
+ owner_kind = "layout"
+ if owner is None:
+ owner = next((root for root in snapshots if "deck" in root["kinds"]), None)
+ owner_kind = "deck"
+ roster = None
+ if owner is not None:
+ structural = sorted(
+ name for name in owner["files"]
+ if name.startswith("templates/")
+ and not _is_spec_file(Path(name))
+ and Path(name).suffix.lower() not in BITMAP_SUFFIXES
+ )
+ paths.update(structural)
+ roster = {"workspace_root": owner["workspace_root"], "kind": owner_kind, "files": structural}
+ return specs, roster, paths
+
+
+def read_template_install(
+ project: Path,
+ snapshots: list[dict],
+ selection_sha256: str | None,
+ *,
+ content_root: Path | None = None,
+) -> dict:
+ """Verify installer provenance and every installed spec, roster file, and asset.
+
+ Extra project images/icons are allowed; selected assets and the exact active
+ template roster must still match. ``content_root`` validates staging before
+ publication using the same checks as Confirm UI handoff.
+ """
+ content_root = content_root or project
+ receipt_path = content_root / INSTALL_RECEIPT_NAME
+ try:
+ receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
+ except (OSError, ValueError) as exc:
+ raise ApplyTemplateError(f"Cannot read {receipt_path}; run apply_template.py: {exc}") from exc
+ if not isinstance(receipt, dict) or receipt.get("schema_version") != 1:
+ raise ApplyTemplateError(f"Invalid {INSTALL_RECEIPT_NAME}; rerun apply_template.py")
+ if (receipt.get("project") != str(project.resolve())
+ or receipt.get("roots") != snapshots
+ or receipt.get("selection_sha256") != selection_sha256):
+ raise ApplyTemplateError("Template installation does not match the confirmed roots/snapshot")
+ specs, roster, expected_paths = _install_contract(snapshots)
+ files = receipt.get("files")
+ if (receipt.get("installed_specs") != specs or receipt.get("active_roster") != roster
+ or not isinstance(files, dict) or set(files) != expected_paths):
+ raise ApplyTemplateError("Template installation spec/roster/asset receipt is incomplete")
+ actual_specs = sorted(path.name for path in (content_root / "templates").glob("design_spec*.md"))
+ actual_roster = {
+ path.relative_to(content_root).as_posix()
+ for path in _iter_files(content_root / "templates")
+ if not _is_spec_file(path) and path.suffix.lower() not in BITMAP_SUFFIXES
+ }
+ if actual_specs != specs or actual_roster != set(roster["files"] if roster else []):
+ raise ApplyTemplateError("Installed template specs or active roster differ from the selection")
+ for name, digest in files.items():
+ path = content_root / name
+ if not path.is_file() or _file_sha256(path) != digest:
+ raise ApplyTemplateError(f"Installed template file changed or is missing: {name}")
+ return receipt
+
+
+def validate_template_snapshot_sources(
+ project: Path, snapshots: list[dict], selection_sha256: str,
+) -> None:
+ """Reject source drift, allowing only an installer-proven in-place change."""
+ for root in snapshots:
+ path = Path(root["workspace_root"])
+ if _workspace_files(path) == root["files"]:
continue
- mapping.dst.parent.mkdir(parents=True, exist_ok=True)
- if mapping.content is not None:
- mapping.dst.write_bytes(mapping.content)
+ if path == project.resolve():
+ read_template_install(project, snapshots, selection_sha256)
else:
- shutil.copy2(mapping.src, mapping.dst)
+ raise ApplyTemplateError(f"Confirmed template source changed: {path}; confirm Stage 1 again")
+
+
+def _write(plan: InstallPlan) -> None:
+ """Stage and verify the full install, then publish with rollback on failure.
+
+ Directory renames are atomic individually. The journal restores all earlier
+ renames if any publication fails, including removed Deck files and the old
+ receipt. Backups survive if rollback itself fails so recovery remains possible.
+ """
+ transaction = Path(tempfile.mkdtemp(prefix=".template-install-", dir=plan.project))
+ staged = transaction / "staged"
+ backup = transaction / "backup"
+ moved: list[str] = []
+ published: list[str] = []
+ cleanup = True
+ try:
+ staged.mkdir()
+ backup.mkdir()
+ names = ["templates", *ASSET_DIRS]
+ for name in names:
+ current = plan.project / name
+ if current.exists():
+ shutil.copytree(current, staged / name)
+ for path in plan.removals:
+ (staged / path.relative_to(plan.project)).unlink()
+ for mapping in plan.mappings:
+ destination = staged / mapping.dst.relative_to(plan.project)
+ if mapping.status != "identical":
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ if mapping.content is not None:
+ destination.write_bytes(mapping.content)
+ else:
+ shutil.copy2(mapping.src, destination)
+ expected = (
+ hashlib.sha256(mapping.content).hexdigest()
+ if mapping.content is not None else _file_sha256(mapping.src)
+ )
+ if _file_sha256(destination) != expected:
+ raise ApplyTemplateError(f"Staged file does not match its source: {mapping.dst}")
+ if _root_snapshots(plan.roots) != plan.root_snapshots:
+ raise ApplyTemplateError("Template source changed during staging; retry the installation")
+ specs, roster, paths = _install_contract(plan.root_snapshots)
+ receipt = {
+ "schema_version": 1,
+ "project": str(plan.project),
+ "selection_sha256": plan.selection_sha256,
+ "roots": plan.root_snapshots,
+ "installed_specs": specs,
+ "active_roster": roster,
+ "files": {name: _file_sha256(staged / name) for name in sorted(paths)},
+ }
+ (staged / INSTALL_RECEIPT_NAME).write_text(
+ json.dumps(receipt, ensure_ascii=False, indent=2) + "\n", encoding="utf-8",
+ )
+ read_template_install(plan.project, plan.root_snapshots, plan.selection_sha256, content_root=staged)
+ for name in [*names, INSTALL_RECEIPT_NAME]:
+ if not (staged / name).exists():
+ continue
+ current = plan.project / name
+ if current.exists():
+ os.replace(current, backup / name)
+ moved.append(name)
+ os.replace(staged / name, current)
+ published.append(name)
+ except BaseException:
+ try:
+ for name in reversed(published):
+ os.replace(plan.project / name, staged / name)
+ for name in reversed(moved):
+ os.replace(backup / name, plan.project / name)
+ except OSError as exc:
+ cleanup = False
+ raise ApplyTemplateError(f"Installation rollback failed; recover backups in {transaction}: {exc}") from exc
+ raise
+ finally:
+ if cleanup:
+ shutil.rmtree(transaction)
def _receipt(plan: InstallPlan) -> str:
@@ -439,6 +630,13 @@ def apply_templates(
for record in roots:
_validate_root(record)
plan = _plan(project, roots)
+ plan.root_snapshots = _root_snapshots(roots)
+ selection_file = project / "confirm_ui" / "template_selection.json"
+ if selection_file.is_file():
+ selection = json.loads(selection_file.read_text(encoding="utf-8"))
+ if selection.get("mode") != "templates" or selection.get("root_snapshots") != plan.root_snapshots:
+ raise ApplyTemplateError("Selected roots or source bytes differ from the Stage-1 confirmation")
+ plan.selection_sha256 = selection["selection_sha256"]
_preflight(plan)
if not dry_run:
_write(plan)
@@ -479,7 +677,7 @@ def main(argv: list[str] | None = None) -> int:
dry_run=args.dry_run,
validate=not args.skip_validation,
)
- except ApplyTemplateError as exc:
+ except (OSError, ValueError) as exc:
print(f"[ERROR] {exc}", file=sys.stderr)
return 1
verb = "would install" if args.dry_run else "installed"
@@ -494,6 +692,8 @@ def main(argv: list[str] | None = None) -> int:
copied = len(plan.mappings) - same
note = f", {same} already present" if same else ""
print(f"[OK] {verb} {copied} file(s) into {plan.project}{note}")
+ if not args.dry_run:
+ print(f"[receipt] {plan.project / INSTALL_RECEIPT_NAME}")
print(_receipt(plan))
return 0
diff --git a/skills/ppt-master/scripts/confirm_ui/server.py b/skills/ppt-master/scripts/confirm_ui/server.py
index 11c851b4..0cf36d35 100644
--- a/skills/ppt-master/scripts/confirm_ui/server.py
+++ b/skills/ppt-master/scripts/confirm_ui/server.py
@@ -447,12 +447,15 @@ def _build_template_library() -> tuple[dict, dict[str, dict], dict[str, dict], d
return library, candidates, registered_roots, index_contracts
-def _build_template_options(confirm_dir: Path) -> tuple[dict, dict[str, dict]]:
+def _build_template_options(
+ confirm_dir: Path, root_snapshots: list[dict] | None = None,
+) -> tuple[dict, dict[str, dict]]:
"""Return the browser contract and its server-owned candidate whitelist."""
source, explicit_roots = _read_template_options_input(confirm_dir)
library, candidates, registered_roots, index_contracts = _build_template_library()
explicit = []
suggested_keys = []
+ snapshots = {item['workspace_root']: item for item in root_snapshots or []}
for root in explicit_roots:
canonical_root = str(root)
registered = registered_roots.get(canonical_root)
@@ -460,7 +463,10 @@ def _build_template_options(confirm_dir: Path) -> tuple[dict, dict[str, dict]]:
suggested_keys.append(registered['key'])
continue
digest = hashlib.sha256(canonical_root.encode('utf-8')).hexdigest()
+ snapshot = snapshots.get(canonical_root)
root_specs = [
+ (root / spec['path'], spec['kind']) for spec in snapshot['specs']
+ ] if snapshot is not None else [
(spec, _template_kind_from_spec(spec))
for spec in _template_design_specs(root)
]
@@ -490,8 +496,7 @@ def _build_template_options(confirm_dir: Path) -> tuple[dict, dict[str, dict]]:
# One supplied exact root is an unambiguous convenience default, including
# a multi-kind root whose kinds compose rather than compete. Several roots
- # are candidates for the single-select controls, not an instruction to
- # select all of them.
+ # remain unselected candidates until the user chooses a combination.
preselected_keys = suggested_keys if len(explicit_roots) == 1 else []
response = {
@@ -534,12 +539,14 @@ def _template_selection_sha256(
mode: str,
selections: list[dict],
options_sha256: str,
+ root_snapshots: list[dict],
) -> str:
"""Bind one resolved choice to the candidate/options contract it used."""
return _json_sha256({
'mode': mode,
'selections': selections,
'options_sha256': options_sha256,
+ 'root_snapshots': root_snapshots,
})
@@ -554,6 +561,7 @@ def _validate_template_selection(data: dict) -> None:
'options_sha256',
'selection_sha256',
'confirmed_at',
+ 'root_snapshots',
}
if set(data) != expected_fields:
raise ValueError(f'{TEMPLATE_SELECTION_NAME} has invalid fields')
@@ -587,7 +595,6 @@ def _validate_template_selection(data: dict) -> None:
seen_root_kinds = set()
seen_kinds: set[str] = set()
- explicit_roots_seen: dict[str, set[str]] = {}
for index, selection in enumerate(selections):
if not isinstance(selection, dict):
raise ValueError(
@@ -632,20 +639,31 @@ def _validate_template_selection(data: dict) -> None:
f'{TEMPLATE_SELECTION_NAME} selections[{index}] '
'workspace_root must be a canonical absolute path'
)
- if source == 'explicit':
- # One explicit workspace root may contribute several kinds, so the
- # cap counts roots rather than selections.
- explicit_roots_seen.setdefault(workspace_root, set()).add(kind)
- if len(explicit_roots_seen) > 1:
- raise ValueError(
- 'template selection allows at most one explicit workspace'
- )
if (workspace_root, kind) in seen_root_kinds:
raise ValueError(
f'{TEMPLATE_SELECTION_NAME} contains duplicate workspace root '
f'for kind {kind!r}: {workspace_root}'
)
seen_root_kinds.add((workspace_root, kind))
+ snapshots = data.get('root_snapshots')
+ if not isinstance(snapshots, list):
+ raise ValueError(f'{TEMPLATE_SELECTION_NAME} requires root_snapshots; confirm Stage 1 again')
+ snapshot_selections = []
+ try:
+ for root in snapshots:
+ if sorted(spec['kind'] for spec in root['specs']) != root['kinds']:
+ raise ValueError('snapshot kinds do not match specs')
+ if not isinstance(root['files'], dict) or any(spec['path'] not in root['files'] for spec in root['specs']):
+ raise ValueError('snapshot is missing spec fingerprints')
+ for spec in root['specs']:
+ item = {'source': root['source'], 'kind': spec['kind'], 'workspace_root': root['workspace_root']}
+ if root['source'] == 'library':
+ item['id'] = spec['id']
+ snapshot_selections.append(item)
+ except (KeyError, TypeError) as exc:
+ raise ValueError(f'{TEMPLATE_SELECTION_NAME} has invalid root_snapshots') from exc
+ if sorted(map(_json_sha256, snapshot_selections)) != sorted(map(_json_sha256, selections)):
+ raise ValueError(f'{TEMPLATE_SELECTION_NAME} root_snapshots do not match selections')
if not isinstance(data.get('confirmed_at'), str) or not data['confirmed_at']:
raise ValueError(
f'{TEMPLATE_SELECTION_NAME} confirmed_at must be a non-empty string'
@@ -654,6 +672,7 @@ def _validate_template_selection(data: dict) -> None:
mode,
selections,
options_sha256,
+ snapshots,
)
if selection_sha256 != expected_selection_sha256:
raise ValueError(f'{TEMPLATE_SELECTION_NAME} selection_sha256 does not match')
@@ -686,7 +705,9 @@ def _validate_explicit_root_closure(
def _read_template_selection(selection_file: Path) -> dict:
- """Read a selection and revalidate it against current indexed options."""
+ """Check the frozen choice, source bytes, and still-current options/indexes."""
+ from apply_template import validate_template_snapshot_sources
+
data = _read_json_object(selection_file)
_validate_template_selection(data)
options_file = selection_file.parent / TEMPLATE_OPTIONS_NAME
@@ -695,7 +716,10 @@ def _read_template_selection(selection_file: Path) -> dict:
f'{TEMPLATE_SELECTION_NAME} must be confirmed after the current '
f'{TEMPLATE_OPTIONS_NAME}'
)
- options, candidates = _build_template_options(selection_file.parent)
+ validate_template_snapshot_sources(
+ selection_file.parent.parent, data['root_snapshots'], data['selection_sha256'],
+ )
+ options, candidates = _build_template_options(selection_file.parent, data['root_snapshots'])
if data['options_sha256'] != options['options_sha256']:
raise ValueError(
f'{TEMPLATE_SELECTION_NAME} options_sha256 no longer matches current options'
@@ -765,28 +789,10 @@ def _read_template_handoff(project_path: Path, handoff_file: Path) -> dict:
f'{TEMPLATE_HANDOFF_NAME} selection_sha256 does not match selection'
)
if data['mode'] == 'templates':
- if not _installed_template_specs(project_path):
- raise ValueError(
- f'{TEMPLATE_HANDOFF_NAME} requires at least one installed '
- f'template spec: {project_path / "templates"}/'
- 'design_spec.<kind>.<id>.md'
- )
- return data
-
+ from apply_template import read_template_install
-def _installed_template_specs(project_path: Path) -> list[Path]:
- """Return every template spec installed into the project by the apply stage.
-
- The apply stage installs one file per selected workspace, named
- ``design_spec.<kind>.<id>.md``. A bare ``design_spec.md`` under
- ``templates/`` means the project is itself a Create Template workspace and
- is deliberately excluded here.
- """
- return sorted(
- path
- for path in (project_path / 'templates').glob('design_spec.*.md')
- if path.is_file() and _TEMPLATE_SPEC_NAME_RE.fullmatch(path.name)
- )
+ read_template_install(project_path, selection['root_snapshots'], selection['selection_sha256'])
+ return data
def _complete_template_selection(project_path: Path) -> int:
@@ -810,12 +816,12 @@ def _complete_template_selection(project_path: Path) -> int:
)
return 1
if selection['mode'] == 'templates':
- if not _installed_template_specs(project_path):
- logger.error(
- 'cannot complete template selection before template apply '
- 'writes %s/design_spec.<kind>.<id>.md',
- project_path / 'templates',
- )
+ from apply_template import read_template_install
+
+ try:
+ read_template_install(project_path, selection['root_snapshots'], selection['selection_sha256'])
+ except (OSError, ValueError) as exc:
+ logger.error('cannot complete template selection: %s', exc)
return 1
handoff_file = confirm_dir / TEMPLATE_HANDOFF_NAME
@@ -939,6 +945,7 @@ def _resolve_template_confirmation(
payload: dict,
candidates: dict[str, dict],
options_sha256: str,
+ project_path: Path,
) -> dict:
"""Resolve browser keys against the current server-owned candidate set."""
required_fields = {'mode', 'selection_keys'}
@@ -974,10 +981,17 @@ def _resolve_template_confirmation(
item.get('id', ''),
item['workspace_root'],
))
+ from apply_template import snapshot_template_roots
+
+ _validate_explicit_root_closure(selections, candidates)
+ root_snapshots = snapshot_template_roots(
+ project_path, sorted({item['workspace_root'] for item in selections}),
+ )
selection_sha256 = _template_selection_sha256(
mode,
selections,
options_sha256,
+ root_snapshots,
)
receipt = {
'schema_version': TEMPLATE_SCHEMA_VERSION,
@@ -988,9 +1002,9 @@ def _resolve_template_confirmation(
'options_sha256': options_sha256,
'selection_sha256': selection_sha256,
'confirmed_at': time.strftime('%Y-%m-%dT%H:%M:%S'),
+ 'root_snapshots': root_snapshots,
}
_validate_template_selection(receipt)
- _validate_explicit_root_closure(selections, candidates)
return receipt
@@ -2812,6 +2826,7 @@ def create_app(
template_selection_payload,
template_candidates,
template_options['options_sha256'],
+ project_path,
)
except (OSError, json.JSONDecodeError, ValueError) as exc:
return jsonify({
diff --git a/skills/ppt-master/scripts/confirm_ui/static/app.js b/skills/ppt-master/scripts/confirm_ui/static/app.js
index 92d64da1..e1d531d1 100644
--- a/skills/ppt-master/scripts/confirm_ui/static/app.js
+++ b/skills/ppt-master/scripts/confirm_ui/static/app.js
@@ -38,7 +38,7 @@
sec_template_library: "Template combination",
template_library_hint: "Choose at most one workspace per kind. All four kinds can combine; Layout takes structural precedence over Deck.",
sec_template_explicit: "Specified templates",
- template_explicit_hint: "Choose at most one exact workspace supplied for this run; every kind it contains is applied. Its source path is shown for verification.",
+ template_explicit_hint: "Choose exact workspaces supplied for this run with non-overlapping kinds; every kind in each selected root is applied. Source paths are shown for verification.",
template_kind_brand: "Brand",
template_kind_style: "Style",
template_kind_layout: "Layout",
@@ -227,7 +227,7 @@
sec_template_library: "テンプレートの組み合わせ",
template_library_hint: "種類ごとにワークスペースを1件まで選択できます。4種類はすべて組み合わせ可能で、構造は Layout が Deck より優先されます。",
sec_template_explicit: "指定テンプレート",
- template_explicit_hint: "この実行で指定された正確なワークスペースを1件まで選択でき、そこに含まれる種別はすべて適用されます。確認用に参照元パスを表示します。",
+ template_explicit_hint: "この実行で指定されたワークスペースを、種別が重複しない範囲で複数選択できます。各ルートに含まれる全種別が適用され、確認用に参照元パスを表示します。",
template_kind_brand: "Brand",
template_kind_style: "Style",
template_kind_layout: "Layout",
@@ -416,7 +416,7 @@
sec_template_library: "模板组合",
template_library_hint: "每种模板最多选择一个工作区;四种模板均可组合,结构由 Layout 优先于 Deck。",
sec_template_explicit: "指定模板",
- template_explicit_hint: "本次运行明确提供的精确工作区最多选择一个,它包含的每一类都会被采用;显示来源路径供你核对。",
+ template_explicit_hint: "可选择本次运行提供的多个精确工作区,各根的模板类型不得重叠;选中的根会采用其全部类型,来源路径供你核对。",
template_kind_brand: "Brand",
template_kind_style: "Style",
template_kind_layout: "Layout",
@@ -605,7 +605,7 @@
sec_template_library: "範本組合",
template_library_hint: "每種範本最多選擇一個工作區;四種範本均可組合,結構由 Layout 優先於 Deck。",
sec_template_explicit: "指定範本",
- template_explicit_hint: "本次執行明確提供的精確工作區最多選擇一個,它包含的每一類都會被採用;顯示來源路徑供你核對。",
+ template_explicit_hint: "可選擇本次執行提供的多個精確工作區,各根的範本類型不得重疊;選中的根會採用其全部類型,來源路徑供你核對。",
template_kind_brand: "Brand",
template_kind_style: "Style",
template_kind_layout: "Layout",
@@ -1143,11 +1143,16 @@
if (!candidate || !slot) {
throw new Error("Invalid preselected template key: " + key);
}
- var value = slot === "explicit" ? (candidate.workspace_root || "") : key;
- if (TEMPLATE_SELECTIONS[slot] && TEMPLATE_SELECTIONS[slot] !== value) {
+ if (slot === "explicit") {
+ if (TEMPLATE_SELECTIONS.explicit.indexOf(candidate.workspace_root) < 0) {
+ TEMPLATE_SELECTIONS.explicit.push(candidate.workspace_root);
+ }
+ return;
+ }
+ if (TEMPLATE_SELECTIONS[slot] && TEMPLATE_SELECTIONS[slot] !== key) {
throw new Error("Multiple preselected templates for slot: " + slot);
}
- TEMPLATE_SELECTIONS[slot] = value;
+ TEMPLATE_SELECTIONS[slot] = key;
});
// Publish options before syncing: expanding an explicit root into its
// kinds reads TEMPLATE_OPTIONS, so a preselected root would otherwise
@@ -1158,7 +1163,7 @@
}
function emptyTemplateSelections() {
- return { brand: "", style: "", layout: "", deck: "", explicit: "" };
+ return { brand: "", style: "", layout: "", deck: "", explicit: [] };
}
function templateSelectionSlot(candidate) {
@@ -1211,8 +1216,10 @@
TEMPLATE_SELECTED_KEYS = TEMPLATE_KINDS.map(function (kind) {
return TEMPLATE_SELECTIONS[kind];
});
- explicitCandidatesForRoot(TEMPLATE_SELECTIONS.explicit).forEach(function (candidate) {
- TEMPLATE_SELECTED_KEYS.push(candidate.key);
+ TEMPLATE_SELECTIONS.explicit.forEach(function (root) {
+ explicitCandidatesForRoot(root).forEach(function (candidate) {
+ TEMPLATE_SELECTED_KEYS.push(candidate.key);
+ });
});
TEMPLATE_SELECTED_KEYS = TEMPLATE_SELECTED_KEYS.filter(Boolean);
}
@@ -1248,6 +1255,16 @@
updateTemplateSelectionControls();
}
+ function chooseExplicitTemplateRoot(root, selected) {
+ TEMPLATE_SELECTIONS.explicit = TEMPLATE_SELECTIONS.explicit.filter(function (value) {
+ return value !== root;
+ });
+ if (selected) TEMPLATE_SELECTIONS.explicit.push(root);
+ syncTemplateSelectionState();
+ TEMPLATE_MODE = "templates";
+ updateTemplateSelectionControls();
+ }
+
function templateOptionTitle(candidate) {
var details = [];
var summary = templateCandidateSummary(candidate);
@@ -1283,20 +1300,29 @@
});
field.appendChild(select);
- if (slot === "explicit") {
- field.appendChild(el(
- "div",
- "template-select-help",
- candidates.length ? t("template_explicit_hint") : t("template_none_explicit")
- ));
- var path = el("div", "template-selected-path");
- path.id = "template-explicit-path";
- path.appendChild(el("span", "template-selected-path-label", t("template_source_path") + ":"));
- var code = el("code", "template-selected-path-value");
- code.id = "template-explicit-path-value";
- path.appendChild(code);
- field.appendChild(path);
- }
+ return field;
+ }
+
+ function renderExplicitTemplateChoices() {
+ var field = el("div", "template-select-field template-select-field-explicit");
+ field.appendChild(el("div", "template-select-label", t("template_source_explicit")));
+ var roots = explicitRootOptions();
+ field.appendChild(el("div", "template-select-help",
+ roots.length ? t("template_explicit_hint") : t("template_none_explicit")));
+ roots.forEach(function (candidate) {
+ var label = el("label", "template-select-help");
+ var checkbox = el("input", "template-explicit-choice");
+ checkbox.type = "checkbox";
+ checkbox.value = candidate.workspace_root;
+ checkbox.checked = TEMPLATE_SELECTIONS.explicit.indexOf(checkbox.value) >= 0;
+ checkbox.addEventListener("change", function () {
+ chooseExplicitTemplateRoot(checkbox.value, checkbox.checked);
+ });
+ label.appendChild(checkbox);
+ label.appendChild(el("span", "", templateCandidateTitle(candidate) + " · " + candidate.summary));
+ label.appendChild(el("code", "template-selected-path-value", candidate.workspace_root));
+ field.appendChild(label);
+ });
return field;
}
@@ -1339,27 +1365,13 @@
var candidates = TEMPLATE_OPTIONS.library[kind] || [];
grid.appendChild(renderTemplateSelectField(kind, templateKindLabel(kind), candidates));
});
- grid.appendChild(renderTemplateSelectField(
- "explicit",
- t("template_source_explicit"),
- explicitRootOptions()
- ));
+ grid.appendChild(renderExplicitTemplateChoices());
panel.appendChild(grid);
sec.appendChild(panel);
host.appendChild(sec);
updateTemplateSelectionControls();
}
- function updateTemplateExplicitPath() {
- var path = document.getElementById("template-explicit-path");
- var value = document.getElementById("template-explicit-path-value");
- if (!path || !value) return;
- var workspaceRoot = TEMPLATE_SELECTIONS.explicit || "";
- path.hidden = !workspaceRoot;
- value.textContent = workspaceRoot;
- value.title = workspaceRoot;
- }
-
function updateTemplateSelectionControls() {
var freeChoice = document.getElementById("template-free-choice");
var useChoice = document.getElementById("template-use-choice");
@@ -1376,11 +1388,13 @@
useChoice.setAttribute("aria-expanded", templatesSelected ? "true" : "false");
}
if (selectorPanel) selectorPanel.hidden = !templatesSelected;
- TEMPLATE_KINDS.concat(["explicit"]).forEach(function (slot) {
+ TEMPLATE_KINDS.forEach(function (slot) {
var select = document.getElementById("template-select-" + slot);
if (select) select.value = TEMPLATE_SELECTIONS[slot] || "";
});
- updateTemplateExplicitPath();
+ document.querySelectorAll(".template-explicit-choice").forEach(function (checkbox) {
+ checkbox.checked = TEMPLATE_SELECTIONS.explicit.indexOf(checkbox.value) >= 0;
+ });
var status = document.getElementById("confirm-status");
if (status) status.textContent = "";
}
diff --git a/skills/ppt-master/scripts/docs/confirm_ui.md b/skills/ppt-master/scripts/docs/confirm_ui.md
index ebf6b31a..8485cc9b 100644
--- a/skills/ppt-master/scripts/docs/confirm_ui.md
+++ b/skills/ppt-master/scripts/docs/confirm_ui.md
@@ -49,7 +49,7 @@ python3 scripts/confirm_ui/server.py <project_path> --shutdown # Step 4 clean
- Confirm UI and live preview use different defaults (`5050` / `6060`) and separate project-local locks (`.confirm_ui.lock` / `live_preview/lock.json`). Step 4 shuts down the confirm service before ending; concurrent projects may use different ports.
- `--daemon` starts the Flask process in the background and returns after the health check. Every Default UI run launches directly into combined Stage 1 and keeps the same process live through final Stage 2. The wait budget defaults to **590 s** (`--wait-timeout`); on timeout the detached server remains live, and the caller re-checks both Stage-1 receipts before chat fallback.
- `--wait-only` attaches to the page opened by `--daemon` and blocks until the requested receipt. If it is already persisted, the command returns before recovery, so a fast submit between launch, chat handoff, and wait is not lost. Otherwise, if the recorded server died, it restarts on the recorded/default port. Use `stage1` for the combined communication/template submission and the default/final wait for Stage 2.
-- `--complete-template-selection` is agent-only. It validates the Stage-1 sidecar and writes the bound `template_handoff.json`; template mode additionally requires at least one project-local `templates/design_spec.<kind>.<id>.md`. Run it after installation/free-design closure and before writing Stage 2. `--reset-template-selection` removes exactly `template_options.json`, `template_selection.json`, and `template_handoff.json`; it does not alter Strategist files, installed template content, or `result.json`. The old `--*-template-phase` names are not aliases.
+- `--complete-template-selection` is agent-only. It validates the Stage-1 sidecar and writes the bound `template_handoff.json`; template mode additionally checks the installer's `template_install.json` against the confirmed roots/snapshot and installed content. Run it after installation/free-design closure and before writing Stage 2. `--reset-template-selection` removes exactly `template_options.json`, `template_selection.json`, and `template_handoff.json`; it does not alter Strategist files, installed template content, or `result.json`. The old `--*-template-phase` names are not aliases.
- `--shutdown` stops a confirm server left running for this project and exits — **idempotent** (a no-op when nothing is running). Tries a graceful `/api/shutdown`, falls back to killing the recorded pid, then clears the lock. Generate Step 4 runs this on every path so the selected port is released before live preview starts.
- Every fresh UI run starts with `--reset-template-selection`, then writes valid `<project_path>/confirm_ui/template_options.json` and a newer `recommendations.stage1.json`; `explicit_workspace_roots` is an empty array when no exact root was supplied. Stage 1 writes the bound selection and communication result together. Stage 2 is exposed only when the matching handoff is newer than that selection and its recommendation is newer than the handoff. `--shutdown` needs neither input.
- Per-project lock at `<project_path>/.confirm_ui.lock` — duplicate launches are refused; stale locks (dead pid) are overwritten.
@@ -100,8 +100,8 @@ separate artifact from the Strategist contract. Its files live under
`templates/design_spec.md`, one or more project-qualified
`templates/design_spec.<kind>.<id>.md`, or compatible legacy
`design_spec.md`.
-- The array supplies candidates for the one specified-root dropdown; it does
- not authorize selecting several explicit roots in one confirmation.
+- The array supplies exact-root candidates. The user may select multiple roots
+ when their kind sets do not overlap; each root is selected atomically.
- Do not write library entries into this file. The server reads only
`templates/brands/brands_index.json`,
`templates/styles/styles_index.json`,
@@ -144,22 +144,21 @@ to the sidecar rather than copying keys into `result.json`.
When the input supplies exactly one root, `preselected_keys` contains its
resolved candidate key as a convenience default, including when exact equality
reclassifies it as library. When several roots are supplied, all remain
-candidates but none is preselected; one specified-root dropdown cannot encode
-an instruction to use all of them.
+candidates but none is preselected; supplying paths does not select all of them.
**Page selection model**: Stage 1 first asks the user to choose `Free design` or
`Use templates`, initialized from `default_mode` but always switchable. Exactly
one supplied root may initialize its candidate as an editable convenience
default; multiple roots remain unselected. Only `Use templates` expands the
candidate controls: Brand, Style, Layout, and Deck each have one registered
-single-select dropdown, and Specified has one explicit-root single-select
-dropdown. Every dropdown includes `None`; template mode cannot submit until at
-least one is non-empty. Free design clears all dropdowns. Registered kinds may
+single-select dropdown, and Specified has one checkbox per exact root with its
+path and kinds visible. Every dropdown includes `None`; template mode cannot submit until at
+least one root is selected. Free design clears all selections. Registered kinds may
be combined, and the complete selection contains at most one contribution per
-kind. Layout and Deck may coexist; Layout takes structural precedence. The specified channel contributes at
-most one root, selected atomically with every kind it exposes; it can coexist
-only with registered roots of non-overlapping kinds. Source provenance never
-grants priority.
+kind. Layout and Deck may coexist; Layout takes structural precedence. Each specified
+root contributes every kind it exposes and may coexist with other explicit or
+registered roots of non-overlapping kinds. Conflicts block submission; path order
+and source provenance never grant priority.
### Output — `template_selection.json` (written with Stage 1)
@@ -182,6 +181,22 @@ grants priority.
"workspace_root": "/canonical/unregistered/workspace/root"
}
],
+ "root_snapshots": [
+ {
+ "workspace_root": "/canonical/library/root/example_style",
+ "source": "library",
+ "kinds": ["style"],
+ "specs": [{"kind": "style", "id": "example_style", "path": "templates/design_spec.md"}],
+ "files": {"templates/design_spec.md": "<source SHA-256>"}
+ },
+ {
+ "workspace_root": "/canonical/unregistered/workspace/root",
+ "source": "explicit",
+ "kinds": ["deck"],
+ "specs": [{"kind": "deck", "id": "example_deck", "path": "templates/design_spec.deck.example_deck.md"}],
+ "files": {"templates/design_spec.deck.example_deck.md": "<source SHA-256>", "templates/01_cover.svg": "<source SHA-256>"}
+ }
+ ],
"options_sha256": "<64 lowercase hex characters>",
"selection_sha256": "<64 lowercase hex characters>",
"confirmed_at": "2026-08-04T12:00:00"
@@ -192,17 +207,24 @@ grants priority.
at least one selection. Roots are unique canonical absolute paths. A library
selection contains exactly `source`, `kind`, `id`, and `workspace_root`; an
explicit selection contains exactly `source`, `kind`, and `workspace_root`.
-There is at most one explicit workspace **root** overall. The unit of choice is
-the root, not the kind: the browser's specified-path control lists roots, and
+Multiple explicit workspace roots may coexist. The unit of choice is
+the root: the browser's specified-path control lists roots, and
selecting one emits a selection for every kind that root exposes. Across those
emitted selections and all library choices, each kind appears at most once.
Layout and Deck may coexist; downstream installation gives Layout structural
precedence. The browser cannot submit arbitrary paths
because the server resolves posted keys against the catalog it just built.
+`root_snapshots` freezes each selected root's source label, kinds, spec identities,
+and SHA-256 hashes for all files under `templates/`, `images/`, and `icons/`.
`options_sha256` binds the receipt to the current input, four index files, and
-resolved candidates. `selection_sha256` binds the mode and canonical sorted
-selections to that option hash. Every receipt read rebuilds the catalog and
-rejects option/index drift or an incomplete explicit-root bundle.
+resolved candidates. `selection_sha256` binds the mode, canonical sorted
+selections, and snapshots to that option hash. Every receipt read checks source
+bytes and rebuilds the catalog using the frozen selected-root kinds, while
+retaining option/index and unselected-candidate drift checks. A changed in-place
+project root is accepted only when a matching installer receipt proves the
+expected installed specs, active roster, and required assets. External source
+changes still require confirmation again. Old selections without snapshots must
+be confirmed again; the server does not reconstruct historical authorization.
The Stage-1 submission writes this receipt and the Stage-1 `result.json`
together. Generate reads both exactly once after `--wait-only --wait-stage
@@ -236,8 +258,12 @@ The command writes, and agents must not hand-author:
```
The handoff must match the current valid selection. Template mode also requires
-at least one `<project_path>/templates/design_spec.<kind>.<id>.md`; free design
-requires no installed spec. Write `recommendations.stage2.json` only after this
+the machine receipt produced by [`apply_template.py`](template-tools.md#apply_templatepy):
+its roots, kinds, selection hash, complete installed spec set, active roster,
+and hashes of every required installed file must match. A missing, unrelated,
+or changed installation cannot complete or retain a ready handoff. Additional
+project images/icons are allowed without changing the template's required assets.
+Free design requires no installation receipt. Write `recommendations.stage2.json` only after this
command succeeds, so its file time is newer than the handoff.
## Field shapes
diff --git a/skills/ppt-master/scripts/docs/template-tools.md b/skills/ppt-master/scripts/docs/template-tools.md
index f9670783..2f7bca8e 100644
--- a/skills/ppt-master/scripts/docs/template-tools.md
+++ b/skills/ppt-master/scripts/docs/template-tools.md
@@ -53,7 +53,7 @@ Globs `*.svg` in the template directory; skips `spec_lock.md` drift checks; enfo
python3 skills/ppt-master/scripts/template_preview_pptx.py "<authoring_workspace>" [--force] [--native-charts-and-tables -o <distinct_path>]
```
-Consumes `templates/*.svg` directly, compiles the declared structured Master/Layout contract into `<authoring_workspace>/exports/<template_id>_template_preview.pptx` (creating `exports/` on demand), and reopens the result to verify one slide per prototype, the expected Master/Layout counts, exact Presentation → Master → Layout → Slide registration, distinct Theme parts per Master, valid unique `p14:creationId` and registration IDs, and — for `standard` / `fidelity` — that every carrier-bound placeholder on each review Slide has the same type, effective index, and full frame as its registered Layout placeholder. Authored modes use ephemeral SVG copies with concise preview-only sample text so long `{{...}}` markers stay readable; source SVGs, carrier typography, slot metadata, and Layout frames are unchanged. The default review keeps visible Chart/Table fallbacks; `--native-charts-and-tables -o <distinct_path>` writes a separately named JSON-first review. The first export refuses an existing output; `--force` replaces it intentionally. It needs no project `spec_lock.md`, creates no persistent project, and never infers structure.
+Consumes `templates/*.svg` directly, compiles the declared structured Master/Layout contract into `<authoring_workspace>/exports/<template_id>_template_preview.pptx` (creating `exports/` on demand), and reopens the result to verify one slide per prototype, the expected Master/Layout counts, exact Presentation → Master → Layout → Slide registration, distinct Theme parts per Master, valid unique `p14:creationId` and registration IDs, and — for `standard` / `fidelity` — that every carrier-bound placeholder on each review Slide has the same type, effective index, and full frame as its registered Layout placeholder. Authored modes use ephemeral SVG copies with concise preview-only sample text so long `{{...}}` markers stay readable; source SVGs, carrier typography, slot metadata, and Layout frames are unchanged. Typed chart/table placeholders automatically enable native Chart/Table compilation, with the triggering slot kinds printed in the receipt. Without typed slots, the default keeps visible fallbacks; `--native-charts-and-tables -o <distinct_path>` explicitly requests a separately named native review. The first export refuses an existing output; `--force` replaces it intentionally. It needs no project `spec_lock.md`, creates no persistent project, and never infers structure.
## `apply_template.py`
@@ -61,7 +61,11 @@ Consumes `templates/*.svg` directly, compiles the declared structured Master/Lay
python3 skills/ppt-master/scripts/apply_template.py <project_path> --root <workspace_root> [--root <workspace_root> ...] [--dry-run] [--skip-validation]
```
-Runs the install half of [`apply-template-workspace.md`](../../workflows/stages/apply-template-workspace.md) §4 for the roots Stage 1 (Default) or the user (Quick) already selected; it selects nothing. Each `--root` is a workspace root exposing `templates/design_spec.md` (library shape) or one `templates/design_spec.<kind>.<id>.md` per kind (project shape); an inner `templates/` directory is refused so sibling `images/` and `icons/` travel with the spec. Per root it runs `svg_quality_checker.py <root>/templates --template-mode --canonical-authoring` (`--skip-validation` when that already ran in the same turn), labels the root `library` when it resolves to the index-derived `templates/<kind_dir>/<id>/` and `explicit` otherwise, and rejects a Style-only library package that carries `images/`, `icons/`, or `exports/`. It then resolves the structural owner (Layout when selected, otherwise Deck), maps every spec to `<project>/templates/design_spec.<kind>.<id>.md` with exactly one `> **Installed from**: \`<root>\` (library|explicit)` line under the H1, maps the owner's `templates/` roster and other non-bitmap structural files and every root's `images/` / `icons/` once, and refuses duplicate kinds, a root passed twice, and any destination that already exists with different bytes — all before writing; a byte-identical destination is reported as `[same]`, so a rerun is a no-op. A root equal to the target project is consumed in place; when a selected Layout supersedes that project's in-place Deck roster, the Deck's structural files are removed and the Layout roster written in the same run. `--dry-run` prints the mapping and receipt without writing. The last stdout line is the §5.3 completion receipt (`roots=…; sources=…; kinds=…; segments=…; active_roster=…; install=…; installed_specs=…`).
+Runs the install half of [`apply-template-workspace.md`](../../workflows/stages/apply-template-workspace.md) §4 for the roots Stage 1 (Default) or the user (Quick) already selected; it selects nothing. Each `--root` is a workspace root exposing `templates/design_spec.md` (library shape) or one `templates/design_spec.<kind>.<id>.md` per kind (project shape); an inner `templates/` directory is refused so sibling `images/` and `icons/` travel with the spec. Per root it runs `svg_quality_checker.py <root>/templates --template-mode --canonical-authoring` (`--skip-validation` when that already ran in the same turn), labels the root `library` when it resolves to the index-derived `templates/<kind_dir>/<id>/` and `explicit` otherwise, and rejects a Style-only library package that carries `images/`, `icons/`, or `exports/`. It then resolves the structural owner (Layout when selected, otherwise Deck), maps every spec to `<project>/templates/design_spec.<kind>.<id>.md` with exactly one `> **Installed from**: \`<root>\` (library|explicit)` line under the H1, maps the owner's `templates/` roster and other non-bitmap structural files and every root's `images/` / `icons/` once, and refuses duplicate kinds, a root passed twice, and any destination that already exists with different bytes — all before writing; a byte-identical destination is reported as `[same]`, preserving content on reruns. A root equal to the target project is consumed in place; when a selected Layout supersedes that project's in-place Deck roster, the Deck's structural files are replaced by the Layout roster. `--dry-run` prints the mapping and receipt without writing. The last stdout line is the §5.3 completion receipt (`roots=…; sources=…; kinds=…; segments=…; active_roster=…; install=…; installed_specs=…`).
+
+The installer stages complete `templates/`, `images/`, and `icons/` trees on the target filesystem, verifies every mapped file and the final spec/roster/asset set, then publishes by directory rename. A publication failure rolls back all earlier renames, including removed Deck files and any previous receipt. If rollback itself fails, the error identifies retained backups for recovery. This is exception rollback across directories, not a single filesystem transaction or a process-crash recovery protocol.
+
+Successful installation also writes `<project>/template_install.json` in that transaction. Its version-1 object records `project`, `roots` (canonical roots, source labels, kinds, spec paths/identities, and source SHA-256 fingerprints), `installed_specs`, `active_roster` (root, kind, and structural file paths, or `null`), and `files` (installed relative paths → SHA-256). `selection_sha256` binds a UI installation to its frozen Stage-1 snapshot; it is `null` for installations without a UI selection. If `confirm_ui/template_selection.json` exists, the supplied roots and their bytes must match it before installation. Confirm UI checks this machine receipt and installed content before completing or reading a handoff; a textual provenance line is insufficient.
## `register_template.py`
diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py
index a6d1ab28..22f2d389 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py
@@ -3124,9 +3124,21 @@ def _remove_template_shape(
sp_tree.remove(shape)
+def _template_reference_indices(
+ states: list[_TemplateRuntimeSlide],
+ public_slide_count: int | None,
+) -> list[int]:
+ """Use public pages as truth, or prototypes for an otherwise unused Master."""
+ return [
+ index for index, state in enumerate(states)
+ if public_slide_count is None or state.spec.slide_num <= public_slide_count
+ ] or list(range(len(states)))
+
+
def _move_template_background(
states: list[_TemplateRuntimeSlide],
target_path: Path,
+ public_slide_count: int | None = None,
) -> str:
backgrounds = [
_extract_slide_background_xml(state.slide_path.read_text(encoding="utf-8"))
@@ -3137,8 +3149,10 @@ def _move_template_background(
"Template background metadata must resolve to an explicit background "
"on every affected slide"
)
+ reference_indices = _template_reference_indices(states, public_slide_count)
canonical_backgrounds = set()
- for background in backgrounds:
+ for index in reference_indices:
+ background = backgrounds[index]
if background is None:
continue
wrapper = ET.fromstring(
@@ -3148,11 +3162,11 @@ def _move_template_background(
ET.tostring(list(wrapper)[0], encoding="utf-8")
)
if len(canonical_backgrounds) != 1:
- slide_names = ", ".join(state.spec.svg_path.name for state in states)
+ slide_names = ", ".join(states[index].spec.svg_path.name for index in reference_indices)
raise TemplateStructureError(
f"Explicit template background differs across slides: {slide_names}"
)
- background_xml = backgrounds[0]
+ background_xml = backgrounds[reference_indices[0]]
if background_xml is None:
raise TemplateStructureError("Template background is unexpectedly empty")
target_xml = target_path.read_text(encoding="utf-8")
@@ -3181,6 +3195,7 @@ def _move_template_solid_background_shapes(
shapes: list[ET.Element],
target_path: Path,
slide_size_emu: tuple[int, int],
+ public_slide_count: int | None = None,
) -> str | None:
"""Move repeated full-slide solid rects into a master/layout p:bg."""
backgrounds = [
@@ -3194,13 +3209,14 @@ def _move_template_solid_background_shapes(
"A template background resolves to a full-slide solid rect on only "
"some slides sharing the structure"
)
- canonical = {background for background in backgrounds if background is not None}
+ reference_indices = _template_reference_indices(states, public_slide_count)
+ canonical = {backgrounds[index] for index in reference_indices}
if len(canonical) != 1:
- slide_names = ", ".join(state.spec.svg_path.name for state in states)
+ slide_names = ", ".join(states[index].spec.svg_path.name for index in reference_indices)
raise TemplateStructureError(
f"Explicit template solid background differs across slides: {slide_names}"
)
- background_xml = backgrounds[0]
+ background_xml = backgrounds[reference_indices[0]]
if background_xml is None:
return None
target_xml = target_path.read_text(encoding="utf-8")
@@ -3295,7 +3311,7 @@ def _move_template_static_shape(
raise TemplateStructureError(
f"{item.element_id}: structure item is a background on only some slides"
)
- return _move_template_background(states, target_path)
+ return _move_template_background(states, target_path, public_slide_count)
resolved_shapes = [shape for shape in shapes if shape is not None]
if item.is_background:
@@ -3304,6 +3320,7 @@ def _move_template_static_shape(
resolved_shapes,
target_path,
slide_size_emu,
+ public_slide_count,
)
if background_xml is None:
raise TemplateStructureError(
@@ -3315,10 +3332,9 @@ def _move_template_static_shape(
# pages alone decide the atom (a re-skinned rule must not be refused
# because an unused prototype still carries the original paint).
reference = [
- (state, shape)
- for state, shape in zip(states, resolved_shapes)
- if public_slide_count is None or state.spec.slide_num <= public_slide_count
- ] or list(zip(states, resolved_shapes))
+ (states[index], resolved_shapes[index])
+ for index in _template_reference_indices(states, public_slide_count)
+ ]
canonical = {
_canonical_shape_xml(shape, state.rels)
for state, shape in reference
@@ -3713,13 +3729,15 @@ def _set_placeholder_theme_font_role(
item: TemplateElementSpec,
theme_font_spec: ThemeFontSpec | None,
) -> None:
- """Force semantic text placeholders onto the correct theme font role."""
+ """Use the placeholder's theme role only when it preserves the actual face."""
if theme_font_spec is None:
return
if item.placeholder == "title":
prefix = "+mj"
+ target_face = theme_font_spec.major
elif item.placeholder in TEMPLATE_PLACEHOLDER_TYPES:
prefix = "+mn"
+ target_face = theme_font_spec.minor
else:
return
for props_tag in ("rPr", "defRPr", "endParaRPr"):
@@ -3727,7 +3745,13 @@ def _set_placeholder_theme_font_role(
for font_tag, suffix in (("latin", "lt"), ("ea", "ea"), ("cs", "cs")):
font = props.find(f"{{{DML_NS}}}{font_tag}")
if font is not None:
- font.set("typeface", f"{prefix}-{suffix}")
+ face = font.get("typeface")
+ if face == f"+mj-{suffix}":
+ face = getattr(theme_font_spec.major, font_tag)
+ elif face == f"+mn-{suffix}":
+ face = getattr(theme_font_spec.minor, font_tag)
+ if face and face == getattr(target_face, font_tag):
+ font.set("typeface", f"{prefix}-{suffix}")
def _layout_placeholder_shape(
diff --git a/skills/ppt-master/scripts/template_preview_pptx.py b/skills/ppt-master/scripts/template_preview_pptx.py
index 3fff0722..0b3450c4 100644
--- a/skills/ppt-master/scripts/template_preview_pptx.py
+++ b/skills/ppt-master/scripts/template_preview_pptx.py
@@ -43,6 +43,7 @@ from svg_to_pptx.pptx_package.builder import ( # noqa: E402
)
from svg_to_pptx.pptx_package.template_structure import ( # noqa: E402
load_template_source_themes,
+ parse_template_slides,
)
@@ -322,7 +323,8 @@ def build_parser() -> argparse.ArgumentParser:
action="store_true",
help=(
"Replace eligible SVG chart/table fallbacks with PowerPoint-native "
- "objects. Default review export keeps the visible SVG fallbacks."
+ "objects. Enabled automatically for typed chart/table placeholders; "
+ "otherwise the default keeps visible SVG fallbacks."
),
)
return parser
@@ -380,11 +382,20 @@ def main(argv: list[str] | None = None) -> int:
text_style, title_px, body_px = infer_master_text_style_spec(
all_svg_files
)
+ typed_slots = sorted({
+ item.placeholder
+ for spec in parse_template_slides(svg_files)
+ for item in spec.placeholders
+ if item.placeholder in {"chart", "table"}
+ })
+ native_objects = args.native_charts_and_tables or bool(typed_slots)
print("PPT Master - Template Preview PPTX Exporter")
print(f" Workspace: {workspace}")
print(f" Template source: {template_dir}")
print(f" Slide SVG prototypes: {len(svg_files)}")
+ if typed_slots:
+ print(" Native Chart/Table compilation: required by typed " + ", ".join(typed_slots) + " slots")
if replication_mode == "mirror":
print(" Review placeholder frames: preserved source Slide geometry")
else:
@@ -408,7 +419,7 @@ def main(argv: list[str] | None = None) -> int:
enable_notes=False,
animation=None,
image_optimize=False,
- native_objects=args.native_charts_and_tables,
+ native_objects=native_objects,
pptx_structure="structured",
use_layout_placeholder_frames=use_full_placeholder_frames,
master_text_style_spec=text_style,
diff --git a/skills/ppt-master/scripts/tests/test_apply_template.py b/skills/ppt-master/scripts/tests/test_apply_template.py
index 2ac6d246..b8351434 100644
--- a/skills/ppt-master/scripts/tests/test_apply_template.py
+++ b/skills/ppt-master/scripts/tests/test_apply_template.py
@@ -53,7 +53,7 @@ class ApplyTemplateTests(unittest.TestCase):
text[h1:],
)
self.assertEqual(text.count("**Installed from**"), 1)
- self.assertEqual(sorted(p.name for p in self.project.iterdir()), ["templates"])
+ self.assertEqual(sorted(p.name for p in self.project.iterdir()), ["template_install.json", "templates"])
receipt = _receipt(plan)
self.assertIn("sources=library", receipt)
self.assertIn("kinds=style", receipt)
diff --git a/skills/ppt-master/scripts/tests/test_template_flow_batch1.py b/skills/ppt-master/scripts/tests/test_template_flow_batch1.py
new file mode 100644
index 00000000..1dd9974d
--- /dev/null
+++ b/skills/ppt-master/scripts/tests/test_template_flow_batch1.py
@@ -0,0 +1,381 @@
+#!/usr/bin/env python3
+"""Regression coverage for template-flow audit N1/N2/N4/N5/N6/N7/N8."""
+
+from __future__ import annotations
+
+import contextlib
+import io
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+from xml.etree import ElementTree as ET
+
+SCRIPTS_DIR = Path(__file__).resolve().parents[1]
+if str(SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(SCRIPTS_DIR))
+
+import apply_template # noqa: E402
+import template_preview_pptx # noqa: E402
+from confirm_ui import server # noqa: E402
+from svg_to_pptx.drawingml.theme_fonts import ThemeFontFace, ThemeFontSpec # noqa: E402
+from svg_to_pptx.pptx_package import builder # noqa: E402
+from svg_to_pptx.pptx_package.template_structure import ( # noqa: E402
+ TemplateElementSpec,
+ TemplateSlideSpec,
+ TemplateStructureError,
+)
+
+PML = builder.PML_NS
+DML = builder.DML_NS
+TEMPLATES = SCRIPTS_DIR.parent / 'templates'
+
+
+def _files(root: Path) -> dict[str, bytes]:
+ return {str(path.relative_to(root)): path.read_bytes()
+ for path in root.rglob('*') if path.is_file()}
+
+
+def _workspace(root: Path, kind: str, template_id: str) -> Path:
+ templates = root / 'templates'
+ templates.mkdir(parents=True)
+ (templates / f'design_spec.{kind}.{template_id}.md').write_text(
+ f'---\nkind: {kind}\n{kind}_id: {template_id}\n---\n# {template_id}\n',
+ encoding='utf-8',
+ )
+ if kind in {'layout', 'deck'}:
+ (templates / f'{kind}.svg').write_text('<svg/>', encoding='utf-8')
+ return root
+
+
+def _confirm(project: Path, roots: list[Path], mode: str = 'templates') -> dict:
+ confirm = project / 'confirm_ui'
+ server._write_json_atomic(confirm / server.TEMPLATE_OPTIONS_NAME, {
+ 'schema_version': 1, 'phase': 'template', 'default_mode': mode,
+ 'explicit_workspace_roots': [str(root) for root in roots],
+ })
+ options, candidates = server._build_template_options(confirm)
+ keys = [key for key, candidate in candidates.items()
+ if candidate['workspace_root'] in {str(root) for root in roots}]
+ selection = server._resolve_template_confirmation(
+ {'mode': mode, 'selection_keys': keys}, candidates, options['options_sha256'],
+ project,
+ )
+ server._write_json_atomic(confirm / server.TEMPLATE_SELECTION_NAME, selection)
+ server._write_json_atomic(confirm / server.RESULT_NAME, {
+ 'stage': 'stage1', 'status': 'stage1-confirmed',
+ })
+ return selection
+
+
+class TemplateInstallTests(unittest.TestCase):
+ def setUp(self) -> None:
+ temp = tempfile.TemporaryDirectory()
+ self.addCleanup(temp.cleanup)
+ self.tmp = Path(temp.name)
+ self.project = _workspace(self.tmp / 'project', 'deck', 'old')
+ self.layout = _workspace(self.tmp / 'layout', 'layout', 'new')
+ for directory in ('images', 'icons'):
+ (self.project / directory).mkdir()
+ (self.project / directory / 'keep.bin').write_bytes(b'original')
+ (self.layout / directory / 'nested').mkdir(parents=True)
+ (self.layout / directory / 'nested' / 'new.bin').write_bytes(b'new')
+
+ def _apply(self):
+ return apply_template.apply_templates(
+ self.project, [str(self.project), str(self.layout)], validate=False,
+ )
+
+ def test_n1_staging_copy_failure_preserves_original_tree(self) -> None:
+ before = _files(self.project)
+ copy2 = shutil.copy2
+
+ def fail_copy(src, dst, *args, **kwargs):
+ if Path(src) == self.layout / 'icons' / 'nested' / 'new.bin':
+ raise OSError('injected staging failure')
+ return copy2(src, dst, *args, **kwargs)
+
+ with patch('apply_template.shutil.copy2', side_effect=fail_copy):
+ with self.assertRaises((OSError, apply_template.ApplyTemplateError)):
+ self._apply()
+ self.assertEqual(_files(self.project), before)
+ self.assertEqual(sorted(p.name for p in self.project.iterdir()), ['icons', 'images', 'templates'])
+
+ def test_n1_each_publication_failure_restores_all_directories(self) -> None:
+ (self.project / 'template_install.json').write_bytes(b'previous receipt')
+ before = _files(self.project)
+ replace = os.replace
+ for name in ('templates', 'images', 'icons', 'template_install.json'):
+ with self.subTest(destination=name):
+ failed = False
+
+ def fail_publish(src, dst):
+ nonlocal failed
+ if Path(dst) == self.project / name and not failed:
+ failed = True
+ raise OSError('injected publication failure')
+ return replace(src, dst)
+
+ with patch('os.replace', side_effect=fail_publish):
+ with self.assertRaises((OSError, apply_template.ApplyTemplateError)):
+ self._apply()
+ self.assertTrue(failed)
+ self.assertEqual(_files(self.project), before)
+
+ def test_n5_disjoint_explicit_roots_can_be_confirmed(self) -> None:
+ brand = _workspace(self.tmp / 'brand', 'brand', 'identity')
+ selection = _confirm(self.project, [brand, self.layout])
+ self.assertEqual({item['kind'] for item in selection['selections']}, {'brand', 'layout'})
+
+ def test_n5_conflicting_roots_are_rejected_in_both_orders(self) -> None:
+ other = _workspace(self.tmp / 'other', 'layout', 'other')
+ for roots in ([other, self.layout], [self.layout, other]):
+ with self.subTest(roots=roots), self.assertRaisesRegex(ValueError, 'one workspace for kind'):
+ _confirm(self.project, roots)
+
+ def test_n5_multikind_root_cannot_be_partially_selected(self) -> None:
+ (self.project / 'templates' / 'design_spec.brand.identity.md').write_text(
+ '---\nkind: brand\nbrand_id: identity\n---\n# Identity\n', encoding='utf-8',
+ )
+ _confirm(self.project, [self.project])
+ options, candidates = server._build_template_options(self.project / 'confirm_ui')
+ keys = [key for key, item in candidates.items()
+ if item['workspace_root'] == str(self.project) and item['kind'] == 'deck']
+ with self.assertRaisesRegex(ValueError, 'every kind'):
+ server._resolve_template_confirmation(
+ {'mode': 'templates', 'selection_keys': keys}, candidates, options['options_sha256'],
+ self.project,
+ )
+
+ def test_n6_authorized_in_place_install_keeps_confirmation_valid(self) -> None:
+ _confirm(self.project, [self.project, TEMPLATES / 'layouts' / 'report_core'])
+ apply_template.apply_templates(
+ self.project, [str(self.project), str(TEMPLATES / 'layouts' / 'report_core')],
+ validate=False,
+ )
+ self.assertEqual(server._complete_template_selection(self.project), 0)
+ handoff = server._read_template_handoff(
+ self.project, self.project / 'confirm_ui' / server.TEMPLATE_HANDOFF_NAME,
+ )
+ self.assertEqual(handoff['status'], 'ready')
+
+ def test_n6_external_spec_drift_is_rejected_before_install(self) -> None:
+ _confirm(self.project, [self.layout])
+ spec = self.layout / 'templates' / 'design_spec.layout.new.md'
+ spec.write_text(spec.read_text(encoding='utf-8') + '\nChanged\n', encoding='utf-8')
+ with self.assertRaises((ValueError, apply_template.ApplyTemplateError)):
+ apply_template.apply_templates(self.project, [str(self.layout)], validate=False)
+
+ def test_n6_unreceipted_in_place_change_is_rejected(self) -> None:
+ _confirm(self.project, [self.project])
+ (self.project / 'templates' / 'deck.svg').write_text('<svg>changed</svg>', encoding='utf-8')
+ with self.assertRaises((ValueError, apply_template.ApplyTemplateError)):
+ server._read_template_selection(self.project / 'confirm_ui' / server.TEMPLATE_SELECTION_NAME)
+
+ def test_n6_options_drift_is_still_rejected(self) -> None:
+ _confirm(self.project, [self.layout])
+ options_path = self.project / 'confirm_ui' / server.TEMPLATE_OPTIONS_NAME
+ options = json.loads(options_path.read_text(encoding='utf-8'))
+ options['lang'] = 'ja'
+ previous_time = options_path.stat().st_mtime_ns
+ server._write_json_atomic(options_path, options)
+ os.utime(options_path, ns=(previous_time, previous_time))
+ with self.assertRaisesRegex(ValueError, 'options_sha256'):
+ server._read_template_selection(self.project / 'confirm_ui' / server.TEMPLATE_SELECTION_NAME)
+
+ def test_n6_external_asset_drift_is_rejected_after_install(self) -> None:
+ brand = _workspace(self.tmp / 'brand', 'brand', 'identity')
+ (brand / 'images').mkdir()
+ (brand / 'images' / 'logo.bin').write_bytes(b'logo')
+ _confirm(self.project, [self.project, brand])
+ apply_template.apply_templates(self.project, [str(self.project), str(brand)], validate=False)
+ (brand / 'images' / 'logo.bin').write_bytes(b'drift')
+ self.assertEqual(server._complete_template_selection(self.project), 1)
+
+ def test_n8_unrelated_installed_spec_cannot_complete_handoff(self) -> None:
+ _confirm(self.project, [TEMPLATES / 'brands' / 'zcare-rescue', TEMPLATES / 'layouts' / 'report_core'])
+ self.assertEqual(server._complete_template_selection(self.project), 1)
+
+ def test_n8_correct_filenames_without_installer_receipt_are_rejected(self) -> None:
+ _confirm(self.project, [self.layout])
+ shutil.copy2(self.layout / 'templates' / 'design_spec.layout.new.md', self.project / 'templates')
+ self.assertEqual(server._complete_template_selection(self.project), 1)
+
+ def test_n8_installed_asset_drift_invalidates_ready_handoff(self) -> None:
+ _confirm(self.project, [self.project, TEMPLATES / 'brands' / 'zcare-rescue'])
+ apply_template.apply_templates(
+ self.project, [str(self.project), str(TEMPLATES / 'brands' / 'zcare-rescue')], validate=False,
+ )
+ self.assertEqual(server._complete_template_selection(self.project), 0)
+ (self.project / 'icons' / 'keep.bin').write_bytes(b'changed')
+ with self.assertRaises((ValueError, apply_template.ApplyTemplateError)):
+ server._read_template_handoff(
+ self.project, self.project / 'confirm_ui' / server.TEMPLATE_HANDOFF_NAME,
+ )
+
+ def test_n8_receipt_for_another_selection_cannot_authorize_handoff(self) -> None:
+ apply_template.apply_templates(self.project, [str(self.project)], validate=False)
+ _confirm(self.project, [self.layout])
+ self.assertEqual(server._complete_template_selection(self.project), 1)
+
+ def test_n8_installed_spec_and_roster_changes_are_rejected(self) -> None:
+ _confirm(self.project, [self.project])
+ apply_template.apply_templates(self.project, [str(self.project)], validate=False)
+ for relative in ('templates/design_spec.deck.old.md', 'templates/deck.svg'):
+ with self.subTest(relative=relative):
+ path = self.project / relative
+ before = path.read_bytes()
+ path.write_bytes(before + b'changed')
+ self.assertEqual(server._complete_template_selection(self.project), 1)
+ path.write_bytes(before)
+ (self.project / 'images' / 'later-project-asset.bin').write_bytes(b'new project material')
+ self.assertEqual(server._complete_template_selection(self.project), 0)
+
+ def test_free_design_still_completes_without_installation(self) -> None:
+ _confirm(self.project, [], mode='free_design')
+ self.assertEqual(server._complete_template_selection(self.project), 0)
+
+
+class TemplateBuilderTests(unittest.TestCase):
+ def _backgrounds(self, colors: list[str], *, baked: bool = False, public_count: int = 1):
+ with tempfile.TemporaryDirectory() as tmp:
+ root_dir = Path(tmp)
+ item = TemplateElementSpec('background', 0, 'rect', layer='master', is_background=True)
+ states = []
+ for num, color in enumerate(colors, 1):
+ root = ET.fromstring(f'<p:sld xmlns:p="{PML}" xmlns:a="{DML}"><p:cSld><p:spTree/></p:cSld></p:sld>')
+ shape = ET.fromstring(
+ f'<p:sp xmlns:p="{PML}" xmlns:a="{DML}"><p:spPr>'
+ '<a:xfrm><a:off x="0" y="0"/><a:ext cx="1280" cy="720"/></a:xfrm>'
+ f'<a:prstGeom prst="rect"/><a:solidFill><a:srgbClr val="{color}"/></a:solidFill>'
+ '</p:spPr></p:sp>'
+ )
+ if baked:
+ root.find(f'{{{PML}}}cSld').insert(0, ET.fromstring(
+ builder._solid_background_xml_from_shape(shape, (1280, 720)),
+ ))
+ else:
+ root.find(f'.//{{{PML}}}spTree').append(shape)
+ path = root_dir / f'slide{num}.xml'
+ ET.ElementTree(root).write(path, encoding='utf-8')
+ spec = TemplateSlideSpec(
+ num, Path(f'page{num}.svg'), 'm', 'M', str(num), str(num), True, True, (item,),
+ )
+ states.append(builder._TemplateRuntimeSlide(
+ spec, path, path.with_suffix('.rels'), ET.ElementTree(root), root, {},
+ {} if baked else {'2': shape}, {} if baked else {'background': ['2']},
+ ))
+ target = root_dir / 'master.xml'
+ target.write_text(
+ f'<p:sldMaster xmlns:p="{PML}"><p:cSld><p:spTree/></p:cSld></p:sldMaster>',
+ encoding='utf-8',
+ )
+ result = builder._move_template_static_shape(
+ states, item, target, root_dir / 'master.rels', (1280, 720), public_slide_count=public_count,
+ )
+ self.assertTrue(all(not list(state.root.iter(f'{{{PML}}}sp')) for state in states))
+ return result
+
+ def test_n2_public_background_wins_over_unused_prototype(self) -> None:
+ for baked in (False, True):
+ with self.subTest(baked=baked):
+ self.assertIn('FAFAFA', self._backgrounds(['FAFAFA', 'FFFFFF'], baked=baked))
+
+ def test_n2_inconsistent_public_backgrounds_still_fail(self) -> None:
+ for baked in (False, True):
+ with self.subTest(baked=baked), self.assertRaises(TemplateStructureError):
+ self._backgrounds(['FAFAFA', 'FFFFFF'], baked=baked, public_count=2)
+
+ def test_n2_master_without_public_pages_uses_its_prototype(self) -> None:
+ self.assertIn('FFFFFF', self._backgrounds(['FFFFFF'], public_count=0))
+
+ def test_n7_custom_faces_survive_slide_and_layout_placeholder_rebuild(self) -> None:
+ fonts = ThemeFontSpec(ThemeFontFace('Arial', 'SimSun', 'Arial'),
+ ThemeFontFace('Arial', 'SimSun', 'Arial'), 'Arial', 'Arial')
+ for kind in ('title', 'body'):
+ for face, expected in (('Arial Black', 'Arial Black'), ('Arial', '+mj-lt' if kind == 'title' else '+mn-lt'),
+ ('+mn-lt', '+mj-lt' if kind == 'title' else '+mn-lt')):
+ with self.subTest(kind=kind, face=face):
+ shape = ET.fromstring(
+ f'<p:sp xmlns:p="{PML}" xmlns:a="{DML}"><p:nvSpPr><p:nvPr/></p:nvSpPr>'
+ '<p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r>'
+ f'<a:rPr><a:latin typeface="{face}"/></a:rPr><a:t>01</a:t>'
+ '</a:r></a:p></p:txBody></p:sp>'
+ )
+ item = TemplateElementSpec('number', 0, 'g', placeholder=kind,
+ placeholder_bounds=(0, 0, 100, 100))
+ layout = builder._layout_placeholder_shape(shape, item, 1, fonts)
+ builder._patch_slide_placeholder(shape, item, 1, theme_font_spec=fonts)
+ for output in (shape, layout):
+ self.assertEqual(output.find(f'.//{{{DML}}}latin').get('typeface'), expected)
+
+
+class TemplatePreviewTests(unittest.TestCase):
+ def test_n4_default_report_core_preview_compiles_typed_slots(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp, contextlib.redirect_stdout(io.StringIO()) as output:
+ code = template_preview_pptx.main([
+ str(TEMPLATES / 'layouts' / 'report_core'), '-o', str(Path(tmp) / 'review.pptx'),
+ ])
+ self.assertEqual(code, 0, output.getvalue())
+ self.assertIn('2 master(s)', output.getvalue())
+ self.assertIn('typed', output.getvalue())
+
+
+class TemplateBrowserTests(unittest.TestCase):
+ @unittest.skipUnless(shutil.which('node'), 'Node.js is needed for the frontend behavior check')
+ def test_n5_explicit_checkboxes_expand_roots_and_reject_kind_conflicts(self) -> None:
+ source = (SCRIPTS_DIR / 'confirm_ui' / 'static' / 'app.js').read_text(encoding='utf-8')
+ selection_code = source[source.index(' function normalizeTemplateCandidates('):
+ source.index(' function normalizeRecId(')]
+ validation_code = source[source.index(' function templateSelectionValid('):
+ source.index(' function submitStage1(')]
+ script = '''
+const assert = require('node:assert/strict');
+var TEMPLATE_KINDS = ['brand', 'style', 'layout', 'deck'];
+var TEMPLATE_SELECTIONS, TEMPLATE_OPTIONS, TEMPLATE_CANDIDATES, TEMPLATE_SELECTED_KEYS, TEMPLATE_MODE;
+var status = {}, inputs = [];
+var document = {
+ getElementById: id => id === 'confirm-status' ? status : null,
+ querySelectorAll: () => inputs
+};
+function t(key) { return key; }
+function localized(item, field) { return item[field]; }
+function el(tag, cls, text) {
+ var element = {children: [], appendChild(child) { this.children.push(child); },
+ addEventListener(event, handler) { this[event] = handler; }};
+ if (tag === 'input') inputs.push(element);
+ return element;
+}
+''' + selection_code + validation_code + '''
+const explicit = [
+ {key: 'b', kind: 'brand', workspace_root: '/one'},
+ {key: 's', kind: 'style', workspace_root: '/one'},
+ {key: 'l', kind: 'layout', workspace_root: '/two'},
+ {key: 'x', kind: 'layout', workspace_root: '/conflict'}
+];
+initTemplateOptions({default_mode: 'templates', explicit, preselected_keys: ['b', 's']});
+renderExplicitTemplateChoices();
+assert.equal(inputs.length, 3);
+assert.deepEqual(TEMPLATE_SELECTED_KEYS, ['b', 's']);
+inputs[1].checked = true;
+inputs[1].change();
+assert.deepEqual(TEMPLATE_SELECTED_KEYS, ['b', 's', 'l']);
+assert.equal(templateSelectionValid(), true);
+inputs[2].checked = true;
+inputs[2].change();
+assert.equal(templateSelectionValid(), false);
+assert.deepEqual(TEMPLATE_SELECTED_KEYS, ['b', 's', 'l', 'x']);
+inputs[2].checked = false;
+inputs[2].change();
+assert.equal(templateSelectionValid(), true);
+chooseFreeDesign();
+assert.deepEqual(TEMPLATE_SELECTED_KEYS, []);
+assert.equal(inputs.some(input => input.checked), false);
+'''
+ result = subprocess.run(['node', '-e', script], capture_output=True, text=True, check=False)
+ self.assertEqual(result.returncode, 0, result.stderr)