From 90d920c8d976c301f4281140db19b0ed0d796a21 Mon Sep 17 00:00:00 2001 From: Shotaro Kataoka <42331656+ShotaroKataoka@users.noreply.github.com> Date: Thu, 29 Oct 2026 23:24:28 +0900 Subject: [PATCH 01/13] feat(html-output-mode): HTML deck output with reveal.js (phase 1) (#440) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * โœจ feat(html-output-mode): add deck.json outputFormat and init_deck_workspace(output_format) deck_output_format() / OUTPUT_FORMATS in engine/schema; validate_specs errors on a bad outputFormat and adds "outputFormat": "html" to the result only for HTML decks. api.init / init_deck_workspace / CLI init_deck_workspace --output-format write the field only for html; PPTX deck.json and check_specs results are unchanged. Verified: SDPM_AUTO_INSTALL_ASSETS=0 uv run pytest tests/test_deck_spec.py tests/test_tool_descriptions.py tests/test_entry_tools.py tests/test_cli_contract.py -q (83 passed) SPEC: 20261029-1619_html-output-mode Progress: tasks 4.1 (init part, outputFormat field) Next: FEAT-001 template conversion (tasks 1.1-1.6) * โœจ feat(html-output-mode): convert pptx templates to theme.css, template.json and decoration SVGs New core package sdpm/sdpm/engine/html/: textstyle.py resolves placeholder text styles through layout -> master placeholder -> txStyles -> defaultTextStyle; decorations.py computes decoration boxes/kinds and layout grounds from the XML and renders decoration-only SVGs via LibreOffice PDF + pdftocairo with a sentinel ground (stripped, together with the PDF page underlay); template.py builds theme.css / template.json, caches them per content hash and prefers the bundled artifacts. Missing LibreOffice/poppler only drops the decorations (decorations_status in the preview_unavailable shape). Bundled artifacts for blank-light / blank-dark under sdpm/templates/html/, generated by scripts/build_bundled_template_html.py (drift-guarded by tests). Verified: SDPM_AUTO_INSTALL_ASSETS=0 uv run pytest tests/test_deck_spec.py tests/test_html_template.py tests/test_architecture.py tests/test_entry_tools.py -q (175 passed, LO-gated render test ran locally); uv run make lint (clean); SDPM_AUTO_INSTALL_ASSETS=0 uv run pytest tests/ -q (1270 passed, 26 skipped) SPEC: 20261029-1619_html-output-mode Progress: tasks 1.1-1.6 (template conversion, bundled artifacts, tests) Next: FEAT-002 (reveal.js vendoring + HTML assembly) * โœจ feat(html-output-mode): assemble offline reveal.js output.html with static checks Vendor reveal.js 6.0.2 under sdpm/vendor/revealjs (MIT, update procedure in sdpm/vendor/README.md, VENDOR_DIR anchor, THIRD-PARTY-LICENSES entry). engine/html/assemble.py builds one self-contained output.html (style :root, theme.css, one decoration SVG background per used layout, deck.css once, slide styles nested under section[data-slug], inline SVG icons and data-URI images, slide-number/footer chrome, inline reveal.js + notes plugin). engine/html/check.py adds the browser-free checks (--fs-* lint for slides and deck.css, structure, data-layout, script, external-url, data-background, self-chrome, :root, data-slug) and the html preview note. sdpm.api gains generate_html / refresh_html; affected_slugs(..., html=True) treats specs/art-direction.html and deck.css as deck-wide. Verified: targeted pytest (html_assemble/check/api, render_scope) 79 passed; uv run make lint clean; full suite 1341 passed, 26 skipped. SPEC: 20261029-1619_html-output-mode Progress: tasks 2.1-2.4, 2.6, 3.1, 3.2, 3.4 (3.3 helper html_preview_unavailable) Next: FEAT-003 role documents (composer-html.md, slide-html-spec.md, orchestrator) * ๐Ÿ“ docs(html-output-mode): add composer-html role document and slide HTML guide Add workflows/composer-html.md (composer html mode, layout pass writes deck.css + frames + empty data-region boxes) and guides/slide-html-spec.md; orchestrator picks HTML only on explicit request / @format:html and passes mode in the spawn prompt; ACP composer prompt and server instructions name start_composing(deck_id, assigned_slugs, mode); import-pptx, hand-edit-sync and translate say PPTX decks only; principles.md rule 4 and AGENTS.md describe one document per composer mode chosen by the spawner. composer.md is unchanged. Verified: pytest test_reference/test_acp_agent_definitions/ test_tool_descriptions/test_entry_tools/test_agent_modes 87 passed; make lint clean; full suite 1341 passed, 26 skipped. SPEC: 20261029-1619_html-output-mode Progress: tasks 2.5, 2.5b, 4.2 (plan step 9, FEAT-003) Next: FEAT-004 start_composing(mode) wiring, run_python HTML branch, guards * โœจ feat(html-output-mode): start_composing mode, run_python HTML branch and CLI generate_html start_composing(mode="pptx"|"html") picks the composer document and slide spec by mode; a mode that does not match deck.json outputFormat returns specs_ok=false with the deck's format. HTML payloads carry slide HTML, deck_css and template_html. The PPTX payload is byte-identical to main. generate_pptx, code_to_slide, start_translation and diff refuse HTML decks. Local run_python rebuilds output.html through sdpm.api.refresh_html for HTML decks; the CLI gains generate_html and start composing --mode, and measure / preview accept HTML decks. Verified: targeted pytest (entry_tools, run_python_semantics, cli_contract, tool_descriptions, acp_agent_definitions, agent_modes, architecture) 229 passed; uv run make lint clean; full suite 1358 passed, 26 skipped; servers/remote no diff. SPEC: 20261029-1619_html-output-mode Progress: tasks 3.3, 4.1, 4.3 (local; remote unchanged by design), 4.4 tests part Next: FEAT-005 docs (architecture.md tool table, CHANGELOG, en/ja) + validation * ๐Ÿ“ docs(html-output-mode): document HTML decks and record phase 1 validation Architecture tool table (start_composing mode, init_deck_workspace output_format, generate_pptx no-op on HTML decks), HTML deck sections in getting-started en/ja, HTML template conversion in custom-template, CHANGELOG [Unreleased] entry. .ash.yaml: suppress SECRET-HEX-HIGH-ENTROPY-STRING for the sourceHash content hash in sdpm/templates/html/*/template.json. Verified: uv run make lint (pass); SDPM_AUTO_INSTALL_ASSETS=0 uv run make test (1358 passed, 26 skipped); uv run python /tmp/sdpm-html-v1/run.py (V1/V3 all OK); ash scan --mode local --fail-on-findings exit 2 โ€” only npm-audit findings on web-ui/infra package-lock.json, unchanged from main. SPEC: 20261029-1619_html-output-mode Progress: 4.4, 4.5, V1, V3, V4 done; V2 awaits manual browser check; V5 blocked by pre-existing npm-audit findings Next: phase 2 (cloud) * ๐Ÿ› fix(html-output-mode): position data-region boxes absolutely in output.html design.md ยง4 writes regions as `
` without `position`; the assembler only made data-ph (theme.css) and chrome absolute, so such regions landed in normal flow. The deck rules now set `[data-sdpm-chrome],[data-region]{position:absolute}` (slide styles and inline style still override). slide-html-spec.md says so instead of asking composers to add it themselves. Verification (cross-FEAT integration, iteration 1): - uv run make lint: All checks passed - SDPM_AUTO_INSTALL_ASSETS=0 uv run make test: 1359 passed, 26 skipped (a pre-fix run under load average >120 had a timing flake in tests/test_webp_background.py; untouched remote code, passes alone x3) - SDPM_AUTO_INSTALL_ASSETS=0 uv run python /tmp/sdpm-html-v1/run.py (V1-V3): ALL CHECKS PASSED (blank-light 285067 B, blank-dark 285321 B, aws-brand-dark 886259 B; V3 reports every rule) - ash scan --mode local --fail-on-findings: exit 2, only npm-audit 89 findings in web-ui/infra package-lock.json (identical to main, accepted as pre-existing); bandit, checkov, semgrep, detect-secrets PASSED SPEC: 20261029-1619_html-output-mode Progress: cross-FEAT integration of FEAT-001..005 (tasks 2.2/2.5 seam) Next: review iteration; V2 manual browser check by the user * ๐Ÿ› fix(html-output-mode): hoist slide at-rules, lower placeholder specificity, embed all resource refs - Slide ", + f'', + f'', + f'', + ] + if deck_css_text: + head.append(f'') + head.append(f'') + head.append("") + config = (f"Reveal.initialize({{width:{width},height:{height},margin:0.04,center:false," + "hash:true,plugins:[RevealNotes]});") + body = [ + "", + '
', + *sections, + "
", + f"", + f"", + f"", + "", + "", + ] + text = "\n".join(head + body) + "\n" + total = len(text.encode("utf-8")) + if total > MAX_OUTPUT_HTML_BYTES: + warnings.append(f"output.html: {_mb(total)} (over {_mb(MAX_OUTPUT_HTML_BYTES)}) โ€” it opens " + "slowly; compress or shrink the embedded images") + return AssembleResult(html=text, bytes=total, layouts_used=layouts_used, + warnings=warnings, slugs=included) + + +__all__ = ["AssembleResult", "MAX_EMBEDDED_FILE_BYTES", "MAX_OUTPUT_HTML_BYTES", "ParsedSlide", + "assemble_deck", "inline_js", "parse_slide", "style_root_css"] diff --git a/sdpm/sdpm/engine/html/check.py b/sdpm/sdpm/engine/html/check.py new file mode 100644 index 000000000..55d767d57 --- /dev/null +++ b/sdpm/sdpm/engine/html/check.py @@ -0,0 +1,416 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +"""Browser-free static checks for HTML decks (slides/.html and deck.css). + +Every check returns diagnostics ``{"slug", "rule", "message"}``; callers turn them +into warnings. Nothing here blocks a build. + +Rules: + structure not exactly one top-level ``
``, or a nested one + layout-missing the section has no ``data-layout`` + layout-unknown ``data-layout`` names no layout of the template + script ``' + '') + (deck / "images" / "chart.svg").write_text(svg, encoding="utf-8") + slides = {"svg": ( + '
chart' + '
' + '
')} + result = _assemble(deck, slides=slides) + assert not result.warnings + doc = lxml_html.document_fromstring(result.html) + section = doc.xpath('//section[@data-slug="svg"]')[0] + uri = "data:image/svg+xml;base64," + base64.b64encode(svg.encode("utf-8")).decode("ascii") + imgs = section.xpath(".//img") + assert imgs[0].get("src") == uri and imgs[0].get("alt") == "chart" + assert imgs[1].get("srcset") == f"{uri} 1x" + assert uri in section.xpath(".//div")[0].get("style") + text = lxml_html.tostring(section, encoding="unicode") + assert not section.xpath(".//svg | .//script") and "onload" not in text + assert "evil" not in result.html + + +def test_size_warnings(tmp_path: Path, monkeypatch) -> None: + from sdpm.engine.html import assemble + + deck = _make_deck(tmp_path) + (deck / "images").mkdir() + (deck / "images" / "big.png").write_bytes(b"\x89PNG" + b"0" * 2000) + slides = {"big": '
'} + assert not _assemble(deck, slides=slides).warnings + monkeypatch.setattr(assemble, "MAX_EMBEDDED_FILE_BYTES", 1000) + monkeypatch.setattr(assemble, "MAX_OUTPUT_HTML_BYTES", 1000) + result = _assemble(deck, slides=slides) + assert [w.split(":", 1)[0] for w in result.warnings] == ["big", "output.html"] + assert "images/big.png is 0.0 MB" in result.warnings[0] + assert result.warnings[1].startswith(f"output.html: {result.bytes / 1048576:.1f} MB") + + +def test_inline_js_escapes_script_end_and_comment_open() -> None: + assert inline_js('a="";b="tail\n" + "
\n" + ) + assert slide_text_summary(text) == { + "layout": "Title Only", + "title": "The claim", + "notes": "Speak slowly. Then pause.", + "text": "Kicker The claim first second tail", + } + + +def test_title_falls_back_to_first_heading() -> None: + summary = slide_text_summary('

intro

Sub

Main

') + assert summary["title"] == "Sub" + assert slide_text_summary('

no heading

')["title"] == "" + + +def test_svg_text_is_included_and_text_is_capped() -> None: + summary = slide_text_summary('
Label' + f"

{'word ' * 2000}

") + assert summary["text"].startswith("Label word") + assert len(summary["text"]) == MAX_TEXT_CHARS == 4000 + + +def test_unusable_slide() -> None: + assert slide_text_summary("
no section
") == {"layout": None, "title": "", "notes": "", "text": ""} + assert slide_text_summary('

x

')["layout"] is None diff --git a/tests/test_remote_html.py b/tests/test_remote_html.py new file mode 100644 index 000000000..693346ea8 --- /dev/null +++ b/tests/test_remote_html.py @@ -0,0 +1,517 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +"""Remote MCP server: HTML decks (init, start_composing, run_python, generate_pptx, +get_preview, template conversion cache on S3).""" + +from __future__ import annotations + +import importlib.util +import json +import os +import re +from pathlib import Path +from unittest.mock import MagicMock, patch + +import pytest + +from sdpm import api +from shared.html_artifacts import HTML_CONTENT_TYPE, TEMPLATE_CACHE_PREFIX +from tools import html_deck, template_html_cache +from tools import init as init_mod +from tools import sandbox as sandbox_mod + +_ROOT = Path(__file__).resolve().parents[1] +_TEMPLATE = _ROOT / "sdpm" / "templates" / "blank-dark.pptx" + +os.environ.setdefault("DECKS_TABLE", "test-table") +os.environ.setdefault("PPTX_BUCKET", "test-pptx") +os.environ.setdefault("RESOURCE_BUCKET", "test-resource") + +_spec = importlib.util.spec_from_file_location("remote_server_html_under_test", _ROOT / "servers" / "remote" / "server.py") +remote_server = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(remote_server) + +SLIDES = { + "cover": '

Hello

' + '
', + "body": '

Claim

Point

', +} +_OUTLINE = "# Remote deck\n\n## S\n" + "".join( + f"- [{slug}] {slug}\n - body: b\n - visual: v\n - evidence: e\n" for slug in SLIDES +) +_HTML_KEY = re.compile(r"^html/d1/[0-9a-f-]{36}\.html$") +_PREVIEW_KEY = re.compile(r"^html/d1/preview/([a-z0-9-]+)_(\d+)\.html$") + + +class FakeStorage: + """Dict-backed stand-in for AwsStorage (pptx bucket + resource bucket + deck record).""" + + pptx_bucket = "test-pptx" + + def __init__(self): + self.objects: dict[str, bytes] = {} + self.content_types: dict[str, str] = {} + self.resource: dict[str, bytes] = {"templates/blank-dark.pptx": _TEMPLATE.read_bytes()} + self.record: dict = {"deckId": "d1", "name": "Remote deck", "visibility": "private"} + self.updates: list[dict] = [] + self.deleted: list[str] = [] + self.if_absent: list[str] = [] + self._s3 = MagicMock() + + # deck record + def get_deck(self, deck_id, user_id): + return dict(self.record) if deck_id == "d1" else None + + def update_deck(self, deck_id, user_id, updates): + self.updates.append(dict(updates)) + old = {k: self.record[k] for k in updates if k in self.record} + for k, v in updates.items(): + if v is None: + self.record.pop(k, None) + else: + self.record[k] = v + return old + + # deck.json + def get_deck_json(self, deck_id): + return json.loads(self.objects[f"decks/{deck_id}/deck.json"]) + + def put_deck_json(self, deck_id, data): + self.objects[f"decks/{deck_id}/deck.json"] = json.dumps(data).encode() + + # objects + def list_files(self, prefix, bucket=""): + source = self.objects if bucket == self.pptx_bucket else self.resource + return sorted(k for k in source if k.startswith(prefix)) + + def download_file_from_pptx_bucket(self, key): + if key not in self.objects: + raise FileNotFoundError(key) + return self.objects[key] + + def download_file(self, key): + if key not in self.resource: + raise FileNotFoundError(key) + return self.resource[key] + + def upload_file(self, key, data, content_type="", tagging=""): + self.objects[key] = data + self.content_types[key] = content_type + + def upload_file_if_absent(self, key, data, content_type="", checksum_sha256="", tagging=""): + self.if_absent.append(key) + if key in self.objects: + return False + self.upload_file(key, data, content_type) + return True + + def delete_object_keys(self, keys): + for key in keys: + self.deleted.append(key) + self.objects.pop(key, None) + + # templates + def list_templates(self): + return [{"name": "blank-dark", "s3Key": "templates/blank-dark.pptx"}] + + def get_user_template_metadata(self, user_id, name): + return None + + def list_user_templates(self, user_id): + return [] + + def html_keys(self): + return [k for k in self.objects if _HTML_KEY.match(k)] + + def preview_keys(self): + return sorted(k for k in self.objects if _PREVIEW_KEY.match(k)) + + +def _seed_html_deck(storage: FakeStorage, tmp_path: Path, slides: dict | None = None) -> None: + deck = tmp_path / "local-deck" + api.init("t", output_dir=deck, output_format="html") + assert api.apply_style(deck, style="typographic", template="blank-dark")["status"] == "ok" + (deck / "specs" / "outline.md").write_text(_OUTLINE, encoding="utf-8") + (deck / "specs" / "brief.md").write_text("# Brief\n", encoding="utf-8") + (deck / "deck.css").write_text(".card { padding: 8px; }\n", encoding="utf-8") + for slug, text in (SLIDES if slides is None else slides).items(): + (deck / "slides" / f"{slug}.html").write_text(text, encoding="utf-8") + for path in deck.rglob("*"): + if path.is_file(): + storage.objects[f"decks/d1/{path.relative_to(deck).as_posix()}"] = path.read_bytes() + + +@pytest.fixture() +def storage(tmp_path): + s = FakeStorage() + _seed_html_deck(s, tmp_path) + return s + + +@pytest.fixture() +def cache_root(tmp_path, monkeypatch): + root = tmp_path / "template-cache" + monkeypatch.setattr(template_html_cache, "CACHE_ROOT", root) + return root + + +@pytest.fixture() +def server(storage, cache_root, monkeypatch): + monkeypatch.setattr(remote_server, "_storage", storage) + monkeypatch.setattr(remote_server, "_check_deck_access", lambda *a, **k: None) + monkeypatch.setattr(remote_server, "_get_user_id", lambda: "user1") + monkeypatch.setattr(remote_server, "_get_kb_sync", lambda: None) + return remote_server + + +def _sandbox(monkeypatch, changed: list[str]): + monkeypatch.setattr( + remote_server.sandbox_mod, "execute_in_sandbox", + lambda **kwargs: ("ok", [], [], list(changed)), + ) + + +def _no_pptx(monkeypatch): + import tools.generate as gen_mod + + def boom(*a, **k): + raise AssertionError("PPTX post-processing must not run for an HTML deck") + + monkeypatch.setattr(gen_mod, "_prepare_workspace", boom) + monkeypatch.setattr(remote_server, "_build_pptx", boom) + + +# --- init_deck_workspace ----------------------------------------------------- + + +def _init(output_format: str | None): + storage = MagicMock() + kwargs = {} if output_format is None else {"output_format": output_format} + result = init_mod.init_deck_workspace(name="n", user_id="u1", storage=storage, **kwargs) + return storage, result + + +def test_init_html_writes_output_format(): + storage, result = _init("html") + data = storage.put_deck_json.call_args.kwargs["data"] + assert data["outputFormat"] == "html" + assert storage.put_deck_json.call_args.kwargs["deck_id"] == result["deckId"] + + +def test_init_pptx_deck_json_unchanged(): + from sdpm.engine.schema import DECK_JSON_SKELETON, complete_deck_skeleton + + for fmt in (None, "pptx"): + storage, _ = _init(fmt) + data = storage.put_deck_json.call_args.kwargs["data"] + assert data == complete_deck_skeleton(DECK_JSON_SKELETON) + assert "outputFormat" not in data + + +def test_init_rejects_unknown_format_before_creating_anything(): + storage = MagicMock() + with pytest.raises(ValueError): + init_mod.init_deck_workspace(name="n", user_id="u1", storage=storage, output_format="pdf") + storage.put_deck.assert_not_called() + storage.put_deck_json.assert_not_called() + + +def test_init_tool_passes_output_format(server, monkeypatch): + seen = {} + monkeypatch.setattr(remote_server.init_mod, "init_deck_workspace", lambda **kw: seen.update(kw) or {"deckId": "x"}) + remote_server.init_deck_workspace(name="n", output_format="html") + assert seen["output_format"] == "html" + + +# --- start_composing / sandbox ----------------------------------------------- + + +def test_start_composing_html_materializes_html_slides_and_template(server, cache_root): + payload = json.loads(server.start_composing(deck_id="d1", assigned_slugs=["cover"], mode="html")) + assert payload["static"]["workflow"].startswith("# Composer (HTML)") + deck = payload["deck"] + assert deck["specs_ok"] is True + assert deck["slides_present"] == ["body", "cover"] + assert deck["existing_slides"] == {"cover": {"html": SLIDES["cover"]}} + assert deck["deck_css"] == ".card { padding: 8px; }\n" + assert deck["template_html"]["layouts"] and "template_analysis" not in deck + # The conversion was persisted to S3 for the next microVM. + assert any(k.startswith(TEMPLATE_CACHE_PREFIX) and k.endswith("/template.json") for k in server._storage.objects) + + +def test_start_composing_without_deck_returns_html_static(server): + payload = json.loads(server.start_composing(mode="html")) + assert set(payload) == {"static"} + assert payload["static"]["workflow"].startswith("# Composer (HTML)") + + +def test_start_composing_mode_mismatch_reports_deck_format(server): + payload = json.loads(server.start_composing(deck_id="d1", assigned_slugs=["cover"])) + assert payload["specs_ok"] is False and payload["mode"] == "html" + + +def test_sandbox_syncs_deck_css(): + assert "deck.css" in sandbox_mod._WORKSPACE_PREFIXES + + +# --- run_python --------------------------------------------------------------- + + +def _run(server, measure=None): + return json.loads(server.run_python(purpose="t", code="print(1)", deck_id="d1", measure_slides=measure)) + + +def test_run_python_html_uploads_output_and_all_missing_previews(server, storage, monkeypatch): + _no_pptx(monkeypatch) + _sandbox(monkeypatch, ["slides/cover.html"]) + storage.record["htmlS3Key"] = "html/d1/old.html" + storage.objects["html/d1/old.html"] = b"old" + + out = _run(server) + + assert "html_error" not in out, out + [key] = storage.html_keys() + assert out["html"] == key and storage.content_types[key] == HTML_CONTENT_TYPE + assert storage.objects[key].lower().startswith(b"") + assert storage.record["htmlS3Key"] == key and storage.record["slideCount"] == 2 + assert "html/d1/old.html" in storage.deleted + # No preview existed yet: every slide gets one, slide 1 becomes the thumbnail. + assert sorted(out["previews"]) == ["body", "cover"] + assert storage.record["thumbnailS3Key"] == out["previews"]["cover"] + assert all(storage.content_types[k] == HTML_CONTENT_TYPE for k in storage.preview_keys()) + assert "pptxS3Key" not in storage.record + + +def test_run_python_html_uploads_only_affected_previews(server, storage, monkeypatch): + _no_pptx(monkeypatch) + old_cover, old_body = "html/d1/preview/cover_100.html", "html/d1/preview/body_100.html" + storage.objects.update({old_cover: b"x", old_body: b"x"}) + storage.record["thumbnailS3Key"] = old_cover + _sandbox(monkeypatch, ["slides/body.html"]) + + out = _run(server) + + assert list(out["previews"]) == ["body"] + assert old_body in storage.deleted and old_cover not in storage.deleted + assert storage.record["thumbnailS3Key"] == old_cover # slide 1 was not re-rendered + + +def test_run_python_html_measure_reports_and_previews_measured(server, storage, monkeypatch): + _no_pptx(monkeypatch) + storage.objects.update({"html/d1/preview/cover_100.html": b"x", "html/d1/preview/body_100.html": b"x"}) + _sandbox(monkeypatch, []) + + out = _run(server, measure=["cover"]) + + assert list(out["previews"]) == ["cover"] + assert "cover" in out["measure"] + assert out["measure"].startswith(html_deck.REMOTE_CHECK_REPORT_HEADER) + assert "output.html" not in out["measure"] + assert out["preview"]["note"] == html_deck.REMOTE_PREVIEW_NOTE and "open" not in out["preview"] + + +def test_run_python_html_non_build_change_does_nothing(server, storage, monkeypatch): + _no_pptx(monkeypatch) + _sandbox(monkeypatch, ["specs/brief.md"]) + out = _run(server) + assert storage.html_keys() == [] and "html" not in out + + +def test_run_python_html_record_failure_reports_stale_html(server, storage, monkeypatch): + _no_pptx(monkeypatch) + _sandbox(monkeypatch, ["deck.css"]) + monkeypatch.setattr(storage, "update_deck", MagicMock(side_effect=RuntimeError("DynamoDB down"))) + + out = _run(server) + + assert "stale" in out["html_error"] + assert storage.html_keys() == [] # the orphaned upload was deleted + + +# --- generate_pptx (finalize) ------------------------------------------------- + + +def test_generate_pptx_finalizes_html_deck(server, storage, monkeypatch): + kb = MagicMock() + monkeypatch.setattr(remote_server, "_get_kb_sync", lambda: kb) + stale = ["html/d1/preview/cover_1.html", "html/d1/preview/gone_1.html"] + storage.objects.update({k: b"x" for k in stale}) + storage.record["htmlS3Key"] = "html/d1/old.html" + + result = json.loads(server.generate_pptx(deck_id="d1")) + + assert result["status"] == "completed" and result["outputFormat"] == "html" + assert result["slideCount"] == 2 and result["slides"] == ["page01 - cover", "page02 - body"] + [key] = storage.html_keys() + assert result["bytes"] == len(storage.objects[key]) + previews = storage.preview_keys() + assert sorted(_PREVIEW_KEY.match(k).group(1) for k in previews) == ["body", "cover"] + assert len({_PREVIEW_KEY.match(k).group(2) for k in previews}) == 1 # one epoch + assert set(stale) <= set(storage.deleted) and "html/d1/old.html" in storage.deleted + assert storage.record["htmlS3Key"] == key + assert storage.record["thumbnailS3Key"] in previews and "/cover_" in storage.record["thumbnailS3Key"] + kwargs = kb.sync_deck.call_args.kwargs + assert kwargs["deck_id"] == "d1" and kwargs["deck_name"] == "Remote deck" + cover = kwargs["slides"][0] + assert cover["id"] == "cover" and cover["layout"] == "Title Slide" + assert cover["title"] == "Hello" and cover["notes"] == "Say hi" + assert "Hello" in cover["elements"][0]["text"] + assert not any(k.startswith("pptx/") for k in storage.objects) + + +def test_generate_pptx_kb_failure_is_a_warning(server, storage, monkeypatch): + kb = MagicMock() + kb.sync_deck.side_effect = RuntimeError("vectors down") + monkeypatch.setattr(remote_server, "_get_kb_sync", lambda: kb) + result = json.loads(server.generate_pptx(deck_id="d1")) + assert result["warnings"]["kbSyncFailed"] == "vectors down" + + +def test_generate_pptx_partial_preview_upload_removes_this_runs_previews(server, storage, monkeypatch): + previous = ["html/d1/preview/cover_1.html", "html/d1/preview/body_1.html"] + storage.objects.update({k: b"x" for k in previous}) + upload = storage.upload_file + + def flaky(key, data, content_type="", tagging=""): + if "/preview/body_" in key: + raise RuntimeError("S3 down") + upload(key, data, content_type, tagging) + + monkeypatch.setattr(storage, "upload_file", flaky) + + result = json.loads(server.generate_pptx(deck_id="d1")) + + assert "body" in result["error"] + assert storage.preview_keys() == sorted(previous) # the complete older set stays the latest + assert storage.html_keys() == [] and "htmlS3Key" not in storage.record + + +def test_generate_pptx_pptx_deck_takes_the_pptx_path(server, storage, monkeypatch): + deck_json = storage.get_deck_json("d1") + deck_json.pop("outputFormat") + storage.put_deck_json("d1", deck_json) + called = {} + monkeypatch.setattr(remote_server.generate, "generate_pptx", lambda **kw: called.update(kw) or {"slideCount": 0}) + json.loads(server.generate_pptx(deck_id="d1")) + assert called["deck_id"] == "d1" + + +# --- get_preview --------------------------------------------------------------- + + +def test_get_preview_html_deck_returns_note(server): + assert server.get_preview(deck_id="d1", slugs=["cover"]) == [ + {"type": "text", "text": html_deck.REMOTE_PREVIEW_NOTE} + ] + + +# --- template conversion cache --------------------------------------------------- + + +def test_template_cache_round_trip_skips_conversion(tmp_path, monkeypatch): + from sdpm.engine.html import template as template_mod + + storage = FakeStorage() + first = tmp_path / "first" + template_mod.load_template_html(_TEMPLATE, decorations=False, cache_root=first) + uploaded = template_html_cache.persist(_TEMPLATE, storage, first) + key = template_mod.cache_key(_TEMPLATE) + cached = sorted(k for k in storage.objects if k.startswith(f"{TEMPLATE_CACHE_PREFIX}{key}/")) + assert uploaded == len(cached) and {k.rsplit("/", 1)[1] for k in cached} >= {"template.json", "theme.css"} + + # A second persist uploads nothing new. + assert template_html_cache.persist(_TEMPLATE, storage, first) == 0 + + # A fresh microVM restores instead of converting; non-allowlisted keys are ignored. + storage.objects[f"{TEMPLATE_CACHE_PREFIX}{key}/evil.sh"] = b"rm -rf /" + second = tmp_path / "second" + assert template_html_cache.restore(_TEMPLATE, storage, second) == len(cached) + assert not (second / key / "evil.sh").exists() + monkeypatch.setattr(template_mod, "build_template_info", MagicMock(side_effect=AssertionError("converted"))) + converted = template_mod.load_template_html(_TEMPLATE, decorations=False, cache_root=second) + assert converted.info["layouts"] + # Already restored: nothing is downloaded again. + assert template_html_cache.restore(_TEMPLATE, storage, second) == 0 + + +def test_template_cache_persist_uploads_only_missing(tmp_path): + from sdpm.engine.html import template as template_mod + + storage = FakeStorage() + root = tmp_path / "c" + template_mod.load_template_html(_TEMPLATE, decorations=False, cache_root=root) + key = template_mod.cache_key(_TEMPLATE) + storage.objects[f"{TEMPLATE_CACHE_PREFIX}{key}/theme.css"] = b"already" + (root / key / "notes.txt").write_text("not allowlisted", encoding="utf-8") + template_html_cache.persist(_TEMPLATE, storage, root) + assert storage.objects[f"{TEMPLATE_CACHE_PREFIX}{key}/theme.css"] == b"already" + assert f"{TEMPLATE_CACHE_PREFIX}{key}/template.json" in storage.objects + assert not any(k.endswith("notes.txt") for k in storage.objects) + assert all(k.startswith(TEMPLATE_CACHE_PREFIX) for k in storage.if_absent) + + +# --- workspace refs --------------------------------------------------------------- + + +def test_prepare_rejects_refs_outside_the_deck(tmp_path, cache_root): + storage = FakeStorage() + _seed_html_deck(storage, tmp_path, slides={ + "cover": '
' + '
', + }) + storage.objects["decks/d1/images/a.png"] = b"png" + tmpdir, meta = html_deck.prepare_html_workspace("d1", "user1", storage, cache_root) + try: + assert (tmpdir / "images" / "a.png").read_bytes() == b"png" + assert json.loads((tmpdir / "deck.json").read_text())["template"] == "template.pptx" + assert meta["template"] == "blank-dark" + finally: + import shutil + + shutil.rmtree(tmpdir, ignore_errors=True) + assert html_deck._safe_relative("../x") is None and html_deck._safe_relative("/x") is None + assert html_deck._safe_relative("a\\b") is None and html_deck._safe_relative("C:x") is None + assert html_deck._safe_relative("./images/a.png") == "images/a.png" + + +# --- tool count -------------------------------------------------------------------- + + +def test_remote_tool_count_unchanged(): + """20 tools as before; a configured knowledge base adds only search_slides.""" + import asyncio + + without_kb = {t.name for t in asyncio.run(remote_server.mcp.list_tools())} + assert len(without_kb) == 20 and "search_slides" not in without_kb + + env = { + "DECKS_TABLE": "decks-test", "PPTX_BUCKET": "pptx-test", "RESOURCE_BUCKET": "resource-test", + "KB_SSM_PARAM": "/sdpm/kb-id", "VECTOR_BUCKET_NAME": "vectors-test", + "VECTOR_INDEX_NAME": "index-test", "AWS_DEFAULT_REGION": "ap-northeast-1", + } + with patch.dict("os.environ", env), patch("boto3.client", lambda *a, **k: MagicMock()): + spec = importlib.util.spec_from_file_location("remote_server_html_count", _ROOT / "servers" / "remote" / "server.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + tools = asyncio.run(module.mcp.list_tools()) + assert {t.name for t in tools} == without_kb | {"search_slides"} + params = {t.name: set(t.inputSchema.get("properties", {})) for t in tools} + assert "output_format" in params["init_deck_workspace"] + assert "mode" in params["start_composing"] + + +# --- container image ----------------------------------------------------------------- + + +def test_runtime_image_copies_bundled_html_data(): + """The remote image ships every bundled-data dir the HTML engine reads (SDPM_SKILL_ROOT). + + reveal.js under sdpm/vendor/ is inlined into every HTML deck; without it in the + image, generate_pptx fails for every HTML deck on the deployed server. + """ + dockerfile = (_ROOT / "servers" / "remote" / "Dockerfile").read_text(encoding="utf-8") + copies = set(re.findall(r"^COPY\s+(\S+)", dockerfile, flags=re.MULTILINE)) + for data_dir in ("sdpm/references/", "sdpm/templates/", "sdpm/vendor/"): + assert data_dir in copies, data_dir + ignored = (_ROOT / ".dockerignore").read_text(encoding="utf-8").split() + assert not any(entry.rstrip("/") in ("sdpm/vendor", "sdpm") for entry in ignored) diff --git a/web-ui/messages/en.json b/web-ui/messages/en.json index a3a341797..8521f3b47 100644 --- a/web-ui/messages/en.json +++ b/web-ui/messages/en.json @@ -121,7 +121,23 @@ "openPptx": "Open PPTX", "downloadPptx": "Download PPTX", "slideAlt": "Slide {number}", - "slideAltFull": "Slide {number} of {total}" + "slideAltFull": "Slide {number} of {total}", + "formatHtml": "HTML", + "formatBadgeTitle": "Format: HTML (presented in a browser)", + "present": "Present", + "presentAria": "Present in a new tab", + "pdf": "PDF", + "pdfAria": "Open the print view in a new tab to save as PDF", + "downloadHtml": "Download HTML", + "open": "Open", + "openHtml": "Open the HTML deck in your browser", + "playerTitle": "HTML deck", + "playerTitleNamed": "HTML deck: {name}", + "htmlPreviewsPlaceholder": "Slide previews will appear here once the HTML deck is built.", + "errorPresent": "Couldn't open the presentation", + "errorPdf": "Couldn't open the PDF view", + "errorDownloadHtml": "Couldn't download the HTML", + "errorOpenHtml": "Couldn't open the HTML" }, "outline": { "body": "Body", @@ -195,10 +211,13 @@ "slashPicker": { "sectionTemplate": "Template", "sectionStyle": "Style", + "sectionFormat": "Format", + "formatHtml": "HTML", + "formatHtmlDescription": "Present in a browser. Can't be edited in PowerPoint.", "noMatch": "No matches", "loading": "Loadingโ€ฆ", "keyHint": "โ†‘โ†“ move โ†ต insert Esc close", - "listLabel": "Template and style suggestions", + "listLabel": "Template, style and format suggestions", "previewAlt": "Preview of {name}", "unknownName": "This template or style is unavailable", "removeToken": "Remove {kind} {name}", @@ -308,6 +327,10 @@ "vibeSummary": "Start rough. See a first draft sooner.", "specSummary": "Decide the story before the slides." }, + "htmlFormatPill": { + "buildAsHtml": "Build as HTML", + "hint": "Creates an HTML deck to present in a browser. It can't be edited in PowerPoint." + }, "tools": { "running": "Running", "completed": "Completed", diff --git a/web-ui/messages/ja.json b/web-ui/messages/ja.json index e83a7043b..bce7381e8 100644 --- a/web-ui/messages/ja.json +++ b/web-ui/messages/ja.json @@ -121,7 +121,23 @@ "openPptx": "PPTX ใ‚’้–‹ใ", "downloadPptx": "PPTX ใ‚’ใƒ€ใ‚ฆใƒณใƒญใƒผใƒ‰", "slideAlt": "ใ‚นใƒฉใ‚คใƒ‰ {number}", - "slideAltFull": "ใ‚นใƒฉใ‚คใƒ‰ {number} / {total}" + "slideAltFull": "ใ‚นใƒฉใ‚คใƒ‰ {number} / {total}", + "formatHtml": "HTML", + "formatBadgeTitle": "ๅฝขๅผ: HTML๏ผˆใƒ–ใƒฉใ‚ฆใ‚ถใง็™บ่กจ๏ผ‰", + "present": "็™บ่กจ", + "presentAria": "ๆ–ฐใ—ใ„ใ‚ฟใƒ–ใง็™บ่กจ", + "pdf": "PDF", + "pdfAria": "ๆ–ฐใ—ใ„ใ‚ฟใƒ–ใงๅฐๅˆท็”ป้ขใ‚’้–‹ใ„ใฆ PDF ใซไฟๅญ˜", + "downloadHtml": "HTML ใ‚’ใƒ€ใ‚ฆใƒณใƒญใƒผใƒ‰", + "open": "้–‹ใ", + "openHtml": "HTML ใƒ‡ใƒƒใ‚ญใ‚’ใƒ–ใƒฉใ‚ฆใ‚ถใง้–‹ใ", + "playerTitle": "HTML ใƒ‡ใƒƒใ‚ญ", + "playerTitleNamed": "HTML ใƒ‡ใƒƒใ‚ญ: {name}", + "htmlPreviewsPlaceholder": "HTML ใƒ‡ใƒƒใ‚ญใ‚’ใƒ“ใƒซใƒ‰ใ™ใ‚‹ใจใ‚นใƒฉใ‚คใƒ‰ใƒ—ใƒฌใƒ“ใƒฅใƒผใŒใ“ใ“ใซ่กจ็คบใ•ใ‚Œใพใ™ใ€‚", + "errorPresent": "็™บ่กจใ‚’้–‹ใ‘ใพใ›ใ‚“ใงใ—ใŸ", + "errorPdf": "PDF ็”จใฎ็”ป้ขใ‚’้–‹ใ‘ใพใ›ใ‚“ใงใ—ใŸ", + "errorDownloadHtml": "HTML ใ‚’ใƒ€ใ‚ฆใƒณใƒญใƒผใƒ‰ใงใใพใ›ใ‚“ใงใ—ใŸ", + "errorOpenHtml": "HTML ใ‚’้–‹ใ‘ใพใ›ใ‚“ใงใ—ใŸ" }, "outline": { "body": "ๆœฌๆ–‡", @@ -195,10 +211,13 @@ "slashPicker": { "sectionTemplate": "ใƒ†ใƒณใƒ—ใƒฌใƒผใƒˆ", "sectionStyle": "ใ‚นใ‚ฟใ‚คใƒซ", + "sectionFormat": "ๅฝขๅผ", + "formatHtml": "HTML", + "formatHtmlDescription": "ใƒ–ใƒฉใ‚ฆใ‚ถใง็™บ่กจใ—ใพใ™ใ€‚PowerPoint ใงใฏ็ทจ้›†ใงใใพใ›ใ‚“", "noMatch": "่ฉฒๅฝ“ใชใ—", "loading": "่ชญใฟ่พผใฟไธญโ€ฆ", "keyHint": "โ†‘โ†“ ็งปๅ‹• โ†ต ๆŒฟๅ…ฅ Esc ้–‰ใ˜ใ‚‹", - "listLabel": "ใƒ†ใƒณใƒ—ใƒฌใƒผใƒˆ / ใ‚นใ‚ฟใ‚คใƒซใฎๅ€™่ฃœ", + "listLabel": "ใƒ†ใƒณใƒ—ใƒฌใƒผใƒˆ / ใ‚นใ‚ฟใ‚คใƒซ / ๅฝขๅผใฎๅ€™่ฃœ", "previewAlt": "{name} ใฎใƒ—ใƒฌใƒ“ใƒฅใƒผ", "unknownName": "ใ“ใฎใƒ†ใƒณใƒ—ใƒฌใƒผใƒˆใพใŸใฏใ‚นใ‚ฟใ‚คใƒซใฏๅˆฉ็”จใงใใพใ›ใ‚“", "removeToken": "{kind}ใ€Œ{name}ใ€ใ‚’ๅ‰Š้™ค", @@ -308,6 +327,10 @@ "vibeSummary": "ใƒฉใƒ•ใช็ด ๆใ‹ใ‚‰ใ€ใพใšๅˆ็จฟใ‚’ใ™ใฐใ‚„ใๅฝขใซใ—ใพใ™ใ€‚", "specSummary": "ใ‚นใƒฉใ‚คใƒ‰ใ‚’ไฝœใ‚‹ๅ‰ใซใ€ไผใˆใ‚‹ใ‚นใƒˆใƒผใƒชใƒผใ‚’ๅ›บใ‚ใพใ™ใ€‚" }, + "htmlFormatPill": { + "buildAsHtml": "HTML ใงไฝœๆˆ", + "hint": "ใƒ–ใƒฉใ‚ฆใ‚ถใง็™บ่กจใ™ใ‚‹ HTML ใ‚’ไฝœใ‚Šใพใ™ใ€‚PowerPoint ใงใฏ็ทจ้›†ใงใใพใ›ใ‚“" + }, "tools": { "running": "ๅฎŸ่กŒไธญ", "completed": "ๅฎŒไบ†", diff --git a/web-ui/package.json b/web-ui/package.json index 7dc70a416..7f4015cf3 100644 --- a/web-ui/package.json +++ b/web-ui/package.json @@ -4,8 +4,8 @@ "private": true, "license": "MIT-0", "scripts": { - "dev": "next dev --turbopack", - "dev:local": "NEXT_PUBLIC_MODE=local next dev --turbopack", + "dev": "next dev --turbopack --hostname 127.0.0.1", + "dev:local": "NEXT_PUBLIC_MODE=local next dev --turbopack --hostname 127.0.0.1", "build": "next build", "build:cloud": "bash -c 'trap \"mv src/app/_api src/app/api 2>/dev/null\" EXIT; mv src/app/api src/app/_api && next build'", "start": "next start", diff --git a/web-ui/playwright.config.ts b/web-ui/playwright.config.ts index 4524eaccc..e28a94077 100644 --- a/web-ui/playwright.config.ts +++ b/web-ui/playwright.config.ts @@ -22,12 +22,13 @@ export default defineConfig({ retries: process.env.CI ? 1 : 0, reporter: process.env.CI ? "github" : "list", use: { - baseURL: `http://localhost:${PORT}`, + baseURL: `http://127.0.0.1:${PORT}`, trace: "retain-on-failure", }, webServer: { - command: `npx next dev --turbopack --port ${PORT}`, - port: PORT, + // Loopback only: the local API routes (file access, /api/open) have no auth. + command: `npx next dev --turbopack --hostname 127.0.0.1 --port ${PORT}`, + url: `http://127.0.0.1:${PORT}`, reuseExistingServer: false, timeout: 120_000, env: { diff --git a/web-ui/src/app/(authenticated)/decks/page.tsx b/web-ui/src/app/(authenticated)/decks/page.tsx index d35952b52..ae7c20f7f 100644 --- a/web-ui/src/app/(authenticated)/decks/page.tsx +++ b/web-ui/src/app/(authenticated)/decks/page.tsx @@ -176,6 +176,9 @@ export default function DecksPage() { deckId={ws.isNew ? ws.createdDeckId || undefined : ws.activeDeckId!} deckName={ws.deck?.name} pptxUrl={ws.deck?.pptxUrl} + outputFormat={ws.deck?.outputFormat} + htmlUrl={ws.deck?.htmlUrl} + slideSize={ws.deck?.slideSize} isLoading={ws.waitingForPng || false} scrollToSlide={ws.scrollToSlide} onScrollComplete={() => ws.setScrollToSlide("")} diff --git a/web-ui/src/app/api/decks/[id]/route.ts b/web-ui/src/app/api/decks/[id]/route.ts index d97e8caa5..ac9f4acd4 100644 --- a/web-ui/src/app/api/decks/[id]/route.ts +++ b/web-ui/src/app/api/decks/[id]/route.ts @@ -16,6 +16,38 @@ function safeRead(p: string): string | null { try { return fs.existsSync(p) ? fs.readFileSync(p, "utf-8") : null } catch { return null } } +/** Slug grammar of HTML slide files (`slides/.html`), as in the core engine. */ +const HTML_SLUG_RE = /^[a-z0-9][a-z0-9_-]*$/ + +/** `?v=` cache-buster so the UI sees a rebuilt file as a new URL; null when absent. */ +function versionedUrl(filePath: string, url: string): string | null { + try { return `${url}?v=${Math.floor(fs.statSync(filePath).mtimeMs)}` } catch { return null } +} + +/** deck.json slideSize as {width, height} CSS px (1920x1080 when missing or invalid). */ +function htmlSlideSize(deckJson: Record): { width: number; height: number } { + const size = deckJson.slideSize as { width?: unknown; height?: unknown } | undefined + const ok = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v) && v > 0 + return size && ok(size.width) && ok(size.height) ? { width: size.width, height: size.height } : { width: 1920, height: 1080 } +} + +/** HTML deck slides: `slides/.html` in outline order, previews from `preview/.html`. */ +function htmlSlides(dp: string, deckId: string, outlineSlugs: string[]): Record[] { + // `dp` comes from resolveDeckDir (allow-list + realpath check); every slug passes HTML_SLUG_RE before it is joined. + const slidesDir = path.join(dp, "slides") // nosemgrep: path-join-resolve-traversal โ€” dp validated by resolveDeckDir + if (!fs.existsSync(slidesDir)) return [] + const slugList = outlineSlugs.length > 0 ? outlineSlugs + : fs.readdirSync(slidesDir).filter(f => f.endsWith(".html")).map(f => f.slice(0, -".html".length)).sort() + return slugList + .filter(slug => HTML_SLUG_RE.test(slug) && fs.existsSync(path.join(slidesDir, `${slug}.html`))) // nosemgrep: path-join-resolve-traversal โ€” slug checked by HTML_SLUG_RE first + .map(slug => ({ + slug, + previewUrl: versionedUrl(path.join(dp, "preview", `${slug}.html`), `/api/preview/${deckId}/preview/${slug}.html`), // nosemgrep: path-join-resolve-traversal โ€” slug passed HTML_SLUG_RE above + composeUrl: null, + updatedAt: new Date().toISOString(), + })) +} + export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) { const { id: deckId } = await params const dp = resolveDeckDir(deckId) @@ -66,12 +98,13 @@ export async function GET(_req: Request, { params }: { params: Promise<{ id: str } // Build slides array + const isHtml = deckJson.outputFormat === "html" const slidesDir = path.join(dp, "slides") - const slides: Record[] = [] + const slides: Record[] = isHtml ? htmlSlides(dp, deckId, outlineSlugs) : [] let slugList = outlineSlugs.length > 0 ? outlineSlugs : (fs.existsSync(slidesDir) ? fs.readdirSync(slidesDir).filter(f => f.endsWith(".json")).map(f => f.replace(".json", "")) : []) let pageNum = 0 - if (fs.existsSync(slidesDir)) { + if (!isHtml && fs.existsSync(slidesDir)) { for (const slug of slugList) { if (!fs.existsSync(path.join(slidesDir, `${slug}.json`))) continue pageNum++ @@ -112,6 +145,11 @@ export async function GET(_req: Request, { params }: { params: Promise<{ id: str isOwner: true, collaborators: [], collaboratorAliases: {}, + ...(isHtml ? { + outputFormat: "html", + htmlUrl: versionedUrl(path.join(dp, "output.html"), `/api/preview/${deckId}/output.html`), + slideSize: htmlSlideSize(deckJson), + } : {}), }) } diff --git a/web-ui/src/app/api/decks/route.ts b/web-ui/src/app/api/decks/route.ts index 00beeb708..6164afc11 100644 --- a/web-ui/src/app/api/decks/route.ts +++ b/web-ui/src/app/api/decks/route.ts @@ -32,23 +32,43 @@ export async function GET() { const deckId = e.name const dp = path.join(DECK_ROOT, deckId) let name = deckId + let isHtml = false for (const fname of ["deck.json", "presentation.json"]) { const p = path.join(dp, fname) if (fs.existsSync(p)) { - try { name = JSON.parse(fs.readFileSync(p, "utf-8")).name || deckId } catch {} + try { + const deckJson = JSON.parse(fs.readFileSync(p, "utf-8")) + name = deckJson.name || deckId + isHtml = deckJson.outputFormat === "html" + } catch {} break } } let slideCount = 0 const slidesDir = path.join(dp, "slides") if (fs.existsSync(slidesDir)) { - slideCount = fs.readdirSync(slidesDir).filter(f => f.endsWith(".json")).length + slideCount = fs.readdirSync(slidesDir).filter(f => f.endsWith(isHtml ? ".html" : ".json")).length } let thumbnailUrl: string | null = null const previewDir = path.join(dp, "preview") if (fs.existsSync(previewDir)) { - const first = fs.readdirSync(previewDir).filter(f => f.endsWith(".png")).sort()[0] + const files = fs.readdirSync(previewDir).sort() + const first = files.find(f => f.endsWith(".png")) + // HTML decks have no PNG previews: fall back to a static HTML preview, slide 1 + // of the outline when it has one (as in cloud), else the first by name. + const htmlPreviews = first ? [] : files.filter(f => /^[a-z0-9][a-z0-9_-]*\.html$/.test(f)) + const firstHtml = htmlPreviews.length === 0 ? undefined : (() => { + let outline = "" + try { outline = fs.readFileSync(path.join(dp, "specs", "outline.md"), "utf-8") } catch {} + const slug = outline.split("\n").map(l => /^-\s*\[([a-z0-9-]+)\]/.exec(l)?.[1]) + .find(s => s && htmlPreviews.includes(`${s}.html`)) + return slug ? `${slug}.html` : htmlPreviews[0] + })() if (first) thumbnailUrl = `/api/preview/${deckId}/preview/${first}` + else if (firstHtml) { + const mtime = Math.floor(fs.statSync(path.join(previewDir, firstHtml)).mtimeMs) + thumbnailUrl = `/api/preview/${deckId}/preview/${firstHtml}?v=${mtime}` + } } const pptxPath = path.join(dp, "output.pptx") const pptxUrl = fs.existsSync(pptxPath) ? `/api/preview/${deckId}/output.pptx` : null diff --git a/web-ui/src/app/api/preview/[...path]/route.ts b/web-ui/src/app/api/preview/[...path]/route.ts index f65412ccb..302f47fb3 100644 --- a/web-ui/src/app/api/preview/[...path]/route.ts +++ b/web-ui/src/app/api/preview/[...path]/route.ts @@ -4,6 +4,12 @@ * Local Preview File Server โ€” serves deck assets (PNG, JSON, PPTX) from filesystem. * URL: /api/preview/{deckId}/{subpath...} * Local mode only. + * + * HTML is served for exactly two paths of an HTML deck, each with a CSP + * `sandbox` header so the document never runs with this app's origin: + * - `output.html`: the reveal.js deck (`sandbox allow-scripts allow-popups`) + * - `preview/.html`: static slide thumbnails (`sandbox`, no scripts) + * Every other `.html` path is 404. */ @@ -19,6 +25,15 @@ const MIME: Record = { ".svg": "image/svg+xml", } +const HTML_PREVIEW_FILE_RE = /^[a-z0-9][a-z0-9_-]*\.html$/ + +/** CSP sandbox for an allowed HTML path, or null when the path must not be served. */ +function htmlSandbox(rest: string[]): string | null { + if (rest.length === 1 && rest[0] === "output.html") return "sandbox allow-scripts allow-popups" + if (rest.length === 2 && rest[0] === "preview" && HTML_PREVIEW_FILE_RE.test(rest[1])) return "sandbox" + return null +} + export async function GET(_req: Request, { params }: { params: Promise<{ path: string[] }> }) { const segments = (await params).path if (!segments || segments.length < 2) return new Response("Not found", { status: 404 }) @@ -29,6 +44,18 @@ export async function GET(_req: Request, { params }: { params: Promise<{ path: s if (!fs.existsSync(filePath)) return new Response("Not found", { status: 404 }) const ext = path.extname(filePath).toLowerCase() + if (ext === ".html") { + const sandbox = htmlSandbox(rest) + if (!sandbox) return new Response("Not found", { status: 404 }) + return new Response(fs.readFileSync(filePath), { + headers: { + "Content-Type": "text/html; charset=utf-8", + "Content-Security-Policy": sandbox, + "X-Content-Type-Options": "nosniff", + "Cache-Control": "no-cache", + }, + }) + } const contentType = MIME[ext] if (!contentType) return new Response("Not found", { status: 404 }) const body = fs.readFileSync(filePath) diff --git a/web-ui/src/components/chat/ChatInput.test.tsx b/web-ui/src/components/chat/ChatInput.test.tsx index 6a6565655..9d0327b89 100644 --- a/web-ui/src/components/chat/ChatInput.test.tsx +++ b/web-ui/src/components/chat/ChatInput.test.tsx @@ -66,7 +66,7 @@ describe("ChatInput slash picker", () => { const { onSend, textarea } = renderInput() changeValue(textarea, "/") - expect(screen.getByRole("listbox", { name: "Template and style suggestions" })).toBeTruthy() + expect(screen.getByRole("listbox", { name: "Template, style and format suggestions" })).toBeTruthy() expect(textarea.getAttribute("aria-expanded")).toBe("true") fireEvent.keyDown(textarea, { key: "ArrowDown" }) @@ -129,3 +129,34 @@ describe("ChatInput slash picker", () => { expect(textarea.getAttribute("aria-expanded")).toBe("true") }) }) + +describe("ChatInput replaceText", () => { + it("replaces the whole input, notifies onInputChange and keeps focus with the caret at the end", () => { + const onInputChange = vi.fn() + const { handle, textarea } = renderInput({ onInputChange }) + changeValue(textarea, "a launch deck") + onInputChange.mockClear() + + const raf = vi.spyOn(window, "requestAnimationFrame").mockImplementation((cb) => { cb(0); return 0 }) + act(() => handle.current?.replaceText("@format:html a launch deck")) + raf.mockRestore() + + expect(textarea.value).toBe("@format:html a launch deck") + expect(onInputChange).toHaveBeenCalledWith("@format:html a launch deck") + expect(document.activeElement).toBe(textarea) + expect(textarea.selectionStart).toBe("@format:html a launch deck".length) + }) + + it("mirrors picker inserts and the send reset through onInputChange", () => { + const onInputChange = vi.fn() + const { onSend, textarea } = renderInput({ onInputChange }) + changeValue(textarea, "/") + fireEvent.keyDown(textarea, { key: "ArrowDown" }) + fireEvent.keyDown(textarea, { key: "Enter" }) + expect(onInputChange).toHaveBeenLastCalledWith("@style:lumina ") + + fireEvent.keyDown(textarea, { key: "Enter", metaKey: true }) + expect(onSend).toHaveBeenCalled() + expect(onInputChange).toHaveBeenLastCalledWith("") + }) +}) diff --git a/web-ui/src/components/chat/ChatInput.tsx b/web-ui/src/components/chat/ChatInput.tsx index f81757e8b..ccbdfd8f3 100644 --- a/web-ui/src/components/chat/ChatInput.tsx +++ b/web-ui/src/components/chat/ChatInput.tsx @@ -71,6 +71,8 @@ export interface ChatInputProps { export interface ChatInputHandle { insertAtCursor: (text: string) => void + /** Replace the whole input (e.g. the HTML format pill); keeps focus, caret at the end. */ + replaceText: (next: string) => void focus: () => void /** Ref to the internal textarea element (for MentionOverlay positioning). */ textareaRef: React.RefObject @@ -106,10 +108,17 @@ export const ChatInput = forwardRef(function Ch }, 400) }, []) + // Every programmatic change goes through here so `onInputChange` mirrors the + // textarea exactly (picker inserts, example prompts, send reset, pill toggle). + const updateInput = useCallback((next: string) => { + setInput(next) + onInputChange?.(next) + }, [onInputChange]) + const picker = useSlashPicker({ textareaRef, value: input, - setValue: setInput, + setValue: updateInput, items: slashItems ?? [], onInserted: handleSlashInserted, }) @@ -134,7 +143,7 @@ export const ChatInput = forwardRef(function Ch const after = input.slice(end) const next = before + text + after const pos = start + text.length - setInput(next) + updateInput(next) // Programmatic inserts bypass onChange, so feed the slash picker here too // (e.g. the empty-state hint inserts "/" to open it). if (slashEnabled) picker.onInputChange(next, pos) @@ -143,6 +152,16 @@ export const ChatInput = forwardRef(function Ch ta.setSelectionRange(pos, pos) }) }, + replaceText(next: string) { + updateInput(next) + picker.close() + const ta = textareaRef.current + if (!ta) return + requestAnimationFrame(() => { + ta.focus() + ta.setSelectionRange(next.length, next.length) + }) + }, focus() { textareaRef.current?.focus() }, @@ -151,7 +170,7 @@ export const ChatInput = forwardRef(function Ch handleFilesRef.current(fakeList) }, textareaRef, - }), [input, picker, slashEnabled]) + }), [input, picker, slashEnabled, updateInput]) const handleFiles = useCallback((files: FileList) => { const currentCount = attachments.length @@ -195,13 +214,12 @@ export const ChatInput = forwardRef(function Ch const removeSlashToken = useCallback((match: TokenMatch) => { const end = input[match.end] === " " ? match.end + 1 : match.end const next = input.slice(0, match.start) + input.slice(end) - setInput(next) - onInputChange?.(next) + updateInput(next) requestAnimationFrame(() => { textareaRef.current?.focus() textareaRef.current?.setSelectionRange(match.start, match.start) }) - }, [input, onInputChange]) + }, [input, updateInput]) const handleSend = async () => { if ((!input.trim() && attachments.length === 0 && snippets.length === 0) || isLoading || disabled) return @@ -237,7 +255,7 @@ export const ChatInput = forwardRef(function Ch const sentAttachments = uploadedFiles.map((f) => ({ fileName: f.fileName, fileType: f.fileType })) onSend(input, uploadedFiles, sentSnippets, sentAttachments) - setInput("") + updateInput("") picker.close() setAttachments([]) setSnippets([]) @@ -314,9 +332,8 @@ export const ChatInput = forwardRef(function Ch maxRows={5} value={input} onChange={(e) => { - setInput(e.target.value) + updateInput(e.target.value) if (slashEnabled) picker.onInputChange(e.target.value, e.target.selectionStart) - onInputChange?.(e.target.value) }} onKeyDown={(e) => { if (slashEnabled && picker.onKeyDown(e, getIsComposing(e))) return diff --git a/web-ui/src/components/chat/ChatMessage.tsx b/web-ui/src/components/chat/ChatMessage.tsx index a4b0a153f..1e276480a 100644 --- a/web-ui/src/components/chat/ChatMessage.tsx +++ b/web-ui/src/components/chat/ChatMessage.tsx @@ -22,7 +22,7 @@ import { useState, useEffect } from "react" import Markdown from "react-markdown" import type { Components } from "react-markdown" import remarkGfm from "remark-gfm" -import { ChevronRight, Sparkles, FileText as FileTextIcon, Image as ImageIcon } from "lucide-react" +import { ChevronRight, CodeXml, Sparkles, FileText as FileTextIcon, Image as ImageIcon } from "lucide-react" import { ToolCard, ToolCardCompact } from "./ToolCard" import { HearingCard } from "./HearingCard" import { SnippetBlock } from "./SnippetBlock" @@ -40,6 +40,7 @@ function extractQuestions(input: Record): HearingQuestion[] { } const MENTION_RE = new RegExp(`(@Page\\s\\d+|@\\[[^\\]]+\\]|${SLASH_TOKEN_SOURCE})`) +const FORMAT_HTML_TOKEN_RE = /^@format:(?:html|"html")$/ const SLIDE_PREVIEW_RE = /\[slide-preview:([a-f0-9]+):([a-z0-9][a-z0-9_-]*)\]/g const COLOR_CODE_RE = /(#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{3}))\b/g @@ -60,6 +61,17 @@ function renderInlinePreviews(text: string, urls: Record): strin }) } +/** Sent-message chip for the `@format:html` token (label shared with the input chip). */ +function FormatHtmlChip() { + const t = useTranslations("slashPicker") + return ( + + + ) +} + /** * Highlight @Page N and @[DeckName] mentions within a text string, * and render inline color swatches next to hex color codes (#RGB / #RRGGBB). @@ -72,6 +84,9 @@ function highlightMentions(text: string): (string | React.JSX.Element)[] { const COMBINED_RE = new RegExp(`(@Page\\s\\d+|@\\[[^\\]]+\\]|${SLASH_TOKEN_SOURCE}|#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{3})\\b)`, "g") const parts = text.split(COMBINED_RE) return parts.map((part, i) => { + if (FORMAT_HTML_TOKEN_RE.test(part)) { + return + } if (MENTION_RE.test(part)) { return {part} } diff --git a/web-ui/src/components/chat/ChatPanel.tsx b/web-ui/src/components/chat/ChatPanel.tsx index cc151ecf0..754c0d7fd 100644 --- a/web-ui/src/components/chat/ChatPanel.tsx +++ b/web-ui/src/components/chat/ChatPanel.tsx @@ -25,6 +25,7 @@ import { FileDropZone } from "./FileDropZone" import { useIsMobile } from "@/hooks/UseMobile" import { Send, ChevronRight, GitBranch } from "lucide-react" import { ModeSelector } from "./ModeSelector" +import { HtmlFormatPill } from "./HtmlFormatPill" import { SessionPickerDialog } from "./SessionPickerDialog" import { ContinuedFromChip } from "./ContinuedFromChip" import { ForkProgressCard } from "./ForkProgressCard" @@ -142,6 +143,8 @@ export const ChatPanel = forwardRef(function Ch const auth = useAuth() const isMobile = useIsMobile() const slashPickerItems = useSlashPickerItems(auth.user?.id_token) + // Mirror of the chat input; the HTML pill derives its state from the text alone. + const [inputText, setInputText] = useState("") /** Persist chat messages to disk (Local mode only). */ const saveLocalChat = useCallback((overrideDeckId?: string) => { @@ -630,6 +633,7 @@ export const ChatPanel = forwardRef(function Ch
)} + chatInputRef.current?.replaceText(next)} /> ) : (
@@ -682,6 +686,8 @@ export const ChatPanel = forwardRef(function Ch slashLoading={slashPickerItems.loading} onSlashOpen={slashPickerItems.ensure} onTextareaFocus={slashPickerItems.ensure} + // Only the initial screen shows the pill; skip the per-keystroke re-render of a long chat. + onInputChange={isInitial ? setInputText : undefined} > {/* Options expander โ€” the only option (web images) is cloud-only */} {!IS_LOCAL && ( diff --git a/web-ui/src/components/chat/HtmlFormatPill.test.tsx b/web-ui/src/components/chat/HtmlFormatPill.test.tsx new file mode 100644 index 000000000..ab3d6ccac --- /dev/null +++ b/web-ui/src/components/chat/HtmlFormatPill.test.tsx @@ -0,0 +1,34 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: MIT-0 + +import { afterEach, describe, expect, it, vi } from "vitest" +import { cleanup, fireEvent, screen } from "@testing-library/react" +import { renderWithIntl } from "@/test/renderWithIntl" +import { HtmlFormatPill } from "./HtmlFormatPill" + +afterEach(cleanup) + +const HINT = "Creates an HTML deck to present in a browser. It can't be edited in PowerPoint." + +describe("HtmlFormatPill", () => { + it("is not pressed without the token and turns it on", () => { + const onChange = vi.fn() + renderWithIntl() + + const pill = screen.getByRole("button", { name: "Build as HTML" }) + expect(pill.getAttribute("aria-pressed")).toBe("false") + expect(pill.getAttribute("title")).toBe(HINT) + fireEvent.click(pill) + expect(onChange).toHaveBeenCalledWith("@format:html a launch deck") + }) + + it("is pressed exactly when the input holds @format:html and turns it off", () => { + const onChange = vi.fn() + renderWithIntl() + + const pill = screen.getByRole("button", { name: "Build as HTML" }) + expect(pill.getAttribute("aria-pressed")).toBe("true") + fireEvent.click(pill) + expect(onChange).toHaveBeenCalledWith("a launch deck") + }) +}) diff --git a/web-ui/src/components/chat/HtmlFormatPill.tsx b/web-ui/src/components/chat/HtmlFormatPill.tsx new file mode 100644 index 000000000..6a8e6e54a --- /dev/null +++ b/web-ui/src/components/chat/HtmlFormatPill.tsx @@ -0,0 +1,44 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: MIT-0 +/** + * HtmlFormatPill โ€” "Build as HTML" toggle on the initial chat screen. + * + * Holds no state of its own: it is pressed exactly when the input contains + * `@format:html`, and pressing it adds or removes that token. PPTX (the + * default) sends nothing. + */ + +"use client" + +import { Check, CodeXml } from "lucide-react" +import { useTranslations } from "next-intl" +import { hasFormatToken, toggleFormatToken } from "@/lib/slashToken" + +interface HtmlFormatPillProps { + /** Current chat input text. */ + text: string + /** Replace the chat input with the toggled text. */ + onChange: (next: string) => void +} + +export function HtmlFormatPill({ text, onChange }: HtmlFormatPillProps) { + const t = useTranslations("htmlFormatPill") + const pressed = hasFormatToken(text) + + return ( + + ) +} diff --git a/web-ui/src/components/chat/SlashPickerPopup.test.tsx b/web-ui/src/components/chat/SlashPickerPopup.test.tsx index f2180162d..7c1177483 100644 --- a/web-ui/src/components/chat/SlashPickerPopup.test.tsx +++ b/web-ui/src/components/chat/SlashPickerPopup.test.tsx @@ -4,7 +4,7 @@ import { afterEach, describe, expect, it, vi } from "vitest" import { cleanup, fireEvent, screen } from "@testing-library/react" import { renderWithIntl } from "@/test/renderWithIntl" -import type { PickerItem } from "@/lib/slashToken" +import { FORMAT_HTML_ITEM, type PickerItem } from "@/lib/slashToken" import { SlashPickerPopup, type SlashPickerPopupProps } from "./SlashPickerPopup" vi.mock("@/hooks/UseMobile", () => ({ useIsMobile: () => false })) @@ -53,13 +53,27 @@ afterEach(() => { }) describe("SlashPickerPopup", () => { + it("renders the Format section last with the localized HTML option", () => { + const all = [...items, FORMAT_HTML_ITEM] + const onSelect = vi.fn() + renderPopup({ items: all, filtered: all, activeIndex: 2, onSelect }) + + const styleHeading = screen.getByText("Style") + const formatHeading = screen.getByText("Format") + expect(styleHeading.compareDocumentPosition(formatHeading) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() + const option = screen.getByRole("option", { name: /HTML/ }) + expect(option.textContent).toContain("Present in a browser. Can't be edited in PowerPoint.") + fireEvent.click(option) + expect(onSelect).toHaveBeenCalledWith(FORMAT_HTML_ITEM) + }) + it("renders non-empty sections in template then style order", () => { renderPopup() const templateHeading = screen.getByText("Template") const styleHeading = screen.getByText("Style") expect(templateHeading.compareDocumentPosition(styleHeading) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() - expect(screen.getByRole("listbox", { name: "Template and style suggestions" }).id).toBe("slash-listbox") + expect(screen.getByRole("listbox", { name: "Template, style and format suggestions" }).id).toBe("slash-listbox") }) it("hides an empty section and marks custom items", () => { diff --git a/web-ui/src/components/chat/SlashPickerPopup.tsx b/web-ui/src/components/chat/SlashPickerPopup.tsx index 44473b821..a0e3f2ea0 100644 --- a/web-ui/src/components/chat/SlashPickerPopup.tsx +++ b/web-ui/src/components/chat/SlashPickerPopup.tsx @@ -1,18 +1,18 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 /** - * SlashPickerPopup โ€” Portal-based template/style autocomplete presentation. + * SlashPickerPopup โ€” Portal-based template/style/format autocomplete presentation. */ "use client" import { useEffect, useRef, useState } from "react" import { createPortal } from "react-dom" -import { Star } from "lucide-react" +import { CodeXml, Star } from "lucide-react" import { useTranslations } from "next-intl" import { buildCoverDoc } from "@/components/StyleSlidePreview" import { useIsMobile } from "@/hooks/UseMobile" -import type { PickerItem, PickerKind } from "@/lib/slashToken" +import { sectionTitleKey, type PickerItem, type PickerKind } from "@/lib/slashToken" /** * DOM id of the option at `index`. Index-based (not name-based) because quoted @@ -80,6 +80,45 @@ function StyleIdentifier({ pinned }: { pinned: boolean }) { ) } +function FormatIdentifier() { + return ( + + ) +} + +/** Localized label and description of a format candidate (its `name` is the token value). */ +function useFormatText(item: PickerItem): { label: string; description: string } { + const t = useTranslations("slashPicker") + return { label: t("formatHtml"), description: item.description || t("formatHtmlDescription") } +} + +function FormatPreview({ item }: { item: PickerItem }) { + const { label, description } = useFormatText(item) + return ( + <> + +
+

{label}

+

{description}

+
+ + ) +} + +function FormatRowText({ item }: { item: PickerItem }) { + const { label, description } = useFormatText(item) + return ( + <> + {label} + {description} + + ) +} + function DebouncedStylePreview({ item }: { item: PickerItem }) { const t = useTranslations("slashPicker") const [previewDoc, setPreviewDoc] = useState(null) @@ -175,6 +214,8 @@ function PreviewPanel({ item }: { item: PickerItem | undefined }) { ) : item.kind === "template" ? ( + ) : item.kind === "format" ? ( + ) : ( <>
@@ -209,7 +250,7 @@ function Section({ return (
- {t(kind === "template" ? "sectionTemplate" : "sectionStyle")} + {t(sectionTitleKey(kind))}
{items.map((item) => { const index = allItems.indexOf(item) @@ -229,13 +270,25 @@ function Section({ }`} > {active &&
diff --git a/web-ui/src/components/chat/SlashTokenReflection.test.tsx b/web-ui/src/components/chat/SlashTokenReflection.test.tsx index c28333f6a..b90933601 100644 --- a/web-ui/src/components/chat/SlashTokenReflection.test.tsx +++ b/web-ui/src/components/chat/SlashTokenReflection.test.tsx @@ -4,7 +4,7 @@ import { afterEach, describe, expect, it, vi } from "vitest" import { cleanup, fireEvent, screen } from "@testing-library/react" import { renderWithIntl } from "@/test/renderWithIntl" -import type { PickerItem } from "@/lib/slashToken" +import { FORMAT_HTML_ITEM, type PickerItem } from "@/lib/slashToken" import { SlashTokenReflection } from "./SlashTokenReflection" const items: PickerItem[] = [ @@ -84,4 +84,17 @@ describe("SlashTokenReflection", () => { end: 17, }) }) + + it("renders @format:html as an HTML chip that can be removed", () => { + const onRemove = vi.fn() + renderWithIntl( + , + ) + + expect(screen.getByText("HTML")).toBeTruthy() + expect(screen.queryByText("Format")).toBeNull() + expect(screen.queryByTitle("This template or style is unavailable")).toBeNull() + fireEvent.click(screen.getByRole("button", { name: "Remove Format HTML" })) + expect(onRemove).toHaveBeenCalledWith({ kind: "format", name: "html", start: 0, end: 12 }) + }) }) diff --git a/web-ui/src/components/chat/SlashTokenReflection.tsx b/web-ui/src/components/chat/SlashTokenReflection.tsx index 7841d3717..18c031a40 100644 --- a/web-ui/src/components/chat/SlashTokenReflection.tsx +++ b/web-ui/src/components/chat/SlashTokenReflection.tsx @@ -1,14 +1,14 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 /** - * SlashTokenReflection โ€” Text-derived chips for template/style tokens in chat input. + * SlashTokenReflection โ€” Text-derived chips for template/style/format tokens in chat input. */ "use client" -import { Star, X } from "lucide-react" +import { CodeXml, Star, X } from "lucide-react" import { useTranslations } from "next-intl" -import { parseTokens, type PickerItem, type TokenMatch } from "@/lib/slashToken" +import { FORMAT_HTML_ITEM, parseTokens, sectionTitleKey, type PickerItem, type TokenMatch } from "@/lib/slashToken" export interface SlashTokenReflectionProps { text: string @@ -43,6 +43,14 @@ function StyleTokenMark({ item }: { item: PickerItem }) { ) } +function FormatTokenMark() { + return ( + + ) +} + export function SlashTokenReflection({ text, items, onRemove }: SlashTokenReflectionProps) { const t = useTranslations("slashPicker") const matches = parseTokens(text) @@ -54,6 +62,10 @@ export function SlashTokenReflection({ text, items, onRemove }: SlashTokenReflec const item = items.find((candidate) => candidate.kind === match.kind && candidate.name === match.name) // Before the catalogue has loaded nothing is known yet โ€” don't flag every chip as unknown. const unknown = items.length > 0 && item == null + // `@format:html` reads as a plain "HTML" chip; other kinds show " ". + const isHtmlFormat = match.kind === "format" && match.name === FORMAT_HTML_ITEM.name + const kindLabel = t(sectionTitleKey(match.kind)) + const nameLabel = isHtmlFormat ? t("formatHtml") : match.name return ( {item ? ( - item.kind === "template" ? : + item.kind === "template" ? ( + + ) : item.kind === "format" ? ( + + ) : ( + + ) ) : ( )} - - {t(match.kind === "template" ? "sectionTemplate" : "sectionStyle")} - - {match.name} + {!isHtmlFormat && {kindLabel}} + {nameLabel} diff --git a/web-ui/src/components/deck/DeckCard.test.tsx b/web-ui/src/components/deck/DeckCard.test.tsx index 77ab740de..1fd5a76ef 100644 --- a/web-ui/src/components/deck/DeckCard.test.tsx +++ b/web-ui/src/components/deck/DeckCard.test.tsx @@ -47,3 +47,20 @@ describe("DeckCard selection", () => { expect(screen.getByRole("checkbox").getAttribute("aria-checked")).toBe("true") }) }) + +describe("DeckCard thumbnail", () => { + it("renders an HTML deck thumbnail in a sandbox=\"\" iframe", () => { + const html = { ...deck, thumbnailUrl: "https://b.s3.ap-northeast-1.amazonaws.com/html/d1/preview/intro_1.html?X-Amz-Signature=x" } + const { container } = renderWithIntl( {}} />) + expect(container.querySelector("img")).toBeNull() + expect(container.querySelector("iframe")?.getAttribute("sandbox")).toBe("") + expect(screen.getByRole("img", { name: "Preview of Quarterly review" })).toBeTruthy() + }) + + it("keeps for image thumbnails", () => { + const png = { ...deck, thumbnailUrl: "/api/preview/d1/preview/intro.png" } + const { container } = renderWithIntl( {}} />) + expect(container.querySelector("iframe")).toBeNull() + expect(container.querySelector("img")?.getAttribute("src")).toBe("/api/preview/d1/preview/intro.png") + }) +}) diff --git a/web-ui/src/components/deck/DeckCard.tsx b/web-ui/src/components/deck/DeckCard.tsx index 561715726..cf5161736 100644 --- a/web-ui/src/components/deck/DeckCard.tsx +++ b/web-ui/src/components/deck/DeckCard.tsx @@ -29,6 +29,8 @@ import { CloudOnly, IS_LOCAL } from "@/lib/mode" import { formatDate, meshGradient } from "@/lib/utils" import { useTranslations } from "next-intl" import { useLocale } from "@/i18n/LocaleProvider" +import { isHtmlPreview } from "@/lib/preview" +import { HtmlSlideFrame } from "@/components/deck/HtmlSlideFrame" interface DeckCardProps { @@ -204,7 +206,14 @@ export function DeckCard({ {/* Thumbnail */}
- {deck.thumbnailUrl ? ( + {deck.thumbnailUrl && isHtmlPreview(deck.thumbnailUrl) ? ( + + ) : deck.thumbnailUrl ? ( {t("previewAlt", { + it("isolates the deck: exact sandbox and allow attributes, never allow-same-origin", () => { + renderWithIntl() + + const frame = screen.getByTitle("HTML deck: Launch") as HTMLIFrameElement + expect(frame.getAttribute("sandbox")).toBe("allow-scripts allow-popups") + expect(frame.getAttribute("allow")).toBe("fullscreen *") + expect(frame.getAttribute("referrerpolicy")).toBe("no-referrer") + expect(frame.getAttribute("src")).toBe(URL_1) + const tokens = frame.getAttribute("sandbox")!.split(/\s+/) + expect(tokens).not.toContain("allow-same-origin") + expect(tokens).not.toContain("allow-modals") + expect(tokens).not.toContain("allow-popups-to-escape-sandbox") + }) + + it("follows the deck aspect ratio", () => { + renderWithIntl() + const wrapper = screen.getByTitle("HTML deck").parentElement as HTMLElement + expect(wrapper.style.aspectRatio).toBe("1280/960") + }) + + it("keeps the loaded deck when only the signature changes, reloads on a new build", () => { + const { rerender } = renderWithIntl() + rerender() + expect(screen.getByTitle("HTML deck").getAttribute("src")).toBe(URL_1) + + const next = "https://bucket.s3.ap-northeast-1.amazonaws.com/html/d1/def.html?X-Amz-Signature=3" + rerender() + expect(screen.getByTitle("HTML deck").getAttribute("src")).toBe(next) + }) + + it("opens at the requested slide and keeps it across a re-signed URL", () => { + const { rerender } = renderWithIntl() + expect(screen.getByTitle("HTML deck").getAttribute("src")).toBe(`${URL_1}#/2`) + + rerender() + expect(screen.getByTitle("HTML deck").getAttribute("src")).toBe(`${URL_1}#/2`) + }) + + it("moves a loaded deck with reveal.js's postMessage API, an unloaded one through the URL", () => { + const { rerender } = renderWithIntl() + const frame = screen.getByTitle("HTML deck") as HTMLIFrameElement + + rerender() + expect(frame.getAttribute("src")).toBe(`${URL_1}#/3`) + + fireEvent.load(frame) + const post = vi.spyOn(frame.contentWindow!, "postMessage").mockImplementation(() => {}) + rerender() + expect(post).toHaveBeenCalledWith(JSON.stringify({ method: "slide", args: [3] }), "*") + expect(frame.getAttribute("src")).toBe(`${URL_1}#/3`) + + rerender() + expect(post).toHaveBeenLastCalledWith(JSON.stringify({ method: "slide", args: [0] }), "*") + }) +}) + +describe("deckUrlAtSlide", () => { + it("adds a reveal.js slide fragment without touching the signed query", () => { + expect(deckUrlAtSlide(URL_1, 4)).toBe(`${URL_1}#/4`) + expect(deckUrlAtSlide(`${URL_1}#/4`, 1)).toBe(`${URL_1}#/1`) + expect(deckUrlAtSlide(`${URL_1}#/4`, 0)).toBe(URL_1) + expect(deckUrlAtSlide(URL_1, undefined)).toBe(URL_1) + }) +}) diff --git a/web-ui/src/components/deck/HtmlDeckPlayer.tsx b/web-ui/src/components/deck/HtmlDeckPlayer.tsx new file mode 100644 index 000000000..a99ac0eb4 --- /dev/null +++ b/web-ui/src/components/deck/HtmlDeckPlayer.tsx @@ -0,0 +1,104 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: MIT-0 +/** + * HtmlDeckPlayer โ€” In-app view of an HTML deck (output.html, reveal.js). + * + * The deck runs its own scripts, so it is isolated in a sandboxed iframe: + * `allow-scripts allow-popups` only. Never add `allow-same-origin` (the deck + * would share the app's origin and storage), `allow-modals` or + * `allow-popups-to-escape-sandbox`. Cloud URLs are S3 presigned URLs on a + * different origin from the app; local URLs are served with a CSP `sandbox` + * header as well. + */ + +"use client" + +import { useEffect, useRef, useState } from "react" +import { useTranslations } from "next-intl" +import { previewIdentity } from "@/lib/preview" + +/** The iframe sandbox tokens of the in-app player (exported for tests). */ +export const HTML_PLAYER_SANDBOX = "allow-scripts allow-popups" + +/** A request to show a slide; a new `seq` repeats the jump to the same index. */ +export interface HtmlPlayerSlide { + /** 0-based slide index in the deck. */ + index: number + seq: number +} + +interface HtmlDeckPlayerProps { + htmlUrl: string + /** Canvas size in CSS px; sets the player's aspect ratio. */ + slideSize?: { width: number; height: number } + deckName?: string + /** Slide to show (thumbnail click, search jump). */ + slide?: HtmlPlayerSlide | null +} + +function withoutFragment(url: string): string { + return url.split("#")[0] +} + +/** + * The deck URL opened at a slide. reveal.js runs with `hash: true`, so `#/` + * selects the slide; a fragment does not change an S3 presigned URL's signature. + */ +export function deckUrlAtSlide(url: string, index: number | undefined): string { + return index ? `${withoutFragment(url)}#/${index}` : withoutFragment(url) +} + +export function HtmlDeckPlayer({ htmlUrl, slideSize, deckName, slide }: HtmlDeckPlayerProps) { + const t = useTranslations("carousel") + const width = slideSize?.width ?? 1920 + const height = slideSize?.height ?? 1080 + const frameRef = useRef(null) + const loadedRef = useRef(false) + + // A re-signed URL for the same build must not reload the deck (and lose the + // current slide); a new build does reload it. + const [src, setSrc] = useState(() => deckUrlAtSlide(htmlUrl, slide?.index)) + useEffect(() => { + setSrc((current) => { + if (previewIdentity(withoutFragment(current)) === previewIdentity(htmlUrl)) return current + loadedRef.current = false + return htmlUrl + }) + }, [htmlUrl]) + + // The initial src already opens the requested slide; later requests go to the + // loaded deck through reveal.js's postMessage API. The sandboxed deck has an + // opaque origin, so the target origin cannot be narrower than "*"; the message + // carries only a slide index. + const initialSeq = useRef(slide?.seq) + const index = slide?.index + const seq = slide?.seq + useEffect(() => { + if (index === undefined || seq === initialSeq.current) return + initialSeq.current = seq + const target = frameRef.current?.contentWindow + if (loadedRef.current && target) { + target.postMessage(JSON.stringify({ method: "slide", args: [index] }), "*") // nosemgrep: wildcard-postmessage-configuration โ€” opaque-origin sandboxed iframe, payload is a slide index + } else { + setSrc((current) => deckUrlAtSlide(current, index)) + } + }, [index, seq]) + + return ( +
+