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

The client tells the crew about an app, in their own words, and the answer comes back there #1904

Parked opened this
Closed without merging

scout/forge:scout/1609-the-client-tells-the-crew-about-an-app-i → main 5 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
11 files changed +437 −1
README.md +11
@@ -106,6 +106,17 @@ thoughts, then the issues you can write to that are not shipped, oldest first
106106 only, shows a guest nothing, and names nothing of a placement in a repository
107107 you cannot read.
108108
109 Telling the crew about an app: whoever can write to an app has a box on its
110 page, and under it a card with their own latest tell and the last thing a crew
111 member said back (`You told the crew`, then `scout answered`, or `No answer yet`).
112 It is a live region (`GET /:owner/:name/app/answer`), so it updates when the crew
113 comments without a reload; it shows only the viewer's own words, never another
114 person's, and nothing to a guest or to someone who cannot write. A second tell
115 replaces the first on the card; `Everything told` links the list. In the terminal,
116 `T` on an app in the dashboard's repository list opens the same card (`enter`
117 gives the thread's web address, `r` refreshes); it reads the same
118 `src/core/tell-answer.ts`, so the gate is one.
119
109120 The family across forges: `:` → Family in the terminal, `/family` on the web,
110121 `GET /api/v1/family` and the MCP `family` tool all give the same view. The
111122 forge that sent this one is shown to anyone; the forges it sent, only to a
scripts/gate.ts +1
@@ -30,6 +30,7 @@ export const GATE: readonly string[] = [
3030 "test/domain-drill.test.ts",
3131 "test/accounts-retire.test.ts",
3232 "test/client-home.test.ts",
33 "test/client-tell.test.ts",
3334 "test/cloud-use.test.ts",
3435 "test/accounts.test.ts",
3536 "test/asks-mute.test.ts",
src/core/releases.json +5 −1
@@ -3,7 +3,11 @@
33 "releases": [
44 {
55 "version": "0.7.123",
6 "migrations": 93
6 "migrations": 93,
7 "ids": [
8 "20261015090000-feed-chips",
9 "20261015230000-a-domain-drill"
10 ]
711 },
812 {
913 "version": "0.7.122",
src/core/tell-answer.ts added +64
@@ -0,0 +1,64 @@
1 /**
2 * The crew's answer to a tell (#1609): the viewer's latest tell on an app,
3 * and the last thing a crew member said back on it. The web card and the
4 * terminal both read it here, so the gate is one: only a person who can
5 * write to the app has a box, so only they have an answer, and only to
6 * their own words.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import { getAppByRepo } from "./apps.ts";
11 import { listIssues, type Issue } from "./issues.ts";
12 import { canSeeOwnerFacts, type Repo } from "./repos.ts";
13 import type { User } from "./users.ts";
14
15 const SHOWN = 600;
16
17 export interface Answer {
18 readonly by: string;
19 /** Plain text, cut short. */
20 readonly text: string;
21 }
22
23 export interface Told {
24 readonly issue: Issue;
25 readonly answer: Answer | undefined;
26 }
27
28 /** The last comment a crew member left on `issue`, if any. */
29 export function crewAnswer(db: Database, issue: Issue): Answer | undefined {
30 const row = db
31 .query<{ by: string; body: string }, [string]>(
32 `SELECT user.username AS by, comment.body AS body
33 FROM comment JOIN user ON user.id = comment.author_id
34 WHERE comment.issue_id = ?1 AND comment.kind = 'comment' AND user.is_agent = 1
35 ORDER BY comment.id DESC LIMIT 1`,
36 )
37 .get(issue.id);
38 if (!row) return undefined;
39 const text =
40 row.body.length > SHOWN ? `${row.body.slice(0, SHOWN).trimEnd()}…` : row.body;
41 return { by: row.by, text };
42 }
43
44 /**
45 * The viewer's latest tell on `repo` (highest number first, so a second
46 * tell is the one shown) and its answer; undefined for a guest, for anyone
47 * who cannot tell this app, and when they have told it nothing.
48 */
49 export function toldAnswer(
50 db: Database,
51 repo: Repo,
52 viewer: User | undefined,
53 ): Told | undefined {
54 if (!viewer || !canSeeOwnerFacts(db, repo, viewer)) return undefined;
55 if (!getAppByRepo(db, repo.id)) return undefined;
56 const [issue] = listIssues(db, repo.id, {
57 kind: "issue",
58 state: "all",
59 author: viewer.username,
60 sealedBy: viewer.id,
61 limit: 1,
62 });
63 return issue ? { issue, answer: crewAnswer(db, issue) } : undefined;
64 }
src/http/server.ts +3
@@ -229,6 +229,7 @@ import {
229229 liveOnYouFragment,
230230 studioDoor,
231231 } from "../web/studio/home.ts";
232 import { appAnswerFragment } from "../web/studio/answer.ts";
232233 import { appNowFragment } from "../web/studio/now.ts";
233234 import { appStateFragment } from "../web/studio/previews.ts";
234235 import { changesList, tellsList } from "../web/studio/lists.ts";
@@ -1046,6 +1047,8 @@ export function buildRouter(): Router<Handler> {
10461047 router.add("GET", "/:owner/:name/app/state", appStateFragment);
10471048 // "Now" on the same page, alone: the region's own address.
10481049 router.add("GET", "/:owner/:name/app/now", appNowFragment);
1050 // The crew's answer to the viewer's latest tell, alone, for its live region.
1051 router.add("GET", "/:owner/:name/app/answer", appAnswerFragment);
10491052 router.add("GET", "/:owner/:name/app/:env/open", appOpen);
10501053 // Where a private app sends a person who arrived by its link.
10511054 router.add("GET", "/apps/open", appsOpen);
src/tui/screens/dashboard.ts +9
@@ -17,6 +17,8 @@
1717 import { protectionNotice } from "../../kernel/protection.ts";
1818 import { holdWords, plannerHold } from "../../crew/autonomy.ts";
1919 import { forgeLane, forgeNeeds } from "../../actions/health.ts";
20 import { toldAnswer } from "../../core/tell-answer.ts";
21 import { toldScreen } from "./told.ts";
2022 import { clientAppRows } from "../../core/client-apps.ts";
2123 import { nextStepsFor } from "../../core/next-steps.ts";
2224 import { agentsLine } from "../../web/studio/client_home.ts";
@@ -541,6 +543,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
541543 binding(["d"], "unpin", {
542544 disabled: focus !== "machine" || pins.length === 0,
543545 }),
546 binding(["T"], "told", { disabled: !f.signedIn || focus !== "repos" }),
544547 binding(["n"], "new repo", { disabled: !f.signedIn }),
545548 binding(["A"], "account", { disabled: !f.signedIn }),
546549 binding(["s"], "sign in", { disabled: f.signedIn }),
@@ -691,6 +694,12 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
691694 ctx.push(newRepoScreen(f, ctx));
692695 return true;
693696 }
697 if (e.key === "T" && f.user && focus === "repos") {
698 const repo = shown()[at("repos").index];
699 if (repo && toldAnswer(f.db, repo, f.user)) ctx.push(toldScreen(f, ctx, repo));
700 else ctx.toast("nothing told here: not an app you can tell, or you have not yet", "attn");
701 return true;
702 }
694703 if (e.key === "A" && f.user) {
695704 openOnWeb(f, ctx, "/settings", "Account settings");
696705 return true;
src/tui/screens/told.ts added +69
@@ -0,0 +1,69 @@
1 /**
2 * An app's tell and the crew's answer in the terminal (#1609): the viewer's
3 * latest tell on one app and the last thing a crew member said back, from
4 * the same `toldAnswer` read the app page's card makes — so the gate is
5 * core's: only someone who can tell the app sees it, and only their own
6 * words. Read-only; `enter` hands over the thread's web address.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import { toldAnswer } from "../../core/tell-answer.ts";
11 import type { Repo } from "../../core/repos.ts";
12 import type { User } from "../../core/users.ts";
13 import type { Ctx, Screen } from "../app/app.ts";
14 import { binding } from "../app/keys.ts";
15 import type { Session } from "../session.ts";
16 import { style } from "../term/style.ts";
17 import { truncate } from "../term/width.ts";
18 import { openOnWeb } from "./common.ts";
19
20 /** Plain text a typed tell or a comment may carry control bytes in. */
21 const plain = (text: string): string =>
22 // eslint-disable-next-line no-control-regex
23 text.replace(/[\u0000-\u0009\u000b-\u001f\u007f-\u009f]+/g, " ").trim();
24
25 /** The lines of the card: empty when the viewer has told this app nothing. */
26 export function toldLines(db: Database, repo: Repo, viewer: User | undefined): string[] {
27 const got = toldAnswer(db, repo, viewer);
28 if (!got) return [];
29 const lines = ["You told the crew", plain(got.issue.title), ""];
30 if (!got.answer) return [...lines, "No answer yet. It shows here when the crew writes back."];
31 return [
32 ...lines,
33 `${got.answer.by} answered`,
34 ...got.answer.text.split("\n").map(plain),
35 ];
36 }
37
38 export function toldScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
39 let lines: string[] = [];
40 const read = (): void => {
41 lines = toldLines(f.db, repo, f.user);
42 };
43 return {
44 title: `${repo.name} · told`,
45 keys: [binding(["enter"], "thread"), binding(["r"], "refresh")],
46 load: async () => read(),
47 render(area, s) {
48 const c = ctx.theme.c;
49 const shown = lines.length > 0 ? lines : ["You have told this app nothing yet."];
50 shown.slice(0, area.h).forEach((line, i) =>
51 s.text(area.x, area.y + i, truncate(line, area.w), style(i === 0 || line === "" ? c.mutedFg : c.fg, c.bg), area.x + area.w),
52 );
53 },
54 key(e) {
55 if (e.key === "enter") {
56 const got = toldAnswer(f.db, repo, f.user);
57 if (got)
58 openOnWeb(f, ctx, `/${repo.ownerName}/${repo.name}/tells/${got.issue.number}`, "That tell");
59 return true;
60 }
61 if (e.key === "r") {
62 read();
63 ctx.invalidate();
64 return true;
65 }
66 return false;
67 },
68 };
69 }
src/web/studio/answer.ts added +72
@@ -0,0 +1,72 @@
1 /**
2 * The crew's answer to a tell, under the box that sent it (#1609): the
3 * viewer's latest tell on this app, in their own words, and the last thing
4 * a crew member said back — or a plain line saying nobody has yet. The
5 * words are plain text, escaped, and cut short; the whole thread and the
6 * list of tells are a link away. It is a live region with an address of its
7 * own (`GET /:owner/:name/app/answer`), so it updates when the crew comments.
8 */
9
10 import { getAppByRepo } from "../../core/apps.ts";
11 import type { Repo } from "../../core/repos.ts";
12 import { toldAnswer } from "../../core/tell-answer.ts";
13 import type { User } from "../../core/users.ts";
14 import type { Ctx } from "../../http/context.ts";
15 import { loadRepo, repoBase } from "../chrome.ts";
16 import { html, type Html } from "../html.ts";
17 import { fragment } from "../layout.ts";
18 import { tellHref, tellsHref } from "./nouns.ts";
19
20 /** The events that can change what the card says. */
21 export const ANSWER_LIVE = "issue.opened,issue.commented,issue.edited";
22
23 /** The card under the box; empty when the viewer has told this app nothing. */
24 function answerCard(
25 db: Ctx["app"]["db"],
26 repo: Repo,
27 viewer: User | undefined,
28 ): Html {
29 const got = toldAnswer(db, repo, viewer);
30 if (!got) return html``;
31 const base = repoBase(repo);
32 const { issue, answer } = got;
33 return html`<section class="card studio-answer" id="answer">
34 <p class="muted small">You told the crew</p>
35 <p class="studio-answer-told">${issue.title}</p>
36 ${answer
37 ? html`<p class="muted small">${answer.by} answered</p>
38 <p class="studio-answer-text">${answer.text}</p>`
39 : html`<p class="muted">No answer yet. It shows here when the crew writes back.</p>`}
40 <p class="small">
41 <a href="${tellHref(base, issue.number)}">The whole thread</a> ·
42 <a href="${tellsHref(base)}">Everything told</a>
43 </p>
44 </section>`;
45 }
46
47 /** The card in its live region, for the app page and for its own fragment. */
48 export function answerRegion(
49 db: Ctx["app"]["db"],
50 repo: Repo,
51 viewer: User | undefined,
52 ): Html {
53 return html`<div
54 id="live-answer"
55 aria-live="polite"
56 data-live="${ANSWER_LIVE}"
57 data-live-repo="${repo.ownerName}/${repo.name}"
58 data-live-src="${repoBase(repo)}/app/answer"
59 >
60 ${answerCard(db, repo, viewer)}
61 </div>`;
62 }
63
64 // GET /:owner/:name/app/answer — the card alone, for the region that shows it.
65 export function appAnswerFragment(ctx: Ctx): Response {
66 const repo = loadRepo(ctx);
67 if (!repo || !getAppByRepo(ctx.app.db, repo.id))
68 return fragment(html``, { status: 404 });
69 return fragment(answerRegion(ctx.app.db, repo, ctx.auth.user), {
70 request: ctx.request,
71 });
72 }
src/web/studio/app.ts +2
@@ -46,6 +46,7 @@ import {
4646 time,
4747 userTag,
4848 } from "../ui.ts";
49 import { answerRegion } from "./answer.ts";
4950 import { changesHref, tellsHref } from "./nouns.ts";
5051 import { nowCard, nowRegion } from "./now.ts";
5152 import { repoAsks } from "./asks.ts";
@@ -476,6 +477,7 @@ export async function studioApp(
476477 <div class="dash">
477478 <div class="dash-main stack">
478479 ${tell}
480 ${answerRegion(db, repo, ctx.auth.user)}
479481 <div id="app-previews">${previews}</div>
480482 ${nowRegion(repo, now)}
481483 </div>
src/web/studio/style.ts +1
@@ -35,6 +35,7 @@ const shell = part(/* css */ `
3535 const tellBox = part(/* css */ `
3636 .studio-tell textarea { min-height: 72px; resize: vertical; }
3737 .studio-tell .bar { display: flex; align-items: center; gap: 8px; margin-top: 8px; }
38 .studio-answer-text { white-space: pre-wrap; overflow-wrap: anywhere; }
3839 `);
3940
4041 /** The app's head card: what production is doing (`previews.ts`). */
test/client-tell.test.ts added +200
@@ -0,0 +1,200 @@
1 /**
2 * The client's box on an app page (#1609): a tell goes to the crew, and the
3 * crew's answer shows under the box — for whoever can tell the app, to their
4 * own words only, in a live region, and in the terminal. A stand-in for the
5 * run writes the answer.
6 */
7
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { addToCrew, createAgent } from "../src/actions/crew.ts";
13 import { enableApp } from "../src/actions/apps.ts";
14 import { createApp, type App } from "../src/app.ts";
15 import { addComment, listIssues, type Issue } from "../src/core/issues.ts";
16 import { addTeamMember, createOrg, createTeam } from "../src/core/orgs.ts";
17 import { createRepo, type Repo } from "../src/core/repos.ts";
18 import { toldAnswer } from "../src/core/tell-answer.ts";
19 import { createUser, getUserByName, type User } from "../src/core/users.ts";
20 import { serve, type Servers } from "../src/http/server.ts";
21 import { toldLines } from "../src/tui/screens/told.ts";
22 import { quietLogs } from "./helpers/globals.ts";
23
24 quietLogs();
25
26 describe("the crew's answer under the client's box", () => {
27 let dir = "";
28 let app: App;
29 let servers: Servers;
30 let repo: Repo;
31 const users: Record<string, User> = {};
32 const cookies: Record<string, string> = { guest: "" };
33
34 const get = async (who: string, path = "/acme/notes") =>
35 (
36 await (
37 await fetch(`${servers.url}${path}`, { headers: { cookie: cookies[who]! } })
38 ).text()
39 ).replace(/\s+/g, " ");
40
41 /** Only the answer region of the page: the rest of it (Now, the feed) names every tell to those who may see them. */
42 const card = async (who: string) => {
43 const page = await get(who);
44 const at = page.indexOf('id="live-answer"');
45 expect(at).toBeGreaterThan(-1);
46 const end = page.indexOf("</section>", at);
47 return end === -1 ? page.slice(at, at + 300) : page.slice(at, end + 10);
48 };
49
50 const tell = (who: string, text: string) =>
51 fetch(`${servers.url}/acme/notes/tell`, {
52 method: "POST",
53 headers: { cookie: cookies[who]!, origin: servers.url },
54 body: new URLSearchParams({ text }),
55 redirect: "manual",
56 });
57
58 const lastTell = (who: string): Issue =>
59 listIssues(app.db, repo.id, { kind: "issue", state: "all", author: who, limit: 1 })[0]!;
60
61 const crewSays = (issue: Issue, body: string) =>
62 addComment(app.db, {
63 issueId: issue.id,
64 authorId: getUserByName(app.db, "scout")!.id,
65 body,
66 });
67
68 beforeAll(async () => {
69 dir = await mkdtemp(join(tmpdir(), "forge-client-tell-"));
70 app = createApp({ dataDir: dir, port: 0 });
71 servers = await serve(app);
72 for (const name of ["alice", "bob", "carol"]) {
73 const made = await createUser(app.db, {
74 trusted: true,
75 username: name,
76 email: `${name}@forge.local`,
77 password: "a-good-passphrase",
78 adminIfFirst: name === "alice",
79 });
80 if (!made.ok) throw new Error(made.error);
81 users[name] = made.value;
82 cookies[name] = (
83 (
84 await fetch(`${servers.url}/signin`, {
85 method: "POST",
86 body: new URLSearchParams({ username: name, password: "a-good-passphrase" }),
87 redirect: "manual",
88 })
89 ).headers.get("set-cookie") ?? ""
90 ).split(";")[0]!;
91 }
92 // The client, bob, can write to an org's app without owning it; carol
93 // is signed in but on no team, and the app is public so she can look.
94 const org = createOrg(app.db, "acme", users.alice!.id);
95 if (!org.ok) throw new Error(String(org.error));
96 const writers = createTeam(app.db, org.value.id, "Writers", "write");
97 if (!writers.ok) throw new Error(String(writers.error));
98 addTeamMember(app.db, writers.value, users.bob!.id);
99 const made = await createRepo(app.db, app.reposRoot, {
100 ownerId: org.value.id,
101 name: "notes",
102 visibility: "public",
103 });
104 if (!made.ok) throw new Error(String(made.error));
105 repo = made.value;
106 const enabled = await enableApp(app, users.alice!, repo, { slug: "notes" });
107 if (!enabled.ok) throw new Error(String(enabled.error));
108 const scout = await createAgent(app, users.alice!, { username: "scout" });
109 if (!scout.ok) throw new Error(String(scout.error));
110 expect(addToCrew(app, users.alice!, repo, "scout").ok).toBe(true);
111 }, 30_000);
112
113 afterAll(async () => {
114 servers.stop();
115 app.close();
116 await rm(dir, { recursive: true, force: true });
117 });
118
119 test("a client who can write but does not own the app tells, is answered, escaped", async () => {
120 expect(await get("bob")).not.toContain("You told the crew");
121
122 const told = await tell("bob", "Make the title bigger");
123 expect(told.status).toBe(303);
124 expect(told.headers.get("location")).toBe("/acme/notes");
125
126 const waiting = await get("bob");
127 expect(waiting).toContain("You told the crew");
128 expect(waiting).toContain("Make the title bigger");
129 expect(waiting).toContain("No answer yet");
130
131 const issue = lastTell("bob");
132 crewSays(issue, "Done: the title is <b>bigger</b> now.");
133 const answered = await get("bob");
134 expect(answered).toContain("scout answered");
135 expect(answered).toContain("Done: the title is &lt;b&gt;bigger&lt;/b&gt; now.");
136 expect(answered).not.toContain("<b>bigger</b>");
137 expect(answered).not.toContain("No answer yet");
138 expect(answered).toContain(`/acme/notes/tells/${issue.number}`);
139 expect(answered).toContain('href="/acme/notes/tells"');
140 expect(answered).not.toContain('style="white-space');
141 });
142
143 test("a guest and a signed-in stranger see no card, and nobody sees another's tell", async () => {
144 for (const who of ["guest", "carol", "alice"]) {
145 const region = await card(who).catch(() => "");
146 for (const text of [region, await get(who, "/acme/notes/app/answer")]) {
147 expect(text).not.toContain("You told the crew");
148 expect(text).not.toContain("Make the title bigger");
149 expect(text).not.toContain("Done: the title");
150 }
151 }
152 await tell("alice", "Add a footer");
153 const alice = await card("alice");
154 expect(alice).toContain("Add a footer");
155 expect(alice).not.toContain("Make the title bigger");
156 expect(alice).not.toContain("Done: the title");
157 expect(await card("bob")).not.toContain("Add a footer");
158 });
159
160 test("the card is a live region with its own address that answers with the card alone", async () => {
161 const page = await get("bob");
162 expect(page).toContain('id="live-answer"');
163 expect(page).toContain('data-live="issue.opened,issue.commented,issue.edited"');
164 expect(page).toContain('data-live-src="/acme/notes/app/answer"');
165 const fragment = await get("bob", "/acme/notes/app/answer");
166 expect(fragment).toContain("Make the title bigger");
167 expect(fragment).not.toContain("<html");
168 const missing = await fetch(`${servers.url}/acme/nope/app/answer`);
169 expect(missing.status).toBe(404);
170 });
171
172 test("a second tell is the one shown, and the first stays one link away", async () => {
173 const first = lastTell("bob");
174 await tell("bob", "And make it blue");
175 const second = lastTell("bob");
176 expect(second.number).toBeGreaterThan(first.number);
177 const page = await card("bob");
178 expect(page).toContain("And make it blue");
179 expect(page).not.toContain("Make the title bigger");
180 expect(page).toContain("No answer yet");
181 expect(page).toContain(`/acme/notes/tells/${second.number}`);
182 expect(page).toContain('href="/acme/notes/tells"');
183 expect(toldAnswer(app.db, repo, users.bob)!.issue.id).toBe(second.id);
184 });
185
186 test("the terminal reads the same card, with the same gate", () => {
187 const bob = toldLines(app.db, repo, users.bob).join("\n");
188 expect(bob).toContain("You told the crew");
189 expect(bob).toContain("And make it blue");
190 expect(bob).toContain("No answer yet");
191 expect(bob).not.toContain("Add a footer");
192 crewSays(lastTell("bob"), "Blue it is.\u001b[31m");
193 const answered = toldLines(app.db, repo, users.bob).join("\n");
194 expect(answered).toContain("scout answered");
195 expect(answered).toContain("Blue it is.");
196 expect(answered).not.toContain("\u001b");
197 expect(toldLines(app.db, repo, users.carol)).toEqual([]);
198 expect(toldLines(app.db, repo, undefined)).toEqual([]);
199 });
200 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs