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): attach pr images and videos through gh (#125800)

Raúl Negrón-Otero09b91cb40784
diff --git a/.agents/skills/qa-frontend/SKILL.md b/.agents/skills/qa-frontend/SKILL.md
index 725aff4f99d6..1ea99e0da456 100644
--- a/.agents/skills/qa-frontend/SKILL.md
+++ b/.agents/skills/qa-frontend/SKILL.md
@@ -46,7 +46,7 @@ Claude Code ships built-in `/run` and `/verify` skills. This skill composes with
7. Confirm every candidate issue with one retry before calling it a finding.
8. In PR mode, apply at most 3 confident fixes, only inside files already changed by the PR. In local mode, default to suggested patches, only edit after explicit approval, and never stage or commit those edits.
9. Annotate key screenshots (caption bar, PASS/FAIL chip, highlight box) and assemble them into a small animated WebP demo reel with `scripts/annotate-evidence.py`.
-10. PR mode only: after approval, upload selected evidence with `hogli pr:upload-image`, verify PR comment connectivity, and post one final PR comment for every completed run, including clean runs. Push only after explicit approval.
+10. PR mode only: after approval, upload selected evidence with `hogli pr:upload-image --print-markdown` (without the flag it attaches to a PR description instead), verify PR comment connectivity, and post one final PR comment for every completed run, including clean runs. Push only after explicit approval.
11. Local mode only: write the rendered report to stdout and to `.qa-frontend/runs/<run-id>/report.md`. No upload, no PR comment, no push.
12. In PR mode, restore the original branch in a finally-style cleanup.
@@ -256,7 +256,7 @@ Evidence files live under `.qa-frontend/runs/<run-id>/` and stay uncommitted. Us
Annotate the key screenshots so a reviewer can read the run without replaying it: each frame gets a caption bar stating what is happening plus a PASS/FAIL/INFO chip, and findings get a highlight box around the element that matters. Then assemble 2-5 annotated key frames into a slow animated WebP demo reel named `.qa-frontend/runs/<run-id>/frontend-qa.webp`. Both steps use `<skill_dir>/scripts/annotate-evidence.py` through `uv run python`, run from a trusted checkout rather than the PR checkout (`uv run` resolves that tree's dependencies) - it needs only the repo's existing Pillow dependency, so do not install packages or use `ffmpeg` for this. Use the recipes and the highlight-rect capture pattern in `references/browser-mcp-patterns.md`. Aim for about 1.5-2 seconds per frame, slightly longer on frames that show a finding. Before uploading or embedding the reel, inspect it. If text is fuzzy or the sequence is less useful than the stills, fall back to the annotated PNGs as primary evidence.
-After the QA loop settles, run the recorded demo pass from `references/browser-mcp-patterns.md` by default: re-run the key flow once with the browser tool's recording on and the `scripts/cursor-overlay.js` visible cursor injected, then transcode to H.264 MP4. Skip it only when `NO_VIDEO` was set, the browser tool cannot record video, or `ffmpeg` is missing - and record the skip and its reason in run notes and the report's Setup section. The MP4 is linked from the local report; in PR mode it may join the approved upload set through `hogli pr:upload-video`, which yields a download link in the comment - an inline player still requires the developer to drag the file into the comment editor by hand.
+After the QA loop settles, run the recorded demo pass from `references/browser-mcp-patterns.md` by default: re-run the key flow once with the browser tool's recording on and the `scripts/cursor-overlay.js` visible cursor injected, then transcode to H.264 MP4. Skip it only when `NO_VIDEO` was set, the browser tool cannot record video, or `ffmpeg` is missing - and record the skip and its reason in run notes and the report's Setup section. The MP4 is linked from the local report; in PR mode it may join the approved upload set through `hogli pr:upload-video --print-markdown`, which yields a download link in the comment - an inline player still requires the developer to drag the file into the comment editor by hand.
Candidate issues must pass one reproducibility retry. Re-run the same action sequence in the same browser session. If it does not reproduce, do not fix or report it as a finding; record it as an `INTERMITTENT` coverage row with the first failure's evidence, per `references/browser-mcp-patterns.md`.
diff --git a/.agents/skills/qa-frontend/references/browser-mcp-patterns.md b/.agents/skills/qa-frontend/references/browser-mcp-patterns.md
index c936c641c674..80c971be17d7 100644
--- a/.agents/skills/qa-frontend/references/browser-mcp-patterns.md
+++ b/.agents/skills/qa-frontend/references/browser-mcp-patterns.md
@@ -285,6 +285,6 @@ Run a **demo pass** by default after the QA loop settles: re-run the key flow on
The sheet must show the caption bar present from the first seconds, every step's caption in order, motion between frames (no stretches of identical idle frames), and the final finding state held at the end. If it does not, fix the trim and re-check; do not share an unverified video.
-Transcoding needs a local `ffmpeg`; if it is missing, keep the WebM and say so in run notes. A 15-second 1280px demo lands around 300 KB. Keep the MP4 under ~10 MB so it stays drag-droppable into a GitHub comment. Do not try to auto-embed video in an agent-posted comment: GitHub only renders a video player for files uploaded by hand through its web editor, and raw-hosted MP4 links are served as downloads, not playable video. Link the MP4 from the local report; in PR mode it may join the approved upload set via `hogli pr:upload-video` (a download link in the comment), and the developer can still drag the file into the comment editor for an inline player. The overlay uses only opaque brand colors, so it reads identically on light and dark themes.
+Transcoding needs a local `ffmpeg`; if it is missing, keep the WebM and say so in run notes. A 15-second 1280px demo lands around 300 KB. Keep the MP4 under ~10 MB so it stays drag-droppable into a GitHub comment. Do not try to auto-embed video in an agent-posted comment: GitHub only renders a video player for files uploaded by hand through its web editor, and raw-hosted MP4 links are served as downloads, not playable video. Link the MP4 from the local report; in PR mode it may join the approved upload set via `hogli pr:upload-video --print-markdown` (a download link in the comment), and the developer can still drag the file into the comment editor for an inline player. The overlay uses only opaque brand colors, so it reads identically on light and dark themes.
Keep paths relative in PR comments. If the comment would be too long, summarize the evidence and rely on the approved uploaded files or the local report. Do not fall back to a secret gist.
diff --git a/.agents/skills/qa-frontend/references/evidence-and-output.md b/.agents/skills/qa-frontend/references/evidence-and-output.md
index 69c18b6f4a3a..17a2a6a8dd77 100644
--- a/.agents/skills/qa-frontend/references/evidence-and-output.md
+++ b/.agents/skills/qa-frontend/references/evidence-and-output.md
@@ -6,28 +6,28 @@ Use this reference after the frontend QA loop completes and findings are settled
PR mode only. Upload is optional and must be explicitly approved before any file leaves the developer's machine. Local mode never uploads evidence.
-Use the repo's own uploader, `hogli pr:upload-image`. It pushes files to the public `PostHog/pr-assets` repo and prints one `![alt](url)` markdown line per file, ready to paste into the PR comment. It accepts png, jpg, gif, and webp up to 10 MB - including the animated `frontend-qa.webp` demo reel - and needs only a GitHub token with write access to a PostHog org repo (the developer's normal `gh` login), no extra secret.
+Use the repo's own uploader, `hogli pr:upload-image --print-markdown`. Without `--print-markdown` it attaches the files to the PR description instead of printing markdown for the comment. With it, it pushes files to the public `PostHog/pr-assets` repo and prints one `![alt](url)` markdown line per file, ready to paste into the PR comment. It accepts png, jpg, gif, and webp up to 10 MB - including the animated `frontend-qa.webp` demo reel - and needs only a GitHub token with write access to a PostHog org repo (the developer's normal `gh` login), no extra secret.
Uploads are PUBLIC and PERMANENT: URLs are SHA-pinned and keep serving even after the file is deleted, so an upload cannot be taken back. Before upload, show the user the exact upload set and ask for approval. Upload only reviewed evidence that does not show secrets, private customer data, or unrelated local context. Pick only human-facing evidence:
- `frontend-qa.webp`, only if generated and inspected as readable
- 1-3 annotated key screenshots that match the findings or PASS narrative
-Do not upload `.md` snapshots, `console.log`, or every numbered screenshot. If the demo pass produced an MP4, include it in the same approved upload set through `hogli pr:upload-video` (mp4/webm, same 10 MB cap and `--yes` gate) - it prints a plain `[label](url)` link line, which is a click-to-download link: GitHub renders no player for raw-hosted video, so an inline player still requires the developer to drag the file into the comment editor by hand. If the reel is less clear than the annotated stills, omit it from the upload set and use the PNGs instead.
+Do not upload `.md` snapshots, `console.log`, or every numbered screenshot. If the demo pass produced an MP4, include it in the same approved upload set through `hogli pr:upload-video --print-markdown` (mp4/webm, same 10 MB cap and `--yes` gate) - it prints a plain `[label](url)` link line, which is a click-to-download link: GitHub renders no player for raw-hosted video, so an inline player still requires the developer to drag the file into the comment editor by hand. If the reel is less clear than the annotated stills, omit it from the upload set and use the PNGs instead.
Before asking for upload approval, inspect the final evidence exactly as it will be posted. Each image must make the claimed PASS, FAIL, SKIP, or NEEDS INTENT row understandable without reconstructing the browser session. If an image only shows the page header, hero, empty shell, or setup state while the actual proof is below the fold or too small to read, do not upload it. Recapture, crop through browser positioning, or add a clearer annotated still first.
When a screenshot uses deliberately odd test data, add a one-sentence explanation in the report near the evidence or coverage row. Do this for cases where the visible data is technically valid but not self-explanatory, such as edge-case email syntax, encoded URLs, timezone boundaries, or synthetic billing states.
```bash
-hogli pr:upload-video --yes --label "demo video" \
+hogli pr:upload-video --yes --print-markdown --label "demo video" \
".qa-frontend/runs/<run-id>/frontend-qa.mp4"
```
Run upload commands from a trusted tree, never from the PR checkout - in PR mode the working tree holds the PR's code, and `./bin/hogli` would execute it. Restore the original branch first (uploads and the comment happen after the QA loop anyway) or invoke hogli from a separate checkout that is on your own branch. After the user approves the upload set:
```bash
-hogli pr:upload-image --yes \
+hogli pr:upload-image --yes --print-markdown \
".qa-frontend/runs/<run-id>/frontend-qa.webp" \
".qa-frontend/runs/<run-id>/<screenshot>.annotated.png"
```
diff --git a/.agents/skills/qa-frontend/references/feature-reel.md b/.agents/skills/qa-frontend/references/feature-reel.md
index 430c9412292d..c1c865c4f4b6 100644
--- a/.agents/skills/qa-frontend/references/feature-reel.md
+++ b/.agents/skills/qa-frontend/references/feature-reel.md
@@ -102,7 +102,7 @@ Look for names, emails, tokens, and internal text in the pixels and in the capti
```bash
# --yes only after the check above, and for a running-app reel only after the developer approves this exact file
-hogli pr:upload-image --yes --alt "<what the flow shows>" "$RUN_DIR/feature-reel.webp"
+hogli pr:upload-image --yes --print-markdown --alt "<what the flow shows>" "$RUN_DIR/feature-reel.webp"
```
Paste the markdown line that the command prints as the "after" of the change. For the "before", follow `references/screenshots-and-reels.md` in `/writing-pr-descriptions`.
diff --git a/.agents/skills/qa-frontend/references/pr-comment-template.md b/.agents/skills/qa-frontend/references/pr-comment-template.md
index 8a50972f25ad..a06b06b45422 100644
--- a/.agents/skills/qa-frontend/references/pr-comment-template.md
+++ b/.agents/skills/qa-frontend/references/pr-comment-template.md
@@ -272,7 +272,7 @@ got: new Question 2 titled " (copy)" - empty title with stray space
## Evidence URLs
-Use the `![alt](url)` markdown lines printed by `hogli pr:upload-image` verbatim - they point at SHA-pinned `raw.githubusercontent.com/PostHog/pr-assets` URLs. Do not reconstruct, shorten, or edit them.
+Use the `![alt](url)` markdown lines printed by `hogli pr:upload-image --print-markdown` verbatim - they point at SHA-pinned `raw.githubusercontent.com/PostHog/pr-assets` URLs. Do not reconstruct, shorten, or edit them.
Embed images and animated WebP reels with markdown image syntax (`![alt](url)`) so they render inline. Use one or two key visuals per finding. Prefer the reel for the flow only when it has been inspected and remains readable. Otherwise use annotated still screenshots. Do not paste the full local screenshot inventory.
diff --git a/.agents/skills/recording-demo-videos/SKILL.md b/.agents/skills/recording-demo-videos/SKILL.md
index 871792a6802d..e472a45e4ec7 100644
--- a/.agents/skills/recording-demo-videos/SKILL.md
+++ b/.agents/skills/recording-demo-videos/SKILL.md
@@ -117,7 +117,7 @@ Reset the data, then record again. Read individual frames with ffmpeg when the s
### 6. Share
In a PostHog Desktop or cloud task, upload the MP4 as a task artifact.
-For a PR, upload it with `hogli pr:upload-video` and paste the markdown it prints.
+For a PR, run `hogli pr:upload-video`. With an open PR it attaches the video to the description as an inline player. Without one it prints a link to paste.
PR assets are public forever, so check the frames for private data before every upload.
## References
diff --git a/.agents/skills/writing-pr-descriptions/SKILL.md b/.agents/skills/writing-pr-descriptions/SKILL.md
index a295a059fea5..baccba4ae47c 100644
--- a/.agents/skills/writing-pr-descriptions/SKILL.md
+++ b/.agents/skills/writing-pr-descriptions/SKILL.md
@@ -123,7 +123,7 @@ Take each screenshot from the first source that can show the change:
Capture at `deviceScaleFactor: 2`. A 1x image looks soft on a high-density screen, and GitHub shrinks a wider image to fit the column. Take the before from the base branch the same way. A new surface has no before, so say that in one line.
-Upload with `hogli pr:upload-image <file>` and paste the markdown it prints. The first run only warns; re-run with `--yes`. The assets are public forever, so never upload customer data, customer names, secrets, or internal info.
+Upload with `hogli pr:upload-image <file>`. With an open PR it attaches the image to the description: a `![alt](./file.png)` reference already in the body is rewritten to the upload, and any other image is appended. Without a PR it prints markdown to paste. The first run only warns; re-run with `--yes`. The assets are public forever, so never upload customer data, customer names, secrets, or internal info.
Touching UI code without a visible change is common, and the mandate has to be dischargeable. When nothing looks different, say so in one line. A reviewer cannot tell that case from a missing screenshot, and silence reads as the second.
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index d0beae1275b3..cb27ce9ca048 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -14,7 +14,7 @@
<!-- If there are frontend changes, please include screenshots. For a new interaction that one screenshot cannot show, a short GIF or animated WebP of the flow can replace the after screenshot. -->
<!-- For frontend or user-facing changes under products/mobile/, before-and-after screenshots from physical iOS AND Android devices are required. Prefer multiple screen sizes. See products/mobile/AGENTS.md for capture and device coverage requirements. -->
-<!-- PostHog employees: `hogli pr:upload-image <file>` uploads to the public PostHog/pr-assets repo and prints markdown to paste here. Never upload customer data, secrets, or internal info. -->
+<!-- PostHog employees: `hogli pr:upload-image <file>` attaches a screenshot to this description once the PR exists, or prints markdown to paste here. Never upload customer data, secrets, or internal info. -->
<!-- If a reference design was involved, include a link to the relevant Figma frame! -->
diff --git a/AGENTS.md b/AGENTS.md
index 345080cc6f6d..33a82cc349fd 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -67,7 +67,7 @@ Invoke `/writing-pr-descriptions` before writing the body — it carries the sha
Always fill the `## 🤖 Agent context` section, including the exact model that wrote the code.
NEVER put sensitive information in a PR description or comment. A user may share sensitive data in an agent session; none of it belongs on the PR.
-**Screenshots:** Show frontend/visual changes with a screenshot, or with a feature reel when `/writing-pr-descriptions` calls for one. Upload with `hogli pr:upload-image <file>` and embed the printed markdown. The first run only warns and uploads nothing; re-run with `--yes` to confirm. Only PostHog employees can upload, but the public can permanently view these assets, so only upload the image if you're certain it doesn't contain customer data (including customer names), secrets, or sensitive internal info.
+**Screenshots:** Show frontend/visual changes with a screenshot, or with a feature reel when `/writing-pr-descriptions` calls for one. Run `hogli pr:upload-image <file>`: with an open PR it attaches the image to the description, otherwise it prints markdown to embed. The first run only warns and uploads nothing; re-run with `--yes` to confirm. Only PostHog employees can upload, but the public can permanently view these assets, so only upload the image if you're certain it doesn't contain customer data (including customer names), secrets, or sensitive internal info.
### Rules
diff --git a/docs/published/handbook/engineering/developing-locally.md b/docs/published/handbook/engineering/developing-locally.md
index 4cc8bba5b435..76761ecd5c35 100644
--- a/docs/published/handbook/engineering/developing-locally.md
+++ b/docs/published/handbook/engineering/developing-locally.md
@@ -77,7 +77,7 @@ If you commit from a devbox, keep your previous signing key on GitHub.
A devbox signs through your forwarded SSH agent, which can't hold a Secure Enclave key, so it keeps signing with the previous key.
Otherwise, once no repository signs with your previous key, remove it from your GitHub settings, so it can't sign verified commits anymore. Commits you already pushed stay verified.
-PR evidence uploads (`hogli pr:upload-image` and `hogli pr:upload-video`) prefer your stored GitHub CLI login over `GITHUB_TOKEN` from `.env.local`. Set `GH_TOKEN` to override the account; `GITHUB_TOKEN` remains the fallback when no CLI login exists.
+PR evidence uploads (`hogli pr:upload-image` and `hogli pr:upload-video`) attach to the PR description through `gh pr edit --attach` when the branch has an open PR and your gh supports `--attach`. Otherwise they upload to the public PostHog/pr-assets repo, and prefer your stored GitHub CLI login over `GITHUB_TOKEN` from `.env.local`. Set `GH_TOKEN` to override the account; `GITHUB_TOKEN` remains the fallback when no CLI login exists.
#### macOS
diff --git a/hogli.yaml b/hogli.yaml
index e81e97c00236..c97764f88d19 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -1176,10 +1176,10 @@ utilities:
description: Clear out unused Claude Code / Codex / PostHog Desktop / phw worktrees by age
pr:upload-image:
click: hogli_commands.upload_image:upload_image
- description: Upload screenshot(s) to the public PostHog/pr-assets repo and print embeddable PR markdown
+ description: Attach screenshot(s) to the PR description, or upload to PostHog/pr-assets and print markdown
pr:upload-video:
click: hogli_commands.upload_video:upload_video
- description: Upload demo video(s) to the public PostHog/pr-assets repo and print link markdown
+ description: Attach demo video(s) to the PR description, or upload to PostHog/pr-assets and print a link
utilities:posthog-worktree:
bin_script: posthog-worktree
description: Manage isolated git worktrees for PostHog development
diff --git a/tools/hogli-commands/hogli_commands/pr_assets.py b/tools/hogli-commands/hogli_commands/pr_assets.py
index 43aeb5293c46..477bb9fc7b95 100644
--- a/tools/hogli-commands/hogli_commands/pr_assets.py
+++ b/tools/hogli-commands/hogli_commands/pr_assets.py
@@ -33,8 +33,8 @@ _API: Final = "https://api.github.com/graphql"
_MAX_ATTEMPTS: Final = 5
PUBLIC_WARNING: Final = (
- "⚠ PUBLIC + PERMANENT upload to PostHog/pr-assets.\n"
- " SHA-pinned URLs keep serving even after the file is deleted, so an upload cannot be taken back.\n"
+ "⚠ PUBLIC + PERMANENT upload, to a public PR description or to PostHog/pr-assets.\n"
+ " Anyone can fetch the URL without logging in, and an upload cannot be taken back.\n"
" Never upload customer data, secrets, tokens, or internal-only information."
)
diff --git a/tools/hogli-commands/hogli_commands/pr_upload.py b/tools/hogli-commands/hogli_commands/pr_upload.py
index bd8e935fe83a..7d5c05dafa7d 100644
--- a/tools/hogli-commands/hogli_commands/pr_upload.py
+++ b/tools/hogli-commands/hogli_commands/pr_upload.py
@@ -2,11 +2,17 @@
The two commands differ only in what they accept and how they render what they
published. ``AssetKind`` carries those differences; ``run`` performs the flow they
-share: warn, validate, gate on --yes, publish, print markdown.
+share: warn, validate, gate on --yes, then publish.
+
+With an open PR and a gh that supports ``--attach``, the files go to GitHub's own
+attachment storage through ``gh pr edit --attach``. Otherwise they go to PostHog/pr-assets
+and the command prints markdown. The ``upload_route`` command property records which
+route ran.
"""
from __future__ import annotations
+import os
import shutil
import subprocess
from dataclasses import dataclass
@@ -14,8 +20,10 @@ from pathlib import Path
from typing import Final
import click
+from hogli import telemetry
from hogli_commands import pr_assets
+from hogli_commands.github_auth import github_token
# 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.
@@ -32,6 +40,8 @@ class AssetKind:
max_mb: int
commit_message: str
markdown: str # formatted with `label` and `url`
+ # gh refuses alt text on video, so only kinds that take it get `<file>#<alt>`.
+ gh_alt_text: bool
def escape_markdown_label(text: str) -> str:
@@ -54,7 +64,8 @@ def _open_pull_request() -> int | None:
return None
try:
result = subprocess.run(
- [gh, "pr", "view", "--json", "number", "--jq", ".number"],
+ # A branch whose PR merged or closed still resolves to it, so keep only an open one.
+ [gh, "pr", "view", "--json", "number,state", "--jq", 'select(.state == "OPEN") | .number'],
capture_output=True,
text=True,
timeout=10,
@@ -70,20 +81,90 @@ def _open_pull_request() -> int | None:
return None
+def _gh_with_attach() -> str | None:
+ """The gh binary when its `pr edit` supports `--attach`, or None.
+
+ Every failure falls back to the pr-assets route, so it is silent.
+ """
+ gh = shutil.which("gh")
+ if gh is None:
+ return None
+ try:
+ result = subprocess.run(
+ [gh, "pr", "edit", "--help"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ check=False,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return None
+ return gh if "--attach" in result.stdout else 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:
+ if pr is None:
return kind.commit_message
- return f"{kind.commit_message} for {_SOURCE_REPO}#{number}"
+ return f"{kind.commit_message} for {_SOURCE_REPO}#{pr}"
+
+
+def _attach_arg(path: Path, label: str) -> str:
+ """`<file>#<alt>` for gh, refusing a file name that gh would read in place of `path`.
+
+ gh uploads the longest existing file name before a `#`, so a sibling such as
+ `shot.png#alt` would be published although it never passed validation.
+ """
+ arg = f"{path}#{label}"
+ cuts = [i for i, char in enumerate(arg) if char == "#" and i > len(str(path))] + [len(arg)]
+ if any(Path(arg[:cut]).exists() for cut in cuts):
+ raise click.ClickException(
+ f"{path.name}: a file named like '{path.name}#…' exists, rename it or pick other alt text"
+ )
+ return arg
-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."""
+def _attach_to_pr(gh: str, files: tuple[Path, ...], caption: str | None, kind: AssetKind, pr: int) -> None:
+ """Attach every file to the PR description through `gh pr edit --attach`.
+
+ gh rewrites a body reference to the local path, such as `![alt](./shot.png)`, to the
+ uploaded asset, and appends a reference for every other file.
+ """
+ args = [gh, "pr", "edit", str(pr)]
+ for path in files:
+ label = caption if caption is not None else path.stem
+ args += ["--attach", _attach_arg(path, label) if kind.gh_alt_text else str(path)]
+
+ # hogli loads application credentials from .env.local, and gh would prefer them over
+ # the developer's own login, which is the one with upload access.
+ token = github_token(prefer_cli=True)
+ env = {**os.environ, "GH_TOKEN": token} if token else None
+
+ if caption is not None and not kind.gh_alt_text:
+ click.secho(f"gh takes no caption for a {kind.noun}, so {kind.caption_flag} is ignored.", fg="yellow", err=True)
+ click.secho(f"Attaching to the description of PR #{pr} …", fg="cyan", err=True)
+ if subprocess.run(args, check=False, env=env).returncode != 0:
+ # gh writes the files that did upload into the body before it exits non-zero.
+ raise click.ClickException(
+ "gh pr edit --attach failed, see its output above. Files that uploaded are already in the "
+ "PR description, so re-run only the ones that failed."
+ )
+ click.secho(f"✓ attached {len(files)} {kind.noun}(s) to the PR description", fg="green", err=True)
+
+
+def run(
+ files: tuple[Path, ...],
+ caption: str | None,
+ yes: bool,
+ kind: AssetKind,
+ pr: int | None = None,
+ print_markdown: bool = False,
+) -> None:
+ """Attach every file to the PR description, or publish it to pr-assets and print markdown."""
click.secho(pr_assets.PUBLIC_WARNING, fg="yellow", bold=True, err=True)
if caption is not None and len(files) > 1:
@@ -104,8 +185,21 @@ def run(files: tuple[Path, ...], caption: str | None, yes: bool, kind: AssetKind
)
raise SystemExit(1)
+ number = pr if pr is not None else _open_pull_request()
+ if print_markdown:
+ route = "pr_assets_requested"
+ elif number is None:
+ route = "pr_assets_no_pr"
+ elif (gh := _gh_with_attach()) is None:
+ route = "pr_assets_gh_without_attach"
+ else:
+ telemetry.add_command_properties(upload_route="gh_attach")
+ _attach_to_pr(gh, files, caption, kind, number)
+ return
+ telemetry.add_command_properties(upload_route=route)
+
click.secho(f"Uploading to {pr_assets.REPO} …", fg="cyan", err=True)
- urls = pr_assets.publish(files, message=commit_message(kind, pr))
+ urls = pr_assets.publish(files, message=commit_message(kind, number))
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
index 4374fe94a613..7308dfa15377 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_pr_upload.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_pr_upload.py
@@ -2,19 +2,23 @@ from __future__ import annotations
import subprocess
from collections.abc import Iterator
+from pathlib import Path
from subprocess import CompletedProcess
import pytest
from unittest.mock import patch
-from hogli_commands import pr_upload, upload_image
+import click
+from click.testing import CliRunner
+from hogli_commands import pr_assets, pr_upload, upload_image, upload_video
_KIND = upload_image._KIND
+_GH = "/usr/bin/gh"
@pytest.fixture
def gh_installed() -> Iterator[None]:
- with patch.object(pr_upload.shutil, "which", return_value="/usr/bin/gh"):
+ with patch.object(pr_upload.shutil, "which", return_value=_GH):
yield
@@ -22,16 +26,14 @@ 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()
[email protected](("pr", "expected"), [(78999, "add screenshot for posthog#78999"), (None, "add screenshot")])
+def test_commit_message_names_only_the_pr_number(pr: int | None, expected: str) -> None:
+ assert pr_upload.commit_message(_KIND, pr) == expected
-def test_detected_pr_is_named_in_the_message(gh_installed: None) -> None:
+def test_detected_pr_is_parsed(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"
+ assert pr_upload._open_pull_request() == 78999
@pytest.mark.parametrize(
@@ -45,13 +47,110 @@ def test_detected_pr_is_named_in_the_message(gh_installed: None) -> None:
],
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:
+def test_detection_failure_means_no_pr(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"
+ assert pr_upload._open_pull_request() is None
-def test_missing_gh_leaves_the_plain_message() -> None:
+def test_missing_gh_means_no_pr() -> None:
with patch.object(pr_upload.shutil, "which", return_value=None):
- assert pr_upload.commit_message(_KIND, None) == "add screenshot"
+ assert pr_upload._open_pull_request() is None
+
+
+ ("command", "filename", "caption_args", "attach_suffix"),
+ [
+ (upload_image.upload_image, "after.png", ["--alt", "after fix"], "#after fix"),
+ (upload_video.upload_video, "demo.mp4", ["--label", "demo"], ""),
+ ],
+ ids=["image_keeps_alt", "video_drops_label"],
+)
+def test_open_pr_and_attach_capable_gh_edit_the_pr_description(
+ tmp_path: Path, command: click.Command, filename: str, caption_args: list[str], attach_suffix: str
+) -> None:
+ # gh rejects alt text on video, so a label forwarded as `#label` would fail the upload.
+ path = tmp_path / filename
+ path.write_bytes(b"fake bytes")
+ with (
+ patch.object(pr_upload, "_gh_with_attach", return_value=_GH),
+ patch.object(pr_upload, "github_token", return_value="personal-token"),
+ patch.object(pr_upload.subprocess, "run", return_value=_gh_returns("")) as run,
+ patch.object(pr_upload.telemetry, "add_command_properties") as add_props,
+ patch.object(pr_assets, "publish") as publish,
+ ):
+ result = CliRunner(mix_stderr=False).invoke(command, ["--yes", "--pr", "1234", *caption_args, str(path)])
+
+ assert result.exit_code == 0, result.stderr
+ run.assert_called_once()
+ assert run.call_args.args[0] == [_GH, "pr", "edit", "1234", "--attach", f"{path}{attach_suffix}"]
+ # an application GITHUB_TOKEN from .env.local must not replace the developer's own login
+ assert run.call_args.kwargs["env"]["GH_TOKEN"] == "personal-token"
+ add_props.assert_called_once_with(upload_route="gh_attach")
+ publish.assert_not_called()
+
+
+def test_sibling_file_gh_would_read_instead_is_refused(tmp_path: Path) -> None:
+ # gh takes the longest existing name before a `#`, so this sibling would be published
+ # in place of the validated file.
+ path = tmp_path / "after.png"
+ path.write_bytes(b"fake bytes")
+ secret = tmp_path / "secret.env"
+ secret.write_bytes(b"SECRET=1")
+ (tmp_path / "after.png#state.png").symlink_to(secret)
+ with (
+ patch.object(pr_upload, "_gh_with_attach", return_value=_GH),
+ patch.object(pr_upload.subprocess, "run") as run,
+ ):
+ result = CliRunner(mix_stderr=False).invoke(
+ upload_image.upload_image, ["--yes", "--pr", "1234", "--alt", "state.png", str(path)]
+ )
+
+ assert result.exit_code != 0
+ run.assert_not_called()
+
+
+def test_failed_gh_attach_exits_nonzero(tmp_path: Path) -> None:
+ path = tmp_path / "after.png"
+ path.write_bytes(b"fake bytes")
+ with (
+ patch.object(pr_upload, "_gh_with_attach", return_value=_GH),
+ patch.object(pr_upload, "github_token", return_value=None),
+ patch.object(pr_upload.subprocess, "run", return_value=_gh_returns("", returncode=1)),
+ patch.object(pr_assets, "publish") as publish,
+ ):
+ result = CliRunner(mix_stderr=False).invoke(upload_image.upload_image, ["--yes", "--pr", "1234", str(path)])
+
+ assert result.exit_code != 0
+ publish.assert_not_called()
+
+
+ ("extra_args", "detected_pr", "gh", "route"),
+ [
+ (["--print-markdown"], 1234, _GH, "pr_assets_requested"),
+ ([], None, _GH, "pr_assets_no_pr"),
+ ([], 1234, None, "pr_assets_gh_without_attach"),
+ ],
+ ids=["print_markdown", "no_pr", "gh_without_attach"],
+)
+def test_pr_assets_route_records_why_gh_was_skipped(
+ tmp_path: Path, extra_args: list[str], detected_pr: int | None, gh: str | None, route: str
+) -> None:
+ path = tmp_path / "after.png"
+ path.write_bytes(b"fake bytes")
+ with (
+ patch.object(pr_upload, "_open_pull_request", return_value=detected_pr),
+ patch.object(pr_upload, "_gh_with_attach", return_value=gh),
+ patch.object(pr_upload.subprocess, "run") as run,
+ patch.object(pr_upload.telemetry, "add_command_properties") as add_props,
+ patch.object(pr_assets, "publish", return_value=["https://example.com/a.png"]) as publish,
+ ):
+ result = CliRunner(mix_stderr=False).invoke(upload_image.upload_image, ["--yes", *extra_args, str(path)])
+
+ assert result.exit_code == 0, result.stderr
+ assert result.stdout.strip() == "![after](https://example.com/a.png)"
+ add_props.assert_called_once_with(upload_route=route)
+ publish.assert_called_once()
+ run.assert_not_called()
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 07f84c9b665c..7401d693eb3b 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_upload_image.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_upload_image.py
@@ -33,8 +33,12 @@ def png(tmp_path: Path) -> Path:
@pytest.fixture(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):
+ # on and these tests pass or fail depending on whether that branch has a PR. The gh
+ # route is covered in test_pr_upload, so these pin the pr-assets route.
+ with (
+ patch.object(pr_upload, "_open_pull_request", return_value=None),
+ patch.object(pr_upload, "_gh_with_attach", return_value=None),
+ ):
yield
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 cce8620f2f67..a186f835887e 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_upload_video.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_upload_video.py
@@ -32,8 +32,12 @@ def mp4(tmp_path: Path) -> Path:
@pytest.fixture(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):
+ # on and these tests pass or fail depending on whether that branch has a PR. The gh
+ # route is covered in test_pr_upload, so these pin the pr-assets route.
+ with (
+ patch.object(pr_upload, "_open_pull_request", return_value=None),
+ patch.object(pr_upload, "_gh_with_attach", return_value=None),
+ ):
yield
diff --git a/tools/hogli-commands/hogli_commands/upload_image.py b/tools/hogli-commands/hogli_commands/upload_image.py
index b46d74587162..c3b9e1d734d6 100644
--- a/tools/hogli-commands/hogli_commands/upload_image.py
+++ b/tools/hogli-commands/hogli_commands/upload_image.py
@@ -1,10 +1,12 @@
-"""hogli pr:upload-image: upload screenshots to the public PostHog/pr-assets repo.
+"""hogli pr:upload-image: put screenshots in a PR description.
-Turns a local screenshot into an embeddable, commit-pinned markdown image line for a PR
-description in one command. Running through hogli means the usage is tracked by hogli's
-built-in command telemetry.
+With an open PR and a gh that supports `--attach`, this runs `gh pr edit --attach`, so
+the screenshot lands in GitHub's own attachment storage. Otherwise it commits the file to
+the public PostHog/pr-assets repo and prints a commit-pinned markdown image line. Running
+through hogli means the usage, including which route ran, is tracked by hogli's built-in
+command telemetry.
-Auth reuses a GitHub token from GH_TOKEN/GITHUB_TOKEN or the gh CLI (`gh auth token`),
+On the pr-assets route, auth reuses a GitHub token from GH_TOKEN/GITHUB_TOKEN or the gh CLI (`gh auth token`),
so it works with or without gh installed as long as a token with write access to a
PostHog org repo is available. The target repo is public by design: GitHub renders PR
images through its anonymous camo proxy, which requires anonymous read. The command
@@ -28,6 +30,7 @@ _KIND: Final = AssetKind(
max_mb=10, # GitHub caps image/gif attachments at 10 MB; larger is a video or wrong file
commit_message="add screenshot",
markdown="![{label}]({url})",
+ gh_alt_text=True,
)
@@ -42,23 +45,33 @@ _KIND: Final = AssetKind(
type=click.IntRange(min=1),
help="PR the screenshot documents (defaults to the current branch's open PR).",
)
+ "--print-markdown",
+ is_flag=True,
+ help="Upload to PostHog/pr-assets and print markdown, instead of attaching to the PR description.",
+)
# 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, pr: int | None, yes: bool) -> None:
- """Upload screenshot(s) to the public PostHog/pr-assets repo and print embeddable markdown.
+def upload_image(files: tuple[Path, ...], alt: str | None, pr: int | None, print_markdown: bool, yes: bool) -> None:
+ """Attach screenshot(s) to the PR description, or upload them and print markdown.
+
+ With an open PR and a gh whose `pr edit` has `--attach`, runs `gh pr edit --attach`. A reference to the
+ local file already in the description, such as `![after](./after.png)`, is rewritten
+ to the upload. Any other screenshot is appended to the description.
- Prints one `![alt](url)` line per file to stdout (everything else goes to stderr),
- so you can pipe or copy the markdown straight into a PR description. URLs are pinned
- to the commit sha, so they keep rendering even if the file is later moved or deleted.
+ With no PR, an older gh, or --print-markdown, uploads to the public PostHog/pr-assets
+ repo and prints one `![alt](url)` line per file to stdout (everything else goes to
+ stderr). URLs are pinned to the commit sha, so they keep rendering even if the file
+ is later moved or deleted.
\b
hogli pr:upload-image screenshot.png
hogli pr:upload-image --alt "dashboard after fix" result.png
hogli pr:upload-image before.png after.png
+ hogli pr:upload-image --print-markdown screenshot.png
- Uploads land in a PUBLIC repo (GitHub image embeds require anonymous read) and are
- permanent: SHA-pinned URLs keep serving even after the file is deleted. Never upload
- customer data, secrets, or internal-only information.
+ Uploads are PUBLIC (anyone can fetch the URL) and permanent. Never upload customer
+ data, secrets, or internal-only information.
"""
- run(files, alt, yes, _KIND, pr)
+ run(files, alt, yes, _KIND, pr, print_markdown)
diff --git a/tools/hogli-commands/hogli_commands/upload_video.py b/tools/hogli-commands/hogli_commands/upload_video.py
index 9e26b1b3ac12..fe7f90d22ea1 100644
--- a/tools/hogli-commands/hogli_commands/upload_video.py
+++ b/tools/hogli-commands/hogli_commands/upload_video.py
@@ -1,10 +1,9 @@
-"""hogli pr:upload-video: upload short demo videos to the public PostHog/pr-assets repo.
+"""hogli pr:upload-video: put short demo videos in a PR description.
-Same storage, auth, and confirmation gate as pr:upload-image (the shared pr_upload
-body), but for video files. GitHub renders no inline player for raw-hosted video, so
-the printed markdown is a plain [label](url) link that opens or downloads the file
-rather than an embed. For an inline player, drag the video into the PR comment editor
-by hand instead.
+Same routes, auth, and confirmation gate as pr:upload-image (the shared pr_upload body),
+but for video files. On the gh route the video renders as an inline player. On the
+pr-assets route GitHub renders no player for raw-hosted video, so the printed markdown
+is a plain [label](url) link that opens or downloads the file.
"""
from __future__ import annotations
@@ -26,12 +25,13 @@ _KIND: Final = AssetKind(
max_mb=10,
commit_message="add video",
markdown="[{label}]({url})",
+ gh_alt_text=False,
)
@click.command(name="pr:upload-video")
@click.argument("files", nargs=-1, required=True, type=click.Path(exists=True, dir_okay=False, path_type=Path))
[email protected]("--label", help="Link text for the markdown (defaults to each file's stem).")
[email protected]("--label", help="Link text for the pr-assets 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.
@click.option(
@@ -39,23 +39,32 @@ _KIND: Final = AssetKind(
type=click.IntRange(min=1),
help="PR the video documents (defaults to the current branch's open PR).",
)
+ "--print-markdown",
+ is_flag=True,
+ help="Upload to PostHog/pr-assets and print a link, instead of attaching to the PR description.",
+)
# 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, pr: int | None, yes: bool) -> None:
- """Upload demo video(s) to the public PostHog/pr-assets repo and print link markdown.
+def upload_video(files: tuple[Path, ...], label: str | None, pr: int | None, print_markdown: bool, yes: bool) -> None:
+ """Attach demo video(s) to the PR description, or upload them and print link markdown.
+
+ With an open PR and a gh whose `pr edit` has `--attach`, runs `gh pr edit --attach`
+ and the video renders as an inline player. A reference to the local file already in
+ the description is rewritten to the upload. Any other video is appended. A video
+ takes no caption on this route, so --label is ignored.
- Prints one `[label](url)` line per file to stdout (everything else goes to stderr).
- GitHub does not render an inline player for raw-hosted video, so the link opens or
- downloads the file; for an inline player, drag the video into the PR comment editor
- by hand instead.
+ With no PR, an older gh, or --print-markdown, uploads to the public PostHog/pr-assets
+ repo and prints one `[label](url)` line per file to stdout (everything else goes to
+ stderr). GitHub renders no player for raw-hosted video, so the link opens or
+ downloads the file.
\b
hogli pr:upload-video demo.mp4
hogli pr:upload-video --label "duplicate-question demo" frontend-qa.mp4
- Uploads land in a PUBLIC repo (anyone can fetch the URL) and are permanent:
- SHA-pinned URLs keep serving even after the file is deleted. Never upload customer
+ Uploads are PUBLIC (anyone can fetch the URL) and permanent. Never upload customer
data, secrets, or internal-only information.
"""
- run(files, label, yes, _KIND, pr)
+ run(files, label, yes, _KIND, pr, print_markdown)