Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion devcapsule-src/devcapsule/commands/presentations.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def run(cls, arguments: argparse.Namespace, context: object | None) -> int:
token_path = arguments.token_file or Path(os.environ.get("DEVCAPSULE_CONSOLE_TOKEN_FILE") or "/run/devcapsule-console-token")
try:
token = token_path.read_text(encoding="utf-8").strip()
except OSError:
except (OSError, UnicodeError):
token = ""
try:
if not (folder / "presentation.json").is_file():
Expand Down
9 changes: 8 additions & 1 deletion devcapsule-src/devcapsule/presentation_authoring.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,15 @@ def presentation_link(folder: Path, *, project: Path, console_url: str, token: s
part in ("..", "node_modules") or part.startswith(".") for part in relative.parts
):
raise ValueError("presentation must be in a visible subdirectory of the console project")
if not console_url or any(ch.isspace() for ch in console_url):
raise ValueError("supply the capsule's HTTP(S) console URL")
origin = urlsplit(console_url)
if origin.scheme not in ("http", "https") or not origin.netloc or origin.username or origin.password:
try:
_ = origin.port
except ValueError as error:
raise ValueError("supply the capsule's HTTP(S) console URL") from error
if (origin.scheme not in ("http", "https") or not origin.hostname
or origin.username is not None or origin.password is not None):
raise ValueError("supply the capsule's HTTP(S) console URL")
path = "/presentations/" + quote(relative.as_posix(), safe="/")
return urlunsplit((origin.scheme, origin.netloc, path, urlencode({"token": token}) if token else "", ""))
6 changes: 4 additions & 2 deletions devcapsule-src/devcapsule/presentation_tools/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,10 @@ Print the engineer's link with the installed CLI:
devcapsule presentations hand-off evidence/login-success/run-001 --project "$PROJECT_PATH"
```

It uses `$DEVCAPSULE_CONSOLE_URL` and the mounted console token; `--console-url`
and `--token-file` supply explicit values. Keep tokened links in chat only, never
Run this from the console project root: a relative evidence folder resolves
from the current working directory, and `--project` supplies the console root
used to form the relative link. It uses `$DEVCAPSULE_CONSOLE_URL` and the
mounted console token; `--console-url` and `--token-file` supply explicit values. Keep tokened links in chat only, never
in a source file, log or committed record. If no token can be read, the link
requires a browser session that already opened the console. If there is no
console URL, report that missing environment input rather than inventing a URL.
Expand Down
13 changes: 13 additions & 0 deletions devcapsule-src/devcapsule/presentation_tools/producer.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,19 @@ def plan_presentation(scenario: Mapping[str, Any], script: Script) -> Presentati
if not isinstance(value, str) or not value.strip():
raise PresentationError(f"the scenario has no {key}")
texts[key] = value.strip()
if not isinstance(script.goal, str) or not script.goal.strip():
raise PresentationError("the script has no goal")
if not script.steps:
raise PresentationError("the script has no steps")
for index, step in enumerate(script.steps, start=1):
for field_name, field_value in (("title", step.title), ("action", step.action), ("expected", step.expected)):
if not isinstance(field_value, str) or not field_value.strip():
raise PresentationError(f"script step {index} has no {field_name}")
if any(not isinstance(item, str) or not item.strip() for item in script.illustrates):
raise PresentationError("script illustrations must be non-empty texts")
if any(not isinstance(name, str) or not name.strip() or not isinstance(detail, str) or not detail.strip()
for name, detail in script.stack):
raise PresentationError("script stack entries must have non-empty name and detail")
actions = scenario.get("actions")
if not isinstance(actions, list) or not actions:
raise PresentationError("the scenario has no actions")
Expand Down
10 changes: 6 additions & 4 deletions devcapsule-src/devcapsule/presentation_tools/recording.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def __init__(
"actions": [{"reason": f"{n}. {step.action}"}
for n, step in enumerate(script.steps, 1)]}
plan_presentation(scenario, script)
if not ffmpeg or not all(isinstance(part, str) and part for part in ffmpeg):
if isinstance(ffmpeg, (str, bytes)) or not ffmpeg or not all(isinstance(part, str) and part for part in ffmpeg):
raise PresentationError("supply the ffmpeg command from the browser-automation environment")
evidence.mkdir(parents=True, exist_ok=False)
self.evidence = evidence
Expand Down Expand Up @@ -124,18 +124,20 @@ def finish(self) -> Path:
raise PresentationError("no complete visual evidence; inspect scenario-result.json and action-log.json")
complete = self.last_step == len(self.script.steps) and not self.failure
suffix = "" if complete else " (FAILED)" if self.failure else " (INCOMPLETE)"
scenario = dict(self.scenario, title=self.scenario["title"] + suffix, actions=self.actions)
scenario = dict(self.scenario, title=self.scenario["title"].strip() + suffix, actions=self.actions)
reached = Script(self.script.goal, self.script.stack, self.script.illustrates,
self.script.steps[:self.last_step])
plan = plan_presentation(scenario, reached)
document = plan.timed(self.frames_after_actions, self.frame_count, 12,
video="scenario-video.webm", poster="poster.png", screenshots=self.screenshots)
video = self.evidence / "scenario-video.webm"
with self.frames.open("rb") as frames, (self.evidence / "ffmpeg.log").open("wb") as log:
subprocess.run(
[*self.ffmpeg, "-y", "-f", "image2pipe", "-vcodec", "mjpeg", "-r", "12",
"-i", "pipe:0", "-c:v", "libvpx", "-b:v", "3M", "-crf", "10",
str(self.evidence / "scenario-video.webm")],
"-i", "pipe:0", "-c:v", "libvpx", "-b:v", "3M", "-crf", "10", str(video)],
stdin=frames, stdout=log, stderr=log, check=True, timeout=120,
)
if not video.is_file() or video.stat().st_size == 0:
raise PresentationError("video encoding produced no scenario-video.webm; inspect ffmpeg.log")
(self.evidence / "poster.png").write_bytes((self.evidence / self.screenshots[0]).read_bytes())
return write_presentation(self.evidence, document)
41 changes: 41 additions & 0 deletions devcapsule-src/tests/integration/test_pex_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,3 +288,44 @@ def invoke(*arguments: str) -> subprocess.CompletedProcess[str]:
saved = invoke("run", "--ide", "codium", "--force", "--save", "--print-command")
assert saved.returncode == 2 and "cannot be combined with --save" in saved.stderr
assert {path: path.read_bytes() for path in before} == before, "no refusal writes anything"


def test_built_pex_exports_standalone_presentation_tools(
built_pex: Path, tmp_path: Path, environment: dict[str, str],
) -> None:
"""The built executable prints the guide and exports a standalone ``presentation_tools`` kit."""
guide = subprocess.run(
[str(built_pex), "presentations", "guide"],
cwd=tmp_path, env=environment, text=True, capture_output=True, check=False,
)
assert guide.returncode == 0, guide.stderr
assert "# Run an E2E scenario with recording and presentation" in guide.stdout

kit = tmp_path / "exported-kit"
exported = subprocess.run(
[str(built_pex), "presentations", "export", str(kit)],
cwd=tmp_path, env=environment, text=True, capture_output=True, check=False,
)
assert exported.returncode == 0, exported.stderr
package = kit / "presentation_tools"
assert (package / "README.md").read_text(encoding="utf-8") + "\n" == guide.stdout
assert {path.name for path in package.iterdir()} == {
"__init__.py", "README.md", "example.py", "producer.py", "recording.py",
}

isolated = subprocess.run(
[
sys.executable, "-I", "-c",
(
"import sys; sys.path.insert(0, sys.argv[1]); "
"from presentation_tools.producer import Script, ScriptStep; "
"from presentation_tools.recording import Recording; "
"import presentation_tools.example; "
"assert 'devcapsule' not in sys.modules and 'tests' not in sys.modules"
),
str(kit),
],
cwd=tmp_path, env={"PATH": os.defpath, "PYTHONDONTWRITEBYTECODE": "1"},
text=True, capture_output=True, check=False,
)
assert isolated.returncode == 0, isolated.stderr
107 changes: 107 additions & 0 deletions devcapsule-src/tests/integration/test_presentations_cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
"""Integration tests of ``devcapsule presentations``: real CLI subprocesses with explicit environments."""
from __future__ import annotations

import os
from pathlib import Path
import subprocess
import sys

import pytest

pytestmark = pytest.mark.integration


def _run_presentations(
tmp_path: Path, *arguments: str, extra_env: dict[str, str] | None = None,
) -> subprocess.CompletedProcess[str]:
environment = {
"PATH": os.defpath,
"PYTHONDONTWRITEBYTECODE": "1",
"HOME": str(tmp_path / "home"),
"DEVCAPSULE_CONFIG_HOME": str(tmp_path / "config"),
}
if extra_env:
environment.update(extra_env)
return subprocess.run(
[sys.executable, "-m", "devcapsule", "presentations", *arguments],
cwd=tmp_path, env=environment, capture_output=True, text=True, timeout=120, check=False,
)


def test_guide_and_export_supply_an_importable_standalone_kit(tmp_path: Path) -> None:
"""``presentations guide`` and ``export`` deliver the guide and a stdlib-only kit, refusing overwrites."""
guide = _run_presentations(tmp_path, "guide")
assert guide.returncode == 0, guide.stderr
assert "# Run an E2E scenario with recording and presentation" in guide.stdout

kit = tmp_path / "kit"
exported = _run_presentations(tmp_path, "export", str(kit))
assert exported.returncode == 0, exported.stderr
assert f"Presentation tools: {kit / 'presentation_tools'}" in exported.stdout
assert (kit / "presentation_tools" / "README.md").read_text(encoding="utf-8") + "\n" == guide.stdout

isolated = subprocess.run(
[
sys.executable, "-I", "-c",
(
"import sys; sys.path.insert(0, sys.argv[1]); "
"from presentation_tools.producer import Script; "
"from presentation_tools.recording import Recording; "
"import presentation_tools.example; "
"assert 'devcapsule' not in sys.modules and 'tests' not in sys.modules"
),
str(kit),
],
cwd=tmp_path, env={"PATH": os.defpath, "PYTHONDONTWRITEBYTECODE": "1"},
capture_output=True, text=True, timeout=120, check=False,
)
assert isolated.returncode == 0, isolated.stderr

refused = _run_presentations(tmp_path, "export", str(kit))
assert refused.returncode == 2
assert "cannot export presentation tools" in refused.stderr


def test_hand_off_reads_environment_and_handles_token_states(tmp_path: Path) -> None:
"""``presentations hand-off`` prints a tokenized link, falls back cleanly on missing or non-UTF-8 tokens, and refuses missing decks or origins."""
project = tmp_path / "project"
evidence = project / "evidence" / "run-001"
evidence.mkdir(parents=True)
(evidence / "presentation.json").write_text("{}", encoding="utf-8")
token_file = tmp_path / "console-token"
token_file.write_text("secret-token\n", encoding="utf-8")

with_token = _run_presentations(
tmp_path, "hand-off", str(evidence),
extra_env={
"PROJECT_PATH": str(project),
"DEVCAPSULE_CONSOLE_URL": "http://127.0.0.1:8787",
"DEVCAPSULE_CONSOLE_TOKEN_FILE": str(token_file),
},
)
assert with_token.returncode == 0, with_token.stderr
assert with_token.stdout.strip() == "http://127.0.0.1:8787/presentations/evidence/run-001?token=secret-token"

token_file.write_bytes(b"\xff\xfe\xfd")
corrupt_token = _run_presentations(
tmp_path, "hand-off", str(evidence),
"--project", str(project), "--console-url", "http://127.0.0.1:8787", "--token-file", str(token_file),
)
assert corrupt_token.returncode == 0, corrupt_token.stderr
assert "no readable run token was found" in corrupt_token.stdout
assert corrupt_token.stdout.splitlines()[-1] == "http://127.0.0.1:8787/presentations/evidence/run-001"

missing_url = _run_presentations(
tmp_path, "hand-off", str(evidence), "--project", str(project), "--token-file", str(tmp_path / "absent"),
)
assert missing_url.returncode == 2
assert "HTTP(S) console URL" in missing_url.stderr

empty_dir = project / "evidence" / "empty"
empty_dir.mkdir(parents=True)
missing_deck = _run_presentations(
tmp_path, "hand-off", str(empty_dir),
"--project", str(project), "--console-url", "http://127.0.0.1:8787",
)
assert missing_deck.returncode == 2
assert "no presentation.json" in missing_deck.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,24 @@ def test_plan_presentation_refuses_a_scenario_that_does_not_join_its_script(docu
plan_presentation(document, SCRIPT)


@pytest.mark.parametrize(
("bad_script", "message"),
[
(Script("", (), (), SCRIPT.steps), "the script has no goal"),
(Script("Goal", (), (), ()), "the script has no steps"),
(Script("Goal", (), (), (ScriptStep(" ", "Open", "Visible"),)), "script step 1 has no title"),
(Script("Goal", (), (), (ScriptStep("Open", " ", "Visible"),)), "script step 1 has no action"),
(Script("Goal", (), (), (ScriptStep("Open", "Open", ""),)), "script step 1 has no expected"),
(Script("Goal", (), (" ",), SCRIPT.steps[:1]), "script illustrations must be non-empty texts"),
(Script("Goal", (("Editor", ""),), (), SCRIPT.steps[:1]), "script stack entries must have non-empty name and detail"),
],
)
def test_plan_presentation_refuses_incomplete_python_script(bad_script: Script, message: str) -> None:
"""``plan_presentation`` refuses Python-constructed scripts with missing goal, steps, step fields, stack or illustrations."""
with pytest.raises(PresentationError, match=re.escape(message)):
plan_presentation(scenario(action("1. One")), bad_script)


def test_plan_for_scenario_reads_the_named_script_below_the_root(tmp_path: Path) -> None:
"""A scenario that names its script is planned from the file at that path below the root."""
(tmp_path / "scripts").mkdir()
Expand Down
Loading