From 82ddcfde7e83215947e9a5e3d014369fc0fe28d5 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 17 Nov 2026 22:16:38 -0500 Subject: [PATCH 1/2] Add Preview access to repository settings and document how previews are found A per-repository dialog holds the preview's address template and one sealed secret (header lines, query parameters or a password) for a protected preview; the secret is never shown again. The new Pull request previews page describes every place a preview is read from, how long it is waited on, how protection is handled and the template's placeholders. --- dashboard/e2e/preview-access.spec.ts | 91 +++++++ dashboard/src/app/settings/repos/page.tsx | 21 ++ .../src/components/preview-access-dialog.tsx | 234 ++++++++++++++++++ dashboard/src/lib/api.ts | 30 +++ docs/content/docs/concepts/meta.json | 2 +- docs/content/docs/concepts/previews.mdx | 69 ++++++ docs/content/release-notes.md | 5 + 7 files changed, 451 insertions(+), 1 deletion(-) create mode 100644 dashboard/e2e/preview-access.spec.ts create mode 100644 dashboard/src/components/preview-access-dialog.tsx create mode 100644 docs/content/docs/concepts/previews.mdx diff --git a/dashboard/e2e/preview-access.spec.ts b/dashboard/e2e/preview-access.spec.ts new file mode 100644 index 00000000..30ec497f --- /dev/null +++ b/dashboard/e2e/preview-access.spec.ts @@ -0,0 +1,91 @@ +import { expect, test, type Page, type Route } from "@playwright/test"; + +// A repository's preview access (its address template and the secret a +// protected preview takes), from Settings > Repositories. +// Every API call is answered here; nothing reaches a real backend. + +interface Backend { + role: string; + saved: Record | null; + calls: { method: string; path: string; body: Record | null }[]; +} + +async function mockApi(page: Page, init: Partial = {}): Promise { + const db: Backend = { role: "admin", saved: null, calls: [], ...init }; + const json = (route: Route, body: unknown, status = 200) => + route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); + await page.route((url) => url.hostname !== "localhost", (route) => route.abort()); + await page.route( + (url) => url.hostname === "localhost" && /^\/(api|auth)\//.test(url.pathname), + async (route) => { + const req = route.request(); + const p = new URL(req.url()).pathname; + const method = req.method(); + const body = req.postData() ? (JSON.parse(req.postData() as string) as Record) : null; + db.calls.push({ method, path: p, body }); + if (p === "/api/me") + return json(route, { user_id: "u_1", team_id: "t_1", github_login: null, email: "person@example.com", avatar_url: "", role: db.role, auth_provider: "email", mfa_enabled: false }); + if (p === "/api/banners") return json(route, { banners: [] }); + if (p === "/api/teams") return json(route, { teams: [{ team_id: "t_1", org: "your-team", status: "active", current: true }] }); + if (p === "/api/repos") + return json(route, { repos: [{ name: "your-team/web", enabled: true, ticket_source: "github", onboard_status: "ready" }, { name: "your-team/api", enabled: false, ticket_source: "github" }] }); + if (p === "/api/github/installation-status") return json(route, { status: "connected", github_org: "your-team", installation_id: 7 }); + if (p === "/api/repos/your-team/web/preview-access") { + if (method === "GET") return json(route, db.saved ?? { configured: false, repo: "your-team/web" }); + if (method === "PUT") { + db.saved = { configured: true, repo: "your-team/web", kind: body?.kind, address: body?.address, secret_set: body?.kind !== "none" }; + return json(route, db.saved); + } + if (method === "DELETE") { + db.saved = null; + return json(route, { configured: false, repo: "your-team/web" }); + } + } + return json(route, { error: `not mocked: ${method} ${p}` }, 404); + }, + ); + return db; +} + +test("an admin saves a preview address and a header secret that is never shown again", async ({ page }) => { + const db = await mockApi(page); + await page.goto("/settings/repos/"); + await page.getByRole("button", { name: "Preview access for your-team/web" }).click(); + const dialog = page.getByTestId("preview-access-dialog"); + await expect(dialog).toBeVisible(); + // A fixed address is a shared environment, never a pull request's own. + await dialog.getByLabel(/Preview address/).fill("https://staging.your-domain.example"); + await expect(dialog.getByText(/needs \{pr\}/)).toBeVisible(); + await expect(dialog.getByRole("button", { name: "Save" })).toBeDisabled(); + await dialog.getByLabel(/Preview address/).fill("https://pr-{pr}.preview.your-domain.example"); + await dialog.getByLabel("How the preview is protected").click(); + await page.getByRole("option", { name: /A header/ }).click(); + await dialog.getByLabel("Header name", { exact: true }).fill("X-Preview-Bypass"); + await dialog.getByLabel("Value").first().fill("s3cr3t-value"); + await dialog.getByRole("button", { name: "Save" }).click(); + await expect(dialog).toBeHidden(); + const put = db.calls.find((c) => c.method === "PUT"); + expect(put?.body).toMatchObject({ kind: "header", address: "https://pr-{pr}.preview.your-domain.example", secret: "X-Preview-Bypass: s3cr3t-value" }); + await page.getByRole("button", { name: "Preview access for your-team/web" }).click(); + await expect(dialog.getByLabel("Value").first()).toHaveValue(""); + await expect(dialog.getByRole("button", { name: "Remove" })).toBeVisible(); +}); + +test("a member sees no preview access button", async ({ page }) => { + await mockApi(page, { role: "member" }); + await page.goto("/settings/repos/"); + await expect(page.getByRole("list", { name: "Repositories" }).getByRole("listitem")).toHaveCount(2); + await expect(page.getByRole("button", { name: /Preview access for/ })).toHaveCount(0); +}); + +for (const width of [375, 1440]) { + test(`the preview access dialog has no horizontal scroll at ${width}px`, async ({ page }) => { + await page.setViewportSize({ width, height: 900 }); + await mockApi(page); + await page.goto("/settings/repos/"); + await page.getByRole("button", { name: "Preview access for your-team/web" }).click(); + await expect(page.getByTestId("preview-access-dialog")).toBeVisible(); + const overflow = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth); + expect(overflow).toBeLessThanOrEqual(0); + }); +} diff --git a/dashboard/src/app/settings/repos/page.tsx b/dashboard/src/app/settings/repos/page.tsx index f624d81a..5a167fde 100644 --- a/dashboard/src/app/settings/repos/page.tsx +++ b/dashboard/src/app/settings/repos/page.tsx @@ -10,6 +10,7 @@ import { api, type Repo } from "@/lib/api"; import { githubAppUrl } from "@/lib/runtime-config"; import { RoleGuard } from "@/components/role-guard"; import { StagingCmsDialog } from "@/components/staging-cms-dialog"; +import { PreviewAccessDialog } from "@/components/preview-access-dialog"; import { useToast } from "@/components/toast"; import { Page, PageHeader } from "@/components/page"; import { buttonClass, secondaryButton } from "@/components/ui"; @@ -78,6 +79,8 @@ function ReposPage() { const [savingRole, setSavingRole] = useState(null); // The repository whose staging CMS connection is open, if any. const [stagingRepo, setStagingRepo] = useState(null); + // The repository whose preview access is open, if any. + const [previewRepo, setPreviewRepo] = useState(null); // Turning repos on or off, syncing and routing roles need `repos`. const { ready, can } = useCan(); const canManage = can("repos"); @@ -312,6 +315,17 @@ function ReposPage() { Staging content )} + {repo.enabled && canManage && ( + + )} } /> @@ -321,6 +335,13 @@ function ReposPage() { )} shownCount} loading={false} onClick={() => setShownCount((n) => n + PAGE_SIZE)} /> + {previewRepo && ( + !v && setPreviewRepo(null)} + /> + )} {stagingRepo && ( !PLACEHOLDERS.includes(b)); + if (unknown) return `${unknown} isn't filled in; use ${PLACEHOLDERS.join(", ")}.`; + if (!["{pr}", "{branch}", "{branch_slug}", "{sha}", "{short_sha}"].some((p) => t.includes(p))) + return "The address needs {pr}, {branch}, {branch_slug}, {sha} or {short_sha}, so each pull request gets its own preview."; + return ""; +} + +const KINDS: { value: PreviewAccessKind; label: string }[] = [ + { value: "none", label: "Not protected" }, + { value: "header", label: "A header (a bypass token or a service token pair)" }, + { value: "query", label: "A query parameter" }, + { value: "basic", label: "A user name and password" }, +]; + +export function PreviewAccessDialog({ + repo, + open, + onOpenChange, +}: { + repo: string; + open: boolean; + onOpenChange: (open: boolean) => void; +}) { + const [saved, setSaved] = useState(null); + const [address, setAddress] = useState(""); + const [kind, setKind] = useState("none"); + // Header kind: up to two `name: value` pairs (a token, or an id and a secret). + const [names, setNames] = useState(["", ""]); + const [values, setValues] = useState(["", ""]); + // Query kind: `name=value`; password kind: user and password. + const [single, setSingle] = useState(""); + const [user, setUser] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const ids = { address: useId(), kind: useId(), single: useId(), user: useId(), h0: useId(), h1: useId(), v0: useId(), v1: useId() }; + + // Each opening reads what is saved; the secret is never sent back. + useEffect(() => { + if (!open) return; + setError(""); + setSaved(null); + setNames(["", ""]); + setValues(["", ""]); + setSingle(""); + setUser(""); + api + .getPreviewAccess(repo) + .then((a) => { + setSaved(a); + setAddress(a.address ?? ""); + setKind(a.kind ?? "none"); + }) + .catch(() => setError("Couldn't load the preview access. Try again.")); + }, [open, repo]); + + const problem = templateProblem(address); + const keepsSecret = !!saved?.secret_set && saved?.kind === kind; + + const secret = (): string => { + if (kind === "header") + return names + .map((n, i) => (n.trim() && values[i].trim() ? `${n.trim()}: ${values[i].trim()}` : "")) + .filter(Boolean) + .join("\n"); + if (kind === "basic") return user.trim() && single.trim() ? `${user.trim()}:${single.trim()}` : ""; + if (kind === "query") return single.trim(); + return ""; + }; + + const save = async () => { + setBusy(true); + setError(""); + try { + const s = secret(); + const a = await api.savePreviewAccess(repo, { kind, address: address.trim(), secret: s || undefined }); + setSaved(a); + onOpenChange(false); + } catch (e) { + setError(e instanceof Error && e.message ? e.message : "Couldn't save. Try again."); + } + setBusy(false); + }; + + const remove = async () => { + setBusy(true); + setError(""); + try { + await api.deletePreviewAccess(repo); + onOpenChange(false); + } catch { + setError("Couldn't remove the preview access. Try again."); + } + setBusy(false); + }; + + const secretHint = keepsSecret ? "Saved. Enter a new one to replace it." : ""; + + return ( + !busy && onOpenChange(v)} + testId="preview-access-dialog" + title={`Preview access for ${repo}`} + description="Coderhelm finds each pull request's preview on its own, in the commit's deployments, deploy statuses, preview checks and bot comments, and checks the changed pages there. Set this only when nothing publishes the preview's address, or when the preview asks for a sign-in." + > +
{ + e.preventDefault(); + if (!problem) void save(); + }} + > +
+ + setAddress(e.target.value)} + placeholder="https://pr-{pr}.preview.your-domain.example" + className={inputClass} + autoComplete="off" + aria-invalid={!!problem || undefined} + aria-describedby={`${ids.address}-help`} + /> +

+ {problem || + "Used only when nothing on the commit publishes the address. {pr} is the pull request number, {branch_slug} the branch as hosts put it in a host name, {sha} and {short_sha} the commit."} +

+
+
+ + setNames((n) => n.map((x, j) => (j === i ? e.target.value : x)))} + className={inputClass} + autoComplete="off" + /> +
+
+ + setValues((v) => v.map((x, j) => (j === i ? e.target.value : x)))} + placeholder={i === 0 ? secretHint : ""} + /> +
+ + ))} + {kind === "basic" && ( +
+ + setUser(e.target.value)} className={inputClass} autoComplete="off" /> +
+ )} + {(kind === "basic" || kind === "query") && ( +
+ + setSingle(e.target.value)} placeholder={secretHint} /> +
+ )} + {kind !== "none" && ( +

+ Kept sealed, never shown again, and sent only to the preview's own host when Coderhelm opens its pages. +

+ )} + {error && ( +

+ {error} +

+ )} + + {saved?.configured && ( + + )} + + + +
+
+ ); +} diff --git a/dashboard/src/lib/api.ts b/dashboard/src/lib/api.ts index 6dbc726c..e2c395db 100644 --- a/dashboard/src/lib/api.ts +++ b/dashboard/src/lib/api.ts @@ -515,6 +515,15 @@ export const api = { }), deleteStagingCms: (repo: string) => request(`/api/repos/${repo}/staging-cms`, { method: "DELETE" }), + /** The repository's preview address template and protection (never its secret). */ + getPreviewAccess: (repo: string) => request(`/api/repos/${repo}/preview-access`), + savePreviewAccess: (repo: string, body: PreviewAccessInput) => + request(`/api/repos/${repo}/preview-access`, { + method: "PUT", + body: JSON.stringify(body), + }), + deletePreviewAccess: (repo: string) => + request(`/api/repos/${repo}/preview-access`, { method: "DELETE" }), // Stats getStats: () => request<{ month: Stats; all_time: Stats }>("/api/stats"), @@ -2744,6 +2753,27 @@ export interface StagingCms { token_set?: boolean; } +/** How a repository's preview is protected. */ +export type PreviewAccessKind = "none" | "header" | "query" | "basic"; + +/** A repository's preview access, as the gateway shows it. */ +export interface PreviewAccess { + configured: boolean; + repo: string; + kind?: PreviewAccessKind; + /** The preview's address template, "" when the preview publishes its own. */ + address?: string; + /** Whether a secret is saved; the secret itself is never returned. */ + secret_set?: boolean; +} + +export interface PreviewAccessInput { + kind: PreviewAccessKind; + address: string; + /** Left out to keep the saved secret (same kind only). */ + secret?: string; +} + export interface StagingCmsInput { provider: "sanity"; project_id: string; diff --git a/docs/content/docs/concepts/meta.json b/docs/content/docs/concepts/meta.json index 521dd532..4f7fb634 100644 --- a/docs/content/docs/concepts/meta.json +++ b/docs/content/docs/concepts/meta.json @@ -1,4 +1,4 @@ { "title": "Concepts", - "pages": ["index", "agents", "agent-permissions", "skills", "memories", "code-graph", "data-sources", "aws-accounts", "test-fixes", "connections", "knowledge", "knowledge-sources", "chat", "roles", "sign-in", "token-limits", "usage-and-audit"] + "pages": ["index", "agents", "agent-permissions", "skills", "memories", "code-graph", "data-sources", "aws-accounts", "test-fixes", "previews", "connections", "knowledge", "knowledge-sources", "chat", "roles", "sign-in", "token-limits", "usage-and-audit"] } diff --git a/docs/content/docs/concepts/previews.mdx b/docs/content/docs/concepts/previews.mdx new file mode 100644 index 00000000..75153d69 --- /dev/null +++ b/docs/content/docs/concepts/previews.mdx @@ -0,0 +1,69 @@ +--- +title: Pull request previews +description: How CoderHelm finds each pull request's preview, waits for it, gets through a protected one, and checks the changed pages on it. +--- + +When a pull request changes something a person sees in the browser, CoderHelm checks it on the pull request's own preview before calling it ready: it waits for the preview of the exact commit at the head of the pull request, opens the changed pages at desktop and phone width, and puts the screenshots in the description. Most teams set nothing for this. CoderHelm reads the preview from wherever your host or your CI already publishes it. + +## Where CoderHelm finds the preview + +CoderHelm reads every place a preview's address is usually published, and only trusts what belongs to the head commit: + +| Where | What counts | +|---|---| +| **Deployments on the commit** | A deployment of the head commit to a preview, pull request or other non-production environment. Its newest status says whether it is building, up, failed or taken down, and its environment address is the preview. Hosting integrations write these, and so does a CI job that sets `environment: { name, url }`. Production and shared environments never count, unless the deployment says it is temporary. | +| **Deploy statuses** | A commit status on the head commit whose name or description says it is a deploy or a preview, with the preview as its link. CI build statuses and links to a host's dashboard or build log are ignored. | +| **Preview checks** | A check run on the head commit whose name or output says it deploys a preview (or that your workflows run as the preview deploy), with the address in its output. | +| **Bot comments** | A bot's comment on the pull request, usually edited on every push. It counts when it names the head commit, or names no commit and was edited after the head commit was made. A comment that names an older commit is an older deploy and is ignored. A table with one row per app is read row by row. | +| **The description** | A link labelled as the preview in the pull request description. It is used only when nothing on the head commit carries an address, because such a link often keeps the same address across pushes. | +| **Your address template** | The preview address you set in **Settings**, **Repositories**, **Preview access** (see below). It is also used only when nothing on the head commit carries an address. | + +When several of these answer, the most direct one wins, in the order of the table. A preview of an older commit is never used for a newer one. + +### Several previews on one pull request + +In a monorepo each app often gets its own preview. CoderHelm picks the one named after the app the change touches (for example, a change under `apps/web/` picks the preview named for `web`), and never another app's preview. A preview named after an API or backend service is used only when nothing else fits, because it has no pages to capture. + +## Waiting for the preview + +- **Still building.** While the head commit's preview is queued or building, CoderHelm waits and looks again every two minutes, even when nothing else on the pull request changes. +- **Nothing published yet.** If nothing at all has appeared for the head commit, CoderHelm waits six minutes, because most hosts start a preview within a minute or two of a push. After that, it says that nothing publishes a preview for this commit. +- **Limit.** It waits at most 60 minutes for one commit. After that it says what it was waiting on, and a new push starts the wait again. +- **Failed or taken down.** A preview that failed or was taken down is reported with where that was read. CoderHelm does not wait on it. +- **Warming up.** A page that answers 404, 502, 503 or 504 right after the preview comes up is tried again, up to three times. + +## Protected previews + +If your previews ask for a sign-in, give CoderHelm a way through in **Settings**, **Repositories**, **Preview access**. Pick the kind your host uses: + +| Kind | What you enter | How it is used | +|---|---|---| +| **A header** | One or two header names with their values: a protection bypass token, or a sign-in service's client id and client secret | Sent with every request to the preview's own host, and never to any other host the page loads from | +| **A query parameter** | `name=value` (join several with `&`), such as a bypass token that sets a cookie | Added to each page's address | +| **A user name and password** | The preview's basic sign-in | Sent only when the preview's own host asks for it | + +The secret is sealed when you save it and never shown again. Only the sandbox that opens the preview's pages receives it, and it is never written to a log, a screenshot record or the pull request. To replace it, enter a new one. To switch to another kind, enter that kind's secret. + +If a page answers 401 or 403, or sends the browser to a sign-in page on another host, the pull request says so and points to this setting. If a secret is saved, it says the preview refused the saved access. + +A preview reachable only from an allowed list of network addresses can't be opened from CoderHelm's sandbox unless that list allows it. Use a bypass header or token instead if your host offers one. + +## The preview address template + +Set this only when nothing on the commit publishes the preview's address. The template starts with `https://` and names the pull request with these placeholders: + +| Placeholder | Filled in with | +|---|---| +| `{pr}` | The pull request number | +| `{branch}` | The branch name as it is, with its slashes (for previews served under a path) | +| `{branch_slug}` | The branch name as hosts put it in a host name: lowercase, every other character a `-`, no `-` at either end | +| `{sha}`, `{short_sha}` | The head commit, in full or as its first seven characters | +| `{owner}`, `{repo}` | The repository's owner and name, as slugs | + +Examples: `https://pr-{pr}.preview.your-domain.example` or `https://{branch_slug}.web.your-domain.example`. A fixed address such as a staging site is refused, because it is shared and not the pull request's own. A host name part longer than 63 characters is cut to 63, as DNS requires. If your host shortens long branch names some other way, rely on its deployments or comments instead, because they carry the exact address. + +A test address that names `{pr}` in the Tests settings ([Failing and flaky tests](/concepts/test-fixes)) is used as the template when Preview access sets none. + +## What the GitHub App needs + +Reading deployments needs **Deployments: read**, and reading deploy statuses needs **Commit statuses: read**. Without them, CoderHelm still reads the preview from checks, comments, the description and your template. diff --git a/docs/content/release-notes.md b/docs/content/release-notes.md index 048405e6..8827a010 100644 --- a/docs/content/release-notes.md +++ b/docs/content/release-notes.md @@ -5,6 +5,11 @@ the team in plain words, one "## : " heading per release, and link t pull requests that shipped it. Leave out CI, pins and dependency bumps. --> +## November 17, 2026: previews found wherever your host publishes them + +- **Previews are found wherever they are published.** CoderHelm reads the head commit's deployments, deploy statuses, preview checks and bot comments, then the description and your address template. Only what belongs to the head commit counts first, and the changed app's preview is picked in a monorepo. It waits at most an hour for a preview that is still building, and reports a failed one with where it read it. ([#772](https://github.com/CoderHelm/coderhelm-platform/pull/772)) +- **Protected previews.** **Settings**, **Repositories**, **Preview access** holds the preview's address when nothing publishes it, and one sealed secret: a header, a query parameter or a password. CoderHelm sends that secret only to the preview's own host. Details: [Pull request previews](/concepts/previews). ([#772](https://github.com/CoderHelm/coderhelm-platform/pull/772)) + ## November 17, 2026: tests that actually run, and plan dependents released by their own ticket - **Tests actually run.** Workspace packages install from the workspace root with CI's own job, cached install and pinned versions, and a failed install says why. Test runs that don't fit in a step get a fresh step of their own instead of being skipped, more CI test commands are read, and the run page and pull request say how many tests ran with and without the change. ([#769](https://github.com/CoderHelm/coderhelm-platform/pull/769)) From 258ad30cc320a6673d1c842fd26e925ce698d4fc Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Wed, 18 Nov 2026 00:04:51 -0500 Subject: [PATCH 2/2] Docs: record the previews page --- docs/published-pages.json | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/published-pages.json b/docs/published-pages.json index 8125b6d4..0c5d022d 100644 --- a/docs/published-pages.json +++ b/docs/published-pages.json @@ -58,6 +58,7 @@ "/concepts/knowledge-sources/", "/concepts/knowledge/", "/concepts/memories/", + "/concepts/previews/", "/concepts/roles/", "/concepts/sign-in/", "/concepts/skills/",