diff --git a/.ash.yaml b/.ash.yaml index b49a05fc7..a22cad719 100644 --- a/.ash.yaml +++ b/.ash.yaml @@ -23,6 +23,14 @@ global_settings: catalog (search_assets names). Vector geometry, not credentials. expiration: "2027-09-27" + - rule_id: "SECRET-BASE64-HIGH-ENTROPY-STRING" + path: "tests/test_html_csp.py" + reason: > + SPEAKER_VIEW_HASH_6_0_2 pins the public CSP sha256 hash of the reveal.js 6.0.2 + speaker-view script, so a vendor update that changes the script fails the test. + A digest of public code, not a credential. + expiration: "2027-10-31" + # --- CFn Custom Resource: urlopen to pre-signed ResponseURL --- # Standard pattern for CloudFormation custom resources. # The URL is the CFn-provided ResponseURL, not user-controlled. diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..1d89d7f74 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Vendored files are checked against upstream SHA256SUMS; keep their bytes unchanged on checkout. +sdpm/vendor/** -text diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5f67f0822..24081e1f6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,6 +20,8 @@ jobs: - uses: astral-sh/setup-uv@v10.3.2 - name: Lint run: uv run ruff check sdpm/ servers/ shared/ api/ agent/ + - name: Vendored files match the manifest + run: cd sdpm/vendor && sha256sum -c SHA256SUMS - name: Test run: uv run pytest tests/ -v --cov=sdpm --cov-report=term @@ -38,6 +40,26 @@ jobs: - name: Smoke test local MCP server run: uv run python scripts/smoke_local.py + # The HTML browser check against a real Chrome: network block, popups, WebRTC + # removal, layout measurement and the speaker view under the deck CSP. The + # fixture fails (not skips) when no browser is found. + browser: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 + with: + python-version: "3.12" + - uses: astral-sh/setup-uv@v10.3.2 + - name: Allow Chrome's sandbox (Ubuntu 24.04 restricts unprivileged user namespaces) + run: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + - name: Real-browser tests + env: + SDPM_TEST_BROWSER: "1" + SDPM_BROWSER: google-chrome + run: google-chrome --version && command -v lsof && uv run pytest tests/test_html_browser_check.py -k real_browser -v -rs + web-ui: runs-on: ubuntu-latest steps: diff --git a/.gitignore b/.gitignore index 45c01366f..ccce24c17 100644 --- a/.gitignore +++ b/.gitignore @@ -95,3 +95,9 @@ output/ desktop/src-tauri/gen/schemas/acl-manifests.json desktop/src-tauri/gen/schemas/desktop-schema.json desktop/src-tauri/gen/schemas/macOS-schema.json + +# git worktrees created by agent workflows +.worktrees/ +# agent workflow scratch (plans, reviews, verification evidence); plugins/ stays tracked +.agents/* +!.agents/plugins/ diff --git a/.kiro/steering/principles.md b/.kiro/steering/principles.md index 3f5aa8b1b..5e6690be0 100644 --- a/.kiro/steering/principles.md +++ b/.kiro/steering/principles.md @@ -21,9 +21,10 @@ The SPEC agent handles user dialogue (Phase 1). Composer agents handle slide gen (Phase 2+3) via the `compose_slides` tool (Agents as Tools pattern). Role and procedure text lives in `sdpm/references/workflows/.md` (orchestrator, -composer, style, translate) and reaches MCP clients through the role's entry tool -(`start_presentation` / `start_composing` / `start_style` / `start_translation`), which also -returns what that role reads first (`sdpm.entry`). +composer, style, translate; the composer's html mode in `composer-html.md`) and reaches MCP +clients through the role's entry tool (`start_presentation` / `start_composing` / +`start_style` / `start_translation`), which also returns what that role reads first +(`sdpm.entry`). Client-side files are thin wiring (composer sub-agent registration) that name a role document without restating it. The L4 agent fetches role documents through the same port (`Source.mcp("start_*", pick="static.workflow")` in `agent/modes/`); only transport-specific @@ -55,20 +56,30 @@ Rules that follow from this: hexagonal purity for one less abstraction — acceptable while there is a single cloud backend. Revisit only if a second backend appears. 4. **Role documents are content, not client config** ("server-driven behavior"). - Each role (orchestrator, composer, style, translate) has exactly one document, - `sdpm/references/workflows/.md`, served through the port via - the role's `start_*` entry tool. Entry points (the `sdpm-*` prompts, ACP agent + Each role (orchestrator, composer, style, translate) has exactly one document per + mode, `sdpm/references/workflows/.md`, served through the port via + the role's `start_*` entry tool. The composer has two modes, pptx (`composer.md`) and + html (`composer-html.md`); the spawner chooses the mode through the entry tool argument + (`start_composing(..., mode=…)`) at dispatch time — never inferred from deck contents — + and the entry tool's `static` part depends only on the mode. Entry points (the `sdpm-*` prompts, ACP agent definitions, `SKILL.md`, server instructions) only ever name a role document — they never restate or duplicate its content. Nothing else lives on the client side: a client holds the one line that starts the server, written by `sdpm register`. Role assignment is a dispatch-time decision, not a discovery-time one: a spawner (the orchestrator delegating to a composer, a prompt dispatching a - role, a client picking a mode) tells the spawned agent which role to load in - its first instruction. The agent then calls `start_(...)` - itself. There is no docstring heuristic to infer role from arguments, and no + role, a client picking a mode) tells the spawned agent which role — and, for the + composer, which mode — to load in its first instruction. The agent then calls + `start_(...)` itself, passing the mode as an argument. There is no docstring heuristic to infer role from arguments, and no case where a role's text is embedded into a system prompt instead of fetched — every consumer, including the L4 agent, fetches live. + + Writing role documents and guides: state what the agent can do (its tools and their + range) and what it should do, in positive form rather than "X is not Y" / "do not X"; + give no concrete examples or form-to-interaction tables (models copy them); leave out + what a check already stops (static checks, CSP, browser check) — the warning itself + says how to fix it. Format-specific notes for the orchestrator come from + `init_deck_workspace` (`format_notes`), keeping `orchestrator.md` format-neutral. 5. **Change-locality goal** — the structure is optimised so that: prompt changes touch only `sdpm/references/workflows/`; engine changes touch only `sdpm/sdpm/engine/`; a new MCP client touches only the client table in diff --git a/AGENTS.md b/AGENTS.md index 2bd0d9f34..d4cc69385 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -64,8 +64,9 @@ docs/ Documentation are peers. `sdpm.tools` defines every MCP tool once — names, schemas, docstrings, logic — and both servers register those functions directly. Role and procedure text is content, not client config: `sdpm/references/workflows/.md` -(orchestrator, composer, style, translate) is the single definition for each role, -delivered to any MCP client by the `start_*` entry tools (`start_presentation`, +(orchestrator, composer, style, translate) is the single definition for each role — one +document per mode for the composer (`composer.md` for pptx, `composer-html.md` for html), +the mode chosen by the spawner through `start_composing(..., mode=…)` — delivered to any MCP client by the `start_*` entry tools (`start_presentation`, `start_composing`, `start_style`, `start_translation`), each of which also returns what that role reads first. Nothing lives on the client side: `sdpm register` (`servers/local/client_config.py`) writes the one line that starts the server into each @@ -75,8 +76,10 @@ See [Architecture](docs/en/architecture.md). ## Conventions - Engine source of truth: `sdpm/sdpm/` — servers must stay thin binds of `sdpm.tools` -- Role + procedure text lives only in `sdpm/references/workflows/.md`; `SKILL.md`, - the ACP agent definitions and server instructions are dispatch/environment only +- Role + procedure text lives only in `sdpm/references/workflows/.md`, one document + per mode (composer: `composer.md` / `composer-html.md`, chosen by the spawner via + `start_composing`'s `mode` argument); `SKILL.md`, the ACP agent definitions and server + instructions are dispatch/environment only - Client configuration is generated, never hand-written: one template in `servers/local/client_config.py` (absolute `uv` + absolute checkout, no launcher, no `PATH`), rendered per client; `tests/test_client_config.py` guards it. Both launchers diff --git a/CHANGELOG.md b/CHANGELOG.md index c0b33a4f0..5cd65f8be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,12 +12,59 @@ Entries before v0.5.0 were written retroactively as summaries. ### Added +- **HTML output mode.** A deck can be a browser presentation instead of a PPTX, locally and + on the AWS stack. Ask for an HTML / browser deck, write `@format:html`, or use the + **Build as HTML** pill (「HTML で作成」) on the first chat screen (also in the `/` picker's + **Format** section; PPTX stays the default). The deck gets `deck.json` + `outputFormat: "html"` (`init_deck_workspace(name, output_format="html")`, which also + returns `format_notes`, the `html-deck` guide), and composers are dispatched with + `start_composing(deck_id, assigned_slugs, mode="html")`, which returns the HTML composer + document, the template's converted layouts and the deck's shared `deck.css`. HTML decks + choose a template and style as PPTX decks do (`apply_style(deck_id, style, template)`); + template decorations are converted to SVG when LibreOffice and poppler are installed. + Each slide is an HTML fragment under `slides/`; `run_python` assembles them into one + offline `output.html` on reveal.js 6 with speaker notes (`S` opens the speaker view), and + every image is embedded. Slides may run inline scripts, with Apache ECharts 6.1.0 and D3 + 7.9.0 embedded only in decks that declare them (`
`); all + three libraries are vendored under `sdpm/vendor/` with their licenses and a checksum + manifest checked in CI. `output.html` carries a Content-Security-Policy that allows only + the engine's scripts and each slide's inline scripts by sha256 hash, plus `data:` images, + fonts and media (`connect-src 'none'`, no-referrer), and every external link opens in a new + tab. Static checks cover structure, layouts and placeholders, fonts, `deck.css`, embedded + sizes, CSP-blocked constructs and scripts that reach outside the deck (`script-external`: + navigation, new tabs, external URLs, WebRTC). After each build that changes slides, the + browser check opens those slides in a browser (locally headless Chrome or Edge, in the + cloud AWS AgentCore Browser) with network requests blocked and WebRTC disabled before slide + code runs, reports layout findings (`overlap`, `overflow`, `outside-region`, + `decoration-overlap`) and JS errors as warnings (`browser_check` in the result; + `SDPM_BROWSER=none` turns it off), and leaves a PNG per slide (`preview_files` locally, + `get_preview` in the cloud). A skipped, stopped or unfinished check is reported as such, + never as clean. In the Web UI an HTML deck plays in a sandboxed in-app player with + **Present** (new tab, link valid for 4 hours), **PDF** (print view, template backgrounds + included) and **HTML** (download `output.html`); slides whose scripts reach outside the + deck are listed in a warning next to Present / Download, on shared decks too. Thumbnails + are static per-slide HTML in `sandbox=""` iframes; the local Web UI has one **Open** + button. Sharing and public decks work as for PPTX; HTML files live under `html/` in the + deck bucket and are served only through presigned URLs. The CLI gains `generate_html + `. Translation, PPTX import, hand-edit sync, `code_to_slide` and the local + `generate_pptx` refuse HTML decks with a message, and an invalid `deck.json` + `outputFormat` stops every build. New dependency: `websockets`. The local Web UI dev + servers (`npm run dev`, `npm run dev:local`) now listen on 127.0.0.1 only. PPTX behaviour + is unchanged and the MCP tool count stays at 20. Deploy: SdpmData, SdpmRuntime, + SdpmAgent, SdpmWebUi and the Web UI. - **Claude Haiku 5.5** is a selectable model (`global.anthropic.claude-haiku-5-5`) for both Chat and Create. It uses the extended-thinking profile (no `temperature`; Bedrock rejects 0.1 with "temperature is deprecated"), with prompt caching enabled, and is listed in the example config's Recommended group. Unlike Haiku 4.5 it is not excluded from the Create picker. +### Changed + +- **AgentCore runtime role.** The MCP runtime role gains + `bedrock-agentcore:StartBrowserSession`, `StopBrowserSession` and + `ConnectBrowserAutomationStream` on `arn:aws:bedrock-agentcore::aws:browser/aws.browser.v1` + only. + ### Removed - **Python 3.10 is no longer supported (breaking).** `requires-python` is now `>=3.11` diff --git a/THIRD-PARTY-LICENSES b/THIRD-PARTY-LICENSES index dc0ea5f59..09d4e58e2 100644 --- a/THIRD-PARTY-LICENSES +++ b/THIRD-PARTY-LICENSES @@ -1,5 +1,39 @@ -This project does not include any third-party code or assets that require attribution -beyond the dependencies listed in pyproject.toml / package.json. +This project includes the following third-party code, copied verbatim: + +reveal.js 6.0.2 + https://github.com/hakimel/reveal.js + License: MIT + Copyright (C) 2011-2026 Hakim El Hattab, http://hakim.se, and reveal.js contributors + Location: sdpm/vendor/revealjs/ (full license text in sdpm/vendor/revealjs/LICENSE) + +marked 17.x (bundled by reveal.js into sdpm/vendor/revealjs/plugin/notes.js) + https://github.com/markedjs/marked + License: MIT + Copyright (c) 2018+, MarkedJS (https://github.com/markedjs/) + Copyright (c) 2011-2018, Christopher Jeffrey (https://github.com/chjj/) + +Apache ECharts 6.1.0 + https://github.com/apache/echarts + License: Apache-2.0 + NOTICE: + Apache ECharts + Copyright 2017-2026 The Apache Software Foundation + This product includes software developed at + The Apache Software Foundation (https://www.apache.org/). + Includes parts of d3, License: BSD-3-Clause (sdpm/vendor/echarts/licenses/LICENSE-d3) + Location: sdpm/vendor/echarts/ (full license text in sdpm/vendor/echarts/LICENSE) + +D3 7.9.0 + https://github.com/d3/d3 + License: ISC + Copyright 2010-2023 Mike Bostock + Location: sdpm/vendor/d3/ (full license text in sdpm/vendor/d3/LICENSE) + +Generated HTML decks (output.html) always embed reveal.js and marked, and embed +ECharts / D3 only when a slide declares them, each preceded by its license notice. + +Beyond that, the project relies only on the dependencies listed in +pyproject.toml / package.json. All third-party dependencies are installed at build time and are subject to their respective licenses. diff --git a/agent/modes/__init__.py b/agent/modes/__init__.py index 7830f1b82..0a43d085b 100644 --- a/agent/modes/__init__.py +++ b/agent/modes/__init__.py @@ -112,6 +112,23 @@ def _orchestrator(*wiring: Part, use_composer: bool = True, **overrides) -> Mode allowed_tools=_DECK_TOOLS, ) +# HTML composer: the html mode of the same entry tool (composer-html workflow + +# slide HTML spec). compose_slides picks it for decks with outputFormat html. +_HTML_COMPOSER = ModeConfig( + parts=[ + Part( + Source.mcp("start_composing", {"mode": "html"}, pick="static.workflow"), + target="system", label="workflow:composer-html", + ), + Part( + Source.mcp("start_composing", {"mode": "html"}, pick="static.slide_spec"), + target="system", label="slide-html-spec", + ), + ], + use_composer=False, + allowed_tools=_DECK_TOOLS, +) + _STYLE_CREATOR = ModeConfig( parts=[ _COMMON_LANGUAGE, @@ -131,5 +148,6 @@ def _orchestrator(*wiring: Part, use_composer: bool = True, **overrides) -> Mode "vibe": _ORCHESTRATOR_FAST, "spec": _ORCHESTRATOR_DIALOGUE, "composer": _COMPOSER, + "html_composer": _HTML_COMPOSER, "style_creator": _STYLE_CREATOR, } diff --git a/agent/modes/composer.py b/agent/modes/composer.py index fed1d5786..2bddea095 100644 --- a/agent/modes/composer.py +++ b/agent/modes/composer.py @@ -73,7 +73,15 @@ def _is_compose_stopped(parent_tool_use_id: str) -> bool: return False -def _start_composing(mcp_client, deck_id: str, assigned_slugs: list[str]) -> dict: +def _start_composing_args(deck_id: str, assigned_slugs: list[str], mode: str | None) -> dict: + """start_composing arguments; ``mode`` is sent only for HTML decks (PPTX calls stay as before).""" + arguments: dict = {"deck_id": deck_id, "assigned_slugs": assigned_slugs} + if mode == "html": + arguments["mode"] = "html" + return arguments + + +def _start_composing(mcp_client, deck_id: str, assigned_slugs: list[str], mode: str | None = None) -> dict: """Call the composer's entry tool and return its ``deck`` part. The same call an interactive composer makes first; here it is made on the @@ -84,7 +92,7 @@ def _start_composing(mcp_client, deck_id: str, assigned_slugs: list[str]) -> dic mcp_client, tool_use_id=f"prefetch-{uuid.uuid4().hex[:8]}", name="start_composing", - arguments={"deck_id": deck_id, "assigned_slugs": assigned_slugs}, + arguments=_start_composing_args(deck_id, assigned_slugs, mode), ) if result.get("status") == "error": raise RuntimeError(f"start_composing failed for deck {deck_id}: {result.get('content')}") @@ -99,7 +107,9 @@ def _start_composing(mcp_client, deck_id: str, assigned_slugs: list[str]) -> dic raise RuntimeError(f"start_composing returned no payload for deck {deck_id}") -def _replay_start_composing(deck_id: str, assigned_slugs: list[str], deck: dict) -> list[dict]: +def _replay_start_composing( + deck_id: str, assigned_slugs: list[str], deck: dict, mode: str | None = None, +) -> list[dict]: """assistant toolUse + user toolResult pair for a start_composing call already made.""" tool_use_id = f"prefill-{uuid.uuid4().hex[:8]}" return [ @@ -110,7 +120,7 @@ def _replay_start_composing(deck_id: str, assigned_slugs: list[str], deck: dict) {"toolUse": { "toolUseId": tool_use_id, "name": "start_composing", - "input": {"deck_id": deck_id, "assigned_slugs": assigned_slugs}, + "input": _start_composing_args(deck_id, assigned_slugs, mode), }}, ], }, @@ -150,7 +160,8 @@ def make_compose_slides(mcp_servers: list, model, composer_mcp_factory=None, ext context=True, description=( "Dispatch composer agents for the groups given — one independent composer " - "per group, writing slides/.json. Runs only what you pass: the layout " + "per group, writing each slide's file (slides/.json, or .html in an " + "HTML deck). Runs only what you pass: the layout " "pass and the content pass are separate calls. " f"Up to {max_concurrency} groups run concurrently. " "Use this once outline.md is finalized.\n\n" @@ -223,6 +234,7 @@ async def compose_slides(deck_id: str, slide_groups: list, tool_context: ToolCon # Validate the deck specification once before launching composers. spec_warnings: list[str] = [] outline_slugs: list[str] = [] + html_deck = False if mcp_client: assigned_slugs = [slug for group in slide_groups for slug in group["slugs"]] check_result = call_tool_with_retry( @@ -249,6 +261,7 @@ async def compose_slides(deck_id: str, slide_groups: list, tool_context: ToolCon spec_warnings = list(spec_result.get("warnings") or []) outline_slugs = list(spec_result.get("slugs") or []) + html_deck = (spec_result.get("outputFormat") or "pptx") == "html" if not spec_result.get("ok"): yield json.dumps({ "status": "error", @@ -270,7 +283,8 @@ async def compose_slides(deck_id: str, slide_groups: list, tool_context: ToolCon try: # Prefetch static composer parts (role prompt + refs) via composition yield {"status": "prefetching", "message": "Loading references..."} - composer_cfg = MODES["composer"] + composer_cfg = MODES["html_composer" if html_deck else "composer"] + compose_mode = "html" if html_deck else None composer_system, composer_history = resolve_parts( composer_cfg.parts, mcp_client=mcp_client, context={} ) @@ -294,17 +308,18 @@ def run_group(gi: int, group: dict) -> dict: # The composer's history opens like an interactive composer's session: # the spawn instruction, then its own start_composing call with the # deck payload as the result. The run continues from there. - deck_part = _start_composing(mcp_client, deck_id, group["slugs"]) if mcp_client else {} + deck_part = _start_composing(mcp_client, deck_id, group["slugs"], compose_mode) if mcp_client else {} opening: list[dict] = [{ "role": "user", "content": [{"text": ( f"deck_id: {deck_id}\n" f"assigned_slugs: {', '.join(group['slugs'])}\n" - f"task_instruction: {group['instruction']}" + + ("mode: html\n" if compose_mode == "html" else "") + + f"task_instruction: {group['instruction']}" )}], }] if deck_part: - opening.extend(_replay_start_composing(deck_id, group["slugs"], deck_part)) + opening.extend(_replay_start_composing(deck_id, group["slugs"], deck_part, compose_mode)) # Time budget: slug_count * seconds-per-slide. Periodic nudge (1st then every 3rd) to stop polishing. deadline = time.time() + len(group["slugs"]) * _SECONDS_PER_SLIDE @@ -537,7 +552,7 @@ async def _after_tool(event: AfterToolCallEvent): }) # Post-compose: build PPTX + assemble report - yield {"status": "building", "message": "Building final PPTX..."} + yield {"status": "building", "message": "Building the HTML deck..." if html_deck else "Building final PPTX..."} cancelled = _is_compose_stopped(parent_tool_use_id) partial = bool(errors) and bool(generated) report = { @@ -569,7 +584,7 @@ async def _after_tool(event: AfterToolCallEvent): ) if generated and mcp_client: - # Generate PPTX + # Finalize the deck (generate_pptx: PPTX, or output.html for an HTML deck) try: build_result = call_tool_with_retry( mcp_client, diff --git a/agent/prompts/wiring/compose_report.md b/agent/prompts/wiring/compose_report.md index 266ef1dd5..727b04cd7 100644 --- a/agent/prompts/wiring/compose_report.md +++ b/agent/prompts/wiring/compose_report.md @@ -32,3 +32,10 @@ You cannot see the composers' own tool results (their `preview_files` stay inside each composer). After the content call returns, call `get_preview(deck_id, slugs=[...all slugs...])` yourself to see the rendering — this is how you look before deciding whether any slide needs another composer. + +For an HTML deck (`check_specs` returns `outputFormat: "html"`), `get_preview` returns the +PNGs the composers' browser checks made of the slides they wrote or changed; a slug with no +PNG yet comes back as a text line (its check was skipped or did not finish — see the +`output.html: Browser check …` warnings in the composers' `summaries`). Review through those +images, the `summaries` and the warnings in `build`, and never tell the user to open a local +`output.html` path. diff --git a/api/html_presign.py b/api/html_presign.py new file mode 100644 index 000000000..444a5f46c --- /dev/null +++ b/api/html_presign.py @@ -0,0 +1,128 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +"""Presigned S3 URLs for HTML deck artifacts (pure helpers for the API Lambda). + +# Security: HTML decks run scripts, so they are served only from the S3 +# regional endpoint (``.s3..amazonaws.com``), a different +# origin from the Web UI. The Web UI CloudFront distribution serves +# ``previews/*``, ``decks/*/*`` and ``pptx/*`` on the app origin; signing an +# ``.html`` key through it would run deck scripts with the app's origin. +# ``html/`` is therefore in no CloudFront behaviour and not in the OAC grant, +# and only ``html/**.html`` keys may be presigned here (forcing a text/html +# response type on any other object, e.g. a user upload, would turn it into +# a page on the bucket origin). + +Imported as ``html_presign`` inside the Lambda bundle and as +``api.html_presign`` in tests. +""" + +import unicodedata +from typing import Any, Dict, Iterable, List, Tuple +from urllib.parse import quote + +import boto3 +from botocore.config import Config as BotoConfig + +from shared.html_artifacts import HTML_CONTENT_TYPE, HTML_PREFIX + +# Purposes callers may request from GET /decks/{id}/html → URL lifetime (s). +PURPOSES: Dict[str, int] = {"present": 14400, "download": 900} +# In-app viewing (get_deck htmlUrl / previewUrl, deck-list thumbnails, search). +VIEW_EXPIRY = 900 +DEFAULT_SLIDE_SIZE: Dict[str, int] = {"width": 1920, "height": 1080} + +_EXPIRY: Dict[str, int] = {"view": VIEW_EXPIRY, **PURPOSES} +_MAX_NAME_CHARS = 120 +_STRIP_CHARS = frozenset('/\\"\'') + + +def html_presign_client(region: str) -> Any: + """S3 client that signs SigV4 URLs on the regional virtual-host endpoint.""" + return boto3.client( + "s3", + region_name=region, + endpoint_url=f"https://s3.{region}.amazonaws.com", + config=BotoConfig(signature_version="s3v4", s3={"addressing_style": "virtual"}), + ) + + +def safe_download_name(name: Any) -> str: + """File name for a downloaded deck: no control chars, path separators or quotes; ends in .html.""" + text = "".join( + ch for ch in str(name or "") + if ch not in _STRIP_CHARS and not unicodedata.category(ch).startswith("C") + ) + text = " ".join(text.split()).strip(" .") + if text.lower().endswith(".html"): + text = text[:-5].rstrip(" .") + text = text[:_MAX_NAME_CHARS].rstrip(" .") + return f"{text or 'deck'}.html" + + +def _content_disposition(deck_name: str) -> str: + filename = safe_download_name(deck_name) + ascii_stem = filename[:-5].encode("ascii", "ignore").decode("ascii").strip(" .") + ascii_name = f"{ascii_stem or 'deck'}.html" + return f"attachment; filename=\"{ascii_name}\"; filename*=UTF-8''{quote(filename, safe='')}" + + +def presign_params(bucket: str, key: str, purpose: str, deck_name: str = "") -> Tuple[Dict[str, str], int]: + """get_object Params and expiry for an HTML artifact. + + ``purpose`` is ``view`` (in-app), ``present`` or ``download``. Raises + ValueError for an unknown purpose or a key outside ``html/**.html``. + """ + if purpose not in _EXPIRY: + raise ValueError(f"unknown purpose: {purpose!r}") + if not isinstance(key, str) or not key.startswith(HTML_PREFIX) or not key.endswith(".html") or ".." in key: + raise ValueError(f"not an HTML artifact key: {key!r}") + disposition = _content_disposition(deck_name) if purpose == "download" else "inline" + params = { + "Bucket": bucket, + "Key": key, + "ResponseContentType": HTML_CONTENT_TYPE, + "ResponseContentDisposition": disposition, + } + return params, _EXPIRY[purpose] + + +def presigned_html_url(client: Any, bucket: str, key: str, purpose: str, deck_name: str = "") -> Tuple[str, int]: + """(presigned GET URL, expires_in seconds) for an HTML artifact; see presign_params.""" + params, expires = presign_params(bucket, key, purpose, deck_name) + return client.generate_presigned_url("get_object", Params=params, ExpiresIn=expires), expires + + +def is_html_deck(deck_json: Any) -> bool: + """True when deck.json declares outputFormat "html" (absent or anything else → PPTX).""" + return isinstance(deck_json, dict) and deck_json.get("outputFormat") == "html" + + +def slide_size(deck_json: Any) -> Dict[str, Any]: + """{width, height} from deck.json slideSize, defaulting to 1920×1080.""" + size = deck_json.get("slideSize") if isinstance(deck_json, dict) else None + if not isinstance(size, dict): + return dict(DEFAULT_SLIDE_SIZE) + out: Dict[str, Any] = {} + for dim in ("width", "height"): + value = size.get(dim) + ok = isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0 + out[dim] = value if ok else DEFAULT_SLIDE_SIZE[dim] + return out + + +def html_slide_slugs(outline_slugs: List[str], slide_keys: Iterable[str], deck_id: str) -> List[str]: + """Slugs of an HTML deck in outline order, keeping those whose slides/{slug}.html exists. + + Without outline slugs, the listed ``.html`` stems are returned in key order. + """ + prefix = f"decks/{deck_id}/slides/" + stems: List[str] = [] + for key in slide_keys: + if key.startswith(prefix) and key.endswith(".html"): + stem = key[len(prefix):-5] + if stem and "/" not in stem: + stems.append(stem) + if not outline_slugs: + return stems + present = set(stems) + return [slug for slug in outline_slugs if slug in present] diff --git a/api/index.py b/api/index.py index 14e8764dd..a464c3dee 100644 --- a/api/index.py +++ b/api/index.py @@ -33,6 +33,15 @@ truncate_tool_inputs, ) from common import get_user_id, now_iso, presigned_url +from html_presign import ( + PURPOSES as HTML_PURPOSES, + html_presign_client, + html_slide_slugs, + is_html_deck, + presigned_html_url, + slide_size, +) +from shared.html_artifacts import build_html_preview_key_map, preview_prefix as html_preview_prefix from shared.schema import ( deck_pk, deck_sk, shared_pk, fav_sk, DECK_SK_PREFIX, FAV_SK_PREFIX, @@ -99,6 +108,13 @@ def preview_url(s3_key: str) -> Optional[str]: dynamodb = boto3.resource("dynamodb") table = dynamodb.Table(TABLE_NAME) s3_client = boto3.client("s3", config=BotoConfig(signature_version="s3v4")) +# HTML decks run scripts, so they are served only from the S3 regional +# endpoint (a different origin from the Web UI): the Web UI CloudFront +# distribution serves previews/*, decks/*/* and pptx/* on the app origin. +# HTML keys are signed with this client only — never preview_url() / +# _cf_signed_url(). +REGION = os.environ.get("AWS_REGION") or boto3.session.Session().region_name or "us-east-1" +html_s3_client = html_presign_client(REGION) app = APIGatewayHttpResolver(cors=cors_config) # --- KB (optional) --- @@ -155,6 +171,23 @@ def _list_preview_keys(deck_id: str) -> set: return {obj["Key"] for obj in resp.get("Contents", [])} +def _html_presigned(key: str, purpose: str = "view", deck_name: str = "") -> Optional[str]: + """Presigned S3 URL for an HTML artifact (regional S3 origin, never CloudFront). + + Returns None when the key is not an ``html/**.html`` key. + """ + try: + return presigned_html_url(html_s3_client, BUCKET_NAME, key, purpose, deck_name)[0] + except ValueError: + return None + + +def _list_html_preview_map(deck_id: str) -> Dict[str, str]: + """slug → latest HTML preview key under html/{deck_id}/preview/ (one S3 call).""" + resp = s3_client.list_objects_v2(Bucket=BUCKET_NAME, Prefix=html_preview_prefix(deck_id)) + return build_html_preview_key_map(obj["Key"] for obj in resp.get("Contents", [])) + + def _resolve_preview_url(deck_id: str, slug: str, preview_keys: set) -> Optional[str]: """Resolve the best preview URL for a slide from cached keys. @@ -193,6 +226,9 @@ def _get_deck_extras(deck_items: List[Dict]) -> Dict[str, Dict]: for deck in deck_items: deck_id = extract_deck_id(deck["SK"]) key = deck.get("thumbnailS3Key") + if key and key.endswith(".html"): + extras[deck_id] = {"thumbnailUrl": _html_presigned(key)} + continue extras[deck_id] = {"thumbnailUrl": preview_url(key) if key else None} return extras @@ -882,6 +918,166 @@ def list_public() -> Dict[str, Any]: return {"decks": decks} +def _read_deck_json(deck_id: str) -> Dict[str, Any]: + """deck.json as a dict ({} when missing, unreadable or not an object).""" + try: + dj_resp = s3_client.get_object(Bucket=BUCKET_NAME, Key=f"decks/{deck_id}/deck.json") + data = json.loads(dj_resp["Body"].read()) + except Exception: + return {} + return data if isinstance(data, dict) else {} + + +def _read_outline_slugs(deck_id: str) -> List[str]: + """Slugs from specs/outline.md in order ([] when missing). + + Canonical implementation: sdpm.api.parse_outline_slugs (not importable in Lambda). + """ + slugs: List[str] = [] + try: + outline_resp = s3_client.get_object(Bucket=BUCKET_NAME, Key=f"decks/{deck_id}/specs/outline.md") + outline_text = outline_resp["Body"].read().decode("utf-8") + slug_re = re.compile(r"^-\s*\[([a-z0-9-]+)\]\s*") + for line in outline_text.splitlines(): + m = slug_re.match(line) + if m: + slugs.append(m.group(1)) + except Exception: + pass + return slugs + + +def _read_specs(deck_id: str) -> Dict[str, Any]: + """Read spec files from S3 (brief.md, outline.md, art-direction.html/.md).""" + specs: Dict[str, Any] = {} + + # brief and outline — always .md + for spec_name in ("brief", "outline"): + spec_key = f"decks/{deck_id}/specs/{spec_name}.md" + try: + spec_resp = s3_client.get_object(Bucket=BUCKET_NAME, Key=spec_key) + content = spec_resp["Body"].read().decode("utf-8") + specs[spec_name] = content if content.strip() else None + except Exception: + specs[spec_name] = None + + # art-direction — try .html first, fall back to .md + art_direction_content = None + for ext in (".html", ".md"): + art_key = f"decks/{deck_id}/specs/art-direction{ext}" + try: + art_resp = s3_client.get_object(Bucket=BUCKET_NAME, Key=art_key) + content = art_resp["Body"].read().decode("utf-8") + if content.strip(): + art_direction_content = content + break + except Exception: + pass + specs["artDirection"] = art_direction_content + return specs + + +_SCRIPT_WARNING_SLUG = re.compile(r"^[a-z0-9][a-z0-9_-]*$") +_SCRIPT_WARNING_KINDS = frozenset({"navigation", "popup", "external-url", "webrtc"}) +_SCRIPT_WARNINGS_MAX = 200 + + +def _script_warnings(raw: Any) -> List[Dict[str, Any]]: + """The record's htmlScriptExternal as ``[{slug, kinds}]``: at most 200 entries with a + slide slug and known kinds; anything else is dropped.""" + out: List[Dict[str, Any]] = [] + for entry in raw if isinstance(raw, list) else []: + if len(out) >= _SCRIPT_WARNINGS_MAX: + break + if not isinstance(entry, dict): + continue + slug, kinds = entry.get("slug"), entry.get("kinds") + if not isinstance(slug, str) or not _SCRIPT_WARNING_SLUG.match(slug): + continue + if not isinstance(kinds, list) or not all(isinstance(k, str) and k in _SCRIPT_WARNING_KINDS for k in kinds): + continue + out.append({"slug": slug, "kinds": list(kinds)}) + return out + + +def _get_html_deck(deck_id: str, decision: Any, deck_json: Dict[str, Any]) -> Dict[str, Any]: + """get_deck response for an HTML deck (outputFormat "html"). + + Slides are the outline slugs whose slides/{slug}.html exists; previews are + the static per-slide HTML thumbnails. Every HTML URL is an S3 presign. + scriptWarnings lists the slides whose script can reach outside the deck. + """ + deck = decision.deck + resp = s3_client.list_objects_v2(Bucket=BUCKET_NAME, Prefix=f"decks/{deck_id}/slides/") + slide_keys = [obj["Key"] for obj in resp.get("Contents", [])] + slugs = html_slide_slugs(_read_outline_slugs(deck_id), slide_keys, deck_id) + + preview_map = _list_html_preview_map(deck_id) + slides = [] + for slug in slugs: + key = preview_map.get(slug) + slides.append({"slug": slug, "previewUrl": _html_presigned(key) if key else None}) + + html_key = deck.get("htmlS3Key") + return { + "deckId": deck_id, + "name": deck.get("name", "Untitled"), + "slideCount": len(slides), + "slides": slides, + "specs": _read_specs(deck_id), + "template": deck_json.get("template") or None, + "defsUrl": None, + "pptxUrl": None, + "outputFormat": "html", + "htmlUrl": _html_presigned(html_key) if html_key else None, + "scriptWarnings": _script_warnings(deck.get("htmlScriptExternal")), + "slideSize": slide_size(deck_json), + "updatedAt": deck.get("updatedAt", ""), + "chatSessionId": deck.get("chatSessionId"), + "isOwner": decision.role == "owner", + "role": decision.role, + "visibility": deck.get("visibility", "private"), + } + + +@app.get("/decks//html") +def get_deck_html(deck_id: str) -> Any: + """Presigned S3 URL of the built HTML deck. + + Query params: + purpose: "present" (inline, 4 h) or "download" (attachment, 15 min). + + Same read permission as get_deck (owner, collaborator, viewer of a public + deck). The URL is on the S3 regional endpoint, never CloudFront. + + Returns: + Dict with url and expiresIn (seconds). + """ + user_id = get_user_id(app.current_event) + + decision = authorize(user_id, deck_id, "read", table) + if not decision.allowed: + return {"error": decision.reason}, 403 + + purpose = app.current_event.get_query_string_value("purpose") or "" + if purpose not in HTML_PURPOSES: + return {"error": "purpose must be 'present' or 'download'"}, 400 + + deck = decision.deck + html_key = deck.get("htmlS3Key") + if not html_key: + return {"error": "HTML not built yet"}, 404 + + try: + url, expires = presigned_html_url( + html_s3_client, BUCKET_NAME, html_key, purpose, deck.get("name", ""), + ) + except ValueError: + logger.warning(f"Deck {deck_id} has a non-HTML htmlS3Key") + return {"error": "HTML not built yet"}, 404 + return {"url": url, "expiresIn": expires} + + @app.get("/decks/") def get_deck(deck_id: str) -> Dict[str, Any]: @@ -893,6 +1089,10 @@ def get_deck(deck_id: str) -> Dict[str, Any]: return {"error": decision.reason}, 403 deck = decision.deck + deck_json = _read_deck_json(deck_id) + if is_html_deck(deck_json): + return _get_html_deck(deck_id, decision, deck_json) + pptx_key = deck.get("pptxS3Key") # Read slides from S3 (deck.json + slides/*.json format) @@ -924,18 +1124,7 @@ def _latest_compose_key(prefix: str, keys: set) -> Optional[str]: has_defs = defs_key is not None # outline.md for slug order, then slides/*.json - # Canonical implementation: sdpm.api.parse_outline_slugs (not importable in Lambda) - slugs = [] - try: - outline_resp = s3_client.get_object(Bucket=BUCKET_NAME, Key=f"decks/{deck_id}/specs/outline.md") - outline_text = outline_resp["Body"].read().decode("utf-8") - slug_re = _re.compile(r"^-\s*\[([a-z0-9-]+)\]\s*") - for line in outline_text.splitlines(): - m = slug_re.match(line) - if m: - slugs.append(m.group(1)) - except Exception: - pass + slugs = _read_outline_slugs(deck_id) # If no outline slugs, list slides/ directory if not slugs: @@ -979,40 +1168,10 @@ def _latest_compose_key(prefix: str, keys: set) -> Optional[str]: slide_entry["slideJson"] = json.dumps(slide_data) slides.append(slide_entry) - # Read spec files from S3 (brief.md, outline.md, art-direction.html/.md) - specs: Dict[str, Any] = {} - - # brief and outline — always .md - for spec_name in ("brief", "outline"): - spec_key = f"decks/{deck_id}/specs/{spec_name}.md" - try: - spec_resp = s3_client.get_object(Bucket=BUCKET_NAME, Key=spec_key) - content = spec_resp["Body"].read().decode("utf-8") - specs[spec_name] = content if content.strip() else None - except Exception: - specs[spec_name] = None - - # art-direction — try .html first, fall back to .md - art_direction_content = None - for ext in (".html", ".md"): - art_key = f"decks/{deck_id}/specs/art-direction{ext}" - try: - art_resp = s3_client.get_object(Bucket=BUCKET_NAME, Key=art_key) - content = art_resp["Body"].read().decode("utf-8") - if content.strip(): - art_direction_content = content - break - except Exception: - pass - specs["artDirection"] = art_direction_content + specs = _read_specs(deck_id) # Confirmed template name from deck.json (written by the agent at Art Direction) - template = None - try: - dj_resp = s3_client.get_object(Bucket=BUCKET_NAME, Key=f"decks/{deck_id}/deck.json") - template = json.loads(dj_resp["Body"].read()).get("template") or None - except Exception: - pass + template = deck_json.get("template") or None return { "deckId": deck_id, @@ -1236,6 +1395,7 @@ def search_slides_api() -> Dict[str, Any]: results: List[Dict] = [] seen: set = set() seen_decks: Dict[str, set] = {} + seen_html_decks: Dict[str, Dict[str, str]] = {} for r in response.get("retrievalResults", []): meta = r.get("metadata", {}) deck_id = meta.get("deckId", "") @@ -1252,6 +1412,15 @@ def search_slides_api() -> Dict[str, Any]: if deck_id not in seen_decks: seen_decks[deck_id] = _list_preview_keys(deck_id) slide_preview_url = _resolve_preview_url(deck_id, slide_id, seen_decks[deck_id]) + if not slide_preview_url: + # HTML decks keep static per-slide previews under html/{deck}/preview/ + if deck_id not in seen_html_decks: + try: + seen_html_decks[deck_id] = _list_html_preview_map(deck_id) + except Exception: + seen_html_decks[deck_id] = {} + html_key = seen_html_decks[deck_id].get(slide_id) + slide_preview_url = _html_presigned(html_key) if html_key else None slide_preview_url = slide_preview_url or "" results.append({ diff --git a/docs/en/architecture.md b/docs/en/architecture.md index d6db50b28..acb01ba80 100644 --- a/docs/en/architecture.md +++ b/docs/en/architecture.md @@ -27,6 +27,7 @@ Dependencies always flow top-down. The core presentation engine. No network, no AWS, no MCP — just Python. - **sdpm/sdpm/engine/** — json↔pptx conversion: builder, converter, layout engine, schema lint, preview, checks, diff, analyzer +- **sdpm/sdpm/engine/html/** — HTML output mode: converts a .pptx template to `theme.css` / `template.json` / decoration SVGs, assembles slide HTML files into a single offline `output.html` (vendored reveal.js under `sdpm/vendor/revealjs/`), and runs the static slide checks - **sdpm/sdpm/knowledge/** — knowledge retrieval: references (guides/workflows/examples) and asset search - **sdpm/sdpm/tools/** — the MCP tool contract: every tool's name, schema, docstring, and logic defined once; both servers register these functions directly - **sdpm/references/** — workflows (role documents: orchestrator/composer/style/translate), @@ -73,6 +74,20 @@ Additional tools over Layer 2: - `run_python` — Execute Python in Amazon Bedrock AgentCore Code Interpreter sandbox (edit deck workspace, analyze data) - `search_slides` — Semantic slide search via Amazon Bedrock Knowledge Base (optional) +HTML decks (`deck.json` `outputFormat: "html"`) use the same tools with these differences: + +| Tool | HTML deck behaviour | +|------|---------------------| +| `init_deck_workspace` | `output_format="html"` creates an HTML deck (default `pptx`) and returns `format_notes` (guide `html-deck`) for the orchestrator | +| `start_composing` | `mode="html"` returns the HTML composer document, the template converted for HTML and the deck's `deck.css` | +| `run_python` | After a change to an HTML build input, rebuilds `output.html` and the changed slides' thumbnails, runs the browser check on the changed slides (and `measure_slides`) and uploads thumbnails and PNGs under `html/` | +| `generate_pptx` | Finalizes the deck as HTML: full build, every thumbnail, deck record update, knowledge-base sync (`search_slides` indexes HTML slides); no browser check (every slide was checked when it was written) | +| `get_preview` | Returns the PNGs the browser check made (`html/{deckId}/png/{slug}_{epoch}.png`); a slug without one gets a text line | + +The remote build reads and updates the deck record under the caller's user id, as the PPTX +build does. Only the deck owner's `run_python` / `generate_pptx` therefore rebuild an HTML +deck on S3; a collaborator's run reports `html_error` (`generate_pptx` returns an error) +and the published HTML stays as the owner last built it. ### Storage ``` @@ -87,6 +102,10 @@ S3 (pptx bucket): decks/{deckId}/includes/ — code block JSON decks/{deckId}/compose/ — per-slide SVG compose JSON (for Web UI animation) previews/{deckId}/{slideId}.png — slide previews + html/{deckId}/{uuid}.html — HTML deck output.html (DynamoDB htmlS3Key) + html/{deckId}/preview/{slug}_{epoch}.html — HTML slide thumbnails (latest epoch wins) + template-html-cache/{cacheKey}/ — template HTML conversion (theme.css, template.json, + layouts/*.svg); expires after 30 days S3 (resource bucket): references/ — examples, workflows, guides @@ -100,8 +119,10 @@ Using `run_python(deck_id=...)` loads the entire deck workspace into the sandbox The agent can read and write files using standard Python file I/O (`open`, `json.load`, etc.); modified files are written back to S3 automatically after every execution. ``` -deck.json — deck metadata (template, fonts, defaultTextColor) +deck.json — deck metadata (template, fonts, defaultTextColor, outputFormat) slides/{slug}.json — per-slide data (one file per slide, slug from outline) +slides/{slug}.html — per-slide HTML fragment (HTML decks) +deck.css — shared slide CSS (HTML decks) specs/brief.md — briefing (audience, purpose, key messages) specs/outline.md — one line per slide: - [slug] message specs/art-direction.html — visual design direction (HTML style guide) @@ -141,6 +162,86 @@ that reference a changed `includes/` file, slides that inherit from an affected `override`, and every slide when `deck.json` or `specs/outline.md` changed (`sdpm.engine.schema.affected_slugs`) — plus the `measure_slides` slugs. +### HTML Deck Security + +An HTML deck runs scripts, so it is never served from the Web UI's origin: + +- `output.html` carries a Content-Security-Policy `` that allows only the engine's own + scripts (reveal.js, the notes plugin, the config and the speaker view), the bundled + libraries a deck declares (ECharts, D3) and each slide's inline scripts, all by sha256 + hash computed at assembly, plus `data:` images, fonts and media; `connect-src` and + `form-action` are `'none'`. A script added to `output.html` afterwards, a `
+""" % {"stun": STUN} + +NET_SLIDE = """

Network

+
+""" + +DNS_SLIDE = """

DNS

+ + +
+""" + + +def _build(deck: Path, dns_host: str | None) -> list[str]: + api.init("egress-canary", output_dir=deck, output_format="html") + styled = api.apply_style(deck, style="typographic", template="blank-dark") + if styled.get("status") != "ok": + raise SystemExit(f"apply_style failed: {styled}") + slides = {"rtc": RTC_SLIDE, "net": NET_SLIDE} + if dns_host: + slides["dns"] = DNS_SLIDE % {"host": dns_host} + outline = "# Egress canary\n\n" + "".join(f"- [{slug}] {slug}\n" for slug in slides) + (deck / "specs" / "outline.md").write_text(outline, encoding="utf-8") + for slug, text in slides.items(): + (deck / "slides" / f"{slug}.html").write_text(text, encoding="utf-8") + return list(slides) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--region", default=os.environ.get("AWS_DEFAULT_REGION", "ap-northeast-1")) + parser.add_argument("--dns-domain", help="a domain whose DNS query log you can read") + args = parser.parse_args() + + os.environ.pop("SDPM_BROWSER", None) # SDPM_BROWSER=none would turn the check off + register_browser_source(make_source(args.region)) + nonce = secrets.token_hex(8) + dns_host = f"{nonce}.{args.dns_domain.strip('.')}" if args.dns_domain else None + + with tempfile.TemporaryDirectory(prefix="sdpm-egress-") as tmp: + deck = Path(tmp) / "deck" + slugs = _build(deck, dns_host) + result = api.refresh_html(deck, measure_slides=slugs) + + check = result.get("browser_check") or {} + print("browser_check:", json.dumps({k: check.get(k) for k in + ("status", "browser", "slides", "network_blocked", "blocked_requests", + "seconds", "note")}, ensure_ascii=False)) + js_errors = [w for w in result.get("warnings", []) if ": JS error" in w] + print(f"js errors ({len(js_errors)}):") + for line in js_errors: + print(" " + line[:300]) + if dns_host: + print(f"DNS egress: look up {dns_host} in the query log of {args.dns_domain} " + "(a query means the hints left the browser)") + else: + print("DNS egress: not verified (pass --dns-domain to test dns-prefetch / preconnect)") + + rtc = [w for w in js_errors if w.startswith("rtc: ")] + leaked = [w for w in rtc if "sdpm slide rtc: available" in w or "sdpm slide rtc: srflx" in w] + probed = any("sdpm slide rtc: probed" in w for w in rtc) + ok = check.get("network_blocked") is True and probed and not leaked + if not probed: + print("FAIL: the rtc slide did not report (it did not run or its srcdoc frame did not load)") + if leaked: + print("FAIL: WebRTC reachable:", *leaked, sep="\n ") + if check.get("network_blocked") is not True: + print("FAIL: network_blocked is not true") + print("PASS" if ok else "FAIL") + return 0 if ok else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/sdpm/SKILL.md b/sdpm/SKILL.md index 1655306c1..8dcb2da58 100644 --- a/sdpm/SKILL.md +++ b/sdpm/SKILL.md @@ -29,6 +29,7 @@ CLI-only operations without a contract name: |---|---| | Preview slides as PNG | `scripts/pptx_builder.py preview` | | Measure text bounding boxes | `scripts/pptx_builder.py measure` | +| Build output.html for an HTML deck | `scripts/pptx_builder.py generate_html ` | | Import an existing PPTX to JSON | `scripts/pptx_to_json.py` | | Start a deck translation | `scripts/translate_extract.py --target-lang ` | | Apply filled translations | `scripts/translate_apply.py -` | @@ -39,6 +40,11 @@ There is no MCP session here — deck files (`deck.json`, `specs/`, `slides/`) a and written directly with normal file I/O. Everything the workflows describe as a tool call (`read_text`, `write_file`, etc.) is just that: open the path, read or write it. +HTML decks (deck.json `outputFormat` `html`; composer: `start composing --mode html`) have +no `run_python` post-processing here — run `generate_html ` after writing slides. It +also checks every slide in a local Chrome / Edge (layout, JS errors) when one is installed; +`measure ` reports those checks and `preview ` writes PNGs to `preview/png/`. + ## Start here To create slides, run `start presentation --workflow-only` and follow it (`start composing diff --git a/sdpm/pyproject.toml b/sdpm/pyproject.toml index 154d3beb5..69a53ac84 100644 --- a/sdpm/pyproject.toml +++ b/sdpm/pyproject.toml @@ -10,6 +10,7 @@ dependencies = [ "qrcode", "pygments>=2.19.2", "defusedxml", + "websockets>=13", ] [tool.setuptools.packages.find] diff --git a/sdpm/references/guides/html-deck.md b/sdpm/references/guides/html-deck.md new file mode 100644 index 000000000..eafaa6a7f --- /dev/null +++ b/sdpm/references/guides/html-deck.md @@ -0,0 +1,29 @@ +--- +name: html-deck +description: "HTML decks for the orchestrator — what a slide can do, how the brief and outline describe it, reviewing and deck.css (init_deck_workspace returns it as format_notes)" +category: guide +--- + +# HTML deck — format notes + +Each slide is a web page inside one self-contained `output.html`. Composers use HTML, CSS and +JS within this range: any layout, styling, SVG and animation; slide scripts that run while +presenting, with the bundled ECharts and D3 libraries; controls the presenter operates on the +slide. Everything the deck shows, data and images included, lives inside the deck and works +offline. + +- **Template** — an HTML deck is built on the template's layouts, placeholders and + decorations. Choose a template as for PPTX and pass it to `apply_style(deck_id, style, + template)`; `deck.json` keeps it. +- **`visual`** names what the audience sees. For a slide the presenter operates, it names the + control and what it changes on screen; the steps to operate it are the presenter's and go in + the speaker notes. +- **Brief** — when the user asks for interactivity, record it in the brief's constraints, so the + outline and every composer carry it. +- **Review** — each composer's browser check leaves a PNG per slide, `/preview/png/.png` + (`get_preview` in the cloud). A slide without a PNG was not checked in a browser: report it + as unchecked. Read each PNG as the audience: its text names the content. A slide whose + visible text tells how to operate it goes back to its composer to move that text into the + speaker notes. +- **`deck.css`** holds the components the slides share. When a composer reports one missing, + dispatch one composer to add it to `deck.css`, then redo that slide. diff --git a/sdpm/references/guides/slide-html-spec.md b/sdpm/references/guides/slide-html-spec.md new file mode 100644 index 000000000..598e77f62 --- /dev/null +++ b/sdpm/references/guides/slide-html-spec.md @@ -0,0 +1,173 @@ +--- +name: slide-html-spec +description: "Slide HTML format — slides/.html sections, data-ph / data-region, tokens, deck.css, slide scripts with the bundled ECharts / D3, notes, images, chrome" +category: guide +--- + +# Slide HTML Reference + +An HTML deck (`deck.json` `"outputFormat": "html"`) is the same deck directory as a PPTX +deck, with slides written as HTML. After each change `run_python` assembles every slide into +one self-contained `output.html` (reveal.js, offline), checks the changed slides and returns +the findings as warnings, each naming its fix. + +``` +/ +├─ deck.json template, defaultBackground, outputFormat "html" +├─ deck.css shared component classes (written by the layout pass) +├─ specs/ brief.md, art-direction.html, outline.md +├─ slides/.html one
per file +└─ output.html generated — open it in a browser +``` + +## What a slide can use + +A slide is a web page: HTML, CSS and JS within this range. + +- Any layout, styling, inline SVG, CSS transitions and animations. +- Slide scripts (below) that run while presenting and respond to the presenter's clicks, + keys, pointer and inputs, with the bundled Apache ECharts 6.1.0 and D3 7.9.0. +- Steps within a slide: `class="fragment"` reveals an element on the next step (effect + classes such as `fade-up`; `data-fragment-index="N"` orders or groups steps). +- Motion across a prefix group (`demo-1`, `demo-2`): `data-auto-animate` on both sections and + the same `data-id` on each element that carries over; each slide of the group is complete + on its own. +- Everything offline: data lives in the slide's script or markup, images in the deck. + Links (``) open in a new tab. + +## File contract + +Each `slides/.html` holds exactly one `
`, with `data-layout` naming a layout of +the template. Slide order comes from `specs/outline.md`; the assembler sets `data-slug`. + +```html +
+

Claim headline

+
+

…

+ +
+ + + +
+``` + +## Canvas + +The section is the template's slide size in px (`template_html.slideSize.width` × `height`, +1920 × 1080 for a 16:9 template). `data-ph` elements are positioned by the template and +`data-region` boxes are absolute; give any other positioned element `position:absolute` +yourself. Flex and grid work inside. The template ground and decorations are the section +background. + +## `template_html` + +`start_composing(..., mode="html")` returns the template's description: + +| Field | Meaning | +|---|---| +| `slideSize` | `{width, height, ptPerPx}` — canvas px and points per px | +| `ptScale` | `0.75 / ptPerPx` — the value of `--sdpm-pt-scale` | +| `fonts` | `{major, minor, halfwidth, fullwidth}` | +| `themeColors` | `text`, `background`, `text2`, `background2`, `accent1`…`accent6` (hex) | +| `ground` | master background colour, or null | +| `layouts[].name` | the `data-layout` value (template order) | +| `layouts[].curated`, `notes` | whether the template recommends the layout, and its usage note | +| `layouts[].placeholders[]` | `{key, type, bbox{x,y,w,h}, text, aliases?, prompt?}` — `key` is the `data-ph` value; `aliases` adds `title` / `subtitle`; `text` is the resolved text style | +| `layouts[].chrome` | `slideNumber` / `footer` boxes the deck draws (see Chrome) | +| `layouts[].decorations[]` | `{name, source, bbox, kind}` — `ground` (covers most of the canvas), `band` (backs a placeholder, e.g. a title band) or `obstacle` (logo, copyright, mark) | +| `layouts[].ground` | `{kind: "solid", color}` or `{kind: "baked"}` (picture / gradient ground) | + +## Placeholders — `data-ph` + +`data-ph=""` puts an element where the layout's placeholder is and styles it like the +template (font, size, colour, alignment, bullets per list level); `title` and `subtitle` work +as aliases. Override the element's own properties with an inline `style`, a slide `", + f'', + f'', + f'', + ] + if deck_css_text: + out.append(f'') + out.append(f'') + return out + + html_open = f'' if lang else "" + notes_js = _vendor_text("plugin/notes.js") + libraries = [name for name in LIBRARIES if name in used_libraries] + scripts = [ + inline_js(_vendor_text("reveal.js")), + f"{_reveal_notice()}\n{_MARKED_NOTICE}\n{inline_js(notes_js)}", + *(inline_js(library_script(name)) for name in libraries), + *([SLIDE_HELPER] if slide_scripts else []), + *(inline_js(code) for _, code in slide_scripts), + _config_script(width, height), + ] + policy = deck_csp([script_hash(s) for s in scripts] + [script_hash(speaker_view_script(notes_js))]) + head = [ + "", + html_open, + "", + '', + csp_meta(policy), + REFERRER_META, + '', + f"{_html.escape(title)}", + *styles(layouts_used, slide_css), + "", + ] + body = [ + "", + '
', + *sections, + "
", + *(f"" for s in scripts), + "", + "", + ] + text = "\n".join(head + body) + "\n" + line_map: list[tuple[int, int, str]] = [] + line = 1 + # Owning slug of each entry: the sections, then the slide scripts (which follow + # "", the engine scripts, the libraries and the helper; the config is last). + owners = [None] * (len(head) + 2) + included + [None] * (len(scripts) - len(slide_scripts)) + owners += [slug for slug, _ in slide_scripts] + [None] * 3 # config, , + for entry, owner in zip(head + body, owners): + end = line + entry.count("\n") + if owner is not None: + line_map.append((line, end, owner)) + line = end + 1 + 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") + + previews: dict[str, str] = {} + for slug, (section_text, layout, own_css) in preview_sections.items(): + previews[slug] = "\n".join([ + "", + html_open, + "", + '', + csp_meta(PREVIEW_CSP), + REFERRER_META, + f"{_html.escape(title)} — {_html.escape(slug)}", + *styles([layout] if layout else [], own_css), + f'', + "", + "", + '
', + section_text, + "
", + "", + "", + ]) + "\n" + return AssembleResult(html=text, bytes=total, layouts_used=layouts_used, + warnings=warnings, slugs=included, previews=previews, + line_map=line_map, libraries=libraries, slide_scripts=len(slide_scripts)) + + +__all__ = ["AssembleResult", "MAX_EMBEDDED_FILE_BYTES", "MAX_OUTPUT_HTML_BYTES", "ParsedSlide", + "assemble_deck", "collect_refs", "inline_js", "letterbox_color", "parse_slide", + "style_root_css"] diff --git a/sdpm/sdpm/engine/html/browser.py b/sdpm/sdpm/engine/html/browser.py new file mode 100644 index 000000000..c4edaac7c --- /dev/null +++ b/sdpm/sdpm/engine/html/browser.py @@ -0,0 +1,201 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +"""Where the browser check gets its browser (design §9). + +A ``BrowserSource`` is a callable ``(width, height) -> ContextManager[BrowserEndpoint]``: +entering it starts (or borrows) a browser and yields the DevTools WebSocket URL, the +headers to connect with and a display name; leaving it releases the browser. + +Two kinds exist. The local source (``local_browser``) starts the Chrome or Edge found on +this machine headless, with DevTools on a random loopback port, a temporary profile and +no network. Adapters register their own with ``register_browser_source`` — the remote +server registers AgentCore Browser; the core itself never imports AWS code. + +``resolve_browser`` picks one: ``SDPM_BROWSER=none`` → the registered source → +``SDPM_BROWSER=`` → an auto-detected Chrome / Edge → none (with a skip note). +""" + +from __future__ import annotations + +import contextlib +import os +import shutil +import subprocess +import sys +import tempfile +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Callable, ContextManager, Iterator + + +@dataclass(frozen=True) +class BrowserEndpoint: + """A DevTools browser endpoint: WebSocket URL, connect headers, display name.""" + + url: str + headers: dict[str, str] = field(default_factory=dict) + name: str = "browser" + + +BrowserSource = Callable[[int, int], ContextManager[BrowserEndpoint]] + +DISABLED_NOTE = ("Browser check skipped: turned off here (SDPM_BROWSER=none), so layout, JS errors " + "and PNG previews of the slides are unknown.") +SKIPPED_NOTE = ("Browser check skipped: no Chrome or Edge found, so layout, JS errors and PNG previews " + "of the slides are unknown — install Chrome or Edge, or open output.html to look.") + + +def not_found_note(value: str) -> str: + """The skip note for an ``SDPM_BROWSER`` path that does not exist.""" + return (f"Browser check skipped: SDPM_BROWSER={value!r} is not an executable, so layout, JS errors " + "and PNG previews of the slides are unknown.") + + +_registered: BrowserSource | None = None + + +def register_browser_source(source: BrowserSource | None) -> None: + """Make ``source`` the browser of every check in this process (None removes it).""" + global _registered + _registered = source + + +def registered_browser_source() -> BrowserSource | None: + """The source an adapter registered, or None.""" + return _registered + + +# ── local Chrome / Edge ─────────────────────────────────────────────────── + +_MAC_APPS = ("Google Chrome.app/Contents/MacOS/Google Chrome", + "Microsoft Edge.app/Contents/MacOS/Microsoft Edge") +_LINUX_NAMES = ("google-chrome", "google-chrome-stable", "chromium", "chromium-browser", + "microsoft-edge", "microsoft-edge-stable") +_WINDOWS_ROOTS = ("ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA") +_WINDOWS_EXES = (r"Google\Chrome\Application\chrome.exe", r"Microsoft\Edge\Application\msedge.exe") + +_FLAGS = ( + "--headless", "--disable-gpu", "--no-first-run", "--no-default-browser-check", + "--disable-extensions", "--disable-background-networking", "--disable-sync", "--mute-audio", + # No network: the check runs untrusted slide code automatically. + "--proxy-server=http://127.0.0.1:9", "--proxy-bypass-list=<-loopback>", + "--host-resolver-rules=MAP * ~NOTFOUND", + "--force-webrtc-ip-handling-policy=disable_non_proxied_udp", +) + + +def find_browser() -> str | None: + """Chrome or Edge executable, or None. ``SDPM_BROWSER`` (a path; ``none`` disables) wins.""" + override = os.environ.get("SDPM_BROWSER", "").strip() + if override: + if override.lower() == "none": + return None + return override if os.path.isfile(override) else shutil.which(override) + candidates: list[str] = [] + if sys.platform == "darwin": + for root in ("/Applications", os.path.expanduser("~/Applications")): + candidates += [os.path.join(root, app) for app in _MAC_APPS] + if os.name == "nt": + for exe in _WINDOWS_EXES: + candidates += [os.path.join(os.environ[root], exe) + for root in _WINDOWS_ROOTS if os.environ.get(root)] + for path in candidates: + if os.path.isfile(path): + return path + if os.name != "nt": + for name in _LINUX_NAMES: + found = shutil.which(name) + if found: + return found + return None + + +def _stop(proc: subprocess.Popen) -> None: + if proc.poll() is not None: + return + proc.terminate() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + + +def _remove(profile: str) -> None: + shutil.rmtree(profile, ignore_errors=True) + if os.path.exists(profile): # Windows: the browser may still hold files for a moment + time.sleep(0.5) + shutil.rmtree(profile, ignore_errors=True) + + +def _display_name(executable: str) -> str: + name = Path(executable).name.lower() + if "edge" in name: + return "Microsoft Edge" + if "chromium" in name: + return "Chromium" + if "chrome" in name: + return "Google Chrome" + return Path(executable).name + + +@contextlib.contextmanager +def local_browser(executable: str, width: int, height: int, *, + start_timeout: float = 15.0) -> Iterator[BrowserEndpoint]: + """Start ``executable`` headless with DevTools on a random 127.0.0.1 port. + + The port and path come from ``DevToolsActivePort`` in a temporary profile; the + browser is stopped and the profile removed on exit. + """ + profile = tempfile.mkdtemp(prefix="sdpm-browser-") + proc = None + try: + argv = [executable, *_FLAGS, f"--window-size={width},{height}", "--remote-debugging-port=0", + f"--user-data-dir={profile}", "about:blank"] + # Fixed argv, no shell; the executable comes from a fixed list or SDPM_BROWSER. + proc = subprocess.Popen( # nosec B603 # nosemgrep: python.lang.security.audit.dangerous-subprocess-use-audit + argv, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + port_file = Path(profile) / "DevToolsActivePort" + started = time.monotonic() + while True: + lines = port_file.read_text(encoding="utf-8").splitlines() if port_file.is_file() else [] + if len(lines) >= 2 and lines[0].strip().isdigit(): + break + code = proc.poll() + if code is not None: + raise RuntimeError(f"{Path(executable).name} exited (code {code}) before DevTools started") + if time.monotonic() - started > start_timeout: + raise TimeoutError(f"DevTools did not start within {start_timeout:g} s") + time.sleep(0.05) + port, path = lines[0].strip(), lines[1].strip() + yield BrowserEndpoint(f"ws://127.0.0.1:{port}{path}", {}, _display_name(executable)) + finally: + if proc is not None: + _stop(proc) + _remove(profile) + + +def _local_source(executable: str) -> BrowserSource: + def source(width: int, height: int) -> ContextManager[BrowserEndpoint]: + return local_browser(executable, width, height) + source.browser_name = _display_name(executable) # type: ignore[attr-defined] # named before it starts + return source + + +def resolve_browser() -> tuple[BrowserSource | None, str | None]: + """``(source, None)`` for the browser to use, or ``(None, skip note)``.""" + override = os.environ.get("SDPM_BROWSER", "").strip() + if override.lower() == "none": + return None, DISABLED_NOTE + if _registered is not None: + return _registered, None + executable = find_browser() + if executable is None: + return None, not_found_note(override) if override else SKIPPED_NOTE + return _local_source(executable), None + + +__all__ = ["BrowserEndpoint", "BrowserSource", "DISABLED_NOTE", "SKIPPED_NOTE", "find_browser", + "local_browser", "not_found_note", "register_browser_source", "registered_browser_source", + "resolve_browser"] diff --git a/sdpm/sdpm/engine/html/browser_check.py b/sdpm/sdpm/engine/html/browser_check.py new file mode 100644 index 000000000..236020889 --- /dev/null +++ b/sdpm/sdpm/engine/html/browser_check.py @@ -0,0 +1,590 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +"""Browser check for HTML decks: load, render, measure, JS errors, PNG (design §9). + +``check_deck`` opens the built ``output.html`` in a browser from +``sdpm.engine.html.browser.resolve_browser`` (local headless Chrome / Edge, or the source +an adapter registered) over the DevTools protocol (``sdpm.engine.html.cdp``): + +1. attach to the page; enable Page / Runtime / Log; fail every http(s) / ws(s) request + through the Fetch domain, navigations included (if the browser rejects that, the check + fails before the deck loads); auto-attach targets the page opens paused, close the + pages and block the frames / workers the same way; install the egress guard + (``EGRESS_GUARD``, on every new document of the page and its frames) that removes + WebRTC and ``WebTransport`` and makes ``window.open`` return null; + set the viewport to the deck size; +2. load the deck: up to ``DIRECT_LIMIT`` UTF-8 bytes with ``Page.setDocumentContent`` on + ``about:blank#sdpm-check``, larger in chunks into a ``blob:`` URL (CDP drops messages + around 10–12 MB); wait for ``Reveal.isReady()``; turn margins, controls, transitions + and the URL hash off; prove the guard (``EGRESS_PROBE``: the top window, a fresh + iframe, a srcdoc iframe, ``window.open``) — a reachable WebRTC constructor fails the + check before any slide runs. ``network_blocked`` then means requests fail through Fetch + and WebRTC is removed (probed); DNS hints (``dns-prefetch``, ``preconnect``) are not covered; +3. per requested slug, in deck order: ``Reveal.slide(i, 0, 999)`` (every fragment + shown), settle (1 frame → ``finish()`` every running animation → 2 frames; the slide + helper makes ``Reveal.isPrintView()`` true while slide code runs under + ``#sdpm-check``), measure the placeholders, regions and blocks + (``layout_judge.judge_slide``), and capture a PNG 1280 px on the long edge; +4. collect JS errors (``errors_from_events``): uncaught exceptions of the page, the slide + helper's ``sdpm slide : …`` console errors, CSP violations. + +A slide that navigates the page away stops the check (``navigated``); the whole check has +a deadline (``min(30 + 3 × slides, 110)`` s, below AgentCore Browser's 120 s session). +``check_deck`` never raises; every status but ``ok`` / ``issues`` carries a ``note``. +""" + +from __future__ import annotations + +import base64 +import json +import logging +import re +import time +from pathlib import Path +from typing import Any, Iterable, Mapping, Sequence + +from sdpm.engine.html.browser import resolve_browser +from sdpm.engine.html.cdp import CdpConnection, CdpError, CdpTimeout +from sdpm.engine.html.layout_judge import judge_slide + +logger = logging.getLogger(__name__) + +DIRECT_LIMIT = 10_000_000 # UTF-8 bytes loaded with Page.setDocumentContent +CHUNK = 2_000_000 # characters per blob chunk +READY_TIMEOUT = 30.0 +PNG_LONG_EDGE = 1280 +NAVIGATED_MARK = "sdpm-check:navigated" +_MAX_MESSAGE = 400 +# URL patterns the check BLOCKS (Fetch.requestPaused → failRequest); nothing connects to them. +_BLOCKED = ["http://*", "https://*", "ws://*", "wss://*"] # nosemgrep: javascript.lang.security.detect-insecure-websocket.detect-insecure-websocket +FETCH_BLOCK = {"patterns": [{"urlPattern": p} for p in _BLOCKED]} +_HELPER_SLUG_RE = re.compile(r"sdpm slide (\S+?): ") +_HASHES_RE = re.compile(r"script-src(?: 'sha256-[^']+')+") +_CSP_HINTS = ("Content Security Policy", "Refused to") +# Appended to a CSP violation: what the slide should do instead. +CSP_FIX = ("; the deck runs offline with inline code only: put data in the slide script and " + "embed images (deck files, assets:)") + +RAF1 = "new Promise(function(r){requestAnimationFrame(function(){r(1);});})" +RAF2 = "new Promise(function(r){requestAnimationFrame(function(){requestAnimationFrame(function(){r(1);});});})" +FINISH = ("(function(){var n=0;document.getAnimations().forEach(function(a){try{a.finish();n++;}catch(e){}});" + "return n;})()") +CONFIGURE = "Reveal.configure({margin:0,controls:false,progress:false,transition:'none',hash:false})" +SLUGS = "Array.prototype.map.call(Reveal.getSlides(),function(s){return s.getAttribute('data-slug');})" + +# Egress the Fetch block does not see: WebRTC (ICE / STUN / TURN over UDP and TCP) and +# WebTransport. The guard runs before any script of every new document of the page and its +# frames: it removes these constructors from the window, seals every same-origin child +# window reached through contentWindow / contentDocument before it is returned, and makes +# window.open return null. EGRESS_PROBE proves it after the deck loaded. +_EGRESS_NAMES = ("RTCPeerConnection", "webkitRTCPeerConnection", "RTCDataChannel", "RTCIceTransport", + "RTCSctpTransport", "RTCDtlsTransport", "RTCRtpSender", "RTCRtpReceiver", + "RTCRtpTransceiver", "RTCIceCandidate", "RTCSessionDescription", "WebTransport") +EGRESS_GUARD = r"""(function(){ +var N=%s; +function no(){return null;} +function lock(w,n,v){try{Object.defineProperty(w,n,{value:v,writable:false,configurable:false});}catch(e){}} +function seal(w){ + if(!w)return w; + try{if(w.__sdpmSealed)return w;}catch(e){return w;} + N.forEach(function(n){lock(w,n,undefined);}); + lock(w,'open',no); + lock(w,'__sdpmSealed',true); + return w;} +seal(window); +[window.HTMLIFrameElement,window.HTMLFrameElement,window.HTMLObjectElement].forEach(function(C){ + if(!C)return;var p=C.prototype; + var cw=Object.getOwnPropertyDescriptor(p,'contentWindow'); + if(cw&&cw.get)Object.defineProperty(p,'contentWindow',{configurable:false,enumerable:cw.enumerable, + get:function(){return seal(cw.get.call(this));}}); + var cd=Object.getOwnPropertyDescriptor(p,'contentDocument'); + if(cd&&cd.get)Object.defineProperty(p,'contentDocument',{configurable:false,enumerable:cd.enumerable, + get:function(){var d=cd.get.call(this);if(d)seal(d.defaultView);return d;}}); +}); +})();""" % json.dumps(list(_EGRESS_NAMES)) +# Resolves to the reachable "." list (empty: the guard holds). window[n] of a +# fresh iframe is read before its contentWindow (whose getter seals it). +EGRESS_PROBE = r"""(function(){ +var N=%s,out=[]; +function check(w,where){if(!w)return; + try{N.forEach(function(n){if(typeof w[n]!=='undefined')out.push(where+'.'+n);});} + catch(e){out.push(where+' (unreadable)');}} +function frame(){var f=document.createElement('iframe');f.style.display='none'; + document.body.appendChild(f);return f;} +check(window,'top'); +var f=frame(); +check(window[window.length-1],'frame'); +check(f.contentWindow,'iframe'); +f.remove(); +var p=null; +try{p=window.open('about:blank');}catch(e){} +check(p,'open'); +try{if(p)p.close();}catch(e){} +return new Promise(function(resolve){ + var s=frame(),done=false; + function fin(loaded){if(done)return;done=true; + if(loaded){check(window[window.length-1],'srcdoc frame');check(s.contentWindow,'srcdoc');} + else out.push('srcdoc (did not load)'); + s.remove();resolve(out);} + s.onload=function(){fin(true);}; + setTimeout(function(){fin(false);},3000); + s.srcdoc='

probe

'; +}); +})()""" % json.dumps(list(_EGRESS_NAMES)) +_GUARD_PARAMS = {"source": EGRESS_GUARD, "runImmediately": True} + +MEASURE = r"""(function(){ +var s=Reveal.getCurrentSlide();if(!s)return null; +var r0=s.getBoundingClientRect();var f=r0.width?s.offsetWidth/r0.width:1; +var out=[],idx=new Map(); +function skip(el){return el.matches('aside.notes,script,style,[data-sdpm-chrome]')||!!el.closest('[data-sdpm-chrome]');} +function text(el){var t=(el.textContent||'').replace(/\s+/g,' ').trim();return t.length>24?t.slice(0,24)+'…':t;} +function label(el,kind){ + if(kind==='ph')return 'data-ph="'+el.getAttribute('data-ph')+'"'; + if(kind==='region')return 'data-region="'+el.getAttribute('data-region')+'"'; + var tag='<'+el.tagName.toLowerCase()+'>',t=text(el); + if(t)return tag+' "'+t+'"'; + var c=(el.getAttribute('class')||'').trim().split(/\s+/)[0]; + return c?'<'+el.tagName.toLowerCase()+' class="'+c+'">':tag;} +function regionOf(el){var p=el.parentElement&&el.parentElement.closest('[data-region]'); + return p&&s.contains(p)&&idx.has(p)?idx.get(p):undefined;} +function add(el,kind,region){ + if(idx.has(el)||skip(el))return; + if(getComputedStyle(el).display==='none')return; + var r=el.getBoundingClientRect();if(!r.width||!r.height)return; + var e={kind:kind,label:label(el,kind),box:[(r.left-r0.left)*f,(r.top-r0.top)*f,r.width*f,r.height*f], + scroll:[el.scrollWidth,el.scrollHeight,el.clientWidth,el.clientHeight]}; + if(region!==undefined)e.region=region; + idx.set(el,out.length);out.push(e);} +s.querySelectorAll('[data-region]').forEach(function(el){add(el,'region',regionOf(el));}); +s.querySelectorAll('[data-ph]').forEach(function(el){add(el,'ph',regionOf(el));}); +s.querySelectorAll('[data-region]').forEach(function(reg){if(!idx.has(reg))return; + Array.prototype.forEach.call(reg.children,function(el){add(el,'child',idx.get(reg));});}); +Array.prototype.forEach.call(s.children,function(el){add(el,'free');}); +return {width:s.offsetWidth,height:s.offsetHeight,elements:out}; +})()""" + +_NOISE = ( + re.compile(r"replaceState.*SecurityError|SecurityError.*replaceState", re.DOTALL), + re.compile(r"Extension context invalidated\."), +) + + +def deadline_for(slide_count: int) -> float: + """The whole check's time budget in seconds.""" + return float(min(30 + 3 * slide_count, 110)) + + +# ── JS errors (pure) ────────────────────────────────────────────────────── + +def _slug_for_line(line: int | None, line_map) -> str | None: + if line is None: + return None + for first, last, slug in line_map: + if first <= line <= last: + return slug + return None + + +def _is_noise(message: str) -> bool: + return any(p.search(message) for p in _NOISE) + + +def errors_from_events(events: Iterable[dict], line_map, main_contexts: set[int] | None, + current_slug: str | None, *, slugs: Iterable[str] | None = None) -> list[dict]: + """JS errors of CDP events as diagnostics ``{slug, rule: "js-error", message, line?}``. + + Sources: main-world ``Runtime.exceptionThrown`` and helper console errors + (``sdpm slide : …``) — ``main_contexts`` (None: any context) — and CSP violations + from ``Log.entryAdded``. A slug comes from the helper prefix, else the line + (``lineNumber + 1``) in ``line_map``, else ``current_slug``. With ``slugs``, errors of + other slugs are dropped; unattributed ones are kept with slug None. + """ + known = {slug for _, _, slug in line_map} + wanted = set(slugs) if slugs is not None else None + out: list[dict] = [] + + def add(message: str, line: int | None, fix: str = "") -> None: + message = message.strip() + if not message or _is_noise(message): + return + m = _HELPER_SLUG_RE.match(message) + slug = m.group(1) if m and (m.group(1) in known or not known) else None + slug = slug or _slug_for_line(line, line_map) or current_slug + if wanted is not None and slug is not None and slug not in wanted: + return + diag: dict[str, Any] = {"slug": slug, "rule": "js-error", + "message": f"JS error: {_HASHES_RE.sub('script-src …', message)[:_MAX_MESSAGE]}{fix}"} + if line is not None: + diag["line"] = line + if not any(d["slug"] == diag["slug"] and d["message"] == diag["message"] for d in out): + out.append(diag) + + def in_main(context_id) -> bool: + return main_contexts is None or context_id is None or context_id in main_contexts + + for event in events: + method, params = event.get("method"), event.get("params") or {} + if method == "Runtime.exceptionThrown": + details = params.get("exceptionDetails") or {} + if not in_main(details.get("executionContextId")): + continue + text = (details.get("exception") or {}).get("description") or details.get("text") or "" + line = details.get("lineNumber") + add(text, line + 1 if isinstance(line, int) else None) + elif method == "Runtime.consoleAPICalled": + if params.get("type") != "error" or not in_main(params.get("executionContextId")): + continue + args = params.get("args") or [] + text = str((args[0] if args else {}).get("value", "")) + if not text.startswith("sdpm slide "): + continue + frames = (params.get("stackTrace") or {}).get("callFrames") or [] + line = frames[0].get("lineNumber") if frames else None + add(text, line + 1 if isinstance(line, int) else None) + elif method == "Log.entryAdded": + entry = params.get("entry") or {} + text = entry.get("text") or "" + if entry.get("level") != "error" or not any(h in text for h in _CSP_HINTS): + continue + line = entry.get("lineNumber") + add(text, line + 1 if isinstance(line, int) else None, CSP_FIX) + return out + + +# ── the check ───────────────────────────────────────────────────────────── + +class _Navigated(Exception): + pass + + +class _Deadline(Exception): + pass + + +class _Run: + """State of one check: the connection, events, timings and results.""" + + def __init__(self, slugs: Sequence[str], line_map, limit: float) -> None: + self.slugs = list(slugs) + self.line_map = line_map + self.started = time.monotonic() + self.limit = limit + self.end = self.started + limit + self.cdp: CdpConnection | None = None + self.session: str | None = None + self.target_id: str | None = None + self.frame_id: str | None = None + self.loaded = False + self.current: str | None = None + self.main_contexts: set[int] = set() + self.errors: list[dict] = [] + self.checked: list[str] = [] + self.findings: dict[str, list[dict]] = {} + self.pngs: dict[str, str] = {} + self.timings: dict[str, float] = {} + self.navigated_at: str | None = None + self.network_blocked: bool | None = None + self.blocked_requests = 0 + + # time + def left(self) -> float: + return self.end - time.monotonic() + + def budget(self, timeout: float) -> float: + left = self.left() + if left <= 0: + raise _Deadline() + return max(min(timeout, left), 0.1) + + # CDP with the deadline and event pumping + def send(self, method: str, params: dict | None = None, *, page: bool = True, timeout: float = 15.0) -> dict: + assert self.cdp is not None + try: + return self.cdp.send(method, params, session=self.session if page else None, + timeout=self.budget(timeout)) + finally: + self.pump() + + def js(self, expr: str, *, await_promise: bool = False, timeout: float = 15.0) -> Any: + assert self.cdp is not None + try: + return self.cdp.evaluate(self.session, expr, await_promise=await_promise, + timeout=self.budget(timeout)) + finally: + self.pump() + + def is_navigation(self, event: dict) -> bool: + """True for an event that says the deck page navigated away.""" + method, params = event.get("method"), event.get("params") or {} + if event.get("sessionId") not in (None, self.session): + return False + if method == "Page.frameNavigated": + frame = params.get("frame") or {} + if frame.get("parentId") is None and (self.frame_id is None or frame.get("id") == self.frame_id): + url = frame.get("url") or "" + return self.loaded or not (url.startswith("blob:") or url.startswith("about:blank")) + elif method == "Runtime.executionContextsCleared": + return self.loaded + elif method == "Runtime.consoleAPICalled": + args = params.get("args") or [] + return bool(args) and args[0].get("value") == NAVIGATED_MARK + return False + + def intercept(self, event: dict) -> None: + """Answer request and target events as they arrive (also while a reply is awaited, + so a paused navigation never stalls the check): fail every paused http(s) / ws(s) + request (any session: the page, a frame, a worker); close a page the deck opens and + give a frame or worker the same block before it runs. Both arrive paused.""" + method, params = event.get("method"), event.get("params") or {} + if method == "Fetch.requestPaused": + self.blocked_requests += 1 + self.cdp.post("Fetch.failRequest", {"requestId": params.get("requestId"), + "errorReason": "BlockedByClient"}, session=event.get("sessionId")) + elif method == "Target.attachedToTarget" and self.session and event.get("sessionId") == self.session: + # Our own attachToTarget arrives without a sessionId and is not handled here. + info = params.get("targetInfo") or {} + if info.get("targetId") == self.target_id: + return + if info.get("type") == "page": + self.cdp.post("Target.closeTarget", {"targetId": info.get("targetId")}) + else: + self.cdp.post("Fetch.enable", FETCH_BLOCK, session=params.get("sessionId")) + if info.get("type") == "iframe": + self.cdp.post("Page.addScriptToEvaluateOnNewDocument", _GUARD_PARAMS, + session=params.get("sessionId")) + self.cdp.post("Runtime.runIfWaitingForDebugger", session=params.get("sessionId")) + + def watch(self, event: dict) -> None: + """``CdpConnection.on_event``: answer requests and targets, stop at once when the + page navigates away.""" + self.intercept(event) + if self.navigated_at is None and self.is_navigation(event): + self.navigated_at = self.current or "" + raise _Navigated() + + def pump(self) -> None: + """Process events read so far: contexts, navigation, JS errors.""" + if self.cdp is None: + return + events = self.cdp.take_events() + if not events: + return + navigated = False + for event in events: + method, params = event.get("method"), event.get("params") or {} + if event.get("sessionId") not in (None, self.session): + continue + navigated = navigated or self.is_navigation(event) + if method == "Runtime.executionContextCreated": + ctx = params.get("context") or {} + aux = ctx.get("auxData") or {} + if aux.get("isDefault") and (self.frame_id is None or aux.get("frameId") == self.frame_id): + self.main_contexts.add(ctx.get("id")) + self.errors.extend(e for e in errors_from_events(events, self.line_map, self.main_contexts or None, + self.current, slugs=self.slugs) + if not any(e["slug"] == d["slug"] and e["message"] == d["message"] + for d in self.errors)) + if navigated and self.navigated_at is None: + self.navigated_at = self.current or "" + raise _Navigated() + + +def _page_setup(run: _Run, width: int, height: int) -> None: + targets = run.send("Target.getTargets", page=False)["targetInfos"] + page = next(t for t in targets if t.get("type") == "page") + run.target_id = page["targetId"] + run.session = run.send("Target.attachToTarget", {"targetId": page["targetId"], "flatten": True}, + page=False)["sessionId"] + for domain in ("Page.enable", "Runtime.enable", "Log.enable"): + run.send(domain) + run.frame_id = run.send("Page.getFrameTree")["frameTree"]["frame"]["id"] + # Requests: the Fetch domain pauses every http(s) / ws(s) request of the page (top-level + # navigations included — Network.setBlockedURLs lets those through in AgentCore Browser) + # and pump() fails it. No Network.enable: its events carry whole data: URLs, and an + # event over ~10 MB makes AgentCore Browser drop the automation stream. + # Targets the page opens are auto-attached paused (popups closed, frames blocked too). + try: + run.send("Fetch.enable", FETCH_BLOCK) + run.send("Target.setAutoAttach", {"autoAttach": True, "waitForDebuggerOnStart": True, "flatten": True}) + except CdpError as exc: + # Fail closed: slide code never runs in a browser that may reach the network + # (AgentCore Browser has internet access); the check fails with a note. + run.network_blocked = False + logger.warning("browser check: could not block network requests: %s", exc) + raise RuntimeError(f"could not block network requests, so no slide was run ({exc})") from exc + # WebRTC and WebTransport bypass Fetch: the guard removes them before deck code runs; + # check_deck probes it after the load and only then sets network_blocked. + try: + run.send("Page.addScriptToEvaluateOnNewDocument", _GUARD_PARAMS) + except CdpError as exc: + run.network_blocked = False + logger.warning("browser check: could not disable WebRTC: %s", exc) + raise RuntimeError(f"could not disable WebRTC, so no slide was run ({exc})") from exc + run.send("Emulation.setDeviceMetricsOverride", + {"width": width, "height": height, "deviceScaleFactor": 1, "mobile": False}) + + +def _load(run: _Run, html: str) -> None: + if len(html.encode("utf-8")) <= DIRECT_LIMIT: + run.send("Page.navigate", {"url": "about:blank#sdpm-check"}) + time.sleep(0.1) + run.send("Page.setDocumentContent", {"frameId": run.frame_id, "html": html}, timeout=60) + else: + run.send("Page.navigate", {"url": "about:blank"}) + time.sleep(0.1) + run.js("window.__sdpmChunks=[];0") + for i in range(0, len(html), CHUNK): + run.js(f"window.__sdpmChunks.push({json.dumps(html[i:i + CHUNK], ensure_ascii=False)});0", timeout=60) + run.js("location.href=URL.createObjectURL(new Blob(window.__sdpmChunks," + "{type:'text/html;charset=utf-8'}))+'#sdpm-check';0") + ready_by = time.monotonic() + READY_TIMEOUT + while True: + try: + if run.js("!!(window.Reveal&&Reveal.isReady&&Reveal.isReady())", timeout=5): + break + except CdpError: + pass # the document is being replaced + if time.monotonic() > ready_by: + raise CdpError(f"the deck did not become ready within {READY_TIMEOUT:g} s") + time.sleep(0.05) + run.loaded = True + run.js(CONFIGURE + ";0") + + +def _slide(run: _Run, slug: str, index: int, *, width: int, height: int, decorations: list[dict], + png_dir: Path | None) -> None: + run.current = slug + # __sdpmCheckRun: the slide shown first gets no ready / slidechanged event here. + run.js(f"Reveal.slide({index},0,999);window.__sdpmCheckRun&&window.__sdpmCheckRun();0") + run.js(RAF1, await_promise=True, timeout=10) + run.js(FINISH) + run.js(RAF2, await_promise=True, timeout=10) + measured = run.js(MEASURE) + findings = judge_slide(slug, measured or {}, decorations) + if png_dir is not None: + clip = {"x": 0, "y": 0, "width": width, "height": height, "scale": PNG_LONG_EDGE / max(width, height)} + data = run.send("Page.captureScreenshot", {"format": "png", "clip": clip}, timeout=30)["data"] + png_dir.mkdir(parents=True, exist_ok=True) + path = png_dir / f"{slug}.png" + path.write_bytes(base64.b64decode(data)) + run.pngs[slug] = str(path) + run.checked.append(slug) + if findings: + run.findings[slug] = findings + + +def _rest_note(run: _Run) -> str: + return (f"{len(run.checked)} of {len(run.slugs)} slide(s) checked; layout, JS errors and PNG " + "previews of the rest are unknown") + + +def check_deck( + output_html: str | Path, + slugs: Sequence[str], + *, + slide_size: tuple[int, int], + line_map, + layouts: Mapping[str, str], + decorations: Mapping[str, list[dict]], + png_dir: str | Path | None = None, + deadline: float | None = None, +) -> dict[str, Any]: + """Check ``slugs`` of a built deck in a browser. Never raises. + + Args: + slide_size: canvas ``(width, height)`` in px (template.json ``slideSize``). + line_map: the assembler's ``(first, last, slug)`` line ranges. + layouts: slug → its ``data-layout``; decorations: layout → template decorations. + png_dir: where ``.png`` goes (None: skip the PNG). + deadline: the time budget in seconds (default ``deadline_for(len(slugs))``). + + Returns: + ``{status, browser?, seconds?, slides, checked, findings: {slug: [diag]}, + errors: [diag], pngs: {slug: path}, timings?, network_blocked?, blocked_requests?, note?}``; status ``ok`` / ``issues`` + / ``skipped`` / ``navigated`` / ``timeout`` / ``failed``. ``network_blocked`` is True + when http(s) / ws(s) requests failed through Fetch and WebRTC was removed (probed + before the first slide ran); DNS hints are not covered. + """ + slugs = list(dict.fromkeys(slugs)) + base: dict[str, Any] = {"slides": 0, "checked": [], "findings": {}, "errors": [], "pngs": {}} + source, skip_note = resolve_browser() + if source is None: + return {"status": "skipped", **base, "note": skip_note} + width, height = int(slide_size[0]), int(slide_size[1]) + limit = float(deadline) if deadline is not None else deadline_for(len(slugs)) + run = _Run(slugs, line_map, limit) + name = getattr(source, "browser_name", "browser") + status, note = "ok", None + png_path = Path(png_dir) if png_dir is not None else None + released = None + try: + html = Path(output_html).read_text(encoding="utf-8") + t0 = time.monotonic() + with source(width, height) as endpoint: + name = endpoint.name + run.timings["acquire"] = round(time.monotonic() - t0, 3) + try: + t1 = time.monotonic() + with CdpConnection(endpoint.url, endpoint.headers) as cdp: + run.cdp = cdp + cdp.on_event = run.watch + _page_setup(run, width, height) + run.timings["connect"] = round(time.monotonic() - t1, 3) + t2 = time.monotonic() + _load(run, html) + run.timings["load"] = round(time.monotonic() - t2, 3) + reachable = run.js(EGRESS_PROBE, await_promise=True) + if reachable: + run.network_blocked = False + raise RuntimeError(f"could not disable WebRTC ({', '.join(map(str, reachable))}), " + "so no slide was run") + run.network_blocked = True + order = run.js(SLUGS) or [] + index = {} + for i, slug in enumerate(order): + index.setdefault(slug, i) + t3 = time.monotonic() + for slug in sorted((s for s in slugs if s in index), key=index.get): + _slide(run, slug, index[slug], width=width, height=height, + decorations=decorations.get(layouts.get(slug, ""), []), png_dir=png_path) + run.current = None + time.sleep(0.1) + run.send("Runtime.evaluate", {"expression": "0"}) # read the last events + run.timings["slides"] = round(time.monotonic() - t3, 3) + except _Navigated: + status = "navigated" + where = f" while {run.navigated_at} was shown" if run.navigated_at else "" + note = (f"Browser check stopped: a slide script navigated the page away{where} (location, " + f"reload, form submit…; the check blocks network requests, so it reached no " + f"site); {_rest_note(run)}. Remove the navigation (see the script-external warning).") + except (_Deadline, CdpTimeout): + status = "timeout" + note = (f"Browser check did not finish within {limit:g} s; {_rest_note(run)}. A slide " + "script that never returns can cause this.") + finally: + run.cdp = None + released = time.monotonic() + run.timings["release"] = round(time.monotonic() - released, 3) + except Exception as exc: # acquisition / connection / CDP failure: reported, never raised + status = "failed" + note = (f"Browser check could not run ({name}): {type(exc).__name__}: {str(exc)[:300]}; " + f"{_rest_note(run)}.") + if released is not None: + run.timings.setdefault("release", round(time.monotonic() - released, 3)) + if status == "ok" and (run.findings or run.errors): + status = "issues" + result: dict[str, Any] = { + "status": status, "browser": name, "seconds": round(time.monotonic() - run.started, 1), + "slides": len(run.checked), "checked": run.checked, "findings": run.findings, + "errors": run.errors, "pngs": run.pngs, "timings": run.timings, + } + if run.network_blocked is not None: + result["network_blocked"] = run.network_blocked + result["blocked_requests"] = run.blocked_requests + if note: + result["note"] = note + return result + + +__all__ = ["CHUNK", "DIRECT_LIMIT", "PNG_LONG_EDGE", "check_deck", "deadline_for", "errors_from_events"] diff --git a/sdpm/sdpm/engine/html/cdp.py b/sdpm/sdpm/engine/html/cdp.py new file mode 100644 index 000000000..6e7a64014 --- /dev/null +++ b/sdpm/sdpm/engine/html/cdp.py @@ -0,0 +1,136 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +"""A small synchronous Chrome DevTools Protocol client over one WebSocket. + +``CdpConnection`` uses ``websockets``' sync client (no asyncio), so it works from a +worker thread and from code already running inside an event loop. Every call has a +deadline; events that arrive while a reply is awaited are kept for ``take_events``. +Sessions are flat (``Target.attachToTarget`` with ``flatten``): page commands carry a +``sessionId``. +""" + +from __future__ import annotations + +import itertools +import json +import time +from typing import Any, Callable, Mapping + + +class CdpError(RuntimeError): + """A CDP error reply, a JS exception, or a closed connection.""" + + +class CdpTimeout(CdpError): + """No reply within the call's timeout.""" + + +class CdpConnection: + """Context manager holding one DevTools WebSocket (browser-level endpoint).""" + + def __init__(self, url: str, headers: Mapping[str, str] | None = None, *, + open_timeout: float = 15, max_size: int = 64 << 20) -> None: + self.url = url + self.headers = dict(headers or {}) + self.open_timeout = open_timeout + self.max_size = max_size + self._ws = None + self._ids = itertools.count(1) + self._events: list[dict] = [] + # Called with each event as it arrives (also while a reply is awaited); an + # exception it raises propagates out of ``send``. + self.on_event: Callable[[dict], None] | None = None + + def __enter__(self) -> "CdpConnection": + try: + from websockets.sync.client import connect + except ImportError as exc: + raise CdpError("websockets is not installed") from exc + try: + conn = connect(self.url, additional_headers=self.headers or None, + max_size=self.max_size, open_timeout=self.open_timeout) + except Exception as exc: + raise CdpError(f"could not connect to the browser: {type(exc).__name__}: {exc}") from exc + self._ws = conn.__enter__() # closed in __exit__ + return self + + def __exit__(self, *exc_info) -> None: + ws, self._ws = self._ws, None + if ws is not None: + try: + ws.__exit__(None, None, None) + except Exception: # nosec B110 - closing a socket that is already gone + pass + + def send(self, method: str, params: dict | None = None, *, session: str | None = None, + timeout: float = 15.0) -> dict: + """Send one command and return its ``result``; events read meanwhile are kept.""" + from websockets.exceptions import ConnectionClosed + + if self._ws is None: + raise CdpError(f"{method}: not connected") + msg_id = next(self._ids) + msg: dict[str, Any] = {"id": msg_id, "method": method, "params": params or {}} + if session: + msg["sessionId"] = session + deadline = time.monotonic() + timeout + try: + self._ws.send(json.dumps(msg)) + while True: + left = deadline - time.monotonic() + if left <= 0: + raise CdpTimeout(f"{method}: no reply within {timeout:g} s") + try: + raw = self._ws.recv(timeout=left) + except TimeoutError: + raise CdpTimeout(f"{method}: no reply within {timeout:g} s") from None + reply = json.loads(raw) + if reply.get("id") == msg_id: + if "error" in reply: + err = reply["error"] + text = err.get("message", err) if isinstance(err, dict) else err + raise CdpError(f"{method}: {text}") + return reply.get("result", {}) + if "method" in reply: + self._events.append(reply) + if self.on_event is not None: + self.on_event(reply) + except ConnectionClosed as exc: + raise CdpError(f"{method}: connection closed ({exc})") from exc + + def post(self, method: str, params: dict | None = None, *, session: str | None = None) -> None: + """Send one command without waiting for its reply, which ``send`` then ignores. + + Safe inside ``on_event`` (a nested ``send`` would swallow the awaited reply). + """ + from websockets.exceptions import ConnectionClosed + + if self._ws is None: + raise CdpError(f"{method}: not connected") + msg: dict[str, Any] = {"id": next(self._ids), "method": method, "params": params or {}} + if session: + msg["sessionId"] = session + try: + self._ws.send(json.dumps(msg)) + except ConnectionClosed as exc: + raise CdpError(f"{method}: connection closed ({exc})") from exc + + def evaluate(self, session: str, expr: str, *, await_promise: bool = False, + timeout: float = 15.0) -> Any: + """``Runtime.evaluate`` by value; a thrown JS exception raises ``CdpError``.""" + result = self.send("Runtime.evaluate", {"expression": expr, "returnByValue": True, + "awaitPromise": await_promise}, + session=session, timeout=timeout) + details = result.get("exceptionDetails") + if details: + text = (details.get("exception") or {}).get("description") or details.get("text") or "exception" + raise CdpError(f"evaluate: {text[:400]}") + return (result.get("result") or {}).get("value") + + def take_events(self) -> list[dict]: + """Events received so far (each returned once).""" + events, self._events = self._events, [] + return events + + +__all__ = ["CdpConnection", "CdpError", "CdpTimeout"] diff --git a/sdpm/sdpm/engine/html/check.py b/sdpm/sdpm/engine/html/check.py new file mode 100644 index 000000000..9db02d514 --- /dev/null +++ b/sdpm/sdpm/engine/html/check.py @@ -0,0 +1,610 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +"""Static checks for HTML decks (slides/.html and deck.css), no browser needed. + +Every check returns diagnostics ``{"slug", "rule", "message"}``; callers turn them +into warnings. Nothing here blocks a build. The browser check (layout, JS errors, +PNG) lives in ``sdpm.engine.html.browser_check``; ``format_check_report`` reports both. + +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 = _deck(tmp_path, slides=slides) + result = api.generate_html(deck) + assert result["script_external"] == [{"slug": "nav", "kinds": ["navigation", "external-url"]}] + assert api.refresh_html(deck)["script_external"] == result["script_external"] + + +def test_generate_html_custom_output_path(tmp_path) -> None: + deck = _deck(tmp_path) + out = tmp_path / "elsewhere" / "deck.html" + assert api.generate_html(deck, out)["output_path"] == str(out) + assert out.is_file() and not (deck / "output.html").exists() + + +def test_generate_html_rejects_pptx_deck(tmp_path) -> None: + deck = tmp_path / "pptx" + api.init("t", output_dir=deck) + with pytest.raises(ValueError, match="PPTX deck"): + api.generate_html(deck) + + +def test_deck_css_embedded_once_and_checked(tmp_path) -> None: + deck = _deck(tmp_path) + css = ".card { font-size: 24px; background: url(http://example.com/a.png); }\n:root { --x: 1; }" + (deck / "deck.css").write_text(css, encoding="utf-8") + result = api.generate_html(deck) + text = (deck / "output.html").read_text(encoding="utf-8") + assert text.count(".card { font-size: 24px;") == 1 + assert re.search(r'

Second

more

', + } + deck = _deck(tmp_path, slides=slides) + assert api.html_slide_texts(deck) == [ + {"slug": "intro", "layout": "Title Slide", "title": "Hello world", "notes": "Say hi", + "text": "Hello world Body text"}, + {"slug": "plain", "layout": "Blank", "title": "Second", "notes": "", "text": "Second more"}, + ] + + +def test_html_deck_refs(tmp_path) -> None: + slides = { + "pic": '
', + "unlisted": None, + } + deck = _deck(tmp_path, slides=slides) + (deck / "slides" / "orphan.html").write_text( + '
', encoding="utf-8") + (deck / "deck.css").write_text(".x{background:url('images/bg.png')}", encoding="utf-8") + assert api.html_deck_refs(deck) == {"relative": {"images/a.png", "images/bg.png"}, + "assets": {"assets:aws/Arch_AWS-Lambda_48"}} diff --git a/tests/test_html_artifacts.py b/tests/test_html_artifacts.py new file mode 100644 index 000000000..4ecede6ce --- /dev/null +++ b/tests/test_html_artifacts.py @@ -0,0 +1,88 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +"""shared.html_artifacts — S3 key layout of HTML deck artifacts.""" + +import re + +import pytest + +from shared import html_artifacts as ha + + +def test_output_key_is_a_fresh_uuid_under_html_prefix(): + a, b = ha.output_key("d1"), ha.output_key("d1") + assert a != b + assert re.fullmatch(r"html/d1/[0-9a-f-]{36}\.html", a) + assert a.startswith(ha.HTML_PREFIX) + + +def test_preview_keys(): + assert ha.preview_prefix("d1") == "html/d1/preview/" + assert ha.preview_key("d1", "intro", 123) == "html/d1/preview/intro_123.html" + + +@pytest.mark.parametrize("deck_id", ["", "../x", "a/b", None]) +def test_invalid_deck_ids_are_rejected(deck_id): + with pytest.raises(ValueError): + ha.output_key(deck_id) + + +@pytest.mark.parametrize("slug", ["", "Intro", "../x", "a/b"]) +def test_invalid_slugs_are_rejected(slug): + with pytest.raises(ValueError): + ha.preview_key("d1", slug, 1) + + +def test_preview_key_map_latest_epoch_wins_and_ignores_other_keys(): + keys = [ + "html/d1/preview/intro_100.html", + "html/d1/preview/intro_200.html", + "html/d1/preview/demo-1_150.html", + "html/d1/preview/notes.txt", + "html/d1/0b6f3a52-1111-4222-8333-444455556666.html", + ] + assert ha.build_html_preview_key_map(keys) == { + "intro": "html/d1/preview/intro_200.html", + "demo-1": "html/d1/preview/demo-1_150.html", + } + + +def test_png_keys_and_latest_epoch_map(): + assert ha.png_prefix("d1") == "html/d1/png/" + assert ha.png_key("d1", "intro", 123) == "html/d1/png/intro_123.png" + assert ha.png_slug_epoch("html/d1/png/demo-1_7.png") == ("demo-1", 7) + assert ha.png_slug_epoch("html/d1/preview/intro_100.html") is None + keys = [ + "html/d1/png/intro_100.png", + "html/d1/png/intro_200.png", + "html/d1/png/demo-1_150.png", + "html/d1/preview/intro_300.html", + "html/d1/preview/cover_300.png", + "html/d1/png/notes.txt", + ] + assert ha.build_html_png_key_map(keys) == { + "intro": "html/d1/png/intro_200.png", + "demo-1": "html/d1/png/demo-1_150.png", + } + assert ha.build_html_preview_key_map(keys) == {"intro": "html/d1/preview/intro_300.html"} + with pytest.raises(ValueError): + ha.png_key("d1", "../x", 1) + + +def test_template_cache_object_key_allowlist(): + assert ha.template_cache_object_key("ab12", "theme.css") == "template-html-cache/ab12/theme.css" + assert ha.template_cache_object_key("ab12", "template.json") == "template-html-cache/ab12/template.json" + assert ha.template_cache_object_key("ab12", "layouts/01-Title_Slide.ground.svg") == ( + "template-html-cache/ab12/layouts/01-Title_Slide.ground.svg" + ) + for rel in ("other.json", "layouts/../x.svg", "layouts/a/b.svg", "layouts/.hidden.svg", + "layouts/a.png", "/theme.css", ".render-x/layouts/a.svg"): + with pytest.raises(ValueError): + ha.template_cache_object_key("ab12", rel) + for key in ("", "../x", "ABC", "ab/12"): + with pytest.raises(ValueError): + ha.template_cache_object_key(key, "theme.css") + + +def test_html_content_type(): + assert ha.HTML_CONTENT_TYPE == "text/html; charset=utf-8" diff --git a/tests/test_html_assemble.py b/tests/test_html_assemble.py new file mode 100644 index 000000000..c483fa0ab --- /dev/null +++ b/tests/test_html_assemble.py @@ -0,0 +1,663 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +"""Assembly of slides/.html into one offline reveal.js output.html.""" + +from __future__ import annotations + +import base64 +import dataclasses +import json +import re +from pathlib import Path + +import pytest +from lxml import html as lxml_html + +from sdpm import api +from sdpm.config import TEMPLATES_DIR, VENDOR_DIR +from sdpm.engine.html.assemble import assemble_deck, inline_js, letterbox_color, parse_slide, style_root_css +from sdpm.engine.html.template import load_template_html +from sdpm.knowledge.assets import assets_installed + +ICON = "assets:aws/Arch_AWS-Lambda_48" + +SLIDES = { + "cover": ( + '
\n' + '

HTML decks

\n' + '

Offline, one file

\n' + ' \n' + "
\n" + ), + "demo-1": ( + '
\n' + " \n" + '

Step one

\n' + '
A
\n' + "
\n" + ), + "demo-2": ( + '
\n' + '

Step two

\n' + '
A
\n' + '
  • first
  • second
\n' + "
\n" + ), +} + + +def _make_deck(tmp_path: Path, template: str = "blank-light", slides: dict[str, str] | None = None) -> Path: + deck = tmp_path / "deck" + api.init("t", output_dir=deck, output_format="html") + assert api.apply_style(deck, style="typographic", template=template)["status"] == "ok" + slides = SLIDES if slides is None else slides + outline = "# Assembly test\n\n" + "".join(f"- [{slug}] {slug}\n" for slug in slides) + (deck / "specs" / "outline.md").write_text(outline, encoding="utf-8") + for slug, text in slides.items(): + (deck / "slides" / f"{slug}.html").write_text(text, encoding="utf-8") + return deck + + +def _assemble(deck: Path, *, deck_css: str | None = None, slides: dict[str, str] | None = None, + template=None): + meta = json.loads((deck / "deck.json").read_text(encoding="utf-8")) + if template is None: + template = load_template_html(TEMPLATES_DIR / f"{meta['template']}.pptx", + cache_root=deck.parent / "template-cache") + slides = SLIDES if slides is None else slides + return assemble_deck( + slides=list(slides.items()), + template=template, + art_direction_html=(deck / "specs" / "art-direction.html").read_text(encoding="utf-8"), + default_background=meta.get("defaultBackground"), + default_text_color=meta.get("defaultTextColor"), + title="Assembly test", + deck_dir=deck, + deck_css=deck_css, + ) + + +@pytest.fixture +def built(tmp_path: Path): + deck = _make_deck(tmp_path) + result = _assemble(deck) + return deck, result, lxml_html.document_fromstring(result.html) + + +def _style_text(doc) -> str: + return "\n".join(el.text or "" for el in doc.iter("style")) + + +def test_sections_in_deck_order_with_slugs(built) -> None: + _, result, doc = built + sections = doc.xpath('//div[@class="slides"]/section') + assert [s.get("data-slug") for s in sections] == list(SLIDES) + assert [s.get("data-layout") for s in sections] == ["Title Slide", "Title Only", "Title Only"] + assert result.slugs == list(SLIDES) + assert result.layouts_used == ["Title Slide", "Title Only"] + assert result.bytes == len(result.html.encode("utf-8")) + + +def test_notes_fragments_and_auto_animate_preserved(built) -> None: + _, _, doc = built + notes = doc.xpath('//section[@data-slug="cover"]/aside[@class="notes"]') + assert [n.text for n in notes] == ["Welcome everyone."] + demo1, demo2 = (doc.xpath(f'//section[@data-slug="{s}"]')[0] for s in ("demo-1", "demo-2")) + assert demo1.get("data-auto-animate") is not None and demo2.get("data-auto-animate") is not None + assert demo1.xpath('.//*[@data-id="box"]') and demo2.xpath('.//*[@data-id="box"]') + assert len(demo2.xpath('.//li[@class="fragment"]')) == 2 + + +def test_vendored_code_carries_license_notices(built) -> None: + _, result, doc = built + vendor_css = doc.xpath("//head/style")[0].text + assert vendor_css.startswith("/*! reveal.js ") and "MIT License" in vendor_css.splitlines()[0] + notes = [s.text for s in doc.xpath("//body/script") if "RevealNotes" in (s.text or "") + and "Reveal.initialize" not in s.text][0] + head = notes.splitlines()[:2] + assert head[0].startswith("/*! reveal.js ") and head[1].startswith("/*! Includes marked | MIT License") + + +def test_reveal_initialize_config(built) -> None: + _, result, _ = built + config = re.search(r"var o=\{(.*?)\};", result.html).group(1) + for part in ("width:1920", "height:1080", "center:false", "hash:true", "RevealNotes"): + assert part in config + assert "Reveal.initialize(o);" in result.html + + +_DECORATION_RULE = r'section\[data-layout="([^"]+)"\]\{background-image:url\("data:image/svg\+xml;base64,' + + +def test_template_without_decorations_adds_no_background_image(built) -> None: + _, _, doc = built + deck_rules = doc.xpath('//style[@id="sdpm-deck"]')[0].text + assert re.findall(_DECORATION_RULE, deck_rules) == [] + + +def test_one_decoration_background_per_used_layout(tmp_path: Path) -> None: + deck = _make_deck(tmp_path) + plain = load_template_html(TEMPLATES_DIR / "blank-light.pptx", cache_root=tmp_path / "template-cache") + svgs = {} + for name in ("Title Slide", "Title Only", "Blank"): # Blank is not used by SLIDES + svg = tmp_path / f"{name}.svg" + svg.write_text('', + encoding="utf-8") + svgs[name] = svg + result = _assemble(deck, template=dataclasses.replace(plain, svg_paths=svgs)) + doc = lxml_html.document_fromstring(result.html) + deck_rules = doc.xpath('//style[@id="sdpm-deck"]')[0].text + assert re.findall(_DECORATION_RULE, deck_rules) == ["Title Slide", "Title Only"] + assert result.html.count('section[data-layout="Title Only"]{background-image') == 1 + + +def test_regions_and_chrome_are_absolutely_positioned(built) -> None: + _, _, doc = built + deck_rules = doc.xpath('//style[@id="sdpm-deck"]')[0].text + assert "[data-sdpm-chrome],[data-region]{position:absolute}" in deck_rules + + +def test_section_box_also_applies_in_the_print_view(built) -> None: + # reveal.js's print view (#print-pdf) moves each section into div.pdf-page; without the + # second selector the section collapses to 1px and its gradient / picture ground is lost. + _, _, doc = built + deck_rules = doc.xpath('//style[@id="sdpm-deck"]')[0].text + box = re.search(r"^([^{]*)\{width:var\(--sdpm-canvas-w\);height:var\(--sdpm-canvas-h\);", + deck_rules, re.MULTILINE) + assert box and [s.strip() for s in box.group(1).split(",")] == [ + ".reveal .slides > section", ".reveal .slides > .pdf-page > section"] + assert "background-size:100% 100%" in deck_rules[box.start():deck_rules.index("}", box.start())] + + +def test_external_links_open_in_a_new_tab(tmp_path: Path) -> None: + slides = {"links": ( + '
\n' + '

Links

\n' + '
a\n' + ' b\n' + ' c\n' + ' d\n' + ' next\n' + ' mail\n' + "
\n" + )} + deck = _make_deck(tmp_path, slides=slides) + result = _assemble(deck, slides=slides) + for document in (result.html, result.previews["links"]): + doc = lxml_html.document_fromstring(document) + link = {a.get("id"): a for a in doc.iter("a")} + assert (link["plain"].get("target"), link["plain"].get("rel")) == ("_blank", "noopener noreferrer") + assert (link["upper"].get("target"), link["upper"].get("rel")) == ("_blank", "noopener noreferrer") + assert (link["self"].get("target"), link["self"].get("rel")) == ("_blank", "nofollow noopener noreferrer") + assert (link["named"].get("target"), link["named"].get("rel")) == ("docs", "noopener noreferrer") + for kept in ("deck", "mail"): + assert link[kept].get("target") is None and link[kept].get("rel") is None + + +def test_no_external_resource_reference(built) -> None: + _, result, doc = built + for el in doc.iter(): + if not isinstance(el.tag, str): + continue + for name in ("src", "href", "srcset", "poster", "data", "xlink:href"): + value = el.get(name) + if value is None or (name == "href" and el.tag == "a"): + continue + assert value.startswith(("data:", "#")), (el.tag, name, value[:80]) + css = _style_text(doc) + assert "@import" not in css + for url in re.findall(r"url\(\s*['\"]?([^'\")]*)", css): + assert url.startswith(("data:", "#")), url[:80] + scripts = list(doc.iter("script")) + assert len(scripts) == 3 and all(s.get("src") is None for s in scripts) + # Only the closing tags of the three inline scripts. + assert len(re.findall(r" None: + _, result, _ = built + head = (VENDOR_DIR / "revealjs" / "reveal.css").read_text(encoding="utf-8")[:200] + assert head.replace(" None: + _, _, doc = built + slide_css = doc.xpath('//style[@id="sdpm-slides"]')[0].text + assert re.search(r'section\[data-slug="demo-1"\]\{\s*\.box \{ color: var\(--accent\); \}\s*\}', slide_css) + assert not doc.xpath('//section//style') + + +def test_ground_comes_from_style_color_bg(built) -> None: + deck, result, _ = built + meta = json.loads((deck / "deck.json").read_text(encoding="utf-8")) + assert meta["defaultBackground"] + assert f":root{{--sdpm-ground:{meta['defaultBackground']}}}" in result.html + assert f"color:{meta['defaultTextColor']}" in result.html + + +def _section_backgrounds(result) -> dict[str, str | None]: + doc = lxml_html.document_fromstring(result.html) + return {s.get("data-slug"): s.get("data-background-color") + for s in doc.xpath('//div[@class="slides"]/section')} + + +def test_letterbox_is_the_style_ground_when_set(built) -> None: + deck, result, _ = built + ground = json.loads((deck / "deck.json").read_text(encoding="utf-8"))["defaultBackground"] + assert set(_section_backgrounds(result).values()) == {ground} + + +def test_letterbox_is_each_layouts_solid_ground(tmp_path: Path) -> None: + deck = _make_deck(tmp_path, template="blank-dark") + slides = {"cover": '
', + "blank": '
', + "unknown": '
'} + template = load_template_html(TEMPLATES_DIR / "blank-dark.pptx", cache_root=tmp_path / "template-cache") + result = assemble_deck( + slides=list(slides.items()), template=template, art_direction_html="", + default_background=None, default_text_color=None, title="t", deck_dir=deck) + # blank-dark: black master, its "Blank" layout has its own #0A1628 ground. + assert _section_backgrounds(result) == {"cover": "#000000", "blank": "#0A1628", "unknown": "#000000"} + + +def test_letterbox_of_a_gradient_ground_is_the_theme_background(tmp_path: Path, decorated_template: Path) -> None: + template = load_template_html(decorated_template, decorations=False, cache_root=tmp_path / "template-cache") + layouts = {layout["name"]: layout for layout in template.info["layouts"]} + assert layouts["Section Header"]["ground"] == {"kind": "baked"} + template.info["themeColors"]["background"] = "#ABCDEF" + assert letterbox_color(layouts["Section Header"], template, None) == "#ABCDEF" + assert letterbox_color(layouts["Section Header"], template, "#123456") == "#123456" + + +def test_letterbox_color_is_engine_only(built) -> None: + _, result, _ = built + assert all(_section_backgrounds(result).values()) + for text in result.previews.values(): + assert "data-background-color=" not in text + config = re.search(r"var o=\{(.*?)\};", result.html).group(1) + assert "margin:0," in config + + +def test_style_root_embedded_before_theme(built) -> None: + deck, result, doc = built + root = style_root_css((deck / "specs" / "art-direction.html").read_text(encoding="utf-8")) + assert root.startswith(":root{") and "--fs-" in root + ids = [s.get("id") for s in doc.iter("style") if s.get("id")] + assert ids == ["sdpm-style-root", "sdpm-theme", "sdpm-deck", "sdpm-slides"] + assert doc.xpath('//style[@id="sdpm-style-root"]')[0].text == root + + +def test_slide_number_chrome_drawn_by_assembler(built) -> None: + _, _, doc = built + numbers = [el.text_content() for el in doc.xpath('//*[@data-sdpm-chrome="slide-number"]')] + assert numbers == ["1", "2", "3"] + + +def test_deck_css_embedded_once_unscoped(tmp_path: Path) -> None: + deck = _make_deck(tmp_path) + css = ".card-shared { border: 2px solid var(--color-border); }" + result = _assemble(deck, deck_css=css) + doc = lxml_html.document_fromstring(result.html) + assert result.html.count(css) == 1 + assert doc.xpath('//style[@id="sdpm-deck-css"]')[0].text == css + ids = [s.get("id") for s in doc.iter("style") if s.get("id")] + assert ids.index("sdpm-deck-css") == ids.index("sdpm-deck") + 1 == ids.index("sdpm-slides") - 1 + + +def test_deck_relative_image_and_css_url_become_data_uris(tmp_path: Path) -> None: + deck = _make_deck(tmp_path) + (deck / "images").mkdir() + png = base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==") + (deck / "images" / "dot.png").write_bytes(png) + slides = {"pic": ( + '
' + 'dot
' + '
')} + result = _assemble(deck, slides=slides, deck_css=".x{background:url(images/dot.png)}") + assert result.html.count("data:image/png;base64,") == 4 + assert any("images/missing.png" in w for w in result.warnings) + assert any("outside the deck" in w for w in result.warnings) + + +@pytest.mark.skipif(not assets_installed(), reason="asset catalogs not installed") +def test_svg_icon_is_inlined_with_prefixed_ids(tmp_path: Path) -> None: + deck = _make_deck(tmp_path) + slides = {"icons": ( + f'
LambdaLambda again
')} + result = _assemble(deck, slides=slides) + assert not result.warnings + doc = lxml_html.document_fromstring(result.html) + svgs = doc.xpath('//section[@data-slug="icons"]/svg') + assert len(svgs) == 2 and not doc.xpath('//section//img') + assert svgs[0].get("aria-label") == "Lambda" and svgs[0].get("class") == "fragment" + ids = [el.get("id") for svg in svgs for el in svg.iter() if isinstance(el.tag, str) and el.get("id")] + assert ids and len(ids) == len(set(ids)) + assert all(i.startswith(("s1i1-", "s1i2-")) for i in ids) + + +def test_unparseable_slide_is_skipped_with_warning(tmp_path: Path) -> None: + deck = _make_deck(tmp_path) + slides = {"ok": SLIDES["cover"], "bad": "
no section
"} + result = _assemble(deck, slides=slides) + assert result.slugs == ["ok"] + assert any(w.startswith("bad: slide skipped") for w in result.warnings) + + +def test_parse_slide_reports_structure() -> None: + parsed = parse_slide(SLIDES["cover"]) + assert parsed.errors == [] and parsed.layout == "Title Slide" and parsed.has_notes + assert parse_slide("
").errors[0].startswith("expected exactly one") + assert parse_slide("").section is None + + +def test_nested_section_slide_is_skipped(tmp_path: Path) -> None: + deck = _make_deck(tmp_path) + slides = {"ok": SLIDES["cover"], + "stack": '
inner
'} + result = _assemble(deck, slides=slides) + assert result.slugs == ["ok"] + assert any(w.startswith("stack: slide skipped") and "nested
" in w for w in result.warnings) + + +def test_non_nestable_at_rules_are_hoisted_and_keyframes_renamed(tmp_path: Path) -> None: + deck = _make_deck(tmp_path) + slides = {"anim": ( + '
" + '
x
')} + result = _assemble(deck, slides=slides) + doc = lxml_html.document_fromstring(result.html) + css = doc.xpath('//style[@id="sdpm-slides"]')[0].text + wrapper = css.index('section[data-slug="anim"]{') + assert css.index("@keyframes sdpm-anim-pulse {") < wrapper + assert css.index("@font-face { font-family: Demo;") < wrapper + assert "@keyframes pulse" not in css + assert ".dot { animation: sdpm-anim-pulse 1s infinite; }" in css[wrapper:] + assert "@media (prefers-reduced-motion) { .dot { animation-name: none } }" in css[wrapper:] + assert ".ring { animation-name: sdpm-anim-pulse, fade; }" in css + assert doc.xpath('//div[@class="dot"]')[0].get("style") == "animation:sdpm-anim-pulse 2s" + + +def test_leading_at_keyword_skips_comments_without_backtracking() -> None: + from sdpm.engine.html.assemble import _leading_at_keyword + + m = _leading_at_keyword(" /* a */\n/* b */ @keyframes pulse {}") + assert m is not None and m.group(1) == "keyframes" + assert _leading_at_keyword(".dot { color: red }") is None + assert _leading_at_keyword("/* unterminated @keyframes x {}") is None + # CodeQL py/redos input for the former regex: "/*" plus many "*//*" and no "@". + assert _leading_at_keyword("/*" + "*//*" * 50_000) is None + + +def test_srcset_object_and_svg_image_refs_are_embedded(tmp_path: Path) -> None: + deck = _make_deck(tmp_path) + (deck / "images").mkdir() + png = base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==") + (deck / "images" / "dot.png").write_bytes(png) + slides = {"refs": ( + '
' + '' + '' + '' + '
')} + result = _assemble(deck, slides=slides) + assert not result.warnings + doc = lxml_html.document_fromstring(result.html) + section = doc.xpath('//section[@data-slug="refs"]')[0] + uri = "data:image/png;base64," + base64.b64encode(png).decode("ascii") + assert section.xpath(".//img")[0].get("srcset") == f"{uri} 1x, data:image/png;base64,AA,BB 2x" + assert section.xpath(".//object")[0].get("data") == uri + images = section.xpath(".//image") + assert images[0].get("href") == uri and images[1].get("xlink:href") == uri + assert section.xpath(".//div")[0].get("style").count(uri) == 2 + assert "images/" not in lxml_html.tostring(section, encoding="unicode") + + +def test_linked_stylesheet_is_not_embedded(tmp_path: Path) -> None: + deck = _make_deck(tmp_path) + (deck / "images").mkdir() + (deck / "images" / "extra.css").write_text(".extra{color:red}", encoding="utf-8") + slides = {"css": '
'} + result = _assemble(deck, slides=slides) + doc = lxml_html.document_fromstring(result.html) + assert doc.xpath('//section[@data-slug="css"]//link')[0].get("href") == "images/extra.css" + assert ".extra{color:red}" not in result.html and "data:text/css" not in result.html + + +def test_deck_svg_is_embedded_as_an_inert_image(tmp_path: Path) -> None: + deck = _make_deck(tmp_path) + (deck / "images").mkdir() + svg = ('' + '') + (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_browser.py b/tests/test_remote_browser.py new file mode 100644 index 000000000..303f2c076 --- /dev/null +++ b/tests/test_remote_browser.py @@ -0,0 +1,134 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +"""Remote MCP server: AgentCore Browser as the browser of the HTML browser check.""" + +from __future__ import annotations + +import importlib.util +import logging +import os +from pathlib import Path +from unittest.mock import MagicMock, patch + +import pytest +from botocore.credentials import Credentials + +from sdpm.engine.html import browser as browser_mod +from sdpm.engine.html.browser_check import check_deck +from tools import agentcore_browser + +_ROOT = Path(__file__).resolve().parents[1] +_STREAM = "wss://bedrock-agentcore.ap-northeast-1.amazonaws.com/browser-streams/aws.browser.v1/sessions/s1/automation" + +os.environ.setdefault("DECKS_TABLE", "test-table") +os.environ.setdefault("PPTX_BUCKET", "test-pptx") +os.environ.setdefault("RESOURCE_BUCKET", "test-resource") + + +class StubClient: + def __init__(self, start_error: Exception | None = None, stop_error: Exception | None = None): + self.started: list[dict] = [] + self.stopped: list[dict] = [] + self.start_error = start_error + self.stop_error = stop_error + + def start_browser_session(self, **kwargs): + self.started.append(kwargs) + if self.start_error: + raise self.start_error + return {"sessionId": "s1", "streams": {"automationStream": {"streamEndpoint": _STREAM}}} + + def stop_browser_session(self, **kwargs): + self.stopped.append(kwargs) + if self.stop_error: + raise self.stop_error + + +def _source(client: StubClient, calls: list | None = None): + def factory(): + if calls is not None: + calls.append(1) + return client + + return agentcore_browser.make_source( + "ap-northeast-1", client_factory=factory, + credentials_factory=lambda: Credentials("AKIDEXAMPLE", "secret", "session-token"), + ) + + +def test_session_starts_with_the_deck_viewport_and_signs_the_stream(): + client = StubClient() + with _source(client)(1920, 1080) as endpoint: + assert client.stopped == [] + assert endpoint.url == _STREAM and endpoint.name == "AgentCore Browser" + assert set(endpoint.headers) == {"Authorization", "X-Amz-Date", "X-Amz-Security-Token"} + assert endpoint.headers["Authorization"].startswith("AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/") + assert "/ap-northeast-1/bedrock-agentcore/aws4_request" in endpoint.headers["Authorization"] + assert endpoint.headers["X-Amz-Security-Token"] == "session-token" + assert client.started == [{ + "browserIdentifier": "aws.browser.v1", "name": "sdpm-check", "sessionTimeoutSeconds": 120, + "viewPort": {"width": 1920, "height": 1080}, + }] + assert client.stopped == [{"browserIdentifier": "aws.browser.v1", "sessionId": "s1"}] + + +def test_session_is_stopped_when_the_check_raises(): + client = StubClient() + with pytest.raises(RuntimeError, match="boom"): + with _source(client)(1280, 720): + raise RuntimeError("boom") + assert client.stopped == [{"browserIdentifier": "aws.browser.v1", "sessionId": "s1"}] + + +def test_failing_stop_is_logged_not_raised(caplog): + client = StubClient(stop_error=RuntimeError("throttled")) + with caplog.at_level(logging.WARNING, logger="sdpm.agentcore_browser"): + with _source(client)(1920, 1080): + pass + assert "stop_browser_session failed for s1" in caplog.text + + +def test_client_is_created_on_first_use_only(): + calls: list = [] + source = _source(StubClient(), calls) + assert calls == [] and source.browser_name == "AgentCore Browser" + for _ in range(2): + with source(1920, 1080): + pass + assert calls == [1] + + +def test_failing_start_is_a_failed_check(tmp_path, monkeypatch): + monkeypatch.delenv("SDPM_BROWSER") + client = StubClient(start_error=RuntimeError("AccessDeniedException")) + browser_mod.register_browser_source(_source(client)) + html = tmp_path / "output.html" + html.write_text("", encoding="utf-8") + + result = check_deck(html, ["cover"], slide_size=(1920, 1080), line_map=[], layouts={}, decorations={}) + + assert result["status"] == "failed" and result["browser"] == "AgentCore Browser" + assert result["note"].startswith( + "Browser check could not run (AgentCore Browser): RuntimeError: AccessDeniedException" + ) + assert client.stopped == [] # nothing was started + + +def _import_server(name: str): + spec = importlib.util.spec_from_file_location(name, _ROOT / "servers" / "remote" / "server.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_importing_the_server_creates_no_boto3_client_and_registers_agentcore(): + boom = MagicMock(side_effect=AssertionError("boto3 used at import")) + with patch("boto3.client", boom), patch("boto3.resource", boom), patch("boto3.Session", boom): + server = _import_server("remote_server_browser_under_test") + boom.assert_not_called() + source = browser_mod.registered_browser_source() + assert source is not None and source.browser_name == "AgentCore Browser" + + browser_mod.register_browser_source(None) + server._register_browser_source() + assert browser_mod.registered_browser_source().browser_name == "AgentCore Browser" diff --git a/tests/test_remote_html.py b/tests/test_remote_html.py new file mode 100644 index 000000000..7a16c373e --- /dev/null +++ b/tests/test_remote_html.py @@ -0,0 +1,908 @@ +# 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 sdpm.engine.html import browser_check +from sdpm.engine.html.browser import DISABLED_NOTE +from sdpm.engine.html.check import CHECK_REPORT_HEADER +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_returns_format_notes_for_html_only(): + from sdpm.entry import format_notes + + _, html = _init("html") + assert html["format_notes"] == format_notes("html") and html["format_notes"] + for fmt in (None, "pptx"): + _, result = _init(fmt) + assert "format_notes" not in result + + +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_drops_previews_of_slides_not_in_the_build(server, storage, monkeypatch): + """A slide output.html leaves out keeps no preview, so thumbnail and player indexes agree.""" + _no_pptx(monkeypatch) + old_cover, gone = "html/d1/preview/cover_100.html", "html/d1/preview/gone_100.html" + storage.objects.update({old_cover: b"x", gone: b"x", "html/d1/preview/body_100.html": b"x"}) + _sandbox(monkeypatch, ["slides/body.html"]) + + out = _run(server) + + assert "html_error" not in out, out + assert gone in storage.deleted + assert old_cover not in storage.deleted + + +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(CHECK_REPORT_HEADER) + # SDPM_BROWSER=none (conftest): the core's unavailable preview passes through. + assert out["preview"] == {"status": "unavailable", "reason": "browser-skipped", "note": DISABLED_NOTE} + assert out["png_previews"] == [] and "preview_files" not in out + + +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) + _fake_check(monkeypatch) # the check writes PNGs, which must go with the previews + _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 + assert storage.preview_keys() == [] # so were this run's previews and PNGs + assert not any(k.startswith("html/d1/png/") for k in storage.objects) + + +def test_run_python_html_single_preview_upload_failure_publishes_nothing(server, storage, monkeypatch): + _no_pptx(monkeypatch) + storage.record["htmlS3Key"] = "html/d1/old.html" + storage.objects["html/d1/old.html"] = b"old" + 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) + _sandbox(monkeypatch, ["deck.css"]) + + out = _run(server) + + assert "body" in out["html_error"] and "stale" in out["html_error"] + assert not {"html", "previews", "png_previews"} & set(out) + assert storage.record["htmlS3Key"] == "html/d1/old.html" and storage.html_keys() == [] + assert storage.preview_keys() == [] + + +def test_run_python_html_same_clock_writes_get_new_keys(server, storage, monkeypatch): + _no_pptx(monkeypatch) + monkeypatch.setattr(html_deck.time, "time_ns", lambda: 1_800_000_000_000 * 1_000_000) + _sandbox(monkeypatch, ["slides/cover.html"]) + + first = _run(server)["previews"]["cover"] + second = _run(server)["previews"]["cover"] + + assert int(_PREVIEW_KEY.match(second).group(2)) > int(_PREVIEW_KEY.match(first).group(2)) + assert first in storage.deleted and first not in storage.objects + + +def test_run_python_html_revision_beats_older_second_epochs(server, storage, monkeypatch): + from shared.html_artifacts import build_html_preview_key_map + + _no_pptx(monkeypatch) + old = "html/d1/preview/cover_1793374283.html" + storage.objects[old] = b"x" + _sandbox(monkeypatch, ["slides/cover.html"]) + + out = _run(server) + + assert build_html_preview_key_map([old, out["previews"]["cover"]])["cover"] == out["previews"]["cover"] + + +def test_run_python_html_unresolved_template_says_how_to_fix(server, storage, monkeypatch): + _no_pptx(monkeypatch) + deck_json = storage.get_deck_json("d1") + deck_json["template"] = "none" + storage.put_deck_json("d1", deck_json) + _sandbox(monkeypatch, ["slides/cover.html"]) + + out = _run(server) + + assert "'none'" in out["html_error"] and "apply_style" in out["html_error"], out + assert storage.html_keys() == [] and storage.preview_keys() == [] + + +def test_js_deck_reports_the_skipped_browser_check(server, storage, tmp_path, monkeypatch): + """With SDPM_BROWSER=none (conftest), run_python of a deck carries the one-line skip + note among the warnings the agent reads; generate_pptx (finalize) checks nothing.""" + _no_pptx(monkeypatch) + body = SLIDES["body"].replace("
", "") + _seed_html_deck(storage, tmp_path / "js", {"cover": SLIDES["cover"], "body": body}) + _sandbox(monkeypatch, ["slides/body.html"]) + note = f"output.html: {DISABLED_NOTE}" + + out = _run(server) + assert note in out["warnings"], out + assert out["browser_check"] == {"status": "skipped", "slides": 0, "note": DISABLED_NOTE} + assert note in _run(server, measure=["cover"])["warnings"] + result = json.loads(server.generate_pptx(deck_id="d1")) + assert note not in (result.get("warnings") or {}).get("build", []), result + + +def test_unreachable_agentcore_browser_is_one_warning_line(server, storage, monkeypatch): + """AgentCore Browser that cannot be started: run_python says so in one line, never clean.""" + from tools import agentcore_browser + from sdpm.engine.html import browser as browser_mod + + class DeniedClient: + def start_browser_session(self, **_kw): + raise RuntimeError("AccessDeniedException: not authorized") + + def stop_browser_session(self, **_kw): # pragma: no cover - nothing started + pytest.fail("stopped a session that never started") + + _no_pptx(monkeypatch) + monkeypatch.delenv("SDPM_BROWSER") + monkeypatch.setattr(browser_mod, "_registered", agentcore_browser.make_source( + "ap-northeast-1", client_factory=DeniedClient)) + _sandbox(monkeypatch, ["slides/body.html"]) + + out = _run(server) + + lines = [w for w in out["warnings"] if w.startswith("output.html: Browser check")] + assert lines == [lines[0]] and "\n" not in lines[0], out["warnings"] + assert lines[0].startswith("output.html: Browser check could not run (AgentCore Browser): RuntimeError: " + "AccessDeniedException") + assert out["browser_check"]["status"] == "failed" and out["png_previews"] == [] + + +# --- browser check PNGs ----------------------------------------------------------- + +_PNG_KEY = re.compile(r"^html/d1/png/([a-z0-9-]+)_(\d+)\.png$") + + +def _png_bytes(size=(1280, 720)) -> bytes: + import io + + from PIL import Image as PILImage + + buf = io.BytesIO() + PILImage.new("RGB", size, (30, 60, 90)).save(buf, format="PNG") + return buf.getvalue() + + +def _fake_check(monkeypatch, *, no_png: frozenset = frozenset(), seen: list | None = None): + """check_deck stand-in: a PNG per checked slug (except ``no_png``), status ok.""" + + def fake(output_html, slugs, *, slide_size, line_map, layouts, decorations, png_dir=None, deadline=None): + if seen is not None: + seen.append(list(slugs)) + pngs = {} + for slug in slugs: + if slug in no_png or png_dir is None: + continue + Path(png_dir).mkdir(parents=True, exist_ok=True) + path = Path(png_dir) / f"{slug}.png" + path.write_bytes(_png_bytes()) + pngs[slug] = str(path) + status = "timeout" if no_png else "ok" + result = {"status": status, "browser": "AgentCore Browser", "seconds": 1.5, "slides": len(pngs), + "checked": list(pngs), "findings": {}, "errors": [], "pngs": pngs, + "timings": {"acquire": 0.9, "connect": 0.1, "load": 0.2, "slides": 0.3, "release": 0.1}, + "network_blocked": True, "blocked_requests": 0} + if no_png: + result["note"] = "Browser check did not finish within 33 s; …" + return result + + monkeypatch.setattr(browser_check, "check_deck", fake) + + +def _png_keys(storage) -> list[str]: + return sorted(k for k in storage.objects if _PNG_KEY.match(k)) + + +def test_run_python_html_uploads_pngs_of_checked_slides(server, storage, monkeypatch, caplog): + import logging + + _no_pptx(monkeypatch) + _fake_check(monkeypatch) + old = {"html/d1/png/body_100.png", "html/d1/png/cover_100.png", "html/d1/png/other_100.png", + "html/d1/png/broken_100.png"} + storage.objects.update({k: b"x" for k in old}) + storage.objects["decks/d1/slides/broken.html"] = b"

no section

" + _sandbox(monkeypatch, ["slides/body.html"]) + + with caplog.at_level(logging.INFO, logger="sdpm.html_deck"): + out = _run(server) + + assert "html_error" not in out, out + assert out["png_previews"] == ["body"] and "preview_files" not in out + [fresh] = [k for k in _png_keys(storage) if k not in old] + assert _PNG_KEY.match(fresh).group(1) == "body" and storage.content_types[fresh] == "image/png" + # The superseded body PNG and the PNG of a slide in this snapshot that did not build go; + # cover was not checked, and "other" is not in this snapshot (a parallel composer may + # have just written it), so both stay. + assert "html/d1/png/body_100.png" in storage.deleted and "html/d1/png/broken_100.png" in storage.deleted + assert "html/d1/png/cover_100.png" in storage.objects and "html/d1/png/other_100.png" in storage.objects + assert out["browser_check"] == {"status": "ok", "browser": "AgentCore Browser", "seconds": 1.5, "slides": 1} + [line] = [json.loads(r.getMessage()) for r in caplog.records + if r.getMessage().startswith('{"kind": "html_browser_check"')] + assert line["deck_id"] == "d1" and line["user_id"] == "user1" and line["status"] == "ok" + assert line["slides"] == 1 and line["seconds"] == 1.5 and line["bytes"] > 0 + assert line["timings"]["acquire"] == 0.9 and line["network_blocked"] is True + assert line["blocked_requests"] == 0 + + +def test_run_python_html_checked_slide_without_png_loses_its_old_png(server, storage, monkeypatch): + """A check that did not finish leaves no stale PNG for get_preview to show.""" + _no_pptx(monkeypatch) + _fake_check(monkeypatch, no_png=frozenset({"body"})) + storage.objects.update({"html/d1/png/body_100.png": b"x", "html/d1/png/cover_100.png": b"x"}) + _sandbox(monkeypatch, []) + + out = _run(server, measure=["body"]) + + assert out["png_previews"] == [] + assert out["browser_check"]["status"] == "timeout" + assert out["preview"]["reason"] == "browser-timeout" + assert "html/d1/png/body_100.png" in storage.deleted + assert "html/d1/png/cover_100.png" in storage.objects + + +def test_get_preview_html_deck_returns_pngs(server, storage, monkeypatch): + from mcp.server.fastmcp.utilities.types import Image + + _no_pptx(monkeypatch) + _fake_check(monkeypatch) + _sandbox(monkeypatch, []) + _run(server, measure=["cover"]) + + out = server.get_preview(deck_id="d1", slugs=["cover", "body"], quality="low") + + assert out[0] == "Slide cover" and isinstance(out[1], Image) + assert out[2] == 'No PNG for body yet: run run_python with measure_slides=["body"]' + assert len(out) == 3 + + +def test_get_preview_html_deck_png_gone_before_download(server, storage, monkeypatch): + """A PNG superseded between the listing and the download gets the text line, not an error.""" + storage.objects["html/d1/png/cover_100.png"] = _png_bytes() + listed = storage.list_files + monkeypatch.setattr(storage, "list_files", lambda prefix, bucket="": ( + listed(prefix, bucket), storage.objects.pop("html/d1/png/cover_100.png", None))[0]) + out = server.get_preview(deck_id="d1", slugs=["cover"]) + assert out == ['No PNG for cover yet: run run_python with measure_slides=["cover"]'] + + +def test_get_preview_html_deck_latest_png_wins(server, storage): + from mcp.server.fastmcp.utilities.types import Image + + storage.objects["html/d1/png/cover_100.png"] = b"not a png" + storage.objects["html/d1/png/cover_200.png"] = _png_bytes() + out = server.get_preview(deck_id="d1", slugs=["cover"]) + assert out[0] == "Slide cover" and isinstance(out[1], Image) + + +def test_generate_pptx_runs_no_check_and_drops_pngs_of_removed_slides(server, storage, monkeypatch): + seen: list = [] + _fake_check(monkeypatch, seen=seen) + storage.objects.update({"html/d1/png/cover_1.png": b"x", "html/d1/png/gone_1.png": b"x"}) + + result = json.loads(server.generate_pptx(deck_id="d1")) + + assert result["status"] == "completed", result + assert seen == [] + assert "html/d1/png/gone_1.png" in storage.deleted + assert "html/d1/png/cover_1.png" in storage.objects + + +# --- 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) + + +_NAV_BODY = ('

Claim

' + '
') + + +def test_run_python_html_records_script_external_and_a_clean_rebuild_removes_it(server, storage, monkeypatch): + _no_pptx(monkeypatch) + _sandbox(monkeypatch, ["slides/body.html"]) + storage.objects["decks/d1/slides/body.html"] = _NAV_BODY.encode() + + out = _run(server) + + assert "html_error" not in out, out + assert storage.record["htmlScriptExternal"] == [{"slug": "body", "kinds": ["popup", "external-url"]}] + assert "script_external" not in out # the record's data; the warnings tell the agent + + storage.objects["decks/d1/slides/body.html"] = SLIDES["body"].encode() + assert "html_error" not in _run(server) + assert "htmlScriptExternal" not in storage.record + assert storage.updates[-1]["htmlScriptExternal"] is None + + +def test_generate_pptx_records_script_external(server, storage): + storage.objects["decks/d1/slides/body.html"] = _NAV_BODY.encode() + result = json.loads(server.generate_pptx(deck_id="d1")) + assert result["status"] == "completed" + assert storage.record["htmlScriptExternal"] == [{"slug": "body", "kinds": ["popup", "external-url"]}] + + storage.objects["decks/d1/slides/body.html"] = SLIDES["body"].encode() + json.loads(server.generate_pptx(deck_id="d1")) + assert "htmlScriptExternal" not in storage.record + + +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_record_failure_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}) + storage.record["htmlS3Key"] = "html/d1/old.html" + storage.objects["html/d1/old.html"] = b"old" + monkeypatch.setattr(storage, "update_deck", MagicMock(side_effect=RuntimeError("DynamoDB down"))) + + result = json.loads(server.generate_pptx(deck_id="d1")) + + assert "DynamoDB down" in result["error"] + assert storage.preview_keys() == sorted(previous) # the older set stays the latest + assert storage.html_keys() == [] and storage.record["htmlS3Key"] == "html/d1/old.html" + + +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" + + +def _misspell_output_format(storage): + deck_json = storage.get_deck_json("d1") + deck_json["outputFormat"] = "htlm" + storage.put_deck_json("d1", deck_json) + + +def test_run_python_invalid_output_format_stops_the_build(server, storage, monkeypatch): + _misspell_output_format(storage) + _no_pptx(monkeypatch) + _sandbox(monkeypatch, ["slides/cover.html"]) + out = _run(server) + assert "htlm" in out["errors"]["outputFormat"] + assert storage.html_keys() == [] + + +def test_generate_pptx_invalid_output_format_returns_error(server, storage, monkeypatch): + _misspell_output_format(storage) + called = [] + monkeypatch.setattr(remote_server.generate, "generate_pptx", lambda **kw: called.append(kw)) + result = json.loads(server.generate_pptx(deck_id="d1")) + assert "outputFormat" in result["error"] + assert called == [] + + +def test_get_preview_invalid_output_format_returns_error(server, storage): + _misspell_output_format(storage) + [item] = server.get_preview(deck_id="d1", slugs=["cover"]) + assert item["type"] == "text" and "outputFormat" in item["text"] + + +@pytest.mark.parametrize("payload", [[], "deck", 3]) +def test_deck_format_treats_a_non_object_deck_json_as_pptx(server, storage, monkeypatch, payload): + monkeypatch.setattr(storage, "get_deck_json", lambda deck_id: payload) + assert remote_server._deck_format("d1") == "pptx" + + +# --- get_preview --------------------------------------------------------------- + + +def test_get_preview_html_deck_without_pngs_says_how_to_make_them(server): + assert server.get_preview(deck_id="d1", slugs=["cover"]) == [ + 'No PNG for cover yet: run run_python with measure_slides=["cover"]' + ] + + +# --- 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) + + +def test_runtime_image_pins_websockets(): + """The browser check's only new dependency is pinned for the runtime image, and the + image no longer turns the check off (AgentCore Browser runs it).""" + constraints = (_ROOT / "servers" / "remote" / "constraints.txt").read_text(encoding="utf-8") + assert re.search(r"^websockets==\d+", constraints, flags=re.MULTILINE) + dockerfile = (_ROOT / "servers" / "remote" / "Dockerfile").read_text(encoding="utf-8") + # Neither the new switch (SDPM_BROWSER) nor the removed phase-3 one may be set. + assert not re.search(r"^ENV\s+SDPM_(BROWSER|JS_CHECK)\b", dockerfile, flags=re.MULTILINE) + + +def test_runtime_image_ships_vendored_libraries(): + """Every vendored file the HTML engine inlines (reveal.js, ECharts, D3 and their + license files) exists and no .dockerignore entry keeps it out of the image.""" + import fnmatch + + from sdpm.engine.html.slide_js import LIBRARIES + + files = [path for paths in LIBRARIES.values() for path in paths] + files += ["revealjs/reveal.js", "revealjs/reveal.css", "revealjs/reset.css", + "revealjs/plugin/notes.js", "revealjs/LICENSE", "revealjs/VERSION", + "echarts/VERSION", "d3/VERSION"] + entries = [line.strip().rstrip("/") for line in + (_ROOT / ".dockerignore").read_text(encoding="utf-8").splitlines() + if line.strip() and not line.lstrip().startswith("#")] + for name in files: + rel = f"sdpm/vendor/{name}" + assert (_ROOT / rel).is_file(), rel + parts = rel.split("/") + candidates = ["/".join(parts[:i]) for i in range(1, len(parts) + 1)] + for entry in entries: + matched = [c for c in candidates if fnmatch.fnmatch(c, entry)] + assert not matched, f".dockerignore entry {entry!r} excludes {matched[0]}" diff --git a/tests/test_render_scope.py b/tests/test_render_scope.py index 06ccf4480..582980e7b 100644 --- a/tests/test_render_scope.py +++ b/tests/test_render_scope.py @@ -60,3 +60,27 @@ def test_with_override_bases_adds_the_chain(): assert with_override_bases(["demo-3"], SLIDES) == ["demo-1", "demo-2", "demo-3"] assert with_override_bases(["cover"], SLIDES) == ["cover"] assert with_override_bases(["missing"], SLIDES) == [] + + +# ── HTML decks (html=True) ────────────────────────────────────────────── + +HTML_SLIDES = {"cover": {}, "demo-1": {}, "demo-2": {}, "end": {}} + + +def test_html_slide_file_hits_that_slide(): + assert affected_slugs(["slides/demo-1.html"], HTML_SLIDES, html=True) == ["demo-1"] + assert affected_slugs(["slides/end.html", "slides/cover.html"], HTML_SLIDES, html=True) == ["cover", "end"] + assert affected_slugs(["slides/draft.html"], HTML_SLIDES, html=True) == [] + + +def test_html_deck_wide_files_hit_every_slide(): + for path in ("deck.json", "specs/outline.md", "specs/art-direction.html", "deck.css", "./deck.css"): + assert affected_slugs([path], HTML_SLIDES, html=True) == list(HTML_SLIDES) + + +def test_html_mode_ignores_json_slides_and_includes(): + assert affected_slugs(["slides/cover.json", "includes/snippet.json"], HTML_SLIDES, html=True) == [] + + +def test_pptx_mode_ignores_html_only_inputs(): + assert affected_slugs(["slides/cover.html", "deck.css", "specs/art-direction.html"], SLIDES) == [] diff --git a/tests/test_run_python_semantics.py b/tests/test_run_python_semantics.py index cf2d1aa7d..4b8cb85a9 100644 --- a/tests/test_run_python_semantics.py +++ b/tests/test_run_python_semantics.py @@ -216,6 +216,132 @@ def test_sanitization_rewrites_and_rebuilds_once(self, deck_dir: Path, monkeypat assert len(calls) == 1 +# --------------------------------------------------------------------------- +# Local: HTML decks (deck.json outputFormat html) rebuild output.html instead +# --------------------------------------------------------------------------- + + +_HTML_OUTLINE = """# Deck + +- [title] Hello + - body: Greeting + - visual: A title + - evidence: brief Sources 1 +""" + +_TITLE_HTML = '

Hello

\n' + + +@pytest.fixture() +def html_deck(tmp_path: Path) -> Path: + import sdpm.api + + deck = Path(sdpm.api.init("html", output_dir=tmp_path / "html-deck", output_format="html")["output_dir"]) + sdpm.api.apply_style(deck_dir=str(deck), style="typographic", template="blank-light") + (deck / "specs" / "outline.md").write_text(_HTML_OUTLINE, encoding="utf-8") + return deck + + +class TestLocalRunPythonHtml: + _patch_generate = TestLocalRunPython._patch_generate + + def _run(self, deck: Path, code: str, measure_slides=None) -> dict: + return json.loads(sandbox_tools.run_python( + purpose="html", code=code, deck_id=str(deck), measure_slides=measure_slides)) + + def test_slide_write_builds_output_html_not_pptx(self, html_deck: Path, monkeypatch): + calls = self._patch_generate(monkeypatch) + out = self._run(html_deck, f'write_text("slides/title.html", {_TITLE_HTML!r})') + assert calls == [] + assert (html_deck / "output.html").is_file() + assert out["html"] == str(html_deck / "output.html") + assert "pptx" not in out and not (html_deck / "output.pptx").exists() + assert out["affected"] == ["title"] + + def test_measure_returns_report_and_browser_skip(self, html_deck: Path, monkeypatch): + calls = self._patch_generate(monkeypatch) + self._run(html_deck, f'write_text("slides/title.html", {_TITLE_HTML!r})') + out = self._run(html_deck, 'print("noop")', measure_slides=["title"]) + assert calls == [] + assert "title: OK" in out["measure"] + assert out["preview"]["status"] == "unavailable" + assert out["preview"]["reason"] == "browser-skipped" + assert out["browser_check"]["status"] == "skipped" + + def test_slide_change_without_browser_says_check_skipped(self, html_deck: Path, monkeypatch): + """SDPM_BROWSER=none (conftest): output.html is built, and the warnings say that + layout / JS / PNG were not checked.""" + from sdpm.engine.html.browser import DISABLED_NOTE + + self._patch_generate(monkeypatch) + out = self._run(html_deck, f'write_text("slides/title.html", {_TITLE_HTML!r})') + assert (html_deck / "output.html").is_file() + assert out["browser_check"] == {"status": "skipped", "slides": 0, "note": DISABLED_NOTE} + assert f"output.html: {DISABLED_NOTE}" in out["warnings"] + assert any(w.startswith("output.html: Browser check skipped: ") for w in out["warnings"]) + assert out["preview_files"] == [] + + def test_browser_findings_and_pngs_come_back(self, html_deck: Path, monkeypatch): + from sdpm.engine.html import browser_check + + self._patch_generate(monkeypatch) + seen: list[list[str]] = [] + + def fake_check(output_html, slugs, *, png_dir, **_kw): + seen.append(list(slugs)) + png_dir.mkdir(parents=True, exist_ok=True) + (png_dir / "title.png").write_bytes(b"\x89PNG") + diag = {"slug": "title", "rule": "overflow", "message": "overflow: data-ph=\"title\" content"} + return {"status": "issues", "browser": "Fake", "seconds": 0.1, "slides": 1, "checked": ["title"], + "findings": {"title": [diag]}, "errors": [], "pngs": {"title": str(png_dir / "title.png")}, + "timings": {}} + + monkeypatch.setattr(browser_check, "check_deck", fake_check) + out = self._run(html_deck, f'write_text("slides/title.html", {_TITLE_HTML!r})', measure_slides=["title"]) + assert seen == [["title"]] + assert 'title: overflow: data-ph="title" content' in out["warnings"] + assert "[overflow]" in out["measure"] and "browser: issues (Fake, 0.1 s)" in out["measure"] + assert out["preview_files"] == [str(html_deck / "preview" / "png" / "title.png")] + assert "preview" not in out + + def test_readonly_run_does_not_rebuild(self, html_deck: Path, monkeypatch): + self._patch_generate(monkeypatch) + out = self._run(html_deck, 'print("noop")') + assert "html" not in out and not (html_deck / "output.html").exists() + + def test_deck_css_write_rebuilds(self, html_deck: Path, monkeypatch): + self._patch_generate(monkeypatch) + self._run(html_deck, f'write_text("slides/title.html", {_TITLE_HTML!r})') + (html_deck / "output.html").unlink() + out = self._run(html_deck, 'write_text("deck.css", ".card { padding: 8px; }")') + assert (html_deck / "output.html").is_file() + assert out["affected"] == ["title"] # deck.css is deck-wide + + def test_snapshot_watches_html_files(self, html_deck: Path): + before = sandbox_tools._build_snapshot(html_deck) + (html_deck / "slides" / "title.html").write_text("
") + after = sandbox_tools._build_snapshot(html_deck) + assert after != before and "slides/title.html" in after + (html_deck / "deck.css").write_text(".x{}") + assert "deck.css" in sandbox_tools._build_snapshot(html_deck) + assert "specs/art-direction.html" in after + + def test_pptx_snapshot_ignores_art_direction_and_deck_css(self, deck_dir: Path): + (deck_dir / "specs" / "art-direction.html").write_text("") + (deck_dir / "deck.css").write_text(".x{}") + (deck_dir / "slides" / "stray.html").write_text("
") + snap = sandbox_tools._build_snapshot(deck_dir) + assert "deck.css" not in snap and "specs/art-direction.html" not in snap + assert "slides/stray.html" not in snap + + def test_invalid_output_format_stops_the_build(self, deck_dir: Path, monkeypatch): + calls = self._patch_generate(monkeypatch) + out = self._run(deck_dir, 'write_json("deck.json", {"template": "t.pptx", "outputFormat": "htlm"})') + assert "htlm" in out["errors"]["outputFormat"] + assert calls == [] + assert not (deck_dir / "output.pptx").exists() + + # --------------------------------------------------------------------------- # Remote: diff-based always-persist write-back # --------------------------------------------------------------------------- diff --git a/tests/test_vendor_checksums.py b/tests/test_vendor_checksums.py new file mode 100644 index 000000000..2e65056ac --- /dev/null +++ b/tests/test_vendor_checksums.py @@ -0,0 +1,36 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +"""sdpm/vendor/SHA256SUMS lists every vendored file with its current sha256.""" + +from __future__ import annotations + +import hashlib + +from sdpm.config import VENDOR_DIR + +_UNLISTED = {"README.md", "SHA256SUMS"} + + +def _manifest() -> dict[str, str]: + entries: dict[str, str] = {} + for line in (VENDOR_DIR / "SHA256SUMS").read_text(encoding="utf-8").splitlines(): + if not line.strip(): + continue + digest, path = line.split(maxsplit=1) + entries[path.removeprefix("./")] = digest + return entries + + +def test_manifest_lists_every_vendored_file(): + on_disk = { + p.relative_to(VENDOR_DIR).as_posix() + for p in VENDOR_DIR.rglob("*") + if p.is_file() and p.name not in _UNLISTED and "__pycache__" not in p.parts + } + assert set(_manifest()) == on_disk + + +def test_vendored_files_match_their_checksums(): + for path, digest in _manifest().items(): + actual = hashlib.sha256((VENDOR_DIR / path).read_bytes()).hexdigest() + assert actual == digest, f"{path} does not match SHA256SUMS" diff --git a/uv.lock b/uv.lock index db160df79..1907f26a0 100644 --- a/uv.lock +++ b/uv.lock @@ -1314,6 +1314,8 @@ dependencies = [ { name = "pygments" }, { name = "python-pptx" }, { name = "qrcode" }, + { name = "websockets", version = "16.1.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "websockets", version = "17.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] [package.metadata] @@ -1324,6 +1326,7 @@ requires-dist = [ { name = "pygments", specifier = ">=2.19.2" }, { name = "python-pptx" }, { name = "qrcode" }, + { name = "websockets", specifier = ">=13" }, ] [package.metadata.requires-dev] @@ -1529,6 +1532,293 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/88/fa/e1388bbcf24ef3274f45c0c1c7b501fd14971037c1b6ee23610553307497/uvicorn-0.49.0-py3-none-any.whl", hash = "sha256:ba3d14c3ee7e41c6c654c46c9eb489d33213cdd30aa1696eab1374337c13f68f", size = 71376, upload-time = "2026-06-03T22:01:29.037Z" }, ] +[[package]] +name = "websockets" +version = "16.1.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11' and sys_platform == 'win32'", + "python_full_version < '3.11' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/21/f7/bc3a25c5ec26ce62ce487690becc2f3710bbc7b33338f005ad390db0b986/websockets-16.1.1.tar.gz", hash = "sha256:db234eda965dcce15df96bb9709f587cd87d4d52aaf0e80e2f34ec04c7670c57", size = 182204, upload-time = "2026-07-17T22:51:05.858Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/08/e7/d1671fb984f9dd844e1da5288070c7c23c9eaba3082d3871aae19c3ab8b9/websockets-16.1.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:49ae99bdfcae803a885c926bf14f886196e84925395bb3f568fef5c0f0979d7d", size = 179570, upload-time = "2026-07-17T22:48:24.032Z" }, + { url = "https://files.pythonhosted.org/packages/99/f5/70df723bf571f5e0b1b845e0a4ff1c966eeb84f667599fc251caa37d15a3/websockets-16.1.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:5bfd1ac19b1b9986a9c95a82d5e23a391ebb09e12c34d7be6094b86efcc35731", size = 177252, upload-time = "2026-07-17T22:48:25.775Z" }, + { url = "https://files.pythonhosted.org/packages/90/72/2f14b2e167170b8bf1c8bb7f9b0d78000f470d41a2085a91f33e3917b6c9/websockets-16.1.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:9246a0d063cfcbcc85f2359dd6876d681213f4790832272aa16641b4ed5d64d4", size = 177530, upload-time = "2026-07-17T22:48:27.337Z" }, + { url = "https://files.pythonhosted.org/packages/f3/18/a17e2f0cde02dc10154c808deed7e1d8528afff93612f70d3f0a5b19b011/websockets-16.1.1-cp310-cp310-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:1214e673c404684b9bf7154f5cf43b45025b1a6160fac3a9e438e9c1a97e22cb", size = 186038, upload-time = "2026-07-17T22:48:28.756Z" }, + { url = "https://files.pythonhosted.org/packages/d5/b0/41de283899cf5929d637b72a508cdbc9aa40dc0f317c6b77613fd1000488/websockets-16.1.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:90001d893bc368e302ef168d82130b4e4fdd27b85fa094682df9b667c2d48838", size = 187278, upload-time = "2026-07-17T22:48:30.328Z" }, + { url = "https://files.pythonhosted.org/packages/50/61/874aab5257e027f9f61b5004cec65e592babca7942b1bc09f38e72b7f1fd/websockets-16.1.1-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:130937b167a52af203c8d58e78d67705874e82759862e3b9671a452fec4abc87", size = 189936, upload-time = "2026-07-17T22:48:31.896Z" }, + { url = "https://files.pythonhosted.org/packages/a6/1a/42173913ac5519607220849ed417c864d77384e4119f06dbba964a50f096/websockets-16.1.1-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9c9f23004a3d40e89c01a7955d186a6cc83418d93b749701944ce2de3e95a1f3", size = 187796, upload-time = "2026-07-17T22:48:33.344Z" }, + { url = "https://files.pythonhosted.org/packages/1b/f4/37c1840bd89b529479aec41470b97b7c683b107ca90b6399ac5afb99dedf/websockets-16.1.1-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f55f0b01956a094c8587146d9558c91937e78789c333860ffaf35931a6e5dbc4", size = 186481, upload-time = "2026-07-17T22:48:34.843Z" }, + { url = "https://files.pythonhosted.org/packages/9e/70/652d9b964adcfbeb056f42e0ca6bece34d108fe75534e74df20643cae199/websockets-16.1.1-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:6aaface73b9c71974c6497366d8b9628357f6c9749e09c4ea3610176c63f2ae3", size = 184351, upload-time = "2026-07-17T22:48:36.307Z" }, + { url = "https://files.pythonhosted.org/packages/13/f1/af3850e5d48d482921985be72ebcb169c6180b3a77b57bd612deebcee23b/websockets-16.1.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:dc0fad4933f427acd5b1cec210f3ea6dce7089e1724e4b9ec6ef47c6c04d1b3b", size = 186791, upload-time = "2026-07-17T22:48:37.762Z" }, + { url = "https://files.pythonhosted.org/packages/1d/40/1a4e3ed4969ec378dcad337e5f1472c5e292cb3e733bc392f0dc2e230abd/websockets-16.1.1-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:f2769a0344a09e9ccf5b3cce538bc75a51b53eff3275d3896310c8552049195d", size = 185413, upload-time = "2026-07-17T22:48:39.127Z" }, + { url = "https://files.pythonhosted.org/packages/aa/3e/4e3fa1afe8f1a6a780434cd9ba8eb422632b044eff3dd73f6af67523c147/websockets-16.1.1-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:f70541f3104339f59f830522d94ebadb1bf47426287381623443d8bb1cdbf33d", size = 187178, upload-time = "2026-07-17T22:48:40.676Z" }, + { url = "https://files.pythonhosted.org/packages/71/ab/dd742766aa5dda7f349be0de49e4d565b84cf6f7f7fa02e07692f0f2bdd9/websockets-16.1.1-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:dc385593a42e31cd6fb60c19f0ecb015b386603818fc2c6c274fb42bd2bb4165", size = 185051, upload-time = "2026-07-17T22:48:42.098Z" }, + { url = "https://files.pythonhosted.org/packages/ae/f5/76438c6560f416f1c0a7f587679fb97cc6e99ed336011d43ce2002dd27c1/websockets-16.1.1-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:387e8e4aa5df2f90b198fa3cad3478822a89cf905b6a6d6c97dc3664689640cc", size = 185846, upload-time = "2026-07-17T22:48:43.472Z" }, + { url = "https://files.pythonhosted.org/packages/62/12/5c0320f2127823d27b2d56d611d31b0b284ad4edcb41364d66bf4c92b537/websockets-16.1.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:fd46fff7eb62c24804d234f0051c7a8ea81285ad63e0337d3dcf33ca82aee58a", size = 186066, upload-time = "2026-07-17T22:48:44.884Z" }, + { url = "https://files.pythonhosted.org/packages/a2/97/875986b857b955c3f9dd192cb8a1af81254dfb2ea22cc9590f0a1e020b8b/websockets-16.1.1-cp310-cp310-win32.whl", hash = "sha256:7883388947767080f094950b342b30d35a2a06b849cd967c422fa0db72b40ea9", size = 179940, upload-time = "2026-07-17T22:48:46.481Z" }, + { url = "https://files.pythonhosted.org/packages/54/82/1013a5fe7ddae8e102bc3b4b39db81d8d28fd02100a324ce6ede8cd832b1/websockets-16.1.1-cp310-cp310-win_amd64.whl", hash = "sha256:d57685547e0060cc6fd90ee6a28405d6bd395e525545f13c8d7cd99c78afd79f", size = 180239, upload-time = "2026-07-17T22:48:48.043Z" }, + { url = "https://files.pythonhosted.org/packages/2b/03/47debfe28e9d6d354be5d777b67fd44c359b9eb299a5d103500bd7cc3e37/websockets-16.1.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:d0fcf657e9f13ff4b177960ab2200237b12994232dfb6df16f1cfe1d4339f93c", size = 179566, upload-time = "2026-07-17T22:48:49.596Z" }, + { url = "https://files.pythonhosted.org/packages/72/93/31efa1ed78c17e5cfc229fd449e3966e1b9cc15753204cd585cc8dd01f4a/websockets-16.1.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:b852788aa51764e2d8e4cf5493d559326bcae5e38d16ba25ffa322b034df272a", size = 177250, upload-time = "2026-07-17T22:48:50.942Z" }, + { url = "https://files.pythonhosted.org/packages/01/4a/542378ab3972b0c1cf1df3df3eff9591cea0d30c58c3aa3c4ddbc244e787/websockets-16.1.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:1427fb4cf0d72f66333e2cacc3ff5f575bf2d7008166ce991a4a470b21d51a22", size = 177528, upload-time = "2026-07-17T22:48:52.59Z" }, + { url = "https://files.pythonhosted.org/packages/33/d9/162321f63c7eed558e9e1798ed7a1e34a4f6dab51f35419e4ed7a4907979/websockets-16.1.1-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:da4ca1a9d72f9030b3146b8d7022719a9f3d478f61efe6f7dd51d243f61c51b2", size = 186859, upload-time = "2026-07-17T22:48:53.915Z" }, + { url = "https://files.pythonhosted.org/packages/de/09/87df740f7430ce564bd52402e9c9458d4d0459cc7d2ee29e530c8204851b/websockets-16.1.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:86d7f0f8bdb25d2c632b72527325e4776430fd5bc61b9118de4e2b8ddb5f5b01", size = 188095, upload-time = "2026-07-17T22:48:55.384Z" }, + { url = "https://files.pythonhosted.org/packages/d2/12/3d2703af7cc095f3c81904c92208cc1ae79affbc67376944b50ee9301f73/websockets-16.1.1-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:7dfcad78ea1492ee3a9ec765cb7f51bbc17d477107aaf6b22abf7b2558d1c5a0", size = 191385, upload-time = "2026-07-17T22:48:56.742Z" }, + { url = "https://files.pythonhosted.org/packages/1d/69/986aa0234a964a00f5149cfc46e136e96c8faad1c783474550f40d31aef4/websockets-16.1.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:fb9a0a6dc3d1b3986cb88091b6899f0396651e0f74e2c9766ab8d6ffc3842e29", size = 188653, upload-time = "2026-07-17T22:48:58.134Z" }, + { url = "https://files.pythonhosted.org/packages/35/6b/10f9d03e3970a69ba67bd3b46b87a929b586d0300fadbfe14f57c1f85490/websockets-16.1.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:29dfa8114c4a620c69591c5973860f768eac29d3fd6904f37f34266cb219c512", size = 187426, upload-time = "2026-07-17T22:48:59.515Z" }, + { url = "https://files.pythonhosted.org/packages/56/db/bb3aad62bf63d8bb3f0634b2eabffcfb3677a34bd19492110ff6869cf703/websockets-16.1.1-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:6ff9417c0ada4d0f7d212f928303e5579bdf3ace4c802fa4afabb30995da58c3", size = 184882, upload-time = "2026-07-17T22:49:00.916Z" }, + { url = "https://files.pythonhosted.org/packages/6c/4c/c09a2ea9bfbeccce52fdc383e5f28af4bc8843338aabac28c81489af6120/websockets-16.1.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:8fe0b50da2d84535fb4f7b4bfa951280f97ce3d558a0443b541166d609e67b57", size = 187584, upload-time = "2026-07-17T22:49:02.283Z" }, + { url = "https://files.pythonhosted.org/packages/c7/8b/31bb4eb4d9eaacf1fdd39d115772a8aeaedfc19b5dc262e57ffbc8a9d42c/websockets-16.1.1-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:34420aaa64440ebd51ac72ca8a45ef4626429438c9b02e633ae412ed43f925d3", size = 186174, upload-time = "2026-07-17T22:49:03.973Z" }, + { url = "https://files.pythonhosted.org/packages/2f/e4/dc02d725610a1ad49e193ef91a548194d71bdc6cdf27da83067dd1f73995/websockets-16.1.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:a6a61aff018180c9c50b7b0da33bfd29d378af3497429c95006c589a23a11648", size = 187986, upload-time = "2026-07-17T22:49:05.553Z" }, + { url = "https://files.pythonhosted.org/packages/e0/73/30ed84c8bfd14c73d4af29d5ed9323c3073b48e0b7b23b67070f4e7fd59b/websockets-16.1.1-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:04fd29a0e2fe9414a95b00e92c67ae51bf900c50c0f8a4b2dafdad621f49ea1d", size = 185565, upload-time = "2026-07-17T22:49:06.959Z" }, + { url = "https://files.pythonhosted.org/packages/7d/d3/4be8d4959f51e31b4f8fc0ece12b45bd3b6c0d15ea23b9990d9c11fc805f/websockets-16.1.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:5c31aa7e39ee3e8a358573257f1c0bb5c52430d1b637030dd9c8cc2c282926be", size = 186598, upload-time = "2026-07-17T22:49:08.293Z" }, + { url = "https://files.pythonhosted.org/packages/26/fa/abb38597a52d84ed9cfacadc7a0c6f2db282c0ab23cdf72b58a666a21227/websockets-16.1.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:d14bfb217eb4701e850f1525c9d29d79c44794cdf1c299ead25f39f8c78dea81", size = 186834, upload-time = "2026-07-17T22:49:09.766Z" }, + { url = "https://files.pythonhosted.org/packages/59/80/1119ad08a228b90c4eb77fbe48df7836731a605f5f881ba701ca826a4a65/websockets-16.1.1-cp311-cp311-win32.whl", hash = "sha256:2e28e602bb13da44fbe518c1781a88e3b9d4c3d48d02c9bad83e546164336f57", size = 179940, upload-time = "2026-07-17T22:49:11.196Z" }, + { url = "https://files.pythonhosted.org/packages/71/b2/e511c1c6f64a95c2f3fc54bffda0e14eaa7e9442be605c29270f7589b918/websockets-16.1.1-cp311-cp311-win_amd64.whl", hash = "sha256:7421fad442de870a8cbf2287d1cad7e706ece0dbfeba5e911df132cbdc1cb56a", size = 180239, upload-time = "2026-07-17T22:49:12.519Z" }, + { url = "https://files.pythonhosted.org/packages/17/9d/681cda21c9eee743203a6cb79b9d3d05adad9aa60ec660c6c9bf4dd619ca/websockets-16.1.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:cc97814dfb786a83b6e2dc2e79351e1b83e6d715647d6887fcabd83026417a00", size = 179600, upload-time = "2026-07-17T22:49:13.92Z" }, + { url = "https://files.pythonhosted.org/packages/fb/8d/6195a88b45e8d2a8f745fc2046e36f885a3c9763e6767d2c46229bf9510c/websockets-16.1.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:e047dc87ef7ca50f4d309bf775ad4a71711c58556d75d7bd0604b2317f43e94b", size = 177272, upload-time = "2026-07-17T22:49:15.453Z" }, + { url = "https://files.pythonhosted.org/packages/73/e3/fe2d498c64dea0095c9a9f9a351af4cd6eef31b618395582bc1f38ba45ff/websockets-16.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:01fbdcbac298efe19360b94bc0039c8f746f0220ba570f327577bfee81059175", size = 177542, upload-time = "2026-07-17T22:49:16.875Z" }, + { url = "https://files.pythonhosted.org/packages/fe/ed/f1831681fce0e3242346e5458486003c5f124ed69e5e0b847fd029db4973/websockets-16.1.1-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:0f62863e8a00a6d33c3d6566ec0b89f23787b747ffe0c3bc71ec0e76b82c94b1", size = 187137, upload-time = "2026-07-17T22:49:18.323Z" }, + { url = "https://files.pythonhosted.org/packages/6f/79/4ff9dcc1bb46f6b4c536936dde1fd60f9b564f3304307274db97f4c9496d/websockets-16.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8087e82f842609734c9b5a1330464f8e94e346ba0e18c832c08bafa4b0d63c15", size = 188374, upload-time = "2026-07-17T22:49:19.65Z" }, + { url = "https://files.pythonhosted.org/packages/62/c3/5c49b6efb36cab733d23773f6de575e1dba65736ead17d5d2b2a1daef779/websockets-16.1.1-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:2bb5d041a8307d2e18782e7ce777f6fdb1e8c2f5d09291484b18c294b789d9aa", size = 191155, upload-time = "2026-07-17T22:49:21.331Z" }, + { url = "https://files.pythonhosted.org/packages/6e/f6/56ccceda3a4838d18f1d40821480da4775397e8b1eecf4031e20c50e2e90/websockets-16.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1db4de4a0e95673f7545d393c49eeb0c2f18ac1ef93073218c79d5cdb2ee75ab", size = 189011, upload-time = "2026-07-17T22:49:22.889Z" }, + { url = "https://files.pythonhosted.org/packages/86/d6/ad5286241a2bce1107e2798d3bfbd62cf79aee167bdb654f8cb1e9dbf949/websockets-16.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f17dbe07eb3ea7f99e4df9b7e0efefe80fbf30d37a8cc4d561a0aed310bc8847", size = 187766, upload-time = "2026-07-17T22:49:24.339Z" }, + { url = "https://files.pythonhosted.org/packages/bc/67/d65c970b7e347fdca69479beb7811c2060529956730a7a4e3ae7c66b0e31/websockets-16.1.1-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4b57693728576d84ede0a77987ab16881b783d2cd9f1dc180a8fbbc3f79c4428", size = 185173, upload-time = "2026-07-17T22:49:25.743Z" }, + { url = "https://files.pythonhosted.org/packages/1d/5b/14af3cd4ee69d8ea9baca58f3dc3cfb1ba78332a347fd478cb096549d60e/websockets-16.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2a636ff1e7a5c4edf71ef0e79adae7f25dba93b4fcbe3dc958733477ffeb0eaf", size = 187809, upload-time = "2026-07-17T22:49:27.147Z" }, + { url = "https://files.pythonhosted.org/packages/7b/11/be301710d70de97e3e7b3586e6d492c9c06d6a61bf1c2202c36cf0c75607/websockets-16.1.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:d6bec75c290fe484a8ba4cacdf838501e17c06ecfbbf31eede81a9e431bd7751", size = 186412, upload-time = "2026-07-17T22:49:28.611Z" }, + { url = "https://files.pythonhosted.org/packages/db/07/fe1435bf6fe738a3d3b54dbe0c18dabf12cba4d909ac8b58b539ce27c1f4/websockets-16.1.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:54509b8e92fee4453e152b7558ddef37ce9705a044922f2095a6105e3f80c96f", size = 188290, upload-time = "2026-07-17T22:49:29.965Z" }, + { url = "https://files.pythonhosted.org/packages/8a/0a/81f394aff8efcbb01208c1ced77df0a3c7fcce584a88c7273663697946c2/websockets-16.1.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:f0aa4aad3b1b69ad3fd85a0fd0952ec64331c762bd77ec51cc814170873890b2", size = 185844, upload-time = "2026-07-17T22:49:31.447Z" }, + { url = "https://files.pythonhosted.org/packages/39/5c/dd485b995473f415510251fe9bd708f2d24458f439fce958daf8d66dc7c6/websockets-16.1.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:42290eb6db4ccaca7012656738214f8514082fb6fa40cdeb61bb9a471b52e383", size = 186823, upload-time = "2026-07-17T22:49:33.104Z" }, + { url = "https://files.pythonhosted.org/packages/9d/0b/f78de76ff446f1e66af12b43c48a35f31744de93cfdec2f4ea67d5d7bbf1/websockets-16.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:53260c8930da5771cec89439bff99c20c8cb03ddb9588b980697355a83cd4bd3", size = 187102, upload-time = "2026-07-17T22:49:34.616Z" }, + { url = "https://files.pythonhosted.org/packages/37/a1/4cf892007778eaf84ad162bfc98046e0ed89b63ac55949e3236626b2a23f/websockets-16.1.1-cp312-cp312-win32.whl", hash = "sha256:1d27fa8462ad6a1cb36206a3d0640b2333340def181fae11ed7f9adeaa5c0747", size = 179943, upload-time = "2026-07-17T22:49:36.213Z" }, + { url = "https://files.pythonhosted.org/packages/d9/de/6abe251d28c3a3f217096575400b27750b18e0b1d2fff3a2a239960fea07/websockets-16.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:b436f6ec4fc3a6b4237c84d3f83170ed2b40bb584222f0ac47a0c8a5921980c7", size = 180243, upload-time = "2026-07-17T22:49:37.626Z" }, + { url = "https://files.pythonhosted.org/packages/ce/fd/6ec6c6d2850aea25b1b2aa9901a016980bb87d01e89b3eb00470b1b5d471/websockets-16.1.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:ab59169ace05dcb49a1d4118f0bde139557adf45091bd85747e36bf5de984dd1", size = 179587, upload-time = "2026-07-17T22:49:38.959Z" }, + { url = "https://files.pythonhosted.org/packages/5f/d8/1d299d2dd34087db39831a34cc645ef8a6f89d78efada6983093513cd81c/websockets-16.1.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:5e3b7d601f6f84156b08cc4a5e541c2b50ad7b36cfc302b657a12477c904a5df", size = 177272, upload-time = "2026-07-17T22:49:40.293Z" }, + { url = "https://files.pythonhosted.org/packages/3d/86/0a70d3ae2f0f2256bb41302d9804dbca65d4360281e7feb3e1f94102ac46/websockets-16.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:cd2ca96a082a36964aca83e992f72abeb61b7306c1a6cba4c7d06a7b93750cac", size = 177530, upload-time = "2026-07-17T22:49:41.786Z" }, + { url = "https://files.pythonhosted.org/packages/b5/c2/c676c69444d9db448b3f0a55a98dcc534affce0bce961d9d2f0b8499b10a/websockets-16.1.1-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:f5d497865f05bb222cab7016c6034542e84e5f29f49c6fd3f4939cda7197b5b8", size = 187197, upload-time = "2026-07-17T22:49:43.658Z" }, + { url = "https://files.pythonhosted.org/packages/0b/13/88137fbaf726ebe29d62c1117fa11fa2bbb6209dc79d4ad738efbe36a2aa/websockets-16.1.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bae954c382e013d5ea5b190d2830526bfa45ad121c326da0049b8c769f185db6", size = 188433, upload-time = "2026-07-17T22:49:45.147Z" }, + { url = "https://files.pythonhosted.org/packages/01/6d/46c2f2ce6751cb26f39293e1ecbf8544cb01321397cd476c2756b98c216d/websockets-16.1.1-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:e09f753a169951eb4f28c2c774f71069304f66e7277e0f5a2892423599cfa854", size = 189868, upload-time = "2026-07-17T22:49:46.581Z" }, + { url = "https://files.pythonhosted.org/packages/29/2b/170a9e8097636cfde4dc3c592b6e00b18a44a2f5407606d96ca542dd5838/websockets-16.1.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:024193f8551a2b0eafbdd160911012c4e6c228c28430c84433253299a9e42d6a", size = 189059, upload-time = "2026-07-17T22:49:47.972Z" }, + { url = "https://files.pythonhosted.org/packages/a7/48/f0d4ebc9ab4b473b8861b9e20fdb663d515d42f7befdf62cdb60fee7a1ec/websockets-16.1.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:aabe464bfd13bd25f4821faf111da6fefdc389f870265a53105580e45b0a2e49", size = 187814, upload-time = "2026-07-17T22:49:49.344Z" }, + { url = "https://files.pythonhosted.org/packages/d5/ba/39a41d3ae8e72696a9492581900611c5a91e2b07563b0bcd2523adea9854/websockets-16.1.1-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a28fcbc9b6baf54a2e23f8655f308e4ccc6afdd7266f8fe7954f320dcda0f785", size = 185229, upload-time = "2026-07-17T22:49:50.787Z" }, + { url = "https://files.pythonhosted.org/packages/3c/36/ac15b604f850d1907f0a85ed721cefe47cd45034b3620069b829746cccbe/websockets-16.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:79eace538c6a97e96d0d03d4f9d314f9677f5ed85a8a984992ffd90b13cb8a56", size = 187874, upload-time = "2026-07-17T22:49:52.228Z" }, + { url = "https://files.pythonhosted.org/packages/a8/f3/3fbd5d71d59299c3770faa5884d4f45070236ca5a35ab3a61830812c409a/websockets-16.1.1-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:496af849a472b531f758dbd4d61338f5000538cb1a7b3d20d9d32a264517f509", size = 186469, upload-time = "2026-07-17T22:49:53.776Z" }, + { url = "https://files.pythonhosted.org/packages/b4/fc/dd90349bba58af2a53ef2ddd9c32716c81eb6d59a0687939fff561860878/websockets-16.1.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:5283810d2646741a0d8da2aa733d6aefa0545809afccb2a5d105a26bc45125f1", size = 188347, upload-time = "2026-07-17T22:49:55.202Z" }, + { url = "https://files.pythonhosted.org/packages/4c/f3/f73ba86427682da59b78c11d77ba56d5b801c32e84afe79b274bbd6a9bb2/websockets-16.1.1-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:4e3b680b1e0a27457e727a0d572fd81dffa87b6dbf8b228ab57da64f7d85aead", size = 185903, upload-time = "2026-07-17T22:49:56.75Z" }, + { url = "https://files.pythonhosted.org/packages/34/7c/f95eb20e80104173b3a0a092291f89ea4047ef6e608e0a57ca06eb14eecb/websockets-16.1.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:69159730a823dde3ea8d08783e8d47ef135a6d7e8d44eb127e32b321c9db8e3e", size = 186855, upload-time = "2026-07-17T22:49:58.467Z" }, + { url = "https://files.pythonhosted.org/packages/b0/35/dd875b3e050ff232d60fa377707f890e369f74d134f1be32e8f68879747c/websockets-16.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:ed5bb271084b46530ee2ddc0410537a9961152c5ccba2fc98c5276d992ccba87", size = 187140, upload-time = "2026-07-17T22:50:00.016Z" }, + { url = "https://files.pythonhosted.org/packages/e8/dc/5cbfcb41824502f6af93b8f3943a4d06c67c23c7d2e31eb18748c4a5b2a7/websockets-16.1.1-cp313-cp313-win32.whl", hash = "sha256:cfb70b4eb56cac4da0a83588f3ad50d46beb0690391082f3d4e2d488c70b68ea", size = 179928, upload-time = "2026-07-17T22:50:01.685Z" }, + { url = "https://files.pythonhosted.org/packages/b0/c1/71e5deb5b7f8f226997ab64908c184ac3105c0155ce2d486f318e5dd08a8/websockets-16.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:d9531d9cbeac99af6f038fb1bc351403531f7d634a2c2e10e2f7c854c6ed5b68", size = 180242, upload-time = "2026-07-17T22:50:03.117Z" }, + { url = "https://files.pythonhosted.org/packages/73/a2/ba78a164eeea4620df4a4df4bd2ed6017438c4655cc0f36f2c0bc0432355/websockets-16.1.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:443aefe96b7fdb132e2a70806cca1f2af49bb3f28e47abcd7c2e9dcf4d8fa1b8", size = 179635, upload-time = "2026-07-17T22:50:05.001Z" }, + { url = "https://files.pythonhosted.org/packages/b9/08/d26d7a7628cd4ac34cbbdb63ac80914ca842ed8e42938c40a53567806df3/websockets-16.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:6456ff333092d509127d75a638cb411afae8ff17f092635015d1902efec8a293", size = 177320, upload-time = "2026-07-17T22:50:06.427Z" }, + { url = "https://files.pythonhosted.org/packages/0f/45/ebec83e6269536aa5932533c67b0af5c781f3e73fdbcd68672dcf43f4f44/websockets-16.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:fce6c48559c86d1ac3632ccb1bebc7d5442fbe79bd9bb0e40379ee54be2a4051", size = 177544, upload-time = "2026-07-17T22:50:07.834Z" }, + { url = "https://files.pythonhosted.org/packages/c9/d5/abc614d2297f6c1c3e01e61260364457a47c25cc1cf6a879038902bc6aa8/websockets-16.1.1-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:92b820d345f7a3fc7b8163949ee92df910f290c3fc517b3d5301c78065adafe1", size = 187270, upload-time = "2026-07-17T22:50:09.275Z" }, + { url = "https://files.pythonhosted.org/packages/52/71/4c99af3b87dff1b2927981f6876607d4acb45338c665242168d3982f7758/websockets-16.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2a606d9c24035242a3e256e9d5b77ed9cd6bccfcb7cf993e5ca3c0f6f68fb6a7", size = 188509, upload-time = "2026-07-17T22:50:10.722Z" }, + { url = "https://files.pythonhosted.org/packages/9b/b4/5c8ca14b0df7eb84ed0524165c5359150210140817a3312aee57bf62a1cf/websockets-16.1.1-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:414e596c75f74e0994084694189d7dc9229fb278e33064d6784b73ffbba3ca31", size = 189882, upload-time = "2026-07-17T22:50:12.293Z" }, + { url = "https://files.pythonhosted.org/packages/25/c1/bedfba9e70557129cb8083748d167bdcc01483dedf0f0df143676df05cbe/websockets-16.1.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:536676848fc5961aca9d20389951f59169508f765637a172403dc5434d722fa0", size = 189114, upload-time = "2026-07-17T22:50:13.789Z" }, + { url = "https://files.pythonhosted.org/packages/df/09/aa835b2787835aebd839114be5de51b797cb480b63ba42b26d34dfe147cb/websockets-16.1.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:97fd3a0e8b53efa41970ac1dff3d8cf0d2884cadeb4caaf95db7ad1526926ee3", size = 187861, upload-time = "2026-07-17T22:50:15.179Z" }, + { url = "https://files.pythonhosted.org/packages/20/26/f6408330694dbc9830857d9d23bc14ac4f6875127a480cfdda8d5ca21198/websockets-16.1.1-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:7b1b19636af86a3c7995d4d028dbe376f39b4bf31541146f9c123582a6c94562", size = 185286, upload-time = "2026-07-17T22:50:16.741Z" }, + { url = "https://files.pythonhosted.org/packages/17/9a/e0675e70dd8a80762cf35bb18799d3f290a4890ffe6439bc51d222796083/websockets-16.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:41c8e77f17294c0ac18008a7309b99b34ee72247ef10b6dff4c3f8b5ac29896b", size = 187935, upload-time = "2026-07-17T22:50:18.213Z" }, + { url = "https://files.pythonhosted.org/packages/33/c1/3234cfb86afde01b81e9bddcc6e534c440975d60a13991259e833069ab3e/websockets-16.1.1-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:9f63bcef7f4b02b06b35fc01c93b96c43b5e88e1e8868676caacf493d5a31f3a", size = 186444, upload-time = "2026-07-17T22:50:19.67Z" }, + { url = "https://files.pythonhosted.org/packages/89/87/9c15206e1d778923d8daa9657de07aa62ea815e13448319c98458c37b281/websockets-16.1.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:dab9eb87869da2d6ed3af3f3adf28414baae6ec9d4df355ffc18889132f3436c", size = 188409, upload-time = "2026-07-17T22:50:21.28Z" }, + { url = "https://files.pythonhosted.org/packages/f2/00/cf5de5c67676de2d3eef8b2a518f168f6796595447a5b7161ba0d012915c/websockets-16.1.1-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:43e3a9fdd7cbf7ba6040c31fae0faf84ca1474fef777c4e37912f1540f854499", size = 185958, upload-time = "2026-07-17T22:50:22.719Z" }, + { url = "https://files.pythonhosted.org/packages/62/c0/731b6ddede2e4136912ec4cff2cffbda35af73546be4762c3d7bd3bd79af/websockets-16.1.1-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:056ae37939ed7e9974f364f5864e76e49182622d8f9751ac1903c0d09b013985", size = 186911, upload-time = "2026-07-17T22:50:24.108Z" }, + { url = "https://files.pythonhosted.org/packages/8c/7f/39c634472c4469a24a7c09cecddffb08fac6d0e74f73881a94ee8a40a196/websockets-16.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:a0eadbbf2c30f01efa58e1f110eb6fa293261f6b0b1aa38f7f48707107690af9", size = 187204, upload-time = "2026-07-17T22:50:25.548Z" }, + { url = "https://files.pythonhosted.org/packages/26/89/9667c256c256dafcc62d21328ce7a40067da857969b68ee9af375b0aaf72/websockets-16.1.1-cp314-cp314-win32.whl", hash = "sha256:195c978b065fa40910582464f99d6b15c8b314c68e0546549a55ed83f4735328", size = 179603, upload-time = "2026-07-17T22:50:27.086Z" }, + { url = "https://files.pythonhosted.org/packages/bd/dd/1c099d6c0fc5deb6b46ccdbb6981fdb4b12c917869cb3952408409dc18db/websockets-16.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:4e8d01cc3bcae7bbf8167f944aeafefed590fae5693552bba9794a9df68371cc", size = 179948, upload-time = "2026-07-17T22:50:28.521Z" }, + { url = "https://files.pythonhosted.org/packages/35/25/9956b2d5e0529d5d23924f21bba1440d4c5c88a562e4f08550871ffa97a7/websockets-16.1.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:0ffd3031ea8bda8d61762e84220186105ba3b748b3c8da2ae4f7816fac03e573", size = 179963, upload-time = "2026-07-17T22:50:29.982Z" }, + { url = "https://files.pythonhosted.org/packages/17/06/55ffc976c488b6aee9ea05761ff7c4e88e7c1fd82818c8ca7b556ad2f90c/websockets-16.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:84a2cef8deffbd9ab8ee0ea546a2a6a7030c28f44e6cdd4547dbfeb489eb8999", size = 177497, upload-time = "2026-07-17T22:50:31.396Z" }, + { url = "https://files.pythonhosted.org/packages/0c/e8/f7dac2e980bacc92bdc26cebae4ae4d50cae5380732c50980598fc0bbae4/websockets-16.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:3df13f73af9b3b38ab1195eb299ecb67a4330c911c97ae04043ff74085728abe", size = 177698, upload-time = "2026-07-17T22:50:32.829Z" }, + { url = "https://files.pythonhosted.org/packages/b2/39/26762f734113e22da2b942c3aca85798e0c0405d64c256549540ff31e5a1/websockets-16.1.1-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:23253dd5bcae3f9aaee0a1d30967a8dbd52e5d3cff93a2e5b84df57b77d4750d", size = 187561, upload-time = "2026-07-17T22:50:34.24Z" }, + { url = "https://files.pythonhosted.org/packages/11/94/c3f330851806b9b02138b774d593478323e73c99238681b4b93efe64e02d/websockets-16.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9c1c5705e314449e3308872fe084b8571ce078ee4fc55a98a769bdefe5917392", size = 188732, upload-time = "2026-07-17T22:50:36.088Z" }, + { url = "https://files.pythonhosted.org/packages/d1/f2/eb2c450f052de334ae33cf200ece6e87b0e14d186807074e4eb1cd2cdea2/websockets-16.1.1-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:69e52d175a0a7d1e13b4b67ad41c560b7d98e8c6f6126eb0bda496c784faf8c7", size = 190872, upload-time = "2026-07-17T22:50:38.008Z" }, + { url = "https://files.pythonhosted.org/packages/70/31/2ac8cecf3a74f7fed9132129fc3d90b3998a1554570c11a69b2a8c20332d/websockets-16.1.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1f79c89b5eb034d1722938a891916582f8f7f503f58ca22518a63c3f2cd18499", size = 189305, upload-time = "2026-07-17T22:50:39.53Z" }, + { url = "https://files.pythonhosted.org/packages/6a/cf/8ab19650d3c0d4562c92e70ab47c257c4aa5c6a713ed87fe63766b31fefc/websockets-16.1.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:39f2a024af5c345ffe8fcf1ee18c049c024c94df393bb09b044a6917c77bde43", size = 188033, upload-time = "2026-07-17T22:50:40.912Z" }, + { url = "https://files.pythonhosted.org/packages/66/d7/a49a38a6127a4acb134fb1912b215d900cc657605cff32445bf519f3acc4/websockets-16.1.1-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:952303a7318d4cbe1011400839bb2051c9f84fa0a35923267f5daba34b15d458", size = 185748, upload-time = "2026-07-17T22:50:42.559Z" }, + { url = "https://files.pythonhosted.org/packages/95/3e/ad1fa40388c7f2e0bb2c7930d0090b6c5498594bd1cdaec18864df3d9e97/websockets-16.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:249116b4a76063d930a46391ad56e135c286e4562a18309029fc2c73f4ed4c62", size = 188285, upload-time = "2026-07-17T22:50:43.974Z" }, + { url = "https://files.pythonhosted.org/packages/35/b8/d5db28ca264b9104f82196f92dc8843e35fd391f763d42e4ad358f5bc97e/websockets-16.1.1-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:61922544a0587a13fd3f53e4c0e5e606510c7b0d9d22c8444e5fae22a06b38cb", size = 186777, upload-time = "2026-07-17T22:50:45.474Z" }, + { url = "https://files.pythonhosted.org/packages/42/9c/726cb39d0cc43ae848dce4aa2acb04eecc6738b1264ec6d700bf6bcfb9f8/websockets-16.1.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:46dcaa042cd1de6c59e7d9269fa63ff7572b6df40510600b678f0826b3c7af51", size = 188682, upload-time = "2026-07-17T22:50:46.973Z" }, + { url = "https://files.pythonhosted.org/packages/be/c7/1168704de8c2dd483edabe4a22cbe4465dd8be8dd95561d214f9fe092871/websockets-16.1.1-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:38565aca3e01ea8734e578fb2118dade0ecb0250533f29e22b8d1a7a196cf4d0", size = 186377, upload-time = "2026-07-17T22:50:48.413Z" }, + { url = "https://files.pythonhosted.org/packages/ca/40/f9ff2d630ffce4e7dfea0b2288e1caf9ebbf9ff8a9ec9396136ce8b94935/websockets-16.1.1-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:42f599f4d48c7e1a3338fdaac3acd075be3b3cf02d4b274f3bf2767aedd3d217", size = 187148, upload-time = "2026-07-17T22:50:49.845Z" }, + { url = "https://files.pythonhosted.org/packages/b5/71/e177c8299f78d7cbe2d14df228643c10c70c0e86e108e092056bbcc16e46/websockets-16.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:dcc04fedf83effaeb9cce98abc9469bb1b42ef85f03e01c8c1f4438ef7555737", size = 187578, upload-time = "2026-07-17T22:50:51.619Z" }, + { url = "https://files.pythonhosted.org/packages/49/b2/b6987faf330f5af5c787a2610124c2e8403d51724f9001ec4fff6311fe7a/websockets-16.1.1-cp314-cp314t-win32.whl", hash = "sha256:8483c2096363120eea8b07c06ae7304d520f686665fffd4811fad423930a65d7", size = 179729, upload-time = "2026-07-17T22:50:53.269Z" }, + { url = "https://files.pythonhosted.org/packages/a2/6e/fbac6ed878dd362fbad7d415fa4f84d38e3e33fed8cde45c64e783acf826/websockets-16.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:bcce07e23e5769375158f5efdcdafa8d5cd014b93c6683865b840ed65b96f231", size = 180072, upload-time = "2026-07-17T22:50:54.969Z" }, + { url = "https://files.pythonhosted.org/packages/e1/ed/71fea6e141590cafc40b14dc5943b0845606bee87bdb52a21b6a73eb4311/websockets-16.1.1-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:820fb8450edddae3812fd58cbc08e2bf22812cb248ecb5f06dbb82119a56e869", size = 177185, upload-time = "2026-07-17T22:50:56.665Z" }, + { url = "https://files.pythonhosted.org/packages/01/ec/00e7eeca200facf9266a83e4cbbf1bed0e67fba1d4d45031d3e5b3d81b5c/websockets-16.1.1-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:125f22dbefaf1554fea66fc83851490edb284ce4f501d37ffed2752f418332d9", size = 177459, upload-time = "2026-07-17T22:50:58.197Z" }, + { url = "https://files.pythonhosted.org/packages/75/fd/5774c4b33f7c0d8f0c51809c8b3a93456c48e3543579262cfa64eb5f522e/websockets-16.1.1-pp311-pypy311_pp73-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:30bbe120437b5648a77d3519b7024ea09530e0b5b18d3698c5a0ae536fe0cc2e", size = 178294, upload-time = "2026-07-17T22:50:59.641Z" }, + { url = "https://files.pythonhosted.org/packages/37/c3/48e2c03d2bd79bb45948841c592d24156312dd5f58cdf8f549febe652fb6/websockets-16.1.1-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b6b9dadbef0cccd9f4c4ee96b08898afa73e26803bbe0f6aeb5bb12b0074206d", size = 179190, upload-time = "2026-07-17T22:51:01.129Z" }, + { url = "https://files.pythonhosted.org/packages/2d/3f/73e511ecf2496ceac57dd4ed8388efe2bcf0769338a2dbf242c8366ae87e/websockets-16.1.1-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:56cd5fc4f10a9ea8aa0804bddb7b42506cf9e136046f3b4c27de8fec9e2ecba5", size = 180330, upload-time = "2026-07-17T22:51:02.603Z" }, + { url = "https://files.pythonhosted.org/packages/be/4d/2d0d67834092e354d2b0498f014a41249a89556bc406cf86f3e1557bb463/websockets-16.1.1-py3-none-any.whl", hash = "sha256:6abbd3e82c731c8e531714466acd5d87b5e88ac3243465337ba71d68e23ae7e3", size = 173814, upload-time = "2026-07-17T22:51:04.184Z" }, +] + +[[package]] +name = "websockets" +version = "17.3" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform != 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/30/4b/4692be6d5bf739ed049b3813901c42091f8c054df89d5c089343823dea0d/websockets-17.3.tar.gz", hash = "sha256:1c7dd93a1c9f89297471493674b1fc1d9467cafd45374f2172213046bdb3a329", size = 188878, upload-time = "2026-10-19T16:58:05.813Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/b8/282f114a67886fccde02a77ff296501ad7fea25f4d696b2b1b337cbd27da/websockets-17.3-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:45cc1ccb12ced6d242335159e8221733c8696da5ad0b6ceef6debb0f5ce89110", size = 218223, upload-time = "2026-10-19T16:54:25.998Z" }, + { url = "https://files.pythonhosted.org/packages/8b/ba/8043c303aa60af053e092c1d667165f46d6729217ce2af795a23a3cd700a/websockets-17.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:46ae05aa1aecd47d4d7de0f05ce2d1d2eb418f8de614964d754cc3b9a409c400", size = 215908, upload-time = "2026-10-19T16:54:27.785Z" }, + { url = "https://files.pythonhosted.org/packages/21/3d/5d0eaa9b29db6c999a2cf749605141796cff21a5e235b2488bd39dcdcac9/websockets-17.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:43f270a5f21e12db08c73d83849a877c02ab7b7d0fb6e2718b5101d9c810212f", size = 216181, upload-time = "2026-10-19T16:54:29.267Z" }, + { url = "https://files.pythonhosted.org/packages/43/fb/33080a7b2d8427b343056eab32ba78235a4bfbbdc79b5593688c7b7c62ef/websockets-17.3-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:2d875224bac1a05a20acade268a7a0e3498e7f8cf890acb7c2b23bacd2bd3659", size = 225246, upload-time = "2026-10-19T16:54:30.807Z" }, + { url = "https://files.pythonhosted.org/packages/61/8c/d4220455cee00adb553c602ba4f1f6a47cd882d86dd9e5124679c0c95c75/websockets-17.3-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:5ad409b7ea102339041281117cf2dadfe71edbb653dc48037cc55d516fb7f448", size = 225517, upload-time = "2026-10-19T16:54:32.182Z" }, + { url = "https://files.pythonhosted.org/packages/75/a3/0ff8e4f0195884ae446844185e81bf7619673d816424b8a58bb5812dd4b8/websockets-17.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:56d43c311f3519fb1057b6114dc24e9060bc3fb6aedf4aa11160484154b66b63", size = 226751, upload-time = "2026-10-19T16:54:33.52Z" }, + { url = "https://files.pythonhosted.org/packages/06/cf/82c88e3fbb6a75a62b2997932664bccfe68256661c69144bd48020160cf1/websockets-17.3-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:a9eacb382f400bb5865e7e6d24bbe709a84510291e707f169dd4a24ee4a5ac6a", size = 230063, upload-time = "2026-10-19T16:54:34.855Z" }, + { url = "https://files.pythonhosted.org/packages/4a/e4/9131d3b73504902a83d10b1e1244319377ca72755351998ac9c408ba6ddb/websockets-17.3-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f09f145b89ea292cf6c25fd7c8c0d90207fd6a9e54c7828499669996a1e5bdcc", size = 227310, upload-time = "2026-10-19T16:54:36.248Z" }, + { url = "https://files.pythonhosted.org/packages/ca/b2/2208506afb45d181b0d6ccf377d9d79985fbcbf871af02ef4f7f3d405f5b/websockets-17.3-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:49fb5b4960ebe1bc557b435da8687deef1302a08f030a33c5606fa6fb11b773b", size = 226087, upload-time = "2026-10-19T16:54:37.583Z" }, + { url = "https://files.pythonhosted.org/packages/39/53/da73e3809f1d4e8c3346ca89a4bed7995de5708f2cb14c9359172a85f5a5/websockets-17.3-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:13cffaedde6e06183860fc92d88fe1d190abda73837fe4c14f5d4803c472f5dd", size = 223360, upload-time = "2026-10-19T16:54:38.91Z" }, + { url = "https://files.pythonhosted.org/packages/9a/7b/eaf828fd414401672e615570b9f2bfd84342b49c86ffb2ae735e4aada32f/websockets-17.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:ef2950896673a9809e8e5ab857525924fbcacfc98b858b0509ccf50d341f80f4", size = 226240, upload-time = "2026-10-19T16:54:40.294Z" }, + { url = "https://files.pythonhosted.org/packages/79/bd/4b6aa6e761c8d89aa6defdd83e40a6b2d9aa21bd01520c8e8470fe8d8681/websockets-17.3-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:2d08ca4bf5a9cdb6fd81b86b51bd5cfb10527d3a1199888f2b02cc6c6a3d5f80", size = 224833, upload-time = "2026-10-19T16:54:41.939Z" }, + { url = "https://files.pythonhosted.org/packages/37/a8/0a6aea08cad7db2c1aa53dbd3ece3ebc09e420e8301cb02f2b812a728a5b/websockets-17.3-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:5e0c0ed37472c4729f3001066510a656486f08f149dda1ebfd3dfe4450c9756e", size = 225599, upload-time = "2026-10-19T16:54:43.54Z" }, + { url = "https://files.pythonhosted.org/packages/1d/82/3998ea56beb079f43fc39dd5935ef8dc150f915bf2de8bd6ddcd50c0fae6/websockets-17.3-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:62059d739af7fc035ed6e63c5390118a60a5e9aa5a5541cd0486a83e741842c7", size = 226643, upload-time = "2026-10-19T16:54:44.914Z" }, + { url = "https://files.pythonhosted.org/packages/c1/a5/6568add8d0a2f37c5780c6de62b5b8ee191ca9d2d0b8ff2123b8277c41b7/websockets-17.3-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:bc6f87d03e3691154673aaa8f08991723d6e3394c83ef2875c7a9049eac9595c", size = 224223, upload-time = "2026-10-19T16:54:46.429Z" }, + { url = "https://files.pythonhosted.org/packages/72/79/b11bc05b0f64d8b14901443a4b01ea80d039cc68b260250b4cb488070aca/websockets-17.3-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:3d78d93846eddc990551c1c31914d90d71957ca3af468969826f7ed0d7d1d51c", size = 225255, upload-time = "2026-10-19T16:54:47.82Z" }, + { url = "https://files.pythonhosted.org/packages/71/f9/9a8902074db7044b64a05feff349e4f44144a961310d3419bab612f00dd1/websockets-17.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:2a377c7132b1e69be7a50d7434d7f26f69e93c70166ebb6d8f8cabf802ac4506", size = 225494, upload-time = "2026-10-19T16:54:49.171Z" }, + { url = "https://files.pythonhosted.org/packages/99/ba/7b873060ce6764207a24c10e81294739abffe2a90dc67c7f7db5042c596c/websockets-17.3-cp311-cp311-win32.whl", hash = "sha256:29b01520c39ef2f23c88b002f11e6ef4165675f6c92f5f3578fd587d69b5a5fc", size = 218720, upload-time = "2026-10-19T16:54:50.501Z" }, + { url = "https://files.pythonhosted.org/packages/28/11/7469f3f28513ec0d43f10b1c88bf970b0b6f0aa8190c42731954297e824c/websockets-17.3-cp311-cp311-win_amd64.whl", hash = "sha256:d338813a440bf6d2f0df55140d3f3080284410b1ebfe9df50e3847bcdb1a17bb", size = 219017, upload-time = "2026-10-19T16:54:51.843Z" }, + { url = "https://files.pythonhosted.org/packages/bc/fd/4724610baabbba94a44c5d1cf1b1a33ff77031e94a51addb0387c7f56b10/websockets-17.3-cp311-cp311-win_arm64.whl", hash = "sha256:6a8248b1ba8861e48e4c7ced3895a1264d2a3b617de72ec94172ce6e64bf16c7", size = 218950, upload-time = "2026-10-19T16:54:53.37Z" }, + { url = "https://files.pythonhosted.org/packages/0d/29/902ffe19c0d35603102f31490dea342f083bc77d8f8bcdc7d8b16f5810f9/websockets-17.3-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:41665c7ea01d3ae497a0c61fd22d3424230d18782a5fceb79f04db9ccb2042c9", size = 218250, upload-time = "2026-10-19T16:54:54.718Z" }, + { url = "https://files.pythonhosted.org/packages/f0/66/f56a2637b1aac263205b0e3cd7b2ff2e2f8b404b8118c991f4d122fd381f/websockets-17.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:8f7469408740cf06a79b01605f2ae0b2acc8839c03fcbbf05da49baee12d3302", size = 215927, upload-time = "2026-10-19T16:54:56.124Z" }, + { url = "https://files.pythonhosted.org/packages/22/7d/a27f25451c4cc62141992b51005688481210f3d3e63de3dc66f9e882ba59/websockets-17.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:d68da281ac208b6236ffa8beef23fe7c7c956d8bf09b421d447232fd94441b35", size = 216196, upload-time = "2026-10-19T16:54:57.538Z" }, + { url = "https://files.pythonhosted.org/packages/9f/77/40bbc1a5c016cf9f598dea21d1250a93245c995eafaec6401d0e4eb4e647/websockets-17.3-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:078d1d41f45ee34eed5a4f3bbe7c588caecbdd6e12dfca73e8c1b0e803773793", size = 225516, upload-time = "2026-10-19T16:54:59.104Z" }, + { url = "https://files.pythonhosted.org/packages/3d/9c/91889c8c62fb7d16cd58e3074473a259303d6229bf0ce496aec87e66f3dc/websockets-17.3-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:a7f391838e8adcf1f2fe71561d9e5a9f74ea7ffa5052eb2db329aac677383136", size = 225795, upload-time = "2026-10-19T16:55:00.438Z" }, + { url = "https://files.pythonhosted.org/packages/b8/29/2e5e2158e9920f806cd45f3cbc81cf5f3eef2b9e5a74b9ef049e2a3578e3/websockets-17.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c15a165673bb3fb57facbf040edf5c0556d20ccd2e0ccc5f23ebb69fb715fdc1", size = 227034, upload-time = "2026-10-19T16:55:02.065Z" }, + { url = "https://files.pythonhosted.org/packages/b6/af/fbab5c4098b26026b877bfc139b1ea0d7c6eaf7a86b84544933b4c445f82/websockets-17.3-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:28d1935c16782a1e3650c9baa79069b016fff739e292e4cb14bbb830d6930491", size = 229863, upload-time = "2026-10-19T16:55:03.415Z" }, + { url = "https://files.pythonhosted.org/packages/ac/72/d6e460a991607794072fe3fdfcb3221a0342af61586f5bd7ea40bddcfd21/websockets-17.3-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c534c9524a2acd0b97b7022074bec3784ac273c683cf9535087e437672ea8531", size = 227669, upload-time = "2026-10-19T16:55:04.763Z" }, + { url = "https://files.pythonhosted.org/packages/ec/8f/1c7da1cfb632e141e019cf2e0bbbd4e6dc8c198c8cc29544e4acf1a89f56/websockets-17.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b459d29c8b82a420a98fa0ce8e9cf787ce0062d98cc90604ef9574fb3cc26ff8", size = 226429, upload-time = "2026-10-19T16:55:06.112Z" }, + { url = "https://files.pythonhosted.org/packages/3e/63/c48ef8bbfbd982f2cfae1cfcf9e63f5bfbb8468fd37ca700507efc0b0007/websockets-17.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:53209dffd91b0aefed9ea630fa6ad5c2944d6210ba3a8a3a8664dc1575289b14", size = 223653, upload-time = "2026-10-19T16:55:07.473Z" }, + { url = "https://files.pythonhosted.org/packages/cb/37/7bedaad48ae8e89eaa4f3942c11be0c41de77ce2118a475f3ba05e9b5a0f/websockets-17.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:9662a9fe457820c60365b3209e03cbd8e4a817195d55de65a80fa680b4bea136", size = 226465, upload-time = "2026-10-19T16:55:08.791Z" }, + { url = "https://files.pythonhosted.org/packages/33/cf/ab9a8a0de4769ca1dce392021b6a922e21b4d3687fe9e1ab4db585a088f8/websockets-17.3-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:5670a762c7ae388bf8aa04199fd436180a4d28318dca9c1eae7b38604676dbfd", size = 225071, upload-time = "2026-10-19T16:55:10.127Z" }, + { url = "https://files.pythonhosted.org/packages/89/96/64d8460cec95f873c61c6d13a09b435915150640525ae56d5871400aec09/websockets-17.3-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:ed59cb4ee258674a6ed9b8515e42079db02cb3be94f133fdd3f200183a40c49d", size = 225841, upload-time = "2026-10-19T16:55:11.519Z" }, + { url = "https://files.pythonhosted.org/packages/a6/98/2b83211ee3087db4ae66533782664c0e283cf4a08cbb14036018d0803e09/websockets-17.3-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:0f78bb2e82fe88912c9d7b25c98e57a9b08655579af89f164fd4c0657a075d62", size = 226945, upload-time = "2026-10-19T16:55:12.85Z" }, + { url = "https://files.pythonhosted.org/packages/9f/fe/6b2a37d422d7f4dfc0c92c95a14649d9bd662243ed8b0774523ed2703604/websockets-17.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:71250e010eede33c1d638e2c7a98288520d67f782fd5eceecaeca3129233a09a", size = 224502, upload-time = "2026-10-19T16:55:14.48Z" }, + { url = "https://files.pythonhosted.org/packages/0c/c5/364015c9311c89ea6085d54c70d654c5d27ba05014d44ef9fd9daa09462b/websockets-17.3-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:729989759feb81ff6493879a0d60a0bd7d2eee41001bbec0381a080318439382", size = 225483, upload-time = "2026-10-19T16:55:15.899Z" }, + { url = "https://files.pythonhosted.org/packages/c2/b3/75d0cae8398816ed34a16a78252bfc8651f2f883cc5a568e1198395f15df/websockets-17.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:90d8c4fa5ba293cf92de351fbc292cdaadb1a1d58d031a1a97ff9b8fb6250ec7", size = 225761, upload-time = "2026-10-19T16:55:17.28Z" }, + { url = "https://files.pythonhosted.org/packages/f0/af/9a7c4b2e87f47a2a6a066acdc2157e9b7cb6222a224b95a432f54ae786ce/websockets-17.3-cp312-cp312-win32.whl", hash = "sha256:0824e6ecee838cc28e6481062574c7fde49f9a2cedfacd36f0e91cb4b37fd6fe", size = 218722, upload-time = "2026-10-19T16:55:18.658Z" }, + { url = "https://files.pythonhosted.org/packages/f7/e8/e52953a8280a1e51cb9307218443f68c8f4dc4b9952db6021d5c12d03c0f/websockets-17.3-cp312-cp312-win_amd64.whl", hash = "sha256:6644eecd99c4e8cdf72e646e17b391bb70b054f44becde37dcdc48cbec7e1527", size = 219024, upload-time = "2026-10-19T16:55:19.987Z" }, + { url = "https://files.pythonhosted.org/packages/85/a4/005eb7c1f5c1a249c1231a6ed83a54ada0b6b8ffab33a608ca20e3034ea0/websockets-17.3-cp312-cp312-win_arm64.whl", hash = "sha256:4a9133dbaedc6f1af358127275676171d9a1bb3e61f47ee62b2ff9acb78af3d0", size = 218950, upload-time = "2026-10-19T16:55:22.161Z" }, + { url = "https://files.pythonhosted.org/packages/ee/1d/c1f4a1c45c5ca2c35ae9fd7cac0e491f8a014c9a86933a5da7b04ff825cf/websockets-17.3-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:52a2ca6f401fb49a8d5d9e0e48ade5f58f1bdda33132907b0e4e3b702628fa4e", size = 218243, upload-time = "2026-10-19T16:55:23.851Z" }, + { url = "https://files.pythonhosted.org/packages/4e/e8/f1b47d0ced4964ae748931a54347fd27b06b62e8ea7837a9de3aee0c5999/websockets-17.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:80578e91764bfca297ddca322c00a3136d993b829e9839e7fa378a19c1fcc25d", size = 215927, upload-time = "2026-10-19T16:55:25.317Z" }, + { url = "https://files.pythonhosted.org/packages/16/df/ab0ed0445d8d81a133c8fed760f3b4f743a2f563804fdbecb2c32fe05d94/websockets-17.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:fe7a168d805c8a7bf1c2de55b7ab2bc958586bfd88d0e87235a92cac66b590a7", size = 216185, upload-time = "2026-10-19T16:55:26.678Z" }, + { url = "https://files.pythonhosted.org/packages/9f/51/b30fd6c5a33dac76a78083be125e3f9804f3d735da494ff03a46834f31f4/websockets-17.3-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:54fcd24944e6d127d198c28dc363967b7131ff0c97833962c2ef2048018de02d", size = 225574, upload-time = "2026-10-19T16:55:28.097Z" }, + { url = "https://files.pythonhosted.org/packages/1c/8a/8ede659919c0805d1fcc79c2ed16588d3419f1687c5117ba46f0217750ec/websockets-17.3-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:de2c12555bf05546f3ee75733f2c81de70aab7f530e86d0d2162b0ddcb3c39ae", size = 225854, upload-time = "2026-10-19T16:55:29.491Z" }, + { url = "https://files.pythonhosted.org/packages/a6/6a/e75d10e3896edc61320062890f71cdc0767dc4a54e2a26a943b703042d13/websockets-17.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c95d25b5382ee0e6191ecafdeabefdc1f7bff8dfee29239b9b79e760ef3b04bd", size = 227091, upload-time = "2026-10-19T16:55:31.146Z" }, + { url = "https://files.pythonhosted.org/packages/dc/d3/658f1e153566e5edae02812122d9f020c30785d8b53c4bda61b8e976f77f/websockets-17.3-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:8f244dfee05ea29b8064701880865eb1684f3a704a5665bd10b64694444dbbd4", size = 228526, upload-time = "2026-10-19T16:55:32.524Z" }, + { url = "https://files.pythonhosted.org/packages/28/00/002f95a02d721d8c6ec2676c5aee904a823838a9c205fc0b31eedd882a7b/websockets-17.3-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:2e99440ef446c7833690c1754e23b0188d440f3cb89812b0764c697a7880cb33", size = 227718, upload-time = "2026-10-19T16:55:34.085Z" }, + { url = "https://files.pythonhosted.org/packages/fa/9c/d36ec9499a62ec4e2a4eb570f93c6fcedd80ad5685e0f9d6866e8cfbbb84/websockets-17.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:26838e2d95d7004c52e8c7b6b51676c872093a3b55a497824f899116a15a8a55", size = 226472, upload-time = "2026-10-19T16:55:35.484Z" }, + { url = "https://files.pythonhosted.org/packages/36/5d/3a6d74e409f24ae4e8661a9d74d6645f71b3e91425a527c0e3f2e78bb15b/websockets-17.3-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:508775efa11d26aec186d10154359f52276e2baf9ca201b52356330883276dfd", size = 223710, upload-time = "2026-10-19T16:55:36.853Z" }, + { url = "https://files.pythonhosted.org/packages/e1/90/e08eb5d69b73cf5babf80922a8c964019b48339ce5c694a5d0c0f083c5a8/websockets-17.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:2789d203babb6ceb2770aadc2394c1f99263ec37fba57a93064f9a8ad899e8ff", size = 226532, upload-time = "2026-10-19T16:55:38.191Z" }, + { url = "https://files.pythonhosted.org/packages/c2/45/b1916efa1dad5af33beafe5c536810e1c80856b7e913f671c35031c57745/websockets-17.3-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:cfef7f7aa434a1e632e0ebda14b39f4f1d7975e0fce5c77ea7b43156fabf9bd8", size = 225129, upload-time = "2026-10-19T16:55:39.635Z" }, + { url = "https://files.pythonhosted.org/packages/04/c1/d427abb3f11e92f102f70f8e73addb767fc62c614565c0ee3f5657fa3551/websockets-17.3-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:39f532fa0d9026de4b9315a175998646112776baad54d55348435c11b05d034e", size = 225900, upload-time = "2026-10-19T16:55:41.033Z" }, + { url = "https://files.pythonhosted.org/packages/07/2b/462fab8e4b09eaa4eac2f40fcff8ee30f851aa40fb518efb0177262f6590/websockets-17.3-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:85d6daa3a7ca404570ae130babbeb347ef9d3faca5300fb13cfa4bb48c3d30d1", size = 227007, upload-time = "2026-10-19T16:55:42.314Z" }, + { url = "https://files.pythonhosted.org/packages/71/36/7404a4376021a0cc7ae9fcbdb1196c0c8aa48df4fd370c185f4f5b677bff/websockets-17.3-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:ce39283ef08b0f28478e920d4d89a1fc169176e568e8a6a821332673145522eb", size = 224565, upload-time = "2026-10-19T16:55:43.93Z" }, + { url = "https://files.pythonhosted.org/packages/c9/5f/b8ada5787d11e6edbf58e2d680235fb3b2fb3298991cc310566f4d6c2fbf/websockets-17.3-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:23046098ebf844753cfd211033624a8247520e5bf2194c24cb1a8c222917acff", size = 225516, upload-time = "2026-10-19T16:55:45.398Z" }, + { url = "https://files.pythonhosted.org/packages/23/1c/0533f760237ac6604efd0bf98c18ea4c1381f2cadd8c8d0b05faecb07a80/websockets-17.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:724224d4c457207271239114bf43afafc3eca4a1b4661ccdd428d11869a03bbd", size = 225797, upload-time = "2026-10-19T16:55:46.989Z" }, + { url = "https://files.pythonhosted.org/packages/97/b4/0e580e8f96197130ebdb32b727e9c891594c930be30d8a9de9aa0bbb7e2c/websockets-17.3-cp313-cp313-win32.whl", hash = "sha256:5af7070d80d278832cbca9c3c3dd44b30a26dcfa3ae1e0f6f19ff34edc27b689", size = 218712, upload-time = "2026-10-19T16:55:48.379Z" }, + { url = "https://files.pythonhosted.org/packages/7d/6c/db5c907d1cbea84444bc759ff63db97fc586988d11a34d5565e8b50080fa/websockets-17.3-cp313-cp313-win_amd64.whl", hash = "sha256:66027e401c70d0cf55021b91b8a7ec2cd5810e20602f945b4fe6ae8b37ed232b", size = 219026, upload-time = "2026-10-19T16:55:50.688Z" }, + { url = "https://files.pythonhosted.org/packages/f1/d3/30f04bec5b9cf0c00c98c038494b210ece923a0b05b6df38a162b759e5ed/websockets-17.3-cp313-cp313-win_arm64.whl", hash = "sha256:6b14914e67044724c31a9360c7b89e9d070117c630746eefdc1620d967545acd", size = 218958, upload-time = "2026-10-19T16:55:52.085Z" }, + { url = "https://files.pythonhosted.org/packages/27/ad/f65e365bbf38d61164b0c2f64776fc7714bfa59ac51e492b038a35f4ab1b/websockets-17.3-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:bc8fd230ef013951900c1fda100eebe4a4b1b407dde2a44186995042dda2c628", size = 218288, upload-time = "2026-10-19T16:55:53.387Z" }, + { url = "https://files.pythonhosted.org/packages/48/1c/33271eba53b4927a1b91d99d838a6d7b888e6f708425262c911450d73696/websockets-17.3-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:cdb8e4b0f6a41b857c74c03116e8ffbef59ef8e533e934b532843178990d01d5", size = 215977, upload-time = "2026-10-19T16:55:55.063Z" }, + { url = "https://files.pythonhosted.org/packages/3d/f3/6d982c60f6c7c95e5faed53d39263df273ecfda904c7d6920c37eee58dd1/websockets-17.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:018fab26140ce221c3853454a608e4e7004f4f10641cb97819dcd5b917bb2e99", size = 216193, upload-time = "2026-10-19T16:55:56.424Z" }, + { url = "https://files.pythonhosted.org/packages/ff/c6/4ff6b8d2a4b32719d4658bbd791ee9d19939a47a69b961c961fd9dc3a64c/websockets-17.3-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:dd0f3037d501178a761fd2814370aca547f79e99a200a61a1f6e7b79ec3d78b9", size = 225573, upload-time = "2026-10-19T16:55:58.252Z" }, + { url = "https://files.pythonhosted.org/packages/eb/8f/46e4030947f5590cb61832901f44a3edb07ef8d1e27f6c06b42c5f1c4d33/websockets-17.3-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:8dbb3862aa649de95660b6337d97101977f160b5b354d07b82fe309874d2c8bc", size = 225927, upload-time = "2026-10-19T16:55:59.561Z" }, + { url = "https://files.pythonhosted.org/packages/f0/1b/3db30fdf4fbefa4ac463060d3f87e2d444f960aa1234028468c09b88bffc/websockets-17.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:af37a1e6b6bd506b597d5fb4cf111fb527d1b2223608a5d441d4738827cfd166", size = 227169, upload-time = "2026-10-19T16:56:01.029Z" }, + { url = "https://files.pythonhosted.org/packages/02/ed/849799cfc0e3e359b75ca1d50605376da52dc9ef0b2a53931e3f5991f96e/websockets-17.3-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:740bba4223fa5216d4d6c5dcd29e697f37229b8a61b69e1a50527b0ea993ab2c", size = 228542, upload-time = "2026-10-19T16:56:02.377Z" }, + { url = "https://files.pythonhosted.org/packages/19/53/dcc397e20ce792fffd9a8f79b6333275748ee7a23f807e576166a0b16edd/websockets-17.3-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4170556762c6fd2913d99dfdd8dbb4c927584899df7facb1034627e355263c45", size = 227772, upload-time = "2026-10-19T16:56:03.768Z" }, + { url = "https://files.pythonhosted.org/packages/c9/36/e5935782f71e9e22247b2a2e562da05e18d8945c49f2692ca1bdaceec178/websockets-17.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d355b22270be8062360b9df2ee0b10277590789a1059257916fb9e256a0cff80", size = 226518, upload-time = "2026-10-19T16:56:05.332Z" }, + { url = "https://files.pythonhosted.org/packages/27/76/bd5978a1e403fc646230cf35cf7c06b40b3a232d440881b9e89ede229b18/websockets-17.3-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4aa85b34c21cf97b3470793d0bf0763d32bfd1e67b83067a0a3ba8dc3474dacf", size = 223766, upload-time = "2026-10-19T16:56:06.703Z" }, + { url = "https://files.pythonhosted.org/packages/da/87/c66eb39bd851d5c14d9eb75aa64d03cfcf2ded77927ca067b5917291d19d/websockets-17.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a0e2e7c2c1a4f25db7b6596738d810c10732e77f852247300a1bc49e364d6dc9", size = 226644, upload-time = "2026-10-19T16:56:08.198Z" }, + { url = "https://files.pythonhosted.org/packages/fe/ae/b9a31d5497fa0b73629a097b173a26123da2ed656b562114644bc623414b/websockets-17.3-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:7fa69212ea60ea24e2d8aff23fe102b1f87f1b27a320f92d2e7b3468997a496a", size = 225107, upload-time = "2026-10-19T16:56:09.627Z" }, + { url = "https://files.pythonhosted.org/packages/61/0c/b773a102f84b60b2052b2cfde773d2f3cd3e8eaa93a145f54450460549cf/websockets-17.3-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:80a6e37e235780f189558ab804f3cbc01c18f5c578995739b49613d544d34ebf", size = 225891, upload-time = "2026-10-19T16:56:10.973Z" }, + { url = "https://files.pythonhosted.org/packages/b2/fa/e7e538575dd4912dea9ea4c9ae86519aa1420969d9cb5cf02fd10fd20ba7/websockets-17.3-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:628efe13630ac3397e7d1278b6be6f22f37a86d638a324334b4cd43c1daf9928", size = 227064, upload-time = "2026-10-19T16:56:12.295Z" }, + { url = "https://files.pythonhosted.org/packages/28/87/bf2b928c156deefd0c50285a48fc985e2ca85d284e7d9981cc5b79b0e696/websockets-17.3-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:443fa28652682d2a3ec3eca49af1b87cb2523561257683e62e03a98967b22138", size = 224618, upload-time = "2026-10-19T16:56:13.73Z" }, + { url = "https://files.pythonhosted.org/packages/8c/9a/d59817ba3535f787c1cf8990a01b3d2896a7d9d8f3b5d55bed22fce595a6/websockets-17.3-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:6705af9d1005127302c04d9f1533ba56e289336c465923ef878430e99295a0b9", size = 225571, upload-time = "2026-10-19T16:56:15.199Z" }, + { url = "https://files.pythonhosted.org/packages/a6/96/8210379dac889e16c75099aefffa200dc55dc8cb030010f309a7eb9c75c1/websockets-17.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:9bde5d82d7ac4859e0cb3a35e148f537a8d4e56aa43f42582b5f263982f095ae", size = 225869, upload-time = "2026-10-19T16:56:16.569Z" }, + { url = "https://files.pythonhosted.org/packages/97/0b/d4741c977fec9e6482beffece572d544d42d230f56fc3ef504f96521063a/websockets-17.3-cp314-cp314-win32.whl", hash = "sha256:be7be57097a65a8fab3d0f0a10d12931deb626a7d8082eb732b1ae41f3a202e3", size = 218232, upload-time = "2026-10-19T16:56:18.028Z" }, + { url = "https://files.pythonhosted.org/packages/33/69/2f9ce899776d0c522f7f44080cad4228a1c14ec13b0125a2efc12ebe41c9/websockets-17.3-cp314-cp314-win_amd64.whl", hash = "sha256:2b06213c8e1ce93b18d0476d7a5e647436c8f23d099888c9065e930e80f4bed5", size = 218582, upload-time = "2026-10-19T16:56:19.399Z" }, + { url = "https://files.pythonhosted.org/packages/4e/e9/11b885666d72add674440a3435c059bea325616959cec8be42605948714c/websockets-17.3-cp314-cp314-win_arm64.whl", hash = "sha256:6b7b540bb321f7f0a7b8f5d107f941bb361e3a154c0b594dae0394997b91b743", size = 218465, upload-time = "2026-10-19T16:56:21.005Z" }, + { url = "https://files.pythonhosted.org/packages/c4/0e/0c0f40ab8eefe9d5a6c78b4e267d8e37d70d3db8dd195574e0ab867e4f81/websockets-17.3-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:c9d06edfd974e918b40e0662a7e76dac13125529ee5ec9fbe42dc0d6faa209c3", size = 218614, upload-time = "2026-10-19T16:56:22.457Z" }, + { url = "https://files.pythonhosted.org/packages/1f/93/d22b3d63aa439bc01a9477880070d05e0b257b0548294786a33be3e842ec/websockets-17.3-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:0a0bcf66289b9d017c175562c35c5304b5cc3ed56aded994ae30b0a9654ba405", size = 216151, upload-time = "2026-10-19T16:56:23.95Z" }, + { url = "https://files.pythonhosted.org/packages/b9/92/f60a9672cdeb8cb4f7156e6e83c76d59fdc586737a97ac77129e9fc188a2/websockets-17.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f3ed747b7651668131029c720fbc32c7ee2d129bdad200e6c8f4037b20f7913a", size = 216354, upload-time = "2026-10-19T16:56:25.251Z" }, + { url = "https://files.pythonhosted.org/packages/9d/da/2be8c5f3c6612d4523f95b074e2352bc11bd090cf121d32bc11af1d52e70/websockets-17.3-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:5868a02c4f6d698ddd19b4c9742748c03dec045289915806845189d96bc3d314", size = 225937, upload-time = "2026-10-19T16:56:26.726Z" }, + { url = "https://files.pythonhosted.org/packages/85/1c/cb84aec871840acd66dfa84520bf7b8e48ce70bdb3f4baa4efd097fbe6b1/websockets-17.3-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:fa87ea2ad64e59fe5622c1dc5716106b6d6e7e4b26b848cb5f5710a75c292ef5", size = 226215, upload-time = "2026-10-19T16:56:28.1Z" }, + { url = "https://files.pythonhosted.org/packages/9b/7b/cfb65557accec2eda2c80288e13eca6f1c797c579375906eb73f4053cfd1/websockets-17.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:65e937576141ac50fac32fa9736dbb3e0e4a7769f91be004011a09216c6ab05f", size = 227389, upload-time = "2026-10-19T16:56:29.518Z" }, + { url = "https://files.pythonhosted.org/packages/70/a3/7e08ec4b23e376ed228831aa44b2f2a3f2e7025cc66dda4b2e53dcc2619e/websockets-17.3-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:35381b575f70a08d4241e73c0cde4672bb9b2a9aae8767ca6b7fb61305a052c8", size = 229534, upload-time = "2026-10-19T16:56:31.072Z" }, + { url = "https://files.pythonhosted.org/packages/4b/7d/8a813e3e53956f876cfaad4f6358625bbd94168aa8046c44e2f3561f12af/websockets-17.3-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5142798871a248b422f353e0684d51dfa119de3403a6fa0904b7cb806d9790ce", size = 227959, upload-time = "2026-10-19T16:56:32.656Z" }, + { url = "https://files.pythonhosted.org/packages/41/23/5f3dab6ab44f2f30042db83a658a57129d5e3c0425c798b3c3e727bc060a/websockets-17.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:e164c4a6868d11988c7f2386e3278ccff21c665cd7d08279b62709dd37a3167c", size = 226691, upload-time = "2026-10-19T16:56:34.101Z" }, + { url = "https://files.pythonhosted.org/packages/5b/49/99a3fb5a2e94d677fbd0d014a6f9a56a3d2b8e8007b7175727bc4fc4ae94/websockets-17.3-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:10b24e836ee0233ca078e1244f6ba40343a22127a9a736f46a7e7b18de2cc711", size = 224225, upload-time = "2026-10-19T16:56:35.452Z" }, + { url = "https://files.pythonhosted.org/packages/6f/e5/f503a4d757858d083c90ea85dd1fd636ae9eb63c9552c75a4c38514ee7ed/websockets-17.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:56a76556ab04ab54a675acce2cac8b4e74ea2cec558a7c9ed37e0367b04b5d50", size = 226984, upload-time = "2026-10-19T16:56:36.887Z" }, + { url = "https://files.pythonhosted.org/packages/4a/a6/8586844ad4b21988837624e1f4b331bc71919c85a6eb1ee3c8bd29893f27/websockets-17.3-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:33221e49be79d7bfe6d12bc52ef9458b256ab74fa8ac5660acfa3065de1c7870", size = 225436, upload-time = "2026-10-19T16:56:38.213Z" }, + { url = "https://files.pythonhosted.org/packages/a7/b9/f419506494d6ffd205a9c3258f56ff5aeae6976de26361057de74f4ab659/websockets-17.3-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:2fa79b9a48ae59744316c71a34cb9f76f30c93e117338522c5135cb7eac10351", size = 226325, upload-time = "2026-10-19T16:56:39.606Z" }, + { url = "https://files.pythonhosted.org/packages/28/c5/55a58faa67149e84cb98b33f9d8fda95242677ea07b78f3ecaf2e77877d6/websockets-17.3-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:f87f02afe05c1c246012e3de100a77cfbabd17db709fe93cf074271ab239b312", size = 227342, upload-time = "2026-10-19T16:56:41.041Z" }, + { url = "https://files.pythonhosted.org/packages/35/e0/fbe561dff24b6ef1b2034877f37b56eb9b81b3c103e2a8b03819bf2b3b6d/websockets-17.3-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:8135a549e27e9941a70e2d2156676ef2ffeff4b06e9d564dbaaae963482afdef", size = 225036, upload-time = "2026-10-19T16:56:42.433Z" }, + { url = "https://files.pythonhosted.org/packages/0d/37/d80753064f8370a24d3bec74807c3928d7b0ebef5381956e2a0108b365c2/websockets-17.3-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:ace8dd1efa5f44c482d091aa38322e20e3ffe5adcdba6b67ad9f4e7da58f3f68", size = 225807, upload-time = "2026-10-19T16:56:43.774Z" }, + { url = "https://files.pythonhosted.org/packages/f1/9d/a11d3168522a2959c4a5661728744d62b9eee344abdba5f9fbc1d359742f/websockets-17.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:2129c9a5fc05a230ce088745a790af073e582b584badc7b05db067ee326f56d7", size = 226241, upload-time = "2026-10-19T16:56:45.088Z" }, + { url = "https://files.pythonhosted.org/packages/06/28/16107b3b83fd2b5024bfecf8d000140f555204a0191202f9c4c981137810/websockets-17.3-cp314-cp314t-win32.whl", hash = "sha256:af7c474f0d8f4d2a196370e85033873c7b063a0b5da9a4f143aa023e3bd25407", size = 218365, upload-time = "2026-10-19T16:56:46.41Z" }, + { url = "https://files.pythonhosted.org/packages/77/dd/8b00e1dd552788d8c7762d7ef61de8f2f238d7357b1a02d4c4650b112196/websockets-17.3-cp314-cp314t-win_amd64.whl", hash = "sha256:0c63ad657695e8f1a48624754cb6b464118ac50d4c1d477c26461c98390f0a62", size = 218706, upload-time = "2026-10-19T16:56:47.754Z" }, + { url = "https://files.pythonhosted.org/packages/39/eb/5d90d57a5cbe614b2f13433aaf1c0b068c804589379061ba06812a185a89/websockets-17.3-cp314-cp314t-win_arm64.whl", hash = "sha256:3c4f631dc8d00e470cde3ec0a35d4b58a817bea592411956f1cf4099dbb306b3", size = 218622, upload-time = "2026-10-19T16:56:49.07Z" }, + { url = "https://files.pythonhosted.org/packages/6e/41/1efe5ecae1f32495dc75641704f959bd2d8e56cdc825f3acc5e010a51960/websockets-17.3-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:f300f28dff74ff4148c21e6971e4de6ca0c34e0086a3d95c017c5174ebf85ca5", size = 218211, upload-time = "2026-10-19T16:56:50.423Z" }, + { url = "https://files.pythonhosted.org/packages/01/ec/4edb653533241203db3f11522e122338d4fda50a41ce2a542029086f8eda/websockets-17.3-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:32029441af953e980b9940f042b337fe4ad9a97fa8b17a4ed878ec67b5b89ef4", size = 215944, upload-time = "2026-10-19T16:56:51.766Z" }, + { url = "https://files.pythonhosted.org/packages/d5/b9/ec450b9650925dd5cf27c1f36d0464786fe3ac702ed656879c4c0dd5c4df/websockets-17.3-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:09f007b2150eff015b2109f006e2ac2012d376f41486defa88ae78a776b00cff", size = 216164, upload-time = "2026-10-19T16:56:53.125Z" }, + { url = "https://files.pythonhosted.org/packages/15/1e/63f7fbff9f0540a0331f1a62424c9ff24faa6ba8aec264f55e9e31017eea/websockets-17.3-cp315-cp315-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:7bdc658c9474864893e0b6b94f1390bf6a912952df1870dd93bb7d1a902b5628", size = 225608, upload-time = "2026-10-19T16:56:54.442Z" }, + { url = "https://files.pythonhosted.org/packages/0c/1b/f6679ad61cb8c110033a1b30d561d5c1052983e202157251ff1778f27932/websockets-17.3-cp315-cp315-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:15decc0fe293d9e3f924bd483f3d76f3d0ff26845112a470e3f8842fec2c82a1", size = 226042, upload-time = "2026-10-19T16:56:55.727Z" }, + { url = "https://files.pythonhosted.org/packages/28/c6/ed993aaef8046cbbb939ae367ee3dd5383dbd055f0500a5b8aed101168b6/websockets-17.3-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:997617dd7856c5dad742bf6893b872319156dd43f47587541a59e4a852d52bbc", size = 227203, upload-time = "2026-10-19T16:56:57.076Z" }, + { url = "https://files.pythonhosted.org/packages/aa/96/7057dc71affe6c8252df8648f5a225642228a6fdd8d046a6b9aa1fb0e9eb/websockets-17.3-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:a004c1fe5a72c496f28c6c1d8c2dc5cfe3278d99478e18f8b838c70a912b366f", size = 228900, upload-time = "2026-10-19T16:56:58.633Z" }, + { url = "https://files.pythonhosted.org/packages/43/e3/8b3268bb7e72b465e55172b86d55f58aa277fb6d9bac92aee615345874df/websockets-17.3-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:35fe35d20baa661cef4a12ee7bc42eaf2376d43ef9816ab29dd47ca957f7a73a", size = 227684, upload-time = "2026-10-19T16:56:59.975Z" }, + { url = "https://files.pythonhosted.org/packages/59/15/fa31c0a12240b1225c3712ff080d2f7ede4f695ca90e59fdb58e8affabba/websockets-17.3-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8b3bede7d583bc9f47d8693a29984882e59077db1a5238ad977fc70ae8169741", size = 226580, upload-time = "2026-10-19T16:57:01.371Z" }, + { url = "https://files.pythonhosted.org/packages/22/b5/75d911c206a3035e2ecfad107878e62c06e574b2437fa2cfb4ecef436fa3/websockets-17.3-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:dafbb58a149d1ebd5767b3f064f911c5ee0897608005e51c3904b0ada2a8d99c", size = 223967, upload-time = "2026-10-19T16:57:02.839Z" }, + { url = "https://files.pythonhosted.org/packages/0e/f8/f98aa36f611acd5770819f6690125c20d55f221fd6db8d00d284b5f78e89/websockets-17.3-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:80326bc571164bbbb6bead2e35d0c943b23b24fde629032197c58151529d24d8", size = 226689, upload-time = "2026-10-19T16:57:04.458Z" }, + { url = "https://files.pythonhosted.org/packages/1a/36/d52f5dff7597de6fbfc26c3d126abd668137915719aebf97abcc3be77eca/websockets-17.3-cp315-cp315-musllinux_1_2_armv7l.whl", hash = "sha256:7d53fc4b90ef6e11de639dc18744d9be8cbd70ccb5ce80027aaffe7b1ab0215a", size = 225353, upload-time = "2026-10-19T16:57:05.857Z" }, + { url = "https://files.pythonhosted.org/packages/d4/10/dcd70ad9f9cd20e8af43284ac250af610e8bf9022da25f5b409153d033b4/websockets-17.3-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:fdd00937f15f5f93c8e53d8060a8c4c010431ab595a9b5b50ddd569a04603944", size = 225879, upload-time = "2026-10-19T16:57:07.249Z" }, + { url = "https://files.pythonhosted.org/packages/70/ab/f26c6bfa99d38ca3d1bf23145306d97c5d0c75e133a8d837373e4b3d4629/websockets-17.3-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:1dae5cd6c92d4440b15f20aa2987baa73c47ea14baa0fec8536a542e82e0ab33", size = 227031, upload-time = "2026-10-19T16:57:08.817Z" }, + { url = "https://files.pythonhosted.org/packages/d7/3f/c8fd74cdb526cc65295b7468f2f84ba16678646d8174288822f99f510274/websockets-17.3-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:b225c656efa2dedecc81651d2290170af25887b7de4f38c5efc7c5ae2b9442ab", size = 224842, upload-time = "2026-10-19T16:57:10.298Z" }, + { url = "https://files.pythonhosted.org/packages/c4/c5/b3a07ce1c54fc0f5441642f5352662b90d7e658c966730eaf6d78a5f20bc/websockets-17.3-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:bd645b5d2f810a181c44f4a71135e7c365b44f4be9ed3d1892635be13a857553", size = 225744, upload-time = "2026-10-19T16:57:11.615Z" }, + { url = "https://files.pythonhosted.org/packages/66/37/8321a8a6ab0215d4df0238e49ace5f539364cf337bb122b85c788e8c93ec/websockets-17.3-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:d2605a3b2af8d66f8b75312d223642c065ec773446c04566d9030ad5e2db13c9", size = 226006, upload-time = "2026-10-19T16:57:13.049Z" }, + { url = "https://files.pythonhosted.org/packages/f8/04/8c457a7e6a260b673bf4e6f2f422eb4af5f11c48505748359706f24f1bef/websockets-17.3-cp315-cp315-win32.whl", hash = "sha256:82e60c00cfb8493a5ba27cdf9b3695fdd153f666f73e11f18968f78ead1d8705", size = 218196, upload-time = "2026-10-19T16:57:14.41Z" }, + { url = "https://files.pythonhosted.org/packages/a0/7c/c2df129d9e344b99bb388bcac54fbbdfeec29e6c716c12dc9a3398757940/websockets-17.3-cp315-cp315-win_amd64.whl", hash = "sha256:4d5f2492cb2192aab2d42e57f2caa2159b4fd20fde06f859ec13354f524b176c", size = 218490, upload-time = "2026-10-19T16:57:16.234Z" }, + { url = "https://files.pythonhosted.org/packages/e6/4f/721b778c85559b2949e46246838e31a346dd815b3cdd8460fe517235675a/websockets-17.3-cp315-cp315-win_arm64.whl", hash = "sha256:55494475206113dbaf731dc8c5ffd5e1094175b753b7bbaad09fe3d7df61165c", size = 218403, upload-time = "2026-10-19T16:57:17.631Z" }, + { url = "https://files.pythonhosted.org/packages/b3/28/241d9ebb4dad79346b5a6abf9f14d7685b12ca358d250eea4920cdb1caf3/websockets-17.3-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:23cb6f6d64e3a389bb8ba150f947f9a6c8c0aca383e814ca3c5cffab738d5646", size = 218523, upload-time = "2026-10-19T16:57:18.978Z" }, + { url = "https://files.pythonhosted.org/packages/b0/bb/559fe539992102c66cbca38b488af6c7b184ab7736d819afc0f72268a2b4/websockets-17.3-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:f27e7e8a85512b6a4b490d5756edde8e6772883a5800e1476172e44eda3f7d7c", size = 216103, upload-time = "2026-10-19T16:57:20.412Z" }, + { url = "https://files.pythonhosted.org/packages/34/ee/e8ade4f13a3d0da68636fe44bb8ac1a3e36fc57070512788320dead42067/websockets-17.3-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:6342f79d6f50e680c8aa59e0615d745e867e51ffd59c77093be60b7c433067af", size = 216316, upload-time = "2026-10-19T16:57:21.761Z" }, + { url = "https://files.pythonhosted.org/packages/4d/06/4812b2a7a5e6571d9be425e76cf54ee69aaa15720caa02307785aa5b19a7/websockets-17.3-cp315-cp315t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:fc23e72bd7f8a8e540fed2244524d0a9aeb6ae3325f3d56f04a7a3debe5b04c2", size = 226467, upload-time = "2026-10-19T16:57:23.077Z" }, + { url = "https://files.pythonhosted.org/packages/d3/e8/adfc05d7f9b6b0cce6cc554426c50b7058609119b6b84a39171fe5ed4e50/websockets-17.3-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:722ab747ff5dc28070b1a8c020dba6466f13f2ab56bc251ad301fefa2454aa1e", size = 226736, upload-time = "2026-10-19T16:57:24.419Z" }, + { url = "https://files.pythonhosted.org/packages/96/b2/d5b93dd933552554507edae9e3a4890269a8ea8b46019450ea9c8a30e7cc/websockets-17.3-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0d20d6ea5aabbeba2e054d33e405192ef75dc12947bbd00ec97d23b14969d325", size = 228065, upload-time = "2026-10-19T16:57:25.908Z" }, + { url = "https://files.pythonhosted.org/packages/10/37/642f0f1cf1c4814147a4f0586f796a0b38e42b69e5a296bfc270fb660051/websockets-17.3-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:90cc9973c51811918247a78d9ab2f54871296e4e37e69a98aba4d3c9acedbf62", size = 229692, upload-time = "2026-10-19T16:57:27.63Z" }, + { url = "https://files.pythonhosted.org/packages/5b/33/eac81cf62ac394b61db6a27ccbe8fb9ae382016ef73ede1edf9242a6a43e/websockets-17.3-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:63b87c93e28957e6dc2bb92d31727a863c9bf4a4daa080f0995fdcb0242c9166", size = 228503, upload-time = "2026-10-19T16:57:29.031Z" }, + { url = "https://files.pythonhosted.org/packages/0d/84/e057788a9bd056f4f7d3a06b59efaaf724bbc6f2d1e1d316f8a93c951abc/websockets-17.3-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4f7431e71072962d3ed1768038200aa4f1e76d9c2d7bedd554d57a55faaf6644", size = 227379, upload-time = "2026-10-19T16:57:30.571Z" }, + { url = "https://files.pythonhosted.org/packages/fa/a7/cca1f9f45b893bb5b7545f2b234f910e07fcd2f8065724ac1a62a0961be2/websockets-17.3-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:534ed583fd4323de45d196535a444cebd1af2105e6e4e0cdcbf8cea266a8747a", size = 224719, upload-time = "2026-10-19T16:57:31.895Z" }, + { url = "https://files.pythonhosted.org/packages/1f/a0/5d07451027150c802ce4c9999e86994a3f0de5f4dbe3d1cce46995999269/websockets-17.3-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:8879b6a4040ee925c638548238ab7fe612cf5fa8752fe847346da0da8be81c3f", size = 227564, upload-time = "2026-10-19T16:57:33.236Z" }, + { url = "https://files.pythonhosted.org/packages/62/90/835f37e13fac0c615a700caae0d39deff1de2d2b9b341836a786f9b359e0/websockets-17.3-cp315-cp315t-musllinux_1_2_armv7l.whl", hash = "sha256:58e5d1e935a90878a935c7d2737a25c71cf4f1c13b6e6bef454ab722c4f338bb", size = 226218, upload-time = "2026-10-19T16:57:34.876Z" }, + { url = "https://files.pythonhosted.org/packages/16/8a/718639939b947fe715501e8073350fd3f8a42f8b5eba3c0c2389c5836513/websockets-17.3-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:0a657b51e4a5f4ac577c11e706ff9a884ea5aaf3e2666bae283a251c63e66acb", size = 226712, upload-time = "2026-10-19T16:57:36.248Z" }, + { url = "https://files.pythonhosted.org/packages/e8/45/6bef8572b9b0dee51369b69776af1e4c7cc3a807f199dc3c165bbcf1199a/websockets-17.3-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:411aa0fb234f42a1444dea1e177890ddfc577b36ffdfafec25cb0d2c818e1af8", size = 227819, upload-time = "2026-10-19T16:57:37.586Z" }, + { url = "https://files.pythonhosted.org/packages/f1/3f/3b726d0b46a132e641d2d8c0243ea8a7d39464dbaf28c7a206e51fbae681/websockets-17.3-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:623d4b44f64efdf235b1e8dce266057073d93cde6197e7d7684f20c297f67f30", size = 225573, upload-time = "2026-10-19T16:57:39.285Z" }, + { url = "https://files.pythonhosted.org/packages/90/96/cd972a12e1412d9b42c42ef42efbd81aa396ca9408d982d524012f011a8d/websockets-17.3-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:5d0c871efc696ef5eb8514df64b86ab28736db753ebb42a2101f3b562f4849c0", size = 226430, upload-time = "2026-10-19T16:57:40.915Z" }, + { url = "https://files.pythonhosted.org/packages/7d/2d/e11524771588188a39f6da234779d4942496b96c5a10b92f3df30db48608/websockets-17.3-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:1db2604e6aedb7a2cb2f6e0575d6c9a852ccac8239703a930ac83b63309177a5", size = 226728, upload-time = "2026-10-19T16:57:42.245Z" }, + { url = "https://files.pythonhosted.org/packages/17/9b/63722aed973f53ea579e1ce0c4563a2b8b536629e556feff26e4c6a2a60d/websockets-17.3-cp315-cp315t-win32.whl", hash = "sha256:07246d4f0293ef0b87eff3d7dd88c1f03dd9f678fa39f6de87b2af8504e7e0de", size = 218325, upload-time = "2026-10-19T16:57:43.585Z" }, + { url = "https://files.pythonhosted.org/packages/34/07/5e0c92e225546f1789c957c0383852797be7c899b07207e9b6eb4a93473f/websockets-17.3-cp315-cp315t-win_amd64.whl", hash = "sha256:856bbb24f2ee6436af7609267e73309e4bb0a0f9982f79f1c2e01019279c6671", size = 218641, upload-time = "2026-10-19T16:57:44.918Z" }, + { url = "https://files.pythonhosted.org/packages/d4/e4/339663de65c44ab3eb5209890e86eed26e1a131d6afab3df6f1c3e5b4d8c/websockets-17.3-cp315-cp315t-win_arm64.whl", hash = "sha256:a22c4956a4d858200dba83f0691bb692d77b0eeddfca80157820d20b85dea4f1", size = 218564, upload-time = "2026-10-19T16:57:46.332Z" }, + { url = "https://files.pythonhosted.org/packages/e1/f1/b462b1518779adf0b6fce305beee07357a79cf0724bbe61113ed6521882e/websockets-17.3-pp311-pypy311_pp80-macosx_10_15_x86_64.whl", hash = "sha256:34c78052277053bcb09810ac8e9ba4029f9e3e277833fc18ec1c928a6246ac91", size = 215839, upload-time = "2026-10-19T16:57:47.742Z" }, + { url = "https://files.pythonhosted.org/packages/a9/59/7dcea408892967516cc00d491ee7bba48577059c6eb0811f436b720bcd98/websockets-17.3-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:ef07e0b6b879f699a16fc7a513b974246fdeaef44908a021130cf4afe6a1c89c", size = 216114, upload-time = "2026-10-19T16:57:49.111Z" }, + { url = "https://files.pythonhosted.org/packages/c6/b7/2d447e461f1160dc8dcdd8b143e2adba54d402e5f828eeb1f8469970c937/websockets-17.3-pp311-pypy311_pp80-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:99c5637b74e2805ee4de9e2a43c8b45f678e50abb1c2da9880f0372f6498ba2f", size = 217065, upload-time = "2026-10-19T16:57:50.424Z" }, + { url = "https://files.pythonhosted.org/packages/01/51/35aa5edd12b23e0001b85517ad447342c07a29fcee62009b0859825b77a7/websockets-17.3-pp311-pypy311_pp80-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2c460aeb12c2bd1c204944d9e9199595bf9e505eb542018d304bf9e63cb60cad", size = 216952, upload-time = "2026-10-19T16:57:51.72Z" }, + { url = "https://files.pythonhosted.org/packages/6c/db/537306b92236d761b99dc56a7316c0ad46f2854cd0756585b3a9d3fe5639/websockets-17.3-pp311-pypy311_pp80-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5e1c174b366565e101f903f9d1cc96d5508f805759dd37d012743f1c73ec0d7b", size = 217844, upload-time = "2026-10-19T16:57:53.144Z" }, + { url = "https://files.pythonhosted.org/packages/e0/c2/494bed87536f3822872e57b07ac9afa744af88ff64dda664b9caa32b1a72/websockets-17.3-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:c4b3f2c7d84f303da873b634d0beef83b5e1137294c3de4e23102841dac0cf4a", size = 306274, upload-time = "2026-10-19T16:57:54.525Z" }, + { url = "https://files.pythonhosted.org/packages/5a/1a/5582103e0362f86c4725051ded89e585ceaf750f26beace530b7e42c81c0/websockets-17.3-pp312-pypy312_pp80-macosx_10_15_x86_64.whl", hash = "sha256:0e65260a1b1d7b81651f47343d836de70b88b02358ae3658efa6382104ec37b1", size = 215872, upload-time = "2026-10-19T16:57:55.95Z" }, + { url = "https://files.pythonhosted.org/packages/ef/a7/f69d65ed3ff9ae73d428a918300c23a992e4d50683090b8dc33cc3341d5a/websockets-17.3-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:94c02b0702656f083c098bdbd93bce22a7aa7a2b34ba56d2472efb67dab7cf58", size = 216136, upload-time = "2026-10-19T16:57:57.251Z" }, + { url = "https://files.pythonhosted.org/packages/69/76/c64fda4ac18a3aeb32e66acec481011a766add480b6362fad80e2c3c1963/websockets-17.3-pp312-pypy312_pp80-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:ade76f8c84ade325bbed96806357fffd353fcc29a5166d6dc6d39381f6d9f76c", size = 217080, upload-time = "2026-10-19T16:57:58.593Z" }, + { url = "https://files.pythonhosted.org/packages/6b/6d/085a3f0e6152bbe79917973f3d33cd008437de6c04675e2f15253b921f21/websockets-17.3-pp312-pypy312_pp80-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:9a215749c9a88ef2842e880215193e56ae60b856773c99702b078236bc6d4adb", size = 216966, upload-time = "2026-10-19T16:57:59.924Z" }, + { url = "https://files.pythonhosted.org/packages/ed/b8/7eb904583ea2090b329f50487e6f8dc58eb558712b9f3c16f289f0be668e/websockets-17.3-pp312-pypy312_pp80-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4e7b5d23ef144b32645d97bd99f382c4394c443395f45fe1576786838d26e308", size = 217828, upload-time = "2026-10-19T16:58:01.822Z" }, + { url = "https://files.pythonhosted.org/packages/79/36/f54b4a1cd9456ca0a65a76d77d181621433793aca633dfeed214748ff4f0/websockets-17.3-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:13eace1b315345ebac5b27821f5dcce24e5cf9976ab18f79e00a59bdd67e5d19", size = 306301, upload-time = "2026-10-19T16:58:03.161Z" }, + { url = "https://files.pythonhosted.org/packages/d7/b0/3f01fcb3406662f6deb1e3e72b34dd0979e993991c0b7435a9e12bc14f02/websockets-17.3-py3-none-any.whl", hash = "sha256:dc2b495a92b3971966bf102e73589f950db3ec1ca6713265355ce7771d97b199", size = 212375, upload-time = "2026-10-19T16:58:04.483Z" }, +] + [[package]] name = "xlsxwriter" version = "3.2.9" diff --git a/web-ui/messages/en.json b/web-ui/messages/en.json index a3a341797..35613a29e 100644 --- a/web-ui/messages/en.json +++ b/web-ui/messages/en.json @@ -121,7 +121,31 @@ "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", + "scriptWarning": "External access", + "scriptWarningDetail": "Slide scripts on {slugs} can send data outside the deck ({kinds}). They run in the Present tab and in the downloaded file.", + "scriptKind": { + "navigation": "page navigation", + "popup": "new tabs", + "externalUrl": "external URLs", + "webrtc": "WebRTC" + }, + "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 +219,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 +335,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", @@ -327,6 +358,7 @@ "web_fetch": "Fetching page", "import_attachment": "Importing file", "generate_pptx": "Generating PPTX", + "generate_pptx_html": "Finalizing HTML deck", "generate_preview": "Generating preview", "start_presentation": "Loading role", "start_composing": "Loading role", diff --git a/web-ui/messages/ja.json b/web-ui/messages/ja.json index e83a7043b..69450a579 100644 --- a/web-ui/messages/ja.json +++ b/web-ui/messages/ja.json @@ -121,7 +121,31 @@ "openPptx": "PPTX を開く", "downloadPptx": "PPTX をダウンロード", "slideAlt": "スライド {number}", - "slideAltFull": "スライド {number} / {total}" + "slideAltFull": "スライド {number} / {total}", + "formatHtml": "HTML", + "formatBadgeTitle": "形式: HTML(ブラウザで発表)", + "present": "発表", + "presentAria": "新しいタブで発表", + "pdf": "PDF", + "pdfAria": "新しいタブで印刷画面を開いて PDF に保存", + "scriptWarning": "外部アクセスあり", + "scriptWarningDetail": "{slugs} のスライドスクリプトはデッキの外にデータを送れます({kinds})。発表タブとダウンロードしたファイルで実行されます。", + "scriptKind": { + "navigation": "ページ移動", + "popup": "新しいタブ", + "externalUrl": "外部 URL", + "webrtc": "WebRTC" + }, + "downloadHtml": "HTML をダウンロード", + "open": "開く", + "openHtml": "HTML デッキをブラウザで開く", + "playerTitle": "HTML デッキ", + "playerTitleNamed": "HTML デッキ: {name}", + "htmlPreviewsPlaceholder": "HTML デッキをビルドするとスライドプレビューがここに表示されます。", + "errorPresent": "発表を開けませんでした", + "errorPdf": "PDF 用の画面を開けませんでした", + "errorDownloadHtml": "HTML をダウンロードできませんでした", + "errorOpenHtml": "HTML を開けませんでした" }, "outline": { "body": "本文", @@ -195,10 +219,13 @@ "slashPicker": { "sectionTemplate": "テンプレート", "sectionStyle": "スタイル", + "sectionFormat": "形式", + "formatHtml": "HTML", + "formatHtmlDescription": "ブラウザで発表します。PowerPoint では編集できません", "noMatch": "該当なし", "loading": "読み込み中…", "keyHint": "↑↓ 移動 ↵ 挿入 Esc 閉じる", - "listLabel": "テンプレート / スタイルの候補", + "listLabel": "テンプレート / スタイル / 形式の候補", "previewAlt": "{name} のプレビュー", "unknownName": "このテンプレートまたはスタイルは利用できません", "removeToken": "{kind}「{name}」を削除", @@ -308,6 +335,10 @@ "vibeSummary": "ラフな素材から、まず初稿をすばやく形にします。", "specSummary": "スライドを作る前に、伝えるストーリーを固めます。" }, + "htmlFormatPill": { + "buildAsHtml": "HTML で作成", + "hint": "ブラウザで発表する HTML を作ります。PowerPoint では編集できません" + }, "tools": { "running": "実行中", "completed": "完了", @@ -327,6 +358,7 @@ "web_fetch": "ページを取得中", "import_attachment": "ファイルを取込中", "generate_pptx": "PPTX を生成中", + "generate_pptx_html": "HTML デッキを仕上げ中", "generate_preview": "プレビューを生成中", "start_presentation": "役割を読込中", "start_composing": "役割を読込中", diff --git a/web-ui/package.json b/web-ui/package.json index 521134785..d64cd8ac4 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..c3f67c225 100644 --- a/web-ui/src/app/(authenticated)/decks/page.tsx +++ b/web-ui/src/app/(authenticated)/decks/page.tsx @@ -27,6 +27,7 @@ import { SlideCarousel } from "@/components/deck/SlideCarousel" import { DeckActions } from "@/components/deck/DeckActions" import { ConfirmDialog } from "@/components/ConfirmDialog" import { ChatPanelShell } from "@/components/chat/ChatPanelShell" +import { DeckFormatProvider } from "@/components/chat/DeckFormatContext" import { ChatPanelHandle } from "@/components/chat/ChatPanel" import { updateVisibility, shareDeck } from "@/services/deckService" import { useIsMobile } from "@/hooks/UseMobile" @@ -148,6 +149,7 @@ export default function DecksPage() {
{isMobile && ws.canChat && activeTab === "chat" ? ( /* Mobile chat tab — ChatPanelShell renders inline on mobile */ + setActiveTab("preview")} @@ -163,6 +165,7 @@ export default function DecksPage() { onLoadingChange={setAgentIsLoading} inline /> + ) : ( // Local: defer SlideCarousel mount until deck data loads so // hadSlidesOnMount captures the real slide count, not the @@ -176,6 +179,10 @@ 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} + scriptWarnings={ws.deck?.scriptWarnings} isLoading={ws.waitingForPng || false} scrollToSlide={ws.scrollToSlide} onScrollComplete={() => ws.setScrollToSlide("")} @@ -261,6 +268,7 @@ export default function DecksPage() { {/* Chat Panel (persistent, desktop) — hidden on mobile workspace chat tab */} {!(isMobile && ws.isWorkspace && ws.canChat && activeTab === "chat") && ( + ws.setChatOpen(false)} @@ -275,6 +283,7 @@ export default function DecksPage() { onWorkflowPhase={setWorkflowPhase} onLoadingChange={setAgentIsLoading} /> + )}
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..8fb2a5723 100644 --- a/web-ui/src/app/api/decks/route.ts +++ b/web-ui/src/app/api/decks/route.ts @@ -32,23 +32,44 @@ 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 keep their browser-check PNGs under preview/png/, not at the top level, + // so their thumbnail is 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.test.ts b/web-ui/src/app/api/preview/[...path]/route.test.ts new file mode 100644 index 000000000..777aa1f40 --- /dev/null +++ b/web-ui/src/app/api/preview/[...path]/route.test.ts @@ -0,0 +1,85 @@ +// @vitest-environment node +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: MIT-0 +/** + * Local preview route: the two HTML paths it serves carry a CSP sandbox, every other + * HTML path and every path outside the deck is refused. + */ + +import fs from "fs" +import os from "os" +import path from "path" +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest" + +type Route = typeof import("./route") + +let root: string +let GET: Route["GET"] +let savedRoot: string | undefined + +const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]) + +function write(rel: string, data: string | Buffer) { + const file = path.join(root, rel) // nosemgrep: path-join-resolve-traversal — test fixture in tmpdir + fs.mkdirSync(path.dirname(file), { recursive: true }) + fs.writeFileSync(file, data) +} + +function get(...segments: string[]) { + return GET(new Request("http://localhost/api/preview"), { params: Promise.resolve({ path: segments }) }) +} + +beforeAll(async () => { + root = fs.mkdtempSync(path.join(os.tmpdir(), "sdpm-preview-route-")) + savedRoot = process.env.SDPM_DECK_ROOT + process.env.SDPM_DECK_ROOT = root + write("d1/output.html", "deck") + write("d1/preview/cover.html", "cover") + write("d1/specs/x.html", "spec") + write("d1/preview/png/cover.png", PNG) + write("other.html", "") + vi.resetModules() + GET = (await import("./route")).GET +}) + +afterAll(() => { + if (savedRoot === undefined) delete process.env.SDPM_DECK_ROOT + else process.env.SDPM_DECK_ROOT = savedRoot + fs.rmSync(root, { recursive: true, force: true }) +}) + +describe("GET /api/preview/[...path]", () => { + it("serves output.html in a sandbox that allows scripts and popups only", async () => { + const res = await get("d1", "output.html") + expect(res.status).toBe(200) + expect(res.headers.get("Content-Security-Policy")).toBe("sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox") + expect(res.headers.get("X-Content-Type-Options")).toBe("nosniff") + expect(res.headers.get("Content-Type")).toBe("text/html; charset=utf-8") + expect(await res.text()).toContain("deck") + }) + + it("serves a slide preview in a sandbox without scripts", async () => { + const res = await get("d1", "preview", "cover.html") + expect(res.status).toBe(200) + expect(res.headers.get("Content-Security-Policy")).toBe("sandbox") + expect(res.headers.get("X-Content-Type-Options")).toBe("nosniff") + expect(res.headers.get("Content-Type")).toBe("text/html; charset=utf-8") + }) + + it("refuses every other HTML path", async () => { + expect((await get("d1", "specs", "x.html")).status).toBe(404) + expect((await get("d1", "preview", "..", "output.html")).status).toBe(404) + }) + + it("refuses paths outside the deck", async () => { + expect((await get("d1", "..", "other.html")).status).toBe(403) + expect((await get("..", "other.html")).status).toBe(403) + }) + + it("serves a PNG as image/png", async () => { + const res = await get("d1", "preview", "png", "cover.png") + expect(res.status).toBe(200) + expect(res.headers.get("Content-Type")).toBe("image/png") + expect(Buffer.from(await res.arrayBuffer()).equals(PNG)).toBe(true) + }) +}) diff --git a/web-ui/src/app/api/preview/[...path]/route.ts b/web-ui/src/app/api/preview/[...path]/route.ts index f65412ccb..636f77f2c 100644 --- a/web-ui/src/app/api/preview/[...path]/route.ts +++ b/web-ui/src/app/api/preview/[...path]/route.ts @@ -4,6 +4,13 @@ * 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 + * allow-popups-to-escape-sandbox`: a link it opens loads normally in its tab) + * - `preview/.html`: static slide thumbnails (`sandbox`, no scripts) + * Every other `.html` path is 404. */ @@ -19,6 +26,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 allow-popups-to-escape-sandbox" + 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 +45,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/DeckFormatContext.tsx b/web-ui/src/components/chat/DeckFormatContext.tsx new file mode 100644 index 000000000..328eb8128 --- /dev/null +++ b/web-ui/src/components/chat/DeckFormatContext.tsx @@ -0,0 +1,20 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: MIT-0 +/** + * DeckFormatContext — the open deck's outputFormat ("pptx" | "html", undefined when + * unknown or no deck is open) for chat components whose labels depend on it. + */ + +"use client" + +import { createContext, useContext } from "react" + +type DeckFormat = "pptx" | "html" | undefined + +const DeckFormatContext = createContext(undefined) + +export const DeckFormatProvider = DeckFormatContext.Provider + +export function useDeckFormat(): DeckFormat { + return useContext(DeckFormatContext) +} 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/chat/ToolCard.test.tsx b/web-ui/src/components/chat/ToolCard.test.tsx index ac798b1cc..be5774d4a 100644 --- a/web-ui/src/components/chat/ToolCard.test.tsx +++ b/web-ui/src/components/chat/ToolCard.test.tsx @@ -16,6 +16,7 @@ import { describe, it, expect } from "vitest" import { renderWithIntl } from "@/test/renderWithIntl" import { ToolCard, ToolCardCompact, TOOL_META, stripPrefix } from "./ToolCard" +import { DeckFormatProvider } from "./DeckFormatContext" describe("ToolCard", () => { it("renders active state with cursor marker and agent name tag", () => { @@ -158,3 +159,34 @@ describe("TOOL_META", () => { expect(TOOL_META.hearing.category).toBe("hearing") }) }) + +describe("generate_pptx label", () => { + it("says Finalizing HTML deck when the open deck is HTML", () => { + const { container } = renderWithIntl( + + ) + expect(container.textContent).toContain("Finalizing HTML deck") + const compact = renderWithIntl( + + ) + expect(compact.container.textContent).toContain("Finalizing HTML deck") + }) + + it("says Finalizing HTML deck when the result is HTML", () => { + const { container } = renderWithIntl( + + ) + expect(container.textContent).toContain("Finalizing HTML deck") + }) + + it("says Generating PPTX otherwise", () => { + const { container } = renderWithIntl( + + ) + expect(container.textContent).toContain("Generating PPTX") + expect(container.textContent).not.toContain("Finalizing HTML deck") + const plain = renderWithIntl() + expect(plain.container.textContent).toContain("Generating PPTX") + }) +}) diff --git a/web-ui/src/components/chat/ToolCard.tsx b/web-ui/src/components/chat/ToolCard.tsx index 22c3fbbb7..22bf6dc70 100644 --- a/web-ui/src/components/chat/ToolCard.tsx +++ b/web-ui/src/components/chat/ToolCard.tsx @@ -39,6 +39,7 @@ import { import type { LucideIcon } from "lucide-react" import { useTranslations } from "next-intl" import { ComposeCard } from "./compose/ComposeCard" +import { useDeckFormat } from "./DeckFormatContext" import { CAT, type ToolCategory } from "./toolPalette" import { basename } from "@/lib/local/pathUtils" @@ -184,8 +185,19 @@ export function stripPrefix(n: string): string { return n.replace(/^spec_driven_presentation_maker_/, "") } +/** Message key of a tool's label: generate_pptx finalizes an HTML deck when the deck or its result is HTML. */ +function labelKey(name: string, deckFormat: "pptx" | "html" | undefined, result?: Record): string { + const key = stripPrefix(name) + if (key === "generate_pptx" + && (deckFormat === "html" || result?.outputFormat === "html" || result?.output_format === "html")) { + return "generate_pptx_html" + } + return key +} + export function ToolCard({ name, input, status, result, isActive = false, streamMessages, toolUseId, sessionId, idToken, accessToken }: ToolCardProps) { const t = useTranslations("tools") + const deckFormat = useDeckFormat() // Dispatch: compose_slides has a dedicated rich card. if (name === "compose_slides" || name.endsWith("_compose_slides")) { return ( @@ -203,7 +215,8 @@ export function ToolCard({ name, input, status, result, isActive = false, stream } const meta = TOOL_META[stripPrefix(name)] || { Icon: Wrench, label: name.replace(/_/g, " "), category: "other" as ToolCategory } - const label = t.has(stripPrefix(name)) ? t(stripPrefix(name)) : meta.label + const key = labelKey(name, deckFormat, result) + const label = t.has(key) ? t(key) : meta.label const isError = status === "error" const isComplete = !!status const colors = isError ? { ...CAT.other, accent: ERR.accent, bg: ERR.bg, border: ERR.border } : CAT[meta.category] @@ -384,8 +397,10 @@ export function ToolCard({ name, input, status, result, isActive = false, stream */ export function ToolCardCompact({ name, input }: { name: string; input?: Record }) { const t = useTranslations("tools") + const deckFormat = useDeckFormat() const meta = TOOL_META[stripPrefix(name)] || { Icon: Wrench, label: name.replace(/_/g, " "), category: "other" as ToolCategory } - const label = t.has(stripPrefix(name)) ? t(stripPrefix(name)) : meta.label + const key = labelKey(name, deckFormat) + const label = t.has(key) ? t(key) : meta.label const colors = CAT[meta.category] const detail = getDetail(name, input) diff --git a/web-ui/src/components/chat/compose/ComposeCard.test.tsx b/web-ui/src/components/chat/compose/ComposeCard.test.tsx index 83c6de404..30e5c4188 100644 --- a/web-ui/src/components/chat/compose/ComposeCard.test.tsx +++ b/web-ui/src/components/chat/compose/ComposeCard.test.tsx @@ -74,6 +74,12 @@ describe("ComposeCard production board", () => { expect(screen.queryAllByLabelText("Slide created")).toHaveLength(0) }) + it("settles every lane when the tool completes without stream updates", () => { + renderWithIntl() + expect(screen.queryByText("Queued")).toBeNull() + expect(screen.getAllByText("1/1 created")).toHaveLength(2) + }) + it("renders cancel only when all credentials are present", () => { const { rerender } = renderWithIntl( diff --git a/web-ui/src/components/chat/compose/ComposeCard.tsx b/web-ui/src/components/chat/compose/ComposeCard.tsx index daf6d79e9..a6987fbee 100644 --- a/web-ui/src/components/chat/compose/ComposeCard.tsx +++ b/web-ui/src/components/chat/compose/ComposeCard.tsx @@ -70,19 +70,23 @@ export function ComposeCard({ const isStopped = isHardStopped || isSoftStopped const isDone = !isActive && !isStopped && !hasError && (status === "success" || state.phase === "done") const rushedCount = state.agents.filter((agent) => agent.budgetReached).length + // Tool completion is the source of truth: a lane with no terminal stream state is done. + const agents = isDone + ? state.agents.map((a) => a.status === "starting" || a.status === "working" ? { ...a, status: "done" as const } : a) + : state.agents // A slug counts as created once the composer agent owning it has finished // (or the whole tool has completed successfully). const expectedSlugs = [...new Set(state.agents.flatMap((agent) => agent.slugs))] const createdSlugs = new Set() - for (const agent of state.agents) { + for (const agent of agents) { if (agent.status === "done" || isDone) agent.slugs.forEach((slug) => createdSlugs.add(slug)) } const totalSlides = expectedSlugs.length const createdSlides = expectedSlugs.filter((slug) => createdSlugs.has(slug)).length const creationPercent = totalSlides > 0 ? Math.min(100, Math.round((createdSlides / totalSlides) * 100)) : 0 const doneSlides = new Set( - state.agents.filter((agent) => agent.status === "done").flatMap((agent) => agent.slugs), + agents.filter((agent) => agent.status === "done").flatMap((agent) => agent.slugs), ).size return ( @@ -148,7 +152,7 @@ export function ComposeCard({ )}
- {state.agents.map((agent, index) => ( + {agents.map((agent, index) => ( { 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 allow-popups-to-escape-sandbox") + 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.filter((t) => t.startsWith("allow-top-navigation"))).toEqual([]) + }) + + 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..2ed590b30 --- /dev/null +++ b/web-ui/src/components/deck/HtmlDeckPlayer.tsx @@ -0,0 +1,107 @@ +// 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 allow-popups-to-escape-sandbox` only. The last + * token lets a link opened from the deck (the engine gives external links + * `target="_blank" rel="noopener noreferrer"`) load the site normally in its + * own tab; the deck itself stays sandboxed. Never add `allow-same-origin` (the + * deck would share the app's origin and storage), `allow-top-navigation*` or + * `allow-modals`. 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 allow-popups-to-escape-sandbox" + +/** 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 ( +
+