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

The terminal asks whoever can, and answers: "What stands in the way" #12976

Merged opened this

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

Merged

trevato/terminal-asks-whoever-can → main 1 commit

  • Merged. trevato/terminal-asks-whoever-can was merged into main as d800c3b.

Review

Sign in to review this change.
5 files changed +483 −0
docs/features/blocked-by.md +2
@@ -42,6 +42,8 @@ What happens when a person presses the button:
4242
4343 On a page the button is `askButton` (`src/web/blocked.ts`): it submits one hidden form the layout draws for every signed-in reader, so it works inside a paragraph, a flash or another form. An API answer carries `blockedFields`; an MCP refusal is built with `badBlocked` and carries the same fields as `structuredContent`.
4444
45 In the terminal the same thing is the palette command **What stands in the way** (`src/tui/screens/asks_admin.ts`), for anyone signed in. It lists what waits on you to answer, what stands in your own way now (no model key, no model budget) and what you asked, in the sentences the page says. `a` sends the ask for the row, `o` opens the control for one who can change it, `n` is Not now.
46
4547 ## A sentence stored before its reader is known
4648
4749 A run's summary, a park comment and a log line are read by anyone. They are stored as the sentence and who can, in words (`storedText`: "This forge has no model key. An admin of this forge can add one."), never a path or a key name. A surface that knows its reader calls `wayIn(app, reader, text)` and draws the link or the button from it: the run's page does.
src/tui/forge.ts +2
@@ -19,6 +19,7 @@ import { fleetCommand } from "./screens/fleet.ts";
1919 import { dataCommand } from "./screens/data.ts";
2020 import { packsCommand } from "./screens/packs.ts";
2121 import { needsCommands } from "./screens/needs.ts";
22 import { asksAdminCommands } from "./screens/asks_admin.ts";
2223 import { shareTellCommand } from "./screens/share_tell.ts";
2324 import { sendChangeCommand } from "./screens/send_change.ts";
2425 import { interruptedOutCommand } from "./screens/interrupted_out.ts";
@@ -261,6 +262,7 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
261262 run: () => openOnWeb(session, ctx, "/explore.atom", "The explore feed"),
262263 },
263264 ...needsCommands(session, ctx),
265 ...asksAdminCommands(session, ctx),
264266 packsCommand(session, ctx),
265267 shareTellCommand(session, ctx),
266268 sendChangeCommand(ctx),
src/tui/screens/asks_admin.ts added +229
@@ -0,0 +1,229 @@
1 /**
2 * "What stands in the way" in the terminal (`docs/features/blocked-by.md`):
3 * the terminal's door to asking whoever can (`actions/ask_admin.ts`), with
4 * the same sentences the page and the API say.
5 *
6 * Three kinds of row, in this order:
7 *
8 * - what waits on this person to answer ("bob asks for a model grant for
9 * bob"): `o` opens the exact control, `n` is "Not now";
10 * - what stands in this person's own way now (no model key, no model
11 * budget): `o` opens the control for one who can change it, `a` sends the
12 * ask for one who cannot;
13 * - what this person asked, and how each stands.
14 *
15 * Every write goes through the action the page calls, so who may ask and
16 * who may answer is decided there. Any event on the bus redraws the list.
17 */
18
19 import {
20 adminAskWords,
21 askAdmin,
22 asksToAnswer,
23 ASK_ADMIN_WORDS,
24 myAdminAsks,
25 putAsideAsk,
26 type AskView,
27 } from "../../actions/ask_admin.ts";
28 import { noBudgetBlocked, noKeyBlocked } from "../../actions/blocked_words.ts";
29 import { budgetLine, NO_BUDGET_LINE } from "../../core/model_grant.ts";
30 import { forgeHasNoKey } from "../../crew/no_key.ts";
31 import { agoWords } from "../../kernel/ago.ts";
32 import { whoCan, type Blocked } from "../../kernel/blocked.ts";
33 import type { Ctx, Screen } from "../app/app.ts";
34 import { binding } from "../app/keys.ts";
35 import type { Command } from "../app/palette.ts";
36 import type { Session } from "../session.ts";
37 import { style } from "../term/style.ts";
38 import { truncate } from "../term/width.ts";
39 import { fill, len, split } from "../ui/layout.ts";
40 import {
41 ListState,
42 drawList,
43 live,
44 openOnWeb,
45 type ListRow,
46 } from "./common.ts";
47
48 /** One row: something to answer, something in this person's way, or something they asked. */
49 export type AskRow =
50 | { readonly kind: "answer"; readonly ask: AskView }
51 | { readonly kind: "way"; readonly blocked: Blocked }
52 | { readonly kind: "asked"; readonly ask: AskView };
53
54 /** What stands in this session's person's own way now, as the page would say it. */
55 export function waysFor(f: Session): Blocked[] {
56 const user = f.user;
57 if (user === undefined) return [];
58 const out: Blocked[] = [];
59 if (forgeHasNoKey(f.app)) out.push(noKeyBlocked(f.app, user));
60 if (budgetLine(f.app.db, user, new Date()) === NO_BUDGET_LINE)
61 out.push(noBudgetBlocked(f.app, user, user));
62 return out;
63 }
64
65 /** Every row this session's person is shown. */
66 export function askRowsFor(f: Session): AskRow[] {
67 if (f.user === undefined) return [];
68 const mine = myAdminAsks(f.app, f.user);
69 const asked = mine.ok ? mine.value : [];
70 // A thing already asked for is said once, as the ask and how it stands.
71 const waiting = new Set(
72 asked
73 .filter((a) => a.state !== "done")
74 .map((a) => `${a.want} ${a.subject}`.trim()),
75 );
76 const keyOf = (b: Blocked): string =>
77 `${b.ask?.body["want"] ?? ""} ${b.ask?.body["subject"] ?? ""}`.trim();
78 return [
79 ...asksToAnswer(f.app, f.user).map((ask) => ({
80 kind: "answer" as const,
81 ask,
82 })),
83 ...waysFor(f)
84 .filter((b) => b.readerCan || !waiting.has(keyOf(b)))
85 .map((blocked) => ({ kind: "way" as const, blocked })),
86 ...asked.map((ask) => ({ kind: "asked" as const, ask })),
87 ];
88 }
89
90 function rowOf(r: AskRow): ListRow {
91 if (r.kind === "answer")
92 return {
93 title: `${r.ask.sentence} (${agoWords(r.ask.lastAt)})`,
94 tone: "attn",
95 note: r.ask.label,
96 meta: "o opens it · n not now",
97 };
98 if (r.kind === "asked")
99 return {
100 title: `You asked: ${r.ask.label}`,
101 note: adminAskWords(r.ask, agoWords(r.ask.lastAt)),
102 ...(r.ask.state === "done" ? { tone: "success" as const } : {}),
103 };
104 const b = r.blocked;
105 return b.link !== undefined
106 ? { title: b.says, tone: "attn", note: b.link.label, meta: "o opens it" }
107 : {
108 title: b.says,
109 tone: "attn",
110 note: whoCan(b),
111 ...(b.ask === undefined ? {} : { meta: `a: ${b.ask.label}` }),
112 };
113 }
114
115 export function asksAdminScreen(f: Session, ctx: Ctx): Screen {
116 const state = new ListState();
117 let rows = askRowsFor(f);
118 const reload = (): void => {
119 rows = askRowsFor(f);
120 ctx.invalidate();
121 };
122 return {
123 title: "What stands in the way",
124 keys: [
125 binding(["j", "k"], "move cursor"),
126 binding(["a"], "ask whoever can"),
127 binding(["o"], "open the control"),
128 binding(["n"], "not now"),
129 ],
130 async load(signal) {
131 live(f, signal, {}, reload);
132 },
133 render(area, s) {
134 const c = ctx.theme.c;
135 const [head, list] = split(area, "v", [len(1), fill(1)]);
136 const says =
137 f.user === undefined
138 ? "Sign in to see what stands in your way."
139 : rows.length === 0
140 ? "Nothing stands in your way, and nobody is waiting on you."
141 : "What waits on you, what stands in your way, and what you asked.";
142 s.text(
143 head!.x,
144 head!.y,
145 truncate(says, head!.w),
146 style(c.mutedFg, c.bg),
147 head!.x + head!.w,
148 );
149 drawList(s, list!, c, state, rows.map(rowOf));
150 },
151 key(e) {
152 if (state.key(e, rows.length)) return true;
153 if (e.ctrl || e.alt) return false;
154 const at = rows[state.index];
155 if (at === undefined || f.user === undefined) return false;
156 if (e.key === "o") {
157 const link =
158 at.kind === "way"
159 ? at.blocked.link
160 : at.kind === "answer"
161 ? { href: at.ask.href, label: at.ask.label }
162 : undefined;
163 if (link === undefined)
164 ctx.toast(at.kind === "asked" ? "Already asked: the row says how it stands." : "That is not yours to change: a asks whoever can.", "attn");
165 else openOnWeb(f, ctx, link.href, link.label);
166 return true;
167 }
168 if (e.key === "a") {
169 const ask = at.kind === "way" ? at.blocked.ask : undefined;
170 if (ask === undefined) {
171 ctx.toast(
172 at.kind === "way"
173 ? "You can change this yourself: o opens it."
174 : at.kind === "asked"
175 ? "Already asked: the row says how it stands."
176 : "This one waits on you: o opens where it is changed.",
177 "attn",
178 );
179 return true;
180 }
181 const asked = askAdmin(f.app, f.user, {
182 want: String(ask.body["want"] ?? ""),
183 subject: String(ask.body["subject"] ?? ""),
184 });
185 ctx.toast(
186 asked.ok
187 ? "Asked. They see it on their home page, with the link to where it is changed."
188 : ASK_ADMIN_WORDS[asked.error],
189 asked.ok ? "success" : "danger",
190 );
191 reload();
192 return true;
193 }
194 if (e.key === "n") {
195 if (at.kind !== "answer") {
196 ctx.toast("Not now is for something that waits on you.", "attn");
197 return true;
198 }
199 const done = putAsideAsk(f.app, f.user, {
200 username: at.ask.username,
201 want: at.ask.want,
202 subject: at.ask.subject,
203 });
204 ctx.toast(
205 done.ok
206 ? `Put aside. ${at.ask.username} is told it waits.`
207 : "That was already answered, or is no longer there.",
208 done.ok ? undefined : "danger",
209 );
210 reload();
211 return true;
212 }
213 return false;
214 },
215 };
216 }
217
218 /** Offered to anyone signed in: the rows are their own. */
219 export const asksAdminCommands = (f: Session, ctx: Ctx): Command[] =>
220 f.user === undefined
221 ? []
222 : [
223 {
224 id: "asks-admin",
225 title: "What stands in the way",
226 hint: "what waits on you and what stands in your way; a asks whoever can, o opens the control",
227 run: () => ctx.push(asksAdminScreen(f, ctx)),
228 },
229 ];
test/palette-roster.test.ts +3
@@ -49,6 +49,7 @@ test("a site-admin person is offered the whole roster", () => {
4949 ["explore", "Explore", "on the web"],
5050 ["explore-feed", "Explore feed", "Atom address"],
5151 ["needs", "How is my forge?", "what needs you, with a recommendation each; a takes a safe one"],
52 ["asks-admin", "What stands in the way", "what waits on you and what stands in your way; a asks whoever can, o opens the control"],
5253 ["packs", "Forge packs", "premade forges to deploy, and how to help build their apps"],
5354 ["mirror-packs", "Mirror the packs' upstreams", "bring each pack's upstream projects in as read-only repositories"],
5455 ["pack-repos", "Pack repositories", "which repositories /packs lists"],
@@ -222,6 +223,7 @@ test("a site-admin agent is offered the roster without the person-only entries",
222223 ["explore", "Explore", "on the web"],
223224 ["explore-feed", "Explore feed", "Atom address"],
224225 ["needs", "How is my forge?", "what needs you, with a recommendation each; a takes a safe one"],
226 ["asks-admin", "What stands in the way", "what waits on you and what stands in your way; a asks whoever can, o opens the control"],
225227 ["packs", "Forge packs", "premade forges to deploy, and how to help build their apps"],
226228 ["share-tell", "Share a link or text with the crew", "a draft, then where; nothing is sent until you confirm"],
227229 ["send-change", "Send a change", "fork, patch, pull: no forge of your own"],
@@ -315,6 +317,7 @@ test("a member person is offered the signed-in roster without the admin entries"
315317 ["explore", "Explore", "on the web"],
316318 ["explore-feed", "Explore feed", "Atom address"],
317319 ["needs", "How is my forge?", "what needs you, with a recommendation each; a takes a safe one"],
320 ["asks-admin", "What stands in the way", "what waits on you and what stands in your way; a asks whoever can, o opens the control"],
318321 ["packs", "Forge packs", "premade forges to deploy, and how to help build their apps"],
319322 ["share-tell", "Share a link or text with the crew", "a draft, then where; nothing is sent until you confirm"],
320323 ["send-change", "Send a change", "fork, patch, pull: no forge of your own"],
test/tui-asks-admin.test.ts added +247
@@ -0,0 +1,247 @@
1 /**
2 * Asking whoever can, in the terminal (`src/tui/screens/asks_admin.ts`): a
3 * member who is stopped reads the sentence the page says and sends the ask
4 * with one key; the admin reads it with the control it is answered on, and
5 * puts it aside with one key. Every write is the page's own action.
6 */
7 import { afterAll, beforeAll, describe, 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 { askAdmin, asksToAnswer } from "../src/actions/ask_admin.ts";
12 import { createRepo } from "../src/actions/repos.ts";
13 import { createApp, type App as Forge } from "../src/app.ts";
14 import { forgetNoKey } from "../src/crew/no_key.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { createForgeApp } from "../src/tui/forge.ts";
17 import { askRowsFor, type AskRow } from "../src/tui/screens/asks_admin.ts";
18 import type { TuiIdentity } from "../src/tui/session.ts";
19 import { headlessTerminal } from "../src/tui/term/terminal.ts";
20 import { quietLogs } from "./helpers/globals.ts";
21 import { promote } from "./helpers/members.ts";
22 import { settleApp, settlePalette, settleUntil } from "./helpers/tui.ts";
23
24 quietLogs();
25
26 describe("what stands in the way, in the terminal", () => {
27 let dataDir: string;
28 let forge: Forge;
29 let ada: User; // site admin
30 let bob: User; // a member, no admin
31
32 const states = () =>
33 forge.db
34 .query<
35 { want: string; state: string },
36 []
37 >("SELECT want, state FROM admin_ask ORDER BY want")
38 .all();
39
40 function boot(user: User) {
41 const terminal = headlessTerminal(200, 32);
42 const identity: TuiIdentity = {
43 sshUsername: "t",
44 remoteAddress: "127.0.0.1",
45 user,
46 };
47 const { app, session } = createForgeApp(forge, identity, {
48 terminal,
49 exitHooks: false,
50 });
51 app.start();
52 const press = async (...keys: string[]) => {
53 for (const key of keys) {
54 const ctrl = key.startsWith("ctrl+");
55 app.dispatch({
56 type: "key",
57 key: ctrl ? key.slice(5) : key,
58 ctrl,
59 alt: false,
60 shift: false,
61 });
62 }
63 await settleApp(app);
64 };
65 const open = async () => {
66 await settleApp(app);
67 await press("ctrl+k");
68 for (const ch of "What stands in the way")
69 app.dispatch({
70 type: "key",
71 key: ch,
72 ctrl: false,
73 alt: false,
74 shift: false,
75 });
76 await settlePalette(app);
77 await press("enter");
78 await settleUntil(app, "open the control");
79 };
80 return {
81 text: () => app.screen.toText(),
82 press,
83 open,
84 session,
85 stop: () => app.stop(),
86 };
87 }
88
89 beforeAll(async () => {
90 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-asks-admin-"));
91 forge = createApp({ dataDir, port: 0 });
92 const make = async (
93 username: string,
94 adminIfFirst: boolean,
95 ): Promise<User> => {
96 const made = await createUser(forge.db, {
97 origin: "seed",
98 trusted: true,
99 username,
100 email: `${username}@forge.local`,
101 password: "a-good-passphrase",
102 adminIfFirst,
103 });
104 if (!made.ok) throw new Error(made.error);
105 return made.value;
106 };
107 ada = await make("ada", true);
108 bob = await make("bob", false);
109 promote(forge.db, bob);
110 }, 60_000);
111
112 afterAll(async () => {
113 forge?.close();
114 if (dataDir) await rm(dataDir, { recursive: true, force: true });
115 });
116
117 test("a member reads what stands in their way in the page's words, and one key sends the ask", async () => {
118 const h = boot(bob);
119 await h.open();
120 // The sentence, who can, and the key that asks: never a path he cannot open or a key name.
121 expect(h.text()).toContain("No model budget yet.");
122 expect(h.text()).toContain("An admin of this forge can grant one.");
123 expect(h.text()).toContain("a: Ask an admin for a model grant");
124 expect(h.text()).not.toContain("/settings/accounts");
125 expect(h.text()).not.toContain("model_grant");
126 // `o` on a row that is not his to change opens nothing and says what to press.
127 await h.press("o");
128 expect(h.text()).toContain("a asks whoever can");
129 expect(states()).toEqual([]);
130 // Each row that stands in his way is asked for with `a`; the one asked moves to "You asked".
131 const before = askRowsFor(h.session).filter((r) => r.kind === "way").length;
132 for (let i = 0; i < before; i++) await h.press("a");
133 expect(states().map((s) => s.state)).toEqual(
134 Array.from({ length: before }, () => "asked"),
135 );
136 expect(states().map((s) => s.want)).toContain("model_grant");
137 expect(h.text()).toContain("You asked: Give bob a model grant");
138 expect(h.text()).toContain("An admin of this forge has not answered yet.");
139 // Nothing waits on him: a member answers nobody's ask.
140 expect(askRowsFor(h.session).filter((r) => r.kind === "answer")).toEqual(
141 [],
142 );
143 h.stop();
144 });
145
146 test("the admin reads the ask with the control it is answered on, and Not now puts it aside", async () => {
147 const waiting = asksToAnswer(forge, ada).length;
148 expect(waiting).toBeGreaterThan(0);
149 const h = boot(ada);
150 await h.open();
151 expect(h.text()).toContain("bob asks for a model grant for bob");
152 expect(h.text()).toContain("o opens it · n not now");
153 // Her own row, when she has one, is hers to change: it offers the control, never an ask.
154 for (const r of askRowsFor(h.session))
155 if (r.kind === "way") expect(r.blocked.link).toBeDefined();
156 // The rows that wait on her come first: `n` on each puts it aside.
157 for (let i = 0; i < waiting; i++) await h.press("n");
158 expect(asksToAnswer(forge, ada)).toEqual([]);
159 expect(states().every((s) => s.state === "later")).toBe(true);
160 expect(h.text()).not.toContain("bob asks for a model grant for bob");
161 h.stop();
162 // The member reads that it was put aside.
163 const asBob = boot(bob);
164 await asBob.open();
165 expect(asBob.text()).toContain(
166 "An admin of this forge put this aside for now.",
167 );
168 asBob.stop();
169 });
170
171 test("each key says what it did on a row it does not apply to, and o opens the control it names", async () => {
172 // Bob holds the row he asked above.
173 const bobs = boot(bob);
174 await bobs.open();
175 const rowsOf = (h: { session: Parameters<typeof askRowsFor>[0] }) => askRowsFor(h.session).map((r) => r.kind);
176 const to = async (h: ReturnType<typeof boot>, kind: AskRow["kind"]) => {
177 const at = rowsOf(h).indexOf(kind);
178 expect(at).toBeGreaterThanOrEqual(0);
179 await h.press("g");
180 for (let i = 0; i < at; i++) await h.press("j");
181 };
182 // His row was put aside above: on it, a asks nothing new, o opens nothing, n is not his.
183 await to(bobs, "asked");
184 const before = states();
185 await bobs.press("a");
186 expect(bobs.text()).toContain("Already asked: the row says how it stands.");
187 await bobs.press("o");
188 expect(bobs.text()).toContain("Already asked: the row says how it stands.");
189 await bobs.press("n");
190 expect(bobs.text()).toContain("Not now is for something that waits on you.");
191 expect(states()).toEqual(before);
192 bobs.stop();
193
194 // A fresh ask from a second member waits on the admin.
195 const cal = await (async () => {
196 const made = await createUser(forge.db, { origin: "seed", trusted: true, username: "cal", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: false });
197 if (!made.ok) throw new Error(made.error);
198 promote(forge.db, made.value);
199 return made.value;
200 })();
201 expect(askAdmin(forge, cal, { want: "model_grant", subject: "cal" }).ok).toBe(true);
202
203 // A member's app with a crew and no key anywhere: the forge has no model key, hers to add.
204 const pad = await createRepo(forge, bob, { name: "pad", visibility: "public", description: "" });
205 if (!pad.ok) throw new Error(JSON.stringify(pad.error));
206 forge.db.run("UPDATE repo SET autonomy = 'autonomous', autonomy_slots = 1 WHERE id = ?1", [pad.value.id]);
207 forgetNoKey(forge.db);
208
209 const h = boot(ada);
210 await h.open();
211 // o on what waits on her opens the exact control the ask is answered on.
212 await to(h, "answer");
213 await h.press("o");
214 expect(h.text()).toContain("/settings/accounts/cal#f-grant");
215 // a on it asks nobody: it is hers to answer.
216 await h.press("a");
217 expect(h.text()).toContain("This one waits on you: o opens where it is changed.");
218 // o on what stands in her own way opens the control she can change herself; a tells her so.
219 await to(h, "way");
220 const own = askRowsFor(h.session).find((r) => r.kind === "way");
221 expect(own?.kind === "way" ? own.blocked.link?.href : undefined).toBe("/settings/crew#crew-key");
222 await h.press("o");
223 expect(h.text()).toContain("/settings/crew#crew-key");
224 await h.press("a");
225 expect(h.text()).toContain("You can change this yourself: o opens it.");
226 await h.press("n");
227 expect(h.text()).toContain("Not now is for something that waits on you.");
228 // Nothing was written by any of it.
229 expect(asksToAnswer(forge, ada).map((a) => a.username)).toEqual(["cal"]);
230 h.stop();
231 });
232
233 test("nobody signed in is offered no entry", async () => {
234 const terminal = headlessTerminal(200, 32);
235 const identity: TuiIdentity = { sshUsername: "t", remoteAddress: "127.0.0.1" };
236 const { app, session } = createForgeApp(forge, identity, { terminal, exitHooks: false });
237 app.start();
238 await settleApp(app);
239 expect(session.user).toBeUndefined();
240 expect(askRowsFor(session)).toEqual([]);
241 app.dispatch({ type: "key", key: "k", ctrl: true, alt: false, shift: false });
242 for (const ch of "What stands in the way") app.dispatch({ type: "key", key: ch, ctrl: false, alt: false, shift: false });
243 await settlePalette(app);
244 expect(app.screen.toText()).not.toContain("what waits on you and what stands in your way");
245 app.stop();
246 });
247 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs