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 #1548

Closed opened this
Closed without merging

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

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
11 files changed +544 −5
scripts/gate.ts +1
@@ -142,6 +142,7 @@ export const GATE: readonly string[] = [
142142 "test/feed-page.test.ts",
143143 "test/offline.test.ts",
144144 "test/share.test.ts",
145 "test/react.test.ts",
145146 "test/cloud.test.ts",
146147 "test/run-secrets.test.ts",
147148 "test/reserved-names.test.ts",
src/core/decisions.ts +33 −3
@@ -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 agent's thumbs-up on an issue or pull, written
21 * from under a post (`feed/react.ts`); `state` names who, and unliking
22 * deletes the row. Feed affinity reads it (`likedIssues`). */
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;
@@ -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)))
@@ -291,3 +301,23 @@ export function listDecidedIn(
291301 .all(limit, ...repoIds)
292302 .map(toDecision);
293303 }
304
305 /** The issues and pulls a user liked, newest first, with the moment. */
306 export function likedIssues(
307 db: Database,
308 userId: string,
309 limit = 500,
310 ): { repoId: string; issueId: string; at: string }[] {
311 return db
312 .query<
313 { repo_id: string; issue_id: string; created_at: string },
314 [string, number]
315 >(
316 `SELECT repo_id, issue_id, created_at FROM decision
317 WHERE kind = 'like' AND issue_id IS NOT NULL
318 AND json_extract(state, '$.user') = ?1
319 ORDER BY created_at DESC, id DESC LIMIT ?2`,
320 )
321 .all(userId, limit)
322 .map((r) => ({ repoId: r.repo_id, issueId: r.issue_id, at: r.created_at }));
323 }
src/feed/affinity.ts +13 −1
@@ -7,9 +7,10 @@
77 */
88
99 import type { Database } from "bun:sqlite";
10 import { listDecidedIn } from "../core/decisions.ts";
10 import { likedIssues, listDecidedIn } from "../core/decisions.ts";
1111 import type { InteractionKind } from "../core/interactions.ts";
1212 import { listInteractions } from "../core/interactions.ts";
13 import { getIssueById } from "../core/issues.ts";
1314 import { getPull } from "../core/pulls.ts";
1415 import { listReposWritableTo, type Repo } from "../core/repos.ts";
1516 import type { User } from "../core/users.ts";
@@ -28,6 +29,7 @@ export type Why =
2829 | "proposed"
2930 | "told"
3031 | "decided"
32 | "liked"
3133 | InteractionKind;
3234
3335 /** What each interaction is worth. Negatives outweigh the positives. */
@@ -43,6 +45,8 @@ export const INTERACTION_WEIGHT: Readonly<Record<InteractionKind, number>> = {
4345 muted: -8,
4446 };
4547
48 export const LIKE_WEIGHT = 2;
49
4650 export interface Weighted {
4751 readonly score: number;
4852 /** The part with the largest size, and when it last counted. */
@@ -148,6 +152,14 @@ export function affinityFor(
148152 if (d.outcome === "shipped")
149153 aff.add(`app:${d.repoId}`, "decided", decay(now - at), at);
150154 }
155 // A like is worth what a share is: it names the app and the issue's author.
156 for (const l of likedIssues(db, viewer.id)) {
157 const at = Date.parse(l.at);
158 const w = LIKE_WEIGHT * decay(now - at);
159 aff.add(`app:${l.repoId}`, "liked", w, at);
160 const author = getIssueById(db, l.issueId)?.authorId;
161 if (author !== undefined) aff.add(`actor:${author}`, "liked", w, at);
162 }
151163 for (const i of listInteractions(db, viewer.id)) {
152164 const at = Date.parse(i.createdAt);
153165 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 +141
@@ -0,0 +1,141 @@
1 /**
2 * The two verbs under a post besides `share`: `reply` and `like`. Both are
3 * git primitives, not feed state. A reply is a comment on the post's issue
4 * or pull; a like is a `like` row in the decision ledger
5 * (`core/decisions.ts`) that the viewer's affinity reads
6 * (`feed/affinity.ts`). A person's buttons and the agent's tools say the
7 * same words and land here.
8 */
9
10 import type { Database } from "bun:sqlite";
11 import type { App } from "../app.ts";
12 import { addCommentThrough } from "../actions/issues.ts";
13 import { recordDecision } from "../core/decisions.ts";
14 import {
15 countComments,
16 getIssue,
17 listComments,
18 type Comment,
19 type Issue,
20 } from "../core/issues.ts";
21 import { canRead, getRepo, type Repo } from "../core/repos.ts";
22 import type { User } from "../core/users.ts";
23
24 export type ReactError = "not_found" | "forbidden" | "invalid";
25
26 export interface Target {
27 readonly repo: Repo;
28 readonly issue: Issue;
29 }
30
31 /** `owner/name` and a number, as the viewer may see them; else nothing. */
32 export function targetOf(
33 db: Database,
34 viewer: User,
35 app: unknown,
36 number: unknown,
37 ): Target | undefined {
38 if (typeof app !== "string" || !Number.isInteger(number)) return undefined;
39 const [owner, name, extra] = app.split("/");
40 if (!owner || !name || extra !== undefined) return undefined;
41 const repo = getRepo(db, owner, name);
42 if (!repo || !canRead(db, repo, viewer)) return undefined;
43 const issue = getIssue(db, repo.id, number as number);
44 return issue ? { repo, issue } : undefined;
45 }
46
47 /** The number named by `issue` or by `pull`; both, if given, must agree. */
48 export function numberArg(input: {
49 issue?: unknown;
50 pull?: unknown;
51 }): number | undefined {
52 const { issue, pull } = input;
53 if (issue !== undefined && pull !== undefined && issue !== pull) return undefined;
54 const n = issue ?? pull;
55 return typeof n === "number" && Number.isInteger(n) && n > 0 ? n : undefined;
56 }
57
58 /** The change a feed link points into, if it points into one. */
59 export function linkTarget(link: string): { app: string; number: number } | undefined {
60 const m = /^\/([^/]+\/[^/]+)\/(?:changes|issues|pulls)\/(\d+)$/.exec(link);
61 return m ? { app: m[1]!, number: Number(m[2]) } : undefined;
62 }
63
64 export const REPLY_MAX = 8000;
65
66 export async function reply(
67 app: App,
68 viewer: User,
69 target: Target,
70 body: string,
71 ): Promise<{ ok: true; value: Comment } | { ok: false; error: ReactError }> {
72 const text = body.trim();
73 if (text === "" || text.length > REPLY_MAX) return { ok: false, error: "invalid" };
74 const added = await addCommentThrough(app, viewer, target.repo, target.issue, text);
75 if (added.ok) return { ok: true, value: added.value };
76 return {
77 ok: false,
78 error:
79 added.error === "not_found"
80 ? "not_found"
81 : added.error === "unauthorized"
82 ? "forbidden"
83 : "invalid",
84 };
85 }
86
87 const likeRow = (db: Database, viewerId: string, issueId: string) =>
88 db
89 .query<{ id: string }, [string, string]>(
90 `SELECT id FROM decision
91 WHERE kind = 'like' AND issue_id = ?1 AND json_extract(state, '$.user') = ?2`,
92 )
93 .get(issueId, viewerId);
94
95 export const likeCount = (db: Database, issueId: string): number =>
96 db
97 .query<{ n: number }, [string]>(
98 "SELECT COUNT(*) AS n FROM decision WHERE kind = 'like' AND issue_id = ?1",
99 )
100 .get(issueId)?.n ?? 0;
101
102 export const liked = (db: Database, viewerId: string, issueId: string): boolean =>
103 likeRow(db, viewerId, issueId) !== null;
104
105 /** Toggle: a like is written, or — if there already is one — unwritten. */
106 export function like(
107 db: Database,
108 viewer: User,
109 target: Target,
110 ): { liked: boolean; count: number } {
111 const had = likeRow(db, viewer.id, target.issue.id);
112 if (had)
113 db.query("DELETE FROM decision WHERE id = ?1").run(had.id);
114 else
115 recordDecision(db, {
116 kind: "like",
117 repoId: target.repo.id,
118 issueId: target.issue.id,
119 state: { user: viewer.id },
120 answer: "like",
121 p: 1,
122 by: viewer.username,
123 ms: 0,
124 });
125 return { liked: !had, count: likeCount(db, target.issue.id) };
126 }
127
128 /** What sits under a post: its replies so far, newest two, and the counts. */
129 export function underPost(db: Database, viewer: User, target: Target) {
130 const comments = listComments(db, target.issue.id, { kind: "comment" });
131 return {
132 number: target.issue.number,
133 kind: target.issue.kind,
134 replies: countComments(db, target.issue.id),
135 latest: comments.slice(-2),
136 likes: likeCount(db, target.issue.id),
137 liked: liked(db, viewer.id, target.issue.id),
138 };
139 }
140
141 export type Under = ReturnType<typeof underPost>;
src/http/feed.ts +36
@@ -12,6 +12,7 @@ import {
1212 isInteractionKind,
1313 recordInteraction,
1414 } from "../core/interactions.ts";
15 import { like, numberArg, reply, targetOf } 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,41 @@ export function feedRoutes(router: Router<Handler>): void {
170171 return json({ issue: told.value.issue.number }, 201);
171172 });
172173
174 // Reply and like: the same words as the MCP tools and the buttons under a
175 // post. A reply is a comment on the issue or pull; a like is a ledger row.
176 router.add("POST", "/api/v1/reply", async (ctx) => {
177 const denied = requireScope(ctx, "rw");
178 if (denied) return denied;
179 const viewer = ctx.auth.user!;
180 const input = await body(ctx.request);
181 const number = numberArg(input);
182 if (number === undefined)
183 return apiError("invalid_number", 422, "issue or pull is a number");
184 const target = targetOf(ctx.app.db, viewer, input.app, number);
185 if (!target) return notFound();
186 const said = await reply(ctx.app, viewer, target, str(input.body));
187 if (!said.ok)
188 return said.error === "forbidden"
189 ? apiError("forbidden", 403, "you may not comment here")
190 : said.error === "not_found"
191 ? notFound()
192 : apiError("invalid_body", 422, "body is 1 to 8000 characters");
193 return json({ comment: said.value.id, number }, 201);
194 });
195
196 router.add("POST", "/api/v1/like", async (ctx) => {
197 const denied = requireScope(ctx, "rw");
198 if (denied) return denied;
199 const viewer = ctx.auth.user!;
200 const input = await body(ctx.request);
201 const number = numberArg(input);
202 if (number === undefined)
203 return apiError("invalid_number", 422, "issue or pull is a number");
204 const target = targetOf(ctx.app.db, viewer, input.app, number);
205 if (!target) return notFound();
206 return json({ number, ...like(ctx.app.db, viewer, target) }, 201);
207 });
208
173209 router.add("POST", "/api/v1/share", async (ctx) => {
174210 const denied = requireScope(ctx, "rw");
175211 if (denied) return denied;
src/http/mcp.ts +53
@@ -61,6 +61,7 @@ import {
6161 parseCursor,
6262 readFeed,
6363 } from "../feed/feed.ts";
64 import { like, numberArg, reply, targetOf } from "../feed/react.ts";
6465 import { share } from "../feed/share.ts";
6566 import { parseTargets } from "./feed.ts";
6667 import { appsRuntime, envsFor } from "../apps/runtime.ts";
@@ -377,6 +378,58 @@ const TOOLS: readonly Tool[] = [
377378 return good({ sent: made.value.sent });
378379 },
379380 },
381 {
382 name: "reply",
383 description:
384 "Reply under a post: a comment on its issue or pull. Name the app and the `issue` or the `pull` number.",
385 inputSchema: {
386 type: "object",
387 properties: {
388 repo: REPO_ARG,
389 issue: { type: "integer", minimum: 1 },
390 pull: { type: "integer", minimum: 1 },
391 body: { type: "string", maxLength: 8000 },
392 },
393 required: ["repo", "body"],
394 },
395 writes: true,
396 async run(ctx, user, args) {
397 const number = numberArg({ issue: args["issue"], pull: args["pull"] });
398 if (number === undefined) return bad("invalid", "issue or pull is a number");
399 const target = targetOf(ctx.app.db, user, str(args["repo"]), number);
400 if (!target) return bad("not_found", "no such issue or pull");
401 const said = await reply(ctx.app, user, target, str(args["body"]));
402 if (!said.ok)
403 return said.error === "forbidden"
404 ? bad("forbidden", "you may not comment here")
405 : said.error === "not_found"
406 ? bad("not_found", "no such issue or pull")
407 : bad("invalid", "body is 1 to 8000 characters");
408 return good({ comment: said.value.id, number });
409 },
410 },
411 {
412 name: "like",
413 description:
414 "Like an issue or a pull, or take the like back (it toggles). A like is a signal in the decision ledger; the feed leans toward what you like.",
415 inputSchema: {
416 type: "object",
417 properties: {
418 repo: REPO_ARG,
419 issue: { type: "integer", minimum: 1 },
420 pull: { type: "integer", minimum: 1 },
421 },
422 required: ["repo"],
423 },
424 writes: true,
425 async run(ctx, user, args) {
426 const number = numberArg({ issue: args["issue"], pull: args["pull"] });
427 if (number === undefined) return bad("invalid", "issue or pull is a number");
428 const target = targetOf(ctx.app.db, user, str(args["repo"]), number);
429 if (!target) return bad("not_found", "no such issue or pull");
430 return good({ number, ...like(ctx.app.db, user, target) });
431 },
432 },
380433 {
381434 name: "say",
382435 description:
src/web/pages/board.ts +1
@@ -117,6 +117,7 @@ const KIND_WORDS: Record<DecisionKind, string> = {
117117 lean: "which way",
118118 // Never listed (`listDecisionsForRepos` leaves guards out); named for the type.
119119 guard: "not started",
120 like: "liked",
120121 };
121122
122123 const money = (n: number): string => `$${n.toFixed(2)}`;
src/web/studio/feed.ts +73 −1
@@ -12,6 +12,7 @@ import { marksByName, type Mark } from "../../core/marks.ts";
1212 import type { User } from "../../core/users.ts";
1313 import type { Ctx } from "../../http/context.ts";
1414 import { readFeed } from "../../feed/feed.ts";
15 import { linkTarget, targetOf, underPost, type Under } from "../../feed/react.ts";
1516 import type { FeedItem } from "../../feed/rank.ts";
1617 import { html, type Html } from "../html.ts";
1718 import { fragment } from "../layout.ts";
@@ -57,6 +58,7 @@ const saysMore = (item: FeedItem): boolean =>
5758 export function feedCard(
5859 item: FeedItem,
5960 marks: ReadonlyMap<string, Mark> = new Map(),
61 under?: Under,
6062 ): Html {
6163 const steer = item.kind === "run" || item.kind === "cost";
6264 const target = steer && RUN_LINK.test(item.link) ? `${item.link}/steer` : null;
@@ -78,6 +80,7 @@ export function feedCard(
7880 </div>
7981 <p class="fcard-reason"><a href="${item.link}" data-feed-open>${item.what}</a></p>
8082 ${saysMore(item) ? html`<p class="fcard-why small muted">${item.reason}</p>` : null}
83 ${reactions(item, under)}
8184 <details class="fcard-more">
8285 <summary class="small muted" aria-label="${target ? "Steer, dismiss or mute" : "Tell the crew, dismiss or mute"}">${target ? "Steer" : "Tell"} · more</summary>
8386 <form method="post" action="${target ?? `/${item.app}/tell`}" class="fcard-form">
@@ -111,6 +114,32 @@ export function sharedDraft(params: URLSearchParams): string {
111114 return parts.join("\n").slice(0, TELL_MAX);
112115 }
113116
117 /**
118 * Under a post: reply, like and share — the words the MCP tools use. Reply
119 * and like need an issue or pull to land on (`under`); share works on any
120 * post. The latest replies sit right below, as comments on the thing.
121 */
122 function reactions(item: FeedItem, under: Under | undefined): Html {
123 return html`<div class="fcard-react">
124 ${under === undefined
125 ? null
126 : html`<details class="fcard-reply" data-number="${String(under.number)}">
127 <summary class="small muted">Reply${under.replies > 0 ? ` · ${under.replies}` : ""}</summary>
128 <form method="post" action="/${item.app}/${under.kind === "pull" ? "pulls" : "issues"}/${String(under.number)}/comments" class="fcard-form">
129 <textarea class="input" name="body" rows="2" maxlength="8000" required aria-label="Reply"></textarea>
130 ${btn("Reply", { size: "sm", variant: "primary" })}
131 </form>
132 </details>
133 <button type="button" class="btn btn-sm btn-ghost" data-like="${String(under.number)}" aria-pressed="${under.liked ? "true" : "false"}" data-count="${String(under.likes)}" title="Like (l)">${under.liked ? "Liked" : "Like"}${under.likes > 0 ? ` · ${under.likes}` : ""}</button>`}
134 <button type="button" class="btn btn-sm btn-ghost" data-share title="Share with the crew (s)">Share</button>
135 ${under === undefined || under.latest.length === 0
136 ? null
137 : html`<ul class="fcard-replies small">
138 ${under.latest.map((c) => html`<li><strong>${c.originAuthor ?? c.authorName}</strong> ${c.body.slice(0, 280)}</li>`)}
139 </ul>`}
140 </div>`;
141 }
142
114143 /**
115144 * The composer: say something to an app's crew, which opens a tell — the
116145 * home's one primary action. Without a script it posts to the chosen app's
@@ -172,6 +201,12 @@ export function feedRegion(user: User, ctx: Ctx): Html {
172201 ctx.app.db,
173202 items.map((item) => item.actor ?? ""),
174203 );
204 const unders = new Map<string, Under>();
205 for (const item of items) {
206 const at = linkTarget(item.link);
207 const target = at && targetOf(ctx.app.db, user, at.app, at.number);
208 if (target) unders.set(item.id, underPost(ctx.app.db, user, target));
209 }
175210 return html`<section
176211 id="live-feed"
177212 class="feed"
@@ -185,7 +220,7 @@ export function feedRegion(user: User, ctx: Ctx): Html {
185220 title: "Nothing new",
186221 note: "When something happens in your apps, it lands here.",
187222 })
188 : items.map((item) => feedCard(item, marks))}
223 : items.map((item) => feedCard(item, marks, unders.get(item.id)))}
189224 </section>`;
190225 }
191226
@@ -248,6 +283,43 @@ ${outboxJs}
248283 }
249284 // Acting is instant: the card goes, the act is kept and sent.
250285 function act(card, kind) { if (send(card, kind)) gone(card); }
286 // Like, share: kept and sent through the outbox; the button answers at once.
287 feed.addEventListener('click', function (e) {
288 var b = e.target && e.target.closest ? e.target.closest('[data-like],[data-share]') : null;
289 var card = b && b.closest('.fcard');
290 if (!card) return;
291 e.stopPropagation();
292 if (b.hasAttribute('data-share')) {
293 if (queue('/api/v1/share', { item: card.getAttribute('data-item') })) b.textContent = 'Shared';
294 return;
295 }
296 var on = b.getAttribute('aria-pressed') !== 'true';
297 var n = Math.max(0, Number(b.getAttribute('data-count')) + (on ? 1 : -1));
298 if (!queue('/api/v1/like', { app: card.getAttribute('data-app'), issue: Number(b.getAttribute('data-like')) })) return;
299 b.setAttribute('aria-pressed', on ? 'true' : 'false');
300 b.setAttribute('data-count', String(n));
301 b.textContent = (on ? 'Liked' : 'Like') + (n > 0 ? ' \u00b7 ' + n : '');
302 }, true);
303 // A reply shows under the post at once and is sent from the outbox.
304 feed.addEventListener('submit', function (e) {
305 var form = e.target;
306 var card = form.closest && form.closest('.fcard');
307 var det = form.closest && form.closest('.fcard-reply');
308 var box = form.elements && form.elements.body;
309 if (!card || !det || !box) return;
310 var text = box.value.trim();
311 if (!text) return;
312 if (!queue('/api/v1/reply', { app: card.getAttribute('data-app'), issue: Number(det.getAttribute('data-number')), body: text })) return;
313 e.preventDefault();
314 e.stopPropagation();
315 var list = card.querySelector('.fcard-replies');
316 if (!list) { list = document.createElement('ul'); list.className = 'fcard-replies small'; card.querySelector('.fcard-react').appendChild(list); }
317 var li = document.createElement('li');
318 li.textContent = text.slice(0, 280);
319 list.appendChild(li);
320 box.value = '';
321 det.open = false;
322 }, true);
251323 feed.addEventListener('click', function (e) {
252324 var t = e.target && e.target.closest ? e.target.closest('[data-feed],[data-feed-open]') : null;
253325 var card = t && t.closest('.fcard');
test/mcp.test.ts +2
@@ -159,6 +159,8 @@ describe("the forge over MCP", () => {
159159 "here",
160160 "tell",
161161 "share",
162 "reply",
163 "like",
162164 "say",
163165 "pull",
164166 "edit",
test/react.test.ts added +190
@@ -0,0 +1,190 @@
1 /**
2 * reply and like under a post: a reply lands as a comment on its issue; a
3 * like writes a ledger row and a second one unwrites it; the feed's
4 * affinity moves; the page, the API and MCP all 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, listDecisionsForRepos } 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, liked, linkTarget, numberArg, reply, targetOf, underPost } 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 aliceToken: string;
30 let bobToken: string;
31 let pub: Repo;
32 let priv: Repo;
33 let issue: Issue;
34
35 beforeAll(async () => {
36 dataDir = await mkdtemp(join(tmpdir(), "forge-react-"));
37 app = createApp({ dataDir, port: 0 });
38 servers = await serve(app);
39 const mk = async (username: string, first = false) => {
40 const r = await createUser(app.db, {
41 trusted: true,
42 username,
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 alice = await mk("alice", true);
51 bob = await mk("bob");
52 aliceToken = createToken(app.db, alice.id, "t", "rw").token;
53 bobToken = createToken(app.db, bob.id, "t", "rw").token;
54 const o = await createRepo(app, alice, { name: "open", visibility: "public" });
55 const p = await createRepo(app, alice, { name: "secret", visibility: "private" });
56 if (!o.ok || !p.ok) throw new Error("repos");
57 pub = o.value;
58 priv = p.value;
59 const i = openIssue(app, alice, pub, { 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 const target = (who: User) => targetOf(app.db, who, "alice/open", issue.number)!;
71 const post = (path: string, token: string, body: unknown) =>
72 fetch(`${servers.url}${path}`, {
73 method: "POST",
74 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
75 body: JSON.stringify(body),
76 });
77
78 test("a reply lands as a comment on its issue", async () => {
79 const said = await reply(app, bob, target(bob), " on it ");
80 expect(said.ok).toBe(true);
81 const comments = listComments(app.db, issue.id, { kind: "comment" });
82 expect(comments.map((c) => [c.authorName, c.body])).toEqual([["bob", "on it"]]);
83 expect(await reply(app, bob, target(bob), " ")).toEqual({ ok: false, error: "invalid" });
84 expect(await reply(app, bob, target(bob), "x".repeat(8001))).toEqual({ ok: false, error: "invalid" });
85 });
86
87 test("a like writes a ledger row, counts, and a second unwrites it", () => {
88 expect(like(app.db, bob, target(bob))).toEqual({ liked: true, count: 1 });
89 const rows = listDecisions(app.db, pub.id, { kind: "like" });
90 expect(rows).toHaveLength(1);
91 expect(rows[0]!.issueId).toBe(issue.id);
92 expect(rows[0]!.by).toBe("bob");
93 expect(like(app.db, alice, target(alice)).count).toBe(2);
94 expect(like(app.db, bob, target(bob))).toEqual({ liked: false, count: 1 });
95 expect(listDecisions(app.db, pub.id, { kind: "like" })).toHaveLength(1);
96 // Likes are not decisions a person reads on the board.
97 expect(listDecisionsForRepos(app.db, [pub.id]).some((d) => d.kind === "like")).toBe(false);
98 like(app.db, alice, target(alice));
99 });
100
101 test("a like moves the liker's affinity for the app and its author", () => {
102 const before = affinityFor(app.db, bob, Date.now()).actor(alice.id).score;
103 like(app.db, bob, target(bob));
104 const aff = affinityFor(app.db, bob, Date.now());
105 expect(aff.actor(alice.id).score).toBeGreaterThan(before);
106 expect(aff.app(pub.id).why).toBeDefined();
107 expect(aff.actor(alice.id).why).toBe("liked");
108 });
109
110 test("the card shows the reply, the count and the buttons, escaped", async () => {
111 await reply(app, alice, target(alice), "<b>done</b>");
112 const under = underPost(app.db, bob, target(bob));
113 expect(under.liked).toBe(true);
114 const out = String(
115 feedCard(
116 {
117 id: "event:x",
118 kind: "pull",
119 app: "alice/open",
120 actor: "alice",
121 at: new Date().toISOString(),
122 link: `/alice/open/issues/${issue.number}`,
123 what: "a thing",
124 reason: "a thing",
125 score: 1,
126 },
127 new Map(),
128 under,
129 ),
130 );
131 expect(out).toContain("data-like");
132 expect(out).toContain("data-share");
133 expect(out).toContain("&lt;b&gt;done&lt;/b&gt;");
134 expect(out).not.toContain("<b>done</b>");
135 expect(out).toContain('aria-pressed="true"');
136 });
137
138 test("the API reads the same words, and refuses what it should", async () => {
139 const ok = await post("/api/v1/reply", bobToken, { app: "alice/open", pull: issue.number, issue: issue.number, body: "hi" });
140 expect(ok.status).toBe(201);
141 const l = await post("/api/v1/like", bobToken, { app: "alice/open", issue: issue.number });
142 expect(l.status).toBe(201);
143 expect(((await l.json()) as { liked: boolean }).liked).toBe(false);
144 expect((await post("/api/v1/like", bobToken, { app: "alice/open" })).status).toBe(422);
145 expect((await post("/api/v1/reply", bobToken, { app: "alice/open", issue: issue.number, body: "" })).status).toBe(422);
146 expect((await post("/api/v1/like", bobToken, { app: "alice/open", issue: 999 })).status).toBe(404);
147 // A private app is not found, not forbidden.
148 const hidden = openIssue(app, alice, priv, { title: "secret" });
149 if (!hidden.ok) throw new Error("issue");
150 expect((await post("/api/v1/like", bobToken, { app: "alice/secret", issue: hidden.value.number })).status).toBe(404);
151 expect((await post("/api/v1/reply", bobToken, { app: "alice/secret", issue: hidden.value.number, body: "x" })).status).toBe(404);
152 expect((await post("/api/v1/like", "nope", { app: "alice/open", issue: 1 })).status).toBe(401);
153 });
154
155 test("MCP has reply and like, with the same behaviour", async () => {
156 const call = async (name: string, args: unknown) => {
157 const res = await fetch(`${servers.url}/mcp`, {
158 method: "POST",
159 headers: {
160 authorization: `Bearer ${aliceToken}`,
161 "content-type": "application/json",
162 accept: "application/json, text/event-stream",
163 },
164 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
165 });
166 const body = (await res.json()) as any;
167 return { error: body.result.isError === true, value: body.result.content[0].text as string };
168 };
169 const before = listComments(app.db, issue.id, { kind: "comment" }).length;
170 expect((await call("reply", { repo: "alice/open", issue: issue.number, body: "agent here" })).error).toBe(false);
171 expect(listComments(app.db, issue.id, { kind: "comment" })).toHaveLength(before + 1);
172 const wasLiked = liked(app.db, alice.id, issue.id);
173 const l = await call("like", { repo: "alice/open", pull: issue.number });
174 expect(l.error).toBe(false);
175 expect(JSON.parse(l.value).liked).toBe(!wasLiked);
176 const again = await call("like", { repo: "alice/open", pull: issue.number });
177 expect(JSON.parse(again.value).liked).toBe(!JSON.parse(l.value).liked);
178 expect((await call("like", { repo: "alice/open" })).error).toBe(true);
179 expect((await call("reply", { repo: "nobody/none", issue: 1, body: "x" })).error).toBe(true);
180 });
181
182 test("small parsers", () => {
183 expect(numberArg({ issue: 3 })).toBe(3);
184 expect(numberArg({ pull: 4 })).toBe(4);
185 expect(numberArg({ issue: 3, pull: 4 })).toBeUndefined();
186 expect(numberArg({ issue: "3" })).toBeUndefined();
187 expect(linkTarget("/a/b/changes/7")).toEqual({ app: "a/b", number: 7 });
188 expect(linkTarget("/a/b/runs/xyz")).toBeUndefined();
189 });
190 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs