Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(hogli): name the pr in pr-assets commits (#79028)

Raúl Negrón-Oterof55a90447bb2
diff --git a/tools/hogli-commands/hogli_commands/pr_upload.py b/tools/hogli-commands/hogli_commands/pr_upload.py
index 4887c8fc984b..bd8e935fe83a 100644
--- a/tools/hogli-commands/hogli_commands/pr_upload.py
+++ b/tools/hogli-commands/hogli_commands/pr_upload.py
@@ -7,13 +7,20 @@ share: warn, validate, gate on --yes, publish, print markdown.
from __future__ import annotations
+import shutil
+import subprocess
from dataclasses import dataclass
from pathlib import Path
+from typing import Final
import click
from hogli_commands import pr_assets
+# Short form, matching what people already write by hand in pr-assets. GitHub raises no
+# cross-reference event on the target PR for it, so an upload never adds timeline noise.
+_SOURCE_REPO: Final = "posthog"
+
@dataclass(frozen=True, kw_only=True)
class AssetKind:
@@ -36,7 +43,46 @@ def escape_markdown_label(text: str) -> str:
return text.replace("\\", "\\\\").replace("]", "\\]")
-def run(files: tuple[Path, ...], caption: str | None, yes: bool, kind: AssetKind) -> None:
+def _open_pull_request() -> int | None:
+ """The open PR for the current branch, or None when there is not one.
+
+ Uploading before `gh pr create` is normal, so every failure here is silent: a missing
+ PR, a missing gh, or a slow network must never block publishing.
+ """
+ gh = shutil.which("gh")
+ if gh is None:
+ return None
+ try:
+ result = subprocess.run(
+ [gh, "pr", "view", "--json", "number", "--jq", ".number"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ check=False,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return None
+ if result.returncode != 0:
+ return None
+ try:
+ return int(result.stdout.strip())
+ except ValueError:
+ return None
+
+
+def commit_message(kind: AssetKind, pr: int | None) -> str:
+ """Name the PR the asset documents, so a stray file can be traced back to it.
+
+ Only the number travels. pr-assets is public and permanent, and a branch name can
+ carry a customer or incident name that must not land there.
+ """
+ number = pr if pr is not None else _open_pull_request()
+ if number is None:
+ return kind.commit_message
+ return f"{kind.commit_message} for {_SOURCE_REPO}#{number}"
+
+
+def run(files: tuple[Path, ...], caption: str | None, yes: bool, kind: AssetKind, pr: int | None = None) -> None:
"""Publish every file and print one markdown line each to stdout."""
click.secho(pr_assets.PUBLIC_WARNING, fg="yellow", bold=True, err=True)
@@ -59,7 +105,7 @@ def run(files: tuple[Path, ...], caption: str | None, yes: bool, kind: AssetKind
raise SystemExit(1)
click.secho(f"Uploading to {pr_assets.REPO} …", fg="cyan", err=True)
- urls = pr_assets.publish(files, message=kind.commit_message)
+ urls = pr_assets.publish(files, message=commit_message(kind, pr))
for path, url in zip(files, urls, strict=True):
label = caption if caption is not None else path.stem
diff --git a/tools/hogli-commands/hogli_commands/tests/test_pr_upload.py b/tools/hogli-commands/hogli_commands/tests/test_pr_upload.py
new file mode 100644
index 000000000000..4374fe94a613
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/tests/test_pr_upload.py
@@ -0,0 +1,57 @@
+from __future__ import annotations
+
+import subprocess
+from collections.abc import Iterator
+from subprocess import CompletedProcess
+
+import pytest
+from unittest.mock import patch
+
+from hogli_commands import pr_upload, upload_image
+
+_KIND = upload_image._KIND
+
+
+def gh_installed() -> Iterator[None]:
+ with patch.object(pr_upload.shutil, "which", return_value="/usr/bin/gh"):
+ yield
+
+
+def _gh_returns(stdout: str, returncode: int = 0) -> CompletedProcess[str]:
+ return CompletedProcess(args=[], returncode=returncode, stdout=stdout, stderr="")
+
+
+def test_explicit_pr_is_used_without_consulting_gh() -> None:
+ # --pr must not pay for a network call, and must win over whatever branch you are on.
+ with patch.object(pr_upload.subprocess, "run") as run:
+ assert pr_upload.commit_message(_KIND, 78999) == "add screenshot for posthog#78999"
+ run.assert_not_called()
+
+
+def test_detected_pr_is_named_in_the_message(gh_installed: None) -> None:
+ with patch.object(pr_upload.subprocess, "run", return_value=_gh_returns("78999\n")):
+ assert pr_upload.commit_message(_KIND, None) == "add screenshot for posthog#78999"
+
+
+ "outcome",
+ [
+ {"return_value": _gh_returns("", returncode=1)},
+ {"return_value": _gh_returns("not a number\n")},
+ {"return_value": _gh_returns("\n")},
+ {"side_effect": subprocess.TimeoutExpired(cmd="gh", timeout=10)},
+ {"side_effect": OSError("gh exploded")},
+ ],
+ ids=["no_open_pr", "unparseable", "empty", "timed_out", "spawn_failed"],
+)
+def test_detection_failure_leaves_the_plain_message(gh_installed: None, outcome: dict[str, object]) -> None:
+ # Screenshots often land before `gh pr create`, so no detection failure may block an
+ # upload or leak a half-built reference like "for posthog#None".
+ with patch.object(pr_upload.subprocess, "run", **outcome):
+ assert pr_upload.commit_message(_KIND, None) == "add screenshot"
+
+
+def test_missing_gh_leaves_the_plain_message() -> None:
+ with patch.object(pr_upload.shutil, "which", return_value=None):
+ assert pr_upload.commit_message(_KIND, None) == "add screenshot"
diff --git a/tools/hogli-commands/hogli_commands/tests/test_upload_image.py b/tools/hogli-commands/hogli_commands/tests/test_upload_image.py
index 211462247b23..07f84c9b665c 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_upload_image.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_upload_image.py
@@ -18,7 +18,7 @@ from unittest.mock import Mock, patch
import click
from click.testing import CliRunner
-from hogli_commands import pr_assets, upload_image
+from hogli_commands import pr_assets, pr_upload, upload_image
_URL = "https://raw.githubusercontent.com/PostHog/pr-assets/abc123/2026/07/f7c1.png"
@@ -30,6 +30,14 @@ def png(tmp_path: Path) -> Path:
return path
[email protected](autouse=True)
+def no_detected_pr() -> Iterator[None]:
+ # Detection shells out to gh, so without this the suite reads whatever branch it runs
+ # on and these tests pass or fail depending on whether that branch has a PR.
+ with patch.object(pr_upload, "_open_pull_request", return_value=None):
+ yield
+
+
@contextmanager
def _publishes(*urls: str) -> Iterator[Mock]:
"""Stand in for storage so these tests turn on the command, not the GitHub wire format."""
@@ -67,6 +75,28 @@ def test_command_caption_rendering(png: Path, alt: str, expected_label: str) ->
assert result.stdout.strip() == f"![{expected_label}]({_URL})"
+def test_pr_flag_reaches_the_commit_message(png: Path) -> None:
+ # Guards the wiring, which each command does for itself: a --pr the command accepts but
+ # never forwards would leave the asset untraceable.
+ with _publishes(_URL) as publish:
+ result = CliRunner(mix_stderr=False).invoke(upload_image.upload_image, ["--yes", "--pr", "1234", str(png)])
+
+ assert result.exit_code == 0
+ assert publish.call_args.kwargs["message"] == "add screenshot for posthog#1234"
+
+
[email protected]("pr", ["0", "-1"], ids=["zero", "negative"])
+def test_pr_flag_rejects_numbers_no_pr_can_have(png: Path, pr: str) -> None:
+ # A typo'd number must fail loudly rather than commit "for posthog#0" to a public repo
+ # permanently, and must not quietly take the no-PR fallback either.
+ with _publishes(_URL) as publish:
+ result = CliRunner(mix_stderr=False).invoke(upload_image.upload_image, ["--yes", "--pr", pr, str(png)])
+
+ assert result.exit_code != 0
+ assert "--pr" in result.stderr
+ publish.assert_not_called()
+
+
def test_requires_yes_before_uploading(png: Path) -> None:
# The gate: a first run without --yes must warn and abort without uploading, so the
# caller has to read the warning and re-run to confirm the public upload.
diff --git a/tools/hogli-commands/hogli_commands/tests/test_upload_video.py b/tools/hogli-commands/hogli_commands/tests/test_upload_video.py
index d86faee1575b..cce8620f2f67 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_upload_video.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_upload_video.py
@@ -17,7 +17,7 @@ from unittest.mock import Mock, patch
import click
from click.testing import CliRunner
-from hogli_commands import pr_assets, upload_video
+from hogli_commands import pr_assets, pr_upload, upload_video
_URL = "https://raw.githubusercontent.com/PostHog/pr-assets/deadbeef/2026/07/a91c.mp4"
@@ -29,6 +29,14 @@ def mp4(tmp_path: Path) -> Path:
return path
[email protected](autouse=True)
+def no_detected_pr() -> Iterator[None]:
+ # Detection shells out to gh, so without this the suite reads whatever branch it runs
+ # on and these tests pass or fail depending on whether that branch has a PR.
+ with patch.object(pr_upload, "_open_pull_request", return_value=None):
+ yield
+
+
@contextmanager
def _publishes(*urls: str) -> Iterator[Mock]:
with patch.object(pr_assets, "publish", return_value=list(urls)) as publish:
@@ -72,6 +80,28 @@ def test_upload_uses_video_commit_message(mp4: Path) -> None:
assert publish.call_args.kwargs["message"] == "add video"
+def test_pr_flag_reaches_the_commit_message(mp4: Path) -> None:
+ # Guards the wiring, which each command does for itself: a --pr the command accepts but
+ # never forwards would leave the asset untraceable.
+ with _publishes(_URL) as publish:
+ result = CliRunner(mix_stderr=False).invoke(upload_video.upload_video, ["--yes", "--pr", "1234", str(mp4)])
+
+ assert result.exit_code == 0
+ assert publish.call_args.kwargs["message"] == "add video for posthog#1234"
+
+
[email protected]("pr", ["0", "-1"], ids=["zero", "negative"])
+def test_pr_flag_rejects_numbers_no_pr_can_have(mp4: Path, pr: str) -> None:
+ # A typo'd number must fail loudly rather than commit "for posthog#0" to a public repo
+ # permanently, and must not quietly take the no-PR fallback either.
+ with _publishes(_URL) as publish:
+ result = CliRunner(mix_stderr=False).invoke(upload_video.upload_video, ["--yes", "--pr", pr, str(mp4)])
+
+ assert result.exit_code != 0
+ assert "--pr" in result.stderr
+ publish.assert_not_called()
+
+
def test_label_rejected_for_multiple_files(mp4: Path, tmp_path: Path) -> None:
other = tmp_path / "second.webm"
other.write_bytes(b"webm fake")
diff --git a/tools/hogli-commands/hogli_commands/upload_image.py b/tools/hogli-commands/hogli_commands/upload_image.py
index 582ad2def121..b46d74587162 100644
--- a/tools/hogli-commands/hogli_commands/upload_image.py
+++ b/tools/hogli-commands/hogli_commands/upload_image.py
@@ -34,10 +34,18 @@ _KIND: Final = AssetKind(
@click.command(name="pr:upload-image")
@click.argument("files", nargs=-1, required=True, type=click.Path(exists=True, dir_okay=False, path_type=Path))
@click.option("--alt", help="Alt text for the markdown (defaults to each file's stem).")
+# IntRange rather than int: a typo'd 0 or -1 would otherwise commit "for posthog#0" to a
+# public repo permanently, and the plain-message fallback would hide the typo instead of
+# reporting it.
+ "--pr",
+ type=click.IntRange(min=1),
+ help="PR the screenshot documents (defaults to the current branch's open PR).",
+)
# Hidden on purpose: the first run without it prints the warning and stops, so the caller
# has to read the warning and re-run with --yes. Undocumented is the whole point of the gate.
@click.option("-y", "--yes", is_flag=True, hidden=True)
-def upload_image(files: tuple[Path, ...], alt: str | None, yes: bool) -> None:
+def upload_image(files: tuple[Path, ...], alt: str | None, pr: int | None, yes: bool) -> None:
"""Upload screenshot(s) to the public PostHog/pr-assets repo and print embeddable markdown.
Prints one `![alt](url)` line per file to stdout (everything else goes to stderr),
@@ -53,4 +61,4 @@ def upload_image(files: tuple[Path, ...], alt: str | None, yes: bool) -> None:
permanent: SHA-pinned URLs keep serving even after the file is deleted. Never upload
customer data, secrets, or internal-only information.
"""
- run(files, alt, yes, _KIND)
+ run(files, alt, yes, _KIND, pr)
diff --git a/tools/hogli-commands/hogli_commands/upload_video.py b/tools/hogli-commands/hogli_commands/upload_video.py
index 42a1114af426..9e26b1b3ac12 100644
--- a/tools/hogli-commands/hogli_commands/upload_video.py
+++ b/tools/hogli-commands/hogli_commands/upload_video.py
@@ -32,10 +32,17 @@ _KIND: Final = AssetKind(
@click.command(name="pr:upload-video")
@click.argument("files", nargs=-1, required=True, type=click.Path(exists=True, dir_okay=False, path_type=Path))
@click.option("--label", help="Link text for the markdown (defaults to each file's stem).")
+# IntRange rather than int, matching pr:upload-image: a typo'd 0 or -1 would otherwise
+# commit "for posthog#0" to a public repo permanently.
+ "--pr",
+ type=click.IntRange(min=1),
+ help="PR the video documents (defaults to the current branch's open PR).",
+)
# Hidden on purpose, matching pr:upload-image: the first run without it prints the
# warning and stops, so the caller has to read the warning and re-run with --yes.
@click.option("-y", "--yes", is_flag=True, hidden=True)
-def upload_video(files: tuple[Path, ...], label: str | None, yes: bool) -> None:
+def upload_video(files: tuple[Path, ...], label: str | None, pr: int | None, yes: bool) -> None:
"""Upload demo video(s) to the public PostHog/pr-assets repo and print link markdown.
Prints one `[label](url)` line per file to stdout (everything else goes to stderr).
@@ -51,4 +58,4 @@ def upload_video(files: tuple[Path, ...], label: str | None, yes: bool) -> None:
SHA-pinned URLs keep serving even after the file is deleted. Never upload customer
data, secrets, or internal-only information.
"""
- run(files, label, yes, _KIND)
+ run(files, label, yes, _KIND, pr)