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

Reply and like on a post are git primitives: a reply is a comment on its issue or pull, a like is a signal in the decision ledger #1041

Closed opened this in answer to
Closed without merging

scout/forge:scout/602-reply-and-like-on-a-post-are-git-primiti → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
12 files changed +577 −16
docs/FEED.md +13
@@ -89,6 +89,19 @@ a card, and paging past the first 20.
8989 updating the kept `/` from live swaps (it is the page as last navigated),
9090 swipes (no swipe UI yet), push, and anything native.
9191
92 ## Reply and like (`src/feed/react.ts`)
93
94 Under a post that is an issue or a pull: **Reply**, **Like**, **Share** (the
95 repost below). Same words for a person and an agent: `POST /api/v1/reply
96 { app, issue|pull, body }` and `POST /api/v1/like { app, issue|pull }`, and the
97 MCP tools `reply` and `like` (`repo` for `app`). A reply is a comment on that
98 issue or pull, so it comes back as a reply post. A like is a `like` row in the
99 decision ledger (`by` is who), toggled: liking again deletes it. Answer is
100 `{ liked, count }`. The crew's decision listings and sums leave likes out; the
101 feed's affinity reads them (weight 3, halved weekly, for the app and the
102 author). Keys on a card: `l` like, `s` share. Posts that are not an issue or a
103 pull (a run, a cost) keep the steer form instead.
104
92105 ## Sharing (`src/feed/share.ts`, `core/shares.ts`)
93106
94107 `POST /api/v1/share` `{ item, to? }` (`rw`, same-origin for sessions) and the
src/core/decisions.ts +84 −5
@@ -15,8 +15,18 @@ import { id as newId } from "../kernel/id.ts";
1515 *
1616 * `lean` was which option on a studio ask card a careful owner would pick.
1717 * Nothing records one any more; older ledgers still hold rows of it, and the
18 * summaries that read them keep the word. */
19 export type DecisionKind = "next" | "land" | "retry" | "lean" | "guard";
18 * summaries that read them keep the word.
19 *
20 * `like` is a person's or an agent's signal on an issue or a pull (`by` is
21 * who): one row each, written by `toggleLike` and deleted by it. It is not
22 * a decision the crew made, so the crew's listings and sums leave it out. */
23 export type DecisionKind =
24 | "next"
25 | "land"
26 | "retry"
27 | "lean"
28 | "guard"
29 | "like";
2030
2131 export interface Decision {
2232 readonly id: string;
@@ -183,7 +193,7 @@ export function listDecisions(
183193 .query<
184194 Row,
185195 [string, number]
186 >("SELECT * FROM decision WHERE repo_id = ?1 ORDER BY created_at DESC, id DESC LIMIT ?2")
196 >("SELECT * FROM decision WHERE repo_id = ?1 AND kind != 'like' ORDER BY created_at DESC, id DESC LIMIT ?2")
187197 .all(repoId, limit)
188198 : db
189199 .query<
@@ -208,7 +218,7 @@ export function listDecisionsForRepos(
208218 // would crowd out the decisions a person reads (`crew/guard.ts`).
209219 `SELECT * FROM decision
210220 WHERE repo_id IN (${unique.map((_, n) => `?${n + 1}`).join(",")})
211 AND kind != 'guard'
221 AND kind NOT IN ('guard', 'like')
212222 ORDER BY created_at DESC, id DESC LIMIT ?${unique.length + 1}`,
213223 )
214224 .all(...unique, Math.min(500, Math.max(1, limit)))
@@ -242,7 +252,7 @@ export function decisionStats(
242252 [string, string]
243253 >(
244254 `SELECT kind, answer, by, outcome, COUNT(*) AS n FROM decision
245 WHERE repo_id = ?1 AND created_at >= ?2 GROUP BY kind, answer, by, outcome`,
255 WHERE repo_id = ?1 AND created_at >= ?2 AND kind != 'like' GROUP BY kind, answer, by, outcome`,
246256 )
247257 .all(repoId, since);
248258 const byKind = new Map<
@@ -291,3 +301,72 @@ export function listDecidedIn(
291301 .all(limit, ...repoIds)
292302 .map(toDecision);
293303 }
304
305 /**
306 * Like an issue or a pull, or take the like back: one `like` row for each
307 * (who, issue). Returns whether it stands now, and how many there are.
308 */
309 export function toggleLike(
310 db: Database,
311 by: string,
312 repoId: string,
313 issueId: string,
314 ): { liked: boolean; count: number } {
315 const gone = db
316 .query("DELETE FROM decision WHERE kind = 'like' AND issue_id = ?1 AND by = ?2")
317 .run(issueId, by).changes;
318 if (gone === 0)
319 recordDecision(db, {
320 kind: "like",
321 repoId,
322 issueId,
323 state: {},
324 answer: "like",
325 p: 1,
326 by,
327 ms: 0,
328 });
329 return { liked: gone === 0, count: likeCounts(db, [issueId], by).get(issueId)!.count };
330 }
331
332 /** Likes for each issue: how many, and whether `by` is one of them. */
333 export function likeCounts(
334 db: Database,
335 issueIds: readonly string[],
336 by: string,
337 ): Map<string, { count: number; mine: boolean }> {
338 const out = new Map(issueIds.map((i) => [i, { count: 0, mine: false }]));
339 const unique = [...out.keys()];
340 for (let i = 0; i < unique.length; i += 400) {
341 const batch = unique.slice(i, i + 400);
342 const rows = db
343 .query<{ issue_id: string; by: string }, string[]>(
344 `SELECT issue_id, by FROM decision WHERE kind = 'like'
345 AND issue_id IN (${batch.map((_, n) => `?${n + 1}`).join(",")})`,
346 )
347 .all(...batch);
348 for (const r of rows) {
349 const c = out.get(r.issue_id)!;
350 c.count += 1;
351 if (r.by === by) c.mine = true;
352 }
353 }
354 return out;
355 }
356
357 /** What `by` has liked, newest first: the repository and the issue's author. */
358 export function likedBy(
359 db: Database,
360 by: string,
361 limit = 200,
362 ): { repoId: string; authorId: string | null; at: string }[] {
363 return db
364 .query<{ repo_id: string; author_id: string | null; created_at: string }, [string, number]>(
365 `SELECT decision.repo_id, issue.author_id, decision.created_at FROM decision
366 LEFT JOIN issue ON issue.id = decision.issue_id
367 WHERE decision.kind = 'like' AND decision.by = ?1
368 ORDER BY decision.created_at DESC LIMIT ?2`,
369 )
370 .all(by, limit)
371 .map((r) => ({ repoId: r.repo_id, authorId: r.author_id, at: r.created_at }));
372 }
src/feed/affinity.ts +11 −1
@@ -7,7 +7,7 @@
77 */
88
99 import type { Database } from "bun:sqlite";
10 import { listDecidedIn } from "../core/decisions.ts";
10 import { likedBy, listDecidedIn } from "../core/decisions.ts";
1111 import type { InteractionKind } from "../core/interactions.ts";
1212 import { listInteractions } from "../core/interactions.ts";
1313 import { getPull } from "../core/pulls.ts";
@@ -28,6 +28,7 @@ export type Why =
2828 | "proposed"
2929 | "told"
3030 | "decided"
31 | "liked"
3132 | InteractionKind;
3233
3334 /** What each interaction is worth. Negatives outweigh the positives. */
@@ -43,6 +44,9 @@ export const INTERACTION_WEIGHT: Readonly<Record<InteractionKind, number>> = {
4344 muted: -8,
4445 };
4546
47 /** A like is a person saying "more of this": worth more than opening it. */
48 export const LIKE_WEIGHT = 3;
49
4650 export interface Weighted {
4751 readonly score: number;
4852 /** The part with the largest size, and when it last counted. */
@@ -148,6 +152,12 @@ export function affinityFor(
148152 if (d.outcome === "shipped")
149153 aff.add(`app:${d.repoId}`, "decided", decay(now - at), at);
150154 }
155 for (const l of likedBy(db, viewer.username)) {
156 const at = Date.parse(l.at);
157 const w = LIKE_WEIGHT * decay(now - at);
158 aff.add(`app:${l.repoId}`, "liked", w, at);
159 if (l.authorId !== null) aff.add(`actor:${l.authorId}`, "liked", w, at);
160 }
151161 for (const i of listInteractions(db, viewer.id)) {
152162 const at = Date.parse(i.createdAt);
153163 const w = INTERACTION_WEIGHT[i.kind] * decay(now - at);
src/feed/rank.ts +1
@@ -58,6 +58,7 @@ const VERB: Partial<Record<Why, string>> = {
5858 steered: "steered",
5959 swiped: "swiped through",
6060 shared: "shared",
61 liked: "liked",
6162 };
6263
6364 function affinityReason(c: Candidate, app: Weighted, actor: Weighted, now: number): string {
src/feed/react.ts added +91
@@ -0,0 +1,91 @@
1 /**
2 * The two small answers under a post: `reply` (a comment on its issue or
3 * pull) and `like` (a signal in the decision ledger, `core/decisions.ts`).
4 * A post is named the way a person and an agent both can: an app, and the
5 * number of an issue or of a pull. Reading it takes the same access the
6 * issue's page does.
7 */
8
9 import type { App } from "../app.ts";
10 import { addCommentThrough } from "../actions/issues.ts";
11 import { toggleLike } from "../core/decisions.ts";
12 import { getIssue, type Issue } from "../core/issues.ts";
13 import { canRead, getRepo, type Repo } from "../core/repos.ts";
14 import { mayView } from "../core/sealed.ts";
15 import type { User } from "../core/users.ts";
16
17 export interface PostRef {
18 readonly app: string;
19 readonly issue?: unknown;
20 readonly pull?: unknown;
21 }
22
23 export type ReactError = "not_found" | "invalid" | "refused";
24
25 /** The number a feed link points at, when it points at an issue or a pull. */
26 export function numberOfLink(link: string): number | undefined {
27 const m = /\/(?:tells|changes)\/(\d+)$/.exec(link);
28 return m ? Number(m[1]) : undefined;
29 }
30
31 /** The issue or pull a reference names, if this viewer may see it. */
32 export function findPost(
33 app: App,
34 viewer: User,
35 ref: PostRef,
36 ):
37 | { ok: true; repo: Repo; issue: Issue }
38 | { ok: false; error: ReactError } {
39 const wantsPull = ref.pull !== undefined;
40 const n = wantsPull ? ref.pull : ref.issue;
41 if ((ref.issue === undefined) === !wantsPull)
42 return { ok: false, error: "invalid" };
43 if (typeof n !== "number" || !Number.isInteger(n) || n < 1)
44 return { ok: false, error: "invalid" };
45 const [owner, name, extra] = ref.app.split("/");
46 const repo =
47 owner && name && extra === undefined
48 ? getRepo(app.db, owner, name)
49 : undefined;
50 if (!repo || !canRead(app.db, repo, viewer))
51 return { ok: false, error: "not_found" };
52 const issue = getIssue(app.db, repo.id, n);
53 if (
54 !issue ||
55 issue.kind !== (wantsPull ? "pull" : "issue") ||
56 !mayView(app.db, repo, issue, viewer)
57 )
58 return { ok: false, error: "not_found" };
59 return { ok: true, repo, issue };
60 }
61
62 export async function reply(
63 app: App,
64 viewer: User,
65 ref: PostRef,
66 body: string,
67 ): Promise<{ ok: true; value: { number: number } } | { ok: false; error: ReactError }> {
68 const text = body.trim();
69 if (text === "" || text.length > 8000) return { ok: false, error: "invalid" };
70 const post = findPost(app, viewer, ref);
71 if (!post.ok) return post;
72 const said = await addCommentThrough(app, viewer, post.repo, post.issue, text);
73 return said.ok
74 ? { ok: true, value: { number: post.issue.number } }
75 : { ok: false, error: "refused" };
76 }
77
78 export function like(
79 app: App,
80 viewer: User,
81 ref: PostRef,
82 ):
83 | { ok: true; value: { liked: boolean; count: number } }
84 | { ok: false; error: ReactError } {
85 const post = findPost(app, viewer, ref);
86 if (!post.ok) return post;
87 return {
88 ok: true,
89 value: toggleLike(app.db, viewer.username, post.repo.id, post.issue.id),
90 };
91 }
src/http/feed.ts +37
@@ -12,6 +12,7 @@ import {
1212 isInteractionKind,
1313 recordInteraction,
1414 } from "../core/interactions.ts";
15 import { like, reply } from "../feed/react.ts";
1516 import { share, RECIPIENTS_MAX } from "../feed/share.ts";
1617 import { canRead, getRepo, getRepoById } from "../core/repos.ts";
1718 import {
@@ -170,6 +171,34 @@ export function feedRoutes(router: Router<Handler>): void {
170171 return json({ issue: told.value.issue.number }, 201);
171172 });
172173
174 // Reply and like: the words an agent has too (MCP `reply`, `like`).
175 router.add("POST", "/api/v1/reply", async (ctx) => {
176 const denied = requireScope(ctx, "rw");
177 if (denied) return denied;
178 const input = await body(ctx.request);
179 const made = await reply(
180 ctx.app,
181 ctx.auth.user!,
182 { app: str(input.app), issue: input.issue, pull: input.pull },
183 str(input.body),
184 );
185 if (!made.ok) return reactError(made.error);
186 return json({ number: made.value.number }, 201);
187 });
188
189 router.add("POST", "/api/v1/like", async (ctx) => {
190 const denied = requireScope(ctx, "rw");
191 if (denied) return denied;
192 const input = await body(ctx.request);
193 const made = like(ctx.app, ctx.auth.user!, {
194 app: str(input.app),
195 issue: input.issue,
196 pull: input.pull,
197 });
198 if (!made.ok) return reactError(made.error);
199 return json(made.value, 200);
200 });
201
173202 router.add("POST", "/api/v1/share", async (ctx) => {
174203 const denied = requireScope(ctx, "rw");
175204 if (denied) return denied;
@@ -190,6 +219,14 @@ export function feedRoutes(router: Router<Handler>): void {
190219 });
191220 }
192221
222 function reactError(error: "not_found" | "invalid" | "refused"): Response {
223 return error === "not_found"
224 ? notFound()
225 : error === "refused"
226 ? apiError("refused", 403, "that could not be said here")
227 : apiError("invalid", 422, "name an app and one issue or pull; a reply is 1 to 8000 characters");
228 }
229
193230 /** `to` as a list of usernames: absent, one, or a few; anything else is no. */
194231 export function parseTargets(raw: unknown): string[] | undefined {
195232 if (raw === undefined || raw === null) return [];
src/http/mcp.ts +63
@@ -52,6 +52,7 @@ import {
5252 parseCursor,
5353 readFeed,
5454 } from "../feed/feed.ts";
55 import { like, reply } from "../feed/react.ts";
5556 import { share } from "../feed/share.ts";
5657 import { parseTargets } from "./feed.ts";
5758 import { appsRuntime, envsFor } from "../apps/runtime.ts";
@@ -326,6 +327,68 @@ const TOOLS: readonly Tool[] = [
326327 return good({ sent: made.value.sent });
327328 },
328329 },
330 {
331 name: "reply",
332 description:
333 "Reply under a post: a comment on its issue or its pull. Name the app and one of `issue` or `pull` by number.",
334 inputSchema: {
335 type: "object",
336 properties: {
337 repo: REPO_ARG,
338 issue: { type: "integer", minimum: 1 },
339 pull: { type: "integer", minimum: 1 },
340 body: { type: "string", maxLength: 8000 },
341 },
342 required: ["repo", "body"],
343 },
344 writes: true,
345 async run(ctx, user, args) {
346 const made = await reply(
347 ctx.app,
348 user,
349 { app: str(args["repo"]), issue: args["issue"], pull: args["pull"] },
350 str(args["body"]),
351 );
352 if (made.ok) return good({ says: `Replied on #${made.value.number}.` });
353 return bad(
354 made.error,
355 made.error === "not_found"
356 ? "no such issue or pull"
357 : made.error === "invalid"
358 ? "name the repo and one of issue or pull; body is 1 to 8000 characters"
359 : "that could not be said here",
360 );
361 },
362 },
363 {
364 name: "like",
365 description:
366 "Like an issue or a pull, or take the like back (it toggles). The like is a signal in the decision ledger; the crew and your feed read it.",
367 inputSchema: {
368 type: "object",
369 properties: {
370 repo: REPO_ARG,
371 issue: { type: "integer", minimum: 1 },
372 pull: { type: "integer", minimum: 1 },
373 },
374 required: ["repo"],
375 },
376 writes: true,
377 run(ctx, user, args) {
378 const made = like(ctx.app, user, {
379 app: str(args["repo"]),
380 issue: args["issue"],
381 pull: args["pull"],
382 });
383 if (made.ok) return good(made.value);
384 return bad(
385 made.error,
386 made.error === "not_found"
387 ? "no such issue or pull"
388 : "name the repo and one of issue or pull",
389 );
390 },
391 },
329392 {
330393 name: "say",
331394 description:
src/web/pages/board.ts +1
@@ -115,6 +115,7 @@ const KIND_WORDS: Record<DecisionKind, string> = {
115115 lean: "which way",
116116 // Never listed (`listDecisionsForRepos` leaves guards out); named for the type.
117117 guard: "not started",
118 like: "liked",
118119 };
119120
120121 const money = (n: number): string => `$${n.toFixed(2)}`;
src/web/studio/feed.ts +103 −9
@@ -1,17 +1,20 @@
11 /**
22 * The home's feed: the ranked read model (`feed/feed.ts`) as posts (#599).
33 * Each post is who did it, what it says in its own words as a link straight
4 * into the thing, a small line of why it is here, a way to say something to
5 * the crew from where you are, and dismiss / mute. Above them, the composer. The first
4 * into the thing, a small line of why it is here, a way to reply, like or share in place (or say something to the crew, on a post that is not an issue or a pull), and dismiss / mute. Above them, the composer. The first
65 * page is server-rendered; the same region answers at `/live/feed` so a
76 * forge event refreshes it through the live-regions client, like the shelf.
87 * Every string on a card is plain text and is escaped here, once.
98 */
109
10 import { likeCounts } from "../../core/decisions.ts";
11 import { getIssue } from "../../core/issues.ts";
1112 import { marksByName, type Mark } from "../../core/marks.ts";
13 import { getRepo } from "../../core/repos.ts";
1214 import type { User } from "../../core/users.ts";
1315 import type { Ctx } from "../../http/context.ts";
1416 import { readFeed } from "../../feed/feed.ts";
17 import { numberOfLink } from "../../feed/react.ts";
1518 import type { FeedItem } from "../../feed/rank.ts";
1619 import { html, type Html } from "../html.ts";
1720 import { fragment } from "../layout.ts";
@@ -49,6 +52,14 @@ const saysMore = (item: FeedItem): boolean =>
4952 !item.reason.startsWith(item.what) &&
5053 !/^because you (own|work on|pinned) /.test(item.reason);
5154
55 /** What sits under a post that is an issue or a pull: its number and its likes. */
56 export interface Reactions {
57 readonly kind: "issue" | "pull";
58 readonly number: number;
59 readonly likes: number;
60 readonly mine: boolean;
61 }
62
5263 /**
5364 * One post: who, where and when; what it says, as a link into the thing;
5465 * why, when that is news; and one quiet control for the rest — say
@@ -57,6 +68,7 @@ const saysMore = (item: FeedItem): boolean =>
5768 export function feedCard(
5869 item: FeedItem,
5970 marks: ReadonlyMap<string, Mark> = new Map(),
71 react?: Reactions,
6072 ): Html {
6173 const steer = item.kind === "run" || item.kind === "cost";
6274 const target = steer && RUN_LINK.test(item.link) ? `${item.link}/steer` : null;
@@ -78,12 +90,23 @@ export function feedCard(
7890 </div>
7991 <p class="fcard-reason"><a href="${item.link}" data-feed-open>${item.what}</a></p>
8092 ${saysMore(item) ? html`<p class="fcard-why small muted">${item.reason}</p>` : null}
93 ${react
94 ? html`<p class="fcard-react">
95 <button type="button" class="btn btn-sm btn-ghost" data-like aria-pressed="${react.mine ? "true" : "false"}" title="Like (l)">${react.mine ? "Liked" : "Like"}<span class="fcard-count" data-count="${String(react.likes)}">${react.likes > 0 ? ` ${react.likes}` : ""}</span></button>
96 <button type="button" class="btn btn-sm btn-ghost" data-share title="Share with the crew (s)">Share</button>
97 </p>`
98 : null}
8199 <details class="fcard-more">
82 <summary class="small muted" aria-label="${target ? "Steer, dismiss or mute" : "Tell the crew, dismiss or mute"}">${target ? "Steer" : "Tell"} · more</summary>
83 <form method="post" action="${target ?? `/${item.app}/tell`}" class="fcard-form">
84 <textarea name="text" rows="2" maxlength="2000" required aria-label="${target ? "Steer this run" : "Tell the crew"}"></textarea>
85 ${btn(target ? "Steer" : "Tell", { size: "sm", variant: "primary" })}
86 </form>
100 <summary class="small muted" aria-label="${react ? "Reply, dismiss or mute" : target ? "Steer, dismiss or mute" : "Tell the crew, dismiss or mute"}">${react ? "Reply" : target ? "Steer" : "Tell"} · more</summary>
101 ${react
102 ? html`<form method="post" action="/${item.app}/${react.kind === "pull" ? "pulls" : "issues"}/${String(react.number)}/comments" class="fcard-form" data-reply="${react.kind}:${String(react.number)}">
103 <textarea name="body" rows="2" maxlength="8000" required aria-label="Reply"></textarea>
104 ${btn("Reply", { size: "sm", variant: "primary" })}
105 </form>`
106 : html`<form method="post" action="${target ?? `/${item.app}/tell`}" class="fcard-form">
107 <textarea name="text" rows="2" maxlength="2000" required aria-label="${target ? "Steer this run" : "Tell the crew"}"></textarea>
108 ${btn(target ? "Steer" : "Tell", { size: "sm", variant: "primary" })}
109 </form>`}
87110 <span class="fcard-acts">
88111 <button type="button" class="btn btn-sm btn-ghost" data-feed="dismissed" title="Dismiss (x)">Dismiss</button>
89112 ${item.kind === "ask" || item.kind === "milestone" ? null : html`<button type="button" class="btn btn-sm btn-ghost" data-feed="muted" title="Mute ${item.app}">Mute app</button>`}
@@ -153,6 +176,19 @@ export function feedRegion(user: User, ctx: Ctx): Html {
153176 ctx.app.db,
154177 items.map((item) => item.actor ?? ""),
155178 );
179 // What sits under each post that is an issue or a pull, asked once.
180 const refs = new Map<string, Reactions>();
181 const issueIds = new Map<string, string>();
182 for (const item of items) {
183 const number = numberOfLink(item.link);
184 const [owner, name] = item.app.split("/");
185 const repo = number && owner && name ? getRepo(ctx.app.db, owner, name) : undefined;
186 const issue = repo && number ? getIssue(ctx.app.db, repo.id, number) : undefined;
187 if (issue) issueIds.set(item.id, issue.id);
188 if (issue)
189 refs.set(item.id, { kind: issue.kind, number: issue.number, likes: 0, mine: false });
190 }
191 const likes = likeCounts(ctx.app.db, [...issueIds.values()], user.username);
156192 return html`<section
157193 id="live-feed"
158194 class="feed"
@@ -166,7 +202,11 @@ export function feedRegion(user: User, ctx: Ctx): Html {
166202 title: "Nothing new",
167203 note: "When something happens in your apps, it lands here.",
168204 })
169 : items.map((item) => feedCard(item, marks))}
205 : items.map((item) => {
206 const ref = refs.get(item.id);
207 const l = likes.get(issueIds.get(item.id) ?? "");
208 return feedCard(item, marks, ref && { ...ref, likes: l?.count ?? 0, mine: l?.mine ?? false });
209 })}
170210 </section>`;
171211 }
172212
@@ -229,10 +269,46 @@ ${outboxJs}
229269 }
230270 // Acting is instant: the card goes, the act is kept and sent.
231271 function act(card, kind) { if (send(card, kind)) gone(card); }
272 // Like and share act in place: the button answers at once and the post
273 // stays where it is. A like is a toggle, so it is sent, not queued.
274 function post(url, payload) {
275 return fetch(url, { method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload) });
276 }
277 function ref(card) {
278 var r = card.querySelector('[data-reply]');
279 var p = r ? r.getAttribute('data-reply').split(':') : [];
280 var o = { app: card.getAttribute('data-app') };
281 o[p[0]] = Number(p[1]);
282 return o;
283 }
284 function like(btn, card) {
285 var on = btn.getAttribute('aria-pressed') !== 'true';
286 var c = btn.querySelector('.fcard-count');
287 var n = Number(c.getAttribute('data-count')) + (on ? 1 : -1);
288 function paintLike(on, n) {
289 btn.setAttribute('aria-pressed', on ? 'true' : 'false');
290 btn.firstChild.nodeValue = on ? 'Liked' : 'Like';
291 c.setAttribute('data-count', String(n));
292 c.textContent = n > 0 ? ' ' + n : '';
293 }
294 var was = !on, wasN = n + (on ? -1 : 1);
295 paintLike(on, n);
296 post('/api/v1/like', ref(card)).then(function (r) { return r.ok ? r.json() : Promise.reject(); })
297 .then(function (v) { paintLike(v.liked, v.count); })
298 .catch(function () { paintLike(was, wasN); });
299 }
300 function share(btn, card) {
301 btn.disabled = true;
302 post('/api/v1/share', { item: card.getAttribute('data-item') })
303 .then(function (r) { btn.textContent = r.ok ? 'Shared' : 'Share'; btn.disabled = r.ok; })
304 .catch(function () { btn.disabled = false; });
305 }
232306 feed.addEventListener('click', function (e) {
233 var t = e.target && e.target.closest ? e.target.closest('[data-feed],[data-feed-open]') : null;
307 var t = e.target && e.target.closest ? e.target.closest('[data-feed],[data-feed-open],[data-like],[data-share]') : null;
234308 var card = t && t.closest('.fcard');
235309 if (!card) return;
310 if (t.hasAttribute('data-like')) { like(t, card); return; }
311 if (t.hasAttribute('data-share')) { share(t, card); return; }
236312 if (t.hasAttribute('data-feed-open')) { send(card, 'opened'); return; }
237313 act(card, t.getAttribute('data-feed'));
238314 });
@@ -241,6 +317,18 @@ ${outboxJs}
241317 feed.addEventListener('submit', function (e) {
242318 var form = e.target;
243319 var card = form.closest && form.closest('.fcard');
320 if (card && form.hasAttribute && form.hasAttribute('data-reply')) {
321 var said = form.elements.body.value.trim();
322 if (!said) return;
323 var to = ref(card);
324 to.body = said;
325 if (!queue('/api/v1/reply', to)) return;
326 e.preventDefault();
327 form.elements.body.value = '';
328 var det = form.closest('details');
329 if (det) det.open = false;
330 return;
331 }
244332 var box = form.elements && form.elements.text;
245333 if (!card || !box || !/\\/tell$/.test(form.getAttribute('action') || '')) return;
246334 var text = box.value.trim();
@@ -265,6 +353,12 @@ ${outboxJs}
265353 box.focus();
266354 });
267355 document.addEventListener('keydown', function (e) {
356 var a0 = document.activeElement;
357 if ((e.key === 'l' || e.key === 's') && !e.metaKey && !e.ctrlKey && !e.altKey && a0 && a0.matches && a0.matches('.fcard')) {
358 var b = a0.querySelector(e.key === 'l' ? '[data-like]' : '[data-share]');
359 if (b) { e.preventDefault(); b.click(); }
360 return;
361 }
268362 if (e.key !== 'x' || e.metaKey || e.ctrlKey || e.altKey) return;
269363 var a = document.activeElement;
270364 if (!a || !a.matches || !a.matches('.fcard')) return;
src/web/studio/feed_style.ts +3 −1
@@ -13,6 +13,8 @@ export const feedCss = /* css */ `
1313 .fcard-more summary { cursor: pointer; list-style: none; padding: 2px 0; }
1414 .fcard-more summary::-webkit-details-marker { display: none; }
1515 .fcard-acts { display: flex; gap: 4px; margin-top: 6px; }
16 .fcard-react { display: flex; gap: 4px; margin: 4px 0 0; }
17 .fcard-react [aria-pressed="true"] { color: var(--accent); }
1618 .fcard-why { margin: 0 0 4px; }
1719 /* The composer: the home's one primary action, on top of the timeline. */
1820 .composer { display: grid; gap: 8px; border: 1px solid var(--border); border-radius: var(--radius); padding: 12px 14px; background: var(--card, var(--bg)); }
@@ -34,7 +36,7 @@ export const feedCss = /* css */ `
3436 .fcard-form textarea { width: 100%; min-height: 56px; resize: vertical; }
3537 @media (max-width: 600px) {
3638 .fcard { padding: 12px 2px; }
37 .fcard-acts .btn { padding: 8px 10px; }
39 .fcard-acts .btn, .fcard-react .btn { padding: 8px 10px; }
3840 .fcard-more summary { padding: 10px 0; }
3941 }
4042 `;
test/mcp.test.ts +2
@@ -158,6 +158,8 @@ describe("the forge over MCP", () => {
158158 "here",
159159 "tell",
160160 "share",
161 "reply",
162 "like",
161163 "say",
162164 "edit",
163165 "asks",
test/react.test.ts added +168
@@ -0,0 +1,168 @@
1 /**
2 * reply and like under a post: a reply is a comment on the issue or pull,
3 * a like is a ledger row that toggles and moves the feed's affinity; the
4 * page, the API and the MCP tools say the same words.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { openIssue } from "../src/actions/issues.ts";
12 import { createRepo } from "../src/actions/repos.ts";
13 import { listDecisions, likeCounts } from "../src/core/decisions.ts";
14 import { listComments, type Issue } from "../src/core/issues.ts";
15 import type { Repo } from "../src/core/repos.ts";
16 import { createToken } from "../src/core/tokens.ts";
17 import { createUser, type User } from "../src/core/users.ts";
18 import { affinityFor } from "../src/feed/affinity.ts";
19 import { like, reply } from "../src/feed/react.ts";
20 import { serve, type Servers } from "../src/http/server.ts";
21 import { feedCard } from "../src/web/studio/feed.ts";
22
23 describe("reply and like", () => {
24 let dataDir: string;
25 let app: App;
26 let servers: Servers;
27 let alice: User;
28 let bob: User;
29 let token: string;
30 let repo: Repo;
31 let secret: Repo;
32 let issue: Issue;
33
34 beforeAll(async () => {
35 dataDir = await mkdtemp(join(tmpdir(), "forge-react-"));
36 app = createApp({ dataDir, port: 0 });
37 servers = await serve(app);
38 const mk = async (username: string, first = false) => {
39 const r = await createUser(app.db, {
40 trusted: true,
41 username,
42 allowReserved: true,
43 email: `${username}@forge.local`,
44 password: "a-good-passphrase",
45 adminIfFirst: first,
46 });
47 if (!r.ok) throw new Error(r.error);
48 return r.value;
49 };
50 await mk("root", true);
51 alice = await mk("alice");
52 bob = await mk("bob");
53 token = createToken(app.db, alice.id, "t", "rw").token;
54 const o = await createRepo(app, alice, { name: "open", visibility: "public" });
55 const s = await createRepo(app, alice, { name: "secret", visibility: "private" });
56 if (!o.ok || !s.ok) throw new Error("repos");
57 repo = o.value;
58 secret = s.value;
59 const i = openIssue(app, alice, repo, { title: "Fix the nav" });
60 if (!i.ok) throw new Error(i.error);
61 issue = i.value;
62 });
63
64 afterAll(async () => {
65 servers.stop();
66 app.close();
67 await rm(dataDir, { recursive: true, force: true });
68 });
69
70 test("a reply lands as a comment on the issue", async () => {
71 const r = await reply(app, bob, { app: "alice/open", issue: issue.number }, " on it ");
72 expect(r.ok).toBe(true);
73 expect(listComments(app.db, issue.id).map((c) => c.body)).toEqual(["on it"]);
74 });
75
76 test("a reply is refused when empty, ambiguous, or on what is not seen", async () => {
77 const ref = { app: "alice/open", issue: issue.number };
78 expect(await reply(app, bob, ref, " ")).toEqual({ ok: false, error: "invalid" });
79 expect(await reply(app, bob, { ...ref, pull: 1 }, "x")).toEqual({ ok: false, error: "invalid" });
80 expect(await reply(app, bob, { app: "alice/open" }, "x")).toEqual({ ok: false, error: "invalid" });
81 // An issue is not a pull.
82 expect(await reply(app, bob, { app: "alice/open", pull: issue.number }, "x")).toEqual({ ok: false, error: "not_found" });
83 expect(await reply(app, bob, { app: "alice/secret", issue: 1 }, "x")).toEqual({ ok: false, error: "not_found" });
84 expect(listComments(app.db, issue.id).length).toBe(1);
85 });
86
87 test("a like writes a ledger row and unwrites it", () => {
88 const ref = { app: "alice/open", issue: issue.number };
89 const on = like(app, bob, ref);
90 expect(on).toEqual({ ok: true, value: { liked: true, count: 1 } });
91 const rows = listDecisions(app.db, repo.id, { kind: "like" });
92 expect(rows.map((d) => [d.issueId, d.by, d.answer])).toEqual([[issue.id, "bob", "like"]]);
93 // The crew's own listing of its decisions does not carry a like.
94 expect(listDecisions(app.db, repo.id).length).toBe(0);
95 expect(like(app, alice, ref)).toEqual({ ok: true, value: { liked: true, count: 2 } });
96 expect(likeCounts(app.db, [issue.id], "bob").get(issue.id)).toEqual({ count: 2, mine: true });
97 expect(like(app, bob, ref)).toEqual({ ok: true, value: { liked: false, count: 1 } });
98 expect(like(app, alice, ref)).toEqual({ ok: true, value: { liked: false, count: 0 } });
99 expect(listDecisions(app.db, repo.id, { kind: "like" })).toEqual([]);
100 });
101
102 test("a like moves the feed's affinity for the app and the author", () => {
103 const now = Date.now();
104 const before = affinityFor(app.db, bob, now);
105 expect(before.app(repo.id).score).toBe(0);
106 like(app, bob, { app: "alice/open", issue: issue.number });
107 const after = affinityFor(app.db, bob, now);
108 expect(after.app(repo.id).score).toBeGreaterThan(0);
109 expect(after.app(repo.id).why).toBe("liked");
110 expect(after.actor(alice.id).score).toBeGreaterThan(0);
111 like(app, bob, { app: "alice/open", issue: issue.number });
112 expect(affinityFor(app.db, bob, now).app(repo.id).score).toBe(0);
113 });
114
115 test("the API answers: auth, validation, and the same effects", async () => {
116 const post = (path: string, payload: unknown, t: string | undefined = token) =>
117 fetch(`${servers.url}/api/v1/${path}`, {
118 method: "POST",
119 headers: { ...(t ? { authorization: `Bearer ${t}` } : {}), "content-type": "application/json" },
120 body: JSON.stringify(payload),
121 });
122 const ref = { app: "alice/open", issue: issue.number };
123 expect((await post("reply", { ...ref, body: "hi" }, "")).status).toBe(401);
124 expect((await post("reply", { ...ref, body: "" })).status).toBe(422);
125 expect((await post("reply", { app: "alice/secret", issue: 1, body: "x" }, createToken(app.db, bob.id, "b", "rw").token)).status).toBe(404);
126 expect((await post("reply", { ...ref, body: "from the api" })).status).toBe(201);
127 expect(listComments(app.db, issue.id).map((c) => c.body)).toContain("from the api");
128 const liked = await post("like", ref);
129 expect(await liked.json()).toEqual({ liked: true, count: 1 });
130 expect(await (await post("like", ref)).json()).toEqual({ liked: false, count: 0 });
131 expect((await post("like", { app: "alice/open" })).status).toBe(422);
132 });
133
134 test("the MCP tools are named reply and like", async () => {
135 const call = (name: string, args: object) =>
136 fetch(`${servers.url}/mcp`, {
137 method: "POST",
138 headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json" },
139 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
140 }).then((r) => r.json() as Promise<{ result: { isError?: boolean; content: { text: string }[] } }>);
141 const r = await call("reply", { repo: "alice/open", issue: issue.number, body: "from mcp" });
142 expect(r.result.isError).toBeFalsy();
143 expect(listComments(app.db, issue.id).map((c) => c.body)).toContain("from mcp");
144 const l = await call("like", { repo: "alice/open", issue: issue.number });
145 expect(JSON.parse(l.result.content[0]!.text)).toEqual({ liked: true, count: 1 });
146 expect((await call("like", { repo: "alice/open", issue: 999 })).result.isError).toBe(true);
147 await call("like", { repo: "alice/open", issue: issue.number });
148 });
149
150 test("the card shows reply, like and share, escaped, with the count", () => {
151 const item = {
152 id: "event:e1", kind: "tell" as const, app: "alice/open", actor: "alice",
153 at: new Date().toISOString(), link: `/alice/open/tells/${issue.number}`,
154 what: "<b>x</b>", reason: "because", score: 1,
155 };
156 const out = String(feedCard(item, new Map(), { kind: "issue", number: issue.number, likes: 2, mine: true }));
157 expect(out).toContain("data-like");
158 expect(out).toContain('aria-pressed="true"');
159 expect(out).toContain("data-share");
160 expect(out).toContain(`action="/alice/open/issues/${issue.number}/comments"`);
161 expect(out).toContain("&lt;b&gt;");
162 // A post that is no issue or pull keeps the old way to tell the crew.
163 const plain = String(feedCard({ ...item, kind: "run", link: "/alice/open/runs/r1" }));
164 expect(plain).not.toContain("data-like");
165 expect(plain).toContain("/alice/open/runs/r1/steer");
166 void secret;
167 });
168 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs