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

An app whose crew is empty says so on its page and offers one tap that seats one #15867

Merged opened this

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

Merged

scout/forge:scout/15831-an-app-whose-crew-is-empty-says-so-on-it → main 0 commits fork 6 threads · 6 unresolved

  • Merged. scout/15831-an-app-whose-crew-is-empty-says-so-on-it was merged into main as 9ab14d4.

Review

Sign in to review this change.
16 files changed +386 −21
docs/features/app-empty-crew.md added +18
@@ -0,0 +1,18 @@
1 ---
2 topic: Tell the crew
3 row: An app with no crew says so and seats one in one tap
4 ---
5 # An app with no crew says so and seats one in one tap
6
7 An app with no builder seated (made before the new-app seating, or by an outside agent) shows a
8 writer "No crew yet" and one "Seat a crew" button on its page. It does what "Choose for me" does for
9 a new app: a builder and a reviewer are seated from the forge's own agents (made as the starter
10 agents when none exist) and autonomy is turned on as the person who tapped. A reader sees nothing;
11 a seated crew shows no line. A forge with no model key and no credit seats no one and says so.
12
13 - Page: `POST /:owner/:name/crew/seat` (`seatCrewSubmit`).
14 - MCP: the `crew` tool for such an app answers `says: "No crew yet"` and `action`; `{ kind: "seat",
15 repo, dryRun? }` plans first, applies with `dryRun: false` and an admin token.
16 - Terminal: `s` on the crew screen (`src/tui/screens/crew.ts`).
17
18 Code: `seatEmptyCrew` in `src/actions/seat_crew.ts`. Test: `test/app-empty-crew.test.ts`.
src/actions/seat_crew.ts added +51
@@ -0,0 +1,51 @@
1 /**
2 * An app with nobody on its crew says so in one line and offers one tap that
3 * seats one: the same seating "Choose for me" does for a new app
4 * (`seatCrew`). The page, the `crew` MCP tool (`kind: "seat"`) and nothing
5 * else call it, so both doors say the same words.
6 */
7
8 import type { App } from "../app.ts";
9 import { listCrewRoles } from "../core/agents.ts";
10 import { canWrite, type Repo } from "../core/repos.ts";
11 import type { User } from "../core/users.ts";
12 import { seatCrew } from "../spawn/starter_crew.ts";
13 import { NO_CREDIT_WORDS, crewCanRun } from "./crew_means.ts";
14
15 export const NO_CREW_WORDS = "No crew yet";
16 export const SEAT_CREW_WORDS = "Seat a crew";
17
18 /** Whether no builder is seated on this repository. */
19 export const crewIsEmpty = (app: App, repo: Repo): boolean =>
20 !listCrewRoles(app.db, repo.id).some((c) => c.role === "builder");
21
22 /** The line for an empty crew, or null when a builder is seated or the viewer cannot seat one. */
23 export function emptyCrewLine(app: App, user: User | undefined, repo: Repo): string | null {
24 return user !== undefined && canWrite(app.db, repo, user) && crewIsEmpty(app, repo) ? NO_CREW_WORDS : null;
25 }
26
27 export type Seated = { ok: true; says: string } | { ok: false; error: "forbidden" | "already" | "cannot"; says: string };
28
29 /** Repositories being seated now, so a second tap does not seat and announce twice. */
30 const seatingOf = new WeakMap<App, Set<string>>();
31
32 /** Seat the crew as "Choose for me" does, for a writer, when no builder is seated. */
33 export async function seatEmptyCrew(app: App, user: User | undefined, repo: Repo): Promise<Seated> {
outdated

Security: this does not refuse user.kind === "agent". The MCP tool and the terminal both refuse agents, but seatCrewSubmit goes straight here, so an agent session with write access and an rw token can seat a crew and turn autonomy on. Put user.kind === "agent" into the forbidden check here so all three doors share it, and add a test for the page door.

34 if (user === undefined || user.kind === "agent" || !canWrite(app.db, repo, user)) return { ok: false, error: "forbidden", says: "Seating a crew needs a person with write access here." };
35 if (!crewIsEmpty(app, repo) || seatingOf.get(app)?.has(repo.id)) return { ok: false, error: "already", says: "A builder is already seated." };
36 if (!crewCanRun(app)) return { ok: false, error: "cannot", says: NO_CREDIT_WORDS };
outdated

Race: crewIsEmpty is checked, then await seatCrew runs, so two taps at once (a double-tap, or page plus terminal) can both pass the check and emit crew.added twice. Re-check emptiness after the await, or make the seating idempotent, and only append events for seats that were new.

37 // One seating at a time per repository: a double tap, or the page and the terminal at once,
38 // seats once and announces once.
39 const seating = seatingOf.get(app) ?? new Set<string>();
40 seatingOf.set(app, seating);
41 seating.add(repo.id);
42 try {
43 const builder = await seatCrew(app.db, repo, user.id);
44 if (builder === undefined) return { ok: false, error: "cannot", says: "No builder and reviewer could be seated." };
45 for (const c of listCrewRoles(app.db, repo.id))
46 app.bus.append({ kind: "crew.added", repoId: repo.id, actorId: user.id, payload: { agent: c.agent.user.username } });
47 return { ok: true, says: `${builder.user.username} builds and a reviewer reads; the crew is seated.` };
48 } finally {
49 seating.delete(repo.id);
50 }
51 }
src/actions/tell.ts +1 −1
@@ -167,7 +167,7 @@ export const UNVERIFIED_WORDS = VERIFY_FIRST;
167167 /** What happened, in the sentence both doors say. */
168168 export function toldWords(told: Told): string {
169169 if (told.routed === undefined)
170 return `Opened as issue #${told.issue.number}. Nobody is on the crew to take it yet — add someone under Settings → Crew.`;
170 return `Opened as issue #${told.issue.number}. No crew yet — Seat a crew on the app page.`;
171171 const r = told.routed;
172172 const who = r.builder.user.username;
173173 return told.assigned
src/http/mcp/tools/crew.ts +17 −2
@@ -13,11 +13,12 @@ import { checkSeatSlots, seatSlotsOf } from "../../../crew/seat_slots.ts";
1313 import { seatsOf } from "../../../crew/seats.ts";
1414 import { weekCard, WEEK_DAYS } from "../../../crew/week_card.ts";
1515 import { ADMIN_WORDS } from "../../../actions/admin_words.ts";
16 import { emptyCrewLine, seatEmptyCrew, SEAT_CREW_WORDS } from "../../../actions/seat_crew.ts";
1617 import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
1718
1819 export const tool: Tool = {
1920 name: "crew",
20 doc: "`{ kind: \"week\" }` (forge admin): `{ days, members[{ username, merged, returned, spentUsd, idle }] }`, the last 7 days per agent; otherwise `{ repo, add?, remove?, dryRun? }`: without `add` or `remove`, the repository's crew as Settings › Crew reads it (`username`, `displayName`, `role`, and `config` for those who may see it) and `seats { auto, mode, seats[{ role, by, does, without?, state }] }`, the three seats and which are empty, `slots[{ role, slots, max, running, waiting, spentUsd, sharePct }]`, how much each may do at once now and today's spend (0 is paused, still on the crew; a reader who cannot write here gets no `auto`, `mode`, `state`, `running`, `waiting`, `spentUsd` or `sharePct`), and `governor { slots, ceiling, held, why, says }`, the builders the governor allows now and why (`null` while the crew is off or for a reader who cannot write here); `seat` (planner, builder or reviewer) with `slots` (0 to 8, the planner 0 or 1) sets how much that seat may do at once, 0 pausing it, on the trail at once; `add` or `remove` (an agent's username) says what would change, planned first (`dryRun` is true unless `false`); applying is the repository's admin with an admin token, never an agent; refusals are `no_such_agent`, `not_an_agent`, `unverified`",
21 doc: "`{ kind: \"seat\", repo, dryRun? }` (a writer, an app with no builder): the same \"Seat a crew\" as \"Choose for me\"; the plain answer for such an app says \"No crew yet\" and names it as `action`; `{ kind: \"week\" }` (forge admin): `{ days, members[{ username, merged, returned, spentUsd, idle }] }`, the last 7 days per agent; otherwise `{ repo, add?, remove?, dryRun? }`: without `add` or `remove`, the repository's crew as Settings › Crew reads it (`username`, `displayName`, `role`, and `config` for those who may see it) and `seats { auto, mode, seats[{ role, by, does, without?, state }] }`, the three seats and which are empty, `slots[{ role, slots, max, running, waiting, spentUsd, sharePct }]`, how much each may do at once now and today's spend (0 is paused, still on the crew; a reader who cannot write here gets no `auto`, `mode`, `state`, `running`, `waiting`, `spentUsd` or `sharePct`), and `governor { slots, ceiling, held, why, says }`, the builders the governor allows now and why (`null` while the crew is off or for a reader who cannot write here); `seat` (planner, builder or reviewer) with `slots` (0 to 8, the planner 0 or 1) sets how much that seat may do at once, 0 pausing it, on the trail at once; `add` or `remove` (an agent's username) says what would change, planned first (`dryRun` is true unless `false`); applying is the repository's admin with an admin token, never an agent; refusals are `no_such_agent`, `not_an_agent`, `unverified`",
2122 description: "List a repository's crew, or add or remove an agent. Plans first; admin token.",
2223 inputSchema: {
2324 type: "object",
@@ -34,8 +35,20 @@ export const tool: Tool = {
3435 writes: true,
3536 dryByDefault: true,
3637 async run(ctx, user, args) {
38 if (args["kind"] === "seat") {
39 const repo = repoArg(ctx, user, args);
40 if (isAnswer(repo)) return repo;
41 if (args["dryRun"] !== undefined && typeof args["dryRun"] !== "boolean") return bad("invalid", "`dryRun` is true or false");
42 if (user.kind === "agent") return bad("forbidden", "changing the crew is a person's call, not an agent's");
43 const line = emptyCrewLine(ctx.app, user, repo);
44 if (line === null) return bad("forbidden", "seating needs write access and an app with no builder");
45 if (args["dryRun"] !== false) return good({ changes: true, says: `This is the plan; nothing changed. ${line}: ${SEAT_CREW_WORDS} seats a builder and a reviewer. Send dryRun: false to apply.` });
46 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin")) return bad("forbidden", "changing the crew needs an admin token");
47 const done = await seatEmptyCrew(ctx.app, user, repo);
48 return done.ok ? good({ changed: true, says: done.says }) : bad("invalid", done.says);
49 }
3750 if (args["kind"] !== undefined) {
38 if (args["kind"] !== "week") return bad("invalid", "`kind` is `week`");
51 if (args["kind"] !== "week") return bad("invalid", "`kind` is `week` or `seat`");
3952 if (user.isAdmin !== true) return bad("forbidden", ADMIN_WORDS.scorecard);
4053 return good({ days: WEEK_DAYS, members: weekCard(ctx.app.db) });
4154 }
@@ -70,8 +83,10 @@ export const tool: Tool = {
7083 const owner = canSeeOwnerFacts(app.db, repo, user);
7184 const seats = seatsOf(app.db, repo, crewOffInPreview());
7285 const slots = seatSlotsOf(app.db, repo);
86 const empty = emptyCrewLine(app, user, repo);
7387 return {
7488 ...good({
89 ...(empty === null ? {} : { says: empty, action: { kind: "seat", label: SEAT_CREW_WORDS } }),
7590 crew: seen.value,
7691 governor: governorSeen(app, user, repo, new Date()) ?? null,
7792 seats: owner ? seats : { seats: seats.seats.map(({ state: _, ...p }) => p) },
src/http/server.ts +2
@@ -309,6 +309,7 @@ import {
309309 releaseSubmit,
310310 composerSubmit,
311311 tellSubmit,
312 seatCrewSubmit,
312313 tellUndoSubmit,
313314 } from "../web/studio/actions.ts";
314315 import { shareTellPage } from "../web/studio/share_tell.ts";
@@ -1455,6 +1456,7 @@ export function buildRouter(): Router<Handler> {
14551456 router.add("GET", "/:owner/:name/tell", tellHerePage);
14561457 router.add("POST", "/:owner/:name/tell", tellSubmit);
14571458 router.add("POST", "/:owner/:name/tell/undo", tellUndoSubmit);
1459 router.add("POST", "/:owner/:name/crew/seat", seatCrewSubmit);
14581460 // The home's composer without a script: a tell to the app it names (#599).
14591461 router.add("POST", "/tell", composerSubmit);
14601462 // Where the phone share sheet lands: the shared words in a form, filed only on Send.
src/tui/screens/crew.ts +13 −3
@@ -13,7 +13,8 @@
1313
1414 import { addToCrew, crewAsSeen, removeFromCrew, type CrewMember } from "../../actions/crew.ts";
1515 import { crewAddedWords, crewRefusal, crewRemovedWords } from "../../actions/crew_words.ts";
16 import { canAdmin, type Repo } from "../../core/repos.ts";
16 import { NO_CREW_WORDS, SEAT_CREW_WORDS, crewIsEmpty, seatEmptyCrew } from "../../actions/seat_crew.ts";
17 import { canAdmin, canWrite, type Repo } from "../../core/repos.ts";
1718 import type { Ctx, Screen } from "../app/app.ts";
1819 import { binding } from "../app/keys.ts";
1920 import { style } from "../term/style.ts";
@@ -38,6 +39,9 @@ export function crewScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
3839 // Settings › Crew's gate: an admin of the repository, and a person.
3940 const mayChange = (): boolean =>
4041 f.user !== undefined && f.user.kind !== "agent" && canAdmin(f.db, repo, f.user);
42 // An app with no builder offers `s`, the same one tap the app page does.
43 const maySeat = (): boolean =>
44 f.user !== undefined && f.user.kind !== "agent" && canWrite(f.db, repo, f.user) && crewIsEmpty(f.app, repo);
4145 const reload = (): void => {
4246 const read = crewAsSeen(f.app, f.user, repo);
4347 crew = read.ok ? read.value : [];
@@ -102,6 +106,7 @@ export function crewScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
102106 get keys() {
103107 return [
104108 binding(["j", "k"], "move"),
109 ...(maySeat() ? [binding(["s"], SEAT_CREW_WORDS.toLowerCase())] : []),
105110 ...(mayChange()
106111 ? [binding(["a"], "put an agent on"), binding(["d"], "take it off", { disabled: crew.length === 0 })]
107112 : []),
@@ -114,7 +119,7 @@ export function crewScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
114119 note !== ""
115120 ? note
116121 : crew.length === 0
117 ? `Nobody is on the crew of ${where}.${mayChange() ? " Press a to put an agent on." : ""}`
122 ? `${NO_CREW_WORDS} on ${where}.${maySeat() ? " Press s to seat a crew." : ""}${mayChange() ? " Press a to put an agent on." : ""}`
118123 : `${plural(crew.length, "agent")} on the crew of ${where}; Settings › Crew sets their roles.`;
119124 const said = wrap(text, Math.max(1, area.w)).slice(0, 3);
120125 const [head, list] = split(area, "v", [len(said.length), fill(1)]);
@@ -130,7 +135,12 @@ export function crewScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
130135 },
131136 key(e) {
132137 if (state.key(e, crew.length)) return true;
133 if (e.ctrl || e.alt || !mayChange()) return false;
138 if (e.ctrl || e.alt) return false;
139 if (e.key === "s" && maySeat()) {
140 void seatEmptyCrew(f.app, f.user, repo).then((done) => say(done.says), () => say("Could not seat a crew."));
outdated

The s key has no test, though docs and the pull claim the terminal door works. Add a test in the crew-screen suite that s seats for a writer, is absent for a reader and an agent, and that the result reaches the web live. The void ... .then also has no catch; a rejection becomes an unhandled promise.

141 return true;
142 }
143 if (!mayChange()) return false;
134144 if (e.key === "a") {
135145 ctx.push(add());
136146 return true;
src/web/studio/actions.ts +12 −1
@@ -16,6 +16,7 @@ import { shipsPastReviews } from "./land_as_is.ts";
1616 import { holdPull, releasePull } from "../../actions/holds.ts";
1717 import { addComment } from "../../actions/issues.ts";
1818 import { overTellLimit, parseFrom, tellTooLongWords } from "../../actions/tell_from.ts";
19 import { seatEmptyCrew } from "../../actions/seat_crew.ts";
1920 import { SENT_WORDS, tell, toldWords } from "../../actions/tell.ts";
2021 import { TAKEN_BACK_WORDS, tellUndoable, undoRefusalWords, undoTell } from "../../actions/tell_undo.ts";
2122 import { contextNote, whereTold } from "../../actions/tell_context.ts";
@@ -120,7 +121,7 @@ function toldAnswer(
120121 */
121122 export function tellFlashWords(routed: Routed | undefined, from: string | null, subject: string): string {
122123 if (routed === undefined)
123 return prefixed("Opened as an issue. Nobody is on the crew to take it yet — add someone under Settings → Crew.", subject);
124 return prefixed("Opened as an issue. No crew yet — Seat a crew on the app page.", subject);
124125 const decided = routed.by === "rule" ? "" : `, ${routed.by} decided in ${routed.ms} ms`;
125126 const watch = from === null ? " Watch it work below." : "";
126127 return prefixed(`${routed.builder.user.username} is on it — ${routed.size} ${routed.kind}${decided}.${watch}`, subject);
@@ -510,3 +511,13 @@ export async function releaseSubmit(ctx: Ctx): Promise<Response> {
510511 });
511512 }
512513

Two blank lines before this function; the file's pattern is one. Tidy it.

514 /** "Seat a crew": what "Choose for me" does, for an app with no builder; a writer's tap. */
515 export async function seatCrewSubmit(ctx: Ctx): Promise<Response> {
516 const repo = loadRepo(ctx);
517 if (!repo) return notFoundPage(ctx);
518 if (!ctx.auth.user) return signInFirst(ctx);
519 const form = await readForm(ctx, "rw");
520 if (form instanceof Response) return form;
521 const done = await seatEmptyCrew(ctx.app, ctx.auth.user, repo);
522 return flashOrJson(ctx, repoBase(repo), { ...(done.ok ? {} : { tone: "danger" as const }), message: done.says });
523 }
src/web/studio/app.ts +5 −5
@@ -9,6 +9,7 @@
99 * for a viewer who can write here; a stranger sees the app.
1010 */
1111
12 import { NO_CREW_WORDS, SEAT_CREW_WORDS } from "../../actions/seat_crew.ts";
1213 import { frontPulls } from "./front_pulls.ts";
1314 import { pausedSentence } from "../../crew/paused_now.ts";
1415 import { appCardPath } from "../og/path.ts";
@@ -345,11 +346,10 @@ export async function studioApp(
345346 <span class="muted small">${TELL_LIMIT_WORDS}</span>
346347 </form>
347348 ${builders.length === 0
348 ? html`<p class="muted small">
349 Nobody on the crew yet.
350 <a href="${base}/settings#crew">Add a crew member under Settings → Crew</a>,
351 then tell them what you want.
352 </p>`
349 ? html`<form method="post" action="${base}/crew/seat" class="row">
outdated

Design principle 5 (one accent): a primary button here sits on the same page as the primary "Tell" button. Make "Seat a crew" a plain/secondary button. Principle 1: "or pick your own" explains the same choice a second time; drop it, since Settings › Crew is already reachable from the page. Also the bar form is hand-rolled markup; use the named component from docs/DESIGN.md.

350 <span class="muted small">${NO_CREW_WORDS}</span>
351 ${btn(SEAT_CREW_WORDS, { variant: "secondary", type: "submit", size: "sm" })}
352 </form>`
353353 : null}`;
354354
355355 // ---- now: one row per thing, in the five words (studio/now.ts) ----
test/app-empty-crew-tui.test.ts added +91
@@ -0,0 +1,91 @@
1 /**
2 * `s` on the crew screen seats a crew for a writer with no builder seated; a reader gets no key
3 * (#15831).
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createAgent } from "../src/actions/crew.ts";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { listCrewRoles } from "../src/core/agents.ts";
13 import type { Repo } from "../src/core/repos.ts";
14 import { createUser, type User } from "../src/core/users.ts";
15 import { createForgeApp } from "../src/tui/forge.ts";
16 import { crewScreen } from "../src/tui/screens/crew.ts";
17 import { headlessTerminal } from "../src/tui/term/terminal.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19 import { settleApp } from "./helpers/tui.ts";
20
21 quietLogs();
22
23 let dir = "";
24 let app: App;
25 let alice: User;
26 let bob: User;
27 let robo: User;
28 let repo: Repo;
29 const KEY = process.env["ANTHROPIC_API_KEY"];
30
31 beforeAll(async () => {
32 process.env["ANTHROPIC_API_KEY"] = "test-key";
33 dir = await mkdtemp(join(tmpdir(), "forge-empty-crew-tui-"));
34 app = createApp({ dataDir: dir, port: 0 });
35 const made: User[] = [];
36 for (const username of ["alice", "bob"]) {
37 const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", ...(username === "alice" ? { adminIfFirst: true } : {}) });
38 if (!u.ok) throw new Error(u.error);
39 made.push(u.value);
40 }
41 [alice, bob] = made as [User, User];
42 const r = await createRepo(app, alice, { name: "lamp", visibility: "public" });
43 if (!r.ok) throw new Error(String(r.error));
44 repo = r.value;
45 const a = await createAgent(app, alice, { username: "robo" });
46 if (!a.ok) throw new Error(String(a.error));
47 robo = a.value.user;
48 });
49 afterAll(async () => {
50 if (KEY === undefined) delete process.env["ANTHROPIC_API_KEY"];
51 else process.env["ANTHROPIC_API_KEY"] = KEY;
52 app.db.close();
53 await rm(dir, { recursive: true, force: true });
54 });
55
56 async function open(who: User, keys: string[]): Promise<string> {
57 const { app: tui, session } = createForgeApp(
58 app,
59 { sshUsername: who.username, remoteAddress: "127.0.0.1", user: who },
60 { terminal: headlessTerminal(140, 40), exitHooks: false },
61 );
62 tui.start();
63 await settleApp(tui);
64 tui.push(crewScreen(session, tui.ctx, repo));
65 await settleApp(tui);
66 for (const key of keys) {
67 tui.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
68 await settleApp(tui);
69 }
70 const text = tui.screen.toText();
71 tui.stop();
72 return text;
73 }
74
75 test("a reader and an agent are offered no `s`, and pressing it seats no one", async () => {
76 for (const who of [bob, robo]) {
77 const text = await open(who, ["s"]);
78 expect(text).not.toContain("Press s to seat a crew");
79 expect(text).not.toMatch(/\bs\b[^\n]*seat a crew/);
80 expect(listCrewRoles(app.db, repo.id)).toEqual([]);
81 }
82 });
83
84 test("`s` seats a crew for a writer, in the web's words, and the page line is gone", async () => {
85 expect(await open(alice, [])).toContain("Press s to seat a crew");
86 const text = await open(alice, ["s"]);
87 expect(text).toContain("the crew is seated");
88 expect(listCrewRoles(app.db, repo.id).map((c) => c.role).sort()).toEqual(["builder", "reviewer"]);
89 const events = app.db.query("select count(*) as n from event where kind = 'crew.added' and repo_id = ?").get(repo.id) as { n: number };
90 expect(events.n).toBe(2);
91 });
test/app-empty-crew.test.ts added +164
@@ -0,0 +1,164 @@
1 /**
2 * An app with no builder says "No crew yet" to a writer, with one "Seat a crew" action that seats
3 * one as "Choose for me" does; a reader sees nothing, and a seated crew shows no line. The `crew`
4 * MCP tool answers the same line and has the same action (#15831).
5 */
6
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { enableApp } from "../src/actions/apps.ts";
13 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
14 import { NO_CREDIT_WORDS } from "../src/actions/crew_means.ts";
15 import { crewIsEmpty } from "../src/actions/seat_crew.ts";
16 import { getRepoById } from "../src/core/repos.ts";
17 import { createToken } from "../src/core/tokens.ts";
18 import { createAgent } from "../src/actions/crew.ts";
19 import { seatEmptyCrew } from "../src/actions/seat_crew.ts";
20 import { createUser, getUserByName } from "../src/core/users.ts";
21 import { listCrewRoles } from "../src/core/agents.ts";
22 import { serve, type Servers } from "../src/http/server.ts";
23 import { signInCookie } from "./helpers/studio-signin.ts";
24 import { quietLogs } from "./helpers/globals.ts";
25
26 quietLogs();
27
28 let dir = "";
29 let app: App;
30 let servers: Servers;
31 let owner = "";
32 let reader = "";
33 const KEY = process.env["ANTHROPIC_API_KEY"];
34
35 beforeAll(async () => {
36 process.env["ANTHROPIC_API_KEY"] = "test-key";
37 dir = await mkdtemp(join(tmpdir(), "forge-empty-crew-"));
38 app = createApp({ dataDir: dir, port: 0 });
39 servers = await serve(app);
40 for (const [username, admin] of [["alice", true], ["bob", false]] as const) {
41 const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", ...(admin ? { adminIfFirst: true } : {}) });
42 if (!u.ok) throw new Error(u.error);
43 if (username === "alice") {
44 for (const name of ["pad", "pad2", "pad3", "pad4"]) {
45 const r = await createRepo(app, u.value, { name, visibility: "public" });
46 if (!r.ok) throw new Error(String(r.error));
47 const c = await commitToBranch(app, u.value, r.value, { message: "Start", files: [{ path: "README.md", content: "x\n" }] });
48 if (!c.ok) throw new Error(JSON.stringify(c.error));
49 const e = await enableApp(app, u.value, r.value, { slug: name });
50 if (!e.ok) throw new Error(String(e.error));
51 }
52 }
53 }
54 owner = await signInCookie(servers.url, "alice");
55 reader = await signInCookie(servers.url, "bob");
56 });
57 afterAll(async () => {
58 servers.stop?.();
59 if (KEY === undefined) delete process.env["ANTHROPIC_API_KEY"];
60 else process.env["ANTHROPIC_API_KEY"] = KEY;
61 app.db.close();
62 await rm(dir, { recursive: true, force: true });
63 });
64
65 const page = async (path: string, cookie: string) =>
66 (await fetch(`${servers.url}${path}`, { headers: { cookie: `${cookie}; forge_mode=studio` } })).text();
67
68 test("a writer sees the line and one action on an empty crew; a reader sees neither", async () => {
69 const mine = await page("/alice/pad", owner);
70 expect(mine).toContain("No crew yet");
71 expect(mine).toContain('action="/alice/pad/crew/seat"');
72 const theirs = await page("/alice/pad", reader);
73 expect(theirs).not.toContain("No crew yet");
74 expect(theirs).not.toContain("Seat a crew");
75 });
76
77 test("the action seats a builder and a reviewer, and the line is gone after", async () => {
78 const res = await fetch(`${servers.url}/alice/pad2/crew/seat`, {
79 method: "POST",
80 headers: { cookie: owner, origin: servers.url, accept: "application/json" },
81 body: new URLSearchParams({}),
82 redirect: "manual",
83 });
outdated

This asserts only <500 and no seating. Assert the refusal status (403 or a flash with the danger tone). Also add tests for the no-credit refusal and the already refusal, and for an agent's tap, since each is behaviour this pull adds.

84 expect(res.status).toBeLessThan(400);
85 const repo = app.db.query("select id from repo where name = 'pad2'").get() as { id: string };
86 expect(listCrewRoles(app.db, repo.id).map((c) => c.role).sort()).toEqual(["builder", "reviewer"]);
87 const after = await page("/alice/pad2", owner);
88 expect(after).not.toContain("No crew yet");
89 expect(after).not.toContain("Seat a crew");
90 });
91
92 test("a reader's tap seats no one", async () => {
93 const res = await fetch(`${servers.url}/alice/pad/crew/seat`, {
94 method: "POST",
95 headers: { cookie: reader, origin: servers.url, accept: "application/json" },
96 body: new URLSearchParams({}),
97 redirect: "manual",
98 });
99 expect(res.status).toBeLessThan(500);
100 expect(await res.text()).toContain("needs a person with write access");
101 const repo = app.db.query("select id from repo where name = 'pad'").get() as { id: string };
102 expect(listCrewRoles(app.db, repo.id)).toEqual([]);
103 expect(crewIsEmpty(app, getRepoById(app.db, repo.id)!)).toBe(true);
104 });
105
106 test("the crew tool says the same line, and seats with the same action", async () => {
107 const alice = app.db.query("select id from user where username = 'alice'").get() as { id: string };
108 const token = createToken(app.db, alice.id, "t", "admin").token;
109 const call = async (args: object) => {
110 const rpc = (await fetch(`${servers.url}/mcp`, {
111 method: "POST",
112 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
113 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "crew", arguments: args } }),
114 }).then((r) => r.json())) as any;
115 return JSON.parse(rpc.result.content[0].text);
116 };
117 const empty = await call({ repo: "alice/pad3" });
118 expect(empty.says).toBe("No crew yet");
119 expect(empty.action.kind).toBe("seat");
120 expect((await call({ kind: "seat", repo: "alice/pad3" })).says).toContain("nothing changed");
121 expect((await call({ kind: "seat", repo: "alice/pad3", dryRun: false })).changed).toBe(true);
122 const seated = await call({ repo: "alice/pad3" });
123 expect(seated.says).toBeUndefined();
124 expect(seated.action).toBeUndefined();
125 });
126
127 test("an agent never seats, and a second seating says a builder is already there", async () => {
128 const agent = await createAgent(app, getUserByName(app.db, "alice")!, { username: "robo" });
129 if (!agent.ok) throw new Error(String(agent.error));
130 const repo = getRepoById(app.db, (app.db.query("select id from repo where name = 'pad'").get() as { id: string }).id)!;
131 const refused = await seatEmptyCrew(app, agent.value.user, repo);
132 expect(refused).toMatchObject({ ok: false, error: "forbidden" });
133 expect(listCrewRoles(app.db, repo.id)).toEqual([]);
134 const alice = getUserByName(app.db, "alice")!;
135 const taps = await Promise.all([seatEmptyCrew(app, alice, repo), seatEmptyCrew(app, alice, repo)]);
136 expect(taps.filter((t) => t.ok).length).toBe(1);
137 expect(taps.filter((t) => !t.ok && t.error === "already").length).toBe(1);
138 const added = app.db.query("select count(*) as n from event where kind = 'crew.added' and repo_id = ?").get(repo.id) as { n: number };
139 expect(added.n).toBe(2);
140 expect(await seatEmptyCrew(app, alice, repo)).toMatchObject({ ok: false, error: "already" });
141 });
142
143 test("with nothing to run the crew on, nobody is seated and the words say so", async () => {
144 const saved = process.env["ANTHROPIC_API_KEY"];
145 delete process.env["ANTHROPIC_API_KEY"];
146 try {
147 const repo = getRepoById(app.db, (app.db.query("select id from repo where name = 'pad4'").get() as { id: string }).id)!;
148 const done = await seatEmptyCrew(app, getUserByName(app.db, "alice")!, repo);
149 expect(done).toEqual({ ok: false, error: "cannot", says: NO_CREDIT_WORDS });
150 expect(listCrewRoles(app.db, repo.id)).toEqual([]);
151 } finally {
152 process.env["ANTHROPIC_API_KEY"] = saved ?? "test-key";
153 }
154 });
155
156 test("a tell to an app with no crew says No crew yet and names the action", async () => {
157 const res = await fetch(`${servers.url}/alice/pad4/tell`, {
158 method: "POST",
159 headers: { cookie: owner, origin: servers.url, accept: "application/json" },
160 body: new URLSearchParams({ text: "make it blue" }),
161 redirect: "manual",
162 });
163 expect(await res.text()).toContain("No crew yet — Seat a crew");
164 });
test/app-tell-line.test.ts +2 −1
@@ -57,5 +57,6 @@ test("a stranger sees no tell form; the owner sees a plain one", async () => {
5757 expect(whole).not.toContain("<textarea");
5858 // No crew: the hint is a muted line with a link, not a long placeholder.
5959 expect(whole).toContain('placeholder="Tell the crew…"');
60 expect(mine).toContain('href="/alice/open/settings#crew"');
60 expect(mine).toContain('action="/alice/open/crew/seat"');
61 expect(mine).toContain("No crew yet");
6162 });
test/first-ask-flash.test.ts +2 −2
@@ -29,9 +29,9 @@ test("prefixed names the subject, or leaves the message alone", () => {
2929 expect(prefixed("atlas is on it", "")).toBe("atlas is on it");
3030 });
3131
32 test("nobody on the crew: the flash names the app and issue, and says to add someone", () => {
32 test("nobody on the crew: the flash names the app and issue, and says to seat a crew", () => {
3333 expect(tellFlashWords(undefined, null, "menu, issue #1")).toBe(
34 "menu, issue #1: Opened as an issue. Nobody is on the crew to take it yet — add someone under Settings → Crew.",
34 "menu, issue #1: Opened as an issue. No crew yet — Seat a crew on the app page.",
3535 );
3636 });
3737
test/first-ask-new-app.test.ts +1 −1
@@ -59,7 +59,7 @@ test("the first tell makes one app, files one open issue on it, keeps no thought
5959 // With credit left the app's page asks for no key and says nobody is missing.
6060 const page = await (await fetch(`${forge.base}/maria/${repo.name}`, { headers: { cookie: forge.owner } })).text();
6161 expect(page).not.toContain("needs a model key");
62 expect(page).not.toContain("Nobody on the crew yet");
62 expect(page).not.toContain("No crew yet");
6363 expect(recentThoughts(db, maria.id, 10).length).toBe(0);
6464 });
6565
test/mcp-forge-tell.test.ts +1 −1
@@ -76,7 +76,7 @@ describe("the forge over MCP: tell", () => {
7676 repo: "alice/game",
7777 text: "add a second level\n\nwith a boss at the end",
7878 });
79 expect(nobody.value.says).toContain("Nobody is on the crew");
79 expect(nobody.value.says).toContain("No crew yet");
8080 const [first] = listIssues(app.db, game.id, { state: "open" });
8181 expect(first!.title).toBe("add a second level");
8282 expect(first!.body).toContain("boss at the end");
test/studio-crew-panel.test.ts +4 −2
@@ -131,8 +131,10 @@ describe("the studio's crew panel on a forge with no agents yet", () => {
131131
132132 test("the app page's way to add a crew member leads unbroken to the door an agent is made through, with nothing dev-only in the way", async () => {
133133 const appPage = await (await get("/alice/pad", ownerCookie)).text();
134 expect(appPage).toContain("Nobody on the crew yet");
135 expect(appPage).toContain('href="/alice/pad/settings#crew"');
134 expect(appPage).toContain("No crew yet");
135 expect(appPage).toContain('href="/alice/pad/settings"');
136 expect(appPage).toContain("Seat a crew");
137 expect(appPage).toContain(`action="/alice/pad/crew/seat"`);
136138
137139 const settings = await (
138140 await get("/alice/pad/settings", ownerCookie)
test/tui-tell.test.ts +2 −2
@@ -85,14 +85,14 @@ describe("tell the crew in the terminal", () => {
8585
8686 test("one line is told, and the answer is the web's words", async () => {
8787 const text = await palette(alice, [":", "tell", "\r", ..."paint the door red".split(""), "\r"]);
88 expect(text).toContain("Nobody is on the crew to take it yet");
88 expect(text).toContain("No crew yet");
8989 expect(listIssues(app.db, repo.id, {}).some((i) => i.title === "paint the door red")).toBe(true);
9090 });
9191
9292 test("a tell from a page carries its page and pull, and bob has no such row", async () => {
9393 const keys = [":", "from a page", "\r", ..."https://notes.apps.test/a".split(""), "\r", "7", "\r", "\r", ..."move the button".split(""), "\r"];
9494 const text = await palette(alice, keys);
95 expect(text).toContain("Nobody is on the crew to take it yet");
95 expect(text).toContain("No crew yet");
9696 const issue = listIssues(app.db, repo.id, {}).find((i) => i.title === "move the button")!;
9797 expect(issue.body).toContain("From: lobby /a (preview of #7)");
9898 expect(await palette(bob, [":", "from a page"])).not.toContain("Tell the crew from a page");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs