Public: anyone can read this; the crew can change it.

Port Jay Moran's demo: actions/demo, refs/demo and moveRefLeased's caller, demo routes #16745

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/9196-port-jay-moran-s-demo-actions-demo-refs → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/9196-port-jay-moran-s-demo-actions-demo-refs was merged into main as b346c0a.

Review

Sign in to review this change.
21 files changed +854 −13
docs/features/demo.md added +33
@@ -0,0 +1,33 @@
1 ---
2 topic: Your apps
3 row: Demo: pin one commit of an app, served at <slug>--demo
4 ---
5 # Demo: pin one commit of an app, served at `<slug>--demo`
6
7 A demo is one commit you chose to show, running beside production with a copy of production's data, the way a preview does. Git holds it: the ref `refs/demo` in the app's repository. No ref, no demo.
8
9 Who: a verified person who can write the repository. A reader, a guest and an agent are refused (the crew proposes; a person chooses what is shown). A repository that mirrors an origin cannot have one. Anyone who can read the repository can see the pin: `refs/demo` is a ref like any other, and the terminal screen shows its commit and the demo's address to every reader.
10
11 ## In the terminal
12
13 Open the app's repository, then the palette command **owner/name — Demo**.
14
15 - `p` pins the tip of the default branch and deploys it.
16 - `x` clears the demo after a confirm: the ref goes, and the environment with its copy of the data.
17
18 The screen reads `refs/demo` itself, so it shows a pin made from anywhere (`src/tui/screens/demo.ts`).
19
20 ## Over the API
21
22 ```
23 PUT /api/v1/repos/<owner>/<name>/demo {"sha":"<full commit id>"} 202 {sha, run}
24 DELETE /api/v1/repos/<owner>/<name>/demo 200 {sha}
25 ```
26
27 `PUT` takes any commit of the repository, not only a branch tip. Refusals: 401 not signed in, 403 not a writer or an agent, 404 no such app, 422 `unverified`, `mirrored`, `not_a_commit` or `demo_moved` (the ref moved while you asked; ask again).
28
29 Then open `<slug>--demo`. A push cannot move `refs/demo`; only these actions do. A forge coming back rebuilds the demo from the ref.
30
31 ## Reserved slug
32
33 `demo` is no longer a valid app slug (`<slug>--demo` would be ambiguous); `slugFor` turns a repository named `demo` into `demo-app`. The check applies when an app is created, so a row already named `demo` is untouched.
src/actions/apps.ts +4
@@ -30,6 +30,8 @@ import { scaffoldFiles } from "../apps/template.ts";
3030 import type { FileWrite } from "../git/write.ts";
3131 import { TEMPLATE_ERRORS, templateFiles, type TemplateError } from "../apps/template_tip.ts";
3232 import {
33 DEMO_ENV,
34 DEMO_REF,
3335 envBuild,
3436 envVariant,
3537 isEnvName,
@@ -70,6 +72,7 @@ import { canAdmin, canEnterApp, canWrite, getRepo, type Repo } from "../core/rep
7072 import type { Run } from "../core/runs.ts";
7173 import { type User } from "../core/users.ts";
7274 import { resolveOid } from "../git/merge.ts";
75 import { exactRefOid } from "../git/branches.ts";
7376 import { previewCommit } from "../git/combined.ts";
7477 import { repoDir } from "../git/repos.ts";
7578 import { err, ok, type Result } from "../kernel/result.ts";
@@ -834,6 +837,7 @@ async function commitFor(
834837 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
835838 if (env === "production")
836839 return resolveOid(dir, `refs/heads/${repo.defaultBranch}`);
840 if (env === DEMO_ENV) return exactRefOid(dir, DEMO_REF);
837841 // A build preview names its commit only by its short sha: the commit it
838842 // serves is the one the runtime holds for it, while it is held.
839843 if (envBuild(env) !== undefined)
src/actions/demo.ts added +129
@@ -0,0 +1,129 @@
1 /**

No terminal door for pin or clear: add a src/tui/ screen calling setDemo and clearDemo with the same gate as pinner, plus docs/features/demo.md.

2 * An app's demo: one commit a writer pinned, served beside production at
3 * `<slug>--demo` with a copy of production's data, the way a preview is.
4 * It is how the owner shows the project at a build they chose.
5 *
6 * Git is the whole of it: the ref `refs/demo` in the app's bare repository.
7 * No ref, no demo. These actions move the ref under a lease, announce it on
8 * the outbox (`app.demo`), and ask the runtime to follow; a forge coming
9 * back rebuilds the demo from the ref (`AppsRuntime.reconcileApp`). A push
10 * cannot move it — the pre-receive hook keeps `refs/demo` the forge's.
11 */
12
13 import type { App } from "../app.ts";
14 import { DEMO_ENV, DEMO_REF } from "../apps/data.ts";
15 import { appsRuntime } from "../apps/runtime.ts";
16 import { getAppByRepo } from "../core/apps.ts";
17 import type { Repo } from "../core/repos.ts";
18 import type { Run } from "../core/runs.ts";
19 import type { User } from "../core/users.ts";
20 import { exactRefOid, moveRefLeased } from "../git/branches.ts";
21 import { isSafeOid } from "../git/guard.ts";
22 import { readerFor } from "../git/read.ts";
23 import { repoDir } from "../git/repos.ts";
24 import { err, ok, type Result } from "../kernel/result.ts";
25 import { isMirror } from "../origins/write-through.ts";
26 import { requireWriter, type AccessError } from "./access.ts";
27 import { requireVerified } from "./verify.ts";
28
29 export type DemoError =
30 | AccessError
31 | "unverified"
32 /** The repository mirrors an origin: a local-only ref there is a bug. */
33 | "mirrored"
34 /** `oid` is not a full object id naming a commit in this repository. */
35 | "not_a_commit"
36 /** `refs/demo` moved between our read and our write; ask again. */
37 | "demo_moved"
38 | "git_failed";
39
40 export interface DemoSet {
41 readonly oid: string;
42 /** The deploy that brings the demo up, or undefined when nothing needs to run. */
43 readonly run: Run | undefined;
44 }
45
46 /**
47 * Who may pin or clear the demo: a verified person who can write the repository, never an agent.
48 */
49 function pinner(
50 app: App,
51 actor: User | undefined,
52 repo: Repo,
53 ): Result<User, DemoError> {
54 const writer = requireWriter(app, actor, repo);
55 if (!writer.ok) return writer;
56 // The crew proposes; a person chooses what is shown (docs/APPS.md rule 1).
57 if (writer.value.kind === "agent") return err("forbidden");
58 const proven = requireVerified(app, writer.value);
59 if (!proven.ok) return proven;
60 if (isMirror(app, repo)) return err("mirrored");
61 if (!getAppByRepo(app.db, repo.id)) return err("not_found");
62 return ok(writer.value);
63 }
64
65 /**
66 * Pin the app's demo at `oid` (a full commit id in this repository) and
67 * deploy it there. Pinning the commit already pinned redeploys nothing.
68 */
69 export async function setDemo(
70 app: App,
71 actor: User | undefined,
72 repo: Repo,
73 oid: string,
74 ): Promise<Result<DemoSet, DemoError>> {
75 const who = pinner(app, actor, repo);
76 if (!who.ok) return who;
77 if (!isSafeOid(oid)) return err("not_a_commit");
78 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
79 const stat = await readerFor(dir).stat(oid);
80 if (!stat.ok || stat.value.type !== "commit") return err("not_a_commit");
81
82 const current = await exactRefOid(dir, DEMO_REF);
83 if (current !== oid) {
84 const moved = await moveRefLeased(dir, DEMO_REF, oid, current);
85 if (!moved.ok)
86 return err(moved.error === "ref_moved" ? "demo_moved" : "git_failed");
87 app.bus.append({
88 kind: "app.demo",
89 repoId: repo.id,
90 actorId: who.value.id,
91 payload: { env: DEMO_ENV, oid, previous: current ?? null },
92 });
93 }
94 const record = getAppByRepo(app.db, repo.id);
95 const runtime = appsRuntime(app);
96 const run =
97 record === undefined || runtime === undefined
98 ? undefined
99 : runtime.requestDeploy(record, repo, DEMO_ENV, oid, "pinned", who.value.id);
100 return ok({ oid, run });
101 }
102
103 /** Remove the app's demo: the ref goes, and the environment with its data. */
104 export async function clearDemo(
105 app: App,
106 actor: User | undefined,
107 repo: Repo,
108 ): Promise<Result<{ readonly oid: string | null }, DemoError>> {
109 const who = pinner(app, actor, repo);
110 if (!who.ok) return who;
111 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
112 const current = await exactRefOid(dir, DEMO_REF);
113 if (current !== undefined) {
114 const moved = await moveRefLeased(dir, DEMO_REF, undefined, current);
115 if (!moved.ok)
116 return err(moved.error === "ref_moved" ? "demo_moved" : "git_failed");
117 app.bus.append({
118 kind: "app.demo",
119 repoId: repo.id,
120 actorId: who.value.id,
121 payload: { env: DEMO_ENV, oid: null, previous: current },
122 });
123 }
124 const record = getAppByRepo(app.db, repo.id);
125 const runtime = appsRuntime(app);
126 if (record !== undefined && runtime !== undefined)
127 await runtime.teardown(record, DEMO_ENV);
128 return ok({ oid: current ?? null });
129 }
src/actions/env_words.ts +2 −1
@@ -4,12 +4,13 @@
44 * terminal's deploys screen, from here.
55 */
66
7 import { envBuild, envPull, envVariant, type EnvName } from "../apps/data.ts";
7 import { DEMO_ENV, envBuild, envPull, envVariant, type EnvName } from "../apps/data.ts";
88 import type { Run } from "../core/runs.ts";
99 import { VERIFY_FIRST } from "./verify_words.ts";
1010
1111 /** `production`, `preview of #12` or `build 1a2b3c4`, as a phrase that fits in a sentence. */
1212 export function envLabel(env: EnvName): string {
13 if (env === DEMO_ENV) return "the demo";
1314 const build = envBuild(env);
1415 if (build !== undefined) return `build ${build}`;
1516 const variant = envVariant(env);
src/apps/data.ts +11 −2
@@ -39,10 +39,16 @@ import { join, relative } from "node:path";
3939 import { defect } from "../kernel/error.ts";
4040
4141 /**
42 * `production`, `pull-<n>` for the preview of pull `n`, or `build-<sha7>`
42 * `production`, `demo` (the one commit a writer pinned at `refs/demo`),
43 * `pull-<n>` for the preview of pull `n`, or `build-<sha7>`
4344 * for a build preview: one commit a writer asked to see now, short-lived.
4445 */
45 export type EnvName = "production" | `pull-${number}` | `build-${string}` | `variant-${string}`;
46 export type EnvName = "production" | "demo" | `pull-${number}` | `build-${string}` | `variant-${string}`;
47
48 export const DEMO_ENV = "demo" satisfies EnvName;
49
50 /** Where an app's demo is pinned, in its bare repository. No ref, no demo. */
51 export const DEMO_REF = "refs/demo";
4652
4753 export const previewEnv = (pullNumber: number): EnvName => `pull-${pullNumber}`;
4854
@@ -73,6 +79,7 @@ export function variantEnvFromLabel(tail: string): EnvName | undefined {
7379 export function isEnvName(value: string): value is EnvName {
7480 return (
7581 value === "production" ||
82 value === DEMO_ENV ||
7683 /^variant-[a-z0-9]{1,16}$/.test(value) ||
7784 /^pull-[1-9]\d*$/.test(value) ||
7885 /^build-[0-9a-f]{7}$/.test(value)
@@ -92,6 +99,7 @@ export function envPull(env: EnvName): number | undefined {
9299 */
93100 export function envHostLabel(slug: string, env: EnvName): string {
94101 if (env === "production") return slug;
102 if (env === DEMO_ENV) return `${slug}--demo`;
95103 const build = envBuild(env);
96104 if (build !== undefined) return `${slug}--b${build}`;
97105 const variant = envVariant(env);
@@ -111,6 +119,7 @@ export function buildEnvFromLabel(tail: string): EnvName | undefined {
111119 /** An environment as a person reads its name: production, the preview of #n, or the build at <sha7>. */
112120 export function envWords(env: EnvName): string {
113121 if (env === "production") return "production";
122 if (env === DEMO_ENV) return "demo";
114123 const build = envBuild(env);
115124 if (build !== undefined) return `the build at ${build}`;
116125 const variant = envVariant(env);
src/apps/proxy.ts +4
@@ -48,6 +48,7 @@ import { err, ok, type Result } from "../kernel/result.ts";
4848 import {
4949 buildEnvFromLabel,
5050 variantEnvFromLabel,
51 DEMO_ENV,
5152 envVariant,
5253 envBuild,
5354 envWords,
@@ -154,6 +155,9 @@ export function parseAppHost(
154155 // `<theirs>--<ours>` — and travels through untouched in `Host`, for that
155156 // app to route.
156157 const last = parts.at(-1)!;
158 if (parts.length >= 2 && last === DEMO_ENV) {
159 return { slug: parts.at(-2)!, env: DEMO_ENV, nested: parts.length > 2 };
160 }
157161 const build = parts.length >= 2 ? buildEnvFromLabel(last) : undefined;
158162 if (build !== undefined) {
159163 return { slug: parts.at(-2)!, env: build, nested: parts.length > 2 };
src/apps/runtime.ts +8 −7
@@ -38,13 +38,14 @@ import type { User } from "../core/users.ts";
3838 import { cancelRun, failAbandonedRuns, STOPPED_SUMMARY } from "../core/runs.ts";
3939 import { Gate } from "../git/env.ts";
4040 import { resolveOid } from "../git/merge.ts";
41 import { exactRefOid } from "../git/branches.ts";
4142 import { repoDir } from "../git/repos.ts";
4243 import { STALE_AFTER_MS } from "../runs/lease.ts";
4344 import { appendRunLog } from "../runs/log.ts";
4445 import { primaryDomain, primaryHosts } from "../core/domains.ts";
4546 import { closeAllAwake, closeOrphans } from "../core/meter.ts";
4647 import { drainPort } from "./handoff.ts";
47 import { appsRoot, envBuild, envPull, variantEnv, envHostLabel, isEnvName, previewEnv, type EnvName } from "./data.ts";
48 import { DEMO_ENV, DEMO_REF, appsRoot, envBuild, envPull, variantEnv, envHostLabel, isEnvName, previewEnv, type EnvName } from "./data.ts";
4849 import { noteProtection } from "../kernel/protection.ts";
4950 import { cellsAvailable } from "./contain.ts";
5051 import { during } from "../perf/jobs.ts";
@@ -306,12 +307,7 @@ export class AppsRuntime {
306307 * branch, a preview per open pull, and nothing for pulls that closed while the
307308 * forge was away.
308309 */
309 async reconcileApp(
310 record: AppRecord,
311 repo: Repo,
312 reason: string,
313 only?: "production" | "preview",
314 ): Promise<void> {
310 async reconcileApp(record: AppRecord, repo: Repo, reason: string, only?: "production" | "preview"): Promise<void> {
315311 const dir = repoDir(this.app.reposRoot, repo.ownerName, repo.name);
316312 const tip = await resolveOid(dir, `refs/heads/${repo.defaultBranch}`);
317313 if (tip !== undefined && only !== "preview") {
@@ -319,6 +315,11 @@ export class AppsRuntime {
319315 this.requestDeploy(record, repo, "production", tip, reason);
320316 }
321317 const open = new Set<EnvName>(["production"]);
318 // The demo lives in git alone: its ref is the whole of it (`actions/demo.ts`).
319 const demo = await exactRefOid(dir, DEMO_REF);
320 if (demo !== undefined) open.add(DEMO_ENV);
321 const woke = reason === "boot" && demo !== undefined && this.settleAsleep(record, DEMO_ENV, demo);
322 if (demo !== undefined && only !== "production" && !woke) this.requestDeploy(record, repo, DEMO_ENV, demo, reason);
322323 // A variant is a branch kept running: it stays while its row does, whatever
323324 // pulls are open (`core/variants.ts`).
324325 for (const variant of listVariants(this.app.db, record.id)) {
src/apps/runtime_sleep.ts +2 −2
@@ -25,7 +25,7 @@ import { beatAwake } from "../core/meter.ts";
2525 import { dropPreviewBuildCache } from "./build_cache.ts";
2626 import { BUSY_WORDS, busyReason } from "./busy.ts";
2727 import { awaitingRun } from "../core/timers.ts";
28 import { envBuild, envVariant, envDataDir, envDir, envPull, type EnvName } from "./data.ts";
28 import { DEMO_ENV, envBuild, envVariant, envDataDir, envDir, envPull, type EnvName } from "./data.ts";
2929 import { parseManifest } from "./manifest.ts";
3030 import { heldManifest } from "../core/starts.ts";
3131 import { identityKey } from "./grants.ts";
@@ -104,7 +104,7 @@ export function mayRun(
104104 if (isQuarantined(rt.app.db, repo.id)) return false;
105105 // Production is the default branch and a build preview a commit a writer asked to see
106106 // (`actions/build_preview.ts`): each is a writer's choice already.
107 if (env === "production" || envBuild(env) !== undefined || envVariant(env) !== undefined)
107 if (env === "production" || env === DEMO_ENV || envBuild(env) !== undefined || envVariant(env) !== undefined)
108108 return true;
109109 const number = envPull(env);
110110 const pull =
src/apps/tty.ts +2
@@ -29,6 +29,7 @@ import { mayView, sealedPreviewPull } from "../core/sealed.ts";
2929 import { err, ok, type Result } from "../kernel/result.ts";
3030 import type { SshSession } from "../ssh/server.ts";
3131 import {
32 DEMO_ENV,
3233 buildEnvFromLabel,
3334 isEnvName,
3435 previewEnv,
@@ -51,6 +52,7 @@ export function parseAppLogin(
5152 return isSlugLike(name) ? { slug: name, env: "production" } : undefined;
5253 const slug = name.slice(0, at);
5354 const number = name.slice(at + 2);
55 if (isSlugLike(slug) && number === DEMO_ENV) return { slug, env: DEMO_ENV };
5456 const build = buildEnvFromLabel(number);
5557 if (isSlugLike(slug) && build !== undefined) return { slug, env: build };
5658 if (!isSlugLike(slug) || !/^[1-9]\d*$/.test(number)) return undefined;
src/contract/openapi/routes/deleteApiV1ReposOwnerNameDemo.ts added +12
@@ -0,0 +1,12 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "delete",
5 path: `${REPO}/demo`,
6 summary: "Clear the app's demo pin",
7 detail: "Takes its environment down; answers { sha }",
8 auth: true,
9 role: "member",
10 reply: { sha: "string" },
11 refuses: [401, 403, 404],
12 };
src/contract/openapi/routes/index.ts +2
@@ -21,6 +21,7 @@ export { route as deleteApiV1ReposOwnerNameBuildsLabel } from "./deleteApiV1Repo
2121 export { route as deleteApiV1ReposOwnerNameBuildsLabelShotsFile } from "./deleteApiV1ReposOwnerNameBuildsLabelShotsFile.ts";
2222 export { route as deleteApiV1ReposOwnerNameCrewDevices } from "./deleteApiV1ReposOwnerNameCrewDevices.ts";
2323 export { route as deleteApiV1ReposOwnerNameCrewUsername } from "./deleteApiV1ReposOwnerNameCrewUsername.ts";
24 export { route as deleteApiV1ReposOwnerNameDemo } from "./deleteApiV1ReposOwnerNameDemo.ts";
2425 export { route as deleteApiV1ReposOwnerNameDeskId } from "./deleteApiV1ReposOwnerNameDeskId.ts";
2526 export { route as deleteApiV1ReposOwnerNameDropFile } from "./deleteApiV1ReposOwnerNameDropFile.ts";
2627 export { route as deleteApiV1ReposOwnerNameEgressGrants } from "./deleteApiV1ReposOwnerNameEgressGrants.ts";
@@ -490,6 +491,7 @@ export { route as putApiV1ReposOwnerNameAppDomainsHostOldRecords } from "./putAp
490491 export { route as putApiV1ReposOwnerNameAppEnvVar } from "./putApiV1ReposOwnerNameAppEnvVar.ts";
491492 export { route as putApiV1ReposOwnerNameAppMembers } from "./putApiV1ReposOwnerNameAppMembers.ts";
492493 export { route as putApiV1ReposOwnerNameCrewUsername } from "./putApiV1ReposOwnerNameCrewUsername.ts";
494 export { route as putApiV1ReposOwnerNameDemo } from "./putApiV1ReposOwnerNameDemo.ts";
493495 export { route as putApiV1ReposOwnerNameDisplayBuilds } from "./putApiV1ReposOwnerNameDisplayBuilds.ts";
494496 export { route as putApiV1ReposOwnerNameFlagsFlag } from "./putApiV1ReposOwnerNameFlagsFlag.ts";
495497 export { route as putApiV1ReposOwnerNameIssuesNumberAssignee } from "./putApiV1ReposOwnerNameIssuesNumberAssignee.ts";
src/contract/openapi/routes/putApiV1ReposOwnerNameDemo.ts added +14
@@ -0,0 +1,14 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "put",
5 path: `${REPO}/demo`,
6 summary: "Pin the app's demo at commit { sha }",
7 detail: "Deploys it; refs/demo holds it; answers 202 { sha, run }; a bad sha answers 422",
8 auth: true,
9 role: "member",
10 body: { sha: "string" },
11 status: 202,
12 reply: { sha: "string", run: "object" },
13 refuses: [401, 403, 404],
outdated

Routes also answer 403 and 422; list them in refuses. Same for the DELETE route.

14 };
src/contract/tags.ts +1
@@ -8,6 +8,7 @@
88 const ALIAS: Readonly<Record<string, string>> = {
99 "crew-devices": "crew",
1010 oembed: "meta",
11 demo: "apps",
1112 app: "apps",
1213 timers: "apps",
1314 schedules: "apps",
src/core/apps.ts +1 −1
@@ -51,7 +51,7 @@ const toApp = (r: AppRow): AppRecord => ({
5151 * preview, so no slug may be `b` and seven hex digits; `<slug>--v-<label>` is a variant (`core/variants.ts`), so none is `v-` and a label.
5252 */
5353 const RESERVED_SLUG = /^b[0-9a-f]{7}$/;
54 const reserved = (slug: string): boolean => RESERVED_SLUG.test(slug) || /^v-[a-z0-9]{1,16}$/.test(slug);
54 const reserved = (slug: string): boolean => slug === "demo" || RESERVED_SLUG.test(slug) || /^v-[a-z0-9]{1,16}$/.test(slug);
5555
5656 /**
5757 * A slug is a DNS label: lowercase letters, digits, single hyphens inside.
src/design/activity.ts +2
@@ -66,6 +66,8 @@ export function eventVerb(event: ForgeEvent): string {
6666 }
6767 if (kind === "app.serving")
6868 return `started serving ${environment(payload["env"])}`;
69 if (kind === "app.demo")
70 return payload["oid"] === null ? "cleared the demo" : "pinned the demo";
6971 if (kind === "app.stopped") return `stopped ${environment(payload["env"])}`;
7072 if (kind === "app.env_set" || kind === "app.env_deleted") {
7173 const name = payload["name"];
src/http/api/app.ts +26
@@ -11,6 +11,7 @@ import { appView, appVisitors, deleteAppEnvVar, disableApp, enableApp, listAppEn
1111 import { servedFlags, setAppFlag, withoutViewers } from "../../actions/app_flags.ts";
1212 import { pullNow, PULL_NOW_REFUSALS } from "../../actions/app_pull.ts";
1313 import { addAppDomain, claimAppDomain, claimProofRecord, checkAppDomain, keepOldRecords, listAppDomains, removeAppDomain } from "../../actions/domains.ts";
14 import { clearDemo, setDemo } from "../../actions/demo.ts";
1415 import { previewBuild, previewBuildRefusalText } from "../../actions/build_preview.ts";
1516 import { SETTING_WORDS } from "../../actions/setting_words.ts";
1617 import { appsRuntime } from "../../apps/runtime.ts";
@@ -397,6 +398,31 @@ export function appRoutes(router: Router<Handler>): void {
397398 },
398399 );
399400
401 // The app's demo: one commit a writer pinned (`actions/demo.ts`). PUT
402 // pins it at `{ sha }` and deploys it; DELETE clears the pin and takes
403 // the environment down. Git holds it, at `refs/demo`, not this route.
404 router.add("PUT", "/api/v1/repos/:owner/:name/demo", async (ctx) => {
405 const denied = requireScope(ctx, "rw");
406 if (denied) return denied;
407 const repo = loadRepo(ctx);
408 if (!repo) return notFound();
409 const input = await body(ctx.request);
410 const sha = typeof input["sha"] === "string" ? input["sha"] : "";
411 const pinned = await setDemo(ctx.app, ctx.auth.user, repo, sha);
412 if (!pinned.ok) return respondAccess(pinned.error, 422);
413 return json({ sha: pinned.value.oid, run: pinned.value.run ?? null }, 202);
414 });
415
416 router.add("DELETE", "/api/v1/repos/:owner/:name/demo", async (ctx) => {
417 const denied = requireScope(ctx, "rw");
418 if (denied) return denied;
419 const repo = loadRepo(ctx);
420 if (!repo) return notFound();
421 const cleared = await clearDemo(ctx.app, ctx.auth.user, repo);
422 if (!cleared.ok) return respondAccess(cleared.error, 422);
423 return json({ sha: cleared.value.oid }, 200);
424 });
425
400426 // Preview now: serve one commit `{ sha }` at its own short-lived
401427 // environment (`actions/build_preview.ts`). Nothing is stored; the answer
402428 // names the environment and where it is served.
src/http/hook.ts +7
@@ -91,6 +91,13 @@ export async function handleHook(app: App, request: Request): Promise<Response>
9191 status: 403,
9292 });
9393 }
94 // So is the demo pin: it moves only through `setDemo`, which
95 // announces it and deploys it (`actions/demo.ts`).
96 if (update.ref === "refs/demo" || update.ref.startsWith("refs/demo/")) {
97 return new Response(`${update.ref}: refs/demo is reserved`, {
98 status: 403,
99 });
100 }
94101 // A push that began before its account was suspended or removed does
95102 // not land: standing is asked again here, at the ref update.
96103 if (actor !== undefined && !isActive(actor)) {
src/tui/screens/demo.ts added +103
@@ -0,0 +1,103 @@
1 /**
2 * An app's demo, in the terminal: the pin the API's `PUT`/`DELETE …/demo`
3 * moves, through the same actions (`actions/demo.ts`) and so the same gate: a
4 * verified person who can write the repository, never an agent. `p` pins the
5 * tip of the default branch (any other commit is the API's `{ sha }`), `x`
6 * clears the pin after a confirm. The screen reads `refs/demo` itself, so it
7 * shows a pin made from anywhere.
8 */
9
10 import { clearDemo, setDemo, type DemoError } from "../../actions/demo.ts";
11 import { requireWriter } from "../../actions/access.ts";
12 import { DEMO_REF } from "../../apps/data.ts";
13 import { getAppByRepo } from "../../core/apps.ts";
14 import type { Repo } from "../../core/repos.ts";
15 import { exactRefOid } from "../../git/branches.ts";
16 import { resolveOid } from "../../git/merge.ts";
17 import { repoDir } from "../../git/repos.ts";
18 import type { Ctx, Screen } from "../app/app.ts";
19 import { binding } from "../app/keys.ts";
20 import type { Command } from "../app/palette.ts";
21 import type { Session } from "../session.ts";
22 import { style } from "../term/style.ts";
23 import { truncate } from "../term/width.ts";
24 import { confirmScreen, later } from "./common.ts";
25
26 export const WORDS: Record<DemoError, string> = {
27 not_found: "No such app.",
28 unauthorized: "Sign in to pin a demo.",
29 forbidden: "A person who writes this repository pins the demo; an agent does not.",
30 unverified: "Verify your email to pin a demo.",
31 mirrored: "This repository mirrors another; its demo cannot be pinned here.",
32 not_a_commit: "That is not a commit of this repository.",
33 demo_moved: "The demo moved while you asked; look again.",
34 git_failed: "Git could not move the demo.",
35 };
36
37 export function demoScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
38 const dir = repoDir(f.app.reposRoot, repo.ownerName, repo.name);
39 let pinned: string | undefined;
40 const read = async (): Promise<void> => {
41 pinned = await exactRefOid(dir, DEMO_REF);
42 ctx.invalidate();
43 };
44 const screen: Screen = {
45 title: `${repo.ownerName}/${repo.name} — Demo`,
46 keys: [binding(["p"], "pin the default branch's tip"), binding(["x"], "clear the demo")],
47 async load() {
48 await read();
49 },
50 render(area, s) {
51 const c = ctx.theme.c;
52 const may = requireWriter(f.app, f.user, repo).ok;
53 const lines = [
54 pinned === undefined ? "No demo is pinned." : `Pinned at ${pinned.slice(0, 12)}, served at ${getAppByRepo(f.app.db, repo.id)?.slug ?? repo.name}--demo.`,
55 may ? "p pins the tip of the default branch; x clears the demo." : "A person who writes this repository pins the demo.",
56 ];
57 lines.forEach((t, i) => s.text(area.x, area.y + i, truncate(t, area.w), style(i === 0 ? c.fg : c.mutedFg, c.bg), area.x + area.w));
58 },
59 key(e) {
60 if (e.ctrl || e.alt || (e.key !== "p" && e.key !== "x")) return false;
61 const say = (done: { ok: boolean; error?: DemoError }, text: string): void => {
62 ctx.toast(done.ok ? text : WORDS[done.error!], done.ok ? undefined : "danger");
63 void read();
64 };
65 if (e.key === "p") {
66 void (async () => {
67 const tip = await resolveOid(dir, `refs/heads/${repo.defaultBranch}`);
68 if (tip === undefined) return say({ ok: false, error: "not_a_commit" }, "");
69 const done = await setDemo(f.app, f.user, repo, tip);
70 say(done.ok ? { ok: true } : { ok: false, error: done.error }, `Demo pinned at ${tip.slice(0, 12)}.`);
71 })();
72 return true;
73 }
74 void later(ctx, () =>
75 confirmScreen(ctx, screen, {
76 title: "Clear the demo",
77 body: ["The demo stops and its copy of the data is deleted."],
78 actions: [{ label: "Cancel", variant: "ghost" }, { label: "Clear" }],
79 selected: 0,
80 onChoose: (i) => {
81 if (i !== 1) return;
82 void clearDemo(f.app, f.user, repo).then((done) => say(done.ok ? { ok: true } : { ok: false, error: done.error }, "Demo cleared."));
83 },
84 }),
85 );
86 return true;
87 },
88 };
89 return screen;
90 }
91
92 /** The palette's command while an app's repository is open. */
93 export function demoCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
94 if (repo === undefined || !getAppByRepo(f.app.db, repo.id)) return [];
95 return [
96 {
97 id: "demo-app",
98 title: `${repo.ownerName}/${repo.name} — Demo`,
99 hint: "this app's demo: pin the default branch's tip, or clear it",
100 run: () => ctx.push(demoScreen(f, ctx, repo)),
101 },
102 ];
103 }
src/tui/screens/workspace.ts +2
@@ -225,6 +225,7 @@ import { settingHistoryCommands } from "./settinghistory.ts";
225225 import { templateCommands } from "./template.ts";
226226 import { buildCacheCommands } from "./buildcache.ts";
227227 import { schedulesCommands } from "./schedules.ts";
228 import { demoCommands } from "./demo.ts";
228229 import { appReleasesCommands } from "./appreleases.ts";
229230 import { largeFilesCommands } from "./largefiles.ts";
230231 import { migrationCommands } from "./migration.ts";
@@ -2448,6 +2449,7 @@ export function workspaceScreen(
24482449 ...autonomyCommands(f, ctx, repo),
24492450 ...trafficCommands(f, ctx, repo),
24502451 ...schedulesCommands(f, ctx, repo),
2452 ...demoCommands(f, ctx, repo),
24512453 ...appReleasesCommands(f, ctx, repo),
24522454 ...largeFilesCommands(f, ctx, repo),
24532455 ...dropCommands(f, ctx, repo),
test/apps-demo.test.ts added +362
@@ -0,0 +1,362 @@
1 /**
2 * An app's demo (`actions/demo.ts`): a writer pins one commit at
3 * `refs/demo`; it runs at `<slug>--demo` with a copy of production's data,
4 * shows in the app's status beside production, and comes back from the ref
5 * when the forge restarts. A reader cannot pin it, a mirror refuses it, a
6 * non-commit is refused, a push cannot move the ref, and clearing it takes
7 * the environment down.
8 */
9
10 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
11 import { mkdtemp, rm } from "node:fs/promises";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { createApp, type App } from "../src/app.ts";
15 import { enableApp } from "../src/actions/apps.ts";
16 import { clearDemo, setDemo } from "../src/actions/demo.ts";
17 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
18 import { DEMO_ENV, DEMO_REF } from "../src/apps/data.ts";
19 import { parseAppHost } from "../src/apps/proxy.ts";
20 import { parseAppLogin } from "../src/apps/tty.ts";
21 import { AppsRuntime, type EnvStatus } from "../src/apps/runtime.ts";
22 import { isSlug, slugFor, type AppRecord } from "../src/core/apps.ts";
23 import { listEvents } from "../src/core/events.ts";
24 import { createOrigin, linkRepoToOrigin } from "../src/core/origins.ts";
25 import type { Repo } from "../src/core/repos.ts";
26 import { listRuns, type Run } from "../src/core/runs.ts";
27 import { createToken } from "../src/core/tokens.ts";
28 import { createUser, type User } from "../src/core/users.ts";
29 import { exactRefOid } from "../src/git/branches.ts";
30 import { repoDir } from "../src/git/repos.ts";
31 import { serve, type Servers } from "../src/http/server.ts";
32 import { pollUntil } from "./helpers/poll.ts";
33 import { gitClientEnv } from "./helpers/git-client.ts";
34
35 const DOMAIN = "apps.test";
36
37 /** Says which commit and environment it is, and what production left in its data. */
38 const SERVER = `import { existsSync, readFileSync, writeFileSync } from "node:fs";
39 import { join } from "node:path";
40 const data = process.env.FORGE_APP_DATA ?? ".";
41 const seed = join(data, "seed.txt");
42 if (process.env.FORGE_APP_ENV === "production" && !existsSync(seed))
43 writeFileSync(seed, "written by production");
44 Bun.serve({
45 port: Number(process.env.PORT ?? "0"),
46 hostname: "127.0.0.1",
47 fetch: () =>
48 new Response(
49 [
50 process.env.FORGE_APP_COMMIT,
51 process.env.FORGE_APP_URL,
52 existsSync(seed) ? readFileSync(seed, "utf8") : "no data",
53 ].join("\\n"),
54 ),
55 });
56 `;
57
58 describe("an app's demo", () => {
59 let dataDir: string;
60 let work: string;
61 let app: App;
62 let servers: Servers;
63 let runtime: AppsRuntime;
64 let alice: User;
65 let bob: User;
66 let repo: Repo;
67 let record: AppRecord;
68 let first = "";
69 let second = "";
70 let aliceToken = "";
71 let bobToken = "";
72
73 const viaHost = (host: string, path = "/") =>
74 fetch(`${servers.url}${path}`, { headers: { host }, redirect: "manual" });
75
76 const api = (method: string, path: string, token: string, body?: unknown) =>
77 fetch(`${servers.url}/api/v1${path}`, {
78 method,
79 headers: {
80 authorization: `Bearer ${token}`,
81 "content-type": "application/json",
82 },
83 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
84 });
85
86 async function until<T>(read: () => T | undefined, ms = 60_000): Promise<T> {
87 let found: T | undefined;
88 await pollUntil(() => (found = read()) !== undefined, "the demo to change", ms);
89 return found as T;
90 }
91
92 const settled = (where: (run: Run) => boolean): Promise<Run> =>
93 until(() =>
94 listRuns(app.db, repo.id, { kind: "deploy", limit: 50 }).find(
95 (r) =>
96 where(r) &&
97 (r.state === "ok" || r.state === "failed" || r.state === "cancelled"),
98 ),
99 );
100
101 const demoStatus = (): EnvStatus | undefined =>
102 runtime.status(record).find((e) => e.env === DEMO_ENV);
103
104 const bare = () => repoDir(app.reposRoot, repo.ownerName, repo.name);
105
106 beforeAll(async () => {
107 dataDir = await mkdtemp(join(tmpdir(), "forge-demo-"));
108 work = await mkdtemp(join(tmpdir(), "forge-demo-work-"));
109 app = createApp({ dataDir, port: 0 });
110 servers = await serve(app);
111 runtime = new AppsRuntime(app, {
112 domain: DOMAIN,
113 scheme: "http",
114 publicPort: servers.port,
115 forgeUrl: servers.url,
116 });
117 await runtime.start();
118 const a = await createUser(app.db, { origin: "seed",
119 trusted: true,
120 username: "alice",
121 email: "[email protected]",
122 password: "a-good-passphrase",
123 adminIfFirst: true,
124 });
125 if (!a.ok) throw new Error(a.error);
126 alice = a.value;
127 const b = await createUser(app.db, { origin: "seed",
128 trusted: true,
129 username: "bob",
130 email: "[email protected]",
131 password: "a-good-passphrase",
132 });
133 if (!b.ok) throw new Error(b.error);
134 bob = b.value;
135 aliceToken = createToken(app.db, alice.id, "test", "rw").token;
136 bobToken = createToken(app.db, bob.id, "test", "rw").token;
137
138 const made = await createRepo(app, alice, { name: "show", visibility: "public" });
139 if (!made.ok) throw new Error(String(made.error));
140 repo = made.value;
141 const c1 = await commitToBranch(app, alice, repo, {
142 message: "the build worth showing",
143 files: [
144 {
145 path: "package.json",
146 content: JSON.stringify({ name: "show", scripts: { start: "bun server.ts" } }),
147 },
148 { path: "server.ts", content: SERVER },
149 ],
150 });
151 if (!c1.ok) throw new Error(JSON.stringify(c1.error));
152 first = c1.value.commitOid;
153 const c2 = await commitToBranch(app, alice, repo, {
154 message: "work in progress",
155 files: [{ path: "NOTES.md", content: "later\n" }],
156 });
157 if (!c2.ok) throw new Error(JSON.stringify(c2.error));
158 second = c2.value.commitOid;
159 const enabled = enableApp(app, alice, repo, {});
160 if (!enabled.ok) throw new Error(enabled.error);
161 record = enabled.value;
162 const production = await settled((r) => r.env === "production");
163 if (production.state !== "ok") throw new Error(production.summary);
164 }, 90_000);
165
166 afterAll(async () => {
167 await runtime.stop();
168 servers.stop();
169 app.close();
170 await rm(dataDir, { recursive: true, force: true });
171 await rm(work, { recursive: true, force: true });
172 });
173
174 test("the demo's hostname reads back as the demo, and nothing else does", () => {
175 expect(parseAppHost(`show--demo.${DOMAIN}`, DOMAIN)).toEqual({
176 slug: "show",
177 env: "demo",
178 nested: false,
179 });
180 // A forge hosted in our demo keeps its own apps in front of ours.
181 expect(parseAppHost(`notes--show--demo.${DOMAIN}`, DOMAIN)).toEqual({
182 slug: "show",
183 env: "demo",
184 nested: true,
185 });
186 // A guest's demo under our app is the guest's to route.
187 expect(parseAppHost(`notes--demo--show.${DOMAIN}`, DOMAIN)).toEqual({
188 slug: "show",
189 env: "production",
190 nested: true,
191 });
192 expect(parseAppHost(`show--3.${DOMAIN}`, DOMAIN)?.env).toBe("pull-3");
193 expect(parseAppHost(`show.${DOMAIN}`, DOMAIN)?.env).toBe("production");
194 // The `--` attachment for a single-label wildcard keeps working.
195 expect(parseAppHost("show--demo--forge.example", "--forge.example")).toEqual({
196 slug: "show",
197 env: "demo",
198 nested: false,
199 });
200 expect(runtime.hostFor("show", DEMO_ENV)).toBe(`show--demo.${DOMAIN}`);
201 expect(parseAppLogin("show--demo")).toEqual({ slug: "show", env: "demo" });
202 // `demo` is no slug, so `<theirs>--demo` never names an app of ours.
203 expect(isSlug("demo")).toBe(false);
204 expect(slugFor("Demo")).toBe("demo-app");
205 });
206
207 test("no ref, no demo", async () => {
208 expect(await exactRefOid(bare(), DEMO_REF)).toBeUndefined();
209 expect(demoStatus()).toBeUndefined();
210 expect((await viaHost(`show--demo.${DOMAIN}`)).status).toBe(404);
211 });
212
213 test("a reader cannot pin the demo", async () => {
214 const response = await api("PUT", "/repos/alice/show/demo", bobToken, {
215 sha: first,
216 });
217 expect(response.status).toBe(403);
218 const direct = await setDemo(app, bob, repo, first);
219 expect(direct.ok).toBe(false);
220 if (!direct.ok) expect(direct.error).toBe("forbidden");
221 const anonymous = await setDemo(app, undefined, repo, first);
222 expect(anonymous.ok).toBe(false);
223 if (!anonymous.ok) expect(anonymous.error).toBe("unauthorized");
224 expect((await api("DELETE", "/repos/alice/show/demo", bobToken)).status).toBe(403);
225 expect(await exactRefOid(bare(), DEMO_REF)).toBeUndefined();
226 });
227
228 test("something that is not a commit here is refused", async () => {
229 const tree = Bun.spawnSync(["git", "rev-parse", `${first}^{tree}`], {
230 cwd: bare(),
231 env: gitClientEnv(),
232 })
233 .stdout.toString()
234 .trim();
235 for (const sha of [tree, "0".repeat(40), "abc123", "--upload-pack=x", ""]) {
236 const response = await api("PUT", "/repos/alice/show/demo", aliceToken, { sha });
237 expect(response.status).toBe(422);
238 expect(((await response.json()) as { error: string }).error).toBe("not_a_commit");
239 }
240 expect(await exactRefOid(bare(), DEMO_REF)).toBeUndefined();
241 });
242
243 test("a mirrored repository refuses a demo", async () => {
244 const made = await createRepo(app, alice, { name: "mirrored", visibility: "public" });
245 if (!made.ok) throw new Error(String(made.error));
246 const c = await commitToBranch(app, alice, made.value, {
247 message: "seed",
248 files: [{ path: "README.md", content: "hi\n" }],
249 });
250 if (!c.ok) throw new Error(JSON.stringify(c.error));
251 const origin = createOrigin(app.db, dataDir, {
252 userId: alice.id,
253 kind: "github",
254 apiUrl: "https://api.github.invalid",
255 webUrl: "https://github.invalid",
256 login: "alice",
257 token: "not-a-real-token",
258 });
259 if (!origin.ok) throw new Error(origin.error);
260 linkRepoToOrigin(app.db, made.value.id, {
261 originId: origin.value.id,
262 fullName: "alice/mirrored",
263 remoteId: "1",
264 htmlUrl: "https://github.invalid/alice/mirrored",
265 });
266 const refused = await setDemo(app, alice, made.value, c.value.commitOid);
267 expect(refused.ok).toBe(false);
268 if (!refused.ok) expect(refused.error).toBe("mirrored");
269 const response = await api("PUT", "/repos/alice/mirrored/demo", aliceToken, {
270 sha: c.value.commitOid,
271 });
272 expect(response.status).toBe(422);
273 expect(((await response.json()) as { error: string }).error).toBe("mirrored");
274 });
275
276 test("a writer pins a commit: it runs at <slug>--demo, with production's data copied", async () => {
277 const response = await api("PUT", "/repos/alice/show/demo", aliceToken, {
278 sha: first,
279 });
280 expect(response.status).toBe(202);
281 const body = (await response.json()) as { sha: string; run: { id: string } | null };
282 expect(body.sha).toBe(first);
283 expect(body.run).not.toBeNull();
284 expect(await exactRefOid(bare(), DEMO_REF)).toBe(first);
285
286 const run = await settled((r) => r.env === DEMO_ENV && r.commitOid === first);
287 expect(run.state).toBe("ok");
288 expect(run.reason).toBe("pinned");
289 const status = demoStatus();
290 expect(status?.state).toBe("running");
291 expect(status?.commitOid).toBe(first);
292 expect(status?.url).toBe(`http://show--demo.${DOMAIN}:${servers.port}`);
293 // Production first, the demo next.
294 expect(runtime.status(record).map((e) => e.env)).toEqual(["production", "demo"]);
295
296 const page = await (await viaHost(`show--demo.${DOMAIN}`)).text();
297 expect(page).toContain(first);
298 expect(page).toContain(`show--demo.${DOMAIN}`);
299 expect(page).toContain("written by production");
300 // Production still serves the default branch's tip.
301 expect(await (await viaHost(`show.${DOMAIN}`)).text()).toContain(second);
302
303 const events = listEvents(app.db, { kind: "app.demo" });
304 expect(events[0]?.payload["oid"]).toBe(first);
305
306 // Over the API the app's environments name the demo.
307 const view = (await (
308 await fetch(`${servers.url}/api/v1/repos/alice/show/app`, {
309 headers: { authorization: `Bearer ${aliceToken}` },
310 })
311 ).json()) as { environments?: { env: string; commitOid: string }[] };
312 expect(view.environments?.find((e) => e.env === "demo")?.commitOid).toBe(first);
313 }, 90_000);
314
315 test("a push cannot move refs/demo", async () => {
316 const remote = `${servers.url.replace("://", `://alice:${aliceToken}@`)}/alice/show.git`;
317 const clone = join(work, "clone");
318 const env = gitClientEnv();
319 const git = async (args: string[], cwd: string): Promise<number> => {
320 const proc = Bun.spawn(["git", ...args], {
321 cwd,
322 env,
323 stdout: "ignore",
324 stderr: "ignore",
325 });
326 return proc.exited;
327 };
328 expect(await git(["clone", "--quiet", remote, clone], work)).toBe(0);
329 expect(await git(["push", "origin", `${second}:refs/demo`], clone)).not.toBe(0);
330 expect(await exactRefOid(bare(), DEMO_REF)).toBe(first);
331 }, 30_000);
332
333 test("the forge coming back rebuilds the demo from the ref", async () => {
334 await runtime.stop();
335 runtime = new AppsRuntime(app, {
336 domain: DOMAIN,
337 scheme: "http",
338 publicPort: servers.port,
339 forgeUrl: servers.url,
340 });
341 await runtime.start();
342 const status = await until(() => demoStatus());
343 expect(status.commitOid).toBe(first);
344 expect(["asleep", "deploying", "running"]).toContain(status.state);
345 const page = await (await viaHost(`show--demo.${DOMAIN}`)).text();
346 expect(page).toContain(first);
347 }, 90_000);
348
349 test("clearing the demo removes the ref and the environment", async () => {
350 const response = await api("DELETE", "/repos/alice/show/demo", aliceToken);
351 expect(response.status).toBe(200);
352 expect(((await response.json()) as { sha: string | null }).sha).toBe(first);
353 expect(await exactRefOid(bare(), DEMO_REF)).toBeUndefined();
354 expect(demoStatus()).toBeUndefined();
355 expect((await viaHost(`show--demo.${DOMAIN}`)).status).toBe(404);
356 expect(listEvents(app.db, { kind: "app.demo" })[0]?.payload["oid"]).toBeNull();
357 // Clearing what is not there is no error.
358 const again = await clearDemo(app, alice, repo);
359 expect(again.ok).toBe(true);
360 if (again.ok) expect(again.value.oid).toBeNull();
361 }, 30_000);
362 });
test/demo-screen.test.ts added +127
@@ -0,0 +1,127 @@
1 /**
2 * The demo through the terminal door: the screen pins the default branch's tip
3 * and clears the pin through `setDemo` and `clearDemo`, so it is gated as the
4 * API is: a reader is refused, and what a writer pins is the ref the API reads.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
12 import { DEMO_REF } from "../src/apps/data.ts";
13 import { createApp as insertApp } from "../src/core/apps.ts";
14 import type { Repo } from "../src/core/repos.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { exactRefOid } from "../src/git/branches.ts";
17 import { repoDir } from "../src/git/repos.ts";
18 import type { Ctx, Screen } from "../src/tui/app/app.ts";
19 import type { KeyEvent } from "../src/tui/term/input.ts";
20 import { WORDS, demoCommands, demoScreen } from "../src/tui/screens/demo.ts";
21 import type { Session } from "../src/tui/session.ts";
22 import { quietLogs } from "./helpers/globals.ts";
23 import { waitFor } from "./helpers/poll.ts";
24
25 quietLogs();
26
27 let dataDir: string;
28 let app: App;
29 let alice: User;
30 let bob: User;
31 let repo: Repo;
32 let tip: string;
33
34 beforeAll(async () => {
35 dataDir = await mkdtemp(join(tmpdir(), "forge-demo-screen-"));
36 app = createApp({ dataDir, port: 0, host: "forge.test" });
37 const make = async (username: string, adminIfFirst = false) => {
38 const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst });
39 if (!made.ok) throw new Error(made.error);
40 return made.value;
41 };
42 alice = await make("alice", true);
43 bob = await make("bob");
44 const made = await createRepo(app, alice, { name: "show", visibility: "public" });
45 if (!made.ok) throw new Error(String(made.error));
46 repo = made.value;
47 const c = await commitToBranch(app, alice, repo, { message: "seed", files: [{ path: "README.md", content: "hi\n" }] });
48 if (!c.ok) throw new Error(JSON.stringify(c.error));
49 tip = c.value.commitOid;
50 const row = insertApp(app.db, { repoId: repo.id, slug: "show", access: "public" });
51 if (!row.ok) throw new Error(row.error);
52 }, 60_000);
53
54 afterAll(async () => {
55 app.db.close();
56 await rm(dataDir, { recursive: true, force: true });
57 });
58
59 const session = (user: User | undefined) => ({ user, db: app.db, app }) as unknown as Session;
60 const ctxWith = (toasts: string[] = []) => ({ toast: (t: string) => toasts.push(t), invalidate() {}, push() {}, theme: {} }) as unknown as Ctx;
61 const press = (key: string): KeyEvent => ({ type: "key", key, ctrl: false, alt: false, shift: false });
62 const ref = () => exactRefOid(repoDir(app.reposRoot, repo.ownerName, repo.name), DEMO_REF);
63
64 describe("the demo screen", () => {
65 test("the palette offers it for an app's repository, and not without one", () => {
66 expect(demoCommands(session(alice), ctxWith(), repo)).toHaveLength(1);
67 expect(demoCommands(session(alice), ctxWith(), undefined)).toEqual([]);
68 });
69
70 test("a reader and a guest are refused, and nothing is pinned", async () => {
71 for (const who of [bob, undefined]) {
72 const toasts: string[] = [];
73 expect(demoScreen(session(who), ctxWith(toasts), repo).key?.(press("p"))).toBe(true);
74 await waitFor(() => toasts.length > 0);
75 expect(toasts.join(" ")).not.toContain("pinned at");
76 }
77 expect(await ref()).toBeUndefined();
78 });
79
80 test("a writer pins the default branch's tip, and the ref is the API's", async () => {
81 const toasts: string[] = [];
82 expect(demoScreen(session(alice), ctxWith(toasts), repo).key?.(press("p"))).toBe(true);
83 await waitFor(() => toasts.length > 0);
84 expect(toasts).toEqual([`Demo pinned at ${tip.slice(0, 12)}.`]);
85 expect(await ref()).toBe(tip);
86 });
87 });
88
89 /** Presses `x` and returns the confirm it pushes, with the toasts it says. */
90 const askToClear = async (who: User | undefined) => {
91 const toasts: string[] = [];
92 const pushed: Screen[] = [];
93 const ctx = { toast: (t: string) => toasts.push(t), invalidate() {}, push: (s: Screen) => pushed.push(s), pop() {}, theme: {} } as unknown as Ctx;
94 expect(demoScreen(session(who), ctx, repo).key?.(press("x"))).toBe(true);
95 await waitFor(() => pushed.length > 0);
96 return { confirm: pushed[0]!, toasts };
97 };
98
99 describe("clearing", () => {
100 test("x asks first; nothing is cleared until it is answered, nor on Cancel", async () => {
101 const { confirm, toasts } = await askToClear(alice);
102 expect(confirm.title).toBe("Clear the demo");
103 expect(await ref()).toBe(tip);
104 // Cancel is selected first, and choosing it returns without starting anything.
105 confirm.key?.(press("enter"));
106 expect(toasts).toEqual([]);
107 expect(await ref()).toBe(tip);
108 });
109
110 test("a reader who chooses Clear is refused, and the ref stays", async () => {
111 const { confirm, toasts } = await askToClear(bob);
112 confirm.key?.(press("right"));
113 confirm.key?.(press("enter"));
114 await waitFor(() => toasts.length > 0);
115 expect(toasts).toEqual([WORDS.forbidden]);
116 expect(await ref()).toBe(tip);
117 });
118
119 test("a writer who chooses Clear clears the ref", async () => {
120 const { confirm, toasts } = await askToClear(alice);
121 confirm.key?.(press("right"));
122 confirm.key?.(press("enter"));
123 await waitFor(() => toasts.length > 0);
124 expect(toasts).toEqual(["Demo cleared."]);
125 expect(await ref()).toBeUndefined();
126 });
127 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs