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

feat(confirm-ui): add pre-strategist template selection

hugohe39b65f22c4861
diff --git a/skills/ppt-master/scripts/confirm_ui/server.py b/skills/ppt-master/scripts/confirm_ui/server.py
index 1394cf6c..9fe74b81 100644
--- a/skills/ppt-master/scripts/confirm_ui/server.py
+++ b/skills/ppt-master/scripts/confirm_ui/server.py
@@ -1,9 +1,11 @@
#!/usr/bin/env python3
"""
-PPT Master - Strategist confirmation stage UI Server (Step 4)
+PPT Master - Template and Strategist confirmation UI Server (Steps 3-4)
-Lightweight Flask backend for the interactive, visual Strategist confirmation
-stage page. Strategist writes each stage to
+Lightweight Flask backend for the independent Step-3 template selection and
+interactive Step-4 Strategist confirmation page. The agent writes template
+input to ``<project>/confirm_ui/template_options.json``; template selection is
+persisted separately from the Strategist contract. Strategist writes each stage to
``<project>/confirm_ui/recommendations.stageN.json``; this server selects the
current stage from ``result.json`` and renders it as a clickable page (color
swatches, live font previews, candidate picks). On submit it writes the user's
@@ -24,6 +26,8 @@ Examples:
python3 scripts/confirm_ui/server.py projects/my-project --no-browser
python3 scripts/confirm_ui/server.py projects/my-project --daemon
python3 scripts/confirm_ui/server.py projects/my-project --wait-only --wait-stage stage1
+ python3 scripts/confirm_ui/server.py projects/my-project --complete-template-phase
+ python3 scripts/confirm_ui/server.py projects/my-project --reset-template-phase
Dependencies:
flask>=3.0.0
@@ -31,6 +35,7 @@ Dependencies:
import argparse
import atexit
+import hashlib
import json
import logging
import os
@@ -91,6 +96,10 @@ RECOMMENDATION_STAGE_NAMES = {
}
RESULT_NAME = 'result.json'
SESSION_NAME = 'session.json'
+TEMPLATE_OPTIONS_NAME = 'template_options.json'
+TEMPLATE_SELECTION_NAME = 'template_selection.json'
+TEMPLATE_HANDOFF_NAME = 'template_handoff.json'
+TEMPLATE_SCHEMA_VERSION = 1
_PALETTE_ROLES = (
'background',
@@ -104,9 +113,17 @@ _TYPOGRAPHY_SIZE_ROLES = ('title', 'subtitle', 'annotation')
_HEX_COLOR_RE = re.compile(r'#?(?:[0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})\Z')
# Static option universe served at /api/catalogs (canvas synced live from config).
+_SKILL_DIR = Path(__file__).resolve().parents[2]
+_TEMPLATES_DIR = _SKILL_DIR / 'templates'
_CATALOGS_PATH = Path(__file__).resolve().parent / 'static' / 'catalogs.json'
-_ICON_LIBRARY_DIR = Path(__file__).resolve().parents[2] / 'templates' / 'icons'
-_AI_IMAGE_COMPARISON_DIR = Path(__file__).resolve().parents[2] / 'references' / 'ai-image-comparison'
+_ICON_LIBRARY_DIR = _TEMPLATES_DIR / 'icons'
+_AI_IMAGE_COMPARISON_DIR = _SKILL_DIR / 'references' / 'ai-image-comparison'
+_TEMPLATE_LIBRARY_CONFIG = {
+ 'brand': ('brands', 'brands_index.json'),
+ 'style': ('styles', 'styles_index.json'),
+ 'layout': ('layouts', 'layouts_index.json'),
+ 'deck': ('decks', 'decks_index.json'),
+}
_ICON_PREVIEW_SAMPLES = {
'chunk-filled': ('home', 'chart-line', 'users', 'target'),
'tabler-filled': ('home', 'chart-dots', 'user', 'bulb'),
@@ -163,6 +180,588 @@ def _write_json_atomic(path: Path, data: dict) -> None:
pass
+def _json_sha256(data: object) -> str:
+ """Return a stable SHA-256 over one JSON-compatible value."""
+ canonical = json.dumps(
+ data,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(',', ':'),
+ )
+ return hashlib.sha256(canonical.encode('utf-8')).hexdigest()
+
+
+def _safe_template_id(template_id: object) -> bool:
+ """Return whether an index key is one safe directory-segment id."""
+ return (
+ isinstance(template_id, str)
+ and re.fullmatch(r'\w[\w.-]*', template_id) is not None
+ )
+
+
+def _read_template_options_input(confirm_dir: Path) -> tuple[dict, list[Path]]:
+ """Read and validate the agent-authored Step-3 template input."""
+ options_file = confirm_dir / TEMPLATE_OPTIONS_NAME
+ data = _read_json_object(options_file)
+ if type(data.get('schema_version')) is not int or data['schema_version'] != TEMPLATE_SCHEMA_VERSION:
+ raise ValueError(
+ f'{TEMPLATE_OPTIONS_NAME} schema_version must be {TEMPLATE_SCHEMA_VERSION}'
+ )
+ if data.get('phase') != 'template':
+ raise ValueError(f'{TEMPLATE_OPTIONS_NAME} phase must be template')
+ if 'lang' in data and (
+ not isinstance(data['lang'], str) or not data['lang'].strip()
+ ):
+ raise ValueError(f'{TEMPLATE_OPTIONS_NAME} lang must be a non-empty string')
+ if 'explicit_workspace_roots' not in data:
+ raise ValueError(
+ f'{TEMPLATE_OPTIONS_NAME} must include explicit_workspace_roots'
+ )
+ raw_roots = data['explicit_workspace_roots']
+ if not isinstance(raw_roots, list):
+ raise ValueError(
+ f'{TEMPLATE_OPTIONS_NAME} explicit_workspace_roots must be an array'
+ )
+
+ roots = []
+ seen = set()
+ for index, raw_root in enumerate(raw_roots):
+ if not isinstance(raw_root, str) or not raw_root.strip():
+ raise ValueError(
+ f'{TEMPLATE_OPTIONS_NAME} explicit_workspace_roots[{index}] '
+ 'must be a non-empty string'
+ )
+ candidate = Path(raw_root)
+ if not candidate.is_absolute():
+ raise ValueError(
+ f'{TEMPLATE_OPTIONS_NAME} explicit_workspace_roots[{index}] '
+ 'must be an absolute path'
+ )
+ try:
+ root = candidate.resolve()
+ except (OSError, RuntimeError) as exc:
+ raise ValueError(
+ f'cannot resolve explicit workspace root {raw_root}: {exc}'
+ ) from exc
+ canonical = str(root)
+ if canonical in seen:
+ raise ValueError(
+ f'{TEMPLATE_OPTIONS_NAME} contains duplicate workspace root: {canonical}'
+ )
+ if not root.is_dir():
+ raise ValueError(f'explicit workspace root is not a directory: {canonical}')
+ if not (
+ (root / 'templates' / 'design_spec.md').is_file()
+ or (root / 'design_spec.md').is_file()
+ ):
+ raise ValueError(
+ 'explicit workspace root is missing templates/design_spec.md '
+ f'or legacy design_spec.md: {canonical}'
+ )
+ seen.add(canonical)
+ roots.append(root)
+ return data, roots
+
+
+def _build_template_library() -> tuple[dict, dict[str, dict], dict[str, dict], dict]:
+ """Build indexed library groups without scanning template directories."""
+ library = {}
+ candidates = {}
+ registered_roots = {}
+ index_contracts = {}
+ for kind, (directory_name, index_name) in _TEMPLATE_LIBRARY_CONFIG.items():
+ kind_dir = (_TEMPLATES_DIR / directory_name).resolve()
+ index_path = kind_dir / index_name
+ index_data = _read_json_object(index_path)
+ index_contracts[kind] = index_data
+ group = []
+ for template_id, metadata in index_data.items():
+ if not _safe_template_id(template_id):
+ raise ValueError(
+ f'{index_path} contains unsafe template id: {template_id!r}'
+ )
+ if not isinstance(metadata, dict):
+ raise ValueError(
+ f'{index_path} entry {template_id!r} must be an object'
+ )
+ workspace_root = (kind_dir / template_id).resolve()
+ if workspace_root.parent != kind_dir:
+ raise ValueError(
+ f'{index_path} entry {template_id!r} does not resolve to a '
+ f'direct child of {kind_dir}'
+ )
+ if not workspace_root.is_dir():
+ raise ValueError(
+ f'{index_path} entry {template_id!r} workspace does not exist: '
+ f'{workspace_root}'
+ )
+ spec_path = workspace_root / 'templates' / 'design_spec.md'
+ if not spec_path.is_file():
+ raise ValueError(
+ f'{index_path} entry {template_id!r} is missing {spec_path}'
+ )
+ summary = metadata.get('summary', '')
+ if not isinstance(summary, str):
+ raise ValueError(
+ f'{index_path} entry {template_id!r} summary must be a string'
+ )
+ key = f'library:{kind}:{template_id}'
+ if key in candidates:
+ raise ValueError(f'duplicate template candidate key: {key}')
+ candidate = {
+ 'key': key,
+ 'source': 'library',
+ 'kind': kind,
+ 'id': template_id,
+ 'label': template_id,
+ 'summary': summary,
+ 'workspace_root': str(workspace_root),
+ }
+ canonical_root = candidate['workspace_root']
+ if canonical_root in registered_roots:
+ raise ValueError(
+ f'duplicate registered workspace root: {canonical_root}'
+ )
+ group.append(candidate)
+ candidates[key] = candidate
+ registered_roots[canonical_root] = candidate
+ library[kind] = group
+ return library, candidates, registered_roots, index_contracts
+
+
+def _build_template_options(confirm_dir: Path) -> 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 = []
+ preselected_keys = []
+ for root in explicit_roots:
+ canonical_root = str(root)
+ registered = registered_roots.get(canonical_root)
+ if registered is not None:
+ preselected_keys.append(registered['key'])
+ continue
+ digest = hashlib.sha256(canonical_root.encode('utf-8')).hexdigest()
+ key = f'explicit:{digest}'
+ if key in candidates:
+ raise ValueError(f'duplicate template candidate key: {key}')
+ candidate = {
+ 'key': key,
+ 'source': 'explicit',
+ 'label': root.name or canonical_root,
+ 'workspace_root': canonical_root,
+ }
+ explicit.append(candidate)
+ candidates[key] = candidate
+ preselected_keys.append(key)
+
+ response = {
+ 'schema_version': TEMPLATE_SCHEMA_VERSION,
+ 'phase': 'template',
+ 'library': library,
+ 'explicit': explicit,
+ 'preselected_keys': preselected_keys,
+ }
+ if 'lang' in source:
+ response['lang'] = source['lang'].strip()
+ response['options_sha256'] = _json_sha256({
+ 'schema_version': TEMPLATE_SCHEMA_VERSION,
+ 'phase': 'template',
+ 'lang': response.get('lang'),
+ 'explicit_workspace_roots': [str(root) for root in explicit_roots],
+ 'library_indexes': index_contracts,
+ 'library': library,
+ 'explicit': explicit,
+ 'preselected_keys': preselected_keys,
+ })
+ return response, candidates
+
+
+def _template_selection_from_candidate(candidate: dict) -> dict:
+ """Project one trusted browser candidate into the persisted selection."""
+ selection = {
+ 'source': candidate['source'],
+ 'workspace_root': candidate['workspace_root'],
+ }
+ if candidate['source'] == 'library':
+ selection['kind'] = candidate['kind']
+ selection['id'] = candidate['id']
+ return selection
+
+
+def _template_selection_sha256(
+ mode: str,
+ selections: list[dict],
+ options_sha256: str,
+) -> str:
+ """Bind one resolved choice to the candidate/options contract it used."""
+ return _json_sha256({
+ 'mode': mode,
+ 'selections': selections,
+ 'options_sha256': options_sha256,
+ })
+
+
+def _validate_template_selection(data: dict) -> None:
+ """Validate the server-owned template-selection receipt shape."""
+ expected_fields = {
+ 'schema_version',
+ 'phase',
+ 'status',
+ 'mode',
+ 'selections',
+ 'options_sha256',
+ 'selection_sha256',
+ 'confirmed_at',
+ }
+ if set(data) != expected_fields:
+ raise ValueError(f'{TEMPLATE_SELECTION_NAME} has invalid fields')
+ if type(data.get('schema_version')) is not int or data['schema_version'] != TEMPLATE_SCHEMA_VERSION:
+ raise ValueError(
+ f'{TEMPLATE_SELECTION_NAME} schema_version must be {TEMPLATE_SCHEMA_VERSION}'
+ )
+ if data.get('phase') != 'template':
+ raise ValueError(f'{TEMPLATE_SELECTION_NAME} phase must be template')
+ if data.get('status') != 'confirmed':
+ raise ValueError(f'{TEMPLATE_SELECTION_NAME} status must be confirmed')
+ mode = data.get('mode')
+ if mode not in {'free_design', 'templates'}:
+ raise ValueError(
+ f'{TEMPLATE_SELECTION_NAME} mode must be free_design or templates'
+ )
+ selections = data.get('selections')
+ if not isinstance(selections, list):
+ raise ValueError(f'{TEMPLATE_SELECTION_NAME} selections must be an array')
+ if mode == 'free_design' and selections:
+ raise ValueError('free_design cannot carry template selections')
+ if mode == 'templates' and not selections:
+ raise ValueError('templates mode requires at least one selection')
+
+ options_sha256 = data.get('options_sha256')
+ selection_sha256 = data.get('selection_sha256')
+ if not isinstance(options_sha256, str) or not re.fullmatch(r'[0-9a-f]{64}', options_sha256):
+ raise ValueError(f'{TEMPLATE_SELECTION_NAME} options_sha256 is invalid')
+ if not isinstance(selection_sha256, str) or not re.fullmatch(r'[0-9a-f]{64}', selection_sha256):
+ raise ValueError(f'{TEMPLATE_SELECTION_NAME} selection_sha256 is invalid')
+
+ seen_roots = set()
+ for index, selection in enumerate(selections):
+ if not isinstance(selection, dict):
+ raise ValueError(
+ f'{TEMPLATE_SELECTION_NAME} selections[{index}] must be an object'
+ )
+ source = selection.get('source')
+ expected_keys = {'source', 'workspace_root'}
+ if source == 'library':
+ expected_keys.update({'kind', 'id'})
+ if selection.get('kind') not in _TEMPLATE_LIBRARY_CONFIG:
+ raise ValueError(
+ f'{TEMPLATE_SELECTION_NAME} selections[{index}] has invalid kind'
+ )
+ if not _safe_template_id(selection.get('id')):
+ raise ValueError(
+ f'{TEMPLATE_SELECTION_NAME} selections[{index}] has invalid id'
+ )
+ elif source != 'explicit':
+ raise ValueError(
+ f'{TEMPLATE_SELECTION_NAME} selections[{index}] has invalid source'
+ )
+ if set(selection) != expected_keys:
+ raise ValueError(
+ f'{TEMPLATE_SELECTION_NAME} selections[{index}] has invalid fields'
+ )
+ workspace_root = selection.get('workspace_root')
+ if not isinstance(workspace_root, str) or not workspace_root:
+ raise ValueError(
+ f'{TEMPLATE_SELECTION_NAME} selections[{index}] '
+ 'workspace_root must be a non-empty string'
+ )
+ root = Path(workspace_root)
+ if not root.is_absolute() or str(root.resolve()) != workspace_root:
+ raise ValueError(
+ f'{TEMPLATE_SELECTION_NAME} selections[{index}] '
+ 'workspace_root must be a canonical absolute path'
+ )
+ if workspace_root in seen_roots:
+ raise ValueError(
+ f'{TEMPLATE_SELECTION_NAME} contains duplicate workspace root: '
+ f'{workspace_root}'
+ )
+ seen_roots.add(workspace_root)
+ 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'
+ )
+ expected_selection_sha256 = _template_selection_sha256(
+ mode,
+ selections,
+ options_sha256,
+ )
+ if selection_sha256 != expected_selection_sha256:
+ raise ValueError(f'{TEMPLATE_SELECTION_NAME} selection_sha256 does not match')
+
+
+def _read_template_selection(selection_file: Path) -> dict:
+ """Read a selection and revalidate it against current indexed options."""
+ data = _read_json_object(selection_file)
+ _validate_template_selection(data)
+ options, candidates = _build_template_options(selection_file.parent)
+ if data['options_sha256'] != options['options_sha256']:
+ raise ValueError(
+ f'{TEMPLATE_SELECTION_NAME} options_sha256 no longer matches current options'
+ )
+ available_selections = {
+ _json_sha256(_template_selection_from_candidate(candidate))
+ for candidate in candidates.values()
+ }
+ for selection in data['selections']:
+ if _json_sha256(selection) not in available_selections:
+ raise ValueError(
+ f'{TEMPLATE_SELECTION_NAME} references an unavailable candidate'
+ )
+ return data
+
+
+def _validate_template_handoff(data: dict) -> None:
+ """Validate the agent-owned Step-3 completion receipt shape."""
+ expected_fields = {
+ 'schema_version',
+ 'phase',
+ 'status',
+ 'mode',
+ 'selection_sha256',
+ 'completed_at',
+ }
+ if set(data) != expected_fields:
+ raise ValueError(f'{TEMPLATE_HANDOFF_NAME} has invalid fields')
+ if type(data.get('schema_version')) is not int or data['schema_version'] != TEMPLATE_SCHEMA_VERSION:
+ raise ValueError(
+ f'{TEMPLATE_HANDOFF_NAME} schema_version must be {TEMPLATE_SCHEMA_VERSION}'
+ )
+ if data.get('phase') != 'template':
+ raise ValueError(f'{TEMPLATE_HANDOFF_NAME} phase must be template')
+ if data.get('status') != 'ready':
+ raise ValueError(f'{TEMPLATE_HANDOFF_NAME} status must be ready')
+ if data.get('mode') not in {'free_design', 'templates'}:
+ raise ValueError(
+ f'{TEMPLATE_HANDOFF_NAME} mode must be free_design or templates'
+ )
+ selection_sha256 = data.get('selection_sha256')
+ if not isinstance(selection_sha256, str) or not re.fullmatch(r'[0-9a-f]{64}', selection_sha256):
+ raise ValueError(f'{TEMPLATE_HANDOFF_NAME} selection_sha256 is invalid')
+ if not isinstance(data.get('completed_at'), str) or not data['completed_at']:
+ raise ValueError(
+ f'{TEMPLATE_HANDOFF_NAME} completed_at must be a non-empty string'
+ )
+
+
+def _read_template_handoff(project_path: Path, handoff_file: Path) -> dict:
+ """Read a handoff and bind it to the current selection and installed state."""
+ data = _read_json_object(handoff_file)
+ _validate_template_handoff(data)
+ selection = _read_template_selection(handoff_file.parent / TEMPLATE_SELECTION_NAME)
+ if data['mode'] != selection['mode']:
+ raise ValueError(f'{TEMPLATE_HANDOFF_NAME} mode does not match selection')
+ if data['selection_sha256'] != selection['selection_sha256']:
+ raise ValueError(
+ f'{TEMPLATE_HANDOFF_NAME} selection_sha256 does not match selection'
+ )
+ if data['mode'] == 'templates':
+ installed_spec = project_path / 'templates' / 'design_spec.md'
+ if not installed_spec.is_file():
+ raise ValueError(
+ f'{TEMPLATE_HANDOFF_NAME} requires installed template spec: '
+ f'{installed_spec}'
+ )
+ return data
+
+
+def _complete_template_phase(project_path: Path) -> int:
+ """Write the agent-owned handoff after free-design or template application."""
+ confirm_dir = project_path / CONFIRM_DIR_NAME
+ selection_file = confirm_dir / TEMPLATE_SELECTION_NAME
+ if not selection_file.exists():
+ logger.error('%s not found — the user must confirm Step 3 first', selection_file)
+ return 1
+ try:
+ selection = _read_template_selection(selection_file)
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
+ logger.error('cannot complete template phase: %s', exc)
+ return 1
+ if selection['mode'] == 'templates':
+ installed_spec = project_path / 'templates' / 'design_spec.md'
+ if not installed_spec.is_file():
+ logger.error(
+ 'cannot complete template phase before template apply writes %s',
+ installed_spec,
+ )
+ return 1
+
+ handoff_file = confirm_dir / TEMPLATE_HANDOFF_NAME
+ if handoff_file.exists():
+ try:
+ existing = _read_template_handoff(project_path, handoff_file)
+ except (OSError, json.JSONDecodeError, ValueError):
+ existing = None
+ if (
+ existing is not None
+ and existing['selection_sha256'] == selection['selection_sha256']
+ ):
+ logger.info('template phase already complete: %s', handoff_file)
+ return 0
+
+ handoff = {
+ 'schema_version': TEMPLATE_SCHEMA_VERSION,
+ 'phase': 'template',
+ 'status': 'ready',
+ 'mode': selection['mode'],
+ 'selection_sha256': selection['selection_sha256'],
+ 'completed_at': time.strftime('%Y-%m-%dT%H:%M:%S'),
+ }
+ _validate_template_handoff(handoff)
+ _write_json_atomic(handoff_file, handoff)
+ logger.info('template phase handoff written to %s', handoff_file)
+ return 0
+
+
+def _reset_template_phase(confirm_dir: Path) -> int:
+ """Remove only the two mutable Step-3 receipts so the user may reselect."""
+ removed = []
+ for filename in (TEMPLATE_SELECTION_NAME, TEMPLATE_HANDOFF_NAME):
+ path = confirm_dir / filename
+ try:
+ path.unlink()
+ removed.append(str(path))
+ except FileNotFoundError:
+ continue
+ except OSError as exc:
+ logger.error('cannot remove %s: %s', path, exc)
+ return 1
+ if removed:
+ logger.info('reset template phase receipts: %s', ', '.join(removed))
+ else:
+ logger.info('template phase receipts already absent')
+ return 0
+
+
+def _template_stage1_ready_error(project_path: Path, confirm_dir: Path) -> Optional[str]:
+ """Return why Step 3 has not safely handed off to a fresh Stage 1."""
+ selection_file = confirm_dir / TEMPLATE_SELECTION_NAME
+ if not selection_file.exists():
+ return f'{TEMPLATE_SELECTION_NAME} not found'
+ try:
+ _read_template_selection(selection_file)
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
+ return f'invalid template selection: {exc}'
+
+ handoff_file = confirm_dir / TEMPLATE_HANDOFF_NAME
+ if not handoff_file.exists():
+ return f'{TEMPLATE_HANDOFF_NAME} not found'
+ try:
+ _read_template_handoff(project_path, handoff_file)
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
+ return f'invalid template handoff: {exc}'
+
+ stage1_file = confirm_dir / RECOMMENDATION_STAGE_NAMES[1]
+ if not stage1_file.exists():
+ return f'{stage1_file.name} not found after template handoff'
+ try:
+ stage1_data = _read_json_object(stage1_file)
+ if _recommendation_stage(stage1_data) != 1:
+ return f'{stage1_file.name} does not declare stage1'
+ if stage1_file.stat().st_mtime_ns < handoff_file.stat().st_mtime_ns:
+ return f'{stage1_file.name} is older than {TEMPLATE_HANDOFF_NAME}'
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
+ return f'cannot validate fresh Stage 1 recommendations: {exc}'
+ return None
+
+
+def _resolve_template_confirmation(
+ payload: dict,
+ candidates: dict[str, dict],
+ options_sha256: str,
+) -> dict:
+ """Resolve browser keys against the current server-owned candidate set."""
+ required_fields = {'mode', 'selection_keys'}
+ if set(payload) != required_fields:
+ raise ValueError('template confirmation accepts only mode and selection_keys')
+ mode = payload.get('mode')
+ if mode not in {'free_design', 'templates'}:
+ raise ValueError('mode must be free_design or templates')
+ selection_keys = payload.get('selection_keys')
+ if not isinstance(selection_keys, list):
+ raise ValueError('selection_keys must be an array')
+ if any(not isinstance(key, str) or not key for key in selection_keys):
+ raise ValueError('selection_keys must contain non-empty strings')
+ if len(selection_keys) != len(set(selection_keys)):
+ raise ValueError('selection_keys must not contain duplicates')
+ if mode == 'free_design' and selection_keys:
+ raise ValueError('free_design cannot carry selection_keys')
+ if mode == 'templates' and not selection_keys:
+ raise ValueError('templates mode requires at least one selection key')
+
+ unknown_keys = [key for key in selection_keys if key not in candidates]
+ if unknown_keys:
+ raise ValueError(
+ 'selection_keys contains unavailable candidate keys: '
+ + ', '.join(unknown_keys)
+ )
+ selections = sorted([
+ _template_selection_from_candidate(candidates[key])
+ for key in selection_keys
+ ], key=lambda item: (
+ item['source'],
+ item.get('kind', ''),
+ item.get('id', ''),
+ item['workspace_root'],
+ ))
+ selection_sha256 = _template_selection_sha256(
+ mode,
+ selections,
+ options_sha256,
+ )
+ receipt = {
+ 'schema_version': TEMPLATE_SCHEMA_VERSION,
+ 'phase': 'template',
+ 'status': 'confirmed',
+ 'mode': mode,
+ 'selections': selections,
+ 'options_sha256': options_sha256,
+ 'selection_sha256': selection_sha256,
+ 'confirmed_at': time.strftime('%Y-%m-%dT%H:%M:%S'),
+ }
+ _validate_template_selection(receipt)
+ return receipt
+
+
+def _confirmation_launch_error(
+ confirm_dir: Path,
+ *,
+ require_template: bool = False,
+) -> Optional[str]:
+ """Return why neither the template phase nor current Strategist stage can launch."""
+ options_file = confirm_dir / TEMPLATE_OPTIONS_NAME
+ if options_file.exists():
+ try:
+ _build_template_options(confirm_dir)
+ selection_file = confirm_dir / TEMPLATE_SELECTION_NAME
+ if selection_file.exists():
+ _read_template_selection(selection_file)
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
+ return f'invalid template phase input: {exc}'
+ return None
+ if require_template:
+ return f'{options_file} not found — cannot start the template phase'
+
+ rec_file = _active_recommendations_path(confirm_dir)
+ if rec_file.exists():
+ return None
+ return (
+ f'{rec_file} and {options_file} not found — write template options or '
+ 'the current Strategist recommendation before launch'
+ )
+
+
def _server_url(port: int, path: str = '') -> str:
"""Return the loopback URL shown to users and used by readiness probes."""
suffix = path if path.startswith('/') or not path else f'/{path}'
@@ -332,6 +931,42 @@ def _wait_for_result(
time.sleep(0.5)
+def _wait_for_template_selection(
+ selection_file: Path,
+ proc: subprocess.Popen,
+ started_at: float,
+ timeout: int,
+) -> int:
+ """Wait until this launch writes a fresh template-selection receipt."""
+ logger.info('waiting for browser template selection...')
+ deadline = None if timeout <= 0 else time.time() + timeout
+ while True:
+ if selection_file.exists():
+ try:
+ if selection_file.stat().st_mtime >= started_at:
+ _read_template_selection(selection_file)
+ logger.info('template selection received: %s', selection_file)
+ return 0
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
+ logger.error('invalid template selection: %s', exc)
+ return 2
+
+ returncode = proc.poll()
+ if returncode is not None:
+ logger.error('confirm UI exited before a fresh template selection was written')
+ return returncode or 1
+
+ if deadline is not None and time.time() >= deadline:
+ logger.error(
+ 'timed out waiting for template selection — the page is still '
+ 'open; re-check %s before falling back to chat',
+ selection_file,
+ )
+ return 124
+
+ time.sleep(0.5)
+
+
def _result_stage(result_file: Path) -> Optional[str]:
"""Return the canonical ``stage`` field of result.json, or None."""
if not result_file.is_file():
@@ -1090,8 +1725,9 @@ def _build_session_state(
status = 'ready_user' if ready else 'waiting_agent'
current_stage = rec_stage if ready else 'stage1'
- return {
+ session = {
'session_id': previous.get('session_id') or uuid.uuid4().hex,
+ 'phase': 'strategist',
'status': status,
'current_stage': current_stage,
'stage_skip': stage_skip,
@@ -1109,6 +1745,77 @@ def _build_session_state(
'event': event or previous.get('event') or 'derived',
}
+ options_file = confirm_dir / TEMPLATE_OPTIONS_NAME
+ selection_file = confirm_dir / TEMPLATE_SELECTION_NAME
+ handoff_file = confirm_dir / TEMPLATE_HANDOFF_NAME
+ if not options_file.exists():
+ return session
+
+ session.update({
+ 'template_options_file': TEMPLATE_OPTIONS_NAME,
+ 'template_options_version': _file_version(options_file),
+ 'template_selection_file': TEMPLATE_SELECTION_NAME,
+ 'template_selection_version': _file_version(selection_file),
+ 'template_handoff_file': TEMPLATE_HANDOFF_NAME,
+ 'template_handoff_version': _file_version(handoff_file),
+ })
+ try:
+ _build_template_options(confirm_dir)
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
+ session.update({
+ 'phase': 'template',
+ 'status': 'error',
+ 'current_stage': 'template',
+ 'expected_stage': 'template',
+ 'expected_stage_number': None,
+ 'template_status': 'error',
+ 'template_error': str(exc),
+ })
+ return session
+
+ if selection_file.exists():
+ try:
+ _read_template_selection(selection_file)
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
+ session.update({
+ 'phase': 'template',
+ 'status': 'waiting_agent',
+ 'current_stage': 'template',
+ 'expected_stage': 'template',
+ 'expected_stage_number': None,
+ 'template_status': 'invalid',
+ 'template_error': str(exc),
+ })
+ return session
+ ready_error = _template_stage1_ready_error(
+ confirm_dir.parent,
+ confirm_dir,
+ )
+ if ready_error is None:
+ session['template_status'] = 'ready'
+ return session
+ session.update({
+ 'phase': 'template',
+ 'status': 'waiting_agent',
+ 'current_stage': 'template',
+ 'expected_stage': 'stage1',
+ 'expected_stage_number': 1,
+ 'template_status': 'confirmed',
+ 'template_error': ready_error,
+ })
+ return session
+
+ session.update({
+ 'phase': 'template',
+ 'status': 'ready_user',
+ 'current_stage': 'template',
+ 'expected_stage': 'template',
+ 'expected_stage_number': None,
+ 'template_status': 'ready_user',
+ 'template_error': None,
+ })
+ return session
+
def _write_session_state(confirm_dir: Path, session: dict) -> None:
"""Persist session.json only when stable state changes."""
@@ -1398,6 +2105,52 @@ def _wait_result_status(
return None
+def _wait_template_selection_status(selection_file: Path) -> Optional[int]:
+ """Return a terminal wait status for the template-selection receipt."""
+ if not selection_file.exists():
+ return None
+ try:
+ _read_template_selection(selection_file)
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
+ logger.error('invalid template selection: %s', exc)
+ return 2
+ logger.info('template selection received: %s', selection_file)
+ return 0
+
+
+def _wait_only_for_template_selection(
+ selection_file: Path,
+ lock_file: Path,
+ timeout: int,
+) -> int:
+ """Attach to the running page and wait for Step-3 template selection."""
+ logger.info('waiting for browser template selection...')
+ deadline = None if timeout <= 0 else time.time() + timeout
+ while True:
+ selection_status = _wait_template_selection_status(selection_file)
+ if selection_status is not None:
+ return selection_status
+
+ lock = _read_lock(lock_file)
+ pid = _lock_pid(lock)
+ if not pid or not _process_alive(pid):
+ logger.error(
+ 'confirm server is no longer running before template selection '
+ 'was confirmed'
+ )
+ return 1
+
+ if deadline is not None and time.time() >= deadline:
+ logger.error(
+ 'timed out waiting for template selection — the page may still '
+ 'be open; re-check %s before falling back to chat',
+ selection_file,
+ )
+ return 124
+
+ time.sleep(0.5)
+
+
def _shutdown_existing(lock_file: Path) -> int:
"""Stop a confirm server left running for this project (idempotent).
@@ -1625,7 +2378,7 @@ def create_app(
@app.route('/api/session')
def get_session():
- """Expose the derived three-stage wizard state for browser polling."""
+ """Expose the derived template/Strategist wizard state for polling."""
session = _sync_session_state(
confirm_dir,
server_port=app.config.get('SERVER_PORT'),
@@ -1635,6 +2388,66 @@ def create_app(
resp.headers['Cache-Control'] = 'no-store'
return resp
+ @app.route('/api/template-options')
+ def get_template_options():
+ """Serve indexed library groups and agent-supplied explicit candidates."""
+ options_file = confirm_dir / TEMPLATE_OPTIONS_NAME
+ if not options_file.exists():
+ return jsonify({'error': f'{TEMPLATE_OPTIONS_NAME} not found'}), 404
+ try:
+ data, _ = _build_template_options(confirm_dir)
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
+ return jsonify({'error': f'invalid template options: {exc}'}), 409
+ resp = jsonify(data)
+ resp.headers['Cache-Control'] = 'no-store'
+ return resp
+
+ @app.route('/api/template-confirm', methods=['POST'])
+ def confirm_template():
+ """Persist a template choice resolved only from current candidate keys."""
+ payload = request.get_json(silent=True)
+ if not isinstance(payload, dict):
+ return jsonify({'error': 'invalid payload'}), 400
+ try:
+ options, candidates = _build_template_options(confirm_dir)
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
+ return jsonify({'error': f'invalid template options: {exc}'}), 409
+ try:
+ receipt = _resolve_template_confirmation(
+ payload,
+ candidates,
+ options['options_sha256'],
+ )
+ except ValueError as exc:
+ return jsonify({'error': str(exc)}), 400
+ selection_file = confirm_dir / TEMPLATE_SELECTION_NAME
+ if selection_file.exists():
+ try:
+ existing = _read_template_selection(selection_file)
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
+ return jsonify({
+ 'error': (
+ f'existing template selection is invalid: {exc}; '
+ 'the agent must run --reset-template-phase'
+ ),
+ }), 409
+ if existing['selection_sha256'] == receipt['selection_sha256']:
+ return jsonify({'status': 'ok', 'idempotent': True})
+ return jsonify({
+ 'error': (
+ 'template phase is already confirmed with a different '
+ 'selection; the agent must run --reset-template-phase'
+ ),
+ }), 409
+ _write_json_atomic(selection_file, receipt)
+ _sync_session_state(
+ confirm_dir,
+ server_port=app.config.get('SERVER_PORT'),
+ event='template-submitted',
+ )
+ logger.info('template selection written to %s', selection_file)
+ return jsonify({'status': 'ok'})
+
@app.route('/api/catalogs')
def get_catalogs():
"""Serve the option universe; canvas is synced live from config.py so
@@ -1764,6 +2577,15 @@ def create_app(
stage = _stage_key(raw_stage)
if raw_stage is not None and stage is None:
return jsonify({'error': 'invalid confirmation stage'}), 400
+ if stage == 'stage1' and (confirm_dir / TEMPLATE_OPTIONS_NAME).exists():
+ template_error = _template_stage1_ready_error(
+ project_path,
+ confirm_dir,
+ )
+ if template_error:
+ return jsonify({
+ 'error': f'template phase is not ready for Stage 1: {template_error}',
+ }), 409
stage_error = _submission_stage_error(
project_path,
confirm_dir,
@@ -1871,7 +2693,7 @@ def create_app(
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
- description='PPT Master Strategist confirmation stage UI',
+ description='PPT Master template and Strategist confirmation UI',
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument('project_dir', help='Path to project directory')
@@ -1886,20 +2708,21 @@ def build_parser() -> argparse.ArgumentParser:
)
parser.add_argument(
'--wait', action='store_true',
- help='With --daemon, wait until a fresh result.json is written',
+ help='With --daemon, wait until the requested template/result receipt is written',
)
parser.add_argument(
'--wait-only', action='store_true',
help='Attach to the confirm server for this project and wait for an '
- 'already-open page to write result.json. If the target result is '
+ 'already-open page to write the requested receipt. If it is '
'already persisted, return without recovery; otherwise recover a '
'dead server on the recorded/default port so browser polling can resume.',
)
parser.add_argument(
- '--wait-stage', default='final', metavar='{stage1,stage2,final}',
- help='With --wait-only, wait for this result.json stage (default: final). '
- 'Use stage1 after the initial daemon launch and chat handoff; use '
- 'stage2 for the direction handoff.',
+ '--wait-stage', default='final', metavar='{template,stage1,stage2,final}',
+ help='Wait for the Step-3 template selection or this result.json stage '
+ '(default: final). Use template after the initial template-phase '
+ 'launch, stage1 after its Strategist handoff, and stage2 for the '
+ 'direction handoff.',
)
parser.add_argument(
'--wait-timeout', type=int, default=WAIT_TIMEOUT_DEFAULT,
@@ -1916,6 +2739,16 @@ def build_parser() -> argparse.ArgumentParser:
'(idempotent). Run at the end of Step 4 so the page never lingers '
'on its selected port before live preview starts.',
)
+ parser.add_argument(
+ '--complete-template-phase', action='store_true',
+ help='Agent-only: bind the current template selection to a ready handoff. '
+ 'Template mode requires <project>/templates/design_spec.md.',
+ )
+ parser.add_argument(
+ '--reset-template-phase', action='store_true',
+ help='Agent-only: remove exactly template_selection.json and '
+ 'template_handoff.json so the user may select again.',
+ )
return parser
@@ -1940,33 +2773,63 @@ def main(argv: Optional[list[str]] = None) -> int:
if not project_path.is_dir():
logger.error('%s is not a directory', project_path)
return 1
- wait_stage = _stage_key(args.wait_stage)
- if wait_stage not in {'stage1', 'stage2', 'final'}:
- logger.error('--wait-stage must be stage1, stage2, or final')
+ raw_wait_stage = str(args.wait_stage).strip().lower()
+ wait_stage = 'template' if raw_wait_stage == 'template' else _stage_key(raw_wait_stage)
+ if wait_stage not in {'template', 'stage1', 'stage2', 'final'}:
+ logger.error('--wait-stage must be template, stage1, stage2, or final')
+ return 2
+
+ template_control = args.complete_template_phase or args.reset_template_phase
+ if template_control and (
+ args.daemon or args.wait or args.wait_only or args.shutdown
+ ):
+ logger.error(
+ '--complete-template-phase/--reset-template-phase cannot be combined '
+ 'with server, wait, or shutdown actions'
+ )
+ return 2
+ if args.complete_template_phase and args.reset_template_phase:
+ logger.error(
+ '--complete-template-phase and --reset-template-phase are mutually exclusive'
+ )
return 2
+ if args.complete_template_phase:
+ return _complete_template_phase(project_path)
+ if args.reset_template_phase:
+ return _reset_template_phase(project_path / CONFIRM_DIR_NAME)
# Step 4 cleanup: stop any lingering confirm server and exit. Independent of
# recommendation files (the page may never have been confirmed).
if args.shutdown:
return _shutdown_existing(project_path / LOCK_FILE_NAME)
- # Staged wait: attach to the server launched by --daemon and block
- # until the page writes the requested intermediate or final result.json.
+ # Staged wait: attach to the server launched by --daemon and block until
+ # the page writes the requested template or Strategist receipt.
if args.wait_only:
lock_file = project_path / LOCK_FILE_NAME
- result_file = project_path / CONFIRM_DIR_NAME / RESULT_NAME
- if not _live_lock(lock_file):
- confirm_dir = project_path / CONFIRM_DIR_NAME
- result_status = _wait_result_status(result_file, wait_stage)
- if result_status is not None:
- return result_status
- rec_file = _active_recommendations_path(confirm_dir)
- if not rec_file.exists():
- logger.error(
- '%s not found — cannot recover confirm UI before wait-only',
- rec_file,
- )
+ confirm_dir = project_path / CONFIRM_DIR_NAME
+ result_file = confirm_dir / RESULT_NAME
+ selection_file = confirm_dir / TEMPLATE_SELECTION_NAME
+ if wait_stage == 'template':
+ wait_status = _wait_template_selection_status(selection_file)
+ if wait_status is not None:
+ return wait_status
+ launch_error = _confirmation_launch_error(
+ confirm_dir,
+ require_template=True,
+ )
+ if launch_error:
+ logger.error('%s', launch_error)
return 1
+ if not _live_lock(lock_file):
+ if wait_stage != 'template':
+ wait_status = _wait_result_status(result_file, wait_stage)
+ if wait_status is not None:
+ return wait_status
+ launch_error = _confirmation_launch_error(confirm_dir)
+ if launch_error:
+ logger.error('%s', launch_error)
+ return 1
exact_port = args.port is not None
recovery_port = (
args.port
@@ -1990,6 +2853,12 @@ def main(argv: Optional[list[str]] = None) -> int:
'recovered confirm UI for wait-only at %s; the browser polling should resume',
_server_url(actual_port),
)
+ if wait_stage == 'template':
+ return _wait_only_for_template_selection(
+ selection_file,
+ lock_file,
+ args.wait_timeout,
+ )
return _wait_only_for_result(
result_file,
lock_file,
@@ -1998,12 +2867,12 @@ def main(argv: Optional[list[str]] = None) -> int:
)
confirm_dir = project_path / CONFIRM_DIR_NAME
- rec_file = _active_recommendations_path(confirm_dir)
- if not rec_file.exists():
- logger.error(
- '%s not found — Strategist must write the current recommendation stage before launch',
- rec_file,
- )
+ launch_error = _confirmation_launch_error(
+ confirm_dir,
+ require_template=args.daemon and args.wait and wait_stage == 'template',
+ )
+ if launch_error:
+ logger.error('%s', launch_error)
return 1
if args.daemon:
@@ -2021,6 +2890,7 @@ def main(argv: Optional[list[str]] = None) -> int:
confirm_dir = project_path / CONFIRM_DIR_NAME
result_file = confirm_dir / RESULT_NAME
+ selection_file = confirm_dir / TEMPLATE_SELECTION_NAME
expected_stage = _expected_result_stage(confirm_dir)
started_at = time.time()
try:
@@ -2035,6 +2905,13 @@ def main(argv: Optional[list[str]] = None) -> int:
logger.error('%s', exc)
return 1
if args.wait:
+ if wait_stage == 'template':
+ return _wait_for_template_selection(
+ selection_file,
+ proc,
+ started_at,
+ args.wait_timeout,
+ )
return _wait_for_result(
result_file,
proc,
diff --git a/skills/ppt-master/scripts/confirm_ui/static/app.js b/skills/ppt-master/scripts/confirm_ui/static/app.js
index 1ee90796..65306bba 100644
--- a/skills/ppt-master/scripts/confirm_ui/static/app.js
+++ b/skills/ppt-master/scripts/confirm_ui/static/app.js
@@ -1,9 +1,10 @@
-/* PPT Master - Strategist confirmation stage UI
- * Stage 1 captures the communication contract, Stage 2 confirms a coherent
- * deck solution, and Stage 3 resolves production mechanics. Finite fields use
- * /static/catalogs.json; coordinated design directions seed color, typography,
- * icons, generated-image rendering, and conditional template-application prose.
- * Final confirm saves result.json.
+/* PPT Master - template selection and Strategist confirmation UI
+ * Generate Step 3 independently selects free design or exact template
+ * candidates before Stage 1 captures the communication contract. Stage 2 then
+ * confirms a coherent deck solution, and Stage 3 resolves production mechanics.
+ * Finite fields use /static/catalogs.json; coordinated design directions seed
+ * color, typography, icons, generated-image rendering, and conditional
+ * template-application prose. Final confirm saves result.json.
*/
(function () {
"use strict";
@@ -13,20 +14,45 @@
en: {
page_title: "PPT Master - Confirm Design",
topbar_hint: "Answer the open questions, or pick and customize recommendations, then continue.",
+ template_stage_title: "Choose a template",
+ template_stage_hint: "Choose free design or one or more exact templates. This selection is separate from Stage 1.",
stage_anchors: "Stage 1 · Communication contract",
stage_design: "Stage 2 · Deck direction & visual system",
stage_images: "Stage 3 · Resources & production",
loading: "Loading…",
load_error: "Could not load the current recommendation stage. The AI must write it before launch.",
btn_confirm: "Confirm",
+ btn_confirm_template: "Confirm template & continue →",
btn_confirm_contract: "Confirm contract & continue →",
btn_confirm_solution: "Confirm solution & continue →",
deriving: "Generating the downstream options from your choices…",
+ template_applying: "Applying the template selection and preparing Stage 1…",
+ template_load_error: "Could not load the available templates.",
+ template_submit_error: "Could not confirm the template selection.",
+ template_selection_required: "Choose free design or at least one template.",
+ template_free_selected: "Free design selected",
+ template_count_selected: "{count} template(s) selected",
connection_lost: "Connection to the confirm server was interrupted; retrying. If this keeps failing, return to the chat for confirmation.",
already_confirmed: "Already confirmed once. Re-submitting overwrites the previous choices.",
confirmed_title: "✓ Confirmed",
confirmed_hint: "Your choices are saved. You can close this page and return to the chat.",
lang_toggle_title: "Switch language",
+ sec_template_free: "Free design",
+ template_free_title: "Design from the current content",
+ template_free_desc: "Use no reusable template workspace. The Strategist will derive the visual system from this project.",
+ sec_template_library: "Existing templates",
+ template_library_hint: "Select any compatible registered Brand, Style, Layout, or Deck workspaces. Multiple selections are allowed.",
+ sec_template_explicit: "Specified templates",
+ template_explicit_hint: "Exact unregistered workspace roots supplied for this run. Their source paths are shown for verification.",
+ template_kind_brand: "Brand",
+ template_kind_style: "Style",
+ template_kind_layout: "Layout",
+ template_kind_deck: "Deck",
+ template_source_library: "Library",
+ template_source_explicit: "Specified",
+ template_source_path: "Source path",
+ template_none_registered: "No registered templates",
+ template_none_explicit: "No specified templates for this run",
sec_canvas: "Canvas format",
sec_pages: "Page count",
sec_audience: "Target audience",
@@ -173,20 +199,45 @@
ja: {
page_title: "PPT Master - デザイン確認",
topbar_hint: "自由記述の質問に答えるか、提案を選択・調整して次へ進んでください。",
+ template_stage_title: "テンプレートを選択",
+ template_stage_hint: "自由デザイン、または使用する正確なテンプレートを選択します。この選択はステージ1とは独立しています。",
stage_anchors: "ステージ 1 · コミュニケーション契約",
stage_design: "ステージ 2 · 全体方針とビジュアルシステム",
stage_images: "ステージ 3 · リソースと制作",
loading: "読み込み中…",
load_error: "現在の推奨ステージを読み込めませんでした。起動前にAIが書き込む必要があります。",
btn_confirm: "確定",
+ btn_confirm_template: "テンプレートを確定して次へ →",
btn_confirm_contract: "契約内容を確定して次へ →",
btn_confirm_solution: "全体方針を確定して次へ →",
deriving: "選択内容をもとに後続の選択肢を生成しています…",
+ template_applying: "テンプレートの選択を適用し、ステージ1を準備しています…",
+ template_load_error: "利用可能なテンプレートを読み込めませんでした。",
+ template_submit_error: "テンプレートの選択を確定できませんでした。",
+ template_selection_required: "自由デザイン、または1つ以上のテンプレートを選択してください。",
+ template_free_selected: "自由デザインを選択中",
+ template_count_selected: "{count} 件のテンプレートを選択中",
connection_lost: "確認ページのサーバー接続が中断されました。再試行しています。失敗が続く場合はチャットで確認してください。",
already_confirmed: "すでに一度確定済みです。再送信すると前回の選択を上書きします。",
confirmed_title: "✓ 確定しました",
confirmed_hint: "選択内容を保存しました。このページを閉じてチャットに戻ってください。",
lang_toggle_title: "言語を切り替え",
+ sec_template_free: "自由デザイン",
+ template_free_title: "現在の内容からデザインする",
+ template_free_desc: "再利用テンプレートを使わず、Strategist がこのプロジェクトからビジュアルシステムを組み立てます。",
+ sec_template_library: "既存のテンプレート",
+ template_library_hint: "登録済みの Brand、Style、Layout、Deck から互換性のあるものを選択します。複数選択できます。",
+ sec_template_explicit: "指定テンプレート",
+ template_explicit_hint: "この実行で指定された未登録の正確なワークスペースです。確認用に参照元パスを表示します。",
+ template_kind_brand: "Brand",
+ template_kind_style: "Style",
+ template_kind_layout: "Layout",
+ template_kind_deck: "Deck",
+ template_source_library: "ライブラリ",
+ template_source_explicit: "指定テンプレート",
+ template_source_path: "参照元パス",
+ template_none_registered: "登録済みテンプレートはありません",
+ template_none_explicit: "この実行で指定されたテンプレートはありません",
sec_canvas: "キャンバス形式",
sec_pages: "ページ数",
sec_audience: "想定読者",
@@ -333,20 +384,45 @@
zh: {
page_title: "确认设计方案",
topbar_hint: "回答开放问题,或选择并调整推荐项,然后继续。",
+ template_stage_title: "选择模板",
+ template_stage_hint: "选择自由设计或一个/多个精确模板。这个选择独立于 Stage 1。",
stage_anchors: "第一阶段 · 沟通契约",
stage_design: "第二阶段 · 完整方案与视觉系统",
stage_images: "第三阶段 · 资源与生产执行",
loading: "加载中…",
load_error: "无法加载推荐文件,需在启动前写入。",
btn_confirm: "确认",
+ btn_confirm_template: "确认模板并继续 →",
btn_confirm_contract: "确认沟通契约并继续 →",
btn_confirm_solution: "确认完整方案并继续 →",
deriving: "正在根据你的选择生成下游选项…",
+ template_applying: "正在应用模板选择并准备 Stage 1…",
+ template_load_error: "无法加载可用模板。",
+ template_submit_error: "无法确认模板选择。",
+ template_selection_required: "请选择自由设计或至少一个模板。",
+ template_free_selected: "已选择自由设计",
+ template_count_selected: "已选择 {count} 个模板",
connection_lost: "确认页服务连接中断,正在重试;如果持续失败,请回到聊天窗口走聊天确认。",
already_confirmed: "已确认过一次,重新提交会覆盖之前的选择。",
confirmed_title: "✓ 已确认",
confirmed_hint: "选择已保存,可关闭此页并回到聊天窗口。",
lang_toggle_title: "切换语言",
+ sec_template_free: "自由设计",
+ template_free_title: "根据当前内容从零设计",
+ template_free_desc: "不使用可复用模板工作区,由 Strategist 根据当前项目推导视觉系统。",
+ sec_template_library: "已有模板",
+ template_library_hint: "从已注册的 Brand、Style、Layout、Deck 中选择兼容模板;支持多选。",
+ sec_template_explicit: "指定模板",
+ template_explicit_hint: "本次运行明确提供的未注册工作区;显示来源路径供你核对。",
+ template_kind_brand: "Brand",
+ template_kind_style: "Style",
+ template_kind_layout: "Layout",
+ template_kind_deck: "Deck",
+ template_source_library: "模板库",
+ template_source_explicit: "指定模板",
+ template_source_path: "来源路径",
+ template_none_registered: "暂无已注册模板",
+ template_none_explicit: "本次运行没有指定模板",
sec_canvas: "画布格式",
sec_pages: "页数",
sec_audience: "目标受众",
@@ -618,6 +694,13 @@
var ICON_PREVIEWS = {}; // /api/icon-previews — real SVG samples from templates/icons
var AI_IMAGE_COMPARISON = {}; // /api/ai-image-comparison — preset rendering catalog
var STATE = {};
+ var TEMPLATE_KINDS = ["brand", "style", "layout", "deck"];
+ var TEMPLATE_OPTIONS = null;
+ var TEMPLATE_CANDIDATES = [];
+ var TEMPLATE_SELECTED_KEYS = [];
+ var TEMPLATE_MODE = "free_design";
+ var TEMPLATE_PHASE = false;
+ var TEMPLATE_SUBMITTING = false;
var REC_ALIASES = {
icons: {
line: "tabler-outline",
@@ -769,6 +852,195 @@
note.textContent = text;
}
+ // ---- Step 3 template selection ---------------------------------------
+ function normalizeTemplateCandidates(raw, source, kind) {
+ if (!Array.isArray(raw)) return [];
+ return raw.filter(function (candidate) {
+ return candidate && candidate.key != null && String(candidate.key).trim();
+ }).map(function (candidate) {
+ var normalized = Object.assign({}, candidate);
+ normalized.key = String(candidate.key);
+ normalized.source = source;
+ if (kind) normalized.kind = kind;
+ return normalized;
+ });
+ }
+
+ function initTemplateOptions(data) {
+ var library = data && data.library && typeof data.library === "object"
+ ? data.library : {};
+ var normalized = {
+ lang: data && data.lang,
+ library: {},
+ explicit: [],
+ preselected_keys: Array.isArray(data && data.preselected_keys)
+ ? data.preselected_keys.map(String) : []
+ };
+ TEMPLATE_CANDIDATES = [];
+ TEMPLATE_KINDS.forEach(function (kind) {
+ var candidates = normalizeTemplateCandidates(library[kind], "library", kind);
+ normalized.library[kind] = candidates;
+ TEMPLATE_CANDIDATES = TEMPLATE_CANDIDATES.concat(candidates);
+ });
+ normalized.explicit = normalizeTemplateCandidates(data && data.explicit, "explicit", "");
+ TEMPLATE_CANDIDATES = TEMPLATE_CANDIDATES.concat(normalized.explicit);
+ var validKeys = TEMPLATE_CANDIDATES.map(function (candidate) { return candidate.key; });
+ TEMPLATE_SELECTED_KEYS = normalized.preselected_keys.filter(function (key, index, all) {
+ return validKeys.indexOf(key) >= 0 && all.indexOf(key) === index;
+ });
+ TEMPLATE_MODE = TEMPLATE_SELECTED_KEYS.length ? "templates" : "free_design";
+ TEMPLATE_OPTIONS = normalized;
+ }
+
+ function templateCandidateTitle(candidate) {
+ return localized(candidate, "label") || candidate.label || candidate.id || candidate.key;
+ }
+
+ function templateCandidateSummary(candidate) {
+ return localized(candidate, "summary") || candidate.summary || "";
+ }
+
+ function templateKindLabel(kind) {
+ return t("template_kind_" + kind);
+ }
+
+ function templateKeySelected(key) {
+ return TEMPLATE_SELECTED_KEYS.indexOf(String(key)) >= 0;
+ }
+
+ function chooseFreeDesign() {
+ TEMPLATE_MODE = "free_design";
+ TEMPLATE_SELECTED_KEYS = [];
+ renderTemplatePhase();
+ }
+
+ function toggleTemplateKey(key) {
+ key = String(key);
+ var index = TEMPLATE_SELECTED_KEYS.indexOf(key);
+ if (index >= 0) TEMPLATE_SELECTED_KEYS.splice(index, 1);
+ else TEMPLATE_SELECTED_KEYS.push(key);
+ TEMPLATE_MODE = TEMPLATE_SELECTED_KEYS.length ? "templates" : "free_design";
+ renderTemplatePhase();
+ }
+
+ function templateSourceBadge(source) {
+ return el(
+ "span",
+ "template-source-badge template-source-" + source,
+ t(source === "explicit" ? "template_source_explicit" : "template_source_library")
+ );
+ }
+
+ function templateCandidateCard(candidate) {
+ var selected = templateKeySelected(candidate.key);
+ var card = el("button", "template-card" + (selected ? " selected" : ""));
+ card.type = "button";
+ card.setAttribute("aria-pressed", selected ? "true" : "false");
+ card.setAttribute("data-template-key", candidate.key);
+
+ var head = el("span", "template-card-head");
+ head.appendChild(el("span", "template-card-title", templateCandidateTitle(candidate)));
+ var badges = el("span", "template-card-badges");
+ badges.appendChild(templateSourceBadge(candidate.source));
+ if (candidate.source === "library" && candidate.kind) {
+ badges.appendChild(el("span", "template-kind-badge", templateKindLabel(candidate.kind)));
+ }
+ head.appendChild(badges);
+ card.appendChild(head);
+
+ var summary = templateCandidateSummary(candidate);
+ if (summary) card.appendChild(el("span", "template-card-summary", summary));
+ if (candidate.source === "explicit") {
+ var path = el("span", "template-card-path");
+ path.appendChild(el("span", "template-card-path-label", t("template_source_path") + ":"));
+ path.appendChild(el("code", "template-card-path-value", candidate.workspace_root || ""));
+ card.appendChild(path);
+ }
+ card.addEventListener("click", function () { toggleTemplateKey(candidate.key); });
+ return card;
+ }
+
+ function renderTemplateFreeDesign(host) {
+ var sec = section("F", "sec_template_free");
+ var selected = TEMPLATE_MODE === "free_design";
+ var card = el("button", "template-card template-free-card" + (selected ? " selected" : ""));
+ card.type = "button";
+ card.setAttribute("aria-pressed", selected ? "true" : "false");
+ card.appendChild(el("span", "template-card-title", t("template_free_title")));
+ card.appendChild(el("span", "template-card-summary", t("template_free_desc")));
+ card.addEventListener("click", chooseFreeDesign);
+ sec.appendChild(card);
+ host.appendChild(sec);
+ }
+
+ function renderTemplateLibrary(host) {
+ var sec = section("L", "sec_template_library", t("template_library_hint"));
+ TEMPLATE_KINDS.forEach(function (kind) {
+ var group = el("div", "template-kind-group");
+ group.appendChild(el("h3", "template-kind-title", templateKindLabel(kind)));
+ var candidates = TEMPLATE_OPTIONS.library[kind] || [];
+ if (!candidates.length) {
+ group.appendChild(el("div", "template-empty", t("template_none_registered")));
+ } else {
+ var grid = el("div", "template-card-grid");
+ candidates.forEach(function (candidate) {
+ grid.appendChild(templateCandidateCard(candidate));
+ });
+ group.appendChild(grid);
+ }
+ sec.appendChild(group);
+ });
+ host.appendChild(sec);
+ }
+
+ function renderTemplateExplicit(host) {
+ var sec = section("E", "sec_template_explicit", t("template_explicit_hint"));
+ var candidates = TEMPLATE_OPTIONS.explicit || [];
+ if (!candidates.length) {
+ sec.appendChild(el("div", "template-empty", t("template_none_explicit")));
+ } else {
+ var grid = el("div", "template-card-grid template-explicit-grid");
+ candidates.forEach(function (candidate) {
+ grid.appendChild(templateCandidateCard(candidate));
+ });
+ sec.appendChild(grid);
+ }
+ host.appendChild(sec);
+ }
+
+ function updateTemplateSelectionStatus() {
+ var status = document.getElementById("confirm-status");
+ if (!status) return;
+ status.textContent = TEMPLATE_MODE === "free_design"
+ ? t("template_free_selected")
+ : t("template_count_selected").replace("{count}", String(TEMPLATE_SELECTED_KEYS.length));
+ }
+
+ function renderTemplatePhase() {
+ if (!TEMPLATE_OPTIONS) return;
+ TEMPLATE_PHASE = true;
+ var heading = document.querySelector("#topbar .topbar-titles h1");
+ if (heading) heading.textContent = t("template_stage_title");
+ var hint = document.getElementById("topbar-hint");
+ if (hint) hint.textContent = t("template_stage_hint");
+ var previewHost = document.getElementById("topbar-preview");
+ if (previewHost) previewHost.innerHTML = "";
+ var host = document.getElementById("sections");
+ host.innerHTML = "";
+ _secCounter = 0;
+ renderTemplateFreeDesign(host);
+ renderTemplateLibrary(host);
+ renderTemplateExplicit(host);
+ document.getElementById("error").style.display = "none";
+ document.getElementById("loading").style.display = "none";
+ host.style.display = "block";
+ document.getElementById("actionbar").style.display = "flex";
+ var btn = document.getElementById("btn-confirm");
+ btn.disabled = false;
+ btn.textContent = t("btn_confirm_template");
+ updateTemplateSelectionStatus();
+ }
+
function normalizeRecId(field, value) {
if (Array.isArray(value)) return normalizeRecId(field, value[0]);
if (value == null || value === "") return value;
@@ -3176,6 +3448,74 @@
ov.style.display = "flex";
}
+ function showTemplateApplying() {
+ TEMPLATE_SUBMITTING = true;
+ document.getElementById("sections").style.display = "none";
+ document.getElementById("actionbar").style.display = "none";
+ var loading = document.getElementById("loading");
+ loading.textContent = t("template_applying");
+ loading.style.display = "block";
+ }
+
+ function pollForTemplateStage1() {
+ fetchJson("/api/session", "session").then(function (session) {
+ var readyStage = Number(session && session.recommendation_stage_number || 0);
+ if (session && (session.status === "error" || session.template_status === "error")) {
+ TEMPLATE_SUBMITTING = false;
+ showError(session.template_error || t("template_load_error"));
+ return null;
+ }
+ if (session && session.template_status === "invalid") {
+ showError(session.template_error || t("template_load_error"));
+ setTimeout(pollForTemplateStage1, 1200);
+ return null;
+ }
+ if (session && session.phase === "template" && session.template_status === "ready_user") {
+ TEMPLATE_SUBMITTING = false;
+ return loadTemplateUi(session).catch(function (err) {
+ showError(t("template_load_error") + " " +
+ (err && err.message ? err.message : ""));
+ return null;
+ });
+ }
+ if (session && session.phase === "strategist" && readyStage >= 1) {
+ return loadStrategistUi(1);
+ }
+ setTimeout(pollForTemplateStage1, 1200);
+ return null;
+ }).catch(function (err) {
+ var loading = document.getElementById("loading");
+ if (loading) {
+ loading.textContent = t("connection_lost") + " " +
+ (err && err.message ? err.message : "");
+ }
+ setTimeout(pollForTemplateStage1, 1500);
+ });
+ }
+
+ function submitTemplateSelection() {
+ if (TEMPLATE_SUBMITTING) return;
+ if (TEMPLATE_MODE !== "free_design" && !TEMPLATE_SELECTED_KEYS.length) {
+ document.getElementById("confirm-status").textContent = t("template_selection_required");
+ return;
+ }
+ var payload = {
+ mode: TEMPLATE_MODE,
+ selection_keys: TEMPLATE_MODE === "templates" ? TEMPLATE_SELECTED_KEYS.slice() : []
+ };
+ var btn = document.getElementById("btn-confirm");
+ btn.disabled = true;
+ postJson("/api/template-confirm", payload, "template confirmation").then(function () {
+ showTemplateApplying();
+ pollForTemplateStage1();
+ }).catch(function (err) {
+ TEMPLATE_SUBMITTING = false;
+ btn.disabled = false;
+ document.getElementById("confirm-status").textContent =
+ t("template_submit_error") + " " + (err && err.message ? err.message : t("error_retry"));
+ });
+ }
+
// ---- staged submit + next-stage transitions -------------------------
function communicationPayload() {
var payload = {
@@ -3458,6 +3798,29 @@
});
}
+ function postJson(url, payload, label) {
+ return fetch(url, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(payload)
+ }).then(function (r) {
+ return r.text().then(function (text) {
+ var data = null;
+ if (text) {
+ try { data = JSON.parse(text); }
+ catch (e) {
+ if (r.ok) throw new Error((label || url) + ": invalid JSON");
+ }
+ }
+ if (!r.ok) {
+ var serverMsg = data && data.error ? data.error : (text || r.statusText || r.status);
+ throw new Error((label || url) + ": " + serverMsg);
+ }
+ return data || {};
+ });
+ });
+ }
+
function loadCatalogs() {
return fetchJson("/api/catalogs", "catalogs")
.catch(function () { return fetchJson("/static/catalogs.json", "static catalogs"); });
@@ -3473,6 +3836,56 @@
.catch(function () { return {}; });
}
+ function applyServerLanguage(data) {
+ var requested = data && data.lang;
+ if (requested !== "zh" && requested !== "en" && requested !== "ja") return;
+ var hasStored = false;
+ try { hasStored = !!window.localStorage.getItem("ppt_lang"); } catch (e) { /* ignore */ }
+ if (hasStored) return;
+ LANG = requested;
+ applyStaticTranslations();
+ var toggleBtn = document.getElementById("btn-lang-toggle");
+ if (toggleBtn) refreshLangToggle(toggleBtn);
+ }
+
+ function loadStrategistUi(forceStage) {
+ return Promise.all([
+ loadCatalogs(),
+ fetchJson("/api/recommendations", "recommendations"),
+ loadIconPreviews(),
+ loadAiImageComparison()
+ ]).then(function (res) {
+ CAT = res[0];
+ REC = res[1];
+ ICON_PREVIEWS = res[2] || {};
+ AI_IMAGE_COMPARISON = res[3] || {};
+ applyServerLanguage(REC);
+ initState();
+ TEMPLATE_PHASE = false;
+ TEMPLATE_SUBMITTING = false;
+ enterStage(REC, forceStage || stageNumber(REC));
+ if (REC._already_confirmed) {
+ document.getElementById("confirm-status").textContent = t("already_confirmed");
+ }
+ return REC;
+ });
+ }
+
+ function loadTemplateUi(session) {
+ return fetchJson("/api/template-options", "template options").then(function (options) {
+ applyServerLanguage(options);
+ initTemplateOptions(options);
+ TEMPLATE_PHASE = true;
+ if (session && (session.template_status === "confirmed" || session.status === "waiting_agent")) {
+ showTemplateApplying();
+ pollForTemplateStage1();
+ } else {
+ renderTemplatePhase();
+ }
+ return options;
+ });
+ }
+
function boot() {
applyStaticTranslations();
var toggleBtn = document.getElementById("btn-lang-toggle");
@@ -3495,7 +3908,14 @@
try { window.localStorage.setItem("ppt_lang", LANG); } catch (e2) { /* ignore */ }
applyStaticTranslations();
refreshLangToggle(toggleBtn);
- if (REC && CAT) renderAll(); // STATE persists → selections preserved
+ if (TEMPLATE_PHASE && TEMPLATE_SUBMITTING) {
+ var loading = document.getElementById("loading");
+ if (loading) loading.textContent = t("template_applying");
+ } else if (TEMPLATE_PHASE && TEMPLATE_OPTIONS) {
+ renderTemplatePhase();
+ } else if (REC && CAT) {
+ renderAll(); // STATE persists → selections preserved
+ }
};
toggleBtn.addEventListener("click", function (e) {
e.stopPropagation();
@@ -3550,38 +3970,29 @@
if (!langMenu.hidden) setMenuOpen(false);
});
document.getElementById("btn-confirm").addEventListener("click", function () {
- if (STAGE === 1) submitStage1();
+ if (TEMPLATE_PHASE) submitTemplateSelection();
+ else if (STAGE === 1) submitStage1();
else if (STAGE === 2) submitStage2();
else confirm();
});
- Promise.all([
- loadCatalogs(),
- fetchJson("/api/recommendations", "recommendations"),
- loadIconPreviews(),
- loadAiImageComparison()
- ]).then(function (res) {
- CAT = res[0];
- REC = res[1];
- ICON_PREVIEWS = res[2] || {};
- AI_IMAGE_COMPARISON = res[3] || {};
- if (REC.lang === "zh" || REC.lang === "en" || REC.lang === "ja") {
- var hasStored = false;
- try { hasStored = !!window.localStorage.getItem("ppt_lang"); } catch (e) { /* ignore */ }
- if (!hasStored) { LANG = REC.lang; applyStaticTranslations(); refreshLangToggle(toggleBtn); }
- }
- initState();
- // stage 1 / 2 / 3 from the recommendations; absent → legacy single-pass.
- STAGE = stageNumber(REC);
- document.getElementById("loading").style.display = "none";
- document.getElementById("sections").style.display = "block";
- document.getElementById("actionbar").style.display = "flex";
- renderAll();
- if (REC._already_confirmed) {
- document.getElementById("confirm-status").textContent = t("already_confirmed");
+ // Session is the first network read. New Generate runs expose an
+ // independent Step-3 template phase; old sessions omit it (or report
+ // `strategist`) and retain the existing Stage-1-first behavior.
+ fetchJson("/api/session", "session").catch(function () {
+ return { phase: "strategist" };
+ }).then(function (session) {
+ if (session && session.phase === "template") {
+ return loadTemplateUi(session).catch(function (err) {
+ showError(t("template_load_error") + " " +
+ (err && err.message ? err.message : ""));
+ return null;
+ });
}
- }).catch(function (err) {
- showError(t("load_error") + " " + (err && err.message ? err.message : ""));
+ return loadStrategistUi().catch(function (err) {
+ showError(t("load_error") + " " + (err && err.message ? err.message : ""));
+ return null;
+ });
});
}
diff --git a/skills/ppt-master/scripts/confirm_ui/static/style.css b/skills/ppt-master/scripts/confirm_ui/static/style.css
index b708f733..4904b3c1 100644
--- a/skills/ppt-master/scripts/confirm_ui/static/style.css
+++ b/skills/ppt-master/scripts/confirm_ui/static/style.css
@@ -601,6 +601,138 @@ textarea.text-input { resize: vertical; line-height: 1.5; }
.subfield { margin-top: 14px; }
.subfield-label { font-size: 12.5px; color: var(--muted); margin-bottom: 7px; }
+/* ---- Step 3 template selection ---- */
+.template-kind-group + .template-kind-group {
+ margin-top: 18px;
+ padding-top: 18px;
+ border-top: 1px solid var(--line);
+}
+.template-kind-title {
+ margin: 0 0 9px;
+ color: var(--ink);
+ font-size: 13px;
+ font-weight: 700;
+}
+.template-card-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
+ gap: 10px;
+}
+.template-card {
+ width: 100%;
+ min-width: 0;
+ border: 1px solid var(--line);
+ border-radius: 10px;
+ background: var(--card);
+ color: var(--ink);
+ padding: 13px 14px;
+ text-align: left;
+ cursor: pointer;
+ transition: border-color .12s ease, background .12s ease, box-shadow .12s ease;
+}
+.template-card:hover {
+ border-color: var(--accent);
+}
+.template-card:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+}
+.template-card.selected {
+ border-color: var(--accent);
+ background: var(--accent-soft);
+ box-shadow: 0 0 0 1px var(--accent);
+}
+.template-free-card {
+ display: flex;
+ flex-direction: column;
+ gap: 5px;
+}
+.template-card-head {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 10px;
+}
+.template-card-title {
+ display: block;
+ min-width: 0;
+ font-size: 13.5px;
+ font-weight: 700;
+ line-height: 1.4;
+ overflow-wrap: anywhere;
+}
+.template-card-badges {
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: flex-end;
+ gap: 5px;
+ flex-wrap: wrap;
+}
+.template-source-badge,
+.template-kind-badge {
+ display: inline-flex;
+ align-items: center;
+ min-height: 20px;
+ border-radius: 999px;
+ padding: 2px 7px;
+ font-size: 10.5px;
+ font-weight: 700;
+ line-height: 1.3;
+}
+.template-source-library,
+.template-kind-badge {
+ background: #eef2f7;
+ color: #475569;
+}
+.template-source-explicit {
+ background: #fff3d6;
+ color: #8a5a00;
+}
+.template-card-summary {
+ display: block;
+ margin-top: 7px;
+ color: var(--muted);
+ font-size: 12.5px;
+ line-height: 1.55;
+}
+.template-card-path {
+ display: block;
+ margin-top: 10px;
+ padding-top: 9px;
+ border-top: 1px dashed #d9dde3;
+}
+.template-card-path-label {
+ display: block;
+ margin-bottom: 3px;
+ color: var(--muted);
+ font-size: 10.5px;
+ font-weight: 700;
+}
+.template-card-path-value {
+ display: block;
+ color: #475569;
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ font-size: 11px;
+ line-height: 1.45;
+ overflow-wrap: anywhere;
+ white-space: normal;
+}
+.template-explicit-grid .template-card {
+ border-style: dashed;
+}
+.template-explicit-grid .template-card.selected {
+ border-style: solid;
+}
+.template-empty {
+ border: 1px dashed var(--line);
+ border-radius: 9px;
+ padding: 12px 14px;
+ color: var(--muted);
+ background: #f8fafc;
+ font-size: 12.5px;
+}
+
/* ---- toggles ---- */
.toggle-row { display: flex; align-items: center; gap: 12px; }
.toggle-desc { font-size: 12.5px; color: var(--muted); }