Public: anyone can read this; the crew can change it.
Archive many at once from the home, with an undo that holds for a day #2531
scout/forge:scout/1620-archive-many-at-once-from-the-home-with → main 2 commits fork
7 files
changed +312
−2
README.md +2
| @@ -350,6 +350,8 @@ updates into a conflict opens the converge issue at every door. See | ||
| 350 | 350 | |
| 351 | 351 | ## Archive |
| 352 | 352 | |
| 353 | Many at once: on the home, an admin opens **Archive repositories**, ticks several and taps Archive (one same-origin `POST /archive`). The page that answers lists them with an **Undo** (`POST /archive/undo`) that wakes exactly that batch for 24 hours; a batch shares one archive time, so the undo needs no state of its own. | |
| 354 | ||
| 353 | 355 | An admin puts a repository away from **Settings → Archive**, with |
| 354 | 356 | `PATCH /api/v1/repos/:owner/:name {"archived":true|false}` (admins only; anyone |
| 355 | 357 | else gets 403), or in the terminal with `a` on the About card (`I`). The |
src/actions/archive_many.ts added +74
| @@ -0,0 +1,74 @@ | ||
| 1 | /** | |
| 2 | * Archive many repositories at once, and take it back for a day (#1620). | |
| 3 | * A batch is the repositories archived together under one shared stamp, so | |
| 4 | * the undo needs no state of its own: it wakes exactly the repositories that | |
| 5 | * still carry that stamp, and only while the stamp is under a day old. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { App } from "../app.ts"; | |
| 9 | import { getRepoById, type Repo } from "../core/repos.ts"; | |
| 10 | import type { User } from "../core/users.ts"; | |
| 11 | import { updateRepoSettings } from "./repos.ts"; | |
| 12 | ||
| 13 | /** How long an undo holds. */ | |
| 14 | export const UNDO_MS = 24 * 60 * 60 * 1000; | |
| 15 | ||
| 16 | /** The most repositories one batch names. */ | |
| 17 | export const BATCH_MAX = 100; | |
| 18 | ||
| 19 | export interface Batch { | |
| 20 | /** The shared stamp the undo presents. */ | |
| 21 | readonly at: string; | |
| 22 | readonly repos: readonly Repo[]; | |
| 23 | } | |
| 24 | ||
| 25 | /** | |
| 26 | * Archive the named repositories the actor administers. One that is missing, | |
| 27 | * not theirs or already archived is left out, without saying which. Agents | |
| 28 | * archive nothing (`updateRepoSettings` refuses them). | |
| 29 | */ | |
| 30 | export async function archiveMany( | |
| 31 | app: App, | |
| 32 | actor: User, | |
| 33 | ids: readonly string[], | |
| 34 | now: Date = new Date(), | |
| 35 | ): Promise<Batch> { | |
| 36 | const at = now.toISOString(); | |
| 37 | const done: Repo[] = []; | |
| 38 | for (const id of new Set(ids.slice(0, BATCH_MAX))) { | |
| 39 | const repo = getRepoById(app.db, id); | |
| 40 | if (repo === undefined || repo.archivedAt !== null) continue; | |
| 41 | const updated = await updateRepoSettings(app, actor, repo, { archived: true, archivedAt: at }); | |
| 42 | if (updated.ok) done.push(updated.value); | |
| 43 | } | |
| 44 | return { at, repos: done }; | |
| 45 | } | |
| 46 | ||
| 47 | /** Whether a batch stamp is still inside its day. */ | |
| 48 | export const undoable = (at: string, now: Date): boolean => { | |
| 49 | const then = Date.parse(at); | |
| 50 | return !Number.isNaN(then) && now.getTime() - then >= 0 && now.getTime() - then < UNDO_MS; | |
| 51 | }; | |
| 52 | ||
| 53 | /** | |
| 54 | * Wake the repositories archived under `at` that the actor administers. | |
| 55 | * Null when the day has passed; otherwise the ones woken (a repository | |
| 56 | * archived again later, or woken by hand, carries another stamp and stays). | |
| 57 | */ | |
| 58 | export async function undoArchive( | |
| 59 | app: App, | |
| 60 | actor: User, | |
| 61 | ids: readonly string[], | |
| 62 | at: string, | |
| 63 | now: Date = new Date(), | |
| 64 | ): Promise<Repo[] | null> { | |
| 65 | if (!undoable(at, now)) return null; | |
| 66 | const woken: Repo[] = []; | |
| 67 | for (const id of new Set(ids.slice(0, BATCH_MAX))) { | |
| 68 | const repo = getRepoById(app.db, id); | |
| 69 | if (repo === undefined || repo.archivedAt !== at) continue; | |
| 70 | const updated = await updateRepoSettings(app, actor, repo, { archived: false }); | |
| 71 | if (updated.ok) woken.push(updated.value); | |
| 72 | } | |
| 73 | return woken; | |
| 74 | } |
src/core/repos.ts +10
| @@ -1050,6 +1050,8 @@ export interface RepoSettings { | ||
| 1050 | 1050 | decisionsBy?: DecisionsBy; |
| 1051 | 1051 | /** Archive (true) or wake (false); the time is stamped here. */ |
| 1052 | 1052 | archived?: boolean; |
| 1053 | /** With `archived: true`, the stamp to use: one batch shares one time. */ | |
| 1054 | archivedAt?: string; | |
| 1053 | 1055 | plansNeedNod?: boolean; |
| 1054 | 1056 | } |
| 1055 | 1057 | |
| @@ -1091,6 +1093,14 @@ export function updateRepoSettings( | ||
| 1091 | 1093 | settings.autonomyBy === undefined ? repo.autonomyBy : settings.autonomyBy, |
| 1092 | 1094 | (settings.crewOutsiders ?? repo.crewOutsiders) ? 1 : 0, |
| 1093 | 1095 | settings.decisionsBy ?? repo.decisionsBy, |
| 1096 | <<<<<<< HEAD | |
| 1097 | settings.archived === undefined | |
| 1098 | ? repo.archivedAt | |
| 1099 | : settings.archived | |
| 1100 | ? (repo.archivedAt ?? settings.archivedAt ?? new Date().toISOString()) | |
| 1101 | : null, | |
| 1102 | ======= | |
| 1103 | >>>>>>> origin/main | |
| 1094 | 1104 | (settings.plansNeedNod ?? repo.plansNeedNod) ? 1 : 0, |
| 1095 | 1105 | ); |
| 1096 | 1106 | return getRepoById(db, repo.id)!; |
src/http/server.ts +3
| @@ -262,6 +262,7 @@ import { | ||
| 262 | 262 | studioDoor, |
| 263 | 263 | } from "../web/studio/home.ts"; |
| 264 | 264 | import { appAnswersFragment } from "../web/studio/answers.ts"; |
| 265 | import { archiveBatch, archiveUndo } from "../web/studio/archive.ts"; | |
| 265 | 266 | import { appNowFragment } from "../web/studio/now.ts"; |
| 266 | 267 | import { appStateFragment } from "../web/studio/previews.ts"; |
| 267 | 268 | import { changesList, tellsList } from "../web/studio/lists.ts"; |
| @@ -628,6 +629,8 @@ export function buildRouter(): Router<Handler> { | ||
| 628 | 629 | // cached by the browser's HTTP cache or an update would wait a day. |
| 629 | 630 | router.add("GET", "/sw.js", serviceWorker); |
| 630 | 631 | router.add("GET", "/", home); |
| 632 | router.add("POST", "/archive", archiveBatch); | |
| 633 | router.add("POST", "/archive/undo", archiveUndo); | |
| 631 | 634 | // A spawned child's claim link: GET shows, POST takes it (spawn/claim.ts). |
| 632 | 635 | router.add("GET", "/claim", claimFragmentPage); |
| 633 | 636 | router.add("POST", "/claim", claimSubmit); |
src/web/studio/archive.ts added +69
| @@ -0,0 +1,69 @@ | ||
| 1 | /** | |
| 2 | * Archive many from the home (#1620): the rail's checkboxes post here, and | |
| 3 | * the page that answers lists what was put away with an Undo that holds for | |
| 4 | * a day (`actions/archive_many.ts`). Both are same-origin POSTs; a repository | |
| 5 | * the viewer does not administer is silently left out, as `not_found` is. | |
| 6 | */ | |
| 7 | ||
| 8 | import { archiveMany, undoArchive, UNDO_MS } from "../../actions/archive_many.ts"; | |
| 9 | import type { Repo } from "../../core/repos.ts"; | |
| 10 | import type { Ctx } from "../../http/context.ts"; | |
| 11 | import { repoBase, signInFirst } from "../chrome.ts"; | |
| 12 | import { readForm } from "../form.ts"; | |
| 13 | import { html, type Html } from "../html.ts"; | |
| 14 | import { page, redirect } from "../layout.ts"; | |
| 15 | import { btn, card } from "../ui.ts"; | |
| 16 | ||
| 17 | /** A repository id is a short token of letters and digits; anything else is not one. */ | |
| 18 | const ID = /^[A-Za-z0-9_-]{1,64}$/; | |
| 19 | const ids = (values: readonly unknown[]): string[] => | |
| 20 | values.filter((v): v is string => typeof v === "string" && ID.test(v)); | |
| 21 | ||
| 22 | const hours = UNDO_MS / 3_600_000; | |
| 23 | ||
| 24 | const list = (repos: readonly Repo[]): Html => | |
| 25 | html`<ul class="list"> | |
| 26 | ${repos.map((r) => html`<li class="row"><a href="${repoBase(r)}">${r.ownerName}/${r.name}</a></li>`)} | |
| 27 | </ul>`; | |
| 28 | ||
| 29 | /** POST /archive — archive the ticked repositories, answer with the list and its Undo. */ | |
| 30 | export async function archiveBatch(ctx: Ctx): Promise<Response> { | |
| 31 | const user = ctx.auth.user; | |
| 32 | if (!user) return signInFirst(ctx); | |
| 33 | const form = await readForm(ctx, "admin"); | |
| 34 | if (form instanceof Response) return form; | |
| 35 | const picked = ids(form.getAll("item")); | |
| 36 | if (picked.length === 0) return redirect("/", { flash: { tone: "danger", message: "Tick the repositories to archive first." } }); | |
| 37 | const batch = await archiveMany(ctx.app, user, picked); | |
| 38 | if (batch.repos.length === 0) | |
| 39 | return redirect("/", { flash: { tone: "danger", message: "Nothing was archived." } }); | |
| 40 | const body = card( | |
| 41 | html`<p>Archived ${batch.repos.length} ${batch.repos.length === 1 ? "repository" : "repositories"}. Undo holds for ${hours} hours.</p> | |
| 42 | ${list(batch.repos)} | |
| 43 | <form method="post" action="/archive/undo" class="form-actions"> | |
| 44 | <input type="hidden" name="at" value="${batch.at}" /> | |
| 45 | ${batch.repos.map((r) => html`<input type="hidden" name="item" value="${r.id}" />`)} | |
| 46 | ${btn("Undo", { variant: "primary" })} | |
| 47 | ${btn("Back home", { href: "/" })} | |
| 48 | </form>`, | |
| 49 | { head: html`<h2>Archived</h2>` }, | |
| 50 | ); | |
| 51 | return page({ ctx, title: "Archived", body: html`<h1 class="sr-only">Archived</h1>${body}` }); | |
| 52 | } | |
| 53 | ||
| 54 | /** POST /archive/undo — wake the batch, if its day has not passed. */ | |
| 55 | export async function archiveUndo(ctx: Ctx): Promise<Response> { | |
| 56 | const user = ctx.auth.user; | |
| 57 | if (!user) return signInFirst(ctx); | |
| 58 | const form = await readForm(ctx, "admin"); | |
| 59 | if (form instanceof Response) return form; | |
| 60 | const at = String(form.get("at") ?? ""); | |
| 61 | const woken = await undoArchive(ctx.app, user, ids(form.getAll("item")), at); | |
| 62 | if (woken === null) | |
| 63 | return redirect("/", { | |
| 64 | flash: { tone: "danger", message: `The undo held for ${hours} hours and that has passed. Wake each from its settings.` }, | |
| 65 | }); | |
| 66 | return redirect("/", { | |
| 67 | flash: { message: `Woke ${woken.length} ${woken.length === 1 ? "repository" : "repositories"}.` }, | |
| 68 | }); | |
| 69 | } |
src/web/studio/home.ts +30 −2
| @@ -19,7 +19,7 @@ import { appsRuntime } from "../../apps/runtime.ts"; | ||
| 19 | 19 | import { appsForRepos } from "../../core/apps.ts"; |
| 20 | 20 | import { WEIGHT_MAX, WEIGHT_NAMES } from "../../core/front.ts"; |
| 21 | 21 | import { LOOK_SIZES } from "../../core/looks.ts"; |
| 22 | import { canRead, getRepo, type Repo } from "../../core/repos.ts"; | |
| 22 | import { canAdmin, canRead, getRepo, listReposWritableTo, type Repo } from "../../core/repos.ts"; | |
| 23 | 23 | import { type User } from "../../core/users.ts"; |
| 24 | 24 | import type { Ctx } from "../../http/context.ts"; |
| 25 | 25 | import { edgeLoginUrl } from "../../http/edge.ts"; |
| @@ -118,6 +118,34 @@ function yourApps(ctx: Ctx, user: User): Html { | ||
| 118 | 118 | ); |
| 119 | 119 | } |
| 120 | 120 | |
| 121 | /** | |
| 122 | * Archive many at once (#1620): every repository the viewer administers | |
| 123 | * and has not put away, behind one tap, each with a box; one same-origin | |
| 124 | * POST archives the ticked ones and the answer carries the Undo. | |
| 125 | */ | |
| 126 | function archiveCard(ctx: Ctx, user: User): Html | null { | |
| 127 | const mine = listReposWritableTo(ctx.app.db, user, { limit: 200, withoutArchived: true }).filter( | |
| 128 | (repo) => canAdmin(ctx.app.db, repo, user), | |
| 129 | ); | |
| 130 | if (mine.length === 0) return null; | |
| 131 | return html`<details class="card home-archive"> | |
| 132 | <summary class="card-head"><h2>Archive repositories</h2></summary> | |
| 133 | <form class="card-body stack" method="post" action="/archive"> | |
| 134 | <ul class="list"> | |
| 135 | ${mine.map( | |
| 136 | (repo) => html`<li class="row"> | |
| 137 | <label class="row" | |
| 138 | ><input type="checkbox" name="item" value="${repo.id}" /> | |
| 139 | ${repo.ownerName}/${repo.name}</label | |
| 140 | > | |
| 141 | </li>`, | |
| 142 | )} | |
| 143 | </ul> | |
| 144 | <div class="form-actions">${btn("Archive selected", { size: "sm", icon: "folder" })}</div> | |
| 145 | </form> | |
| 146 | </details>`; | |
| 147 | } | |
| 148 | ||
| 121 | 149 | /** |
| 122 | 150 | * Each live region on the home has an address of its own (`data-live-src`), |
| 123 | 151 | * so an event fetches that region — your apps, or what is on you — and not |
| @@ -245,7 +273,7 @@ export async function studioHome( | ||
| 245 | 273 | // on a phone. |
| 246 | 274 | user.isAdmin || appRepos.length > 0 ? crewKeyNote(ctx) : null |
| 247 | 275 | } |
| 248 | ${appsRegion(ctx, user)} | |
| 276 | ${appsRegion(ctx, user)} ${archiveCard(ctx, user)} | |
| 249 | 277 | ${terminalCard(ctx)} ${downloadsCard(ctx, user)} |
| 250 | 278 | ${orgsCard(ctx, user)} |
| 251 | 279 | </aside> |
test/archive-many.test.ts added +124
| @@ -0,0 +1,124 @@ | ||
| 1 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 2 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import { archiveMany, undoArchive, UNDO_MS } from "../src/actions/archive_many.ts"; | |
| 6 | import { createApp, type App } from "../src/app.ts"; | |
| 7 | import { getRepo } from "../src/core/repos.ts"; | |
| 8 | import { getUserByName } from "../src/core/users.ts"; | |
| 9 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 10 | ||
| 11 | describe("archive many from the home", () => { | |
| 12 | let dataDir: string; | |
| 13 | let app: App; | |
| 14 | let servers: Servers; | |
| 15 | let base: string; | |
| 16 | let ada = ""; | |
| 17 | let bob = ""; | |
| 18 | const names = ["one", "two", "three"]; | |
| 19 | ||
| 20 | const form = (fields: [string, string][]) => new URLSearchParams(fields); | |
| 21 | const state = (n: string) => getRepo(app.db, "ada", n)!; | |
| 22 | const id = (n: string) => state(n).id; | |
| 23 | ||
| 24 | async function signup(username: string): Promise<string> { | |
| 25 | const res = await fetch(`${base}/signup`, { | |
| 26 | method: "POST", | |
| 27 | body: form([["username", username], ["email", `${username}@f.dev`], ["password", "archive-password"]]), | |
| 28 | redirect: "manual", | |
| 29 | }); | |
| 30 | return (res.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 31 | } | |
| 32 | const post = (path: string, cookie: string, fields: [string, string][], origin = base) => | |
| 33 | fetch(`${base}${path}`, { method: "POST", headers: { cookie, origin }, body: form(fields), redirect: "manual" }); | |
| 34 | ||
| 35 | beforeAll(async () => { | |
| 36 | dataDir = await mkdtemp(join(tmpdir(), "forge-archive-many-")); | |
| 37 | app = createApp({ dataDir, port: 0 }); | |
| 38 | servers = await serve(app); | |
| 39 | base = servers.url; | |
| 40 | ada = await signup("ada"); | |
| 41 | bob = await signup("bob"); | |
| 42 | for (const name of names) | |
| 43 | await fetch(`${base}/new`, { | |
| 44 | method: "POST", | |
| 45 | headers: { cookie: ada }, | |
| 46 | body: form([["name", name], ["visibility", "public"], ["description", "x"]]), | |
| 47 | redirect: "manual", | |
| 48 | }); | |
| 49 | }); | |
| 50 | ||
| 51 | afterAll(async () => { | |
| 52 | servers.stop(); | |
| 53 | app.close(); | |
| 54 | await rm(dataDir, { recursive: true, force: true }); | |
| 55 | }); | |
| 56 | ||
| 57 | test("the home offers an admin the boxes and the button; a stranger's has none of ada's", async () => { | |
| 58 | const home = await (await fetch(`${base}/`, { headers: { cookie: ada } })).text(); | |
| 59 | expect(home).toContain('action="/archive"'); | |
| 60 | expect(home).toContain(`value="${id("one")}"`); | |
| 61 | const other = await (await fetch(`${base}/`, { headers: { cookie: bob } })).text(); | |
| 62 | expect(other).not.toContain(`value="${id("one")}"`); | |
| 63 | }); | |
| 64 | ||
| 65 | test("cross-origin and non-admin posts change nothing", async () => { | |
| 66 | const items: [string, string][] = names.map((n) => ["item", id(n)]); | |
| 67 | expect((await post("/archive", ada, items, "http://evil.example")).status).toBe(403); | |
| 68 | await post("/archive", bob, items); | |
| 69 | for (const n of names) expect(state(n).archivedAt).toBeNull(); | |
| 70 | const at = new Date().toISOString(); | |
| 71 | expect((await post("/archive/undo", ada, [["at", at], ...items], "http://evil.example")).status).toBe(403); | |
| 72 | }); | |
| 73 | ||
| 74 | test("archives several in one post, lists them with an Undo, and Undo wakes exactly those", async () => { | |
| 75 | const res = await post("/archive", ada, [["item", id("one")], ["item", id("two")]]); | |
| 76 | expect(res.status).toBe(200); | |
| 77 | const text = (await res.text()).split('id="main"')[1]!.split("</main>")[0]!; | |
| 78 | expect(text).toContain("Archived 2 repositories"); | |
| 79 | expect(text).toContain("ada/one"); | |
| 80 | expect(text).toContain("ada/two"); | |
| 81 | expect(text).not.toContain("ada/three"); | |
| 82 | expect(text).toContain('action="/archive/undo"'); | |
| 83 | const at = state("one").archivedAt!; | |
| 84 | expect(state("two").archivedAt).toBe(at); | |
| 85 | expect(state("three").archivedAt).toBeNull(); | |
| 86 | ||
| 87 | // A stranger's undo wakes nothing. | |
| 88 | await post("/archive/undo", bob, [["at", at], ["item", id("one")], ["item", id("two")]]); | |
| 89 | expect(state("one").archivedAt).toBe(at); | |
| 90 | ||
| 91 | // Ada archives three alone, then undoes the first batch: three stays. | |
| 92 | await post("/archive", ada, [["item", id("three")]]); | |
| 93 | const undo = await post("/archive/undo", ada, [["at", at], ["item", id("one")], ["item", id("two")], ["item", id("three")]]); | |
| 94 | expect(undo.status).toBe(303); | |
| 95 | expect(state("one").archivedAt).toBeNull(); | |
| 96 | expect(state("two").archivedAt).toBeNull(); | |
| 97 | expect(state("three").archivedAt).not.toBeNull(); | |
| 98 | }); | |
| 99 | ||
| 100 | test("an undo is refused after a day, with a fake clock", async () => { | |
| 101 | const ada_ = getUserByName(app.db, "ada")!; | |
| 102 | const t0 = new Date("2026-01-01T00:00:00Z"); | |
| 103 | const woke = await undoArchive(app, ada_, [id("three")], state("three").archivedAt!, new Date()); | |
| 104 | expect(woke?.length).toBe(1); | |
| 105 | ||
| 106 | const batch = await archiveMany(app, ada_, [id("one"), id("two")], t0); | |
| 107 | expect(batch.repos.length).toBe(2); | |
| 108 | const ids = batch.repos.map((r) => r.id); | |
| 109 | const late = new Date(t0.getTime() + UNDO_MS); | |
| 110 | expect(await undoArchive(app, ada_, ids, batch.at, late)).toBeNull(); | |
| 111 | expect(state("one").archivedAt).toBe(batch.at); | |
| 112 | const early = new Date(t0.getTime() + UNDO_MS - 1); | |
| 113 | expect((await undoArchive(app, ada_, ids, batch.at, early))?.length).toBe(2); | |
| 114 | expect(state("one").archivedAt).toBeNull(); | |
| 115 | }); | |
| 116 | ||
| 117 | test("a late undo over HTTP says so and changes nothing", async () => { | |
| 118 | const old = new Date(Date.now() - 2 * UNDO_MS).toISOString(); | |
| 119 | app.db.query("UPDATE repo SET archived_at = ?1 WHERE id = ?2").run(old, id("one")); | |
| 120 | const res = await post("/archive/undo", ada, [["at", old], ["item", id("one")]]); | |
| 121 | expect(res.status).toBe(303); | |
| 122 | expect(state("one").archivedAt).toBe(old); | |
| 123 | }); | |
| 124 | }); |
new above
offline