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

A share can carry one sentence, so it reads as a quote #12450

Merged opened this

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

Merged

mason/forge:mason/12399-a-share-can-carry-one-sentence-so-it-rea → main 5 commits fork 1 thread · 1 unresolved

  • Merged. mason/12399-a-share-can-carry-one-sentence-so-it-rea was merged into main as d9ec9c8.

Review

Sign in to review this change.
11 files changed +261 −15
docs/FEED.md +2 −1
@@ -124,7 +124,7 @@ The `choose` card comes from `src/feed/choose.ts`, a run card offers Stop
124124
125125 ## Sharing (`src/feed/share.ts`, `core/shares.ts`)
126126
127 `POST /api/v1/share` `{ item, to? }` (`rw`, same-origin for sessions) and the
127 `POST /api/v1/share` `{ item, to?, note? }` (`rw`, same-origin for sessions) and the
128128 MCP tool `share` are one verb. `to` is up to 10 usernames. The sender must
129129 see the item (it is looked up in the sender's own feed sources); the answer
130130 is `{ sent: [{ to, outcome }] }`, outcome one of `delivered queued steered
@@ -145,6 +145,7 @@ may not see the item are both `unreachable`.
145145 - **Budget:** 5 delivered a day per person. More are queued, delivered
146146 best-weighted first as room frees (checked on each feed read), and dropped
147147 after 48 hours; a waiting share's worth falls linearly with its age.
148 - **A note:** `note` is one sentence of the sharer's own, 1–280 characters, no control characters (else 400 naming the limit); the card reads "shared by X: <note>", escaped, on the page and in the terminal. It is stored once on the row and is not part of the dedupe.
148149 - **Dedupe:** one share per item per recipient, ever.
149150 - **Sender weight:** `2·(opens+1)/(shares+2)` over 90 days of delivered
150151 shares to people, clamped 0.2–2; an open is the recipient's `opened` of the
docs/MCP.md +1 −1
@@ -199,7 +199,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
199199 | `secrets` | — | Admin: list\|set\|remove sealed secrets | 248 |
200200 | `sessions` | `list`, `end`, `end_idle`, `signins`, `shells` | Where you are signed in: your tokens and browsers, never a secret; `username` for a person as owner; action end + id signs a browser out | 385 |
201201 | `sever` | — | Unlink a spawned forge from its parent, or an app from the repository it came from | 225 |
202 | `share` | — | Share a feed item: no `to` tells the app's crew and owners, else followers; budgeted | 258 |
202 | `share` | — | Share a feed item: no `to` tells the app's crew and owners, else followers; budgeted | 283 |
203203 | `signup` | — | Sign-ups: open (default); invite lets in only a person with an open invite link; closed refuses every new account | 324 |
204204 | `sizes` | — | A child forge's sizes: small, medium and large, each with CPU, memory and disk | 196 |
205205 | `snapshot_now` | — | Take a snapshot now, as Backups does (admin) | 133 |
src/core/migration-pins/20261114090000-a-share-note.pin added +1
@@ -0,0 +1,1 @@
1 c0090bf948f786ac61f0c92852ec69c867f6e50221eddc015e55334655b5c293
src/core/migrations/20261114090000-a-share-note.ts added +7
@@ -0,0 +1,7 @@
1 // A share can carry one sentence of the sharer's own (at most 280
2 // characters, checked at the boundary). NULL is no note, and every share
3 // from before has none. Stored once with the row; it is not part of the
4 // dedupe, which stays one row per item and recipient. Additive.
5 export default `
6 ALTER TABLE share ADD COLUMN note TEXT;
7 `;
src/core/shares.ts +29 −3
@@ -26,6 +26,8 @@ export interface Share {
2626 readonly kind: string;
2727 readonly link: string;
2828 readonly what: string;
29 /** The sharer's own sentence, or null. */
30 readonly note: string | null;
2931 readonly state: ShareState;
3032 readonly createdAt: string;
3133 readonly deliveredAt: string | null;
@@ -40,6 +42,7 @@ interface Row {
4042 kind: string;
4143 link: string;
4244 what: string;
45 note: string | null;
4346 state: ShareState;
4447 created_at: string;
4548 delivered_at: string | null;
@@ -54,6 +57,7 @@ const toShare = (r: Row): Share => ({
5457 kind: r.kind,
5558 link: r.link,
5659 what: r.what,
60 note: r.note,
5761 state: r.state,
5862 createdAt: r.created_at,
5963 deliveredAt: r.delivered_at,
@@ -116,9 +120,29 @@ export function senderWeight(
116120 return Math.min(WEIGHT_MAX, Math.max(WEIGHT_MIN, w));
117121 }
118122
123 export const NOTE_MAX = 280;
124
125 /**
126 * A note as given: absent is no note (null); text is trimmed and kept when
127 * it is 1–`NOTE_MAX` characters with no control character. Anything else —
128 * not text, empty after trim, too long, a control character — is `undefined`.
129 */
130 export function parseNote(raw: unknown): string | null | undefined {
131 if (raw === undefined || raw === null) return null;
132 if (typeof raw !== "string") return undefined;
133 const note = raw.trim();
134 if (note === "" || [...note].length > NOTE_MAX) return undefined;
135 // eslint-disable-next-line no-control-regex
136 if (/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/.test(note)) return undefined;
137 return note;
138 }
139
140 export const NOTE_WORDS = `note is one sentence of at most ${NOTE_MAX} characters, no line breaks or control characters`;
141
119142 export function addShare(
120143 db: Database,
121 input: Omit<Share, "id" | "state" | "createdAt" | "deliveredAt"> & {
144 input: Omit<Share, "id" | "state" | "createdAt" | "deliveredAt" | "note"> & {
145 note?: string | null;
122146 state: "delivered" | "queued";
123147 at: number;
124148 },
@@ -132,13 +156,14 @@ export function addShare(
132156 kind: input.kind,
133157 link: input.link,
134158 what: input.what,
159 note: input.note ?? null,
135160 state: input.state,
136161 created_at: iso(input.at),
137162 delivered_at: input.state === "delivered" ? iso(input.at) : null,
138163 };
139164 db.query(
140 `INSERT INTO share (id, item_id, sender_id, recipient_id, repo_id, kind, link, what, state, created_at, delivered_at)
141 VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11)`,
165 `INSERT INTO share (id, item_id, sender_id, recipient_id, repo_id, kind, link, what, note, state, created_at, delivered_at)
166 VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12)`,
142167 ).run(
143168 row.id,
144169 row.item_id,
@@ -148,6 +173,7 @@ export function addShare(
148173 row.kind,
149174 row.link,
150175 row.what,
176 row.note,
151177 row.state,
152178 row.created_at,
153179 row.delivered_at,
src/feed/feed.ts +1 −1
@@ -270,7 +270,7 @@ function sharedCandidates(
270270 link: s.link,
271271 what: s.what,
272272 urgency: SHARE_BOOST * senderWeight(db, sender.id, now),
273 said: `shared by ${sender.username}: ${s.what}`,
273 said: `shared by ${sender.username}: ${s.note ?? s.what}`,

This carries the note, but src/tui/screens/feed.ts:168 renders item.what and ignores reason, so the terminal never shows it. Render the reason there and test it.

274274 });
275275 }
276276 return out;
src/feed/share.ts +9 −5
@@ -89,6 +89,7 @@ export async function share(
8989 itemId: string,
9090 to: readonly string[] = [],
9191 now = Date.now(),
92 note: string | null = null,
9293 ): Promise<
9394 | { ok: true; value: { sent: Sent[]; item: Candidate } }
9495 | { ok: false; error: ShareError }
@@ -145,7 +146,7 @@ export async function share(
145146 continue;
146147 }
147148 if (w.kind === "agent") {
148 mine(await steer(app, sender, w, repo, item));
149 mine(await steer(app, sender, w, repo, item, note));
149150 continue;
150151 }
151152 if (!muted.has(w.id)) muted.set(w.id, mutedRepos(db, w.id));
@@ -163,6 +164,7 @@ export async function share(
163164 kind: item.kind,
164165 link: item.link,
165166 what: words(item),
167 note,
166168 state: room ? "delivered" : "queued",
167169 at: now,
168170 });
@@ -191,27 +193,28 @@ async function steer(
191193 agent: User,
192194 repo: NonNullable<ReturnType<typeof getRepoById>>,
193195 item: Candidate,
196 note: string | null,
194197 ): Promise<Outcome> {
195 const text = `Shared by ${sender.username} with ${agent.username}: ${words(item)} (${item.link})`;
198 const text = `Shared by ${sender.username} with ${agent.username}: ${note ?? words(item)} (${item.link})`;
196199 const number = /\/pulls\/(\d+)$/.exec(item.link)?.[1];
197200 const issue =
198201 number === undefined ? undefined : getIssue(app.db, repo.id, Number(number));
199202 if (issue !== undefined) {
200203 const said = await addCommentThrough(app, sender, repo, issue, text);
201204 if (said.ok) {
202 markSent(app, item, agent, sender);
205 markSent(app, item, agent, sender, note);
203206 return "steered";
204207 }
205208 return "unreachable";
206209 }
207210 const told = await tell(app, sender, repo, text);
208211 if (!told.ok) return "unreachable";
209 markSent(app, item, agent, sender);
212 markSent(app, item, agent, sender, note);
210213 return "told";
211214 }
212215
213216 /** An agent has no feed; the row only keeps it from being steered twice. */
214 function markSent(app: App, item: Candidate, agent: User, sender: User): void {
217 function markSent(app: App, item: Candidate, agent: User, sender: User, note: string | null): void {
215218 addShare(app.db, {
216219 itemId: item.id,
217220 senderId: sender.id,
@@ -220,6 +223,7 @@ function markSent(app: App, item: Candidate, agent: User, sender: User): void {
220223 kind: item.kind,
221224 link: item.link,
222225 what: words(item),
226 note,
223227 state: "delivered",
224228 at: Date.now(),
225229 });
src/http/feed.ts +4 −2
@@ -22,7 +22,7 @@ import {
2222 import { chipsOf, isKindChip, setChip } from "../core/feed_chips.ts";
2323 import { CURSOR_NOT_ISSUED, KIND_HAS_NO_CHIP } from "../actions/feed_words.ts";
2424 import { getUserByName, getUsersByIds } from "../core/users.ts";
25 import { drainQueue } from "../core/shares.ts";
25 import { drainQueue, NOTE_WORDS, parseNote } from "../core/shares.ts";
2626 import { feedTag, hasQueuedShares } from "../feed/feed_tag.ts";
2727 import { lastVisit } from "../core/home_visit.ts";
2828 import { feedDigest } from "../web/studio/since.ts";
@@ -367,7 +367,9 @@ export function feedRoutes(router: Router<Handler>): void {
367367 422,
368368 `to is up to ${RECIPIENTS_MAX} usernames`,
369369 );
370 const made = await share(ctx.app, ctx.auth.user!, itemId, to);
370 const note = parseNote(input.note);
371 if (note === undefined) return apiError("invalid_note", 400, NOTE_WORDS);
372 const made = await share(ctx.app, ctx.auth.user!, itemId, to, Date.now(), note);
371373 if (!made.ok) return notFound();
372374 return json({ sent: made.value.sent }, 201);
373375 });
src/http/mcp/tools/share.ts +6 −2
@@ -1,11 +1,12 @@
11 import { ITEM_ID } from "../../../core/interactions.ts";
2 import { NOTE_MAX, NOTE_WORDS, parseNote } from "../../../core/shares.ts";
23 import { share } from "../../../feed/share.ts";
34 import { parseTargets } from "../../feed.ts";
45 import { good, bad, type Tool, str } from "../shared.ts";
56
67 export const tool: Tool = {
78 name: "share",
8 doc: "`{ item, to? }`: share a feed item (`item` is its id); with no `to` it goes to the app's crew and owners, else to up to 10 named usernames' followers; a daily budget each; answers `{ sent }`",
9 doc: "`{ item, to?, note? }`: share a feed item (`item` is its id); with no `to` it goes to the app's crew and owners, else to up to 10 named usernames' followers; a daily budget each; `note` is one sentence of at most 280 characters shown on the recipient's card as \"shared by you: note\"; answers `{ sent }`",
910 description:
1011 "Share a feed item: no `to` tells the app's crew and owners, else followers; budgeted.",
1112 inputSchema: {
@@ -17,6 +18,7 @@ export const tool: Tool = {
1718 items: { type: "string" },
1819 maxItems: 10,
1920 },
21 note: { type: "string", maxLength: NOTE_MAX },
2022 },
2123 required: ["item"],
2224 },
@@ -26,7 +28,9 @@ export const tool: Tool = {
2628 const to = parseTargets(args["to"]);
2729 if (!ITEM_ID.test(item) || to === undefined)
2830 return bad("invalid", "item is a feed item id; to is up to 10 usernames");
29 const made = await share(ctx.app, user, item, to);
31 const note = parseNote(args["note"]);
32 if (note === undefined) return bad("invalid", NOTE_WORDS);
33 const made = await share(ctx.app, user, item, to, Date.now(), note);
3034 if (!made.ok) return bad("not_found", "no such item");
3135 return good({ sent: made.value.sent });
3236 },
test/feed-share.test.ts added +131
@@ -0,0 +1,131 @@
1 /**
2 * A share can carry one sentence (#12399): shown escaped, limited at the boundary, not part of
3 * the dedupe.
4 */
5 import { afterAll, beforeAll, describe, 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 { createApp, type App } from "../src/app.ts";
10 import { createRepo } from "../src/actions/repos.ts";
11 import type { Repo } from "../src/core/repos.ts";
12 import { NOTE_MAX, parseNote } from "../src/core/shares.ts";
13 import { createToken } from "../src/core/tokens.ts";
14 import { createUser, type User } from "../src/core/users.ts";
15 import { readFeed } from "../src/feed/feed.ts";
16 import { share } from "../src/feed/share.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { feedCard } from "../src/web/studio/feed.ts";
19 import { promote } from "./helpers/members.ts";
20
21 describe("share note", () => {
22 let dataDir: string;
23 let app: App;
24 let servers: Servers;
25 let alice: User;
26 let bob: User;
27 let carol: User;
28 let aliceToken: string;
29 let repo: Repo;
30 let n = 0;
31 const emit = () =>
32 `event:${app.bus.append({
33 kind: "run.finished",
34 repoId: repo.id,
35 actorId: alice.id,
36 payload: { kind: "deploy", state: "ok", summary: `run ${++n}`, runId: `r${n}` },
37 }).id}`;
38
39 beforeAll(async () => {
40 dataDir = await mkdtemp(join(tmpdir(), "forge-share-note-"));
41 app = createApp({ dataDir, port: 0 });
42 servers = await serve(app);
43 const mk = async (username: string, first = false) => {
44 const r = await createUser(app.db, { origin: "seed", trusted: true, username, allowReserved: true,
45 email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first });
46 if (!r.ok) throw new Error(r.error);
47 promote(app.db, r.value);
48 return r.value;
49 };
50 await mk("root", true);
51 alice = await mk("alice");
52 bob = await mk("bob");
53 carol = await mk("carol");
54 aliceToken = createToken(app.db, alice.id, "t", "rw").token;
55 const o = await createRepo(app, alice, { name: "open", visibility: "public" });
56 if (!o.ok) throw new Error("repo");
57 repo = o.value;
58 });
59
60 afterAll(async () => {
61 servers.stop();
62 app.close();
63 await rm(dataDir, { recursive: true, force: true });
64 });
65
66 test("the note shows on the recipient's card, escaped", async () => {
67 const item = emit();
68 const made = await share(app, alice, item, ["bob"], Date.now(), "<script>alert(1)</script> read this");
69 expect(made.ok).toBe(true);
70 const hit = readFeed(app.db, bob).items.find((i) => i.id.startsWith("share:"))!;
71 expect(hit.reason).toBe("shared by alice: <script>alert(1)</script> read this");
72 const html = feedCard(hit).text;
73 expect(html).toContain("shared by alice: &lt;script&gt;alert(1)&lt;/script&gt; read this");
74 expect(html).not.toContain("<script>alert");
75 });
76
77 test("a share with no note reads as before, and the note is not part of the dedupe", async () => {
78 const item = emit();
79 await share(app, alice, item, ["carol"]);
80 const plain = readFeed(app.db, carol).items.find((i) => i.id.startsWith("share:"))!;
81 expect(plain.reason).toStartWith("shared by alice: ");
82 expect(plain.reason).not.toContain("null");
83 const again = await share(app, alice, item, ["carol"], Date.now(), "second try");
84 if (!again.ok) throw new Error(again.error);
85 expect(again.value.sent).toEqual([{ to: "carol", outcome: "duplicate" }]);
86 expect(app.db.query("SELECT COUNT(*) AS n FROM share WHERE item_id = ?1").get(item)).toEqual({ n: 1 });
87 });
88
89 test("the note is read at the boundary", () => {
90 expect(parseNote(undefined)).toBeNull();
91 expect(parseNote(" hi ")).toBe("hi");
92 expect(parseNote("a".repeat(NOTE_MAX))).toHaveLength(NOTE_MAX);
93 expect(parseNote("a".repeat(NOTE_MAX + 1))).toBeUndefined();
94 expect(parseNote(" ")).toBeUndefined();
95 expect(parseNote("")).toBeUndefined();
96 expect(parseNote("a\nb")).toBeUndefined();
97 expect(parseNote("a\u0007b")).toBeUndefined();
98 expect(parseNote(5)).toBeUndefined();
99 });
100
101 test("the route answers 400 naming the limit, and keeps the note", async () => {
102 const post = (payload: unknown) =>
103 fetch(`${servers.url}/api/v1/share`, {
104 method: "POST",
105 headers: { authorization: `Bearer ${aliceToken}`, "content-type": "application/json" },
106 body: JSON.stringify(payload),
107 });
108 const item = emit();
109 for (const note of ["a".repeat(NOTE_MAX + 1), " ", "x\u0000y"]) {
110 const r = await post({ item, to: ["bob"], note });
111 expect(r.status).toBe(400);
112 expect(await r.text()).toContain("280");
113 }
114 expect((await post({ item, to: ["bob"], note: "worth a look" })).status).toBe(201);
115 const row = app.db.query<{ note: string }, [string]>("SELECT note FROM share WHERE item_id = ?1").get(item);
116 expect(row?.note).toBe("worth a look");
117 });
118
119 test("the MCP tool takes a note and refuses a long one", async () => {
120 const call = async (args: object) =>
121 (await fetch(`${servers.url}/mcp`, {
122 method: "POST",
123 headers: { authorization: `Bearer ${aliceToken}`, "content-type": "application/json", accept: "application/json, text/event-stream" },
124 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "share", arguments: args } }),
125 })).text();
126 const item = emit();
127 expect(await call({ item, to: ["bob"], note: "a".repeat(NOTE_MAX + 1) })).toContain("280");
128 await call({ item, to: ["bob"], note: "via mcp" });
129 expect(app.db.query<{ note: string }, [string]>("SELECT note FROM share WHERE item_id = ?1").get(item)?.note).toBe("via mcp");
130 });
131 });
test/tui-feed-share-note.test.ts added +70
@@ -0,0 +1,70 @@
1 /** The terminal's feed shows a share's note as plain text on one row (#12399). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createRepo } from "../src/actions/repos.ts";
7 import { createApp, type App as Forge } from "../src/app.ts";
8 import type { Repo } from "../src/core/repos.ts";
9 import { createUser, type User } from "../src/core/users.ts";
10 import { share } from "../src/feed/share.ts";
11 import { createForgeApp } from "../src/tui/forge.ts";
12 import { feedScreen } from "../src/tui/screens/feed.ts";
13 import { headlessTerminal } from "../src/tui/term/terminal.ts";
14 import { quietLogs } from "./helpers/globals.ts";
15 import { promote } from "./helpers/members.ts";
16 import { settleApp } from "./helpers/tui.ts";
17
18 quietLogs();
19
20 let dataDir: string;
21 let forge: Forge;
22 let alice: User;
23 let bob: User;
24 let repo: Repo;
25
26 beforeAll(async () => {
27 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-share-note-"));
28 forge = createApp({ dataDir, port: 0 });
29 const mk = async (username: string, first = false) => {
30 const r = await createUser(forge.db, { origin: "seed", trusted: true, username, allowReserved: true,
31 email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first });
32 if (!r.ok) throw new Error(r.error);
33 promote(forge.db, r.value);
34 return r.value;
35 };
36 await mk("root", true);
37 alice = await mk("alice");
38 bob = await mk("bob");
39 const o = await createRepo(forge, alice, { name: "open", visibility: "public" });
40 if (!o.ok) throw new Error("repo");
41 repo = o.value;
42 });
43
44 afterAll(async () => {
45 forge.close();
46 await rm(dataDir, { recursive: true, force: true });
47 });
48
49 test("a shared item's note is on the recipient's terminal row, as plain text on one line", async () => {
50 const ev = forge.bus.append({
51 kind: "run.finished",
52 repoId: repo.id,
53 actorId: alice.id,
54 payload: { kind: "deploy", state: "ok", summary: "run 1", runId: "r1" },
55 });
56 const made = await share(forge, alice, `event:${ev.id}`, ["bob"], Date.now(), "<script>x</script>\nread this");
57 expect(made.ok).toBe(true);
58 const { app, session } = createForgeApp(
59 forge,
60 { sshUsername: "bob", remoteAddress: "127.0.0.1", user: bob },
61 { terminal: headlessTerminal(140, 44), exitHooks: false },
62 );
63 app.start();
64 await settleApp(app);
65 app.push(feedScreen(session, app.ctx));
66 await settleApp(app);
67 const text = app.screen.toText();
68 app.stop();
69 expect(text).toContain("shared by alice: <script>x</script> read this");
70 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs