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

A repository's crew page adds a member to a slot in place: no reload, and the scroll position stays #18474

opened this

Merged 4h 50m ago, live in production

scout/forge:scout/18459-a-repository-s-crew-page-adds-a-member-t → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/18459-a-repository-s-crew-page-adds-a-member-t was merged into main as 99ed63c.

Review

Sign in to review this change.
10 files changed +309 −77
src/http/lazy_lists.ts +1
@@ -1100,6 +1100,7 @@ export const REPO_SETTINGS_ROUTES = [
11001100 ["GET", "/:owner/:name/wallet.csv"],
11011101 ["POST", "/:owner/:name/wallet"],
11021102 ["GET", "/:owner/:name/settings/crew"],
1103 ["GET", "/:owner/:name/settings/crew/seat/:role"],
11031104 ["POST", "/:owner/:name/settings/crew"],
11041105 ["POST", "/:owner/:name/settings/crew/subscriptions"],
11051106 ["POST", "/:owner/:name/settings/crew/:username/remove"],
src/http/routes/repo_settings.ts +2 −1
@@ -8,7 +8,7 @@ import { appFlagEditPage } from "../../web/pages/app_flag_edit.ts";
88 import { appFlagSet } from "../../web/pages/app_flags.ts";
99 import { appSecretGrant, appSecretRevoke } from "../../web/pages/app_secrets.ts";
1010 import { crewDevicesPage, crewDeviceAdd, crewDeviceGrant, crewDeviceRemove } from "../../web/pages/crew_devices.ts";
11 import { crewSettingsPage, crewAdd, crewSubscriptionsSave, crewRemove, crewRoleUpdate, pillarUpdate } from "../../web/pages/crew-settings.ts";
11 import { crewSettingsPage, crewSeatFragment, crewAdd, crewSubscriptionsSave, crewRemove, crewRoleUpdate, pillarUpdate } from "../../web/pages/crew-settings.ts";
1212 import { forgeTemplateUpdate } from "../../web/pages/forge-template-setting.ts";
1313 import { machinesSettingsPage, machineShellPage } from "../../web/pages/machines.ts";
1414 import { promptsSettingsPage, promptSourceAdd, promptSourceRun, promptSourceDelete } from "../../web/pages/prompts.ts";
@@ -134,6 +134,7 @@ export function repoSettingsRoutes(router: Router<Handler>): void {
134134 router.add("GET", "/:owner/:name/wallet.csv", walletCsvDownload);
135135 router.add("POST", "/:owner/:name/wallet", walletSave);
136136 router.add("GET", "/:owner/:name/settings/crew", crewSettingsPage);
137 router.add("GET", "/:owner/:name/settings/crew/seat/:role", crewSeatFragment);
137138 router.add("POST", "/:owner/:name/settings/crew", crewAdd);
138139 router.add(
139140 "POST",
src/web/in_place.ts added +63
@@ -0,0 +1,63 @@
1 /**
2 * Forms that act in place. A `<form data-in-place>` posts in the background
3 * asking for JSON, then redraws only what the server says changed: its
4 * answer lists `redraw` URLs, each fetched as the same server-rendered
5 * fragment the page was built from and swapped for the element carrying
6 * `data-fragment` with that URL. Scroll never moves and the focused control
7 * is found again by id. A refusal (422, `{ok:false, error}`) is written
8 * beside the form, never on a new page. A form that also has `data-team`
9 * posts when its select or number changes, and its button hides.
10 *
11 * No state lives here: the page stays what the server drew. Without script
12 * the form posts and redirects as it always did. `IN_PLACE_BUDGET` is the
13 * gzipped byte budget, held by `test/crew-in-place.test.ts`.
outdated

Low (clean): this says the budget is held by test/in-place.test.ts, which does not exist in this pull. The budget is asserted in test/crew-in-place.test.ts. Fix the reference, or move the budget assertion into a test named for this module.

14 */
15 export const IN_PLACE_BUDGET = 1000;
16
17 export const inPlaceJs = /* js */ `
18 (function () {
19 var D = document;
20 function hide(r) { r.querySelectorAll('form[data-team] button[type=submit]').forEach(function (b) { b.hidden = true; }); }
21 hide(D);
22 D.addEventListener('change', function (e) {
23 var t = e.target, f = t.form;
24 if (f && f.hasAttribute('data-team') && (t.tagName === 'SELECT' || t.type === 'number')) f.requestSubmit();
25 });
26 function swap(url) {
27 return fetch(url, { credentials: 'same-origin', headers: { accept: 'text/html' } }).then(function (r) {
28 if (!r.ok) throw 0;
29 return r.text();
30 }).then(function (h) {
31 var t = D.createElement('template'), n;
32 t.innerHTML = h;
33 n = t.content.firstElementChild;
34 D.querySelectorAll('[data-fragment]').forEach(function (o) {
35 if (o.getAttribute('data-fragment') === url && n) { o.replaceWith(n); hide(n); }
36 });
37 });
38 }
39 D.addEventListener('submit', function (e) {
40 var f = e.target;
41 if (!f.hasAttribute || !f.hasAttribute('data-in-place') || !window.fetch || e.defaultPrevented) return;
42 e.preventDefault();
43 if (f.__ip) return;
44 f.__ip = 1;
45 var id = D.activeElement && D.activeElement.id, say = f.__say;
46 if (!say) { say = f.__say = D.createElement('p'); say.className = 'small'; say.setAttribute('role', 'alert'); f.insertAdjacentElement('afterend', say); }
47 function fail(t) { f.__ip = 0; say.textContent = t; }
48 fetch(f.action, { method: 'POST', body: new URLSearchParams(new FormData(f)), credentials: 'same-origin', headers: { accept: 'application/json' } })
49 .then(function (r) {
50 return r.json().catch(function () { return {}; }).then(function (j) {
51 if (!r.ok || j.ok === false) return fail(j.error || 'That did not go through (' + r.status + '). Nothing changed.');
52 say.textContent = '';
53 f.__ip = 0;
54 return Promise.all((j.redraw || []).map(swap)).then(function () {
55 var k = id && D.getElementById(id);
56 if (k) k.focus({ preventScroll: true });
57 });
58 });
59 })
60 .catch(function () { location.reload(); });
61 });
62 })();
63 `;
src/web/pages/crew-settings.ts +28 −7
@@ -9,15 +9,29 @@ import { seatSlotsSaid, setSeatSlots } from "../../actions/seat_slots.ts";
99 import { checkSeatSlots } from "../../crew/seat_slots.ts";
1010 import { addToCrew, listCrew, removeFromCrew } from "../../actions/crew.ts";
1111 import { crewAddedWords, crewRefusal, crewRemovedWords } from "../../actions/crew_words.ts";
12 import { getAgentByName, isCrewRole, setCrewRole } from "../../core/agents.ts";
12 import { crewRole, getAgentByName, isCrewRole, setCrewRole } from "../../core/agents.ts";
1313 import type { Ctx } from "../../http/context.ts";
1414 import { loadRepo, repoBase, repoNotFound } from "../chrome.ts";
1515 import { field } from "../form.ts";
16 import { flashTo, redirect } from "../layout.ts";
17 import { adminForm } from "../admin_form.ts";
16 import { flashOrJson, flashTo, fragment, redirect } from "../layout.ts";
17 import { seatFragment } from "../studio/crew.ts";
18 import { adminForm, loadAdminRepo } from "../admin_form.ts";
19 import { html } from "../html.ts";
1820 import { saveGrants } from "./subscriptions.ts";
1921 import { adminPage } from "../../http/page_may.ts";
2022
23 /** The seats a change touched, as the fragment URLs a form acting in place redraws. */
24 const redraw = (base: string, ...roles: (string | undefined)[]): { redraw: string[] } => ({
25 redraw: [...new Set(roles.filter((r): r is string => r !== undefined))].map((r) => `${base}/settings/crew/seat/${r}`),
26 });
27
28 // GET /:owner/:name/settings/crew/seat/:role: one seat, as the card draws it.
29 export function crewSeatFragment(ctx: Ctx): Response {
30 const repo = loadAdminRepo(ctx);
31 const row = repo && seatFragment(ctx, repo, ctx.params.role ?? "");
32 return row ? fragment(row, { request: ctx.request }) : fragment(html``, { status: 404 });
33 }
34
2135 // GET /:owner/:name/settings/crew
2236 export function crewSettingsPage(ctx: Ctx): Response {
2337 const repo = loadRepo(ctx);
@@ -46,15 +60,18 @@ export async function crewAdd(ctx: Ctx): Promise<Response> {
4660 // The team card's one button names the seat it fills.
4761 const role = field(form, "role");
4862 const asked = isCrewRole(role) ? role : undefined;
63 const named = getAgentByName(ctx.app.db, field(form, "agent"));
64 const before = named && crewRole(ctx.app.db, repo.id, named.user.id);
4965 const added = addToCrew(ctx.app, ctx.auth.user, repo, field(form, "agent"), asked);
5066 // An agent already on the crew picked for another list moves to it.
5167 if (added.ok && asked !== undefined) setCrewRole(ctx.app.db, repo.id, added.value.user.id, asked);
52 return flashTo(
68 return flashOrJson(
5369 ctx,
5470 `${repoBase(repo)}/settings#crew`,
5571 added.ok
5672 ? { message: crewAddedWords(added.value.user.username) }
5773 : { tone: "danger", message: crewRefusal(added.error) },
74 redraw(repoBase(repo), asked, before),
5875 );
5976 }
6077
@@ -64,13 +81,16 @@ export async function crewRemove(ctx: Ctx): Promise<Response> {
6481 if (gate instanceof Response) return gate;
6582 const { repo } = gate;
6683 const username = ctx.params.username ?? "";
84 const named = getAgentByName(ctx.app.db, username);
85 const before = named && crewRole(ctx.app.db, repo.id, named.user.id);
6786 const removed = removeFromCrew(ctx.app, ctx.auth.user, repo, username);
68 return flashTo(
87 return flashOrJson(
6988 ctx,
7089 `${repoBase(repo)}/settings#crew`,
7190 removed.ok
7291 ? { message: crewRemovedWords(username) }
7392 : { tone: "danger", message: crewRefusal(removed.error) },
93 redraw(repoBase(repo), before),
7494 );
7595 }
7696
@@ -101,16 +121,17 @@ export async function pillarUpdate(ctx: Ctx): Promise<Response> {
101121 const base = repoBase(repo);
102122 const checked = checkSeatSlots(field(form, "seat"), field(form, "slots"));
103123 if (checked === undefined)
104 return flashTo(ctx, `${base}/settings#team`, {
124 return flashOrJson(ctx, `${base}/settings#team`, {
105125 tone: "danger",
106126 message: "Use a whole number from 0 (paused) to 8; the planner 0 or 1.",
107127 });
108128 const done = await setSeatSlots(ctx.app, ctx.auth.user, repo, checked.role, checked.slots);
109 return flashTo(
129 return flashOrJson(
110130 ctx,
111131 `${base}/settings#team`,
112132 done.ok
113133 ? { message: seatSlotsSaid(checked.role, checked.slots) }
114134 : { tone: "danger", message: "That could not be saved." },
135 redraw(base, checked.role),
115136 );
116137 }
src/web/studio/crew.ts +87 −68
@@ -41,6 +41,7 @@ import { html, type Html } from "../html.ts";
4141 import { blockedWay } from "../blocked.ts";
4242 import { noAgentsBlocked } from "../../actions/blocked_words.ts";
4343 import { icon } from "../icons.ts";
44 import { inPlaceJs } from "../in_place.ts";
4445 import { crewReadiness } from "../pages/crew.ts";
4546 import { grantsSection } from "../pages/subscriptions.ts";
4647 import { seatSlotsOf, seatSlotsWords, SEAT_UNIT } from "../../crew/seat_slots.ts";
@@ -119,15 +120,11 @@ const SEAT_BADGE: Record<Seat["state"], { text: string; tone: Tone }> = {
119120 invite: { text: "open seat", tone: "default" },
120121 };
121122
122 /** The script: choosing in a team list, or setting its number, saves at once. */
123 export const teamJs = /* js */ `
124 (function () {
125 document.querySelectorAll("form[data-team] select, form[data-team] input[type=number]").forEach(function (el) {
126 el.addEventListener("change", function () { el.form.requestSubmit(); });
127 });
128 document.querySelectorAll("form[data-team] button[type=submit]").forEach(function (b) { b.hidden = true; });
129 })();
130 `;
123 /**
124 * The script: choosing in a team list, or setting its number, saves at once and redraws that seat
125 * only (`in_place.ts`).
126 */
127 export const teamJs = inPlaceJs;
131128
132129 /**
133130 * One crew member as one line: name, the seat it holds, its state. What the agent's own words say
@@ -162,7 +159,7 @@ export function memberRow(
162159 }),
163160 ...(admin
164161 ? {
165 after: html`<form class="row-actions" method="post" action="${base}/settings/crew/${encodeURIComponent(user)}/remove">
162 after: html`<form class="row-actions" method="post" action="${base}/settings/crew/${encodeURIComponent(user)}/remove" data-in-place>
166163 ${btn("Remove", { size: "sm", icon: "x" })}
167164 </form>`,
168165 }
@@ -179,6 +176,82 @@ const SEAT_TITLE: Record<CrewRole, string> = {
179176 designer: "Designers",
180177 };
181178
179 /** Where one seat's fragment is read: the same row the card draws, alone (`seatFragment`). */
180 const seatUrl = (base: string, role: string): string => `${base}/settings/crew/seat/${role}`;
181
182 /**
183 * Each seat's row, by role (what the card lists and what a redraw sends), with the facts it read.
184 */
185 function seatRows(ctx: Ctx, repo: Repo, base: string, admin: boolean, everyone: readonly Agent[]) {
186 const team = seatsOf(ctx.app.db, repo, crewOffInPreview());
187 const crew = listCrewRoles(ctx.app.db, repo.id);
188 const held = new Map(crew.map((c) => [c.agent.user.username, c.role]));
189 const byName = new Map(crew.map((c) => [c.agent.user.username, c.agent]));
190 const seatSlots = new Map(seatSlotsOf(ctx.app.db, repo).map((p) => [p.role, p]));
191 const rows = new Map<string, Html>();
192 for (const p of team.seats) {
193 const slots = seatSlots.get(p.role)!;
194 const paused = slots.slots === 0;
195 const b = SEAT_BADGE[p.state];
196 const picks = everyone.filter(
197 (a) => a.roles.includes(p.role) && held.get(a.user.username) !== p.role,
198 );
199 const add =
200 !admin || picks.length === 0
201 ? null
202 : html`<form class="row-fields" method="post" action="${base}/settings/crew" data-team data-in-place>
203 <input type="hidden" name="role" value="${p.role}" />
204 <label class="sr-only" for="f-add-${p.role}">Add to ${SEAT_TITLE[p.role]}</label>
205 <select class="input input-sm" id="f-add-${p.role}" name="agent">
206 <option value="" disabled selected>Add…</option>
207 ${picks.map((a) => html`<option value="${a.user.username}">${a.user.username}</option>`)}
208 </select>
209 ${btn("Add", { size: "sm" })}
210 </form>`;
211 const setter = !admin
212 ? null
213 : html`<form class="row-fields" method="post" action="${base}/settings/pillars" data-team data-in-place>
214 <input type="hidden" name="seat" value="${p.role}" />
215 <label class="sr-only" for="f-seat-${p.role}">${p.role}: ${SEAT_UNIT[p.role]}</label>
216 <input class="input input-sm" id="f-seat-${p.role}" name="slots" type="number" inputmode="numeric"
217 min="0" max="${String(slots.max)}" value="${String(slots.slots)}" />
218 ${btn("Set", { size: "sm" })}
219 </form>`;
220 const members = p.by.map((u) => {
221 const agent = byName.get(u);
222 return memberRow(u, agent, p.role, paused, base, admin);
223 });
224 rows.set(p.role, row({
225 lead: icon(SEAT_LEAD[p.state]),
226 title: SEAT_TITLE[p.role],
227 meta: html`${p.does}${p.state === "warn" ? ` No ${p.role}: ${p.without}.` : null}`,
228 trail: html`${paused ? badge("paused", { tone: "attn" }) : badge(b.text, { tone: b.tone })}${add}`,
229 data: { seat: p.role, state: p.state, fragment: seatUrl(base, p.role) },
230 children: [
231 ...members,
232 row({
233 title: paused ? "Paused" : `${String(slots.slots)} ${SEAT_UNIT[p.role]}`,
234 meta: html`${seatSlotsWords(slots)}`,
235 ...(setter ? { trail: setter } : {}),
236 data: { slots: p.role, at: String(slots.slots) },
237 }),
238 ],
239 }));
240 }
241 const maintainers = maintainerRow(base, admin, everyone, crew, held);
242 if (maintainers !== null) rows.set("maintainer", maintainers);
243 return { rows, team, crew };
244 }
245
246 /**
247 * One seat's row alone, for a form that acted in place (`GET …/settings/crew/seat/:role`);
248 * undefined for a name that is no seat.
249 */
250 export function seatFragment(ctx: Ctx, repo: Repo, role: string): Html | undefined {
251 const all = listAllAgents(ctx.app, ctx.auth.user);
252 return seatRows(ctx, repo, repoBase(repo), true, all.ok ? all.value : []).rows.get(role);
253 }
254
182255 /**
183256 * Your team, as three lists: Planners, Builders, Reviewers (`seatsOf`, the
184257 * same facts the MCP `crew` tool returns). Each list holds who fills it, a
@@ -193,62 +266,8 @@ function teamCard(
193266 admin: boolean,
194267 everyone: readonly Agent[],
195268 ): Html {
196 const team = seatsOf(ctx.app.db, repo, crewOffInPreview());
197 const crew = listCrewRoles(ctx.app.db, repo.id);
198 const held = new Map(crew.map((c) => [c.agent.user.username, c.role]));
199 const byName = new Map(crew.map((c) => [c.agent.user.username, c.agent]));
200 const seatSlots = new Map(seatSlotsOf(ctx.app.db, repo).map((p) => [p.role, p]));
201 const rows = team.seats.map((p) => {
202 const slots = seatSlots.get(p.role)!;
203 const paused = slots.slots === 0;
204 const b = SEAT_BADGE[p.state];
205 const picks = everyone.filter(
206 (a) => a.roles.includes(p.role) && held.get(a.user.username) !== p.role,
207 );
208 const add =
209 !admin || picks.length === 0
210 ? null
211 : html`<form class="row-fields" method="post" action="${base}/settings/crew" data-team>
212 <input type="hidden" name="role" value="${p.role}" />
213 <label class="sr-only" for="f-add-${p.role}">Add to ${SEAT_TITLE[p.role]}</label>
214 <select class="input input-sm" id="f-add-${p.role}" name="agent">
215 <option value="" disabled selected>Add…</option>
216 ${picks.map((a) => html`<option value="${a.user.username}">${a.user.username}</option>`)}
217 </select>
218 ${btn("Add", { size: "sm" })}
219 </form>`;
220 const setter = !admin
221 ? null
222 : html`<form class="row-fields" method="post" action="${base}/settings/pillars" data-team>
223 <input type="hidden" name="seat" value="${p.role}" />
224 <label class="sr-only" for="f-seat-${p.role}">${p.role}: ${SEAT_UNIT[p.role]}</label>
225 <input class="input input-sm" id="f-seat-${p.role}" name="slots" type="number" inputmode="numeric"
226 min="0" max="${String(slots.max)}" value="${String(slots.slots)}" />
227 ${btn("Set", { size: "sm" })}
228 </form>`;
229 const members = p.by.map((u) => {
230 const agent = byName.get(u);
231 return memberRow(u, agent, p.role, paused, base, admin);
232 });
233 return row({
234 lead: icon(SEAT_LEAD[p.state]),
235 title: SEAT_TITLE[p.role],
236 meta: html`${p.does}${p.state === "warn" ? ` No ${p.role}: ${p.without}.` : null}`,
237 trail: html`${paused ? badge("paused", { tone: "attn" }) : badge(b.text, { tone: b.tone })}${add}`,
238 data: { seat: p.role, state: p.state },
239 children: [
240 ...members,
241 row({
242 title: paused ? "Paused" : `${String(slots.slots)} ${SEAT_UNIT[p.role]}`,
243 meta: html`${seatSlotsWords(slots)}`,
244 ...(setter ? { trail: setter } : {}),
245 data: { slots: p.role, at: String(slots.slots) },
246 }),
247 ],
248 });
249 });
250 const maintainers = maintainerRow(base, admin, everyone, crew, held);
251 if (maintainers !== null) rows.push(maintainers);
269 const { rows: byRole, team, crew } = seatRows(ctx, repo, base, admin, everyone);
270 const rows = [...byRole.values()];
252271 const intro = crewOffInPreview()
253272 ? "The crew is off in a preview."
254273 : team.auto
@@ -302,7 +321,7 @@ function maintainerRow(
302321 const add =
303322 !admin || picks.length === 0
304323 ? null
305 : html`<form class="row-fields" method="post" action="${base}/settings/crew" data-team>
324 : html`<form class="row-fields" method="post" action="${base}/settings/crew" data-team data-in-place>
306325 <input type="hidden" name="role" value="maintainer" />
307326 <label class="sr-only" for="f-add-maintainer">Add to ${SEAT_TITLE.maintainer}</label>
308327 <select class="input input-sm" id="f-add-maintainer" name="agent">
@@ -322,7 +341,7 @@ function maintainerRow(
322341 title: SEAT_TITLE.maintainer,
323342 meta: html`Keeps the code easy to change.`,
324343 trail: html`${add}`,
325 data: { seat: "maintainer" },
344 data: { seat: "maintainer", fragment: seatUrl(base, "maintainer") },
326345 children: members,
327346 });
328347 }
test/crew-in-place.test.ts added +124
@@ -0,0 +1,124 @@
1 /**
2 * The crew card acts in place: a form that asks for JSON gets `{ok, flash, redraw}`
3 * or a 422 with the words; the redraw URL answers one seat and nothing else; without
4 * script the same POST still redirects back to `#crew`.
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 { gzipSync } from "node:zlib";
11 import { createApp, type App } from "../src/app.ts";
12 import { createAgent } from "../src/actions/crew.ts";
13 import { createRepo } from "../src/actions/repos.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { IN_PLACE_BUDGET, inPlaceJs } from "../src/web/in_place.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18
19 quietLogs();
20 const PASSWORD = "a-long-crew-passphrase";
21
22 describe("crew card in place", () => {
23 let dir = "";
24 let app: App;
25 let servers: Servers;
26 let admin = "";
27 let bob = "";
28 const base = () => `${servers.url}/alice/yard/settings`;
29 const signIn = async (username: string): Promise<string> =>
30 ((await fetch(`${servers.url}/signin`, { method: "POST", body: new URLSearchParams({ username, password: PASSWORD }), redirect: "manual" })).headers.get("set-cookie") ?? "").split(";")[0]!;
31 const post = (path: string, body: Record<string, string>, o: { json?: boolean; cookie?: string; origin?: string } = {}) =>
32 fetch(`${base()}${path}`, {
33 method: "POST",
34 headers: { origin: o.origin ?? servers.url, cookie: o.cookie ?? admin, ...(o.json === false ? {} : { accept: "application/json" }) },
35 body: new URLSearchParams(body),
36 redirect: "manual",
37 });
38
39 beforeAll(async () => {
40 dir = await mkdtemp(join(tmpdir(), "forge-crew-in-place-"));
41 app = createApp({ dataDir: dir, port: 0 });
42 servers = await serve(app);
43 const a = await createUser(app.db, { origin: "seed", username: "alice", email: "[email protected]", password: PASSWORD, adminIfFirst: true, trusted: true });
44 const b = await createUser(app.db, { origin: "seed", username: "bob", email: "[email protected]", password: PASSWORD, trusted: true });
45 if (!a.ok || !b.ok) throw new Error("users");
46 const made = await createRepo(app, a.value, { name: "yard", visibility: "public" });
47 if (!made.ok) throw new Error(String(made.error));
48 for (const [username, roles] of [["both", ["builder", "reviewer"]], ["onlyplan", ["planner"]]] as const) {
49 const bot = await createAgent(app, a.value, { username, roles });
50 if (!bot.ok) throw new Error("agent");
51 }
52 admin = await signIn("alice");
53 bob = await signIn("bob");
54 }, 30_000);
55 afterAll(async () => {
56 await servers.stop();
57 await rm(dir, { recursive: true, force: true });
58 });
59
60 test("an add answers JSON naming the one seat to redraw, and the fragment is that seat alone", async () => {
61 const res = await post("/crew", { agent: "both", role: "builder" });
62 expect(res.status).toBe(200);
63 const j = (await res.json()) as { ok: boolean; redraw: string[] };
64 expect(j.ok).toBe(true);
65 expect(j.redraw).toEqual(["/alice/yard/settings/crew/seat/builder"]);
66 const frag = await fetch(`${servers.url}${j.redraw[0]}`, { headers: { cookie: admin, accept: "text/html" } });
67 expect(frag.status).toBe(200);
68 expect(frag.headers.get("content-type")).toContain("text/html");
69 const text = await frag.text();
70 expect(text).toContain('data-seat="builder"');
71 expect(text).toContain('data-member="both"');
72 expect(text).not.toContain("<html");
73 expect(text).not.toContain('data-seat="planner"');
74 expect(text).not.toContain('data-seat="reviewer"');
75 });
76
77 test("moving a member names both seats", async () => {
78 const j = (await (await post("/crew", { agent: "both", role: "reviewer" })).json()) as { redraw: string[] };
79 expect(j.redraw.map((u) => u.split("/").pop()).sort()).toEqual(["builder", "reviewer"]);
80 });
81
82 test("a refusal is a 422 with its words, and nothing moves", async () => {
83 const res = await post("/crew", { agent: "onlyplan", role: "builder" });
84 expect(res.status).toBe(422);
85 const j = (await res.json()) as { ok: boolean; error: string };
86 expect(j.ok).toBe(false);
87 expect(j.error.length).toBeGreaterThan(5);
88 const bad = await post("/pillars", { seat: "builder", slots: "99" });
89 expect(bad.status).toBe(422);
90 expect(((await bad.json()) as { error: string }).error).toContain("whole number");
91 });
92
93 test("a slot count and a removal redraw their seat", async () => {
94 const set = (await (await post("/pillars", { seat: "builder", slots: "2" })).json()) as { ok: boolean; redraw: string[] };
95 expect(set.redraw.map((u) => u.split("/").pop())).toEqual(["builder"]);
96 const gone = (await (await post("/crew/both/remove", {})).json()) as { ok: boolean; redraw: string[] };
97 expect(gone.redraw.map((u) => u.split("/").pop())).toEqual(["reviewer"]);
98 });
99
100 test("without script the POST still redirects to the crew card", async () => {
101 const res = await post("/crew", { agent: "both", role: "builder" }, { json: false });
102 expect(res.status).toBe(303);
103 expect(res.headers.get("location")).toContain("/settings#crew");
104 });
105
106 test("a cross-origin POST is refused, and the fragment is the admin's alone", async () => {
107 const cross = await post("/crew", { agent: "onlyplan", role: "planner" }, { origin: "https://evil.example" });
108 expect(cross.status).not.toBe(200);
109 expect(cross.status).not.toBe(303);
110 for (const cookie of [bob, ""]) {
111 const r = await fetch(`${base()}/crew/seat/builder`, { headers: { cookie } });
112 expect(r.status).toBe(404);
113 }
114 const nope = await fetch(`${base()}/crew/seat/janitor`, { headers: { cookie: admin } });
115 expect(nope.status).toBe(404);
116 });
117
118 test("the page marks its forms and seats, and the script stays inside its budget", async () => {
119 const page = await (await fetch(`${base()}`, { headers: { cookie: admin } })).text();
120 expect(page).toContain("data-in-place");
121 expect(page).toContain('data-fragment="/alice/yard/settings/crew/seat/builder"');
122 expect(gzipSync(inPlaceJs).length).toBeLessThanOrEqual(IN_PLACE_BUDGET);
123 });
124 });
test/no-polling.test.ts +1
@@ -303,6 +303,7 @@ export function findPolling(source: string): string[] {
303303 */
304304 const ORIGIN = "needs a connected origin account; the seed connects none";
305305 const NOT_WALKED: Record<string, string> = {
306 "/:owner/:name/settings/crew/seat/:role": "one seat of the crew card as an HTML fragment, not a page; :role is a seat the seed does not name",
306307 "/talk/dev/:token": "a frame proxied from a running dev cell, not a page; the seed starts none",
307308 "/talk/dev/:token/*path": "a file proxied from a running dev cell, not a page; the seed starts none",
308309 "/infra/end/:act/*path": "the plan of a stop or delete, a page for a cloud resource the seed does not have; the action word is not in the seed",
test/open-routes-floor.test.ts +1 −1
@@ -42,7 +42,7 @@ const FILL: Readonly<Record<string, string>> = {
4242 // Not seeded: each still has to answer its not-found with the floor.
4343 team: "core", env: "prod", file: "README.md", label: "v1", chapter: "1", kind: "desktop", machine: "web",
4444 range: `${"0".repeat(40)}...${"1".repeat(40)}`, op: "x", step: "1", group: "a", version: "1", slug: "board", receipt: "r", token: "t", code: "c", spec: "16", stage: "build", walk: "1", flag: "x", room: "lobby", box: "net", service: "hub", hash: "0".repeat(16), uuid: "069a79f4-44e9-4726-a5be-fca90e38aaf5",
45 secret: "s".repeat(32), key: "k",
45 secret: "s".repeat(32), key: "k", role: "builder",
4646 };
4747
4848 /** Open GET routes that cannot be filled in from a seeded public repository, each with why. */
test/pages-budget.test.ts +1
@@ -72,6 +72,7 @@ const NOT_PAGES = new Set([
7272 "/events", "/system/stream", "/settings/teams/stream", "/fleet/graph/live",
7373 "/settings/traffic/scrapes/export", "/settings/backups/live", "/:owner/:name/stream",
7474 "/settings/origins/flows/:id/stream", "/boards/:slug/stream", "/boards/stream", "/:owner/:name/archive/:file", // a tarball download, not a page
75 "/:owner/:name/settings/crew/seat/:role", // one seat of the crew card (#18459), a fragment, not a page
7576 "/api/v1/runner/jobs/:id/git/info/refs", // a runner's git door for one job (#13652), not a page
7677 ]);
7778
test/security-floor-routes.test.ts +1
@@ -129,6 +129,7 @@ const UNSEEDED: Record<string, string> = {
129129 "/:owner/:name/milestones/:number/limb/:op": LIMB,
130130 "/:owner/:name/pulls/:number/review/:step": "needs a pull with a review script, which the seed does not write (test/review-steps.test.ts covers it)",
131131 "/:owner/:name/settings/app/flags/:flag": "needs an app whose flags.json declares a flag; the seed has none",
132 "/:owner/:name/settings/crew/seat/:role": "a crew seat fragment named by a role the seed does not pass; it is a fragment, not a page (test/crew-in-place.test.ts covers it)",
132133 "/:owner/:name/variants/:group": VARIANT,
133134 "/:owner/:name/waves/:version": WAVE,
134135 "/api/v1/boards/:slug/panels/:id": BOARD,

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs