Public: anyone can read this; the crew can change it.
Admins mark which repositories are offered as templates for new forges #16752
Check · Review · Land · Live done — Landed and live in production.
mason/forge:mason/7536-admins-mark-which-repositories-are-offer → main 0 commits fork 4 threads · 4 unresolved
29 files
changed +675
−21
- docs/features/forge-templates.md
- scripts/unused-exports-allow.json
- src/actions/forge_templates.ts
- src/contract/openapi/routes/deleteApiV1ForgeTemplatesId.ts
- src/contract/openapi/routes/index.ts
- src/contract/openapi/routes/postApiV1ForgeTemplates.ts
- src/contract/tags.ts
- src/core/event_audience.ts
- src/core/forge_templates.ts
- src/core/migration-pins/20261130110000-forge-template.pin
- src/core/migrations/20261130110000-forge-template.ts
- src/http/api.ts
- src/http/api/forge_templates.ts
- src/http/api/forges.ts
- src/http/marks/api-v1-forge-templates.json
- src/http/mcp/tools/templates.ts
- src/http/server.ts
- src/spawn/template_list.ts
- src/spawn/template_says.ts
- src/spawn/templates.ts
- src/tui/screens/app_templates.ts
- src/web/pages/forge-template-setting.ts
- src/web/pages/new-forge-template.ts
- src/web/pages/new-forge.ts
- src/web/pages/settings.ts
- test/conversation-confirm.test.ts
- test/forge-templates.test.ts
- test/private-by-default.test.ts
- test/tui-app-templates.test.ts
docs/features/forge-templates.md added +18
| @@ -0,0 +1,18 @@ | ||
| 1 | --- | |
| 2 | topic: Hosting forges for others, and getting paid | |
| 3 | row: Templates an admin offers for new forges | |
| 4 | --- | |
| 5 | # Templates an admin offers for new forges | |
| 6 | ||
| 7 | A site admin may offer any repository on this forge as a template for new forges, so the list grows without a release. | |
| 8 | ||
| 9 | - **Offer:** `POST /api/v1/forge-templates {repo, title, says}` (site admin, `rw`), the MCP `templates` tool with `action: "offer"`, or the control on the repository's App settings. The repository must be readable by the admin and its default branch must declare an app (`forge.json`, checked as the settings toggle checks it). Offering again rewords it. | |
| 10 | - **Withdraw:** `DELETE /api/v1/forge-templates/:id` (`owner~name` or `owner%2Fname`), `action: "withdraw"`, or the Withdraw button. | |
| 11 | - **Where it shows:** `GET /api/v1/forges/templates` (`source: "repo"`, id `owner/name`) and the New forge picker, under the admin's title and sentence, to whoever can read the repository. A repository made private or deleted drops out; a spawn naming it, or a withdrawn one, is a 422. | |
| 12 | - **Birth:** the new forge copies the repository's files at its default-branch tip and records `{id, repo, tip}` in `parent.json` (`spawn/template_record.ts`). | |
| 13 | ||
| 14 | Whether a repository is offered is its template flag (`repo.is_template`); `forge_template` only holds the admin's words, so the list, the picker and a spawn read one truth. | |
| 15 | ||
| 16 | Offering sets the flag only when it was off, and remembers that it did (`forge_template.flagged`); withdrawing clears it only then, so a flag the repository's owner set stays. This is separate from the New app list (`app_template`, Settings → App templates), which an offer never touches. In the terminal, the App templates screen takes `o` (offer: repository, title, sentence) and `w` (withdraw). | |
| 17 | ||
| 18 | The web control is `src/web/pages/forge-template-setting.ts`; its terminal side is `src/tui/screens/app_templates.ts`. |
scripts/unused-exports-allow.json +1
src/actions/forge_templates.ts added +94
| @@ -0,0 +1,94 @@ | ||
| 1 | /** | |
| 2 | * A site admin offers a repository as a template for new forges, or withdraws it (#7536). Only | |
| 3 | * an admin; only a repository the admin can read whose tip declares an app (`templateProblem`, | |
| 4 | * the manifest's own checks). Offering sets the repository's template flag and keeps the admin's | |
| 5 | * title and sentence; withdrawing forgets the words, and clears the flag only if the offer set it. | |
| 6 | * One place, so the API, the MCP and the settings page refuse in the same words. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { App } from "../app.ts"; | |
| 10 | import { templateProblem } from "../apps/template_problem.ts"; | |
| 11 | import { parseTemplateName } from "../apps/template_tip.ts"; | |
| 12 | import { offer, SAYS_MAX, TITLE_MAX, withdraw } from "../core/forge_templates.ts"; | |
| 13 | import { canRead, getRepo, updateRepoSettings, type Repo } from "../core/repos.ts"; | |
| 14 | import type { User } from "../core/users.ts"; | |
| 15 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 16 | ||
| 17 | export type ForgeTemplateError = "forbidden" | "no_such_repo" | "invalid" | "no_app"; | |
| 18 | ||
| 19 | export interface ForgeTemplateRefusal { | |
| 20 | readonly error: ForgeTemplateError; | |
| 21 | readonly message: string; | |
| 22 | } | |
| 23 | ||
| 24 | export interface OfferedTemplate { | |
| 25 | readonly id: string; | |
| 26 | readonly title: string; | |
| 27 | readonly says: string; | |
| 28 | } | |
| 29 | ||
| 30 | const FORBIDDEN = { error: "forbidden", message: "Only a site admin offers templates." } as const; | |
| 31 | const refusal = (error: ForgeTemplateError, message: string): Result<never, ForgeTemplateRefusal> => | |
| 32 | err({ error, message }); | |
| 33 | ||
| 34 | /** The statuses a refusal answers with, for the HTTP door. */ | |
| 35 | export const FORGE_TEMPLATE_STATUS: Record<ForgeTemplateError, number> = { | |
| 36 | forbidden: 403, | |
| 37 | no_such_repo: 404, | |
| 38 | invalid: 422, | |
| 39 | no_app: 422, | |
| 40 | }; | |
| 41 | ||
| 42 | const isSiteAdmin = (actor: User | undefined): actor is User => actor !== undefined && actor.isAdmin && actor.kind === "user"; | |
| 43 | ||
| 44 | /** | |
| 45 | * One line of plain text no longer than `max`, trimmed; undefined when it is empty, long or has a | |
| 46 | * control character. | |
| 47 | */ | |
| 48 | function oneLine(v: unknown, max: number): string | undefined { | |
| 49 | if (typeof v !== "string") return undefined; | |
| 50 | const s = v.trim(); | |
| 51 | // biome-ignore lint: control characters are the point | |
| 52 | return s === "" || s.length > max || /[\u0000-\u001f\u007f]/.test(s) ? undefined : s; | |
| 53 | } | |
| 54 | ||
| 55 | /** The repository named `owner/name` that `actor` can read, as the door's refusals say it. */ | |
| 56 | function readable(app: App, actor: User, named: unknown): Result<Repo, ForgeTemplateRefusal> { | |
| 57 | const parsed = typeof named === "string" ? parseTemplateName(named) : undefined; | |
| 58 | const repo = parsed && parsed.folder === undefined && getRepo(app.db, parsed.owner, parsed.name); | |
| 59 | // A repository the admin cannot read is not told apart from one that is not there. | |
| 60 | return repo && canRead(app.db, repo, actor) ? ok(repo) : refusal("no_such_repo", "No repository by that name. Name it owner/name."); | |
| 61 | } | |
| 62 | ||
| 63 | export async function offerTemplate( | |
| 64 | app: App, | |
| 65 | actor: User | undefined, | |
| 66 | input: { repo?: unknown; title?: unknown; says?: unknown }, | |
| 67 | ): Promise<Result<OfferedTemplate, ForgeTemplateRefusal>> { | |
| 68 | if (!isSiteAdmin(actor)) return err(FORBIDDEN); | |
| 69 | const repo = readable(app, actor, input.repo); | |
| 70 | if (!repo.ok) return repo; | |
| 71 | const title = oneLine(input.title, TITLE_MAX); | |
| 72 | if (title === undefined) return refusal("invalid", `title is one line of at most ${TITLE_MAX} characters`); | |
| 73 | const says = oneLine(input.says, SAYS_MAX); | |
| 74 | if (says === undefined) return refusal("invalid", `says is one sentence of at most ${SAYS_MAX} characters`); | |
| 75 | const problem = await templateProblem(app, repo.value); | |
| 76 | if (problem !== undefined) return refusal("no_app", `${repo.value.ownerName}/${repo.value.name} declares no app at its tip: ${problem}`); | |
| 77 | const id = `${repo.value.ownerName}/${repo.value.name}`; | |
| 78 | const setsFlag = !repo.value.template; | |
| 79 | if (setsFlag) updateRepoSettings(app.db, repo.value, { template: true }); | |
| 80 | offer(app.db, repo.value.id, title, says, actor.id, setsFlag); | |
| 81 | app.bus.append({ kind: "forge_template.offered", actorId: actor.id, payload: { repo: id } }); | |
| 82 | return ok({ id, title, says }); | |
| 83 | } | |
| 84 | ||
| 85 | export function withdrawTemplate(app: App, actor: User | undefined, named: unknown): Result<{ id: string }, ForgeTemplateRefusal> { | |
| 86 | if (!isSiteAdmin(actor)) return err(FORBIDDEN); | |
| 87 | const repo = readable(app, actor, named); | |
| 88 | if (!repo.ok) return repo; | |
| 89 | const id = `${repo.value.ownerName}/${repo.value.name}`; | |
| 90 | // Clear the template flag only when the offer set it; an owner's own flag stays. | |
| 91 | if (withdraw(app.db, repo.value.id) && repo.value.template) updateRepoSettings(app.db, repo.value, { template: false }); | |
| 92 | app.bus.append({ kind: "forge_template.withdrawn", actorId: actor.id, payload: { repo: id } }); | |
| 93 | return ok({ id }); | |
| 94 | } |
src/contract/openapi/routes/deleteApiV1ForgeTemplatesId.ts added +12
| @@ -0,0 +1,12 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "delete", | |
| 5 | path: "/api/v1/forge-templates/{id}", | |
| 6 | summary: "Withdraw a repository from the templates offered for new forges (site admin, rw scope)", | |
| 7 | detail: | |
| 8 | "Withdraw a repository (id is owner/name, the slash as %2F or ~) from the templates offered for new forges; a spawn naming it is then refused", | |
| 9 | auth: true, | |
| 10 | role: "admin", | |
| 11 | refuses: [401, 404], | |
| 12 | }; |
src/contract/openapi/routes/index.ts +2
| @@ -9,6 +9,7 @@ export { route as deleteApiV1CodesId } from "./deleteApiV1CodesId.ts"; | ||
| 9 | 9 | export { route as deleteApiV1ConversationFilesId } from "./deleteApiV1ConversationFilesId.ts"; |
| 10 | 10 | export { route as deleteApiV1ConversationQueueId } from "./deleteApiV1ConversationQueueId.ts"; |
| 11 | 11 | export { route as deleteApiV1FeaturesSlug } from "./deleteApiV1FeaturesSlug.ts"; |
| 12 | export { route as deleteApiV1ForgeTemplatesId } from "./deleteApiV1ForgeTemplatesId.ts"; | |
| 12 | 13 | export { route as deleteApiV1ForgesRecipesName } from "./deleteApiV1ForgesRecipesName.ts"; |
| 13 | 14 | export { route as deleteApiV1OrgsOrgTeamsTeam } from "./deleteApiV1OrgsOrgTeamsTeam.ts"; |
| 14 | 15 | export { route as deleteApiV1OrgsOrgTeamsTeamMembersUsername } from "./deleteApiV1OrgsOrgTeamsTeamMembersUsername.ts"; |
| @@ -345,6 +346,7 @@ export { route as postApiV1FirstAdmin } from "./postApiV1FirstAdmin.ts"; | ||
| 345 | 346 | export { route as postApiV1FirstAdminRecover } from "./postApiV1FirstAdminRecover.ts"; |
| 346 | 347 | export { route as postApiV1FleetOps } from "./postApiV1FleetOps.ts"; |
| 347 | 348 | export { route as postApiV1FleetOpsIdUndo } from "./postApiV1FleetOpsIdUndo.ts"; |
| 349 | export { route as postApiV1ForgeTemplates } from "./postApiV1ForgeTemplates.ts"; | |
| 348 | 350 | export { route as postApiV1Forges } from "./postApiV1Forges.ts"; |
| 349 | 351 | export { route as postApiV1ForgesNameClaimLink } from "./postApiV1ForgesNameClaimLink.ts"; |
| 350 | 352 | export { route as postApiV1ForgesNameSandbox } from "./postApiV1ForgesNameSandbox.ts"; |
src/contract/openapi/routes/postApiV1ForgeTemplates.ts added +19
| @@ -0,0 +1,19 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "post", | |
| 5 | path: "/api/v1/forge-templates", | |
| 6 | summary: "Offer a repository as a template for new forges", | |
| 7 | detail: | |
| 8 | "Offer a repository as a template for new forges (site admin, rw scope); send { repo: \"owner/name\", title, says }; the repository must be readable by you and its default branch must declare an app; offering again rewords it. It then appears in GET /api/v1/forges/templates and the New forge picker", | |
| 9 | auth: true, | |
| 10 | role: "admin", | |
| 11 | refusals: { | |
| 12 | forbidden: "the caller is not a site admin", | |
| 13 | no_such_repo: "no repository by that name that you can read", | |
| 14 | invalid: "title (at most 60 characters) and says (at most 140) are one line each", | |
| 15 | no_app: "the repository's default branch declares no app", | |
| 16 | }, | |
| 17 | errorStatus: { 422: "`invalid` or `no_app`: a title and a sentence are required; the repository's tip must declare an app" }, | |
| 18 | refuses: [401, 404], | |
| 19 | }; |
src/contract/tags.ts +1
src/core/event_audience.ts +2
| @@ -353,6 +353,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 353 | 353 | kind === "repo.file_released" || |
| 354 | 354 | // Which repositories New app offers is the admins' choice (`actions/app_templates.ts`). |
| 355 | 355 | kind.startsWith("app_template.") || |
| 356 | // Likewise which repositories new forges may start from (`actions/forge_templates.ts`). | |
| 357 | kind.startsWith("forge_template.") || | |
| 356 | 358 | // What a parent lends a child's crew, by name and dollar, is the admins' business |
| 357 | 359 | // (`actions/child_credit.ts`, #10484). |
| 358 | 360 | kind === "forge.credit_set" || |
src/core/forge_templates.ts added +53
| @@ -0,0 +1,53 @@ | ||
| 1 | /** | |
| 2 | * The words a site admin gave the repositories offered as templates for new forges (#7536): | |
| 3 | * a title and one sentence each, kept in `forge_template`. Plain rows in, plain rows out; who may | |
| 4 | * offer, and what a repository must be, is the action's (`actions/forge_templates.ts`). Whether a | |
| 5 | * repository is offered at all is its `is_template` flag, so the list, the picker and a spawn | |
| 6 | * read one truth; a row only says it in the admin's words and remembers whether the offer set the | |
| 7 | * flag, so a withdrawal never clears one the repository's owner set. | |
| 8 | */ | |
| 9 | ||
| 10 | import type { Database } from "bun:sqlite"; | |
| 11 | ||
| 12 | export const TITLE_MAX = 60; | |
| 13 | export const SAYS_MAX = 140; | |
| 14 | ||
| 15 | export interface OfferedNote { | |
| 16 | /** The repository as `owner/name`, the template's id. */ | |
| 17 | readonly id: string; | |
| 18 | readonly title: string; | |
| 19 | readonly says: string; | |
| 20 | } | |
| 21 | ||
| 22 | /** The title and sentence of every offered repository, by `owner/name`. */ | |
| 23 | export function offeredNotes(db: Database): Map<string, OfferedNote> { | |
| 24 | const rows = db | |
| 25 | .query<OfferedNote, []>( | |
| 26 | `SELECT user.username || '/' || repo.name AS id, t.title AS title, t.says AS says | |
| 27 | FROM forge_template t JOIN repo ON repo.id = t.repo_id JOIN user ON user.id = repo.owner_id | |
| 28 | WHERE repo.is_template = 1 | |
| 29 | ORDER BY t.marked_at, t.repo_id`, | |
| 30 | ) | |
| 31 | .all(); | |
| 32 | return new Map(rows.map((r) => [r.id, r])); | |
| 33 | } | |
| 34 | ||
| 35 | /** | |
| 36 | * Offer a repository in these words, or change the words of one already offered. `flagged` is | |
| 37 | * true when this offer is what turned the repository's template flag on; a reword keeps it. | |
| 38 | */ | |
| 39 | export function offer(db: Database, repoId: string, title: string, says: string, actorId: string, flagged: boolean): void { | |
| 40 | db.query( | |
| 41 | `INSERT INTO forge_template (repo_id, title, says, flagged, marked_by) VALUES (?1, ?2, ?3, ?4, ?5) | |
| 42 | ON CONFLICT (repo_id) DO UPDATE SET title = excluded.title, says = excluded.says, marked_by = excluded.marked_by`, | |
| 43 | ).run(repoId, title, says, flagged ? 1 : 0, actorId); | |
| 44 | } | |
| 45 | ||
| 46 | /** | |
| 47 | * Forget the words of a repository no longer offered. True when the offer had set the repository's | |
| 48 | * template flag itself, so the caller clears it; false when the flag was the owner's (or no offer). | |
| 49 | */ | |
| 50 | export function withdraw(db: Database, repoId: string): boolean { | |
| 51 | const row = db.query<{ flagged: number }, [string]>("DELETE FROM forge_template WHERE repo_id = ?1 RETURNING flagged").get(repoId); | |
| 52 | return row?.flagged === 1; | |
| 53 | } |
src/core/migration-pins/20261130110000-forge-template.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | a52d6e673bceea8763384cdd56305d4a07cb1e5321587e98f8f4c6c219be3e74 |
src/core/migrations/20261130110000-forge-template.ts added +14
| @@ -0,0 +1,14 @@ | ||
| 1 | // Repositories a site admin offers as templates for new forges (#7536): the words the picker | |
| 2 | // shows for each (`title`, `says`) and who marked it. The offer itself is the repository's | |
| 3 | // `is_template` flag; a row only says it in the admin's words, and `flagged` says the offer set | |
| 4 | // that flag (so withdrawing may clear it) rather than the repository's owner. Additive. | |
| 5 | export default ` | |
| 6 | CREATE TABLE forge_template ( | |
| 7 | repo_id TEXT PRIMARY KEY REFERENCES repo(id) ON DELETE CASCADE, | |
| 8 | title TEXT NOT NULL, | |
| 9 | says TEXT NOT NULL, | |
| 10 | flagged INTEGER NOT NULL DEFAULT 0, | |
| 11 | marked_by TEXT REFERENCES user(id) ON DELETE SET NULL, | |
| 12 | marked_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')) | |
| 13 | ); | |
| 14 | `; |
src/http/api.ts +2
| @@ -351,6 +351,7 @@ import { diskReadingRoutes } from "./api/disk_readings.ts"; | ||
| 351 | 351 | import { TEMPLATE_ERRORS } from "../apps/template_tip.ts"; |
| 352 | 352 | import { flagsRoutes } from "./api/flags.ts"; |
| 353 | 353 | import { appTemplateRoutes } from "./api/app_templates.ts"; |
| 354 | import { forgeTemplateRoutes } from "./api/forge_templates.ts"; | |
| 354 | 355 | import { issueRoutes, labelsHandler } from "./api/issues.ts"; |
| 355 | 356 | import { chapterRoutes } from "./api/chapters.ts"; |
| 356 | 357 | import { chapterNames } from "../core/chapters.ts"; |
| @@ -1265,6 +1266,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo | ||
| 1265 | 1266 | diskReadingRoutes(router); |
| 1266 | 1267 | flagsRoutes(router); |
| 1267 | 1268 | appTemplateRoutes(router); |
| 1269 | forgeTemplateRoutes(router); | |
| 1268 | 1270 | |
| 1269 | 1271 | // Open read hooks (#1789): the owner, or an agent holding `telemetry:read`. |
| 1270 | 1272 | // Anyone else is refused; every agent read is logged. |
src/http/api/forge_templates.ts added +36
| @@ -0,0 +1,36 @@ | ||
| 1 | /** | |
| 2 | * Templates offered for new forges (#7536). `POST /api/v1/forge-templates` with | |
| 3 | * `{ repo: "owner/name", title, says }` offers a repository, or rewords one already offered; | |
| 4 | * `DELETE /api/v1/forge-templates/:id` (`owner/name`, the slash as `%2F` or `~`, every one) | |
| 5 | * withdraws it. Site admin only: anyone else signed in is told 403. The list is | |
| 6 | * `GET /api/v1/forges/templates`. | |
| 7 | */ | |
| 8 | ||
| 9 | import { FORGE_TEMPLATE_STATUS, offerTemplate, withdrawTemplate } from "../../actions/forge_templates.ts"; | |
| 10 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; | |
| 11 | import type { Handler } from "../context.ts"; | |
| 12 | import { apiError, body, json, requireScope, unauthorized } from "../respond.ts"; | |
| 13 | import type { Router } from "../router.ts"; | |
| 14 | ||
| 15 | export function forgeTemplateRoutes(router: Router<Handler>): void { | |
| 16 | router.add("POST", "/api/v1/forge-templates", async (ctx) => { | |
| 17 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 18 | if (!ctx.auth.user) return unauthorized(); | |
| 19 | const scoped = requireScope(ctx, "rw"); | |
| 20 | if (scoped) return scoped; | |
| 21 | const input = await body(ctx.request); | |
| 22 | const done = await offerTemplate(ctx.app, ctx.auth.user, input); | |
| 23 | if (done.ok) return json(done.value, 201); | |
| 24 | return apiError(done.error.error, FORGE_TEMPLATE_STATUS[done.error.error], done.error.message); | |
| 25 | }); | |
| 26 | ||
| 27 | router.add("DELETE", "/api/v1/forge-templates/:id", (ctx) => { | |
| 28 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 29 | if (!ctx.auth.user) return unauthorized(); | |
| 30 | const scoped = requireScope(ctx, "rw"); | |
| 31 | if (scoped) return scoped; | |
| 32 | const done = withdrawTemplate(ctx.app, ctx.auth.user, (ctx.params["id"] ?? "").split("~").join("/")); | |
| 33 | if (done.ok) return json(done.value); | |
| 34 | return apiError(done.error.error, FORGE_TEMPLATE_STATUS[done.error.error], done.error.message); | |
| 35 | }); | |
| 36 | } |
src/http/api/forges.ts +2 −1
| @@ -18,6 +18,7 @@ import { checkMove } from "../../spawn/move_check.ts"; | ||
| 18 | 18 | import { moveToCell } from "../../spawn/move_cell.ts"; |
| 19 | 19 | import { deleteRecipe, listRecipes, saveRecipe } from "../../spawn/recipes.ts"; |
| 20 | 20 | import { sizesView } from "../../spawn/sizes.ts"; |
| 21 | import { repoTemplateRows } from "../../spawn/template_list.ts"; | |
| 21 | 22 | import { templatesView } from "../../spawn/templates.ts"; |
| 22 | 23 | import { billDownload } from "./forge_bill.ts"; |
| 23 | 24 | import { crossOrigin, type Ctx, type Handler } from "../context.ts"; |
| @@ -61,7 +62,7 @@ export function forgeRoutes(router: Router<Handler>): void { | ||
| 61 | 62 | // What small, medium and large mean, and which templates a child may |
| 62 | 63 | // start from: public, and cacheable by ETag. |
| 63 | 64 | router.add("GET", "/api/v1/forges/sizes", (ctx) => publicTable(ctx, "sizes", sizesView)); |
| 64 | router.add("GET", "/api/v1/forges/templates", (ctx) => publicTable(ctx, "templates", templatesView)); | |
| 65 | router.add("GET", "/api/v1/forges/templates", (ctx) => publicTable(ctx, "templates", () => templatesView(undefined, repoTemplateRows(ctx.app.db, undefined)))); | |
| 65 | 66 | |
| 66 | 67 | // One month of a hosted forge's ledger and this forge's key, for its owner |
| 67 | 68 | // (`core/ledger_bill.ts`). |
src/http/marks/api-v1-forge-templates.json added +4
src/http/mcp/tools/templates.ts +27 −6
| @@ -1,11 +1,32 @@ | ||
| 1 | import { offerTemplate, withdrawTemplate } from "../../../actions/forge_templates.ts"; | |
| 2 | import { repoTemplateRows } from "../../../spawn/template_list.ts"; | |
| 1 | 3 | import { templatesView } from "../../../spawn/templates.ts"; |
| 2 | import { good, type Tool } from "../shared.ts"; | |
| 4 | import { bad, good, str, type Tool } from "../shared.ts"; | |
| 3 | 5 | |
| 4 | 6 | export const tool: Tool = { |
| 5 | 7 | name: "templates", |
| 6 | doc: "the templates a child forge may start from (`blank` first, the default), each with id, title, one sentence and source, and `packs` (apps, crew roles, budget, \"not stated\" if the pack is silent); pass an id as `spawn`'s `template`; so may the `owner/name` of a repository marked as a template", | |
| 7 | description: "The templates a child forge may start from.", | |
| 8 | inputSchema: { type: "object", properties: {} }, | |
| 9 | writes: false, | |
| 10 | run: () => good(templatesView()), | |
| 8 | doc: "the templates a child forge may start from (`blank` first, the default), each with id, title, one sentence and source, and `packs` (apps, crew roles, budget, \"not stated\" if the pack is silent); pass an id as `spawn`'s `template`; so may the `owner/name` of a repository an admin offered. With `action` `offer` (`repo`, `title`, `says`) or `withdraw` (`repo`), a site admin changes which repositories are offered (`rw`)", | |
| 9 | description: "The templates a child forge may start from; an admin offers or withdraws repositories.", | |
| 10 | inputSchema: { | |
| 11 | type: "object", | |
| 12 | properties: { | |
| 13 | action: { type: "string", enum: ["offer", "withdraw"] }, | |
| 14 | repo: { type: "string", description: "owner/name" }, | |
| 15 | title: { type: "string", description: "with offer: one line" }, | |
| 16 | says: { type: "string", description: "with offer: one sentence" }, | |
| 17 | }, | |
| 18 | }, | |
| 19 | writes: true, | |
| 20 | readsWithout: "action", | |
| 21 | async run(ctx, user, args) { | |
| 22 | if (args["action"] === undefined) return good(templatesView(undefined, repoTemplateRows(ctx.app.db, user))); | |
| 23 | const done = | |
| 24 | args["action"] === "offer" | |
| 25 | ? await offerTemplate(ctx.app, user, { repo: str(args["repo"]), title: args["title"], says: args["says"] }) | |
| 26 | : args["action"] === "withdraw" | |
| 27 | ? withdrawTemplate(ctx.app, user, str(args["repo"])) | |
| 28 | : undefined; | |
| 29 | if (done === undefined) return bad("invalid", "action is offer or withdraw"); | |
| 30 | return done.ok ? good(done.value) : bad(done.error.error, done.error.message); | |
| 31 | }, | |
| 11 | 32 | }; |
src/http/server.ts +2
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | * verdict. Auth is resolved once per request and handed to handlers as data. |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | import { forgeTemplateUpdate } from "../web/pages/forge-template-setting.ts"; | |
| 8 | 9 | import { allocationMove, allocationPage, allocationWeekly } from "../web/pages/allocation.ts"; |
| 9 | 10 | import { cloudConnectBuild, cloudConnectPage, cloudConnectProvider, cloudConnectSubmit } from "../web/pages/cloud.ts"; |
| 10 | 11 | import { runOwnToken } from "../web/own_token.ts"; |
| @@ -1896,6 +1897,7 @@ export function buildRouter(): Router<Handler> { | ||
| 1896 | 1897 | router.add("GET", "/:owner/:name/machines/:machine/shell", machineShellPage); |
| 1897 | 1898 | router.add("POST", "/:owner/:name/settings/app", appSettingsUpdate); |
| 1898 | 1899 | router.add("POST", "/:owner/:name/settings/app/disable", appDisable); |
| 1900 | router.add("POST", "/:owner/:name/settings/app/forge-template", forgeTemplateUpdate); | |
| 1899 | 1901 | router.add("POST", "/:owner/:name/settings/app/members", appMembersUpdate); |
| 1900 | 1902 | router.add("POST", "/:owner/:name/settings/app/env", appEnvSet); |
| 1901 | 1903 | router.add("POST", "/:owner/:name/settings/app/flags", appFlagSet); |
src/spawn/template_list.ts +9 −1
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | 7 | import type { Database } from "bun:sqlite"; |
| 8 | import { offeredNotes } from "../core/forge_templates.ts"; | |
| 8 | 9 | import { listReposVisibleTo } from "../core/repos.ts"; |
| 9 | 10 | import type { User } from "../core/users.ts"; |
| 10 | 11 | import type { TemplateUse } from "./template_use.ts"; |
| @@ -48,12 +49,19 @@ export function templateList(db: Database, viewer: User | undefined, used: Reado | ||
| 48 | 49 | */ |
| 49 | 50 | export function templateListUnsorted(db: Database, viewer: User | undefined): TemplateRow[] { |
| 50 | 51 | const repos = listReposVisibleTo(db, viewer, { templatesOnly: true, limit: 50 }).map((r) => `${r.ownerName}/${r.name}`); |
| 52 | const said = repos.length === 0 ? new Map<string, { title: string; says: string }>() : offeredNotes(db); | |
| 51 | 53 | return [...TEMPLATES.map((t) => t.id), ...repos].map((id) => { |
| 52 | 54 | const t = templateOf(id); |
| 53 | return { id, title: t.title, says: t.says }; | |
| 55 | // An admin's words for an offered repository (#7536) are its title and sentence. | |
| 56 | const note = said.get(id); | |
| 57 | return { id, title: note?.title ?? t.title, says: note?.says ?? t.says }; | |
| 54 | 58 | }); |
| 55 | 59 | } |
| 56 | 60 | |
| 61 | /** The template repositories a viewer can read, in the admin's words where an admin gave them. */ | |
| 62 | export const repoTemplateRows = (db: Database, viewer: User | undefined): TemplateRow[] => | |
| 63 | templateListUnsorted(db, viewer).filter((r) => templateOf(r.id).source === "repo"); | |
| 64 | ||
| 57 | 65 | /** The path of a template's own page: a built-in id, or `owner/name`, as two segments. */ |
| 58 | 66 | export const templatePath = (id: string): string => `/templates/${id}`; |
| 59 | 67 |
src/spawn/template_says.ts +4 −1
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | 8 | import type { App } from "../app.ts"; |
| 9 | import { offeredNotes } from "../core/forge_templates.ts"; | |
| 9 | 10 | import { getRepo } from "../core/repos.ts"; |
| 10 | 11 | import { blobForRender, refTip } from "../git/read.ts"; |
| 11 | 12 | import { repoDir } from "../git/repos.ts"; |
| @@ -110,11 +111,13 @@ export async function withReadmeSays(app: App, rows: readonly TemplateRow[]): Pr | ||
| 110 | 111 | for (const id of [...mine.keys()]) if (!ids.has(id)) mine.delete(id); |
| 111 | 112 | } |
| 112 | 113 | const out = [...rows]; |
| 114 | const said = offeredNotes(app.db); | |
| 113 | 115 | let next = 0; |
| 114 | 116 | const worker = async () => { |
| 115 | 117 | for (let i = next++; i < rows.length; i = next++) { |
| 116 | 118 | const r = rows[i]!; |
| 117 | const says = repoTemplateRef(r.id) === undefined ? undefined : await readmeSays(app, r.id); | |
| 119 | // An offered repository keeps the sentence its admin wrote (#7536). | |
| 120 | const says = repoTemplateRef(r.id) === undefined || said.has(r.id) ? undefined : await readmeSays(app, r.id); | |
| 118 | 121 | if (says !== undefined) out[i] = { ...r, says }; |
| 119 | 122 | } |
| 120 | 123 | }; |
src/spawn/templates.ts +15 −4
| @@ -1,8 +1,8 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * Templates: the named starting points a new forge's apps may come from, in |
| 3 | 3 | * one list. Plain data in, plain data out; nothing here writes a file. A |
| 4 | * template is built in (its files are this forge's own code) or, one day, | |
| 5 | * backed by a repository on this forge (`source: "repo"`, `repo`). | |
| 4 | * template is built in (its files are this forge's own code) or backed by a repository on this | |
| 5 | * forge (`source: "repo"`, `repo`). | |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | 8 | import { err, ok, type Result } from "../kernel/result.ts"; |
| @@ -74,14 +74,25 @@ export function templateOf(id: string): Template { | ||
| 74 | 74 | export const templateNotMarked = (ref: string): string => `${ref} is not marked as a template`; |
| 75 | 75 | export const templateNotReadable = (ref: string): string => `${ref} is not readable by you`; |
| 76 | 76 | |
| 77 | /** A repository offered as a template, in its admin's words (`core/forge_templates.ts`). */ | |
| 78 | export interface OfferedRow { | |
| 79 | readonly id: string; | |
| 80 | readonly title: string; | |
| 81 | readonly says: string; | |
| 82 | } | |
| 83 | ||
| 77 | 84 | /** |
| 78 | 85 | * What each template is, for a page or an agent to offer; `packs` says what a forge made from |
| 79 | 86 | * each listed pack gets: its apps, crew roles and budget, "not stated" where the pack is silent. |
| 80 | 87 | */ |
| 81 | export function templatesView(packs: readonly Pack[] = catalog().packs): { | |
| 88 | export function templatesView( | |
| 89 | packs: readonly Pack[] = catalog().packs, | |
| 90 | offered: readonly OfferedRow[] = [], | |
| 91 | ): { | |
| 82 | 92 | templates: readonly Template[]; |
| 83 | 93 | default: string; |
| 84 | 94 | packs: readonly PackFacts[]; |
| 85 | 95 | } { |
| 86 | return { templates: TEMPLATES, default: DEFAULT_TEMPLATE, packs: packs.map(packFacts) }; | |
| 96 | const repos: Template[] = offered.map((r) => ({ id: r.id, title: r.title, says: r.says, source: "repo", repo: r.id })); | |
| 97 | return { templates: [...TEMPLATES, ...repos], default: DEFAULT_TEMPLATE, packs: packs.map(packFacts) }; | |
| 87 | 98 | } |
src/tui/screens/app_templates.ts +54 −4
| @@ -4,7 +4,8 @@ | ||
| 4 | 4 | * an `owner/name` and marks it; `u` unmarks the one under the cursor after a |
| 5 | 5 | * confirm. Both go through `markTemplate`, so the refusals are the page's and |
| 6 | 6 | * the API's words. Anyone who is not an admin (or is an agent) is offered no |
| 7 | * entry and marks nothing. | |
| 7 | * entry and marks nothing. `o` offers a repository as a template for new forges in a title and a | |
| 8 | * sentence (#7536), `w` withdraws one; both go through `actions/forge_templates.ts`. | |
| 8 | 9 | */ |
| 9 | 10 | |
| 10 | 11 | import { MARK_TEMPLATE_ERRORS, markTemplate } from "../../actions/app_templates.ts"; |
| @@ -12,6 +13,8 @@ import { templateFactsOf } from "../../web/template_card.ts"; | ||
| 12 | 13 | import { holdsRows, templateHolds } from "../../spawn/template_holds.ts"; |
| 13 | 14 | import { templateRows, type TemplateFacts } from "../../spawn/template_facts.ts"; |
| 14 | 15 | import { DEFAULT_TEMPLATE, markedTemplates } from "../../core/app_templates.ts"; |
| 16 | import { offerTemplate, withdrawTemplate } from "../../actions/forge_templates.ts"; | |
| 17 | import { offeredNotes, SAYS_MAX, TITLE_MAX } from "../../core/forge_templates.ts"; | |
| 15 | 18 | import type { Ctx, Screen } from "../app/app.ts"; |
| 16 | 19 | import type { PaletteEntry } from "./entries.ts"; |
| 17 | 20 | import { binding } from "../app/keys.ts"; |
| @@ -19,7 +22,7 @@ import { style } from "../term/style.ts"; | ||
| 19 | 22 | import { wrap } from "../term/width.ts"; |
| 20 | 23 | import { fill, len, split } from "../ui/layout.ts"; |
| 21 | 24 | import type { Session } from "../session.ts"; |
| 22 | import { ListState, confirmScreen, drawList, promptScreen, type ListRow } from "./common.ts"; | |
| 25 | import { ListState, confirmScreen, drawList, later, promptScreen, type ListRow } from "./common.ts"; | |
| 23 | 26 | |
| 24 | 27 | const mayMark = (f: Session): boolean => f.user?.isAdmin === true && f.user.kind === "user"; |
| 25 | 28 | |
| @@ -72,6 +75,48 @@ export function appTemplatesScreen(f: Session, ctx: Ctx): Screen { | ||
| 72 | 75 | }, |
| 73 | 76 | }); |
| 74 | 77 | |
| 78 | // Offering for new forges: which repository, its title, its sentence; each prompt keeps the | |
| 79 | // refusal's words open until the answer is one the action takes. | |
| 80 | const offer = (): Screen => | |
| 81 | promptScreen(ctx, screen, { | |
| 82 | title: "Offer for new forges", | |
| 83 | label: "Which repository?", | |
| 84 | placeholder: "owner/name", | |
| 85 | onSubmit: (named) => | |
| 86 | later(ctx, () => | |
| 87 | promptScreen(ctx, screen, { | |
| 88 | title: "Offer for new forges", | |
| 89 | label: "Title", | |
| 90 | hint: `One line, at most ${TITLE_MAX} characters.`, | |
| 91 | onSubmit: (title) => | |
| 92 | later(ctx, () => | |
| 93 | promptScreen(ctx, screen, { | |
| 94 | title: "Offer for new forges", | |
| 95 | label: "What a forge made from it starts with", | |
| 96 | hint: `One sentence, at most ${SAYS_MAX} characters.`, | |
| 97 | onSubmit: async (says) => { | |
| 98 | const done = await offerTemplate(f.app, f.user, { repo: named, title, says }); | |
| 99 | note = done.ok ? `${done.value.id} is offered for new forges.` : done.error.message; | |
| 100 | ctx.invalidate(); | |
| 101 | }, | |
| 102 | }), | |
| 103 | ), | |
| 104 | }), | |
| 105 | ), | |
| 106 | }); | |
| 107 | const withdraw = (): Screen => | |
| 108 | promptScreen(ctx, screen, { | |
| 109 | title: "Withdraw from new forges", | |
| 110 | label: "Which repository?", | |
| 111 | placeholder: "owner/name", | |
| 112 | onSubmit: (named) => { | |
| 113 | const done = withdrawTemplate(f.app, f.user, named); | |
| 114 | note = done.ok ? `${done.value.id} is no longer offered for new forges.` : done.error.message; | |
| 115 | ctx.invalidate(); | |
| 116 | return undefined; | |
| 117 | }, | |
| 118 | }); | |
| 119 | ||
| 75 | 120 | const lines = (): ListRow[] => |
| 76 | 121 | rows.map((r) => ({ |
| 77 | 122 | title: r.name, |
| @@ -80,10 +125,10 @@ export function appTemplatesScreen(f: Session, ctx: Ctx): Screen { | ||
| 80 | 125 | |
| 81 | 126 | const screen: Screen = { |
| 82 | 127 | title: "App templates", |
| 83 | keys: [binding(["m"], "mark one"), binding(["u"], "unmark"), binding(["j", "k"], "move cursor")], | |
| 128 | keys: [binding(["m"], "mark one"), binding(["u"], "unmark"), binding(["o"], "offer for forges"), binding(["w"], "withdraw"), binding(["j", "k"], "move cursor")], | |
| 84 | 129 | render(area, s) { |
| 85 | 130 | const c = ctx.theme.c; |
| 86 | const text = note !== "" ? note : mayMark(f) ? `${rows.length} offered by New app.` : MARK_TEMPLATE_ERRORS.forbidden; | |
| 131 | const text = note !== "" ? note : mayMark(f) ? `${rows.length} offered by New app; ${offeredNotes(f.db).size} by New forge.` : MARK_TEMPLATE_ERRORS.forbidden; | |
| 87 | 132 | const at = rows[state.index]; |
| 88 | 133 | if (at !== undefined && mayMark(f)) learn(at.name); |
| 89 | 134 | const detail = at === undefined ? [] : (gets.get(at.name) ?? []); |
| @@ -100,6 +145,11 @@ export function appTemplatesScreen(f: Session, ctx: Ctx): Screen { | ||
| 100 | 145 | ctx.push(mark()); |
| 101 | 146 | return true; |
| 102 | 147 | } |
| 148 | if (e.key === "o" || e.key === "w") { | |
| 149 | note = ""; | |
| 150 | ctx.push(e.key === "o" ? offer() : withdraw()); | |
| 151 | return true; | |
| 152 | } | |
| 103 | 153 | const r = rows[state.index]; |
| 104 | 154 | if (e.key === "u" && r !== undefined) { |
| 105 | 155 | note = ""; |
src/web/pages/forge-template-setting.ts added +53
| @@ -0,0 +1,53 @@ | ||
| 1 | /** | |
| 2 | * The admin control on a repository's App settings (#7536): offer the repository as a template | |
| 3 | * for new forges in a title and a sentence, reword it, or withdraw it. Shown to a site admin | |
| 4 | * only; the action refuses anyone else in the same words as the API and the MCP. | |
| 5 | */ | |
| 6 | ||
| 7 | import { offerTemplate, withdrawTemplate } from "../../actions/forge_templates.ts"; | |
| 8 | import { offeredNotes, SAYS_MAX, TITLE_MAX } from "../../core/forge_templates.ts"; | |
| 9 | import type { Repo } from "../../core/repos.ts"; | |
| 10 | import type { Ctx } from "../../http/context.ts"; | |
| 11 | import { adminForm } from "../admin_form.ts"; | |
| 12 | import { field } from "../form.ts"; | |
| 13 | import { html, type Html } from "../html.ts"; | |
| 14 | import { flashTo } from "../layout.ts"; | |
| 15 | import { repoBase } from "../chrome.ts"; | |
| 16 | import { btn, card, field as inputField } from "../ui.ts"; | |
| 17 | ||
| 18 | /** The control, or nothing for anyone but a site admin. */ | |
| 19 | export function forgeTemplateSetting(ctx: Ctx, repo: Repo): Html | null { | |
| 20 | const user = ctx.auth.user; | |
| 21 | if (user === undefined || !user.isAdmin || user.kind !== "user") return null; | |
| 22 | const note = offeredNotes(ctx.app.db).get(`${repo.ownerName}/${repo.name}`); | |
| 23 | return card( | |
| 24 | html`<form method="post" action="${repoBase(repo)}/settings/app/forge-template"> | |
| 25 | <h2>Offer as a template for new forges</h2> | |
| 26 | <p class="muted"> | |
| 27 | The New forge page and <span class="mono">/api/v1/forges/templates</span> list it under this | |
| 28 | title and sentence, to whoever can read the repository. | |
| 29 | </p> | |
| 30 | ${inputField({ name: "title", label: "Title", value: note?.title ?? repo.name, maxlength: TITLE_MAX, required: true })} | |
| 31 | ${inputField({ name: "says", label: "What a forge made from it starts with", value: note?.says ?? "", maxlength: SAYS_MAX, required: true })} | |
| 32 | <div class="form-actions"> | |
| 33 | ${btn(note === undefined ? "Offer" : "Save", { variant: "primary", name: "do", value: "offer" })} | |
| 34 | ${note === undefined ? null : btn("Withdraw", { name: "do", value: "withdraw" })} | |
| 35 | </div> | |
| 36 | </form>`, | |
| 37 | ); | |
| 38 | } | |
| 39 | ||
| 40 | // POST /:owner/:name/settings/app/forge-template | |
| 41 | export async function forgeTemplateUpdate(ctx: Ctx): Promise<Response> { | |
| 42 | const gate = await adminForm(ctx); | |
| 43 | if (gate instanceof Response) return gate; | |
| 44 | const { repo, form } = gate; | |
| 45 | const to = `${repoBase(repo)}/settings/app`; | |
| 46 | const id = `${repo.ownerName}/${repo.name}`; | |
| 47 | if (field(form, "do") === "withdraw") { | |
| 48 | const done = withdrawTemplate(ctx.app, ctx.auth.user, id); | |
| 49 | return flashTo(ctx, to, done.ok ? { message: `${id} is no longer offered as a template.` } : { tone: "danger", message: done.error.message }); | |
| 50 | } | |
| 51 | const done = await offerTemplate(ctx.app, ctx.auth.user, { repo: id, title: field(form, "title"), says: field(form, "says") }); | |
| 52 | return flashTo(ctx, to, done.ok ? { message: `${id} is offered as a template.` } : { tone: "danger", message: done.error.message }); | |
| 53 | } |
src/web/pages/new-forge-template.ts +5 −2
| @@ -21,6 +21,7 @@ export function templateOptions( | ||
| 21 | 21 | chosen: string, |
| 22 | 22 | repos: readonly string[], |
| 23 | 23 | heads: ReadonlyMap<string, string> = new Map(), |
| 24 | notes: ReadonlyMap<string, { title: string; says: string }> = new Map(), | |
| 24 | 25 | ): { value: string; label: string; selected?: boolean }[] { |
| 25 | 26 | const known = TEMPLATES.some((t) => t.id === chosen) || repos.includes(chosen); |
| 26 | 27 | const at = known ? chosen : DEFAULT_TEMPLATE; |
| @@ -28,7 +29,8 @@ export function templateOptions( | ||
| 28 | 29 | ...TEMPLATES.map((t) => ({ value: t.id, label: `${t.title}: ${lower(t.says)}`, selected: t.id === at })), |
| 29 | 30 | ...repos.map((ref) => ({ |
| 30 | 31 | value: ref, |
| 31 | label: `${ref}: ${lower(templateOf(ref).says)}${headLabel(heads.get(ref))}`, | |
| 32 | // An offered repository (#7536) goes by its admin's title and sentence. | |
| 33 | label: `${notes.has(ref) ? `${notes.get(ref)!.title} (${ref})` : ref}: ${lower(notes.get(ref)?.says ?? templateOf(ref).says)}${headLabel(heads.get(ref))}`, | |
| 32 | 34 | selected: ref === at, |
| 33 | 35 | })), |
| 34 | 36 | ]; |
| @@ -39,10 +41,11 @@ export function templatePicker( | ||
| 39 | 41 | repos: readonly string[], |
| 40 | 42 | heads: ReadonlyMap<string, string>, |
| 41 | 43 | error: string | undefined, |
| 44 | notes: ReadonlyMap<string, { title: string; says: string }> = new Map(), | |
| 42 | 45 | ): Html { |
| 43 | 46 | return html`<fieldset class="field" id="f-template" aria-describedby="f-template-hint${error ? " f-template-err" : ""}" ${error ? html`data-invalid` : null}> |
| 44 | 47 | <legend>Template</legend> |
| 45 | ${templateOptions(chosen, repos, heads).map( | |
| 48 | ${templateOptions(chosen, repos, heads, notes).map( | |
| 46 | 49 | (o) => html`<label class="check"> |
| 47 | 50 | <input type="radio" name="template" value="${o.value}" ${o.selected ? html`checked` : null} /> |
| 48 | 51 | <span>${o.label}</span> |
src/web/pages/new-forge.ts +2 −1
| @@ -43,6 +43,7 @@ import { templateListUnsorted } from "../../spawn/template_list.ts"; | ||
| 43 | 43 | import { templateRows } from "./templates.ts"; |
| 44 | 44 | import { templateHeads } from "../../spawn/template_head.ts"; |
| 45 | 45 | import { html, type Html } from "../html.ts"; |
| 46 | import { offeredNotes } from "../../core/forge_templates.ts"; | |
| 46 | 47 | import { templatePicker } from "./new-forge-template.ts"; |
| 47 | 48 | import { noteForgeMade } from "../funnel_door.ts"; |
| 48 | 49 | import { page, redirect } from "../layout.ts"; |
| @@ -318,7 +319,7 @@ function formView( | ||
| 318 | 319 | ...(freshErr ? { error: freshErr } : {}), |
| 319 | 320 | })} |
| 320 | 321 | ${modeRows(values, errors["modes"])} |
| 321 | ${templatePicker(values.template, templates, heads, errors["template"])} | |
| 322 | ${templatePicker(values.template, templates, heads, errors["template"], templates.length === 0 ? new Map() : offeredNotes(ctx.app.db))} | |
| 322 | 323 | <details class="disclosure" ${Object.keys(errors).some((k) => MORE_FIELDS.includes(k)) ? html`open` : null}> |
| 323 | 324 | <summary>More settings</summary> |
| 324 | 325 | <fieldset class="field" ${errors["followMode"] ? html`data-invalid` : null}> |
src/web/pages/settings.ts +2
| @@ -94,6 +94,7 @@ import { | ||
| 94 | 94 | settingsLayout, |
| 95 | 95 | } from "../chrome.ts"; |
| 96 | 96 | import { adminForm, loadAdminRepo } from "../admin_form.ts"; |
| 97 | import { forgeTemplateSetting } from "./forge-template-setting.ts"; | |
| 97 | 98 | import { daySpark } from "../studio/kpi_row.ts"; |
| 98 | 99 | import { settingsLead, teamJs } from "../studio/crew.ts"; |
| 99 | 100 | import { pageTitle } from "../studio/nouns.ts"; |
| @@ -879,6 +880,7 @@ function appSettingsView( | ||
| 879 | 880 | <div class="form-actions">${btn("Save", { variant: "primary" })}</div> |
| 880 | 881 | </form> |
| 881 | 882 | </div> |
| 883 | ${forgeTemplateSetting(ctx, repo)} | |
| 882 | 884 | <div class="mt"> |
| 883 | 885 | ${card( |
| 884 | 886 | html`<p> |
test/conversation-confirm.test.ts +1 −1
| @@ -129,7 +129,7 @@ describe("the one list of what asks first", () => { | ||
| 129 | 129 | "follow_mode", "forge", "fork", "front_page", "hold", "issue_teams", "keep_plan", "knobs", "labels", "lift", "limb", "maintenance", "make_it_yours", "map", "merge", "new_app", |
| 130 | 130 | "next_up", "week", "notify", "open_pull", "org_create", "origin_apps", "pins", "plan", "profile", "propose_to_parent_forge", "repo_labels", "reports", |
| 131 | 131 | "repo", "restore_drill", "review", "say", "scorecard", "signup", "snapshot_now", "spend", "steer", "sync", "system", "take_back", "take_updates", |
| 132 | "teams", "tell", "threads", "trail", "upstream", "variant", "wait_for", "watch", "whoami_can", "write_file", | |
| 132 | "teams", "tell", "templates", "threads", "trail", "upstream", "variant", "wait_for", "watch", "whoami_can", "write_file", | |
| 133 | 133 | ]); |
| 134 | 134 | |
| 135 | 135 | test("every tool that writes asks first or is named as one that does not (#8230)", () => { |
test/forge-templates.test.ts added +207
| @@ -0,0 +1,207 @@ | ||
| 1 | /** | |
| 2 | * An admin offers repositories as templates for new forges (#7536): only a site admin, only a | |
| 3 | * repository whose tip declares an app; the offer shows in the list and the picker in the admin's | |
| 4 | * words, a forge made from it has the files at the tip recorded in `parent.json`, and a withdrawn, | |
| 5 | * private or deleted repository drops out and a spawn naming it is a 422. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, readFile, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { setRole } from "../src/actions/roles.ts"; | |
| 12 | import { commitToBranch, createRepo, deleteRepo, updateRepoSettings } from "../src/actions/repos.ts"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { getRepo } from "../src/core/repos.ts"; | |
| 15 | import { createSession } from "../src/core/sessions.ts"; | |
| 16 | import { createToken } from "../src/core/tokens.ts"; | |
| 17 | import { createUser, type User } from "../src/core/users.ts"; | |
| 18 | import { runGit } from "../src/git/env.ts"; | |
| 19 | import { repoDir } from "../src/git/repos.ts"; | |
| 20 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 21 | import { ok } from "../src/kernel/result.ts"; | |
| 22 | import { usePlacement, useProbe } from "../src/spawn/door.ts"; | |
| 23 | import { FORGE_CODE_NAME } from "../src/spawn/forge_code.ts"; | |
| 24 | import { quietLogs } from "./helpers/globals.ts"; | |
| 25 | ||
| 26 | quietLogs(); | |
| 27 | ||
| 28 | describe("templates an admin offers", () => { | |
| 29 | let dir = ""; | |
| 30 | let app: App; | |
| 31 | let servers: Servers; | |
| 32 | let alice: User; | |
| 33 | let bob: User; | |
| 34 | let placed = 0; | |
| 35 | const tokens = new Map<string, string>(); | |
| 36 | const WORDS = { title: "Booking kit", says: "A booking page with a calendar." }; | |
| 37 | ||
| 38 | const call = (who: User, method: string, path: string, payload?: unknown) => | |
| 39 | fetch(`${servers.url}${path}`, { | |
| 40 | method, | |
| 41 | headers: { "content-type": "application/json", authorization: `Bearer ${tokens.get(who.id)}` }, | |
| 42 | ...(payload === undefined ? {} : { body: JSON.stringify(payload) }), | |
| 43 | }); | |
| 44 | const offer = (who: User, repo: string) => call(who, "POST", "/api/v1/forge-templates", { repo, ...WORDS }); | |
| 45 | const listed = async () => ((await (await fetch(`${servers.url}/api/v1/forges/templates`)).json()) as { templates: { id: string; title: string; says: string; source: string; repo?: string }[] }).templates; | |
| 46 | const spawn = (name: string, template: string) => | |
| 47 | call(alice, "POST", "/api/v1/forges", { name, apps: [], template, dryRun: false }); | |
| 48 | ||
| 49 | beforeAll(async () => { | |
| 50 | dir = await mkdtemp(join(tmpdir(), "forge-forge-templates-")); | |
| 51 | app = createApp({ dataDir: dir, port: 0 }); | |
| 52 | const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 53 | const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); | |
| 54 | if (!a.ok || !b.ok) throw new Error("users"); | |
| 55 | alice = a.value; | |
| 56 | bob = b.value; | |
| 57 | for (const u of [alice, bob]) tokens.set(u.id, createToken(app.db, u.id, "rw", "rw").token); | |
| 58 | servers = await serve(app); | |
| 59 | useProbe(app, () => async () => true); | |
| 60 | usePlacement(app, { | |
| 61 | place: async (plan) => ok({ url: `https://${plan.name}.fake.test`, bodyId: `fake-${++placed}` }), | |
| 62 | retire: async () => ok(), | |
| 63 | }); | |
| 64 | for (const name of ["kit", "plain", "gone", "hidden"]) { | |
| 65 | const made = await createRepo(app, alice, { name, visibility: "public" }); | |
| 66 | if (!made.ok) throw new Error(name); | |
| 67 | const files = [{ path: "kit.txt", content: name }]; | |
| 68 | if (name !== "plain") files.push({ path: "forge.json", content: '{"app":{"run":"bun main.ts"}}' }); | |
| 69 | await commitToBranch(app, alice, made.value, { message: "seed", files }); | |
| 70 | } | |
| 71 | }, 30_000); | |
| 72 | ||
| 73 | afterAll(async () => { | |
| 74 | servers?.stop(); | |
| 75 | app?.close(); | |
| 76 | await rm(dir, { recursive: true, force: true }); | |
| 77 | }); | |
| 78 | ||
| 79 | test("only an admin offers a template", async () => { | |
| 80 | expect((await offer(bob, "alice/kit")).status).toBe(403); | |
| 81 | expect((await call(bob, "DELETE", "/api/v1/forge-templates/alice%2Fkit")).status).toBe(403); | |
| 82 | expect((await fetch(`${servers.url}/api/v1/forge-templates`, { method: "POST", body: "{}" })).status).toBe(401); | |
| 83 | expect((await listed()).map((t) => t.id)).not.toContain("alice/kit"); | |
| 84 | expect(getRepo(app.db, "alice", "kit")?.template).toBe(false); | |
| 85 | }); | |
| 86 | ||
| 87 | test("a repo without an app manifest is refused", async () => { | |
| 88 | const res = await offer(alice, "alice/plain"); | |
| 89 | expect(res.status).toBe(422); | |
| 90 | expect(((await res.json()) as { error: string }).error).toBe("no_app"); | |
| 91 | expect((await call(alice, "POST", "/api/v1/forge-templates", { repo: "alice/kit", title: "", says: "x" })).status).toBe(422); | |
| 92 | expect((await offer(alice, "alice/nothing")).status).toBe(404); | |
| 93 | expect(getRepo(app.db, "alice", "plain")?.template).toBe(false); | |
| 94 | }); | |
| 95 | ||
| 96 | test("an offered repo appears in the list and the picker", async () => { | |
| 97 | for (const name of ["kit", "gone", "hidden"]) expect((await offer(alice, `alice/${name}`)).status).toBe(201); | |
| 98 | expect((await listed()).find((t) => t.id === "alice/kit")).toEqual({ id: "alice/kit", ...WORDS, source: "repo", repo: "alice/kit" }); | |
| 99 | const cookie = `forge_session=${createSession(app.db, bob.id).token}`; | |
| 100 | const page = await (await fetch(`${servers.url}/forges/new`, { headers: { cookie } })).text(); | |
| 101 | expect(page).toContain('value="alice/kit"'); | |
| 102 | expect(page).toContain("Booking kit (alice/kit): a booking page with a calendar."); | |
| 103 | // The same offer through the MCP tool, for the agent. | |
| 104 | const via = await fetch(`${servers.url}/mcp`, { | |
| 105 | method: "POST", | |
| 106 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${tokens.get(alice.id)}` }, | |
| 107 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "templates", arguments: { action: "withdraw", repo: "alice/gone" } } }), | |
| 108 | }); | |
| 109 | expect(((await via.json()) as any).result.isError).toBeFalsy(); | |
| 110 | expect((await listed()).map((t) => t.id)).not.toContain("alice/gone"); | |
| 111 | }); | |
| 112 | ||
| 113 | test("a forge made from an offered repo has its files at the tip", async () => { | |
| 114 | const head = await runGit(["rev-parse", "HEAD"], { cwd: repoDir(app.reposRoot, "alice", "kit") }); | |
| 115 | if (!head.ok) throw new Error("head"); | |
| 116 | const made = await spawn("kid", "alice/kit"); | |
| 117 | expect(made.status).toBe(201); | |
| 118 | const parent = JSON.parse(await readFile(join(dir, "children", `fake-${placed}`, "parent.json"), "utf8")); | |
| 119 | expect(parent.template).toEqual({ id: "alice/kit", repo: "alice/kit", tip: head.value.trim() }); | |
| 120 | const child = createApp({ dataDir: join(dir, "children", `fake-${placed}`) }); | |
| 121 | try { | |
| 122 | const code = getRepo(child.db, "kid", FORGE_CODE_NAME)!; | |
| 123 | const shown = await runGit(["show", `${code.defaultBranch}:kit.txt`], { cwd: repoDir(child.reposRoot, "kid", FORGE_CODE_NAME) }); | |
| 124 | expect(shown.ok && shown.value).toBe("kit"); | |
| 125 | } finally { | |
| 126 | child.close(); | |
| 127 | } | |
| 128 | }, 60_000); | |
| 129 | ||
| 130 | test("a withdrawn or private repo drops out", async () => { | |
| 131 | expect((await call(alice, "DELETE", "/api/v1/forge-templates/alice~kit")).status).toBe(200); | |
| 132 | expect((await listed()).map((t) => t.id)).not.toContain("alice/kit"); | |
| 133 | const withdrawn = await spawn("again", "alice/kit"); | |
| 134 | expect(withdrawn.status).toBe(422); | |
| 135 | ||
| 136 | const hidden = getRepo(app.db, "alice", "hidden")!; | |
| 137 | expect((await listed()).map((t) => t.id)).toContain("alice/hidden"); | |
| 138 | await updateRepoSettings(app, alice, hidden, { visibility: "private" }); | |
| 139 | expect((await listed()).map((t) => t.id)).not.toContain("alice/hidden"); | |
| 140 | // The anonymous list, and bob's spawn, no longer see it. | |
| 141 | const bobs = await call(bob, "POST", "/api/v1/forges", { name: "peek", apps: [], template: "alice/hidden", dryRun: false }); | |
| 142 | expect(bobs.status).toBe(422); | |
| 143 | ||
| 144 | // A repository offered and then deleted is gone from the list, row and all. | |
| 145 | expect((await offer(alice, "alice/gone")).status).toBe(201); | |
| 146 | await deleteRepo(app, alice, getRepo(app.db, "alice", "gone")!); | |
| 147 | expect((await listed()).map((t) => t.id)).not.toContain("alice/gone"); | |
| 148 | expect((await spawn("late", "alice/gone")).status).toBe(422); | |
| 149 | expect(app.db.query("SELECT COUNT(*) AS n FROM forge_template WHERE repo_id NOT IN (SELECT id FROM repo)").get()).toEqual({ n: 0 }); | |
| 150 | }, 60_000); | |
| 151 | ||
| 152 | const makeKit = async (owner: User, name: string) => { | |
| 153 | const made = await createRepo(app, owner, { name, visibility: "public" }); | |
| 154 | if (!made.ok) throw new Error(name); | |
| 155 | await commitToBranch(app, owner, made.value, { message: "seed", files: [{ path: "forge.json", content: '{"app":{"run":"bun main.ts"}}' }] }); | |
| 156 | return made.value; | |
| 157 | }; | |
| 158 | ||
| 159 | test("withdrawing clears the template flag only when the offer set it", async () => { | |
| 160 | // The owner's own flag stays through an offer and its withdrawal. | |
| 161 | const owned = await makeKit(alice, "owned"); | |
| 162 | await updateRepoSettings(app, alice, owned, { template: true }); | |
| 163 | expect((await offer(alice, "alice/owned")).status).toBe(201); | |
| 164 | expect((await call(alice, "DELETE", "/api/v1/forge-templates/alice~owned")).status).toBe(200); | |
| 165 | expect(getRepo(app.db, "alice", "owned")?.template).toBe(true); | |
| 166 | // A flag the offer set is cleared again, and a reword does not forget that it was the offer's. | |
| 167 | await makeKit(alice, "fresh"); | |
| 168 | expect((await offer(alice, "alice/fresh")).status).toBe(201); | |
| 169 | expect(getRepo(app.db, "alice", "fresh")?.template).toBe(true); | |
| 170 | expect((await offer(alice, "alice/fresh")).status).toBe(201); | |
| 171 | expect((await call(alice, "DELETE", "/api/v1/forge-templates/alice~fresh")).status).toBe(200); | |
| 172 | expect(getRepo(app.db, "alice", "fresh")?.template).toBe(false); | |
| 173 | }); | |
| 174 | ||
| 175 | test("the settings page offers for an admin and flashes the refusal to anyone else", async () => { | |
| 176 | const mine = await makeKit(alice, "paged"); | |
| 177 | setRole(app, alice, "bob", "member"); | |
| 178 | const theirs = await makeKit(bob, "bobs"); | |
| 179 | const post = async (who: User, path: string, form: Record<string, string>) => | |
| 180 | fetch(`${servers.url}${path}/settings/app/forge-template`, { | |
| 181 | method: "POST", | |
| 182 | headers: { cookie: `forge_session=${createSession(app.db, who.id).token}`, origin: servers.url }, | |
| 183 | body: new URLSearchParams(form), | |
| 184 | redirect: "manual", | |
| 185 | }); | |
| 186 | // A repository admin who is not a site admin is refused in the action's words; nothing is | |
| 187 | // offered. | |
| 188 | const refused = await post(bob, "/bob/bobs", { do: "offer", title: "Mine", says: "Not allowed." }); | |
| 189 | expect(refused.status).toBe(303); | |
| 190 | expect(decodeURIComponent(refused.headers.get("set-cookie") ?? "").replace(/\+/g, " ")).toContain("Only a site admin offers templates."); | |
| 191 | expect(getRepo(app.db, "bob", "bobs")?.template).toBe(false); | |
| 192 | expect(theirs.template).toBe(false); | |
| 193 | // Someone who cannot administer the repository is told nothing. | |
| 194 | expect((await post(bob, "/alice/paged", { do: "offer", title: "Mine", says: "No." })).status).toBe(404); | |
| 195 | // The site admin offers, and the title shows with the repository id in the picker. | |
| 196 | const done = await post(alice, "/alice/paged", { do: "offer", title: "Paged kit", says: "A paged start." }); | |
| 197 | expect(done.status).toBe(303); | |
| 198 | expect(getRepo(app.db, "alice", "paged")?.template).toBe(true); | |
| 199 | expect((await listed()).find((t) => t.id === "alice/paged")?.title).toBe("Paged kit"); | |
| 200 | const picker = await (await fetch(`${servers.url}/forges/new`, { headers: { cookie: `forge_session=${createSession(app.db, bob.id).token}` } })).text(); | |
| 201 | expect(picker).toContain("Paged kit (alice/paged): a paged start."); | |
| 202 | // And withdraws. | |
| 203 | expect((await post(alice, "/alice/paged", { do: "withdraw" })).status).toBe(303); | |
| 204 | expect((await listed()).map((t) => t.id)).not.toContain("alice/paged"); | |
| 205 | expect(mine.template).toBe(false); | |
| 206 | }); | |
| 207 | }); |
test/private-by-default.test.ts +2
| @@ -60,10 +60,12 @@ const DOORS: Readonly<Record<string, Door>> = { | ||
| 60 | 60 | "POST /:owner/:name/issues/new": { noRepository: "an issue" }, |
| 61 | 61 | "POST /:owner/:name/make-it-yours": { proven: "test/make-it-yours.test.ts", says: 'getRepo(app.db, "frank", "garden")!.visibility).toBe("private")' }, |
| 62 | 62 | "POST /:owner/:name/pulls/new": { noRepository: "a pull" }, |
| 63 | "POST /:owner/:name/settings/app/forge-template": { noRepository: "marks a repository a template for new forges; its copies are walked as a template" }, | |
| 63 | 64 | "POST /admin/agent-start": { noRepository: "the setting that opens the start call" }, |
| 64 | 65 | "POST /api/v1/admin/app-templates": { noRepository: "marks a repository a template; its copies are walked as a template" }, |
| 65 | 66 | "POST /api/v1/admin/pinned/:name/claim": { noRepository: "issues a new claim link for a pinned forge nobody has claimed" }, |
| 66 | 67 | "POST /api/v1/apps": { walked: API }, |
| 68 | "POST /api/v1/forge-templates": { noRepository: "marks a repository a template for new forges; its copies are walked as a template" }, | |
| 67 | 69 | "POST /api/v1/forges": { walked: SPAWN }, |
| 68 | 70 | "POST /api/v1/migrate": { proven: "test/migrate-trail.test.ts", says: "a migration that asks for no visibility is private" }, |
| 69 | 71 | "POST /api/v1/repos": { walked: API }, |
test/tui-app-templates.test.ts +31
| @@ -12,6 +12,7 @@ import { markTemplate } from "../src/actions/app_templates.ts"; | ||
| 12 | 12 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; |
| 13 | 13 | import { setRole } from "../src/actions/roles.ts"; |
| 14 | 14 | import { createApp, type App } from "../src/app.ts"; |
| 15 | import { offeredNotes } from "../src/core/forge_templates.ts"; | |
| 15 | 16 | import { offeredTemplates } from "../src/core/app_templates.ts"; |
| 16 | 17 | import { getRepo, listReposOwnedBy } from "../src/core/repos.ts"; |
| 17 | 18 | import { createUser, type User } from "../src/core/users.ts"; |
| @@ -140,6 +141,36 @@ describe("the app templates screen", () => { | ||
| 140 | 141 | await feed("\x1b[C\r"); // right to Unmark, enter |
| 141 | 142 | expect(offeredTemplates(app.db, admin)).toEqual(["trevato/app-template"]); |
| 142 | 143 | })); |
| 144 | ||
| 145 | test("o offers for new forges in a title and a sentence, w withdraws, a plain repo is refused", async () => { | |
| 146 | const made = await createRepo(app, admin, { name: "booking", visibility: "public", description: "" }); | |
| 147 | if (!made.ok) throw new Error("booking"); | |
| 148 | await commitToBranch(app, admin, made.value, { message: "t", files: [{ path: "forge.json", content: '{"app":{"run":"bun main.ts"}}' }] }); | |
| 149 | await withScreen(admin, markScreen, async ({ text, feed }) => { | |
| 150 | await feed("o"); | |
| 151 | await feed("giver/booking\r"); | |
| 152 | await feed("Booking kit\r"); | |
| 153 | await feed("A booking page.\r"); | |
| 154 | expect(text()).toContain("giver/booking is offered for new forges."); | |
| 155 | expect(offeredNotes(app.db).get("giver/booking")).toMatchObject({ title: "Booking kit", says: "A booking page." }); | |
| 156 | await feed("w"); | |
| 157 | await feed("giver/booking\r"); | |
| 158 | expect(text()).toContain("giver/booking is no longer offered for new forges."); | |
| 159 | expect(offeredNotes(app.db).has("giver/booking")).toBe(false); | |
| 160 | await feed("o"); | |
| 161 | await feed("giver/kit\r"); | |
| 162 | await feed("Kit\r"); | |
| 163 | await feed("Plain.\r"); | |
| 164 | expect(text()).toContain("declares no app at its tip"); | |
| 165 | }); | |
| 166 | }); | |
| 167 | ||
| 168 | test("a non-admin who presses o offers nothing", () => | |
| 169 | withScreen(taker, markScreen, async ({ feed }) => { | |
| 170 | await feed("o"); | |
| 171 | await feed("giver/kit\r"); | |
| 172 | expect(offeredNotes(app.db).size).toBe(0); | |
| 173 | })); | |
| 143 | 174 | }); |
| 144 | 175 | |
| 145 | 176 | describe("the New app picker", () => { |
new above
offline
High: this sets
is_template, which the existing app-templates feature (actions/app_templates.ts) also owns. Offering here makes the repo a New app template as a side effect. One way to do one thing: reuse or extend that action.