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

A variant group appears in the feed as one `choose` item that opens its deck #1752

Closed opened this
Closed without merging

scout/forge:scout/1411-a-variant-group-appears-in-the-feed-as-o → main 3 commits fork 2 threads · 2 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +285 −6
README.md +5 −1
@@ -803,4 +803,8 @@ confirm before a dislike), through `POST /api/v1/repos/:owner/:name/pulls/:numbe
803803 terminal. Each person has one vote per pull, kept as a `lean` row in the
804804 decision ledger. A dislike closes the pull and leaves its one-line reason as a
805805 comment the builder reads; the last open sibling shows Ship. Readers see the
806 cards and no buttons.
806 cards and no buttons. In the feed a group of two or more siblings is one
807 **Choose** item, shown to writers only, linking to the deck: it asks while two or
808 more are open, then says how the group ended and fades after a week. Its pulls
809 are not also feed items for those writers; a reader, or a group of one, still
810 sees the pulls' own events.
scripts/gate.ts +1
@@ -36,6 +36,7 @@ export const GATE: readonly string[] = [
3636 "test/boards-query.test.ts",
3737 "test/turnstile.test.ts",
3838 "test/variants-deck.test.ts",
39 "test/feed-choose.test.ts",
3940 "test/variants-surfaces.test.ts",
4041 "test/thoughts.test.ts",
4142 "test/passkeys.test.ts",
src/feed/choose.ts added +102
@@ -0,0 +1,102 @@
1 /**
2 * A variant group in the feed: sibling pulls answering one tell are one
3 * `choose` item that opens the deck, not n pull items. While two or more
4 * siblings are open it asks; once one is shipped or none is open it only
5 * says how it ended. Read from what is true now, so the ask goes the moment
6 * the group is decided. Only a viewer who may write to the repository sees it.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import { getIssue } from "../core/issues.ts";
11 import { closesFromBody, variantMembers, type Pull } from "../core/pulls.ts";
12 import type { Repo } from "../core/repos.ts";
13 import type { Candidate } from "./items.ts";
14
15 /** Above the news, below the asks (which start at 5). */
16 const CHOOSE_URGENCY = 3;
17 /** A decided group is news for a while, then it is history. */
18 const DECIDED_DAYS = 7;
19
20 const clip = (s: string, n: number): string =>
21 s.length > n ? `${s.slice(0, n - 1)}…` : s;
22
23 const isOpen = (p: Pull): boolean => p.state === "open" && p.mergedAt === null;
24
25 /** The words the group answers: the tell it closes, else the first pull's title. */
26 function tellOf(db: Database, repo: Repo, members: readonly Pull[]): string {
27 for (const p of members)
28 for (const n of closesFromBody(p.body)) {
29 const t = getIssue(db, repo.id, n)?.title;
30 if (t) return t;
31 }
32 return members[0]?.title ?? "a tell";
33 }
34
35 /**
36 * The variant groups of two or more pulls in these repositories, in one query
37 * whatever the number of repositories. These are the groups that have a
38 * `choose` item, so their pulls are not also feed items.
39 */
40 export function variantGroupsOf(
41 db: Database,
42 repos: readonly Repo[],
43 ): { repo_id: string; g: string }[] {
44 if (repos.length === 0) return [];
45 const marks = repos.map((_, i) => `?${i + 1}`).join(",");
46 return db
47 .query<{ repo_id: string; g: string }, string[]>(
48 `SELECT i.repo_id AS repo_id, p.variant_group AS g FROM pull p JOIN issue i ON i.id = p.issue_id
49 WHERE i.repo_id IN (${marks}) AND p.variant_group IS NOT NULL
50 GROUP BY i.repo_id, p.variant_group HAVING COUNT(*) >= 2`,
51 )
52 .all(...repos.map((r) => r.id));
53 }
54
55 export function chooseCandidates(
56 db: Database,
57 repos: readonly Repo[],
58 now: number,
59 ): Candidate[] {
60 const out: Candidate[] = [];
61 const groups = variantGroupsOf(db, repos);
62 const byId = new Map(repos.map((r) => [r.id, r]));
63 for (const { repo_id, g } of groups) {
64 const repo = byId.get(repo_id);
65 if (!repo) continue;
66 const members = variantMembers(db, repo.id, g);
67 if (members.length < 2) continue;
68 const open = members.filter(isOpen);
outdated

at is now for undecided groups, so the item looks new on every read and paging cursors are unstable. Use the newest member's updatedAt.

69 const shipped = members.find((p) => p.mergedAt !== null);
70 const decided = shipped !== undefined || open.length === 0;
71 const at = decided
72 ? (members
73 .map((p) => p.mergedAt ?? p.closedAt ?? p.updatedAt)
74 .sort()
75 .at(-1) ?? new Date(now).toISOString())
76 : (members
77 .map((p) => p.updatedAt)
78 .sort()
79 .at(-1) ?? new Date(now).toISOString());
80 if (decided && now - Date.parse(at) > DECIDED_DAYS * 86_400_000) continue;
81 const tell = `“${clip(tellOf(db, repo, members), 80)}”`;
82 const what = !decided
83 ? `choose among ${open.length} variants of ${tell}`
84 : shipped !== undefined
85 ? `${tell}: variant #${shipped.number} shipped, the other ${members.length - 1} are settled`
86 : `${tell}: all ${members.length} variants were closed`;
87 out.push({
88 id: `choose:${g}`,
89 kind: "choose",
90 repoId: repo.id,
91 app: `${repo.ownerName}/${repo.name}`,
92 actorId: null,
93 actor: null,
94 at,
95 link: `/${repo.ownerName}/${repo.name}/variants/${g}`,
96 what,
97 urgency: decided ? 0 : CHOOSE_URGENCY,
98 said: what,
99 });
100 }
101 return out;
102 }
src/feed/feed.ts +6 −2
@@ -50,11 +50,15 @@ export function readFeed(
5050 ].filter((c) =>
5151 // An ask is never muted away. Its own dismissal was already read by
5252 // `askLinesFor`, cause-aware: it comes back when something new happens.
53 // A milestone the viewer chose to watch is not muted with its app.
53 // A milestone the viewer chose to watch is not muted with its app, nor
54 // a choice that waits on them.
5455 c.id.startsWith("ask:")
5556 ? true
5657 : !dismissed.has(c.id) &&
57 (c.kind === "ask" || c.kind === "milestone" || !muted.has(c.repoId)),
58 (c.kind === "ask" ||
59 c.kind === "milestone" ||
60 c.kind === "choose" ||
61 !muted.has(c.repoId)),
5862 );
5963 let ranked = rank(candidates, affinityFor(db, viewer, now), now);
6064 const cursor = options.cursor;
src/feed/items.ts +19 −2
@@ -25,6 +25,7 @@ import {
2525 } from "../core/repos.ts";
2626 import { getUserById, type User } from "../core/users.ts";
2727 import { watchedBy } from "../core/watches.ts";
28 import { chooseCandidates, variantGroupsOf } from "./choose.ts";
2829 import { askLinesFor } from "../web/studio/asks.ts";
2930
3031 export type FeedKind =
@@ -39,7 +40,9 @@ export type FeedKind =
3940 | "tell"
4041 | "reply"
4142 | "look"
42 | "milestone";
43 | "milestone"
44 // Sibling pulls of one tell, as one item that opens their deck (#1411).
45 | "choose";
4346
4447 /** What a candidate is, before it is ranked and worded. */
4548 export interface Candidate {
@@ -223,11 +226,15 @@ export function candidatesFor(
223226 return owner.get(repo.id)!;
224227 };
225228
229 // Only a viewer who is shown a group's `choose` item loses its pulls' events.
230 const chosen = new Set(
231 variantGroupsOf(db, writable).map((g) => `${g.repo_id}:${g.g}`),
232 );
226233 const out: Candidate[] = [];
227234 for (const e of events) {
228235 const repo = repos.get(e.repoId!);
229236 if (!repo) continue;
230 const c = fromEvent(db, e, repo, owns(repo));
237 const c = fromEvent(db, e, repo, owns(repo), chosen);
231238 if (c) out.push({ ...c, actor: nameOf(e.actorId) });
232239 }
233240 for (const a of asks) {
@@ -256,6 +263,7 @@ export function candidatesFor(
256263 }
257264 out.push(...watchedCandidates(db, viewer, now));
258265 out.push(...frozenCandidates(db, viewer, now));
266 out.push(...chooseCandidates(db, writable, now));
259267 for (const d of decided) {
260268 const repo = repos.get(d.repoId);
261269 if (!repo) continue;
@@ -282,6 +290,7 @@ function fromEvent(
282290 e: ForgeEvent,
283291 repo: Repo,
284292 ownerFacts: boolean,
293 chosen: ReadonlySet<string>,
285294 ): Partial | undefined {
286295 const common = {
287296 id: `event:${e.id}`,
@@ -295,6 +304,14 @@ function fromEvent(
295304 const number = typeof p["number"] === "number" ? p["number"] : undefined;
296305 const pull = number === undefined ? undefined : getPull(db, repo.id, number);
297306 const title = pull?.title ?? "";
307 // A variant's own events are the group's one `choose` item (`choose.ts`),
308 // for whoever is shown that item; others keep the pull's events.
309 if (
310 e.kind.startsWith("pull.") &&
311 pull?.variantGroup &&
312 chosen.has(`${repo.id}:${pull.variantGroup}`)
313 )
314 return undefined;
298315 const told = pull === undefined ? null : toldBy(db, pull);
299316 const toldParts = [
300317 ...(told === null ? [] : [`told by ${told}`]),
src/web/studio/feed.ts +2 −1
@@ -39,6 +39,7 @@ const KIND_LABEL: Record<FeedItem["kind"], string> = {
3939 tell: "Told",
4040 reply: "Reply",
4141 look: "Look",
42 choose: "Choose",
4243 };
4344
4445 /**
@@ -87,7 +88,7 @@ export function feedCard(
8788 </form>
8889 <span class="fcard-acts">
8990 <button type="button" class="btn btn-sm btn-ghost" data-feed="dismissed" title="Dismiss (x)">Dismiss</button>
90 ${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>`}
91 ${item.kind === "ask" || item.kind === "milestone" || item.kind === "choose" ? null : html`<button type="button" class="btn btn-sm btn-ghost" data-feed="muted" title="Mute ${item.app}">Mute app</button>`}
9192 </span>
9293 </details>
9394 </article>`;
test/feed-choose.test.ts added +150
@@ -0,0 +1,150 @@
1 /**
2 * A variant group is one `choose` item in the feed: it names the tell and the
3 * siblings still open, links to the deck, and stops asking once one sibling
4 * ships or all are closed. Its pulls are not separate feed items.
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 { setIssueState } from "../src/actions/issues.ts";
11 import { openPull } from "../src/actions/pulls.ts";
12 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import { getPull } from "../src/core/pulls.ts";
15 import type { Repo } from "../src/core/repos.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { readFeed } from "../src/feed/feed.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19
20 quietLogs();
21
22 describe("a variant group in the feed", () => {
23 let dataDir: string;
24 let app: App;
25 let alice: User;
26 let bob: User;
27 let lib: Repo;
28 let n = 0;
29
30 const variant = async (group: string) => {
31 const branch = `v${++n}`;
32 const c = await commitToBranch(app, alice, lib, {
33 branch,
34 message: branch,
35 files: [{ path: `${branch}.md`, content: "x\n" }],
36 });
37 if (!c.ok) throw new Error(JSON.stringify(c.error));
38 const o = await openPull(app, alice, lib, {
39 title: `Try ${branch}`,
40 baseBranch: "main",
41 headBranch: branch,
42 variantGroup: group,
43 });
44 if (!o.ok) throw new Error(String(o.error));
45 app.bus.append({
46 kind: "pull.opened",
47 repoId: lib.id,
48 actorId: alice.id,
49 payload: { number: o.value.number },
50 });
51 return o.value;
52 };
53 const items = (who: User) => readFeed(app.db, who, { limit: 50 }).items;
54 const chooses = (who: User, group: string) =>
55 items(who).filter((i) => i.id === `choose:${group}`);
56
57 beforeAll(async () => {
58 dataDir = await mkdtemp(join(tmpdir(), "forge-feed-choose-"));
59 app = createApp({ dataDir, port: 0 });
60 const mk = async (username: string) => {
61 const r = await createUser(app.db, {
62 trusted: true,
63 username,
64 email: `${username}@forge.local`,
65 password: "a-good-passphrase",
66 });
67 if (!r.ok) throw new Error(String(r.error));
68 return r.value;
69 };
70 alice = await mk("alice");
71 bob = await mk("bob");
72 const made = await createRepo(app, alice, { name: "lib", visibility: "public" });
73 if (!made.ok) throw new Error(String(made.error));
74 lib = made.value;
75 const seed = await commitToBranch(app, alice, lib, {
76 message: "seed",
77 files: [{ path: "README.md", content: "# lib\n" }],
78 });
79 if (!seed.ok) throw new Error(JSON.stringify(seed.error));
80 }, 60_000);
81 afterAll(async () => {
82 app.close();
83 await rm(dataDir, { recursive: true, force: true });
84 });
85
86 test("two siblings are one choose item, not two pull items", async () => {
87 const a = await variant("g1");
88 const b = await variant("g1");
89 const feed = items(alice);
90 const found = feed.filter((i) => i.kind === "choose");
91 expect(found.length).toBe(1);
92 expect(found[0]!.link).toBe(`/alice/lib/variants/g1`);
93 expect(found[0]!.what).toContain("2 variants");
94 expect(feed.filter((i) => i.kind === "pull").length).toBe(0);
95 expect(a.number).not.toBe(b.number);
96 });
97
98 test("it is for those who may choose, not for a reader", () => {
99 expect(chooses(bob, "g1").length).toBe(0);
100 });
101
102 test("it counts only the siblings still open", async () => {
103 const a = await variant("g2");
104 await variant("g2");
105 await variant("g2");
106 expect(chooses(alice, "g2")[0]!.what).toContain("3 variants");
107 const closed = setIssueState(app, alice, lib, a, "closed");
108 expect(closed.ok).toBe(true);
109 expect(chooses(alice, "g2")[0]!.what).toContain("2 variants");
110 });
111
112 test("a closed group reads as decided and no longer asks", async () => {
113 const a = await variant("g3");
114 const b = await variant("g3");
115 for (const p of [a, b]) setIssueState(app, alice, lib, getPull(app.db, lib.id, p.number)!, "closed");
116 const [item] = chooses(alice, "g3");
117 expect(item!.what).toContain("closed");
118 expect(item!.what).not.toContain("choose among");
119 });
120
121 test("a shipped sibling decides the group", async () => {
122 const a = await variant("g4");
123 await variant("g4");
124 app.db
125 .query("UPDATE pull SET merged_at = ?1 WHERE issue_id = ?2")
126 .run(new Date().toISOString(), a.id);
127 app.db.query("UPDATE issue SET state = 'closed' WHERE id = ?1").run(a.id);
128 const [item] = chooses(alice, "g4");
129 expect(item!.what).toContain(`variant #${a.number} shipped`);
130 expect(item!.what).not.toContain("choose among");
131 });
132
133 test("a reader still sees the pulls of a group, and a group of one is a pull", async () => {
134 const a = await variant("g5");
135 await variant("g5");
136 const solo = await variant("g6");
137 const readerPulls = items(bob).filter((i) => i.kind === "pull" || i.kind === "pulls");
138 expect(readerPulls.some((i) => i.link.endsWith(`/changes/${a.number}`))).toBe(true);
139 expect(items(alice).some((i) => i.link.endsWith(`/changes/${solo.number}`))).toBe(true);
140 expect(chooses(alice, "g6").length).toBe(0);
141 });
142
143 test("an open group keeps its time between reads", async () => {
144 await variant("g7");
145 await variant("g7");
146 const first = chooses(alice, "g7")[0]!.at;
147 await Bun.sleep(5);
148 expect(chooses(alice, "g7")[0]!.at).toBe(first);
149 });
150 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs