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

Filters the owner sets: which repositories, kinds and people reach the inbox, the feed and the home #1485

Closed opened this in answer to
Closed without merging

scout/forge:scout/1112-filters-the-owner-sets-which-repositorie → main 20 commits fork 1 thread · 1 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
48 files changed +929 −7
.bash_profile added
No content changes.
.bashrc added
No content changes.
.claude/agents added
No content changes.
.claude/commands added
No content changes.
.claude/hooks added
No content changes.
.claude/launch.json added
No content changes.
.claude/loop.md added
No content changes.
.claude/output-styles added
No content changes.
.claude/routines added
No content changes.
.claude/scheduled_tasks.json added
No content changes.
.claude/settings.json added
No content changes.
.claude/settings.local.json added
No content changes.
.claude/skills added
No content changes.
.claude/workflows added
No content changes.
.gitconfig added
No content changes.
.gitmodules added
No content changes.
.idea added
No content changes.
.mcp.json added
No content changes.
.profile added
No content changes.
.ripgreprc added
No content changes.
.vscode added
No content changes.
.zprofile added
No content changes.
.zshrc added
No content changes.
README.md +5
@@ -70,6 +70,11 @@ yourself carry whatever your own git says.
7070 pull requests with a real diff viewer, review comments, merges, settings,
7171 tokens and keys — as a keyboard-driven terminal app. The same port serves git.
7272
73 **Filter** (#1112): you choose which repositories, kinds of activity and people
74 reach your inbox, feed and home. Set it on the page (the Filter row) or in the
75 terminal palette (`filter-<kind>`, `filter-app`, `filter-people`); both store
76 the same thing. Details in [`docs/FEED.md`](docs/FEED.md).
77
7378 ```sh
7479 ssh -p 2222 localhost # the terminal UI
7580 git clone ssh://localhost:2222/you/hello.git # git, same port
docs/FEED.md +11
@@ -16,6 +16,17 @@ Same-origin checked for browser sessions, `rw` for tokens. An `event:` item
1616 names its own repo and actor; any other item names its app as `owner/name`.
1717 Anything the viewer cannot read is a 404.
1818
19 ## What reaches you (`src/core/view.ts`, #1112)
20
21 A filter the viewer sets once, kept per user in `user_view`: repositories
22 muted, kinds hidden (`pulls decisions words releases`), people hidden. It
23 narrows `/live/on-you`, `/live/apps`, `/api/v1/feed`, `/api/v1/asks`, the home's
24 needs-you and the phone's notices. A muted repository's asks still exist and
25 still count on its own page. `GET /api/v1/view` reads it; `PUT /api/v1/view`
26 `{ muted_repos?: ["owner/name"], hidden_kinds?, hidden_people? }` replaces the
27 fields given (same-origin checked, `rw`). MCP: `view`, `view_set`. The home's
28 Filter row posts the same thing to `POST /view`.
29
1930 ## Where items come from (`src/feed/items.ts`)
2031
2132 - Events through `listEventsVisibleTo` then `audienceFilter`: `run.finished`
docs/MCP.md +2
@@ -47,6 +47,8 @@ for a tunnel and a forge that sleeps.
4747 | `app_members` | `{ repo, members?, dryRun? }`: the people a private app names, who may enter it and its previews and nothing else; a writer (never an agent) changes the list with an admin-scope token | yes |
4848 | `explore` | `{ query? }`: the apps and people you can see, ranked by forks, ships, use and freshness, with their numbers; `kind:` `sort:` and words in one line | |
4949 | `feed` | `{ limit?, cursor? }`: your home timeline — tells, replies, runs, changes and looks — ranked, with who, what, why and a link; the same items as `GET /api/v1/feed` | |
50 | `view` | the filter that decides what reaches you: repositories muted, kinds and people hidden; it narrows `asks` and `feed` | |
51 | `view_set` | `{ muted_repos?, hidden_kinds?, hidden_people? }`: set that filter; a field given replaces what was saved | yes |
5052 | `make_it_yours` | `{ repo, name?, visibility?, dryRun? }`: a fork of an app you can see, as your own app, following the original; code and history copied, data and secrets not; private unless `visibility` is public (a public original only); at most 5 copies an account a day; plans unless `dryRun` is false | yes |
5153 | `front_page` | `{ pinned?, hidden?, weights?, dryRun? }`: the front page as a stranger sees it, ranked, with numbers; a site admin sets what is pinned (first public one featured), hidden, and what counts (weights of forks, ships, use, fresh, 0 to 10) | yes |
5254 | `map` | an app's plan: ready now, waiting on what, the critical path, where the crew is, parked twice and why (`app`) | |
scripts/gate.ts +2
@@ -89,6 +89,8 @@ export const GATE: readonly string[] = [
8989 "test/autonomy.test.ts",
9090 "test/studio.test.ts",
9191 "test/studio-words.test.ts",
92 "test/view.test.ts",
93 "test/tui-view.test.ts",
9294 "test/converge-settled.test.ts",
9395 "test/following.test.ts",
9496 "test/forks.test.ts",
src/actions/here.ts +6
@@ -212,6 +212,12 @@ function forgeActions(viewer: User | undefined): Action[] {
212212 mcp: "report",
213213 account: false,
214214 },
215 ...(viewer === undefined
216 ? []
217 : [
218 { do: "read what reaches you (the filter)", http: "GET /api/v1/view", mcp: "view" },
219 { do: "set what reaches you", http: "PUT /api/v1/view", mcp: "view_set" },
220 ]),
215221 ...(viewer === undefined
216222 ? [{ do: "use the MCP", http: "POST /mcp", account: true }]
217223 : [{ do: "use the MCP", http: "POST /mcp" }]),
src/actions/view.ts added +87
@@ -0,0 +1,87 @@
1 /**
2 * Say what reaches you (`core/view.ts`), and read it back — the one place
3 * the page's form, `/api/v1/view` and the MCP tools share. A field left out
4 * keeps what was saved; a field given replaces it whole. Repositories are
5 * named `owner/name` and must be readable by the person.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { canRead, getRepo, getReposByIds } from "../core/repos.ts";
10 import type { User } from "../core/users.ts";
11 import {
12 isViewKind,
13 saveView,
14 VIEW_KINDS,
15 VIEW_MAX,
16 viewOf,
17 type View,
18 } from "../core/view.ts";
19 import { err, ok, type Result } from "../kernel/result.ts";
20
21 export interface ViewAnswer {
22 muted_repos: string[];
23 hidden_kinds: string[];
24 hidden_people: string[];
25 kinds: readonly string[];
26 }
27
28 export function viewAnswer(db: Database, user: User): ViewAnswer {
29 const view = viewOf(db, user.id);
30 const repos = getReposByIds(db, view.mutedRepos);
31 return {
32 muted_repos: view.mutedRepos.flatMap((id) => {
33 const repo = repos.get(id);
34 return repo && canRead(db, repo, user) ? [`${repo.ownerName}/${repo.name}`] : [];
35 }),
36 hidden_kinds: [...view.hiddenKinds],
37 hidden_people: [...view.hiddenPeople],
38 kinds: VIEW_KINDS,
39 };
40 }
41
42 const strings = (v: unknown): string[] | undefined =>
43 Array.isArray(v) && v.length <= VIEW_MAX && v.every((x) => typeof x === "string")
44 ? (v as string[])
45 : undefined;
46
47 export type ViewError = { code: "invalid" | "not_found"; message: string };
48
49 export function setView(
50 db: Database,
51 user: User,
52 input: Record<string, unknown>,
53 ): Result<ViewAnswer, ViewError> {
54 const saved = viewOf(db, user.id);
55 let mutedRepos = saved.mutedRepos;
56 let hiddenKinds = saved.hiddenKinds;
57 let hiddenPeople = saved.hiddenPeople;
58 if (input["muted_repos"] !== undefined) {
59 const names = strings(input["muted_repos"]);
60 if (!names)
61 return err({ code: "invalid", message: `muted_repos is up to ${VIEW_MAX} owner/name strings` });
62 const ids: string[] = [];
63 for (const name of names) {
64 const [owner, repoName, extra] = name.split("/");
65 const repo =
66 owner && repoName && extra === undefined ? getRepo(db, owner, repoName) : undefined;
67 if (!repo || !canRead(db, repo, user))
68 return err({ code: "not_found", message: `no such repository: ${name.slice(0, 80)}` });
69 ids.push(repo.id);
70 }
71 mutedRepos = ids;
72 }
73 if (input["hidden_kinds"] !== undefined) {
74 const kinds = strings(input["hidden_kinds"]);
75 if (!kinds || !kinds.every(isViewKind))
76 return err({ code: "invalid", message: `hidden_kinds are among ${VIEW_KINDS.join(", ")}` });
77 hiddenKinds = kinds as View["hiddenKinds"];
78 }
79 if (input["hidden_people"] !== undefined) {
80 const people = strings(input["hidden_people"]);
81 if (!people || !people.every((p) => /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/.test(p)))
82 return err({ code: "invalid", message: "hidden_people are usernames" });
83 hiddenPeople = people;
84 }
85 saveView(db, user.id, { mutedRepos, hiddenKinds, hiddenPeople });
86 return ok(viewAnswer(db, user));
87 }
src/core/reserved.ts +1
@@ -93,6 +93,7 @@ export const SYSTEM_NAMES: readonly string[] = [
9393 "tell",
9494 "theme",
9595 "verify",
96 "view",
9697 "www",
9798 "asked",
9899 "claim",
src/core/schema.ts +9
@@ -1595,6 +1595,15 @@ export const migrations: readonly string[] = [
15951595 PRIMARY KEY (repo_id, parent_id, issue_id)
15961596 );
15971597 `,
1598 // 76 — what reaches a person (#1112): one JSON filter per user —
1599 // repositories muted, kinds and people hidden (`core/view.ts`).
1600 `
1601 CREATE TABLE user_view (
1602 user_id TEXT PRIMARY KEY REFERENCES user(id) ON DELETE CASCADE,
1603 filter TEXT NOT NULL,
1604 updated_at TEXT NOT NULL
1605 );
1606 `,
15981607 ];
15991608
16001609 /**
src/core/view.ts added +116
@@ -0,0 +1,116 @@
1 /**
2 * What reaches a person: the filter they set once and the forge remembers.
3 * One row per user (`user_view`), a small JSON document — repositories
4 * muted, kinds hidden, people hidden. Pure data: it narrows the inbox, the
5 * feed, the home's panels and the phone's notices, never a page about the
6 * thing itself, so a muted repository's asks still count on its own page.
7 */
8
9 import type { Database } from "bun:sqlite";
10
11 /** The kinds a person can hide. Anything else (runs, cost, the map) always shows. */
12 export const VIEW_KINDS = ["pulls", "decisions", "words", "releases"] as const;
13 export type ViewKind = (typeof VIEW_KINDS)[number];
14
15 export const isViewKind = (v: unknown): v is ViewKind =>
16 typeof v === "string" && (VIEW_KINDS as readonly string[]).includes(v);
17
18 export const VIEW_KIND_LABEL: Readonly<Record<ViewKind, string>> = {
19 pulls: "Pulls to review",
20 decisions: "Decisions",
21 words: "The crew's words",
22 releases: "Releases",
23 };
24
25 export const VIEW_MAX = 200;
26 const REPO_ID = /^[A-Za-z0-9_-]{1,64}$/;
27 const USERNAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
28
29 export interface View {
30 /** Repository ids that do not reach the person. */
31 readonly mutedRepos: readonly string[];
32 /** Kinds that do not reach them. */
33 readonly hiddenKinds: readonly ViewKind[];
34 /** Usernames (lower case) whose doings do not reach them. */
35 readonly hiddenPeople: readonly string[];
36 }
37
38 export const NO_VIEW: View = { mutedRepos: [], hiddenKinds: [], hiddenPeople: [] };
39
40 const unique = <T>(xs: readonly T[]): T[] => [...new Set(xs)];
41
42 /** A view from anything: unknown shapes and bad members are dropped, never kept. */
43 export function parseView(raw: unknown): View {
44 const o = typeof raw === "object" && raw !== null ? (raw as Record<string, unknown>) : {};
45 const list = (v: unknown): unknown[] => (Array.isArray(v) ? v.slice(0, VIEW_MAX) : []);
46 return {
47 mutedRepos: unique(
48 list(o["mutedRepos"]).filter((x): x is string => typeof x === "string" && REPO_ID.test(x)),
49 ),
50 hiddenKinds: unique(list(o["hiddenKinds"]).filter(isViewKind)),
51 hiddenPeople: unique(
52 list(o["hiddenPeople"])
53 .filter((x): x is string => typeof x === "string" && USERNAME.test(x))
54 .map((x) => x.toLowerCase()),
55 ),
56 };
57 }
58
59 export function viewOf(db: Database, userId: string): View {
60 const row = db
61 .query<{ filter: string }, [string]>("SELECT filter FROM user_view WHERE user_id = ?1")
62 .get(userId);
63 if (!row) return NO_VIEW;
64 try {
65 return parseView(JSON.parse(row.filter));
66 } catch {
67 return NO_VIEW;
68 }
69 }
70
71 export function saveView(db: Database, userId: string, view: View): View {
72 const clean = parseView(view);
73 db.query(
74 `INSERT INTO user_view (user_id, filter, updated_at) VALUES (?1, ?2, ?3)
75 ON CONFLICT(user_id) DO UPDATE SET filter = excluded.filter, updated_at = excluded.updated_at`,
76 ).run(userId, JSON.stringify(clean), new Date().toISOString());
77 return clean;
78 }
79
80 /** What a thing is, for the filter: its repository, its kind (if it has one a person can hide), its doer. */
81 export interface Subject {
82 readonly repoId: string;
83 readonly kind: ViewKind | undefined;
84 readonly person: string | null | undefined;
85 }
86
87 /** Whether a thing reaches the person whose view this is. */
88 export function reaches(view: View, s: Subject): boolean {
89 if (view.mutedRepos.includes(s.repoId)) return false;
90 if (s.kind !== undefined && view.hiddenKinds.includes(s.kind)) return false;
91 if (s.person && view.hiddenPeople.includes(s.person.toLowerCase())) return false;
92 return true;
93 }
94
95 /** The ask kinds a person can hide: a change waiting on a person is a pull, the rest are decisions. */
96 export const viewKindOfAsk = (kind: string): ViewKind =>
97 kind === "look" || kind === "review" || kind === "stopped" ? "pulls" : "decisions";
98
99 /** A feed item's kind as the filter names it; undefined when it cannot be hidden. */
100 export function viewKindOfFeed(kind: string): ViewKind | undefined {
101 switch (kind) {
102 case "pull":
103 return "pulls";
104 case "ask":
105 case "decision":
106 return "decisions";
107 case "tell":
108 case "reply":
109 case "look":
110 return "words";
111 case "milestone":
112 return "releases";
113 default:
114 return undefined;
115 }
116 }
src/feed/feed.ts +9 −1
@@ -13,6 +13,7 @@ import { canRead, getRepoById } from "../core/repos.ts";
1313 import { deliveredFor, drainQueue, senderWeight } from "../core/shares.ts";
1414 import { getUserById, type User } from "../core/users.ts";
1515 import { candidatesFor, type Candidate } from "./items.ts";
16 import { reaches, viewKindOfFeed, viewOf } from "../core/view.ts";
1617 import { rank, type FeedItem } from "./rank.ts";
1718
1819 export const FEED_LIMIT_DEFAULT = 20;
@@ -39,6 +40,7 @@ export function readFeed(
3940 const limit = Math.min(options.limit ?? FEED_LIMIT_DEFAULT, FEED_LIMIT_MAX);
4041 const muted = mutedRepos(db, viewer.id);
4142 const dismissed = dismissedItems(db, viewer.id);
43 const view = viewOf(db, viewer.id);
4244 drainQueue(db, viewer.id, now);
4345 const shared = sharedCandidates(db, viewer, now).filter(
4446 (c) => !dismissed.has(c.itemId),
@@ -47,7 +49,13 @@ export function readFeed(
4749 const candidates = [
4850 ...candidatesFor(db, viewer, now).filter((c) => !boosted.has(c.id)),
4951 ...shared,
50 ].filter((c) =>
52 ]
53 // An ask was filtered where it was made (`askLinesFor`), by its own kinds.
54 .filter((c) =>
55 c.id.startsWith("ask:") ||
56 reaches(view, { repoId: c.repoId, kind: viewKindOfFeed(c.kind), person: c.actor }),
57 )
58 .filter((c) =>
5159 // An ask is never muted away. Its own dismissal was already read by
5260 // `askLinesFor`, cause-aware: it comes back when something new happens.
5361 // A milestone the viewer chose to watch is not muted with its app.
src/http/feed.ts +17
@@ -19,6 +19,7 @@ import {
1919 parseCursor,
2020 readFeed,
2121 } from "../feed/feed.ts";
22 import { setView, viewAnswer } from "../actions/view.ts";
2223 import { asksAnswer } from "../web/studio/asks.ts";
2324 import {
2425 applyAsksBulk,
@@ -64,6 +65,22 @@ export function feedRoutes(router: Router<Handler>): void {
6465 );
6566 });
6667
68 // What reaches the viewer (`core/view.ts`): read it, or replace the fields given.
69 router.add("GET", "/api/v1/view", (ctx) => {
70 const viewer = ctx.auth.user;
71 if (!viewer) return unauthorized();
72 return json(viewAnswer(ctx.app.db, viewer), 200, { "cache-control": "private, no-store" });
73 });
74
75 router.add("PUT", "/api/v1/view", async (ctx) => {
76 const denied = requireScope(ctx, "rw");
77 if (denied) return denied;
78 const set = setView(ctx.app.db, ctx.auth.user!, await body(ctx.request));
79 if (!set.ok)
80 return apiError(set.error.code, set.error.code === "invalid" ? 422 : 404, set.error.message);
81 return json(set.value);
82 });
83
6784 // What asks the viewer, ranked, with the week's measure (`asksAnswer`).
6885 router.add("GET", "/api/v1/asks", (ctx) => {
6986 const viewer = ctx.auth.user;
src/http/mcp.ts +34 −2
@@ -119,6 +119,7 @@ import { resourceMetadataUrl } from "./oauth.ts";
119119 import { body, boundedBody, json } from "./respond.ts";
120120 import type { Router } from "./router.ts";
121121 import { mayReadRuns } from "../actions/runs.ts";
122 import { setView, viewAnswer } from "../actions/view.ts";
122123 import { manifestFor } from "../actions/here.ts";
123124 import { clientBucket } from "./peer.ts";
124125 import { fileReport } from "../actions/reports.ts";
@@ -419,13 +420,44 @@ const TOOLS: readonly Tool[] = [
419420 {
420421 name: "asks",
421422 description:
422 "What waits on you, most consequential first: each row names the decision, its options and what happens if nobody acts, and why it ranks where it does (security, money, held-up work, then age). Rows of one kind in one app are collapsed with their item ids. Also the forge's own needs (for a site admin) and the last 7 days' asks raised, acted on, dismissed and gone by themselves.",
423 "What waits on you, most consequential first: each row names the decision, its options and what happens if nobody acts, and why it ranks where it does (security, money, held-up work, then age). Rows of one kind in one app are collapsed with their item ids. Less what your `view` filter keeps from you. Also the forge's own needs (for a site admin) and the last 7 days' asks raised, acted on, dismissed and gone by themselves.",
423424 inputSchema: { type: "object", properties: {} },
424425 writes: false,
425426 run(ctx, user) {
426427 return good(asksAnswer(ctx, user));
427428 },
428429 },
430 {
431 name: "view",
432 description:
433 "The filter that decides what reaches you: repositories muted (`owner/name`), kinds hidden (pulls, decisions, words, releases) and people hidden. It narrows `asks`, `feed`, the home and the phone's notices; a muted repository's asks still exist and still count on its own page.",
434 inputSchema: { type: "object", properties: {} },
435 writes: false,
436 run(ctx, user) {
437 return good(viewAnswer(ctx.app.db, user));
438 },
439 },
440 {
441 name: "view_set",
442 description:
443 "Set what reaches you. Each field given replaces what was saved; a field left out is kept. The forge remembers it for `asks`, `feed` and the home.",
444 inputSchema: {
445 type: "object",
446 properties: {
447 muted_repos: { type: "array", items: { type: "string" }, maxItems: 200 },
448 hidden_kinds: {
449 type: "array",
450 items: { type: "string", enum: ["pulls", "decisions", "words", "releases"] },
451 },
452 hidden_people: { type: "array", items: { type: "string" }, maxItems: 200 },
453 },
454 },
455 writes: true,
456 run(ctx, user, args) {
457 const set = setView(ctx.app.db, user, args);
458 return set.ok ? good(set.value) : bad(set.error.code, set.error.message);
459 },
460 },
429461 {
430462 name: "asks_act",
431463 description:
@@ -1027,7 +1059,7 @@ const TOOLS: readonly Tool[] = [
10271059 {
10281060 name: "feed",
10291061 description:
1030 "Your home timeline, as the forge's home shows it: tells, replies, runs, changes and looks across the apps you can see, ranked, each with who did it, what it says, why it is there and a link to its thing. Pass `cursor` (next_cursor from the last answer) for the next page. The same items as GET /api/v1/feed.",
1062 "Your home timeline, as the forge's home shows it: tells, replies, runs, changes and looks across the apps you can see, ranked, each with who did it, what it says, why it is there and a link to its thing. Pass `cursor` (next_cursor from the last answer) for the next page. The same items as GET /api/v1/feed, less what your `view` filter keeps from you.",
10311063 inputSchema: {
10321064 type: "object",
10331065 properties: {
src/http/server.ts +2
@@ -5,6 +5,7 @@
55 * verdict. Auth is resolved once per request and handed to handlers as data.
66 */
77
8 import { viewSubmit } from "../web/studio/view_row.ts";
89 import { unsealReleased } from "../actions/sealed.ts";
910 import { capacityPage, capacitySet } from "../web/pages/capacity.ts";
1011 import {
@@ -572,6 +573,7 @@ export function buildRouter(): Router<Handler> {
572573 router.add("GET", "/board/returns", returnsPage);
573574 // One screen for "is everything fine?": what asks the viewer (docs/STUDIO.md).
574575 router.add("GET", "/asks", asksPage);
576 router.add("POST", "/view", viewSubmit);
575577 router.add("POST", "/asks/bulk", asksBulkSubmit);
576578 router.add("POST", "/asks/bulk/:id/undo", asksBulkUndo);
577579 router.add("POST", "/asks/listen", asksListen);
src/tui/forge.ts +4
@@ -38,6 +38,8 @@ import { repoScreen } from "./screens/repo.ts";
3838 import { signInScreen } from "./screens/signin.ts";
3939 import { local } from "./screens/where.ts";
4040
41 import { viewCommands } from "./view_commands.ts";
42
4143 export { Session, type TuiIdentity };
4244
4345 export function forgeRoot(session: Session): (ctx: Ctx) => Screen {
@@ -122,6 +124,8 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
122124 },
123125 ];
124126
127 commands.push(...viewCommands(session, ctx, askFor));
128
125129 for (const verb of REPO_VERBS)
126130 commands.push({
127131 id: verb.id,
src/tui/screens/dashboard.ts +10
@@ -18,6 +18,7 @@ import { forgeNeeds } from "../../actions/health.ts";
1818 import { mayView } from "../../core/sealed.ts";
1919 import { pinRepo, unpinRepo } from "../../actions/origins.ts";
2020 import { listAssignedTo, type Issue } from "../../core/issues.ts";
21 import { reaches, viewOf } from "../../core/view.ts";
2122 import { listPins, pinnedRepoIds, type Pin } from "../../core/pins.ts";
2223 import { listOrgsForUser } from "../../core/orgs.ts";
2324 import {
@@ -134,9 +135,16 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
134135 f.db,
135136 issues.map((issue) => issue.repoId),
136137 );
138 const view = viewOf(f.db, f.user.id);
137139 return issues.flatMap((issue) => {
138140 const repo = byId.get(issue.repoId);
141 // What the person's filter keeps from them, as the web's list does.
139142 return repo !== undefined &&
143 reaches(view, {
144 repoId: repo.id,
145 kind: issue.kind === "pull" ? "pulls" : undefined,
146 person: issue.authorName,
147 }) &&
140148 canRead(f.db, repo, f.user) &&
141149 mayView(f.db, repo, issue, f.user)
142150 ? [{ issue, repo }]
@@ -259,6 +267,8 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
259267 // The repo list, the counts beside it and what is on you are all
260268 // functions of the outbox, so one subscription refreshes all of them.
261269 live(f, signal, {}, reload);
270 f.onViewChange.add(reload);
271 signal.addEventListener("abort", () => f.onViewChange.delete(reload));
262272 reload();
263273 return Promise.resolve();
264274 },
src/tui/session.ts +2
@@ -51,6 +51,8 @@ export type SignInError =
5151 export class Session {
5252 user: User | undefined;
5353 keyId: string | undefined;
54 /** Screens that list what reaches the person, told when their filter changes (#1112). */
55 readonly onViewChange = new Set<() => void>();
5456
5557 constructor(
5658 readonly app: App,
src/tui/view_commands.ts added +80
@@ -0,0 +1,80 @@
1 /**
2 * The filter (#1112) from the palette: toggle a kind, mute or unmute an app, hide people.
3 * Both go through `setView`, the call the page, the API and MCP make, so the
4 * terminal cannot store anything they would refuse.
5 */
6
7 import { setView, viewAnswer } from "../actions/view.ts";
8 import { VIEW_KIND_LABEL, VIEW_KINDS } from "../core/view.ts";
9 import type { Ctx, Screen } from "./app/app.ts";
10 import type { Command } from "./app/palette.ts";
11 import type { Session } from "./session.ts";
12
13 type Ask = (
14 ctx: Ctx,
15 title: string,
16 label: string,
17 onSubmit: (value: string) => string | undefined,
18 ) => Screen;
19
20 export function viewCommands(session: Session, ctx: Ctx, ask: Ask): Command[] {
21 const user = session.user;
22 if (user === undefined) return [];
23 const say = (result: ReturnType<typeof setView>, done: string): void =>
24 ctx.toast(result.ok ? done : result.error.message, result.ok ? "success" : "danger");
25 const kinds = VIEW_KINDS.map(
26 (kind): Command => ({
27 id: `filter-${kind}`,
28 title: `Filter: show or hide ${VIEW_KIND_LABEL[kind]}`,
29 hint: "what reaches you",
30 run: () => {
31 const hidden = viewAnswer(session.db, user).hidden_kinds;
32 const on = hidden.includes(kind);
33 say(
34 setView(session.db, user, {
35 hidden_kinds: on ? hidden.filter((k) => k !== kind) : [...hidden, kind],
36 }),
37 on ? `${VIEW_KIND_LABEL[kind]} shown` : `${VIEW_KIND_LABEL[kind]} hidden`,
38 );
39 for (const reload of session.onViewChange) reload();
40 },
41 }),
42 );
43 const app: Command = {
44 id: "filter-app",
45 title: "Filter: mute or unmute an app",
46 hint: "owner/name",
47 run: () =>
48 ctx.push(
49 ask(ctx, "Mute or unmute", "owner/name", (spec) => {
50 const muted = viewAnswer(session.db, user).muted_repos;
51 const key = spec.toLowerCase();
52 const on = muted.some((m) => m.toLowerCase() === key);
outdated

key is lowercased, but muted holds ${ownerName}/${name} as stored. A repository with upper case in its name can never be unmuted from here: the toggle adds it again. Compare with muted.find((m) => m.toLowerCase() === key) and filter on the same test.

53 const set = setView(session.db, user, {
54 muted_repos: on ? muted.filter((m) => m.toLowerCase() !== key) : [...muted, key],
55 });
56 if (!set.ok) return "not found";
57 say(set, on ? `${spec} unmuted` : `${spec} muted`);
58 for (const reload of session.onViewChange) reload();
59 return undefined;
60 }),
61 ),
62 };
63 const people: Command = {
64 id: "filter-people",
65 title: "Filter: hide people",
66 hint: "usernames, empty shows everyone",
67 run: () =>
68 ctx.push(
69 ask(ctx, "Hide people", "usernames", (value) => {
70 const names = value.split(/[\s,]+/).filter((n) => n !== "");
71 const set = setView(session.db, user, { hidden_people: names });
72 if (!set.ok) return set.error.message;
73 say(set, names.length === 0 ? "everyone shown" : `${names.length} hidden`);
74 for (const reload of session.onViewChange) reload();
75 return undefined;
76 }),
77 ),
78 };
79 return [...kinds, app, people];
80 }
src/web/pages/site.ts +11
@@ -8,6 +8,7 @@
88 * typed still in it. A dead end that loses input is a bug, not a message.
99 */
1010
11 import { reaches, viewOf } from "../../core/view.ts";
1112 import { mayView } from "../../core/sealed.ts";
1213 import { signOutHere } from "../../actions/signins.ts";
1314 import { clientAddress } from "../../http/peer.ts";
@@ -184,6 +185,7 @@ export function onYouCard(ctx: Ctx, user: User): Html | undefined {
184185 const visible = new Set(
185186 listReposVisibleTo(db, user, { limit: 200 }).map((repo) => repo.id),
186187 );
188 const view = viewOf(db, user.id);
187189 const muted = mutedRepos(db, user.id);
188190 const shown: { issue: Issue; repo: Repo }[] = [];
189191 // Muted repositories that hold work assigned to the viewer: said, never silent.
@@ -191,6 +193,15 @@ export function onYouCard(ctx: Ctx, user: User): Html | undefined {
191193 for (const issue of assigned) {
192194 const repo = repos.get(issue.repoId);
193195 if (!repo) continue;
196 // What the person's filter keeps from them (`core/view.ts`).
197 if (
198 !reaches(view, {
199 repoId: repo.id,
200 kind: issue.kind === "pull" ? "pulls" : undefined,
201 person: issue.authorName,
202 })
203 )
204 continue;
194205 if (!visible.has(repo.id) && !canRead(db, repo, user)) continue;
195206 if (!mayView(db, repo, issue, user)) continue;
196207 if (muted.has(repo.id)) {
src/web/studio/asks.ts +11 −2
@@ -7,6 +7,7 @@
77 * to the route a person could have posted to by hand (`actions.ts`).
88 */
99
10 import { reaches, viewKindOfAsk, viewOf } from "../../core/view.ts";
1011 import type { Database } from "bun:sqlite";
1112 import { previewEnv } from "../../apps/data.ts";
1213 import { crewForRepos } from "../../core/agents.ts";
@@ -542,14 +543,22 @@ function scoredFor(
542543 return asks.map((a) => ({ ...a, consequence: scores.get(a.id)! }));
543544 }
544545
545 /** What asks the viewer now: candidates, less what they set aside. */
546 /**
547 * What asks the viewer now: candidates, less what they set aside and what
548 * their filter keeps from them (`core/view.ts`). The filter narrows what
549 * reaches them; the asks themselves stay, and count on their own page
550 * (`decisionsFor`'s `evenDismissed`).
551 */
546552 function waitingOn(
547553 db: Database,
548554 user: User | undefined,
549555 repos: readonly Repo[],
550556 ): Scored[] {
551557 if (!user) return [];
552 return notDismissed(db, user, scoredFor(db, user, repos));
558 const view = viewOf(db, user.id);
559 return notDismissed(db, user, scoredFor(db, user, repos)).filter((a) =>
560 reaches(view, { repoId: a.repo.id, kind: viewKindOfAsk(a.kind), person: a.who }),
561 );
553562 }
554563
555564 /** How an ask that is no longer asked ended, when nobody dismissed it. */
src/web/studio/home.ts +7 −2
@@ -17,6 +17,7 @@ import {
1717 import { appsRuntime } from "../../apps/runtime.ts";
1818 import { appsForRepos } from "../../core/apps.ts";
1919 import { WEIGHT_MAX, WEIGHT_NAMES } from "../../core/front.ts";
20 import { viewOf } from "../../core/view.ts";
2021 import { LOOK_SIZES } from "../../core/looks.ts";
2122 import { canRead, getRepo, type Repo } from "../../core/repos.ts";
2223 import { type User } from "../../core/users.ts";
@@ -48,6 +49,7 @@ import { writableAppsOf } from "./asks.ts";
4849 import { needsYouSection, type AsksTop } from "./asks_page.ts";
4950 import { composer, feedJs, feedNote, feedRegion } from "./feed.ts";
5051 import { homeTabs } from "./home_tabs.ts";
52 import { viewRow } from "./view_row.ts";
5153 import { crewKeyNote } from "./crew.ts";
5254 import { everydayCard } from "../pages/everyday.ts";
5355 import { nextStepsCard } from "../pages/next-steps.ts";
@@ -67,7 +69,10 @@ const RAIL_APPS = 8;
6769 * The apps' full rows are `/apps`.
6870 */
6971 function yourApps(ctx: Ctx, user: User): Html {
70 const { repos } = writableAppsOf(ctx, user);
72 const view = viewOf(ctx.app.db, user.id);
73 const repos = writableAppsOf(ctx, user).repos.filter(
74 (r) => !view.mutedRepos.includes(r.id),
75 );
7176 const runtime = appsRuntime(ctx.app);
7277 const records = appsForRepos(
7378 ctx.app.db,
@@ -191,7 +196,7 @@ export async function studioHome(
191196 ${homeTabs("feed")}
192197 <div class="dash">
193198 <div class="dash-main stack">
194 ${needsYou.body} ${composer(ctx, user)}
199 ${viewRow(ctx, user)} ${needsYou.body} ${composer(ctx, user)}
195200 <div class="bar feed-head">
196201 <span class="spacer"></span>
197202 <a class="small muted" href="/asked">What you asked for</a>
src/web/studio/view_row.ts added +112
@@ -0,0 +1,112 @@
1 /**
2 * The filter row on the home (#1112): repository chips, kind chips and
3 * people, saved per person (`core/view.ts`) and applied to the inbox, the
4 * feed and the rail. Plain checkboxes in a form — it works with no script —
5 * and one POST that saves the whole row.
6 */
7
8 import { canRead, getReposByIds, type Repo } from "../../core/repos.ts";
9 import type { User } from "../../core/users.ts";
10 import {
11 isViewKind,
12 saveView,
13 VIEW_KIND_LABEL,
14 VIEW_KINDS,
15 VIEW_MAX,
16 viewOf,
17 } from "../../core/view.ts";
18 import type { Ctx } from "../../http/context.ts";
19 import { signInFirst } from "../chrome.ts";
20 import { field, readForm } from "../form.ts";
21 import { html, type Html } from "../html.ts";
22 import { redirect } from "../layout.ts";
23 import { btn } from "../ui.ts";
24 import { writableAppsOf } from "./asks.ts";
25
26 /** How many repository chips the row offers. */
27 const CHIPS = 24;
28
29 const chip = (name: string, value: string, label: string, on: boolean): Html =>
30 html`<label class="view-chip"
31 ><input type="checkbox" name="${name}" value="${value}" ${on ? html`checked` : null} />
32 ${label}</label
33 >`;
34
35 export function viewRow(ctx: Ctx, user: User): Html {
36 const view = viewOf(ctx.app.db, user.id);
37 const repos: Repo[] = writableAppsOf(ctx, user).repos.slice(0, CHIPS);
38 const quiet = view.mutedRepos.length + view.hiddenKinds.length + view.hiddenPeople.length;
39 return html`<details class="quiet-details view-row" id="view-row" ${quiet > 0 ? html`open` : null}>
40 <summary>
41 Filter${quiet > 0 ? html` <span class="muted small">· ${quiet} kept out</span>` : null}
42 </summary>
43 <form method="post" action="/view" class="stack">
44 <div class="bar" role="group" aria-label="Kinds">
45 ${VIEW_KINDS.map((k) =>
46 chip("show_kind", k, VIEW_KIND_LABEL[k], !view.hiddenKinds.includes(k)),
47 )}
48 </div>
49 ${repos.length === 0
50 ? null
51 : html`<div class="bar" role="group" aria-label="Apps">
52 ${repos.map(
53 (r) => html`<input type="hidden" name="listed" value="${r.id}" />${chip(
54 "show_repo",
55 r.id,
56 `${r.ownerName}/${r.name}`,
57 !view.mutedRepos.includes(r.id),
58 )}`,
59 )}
60 </div>`}
61 <label class="small muted"
62 >People kept out (usernames)
63 <input
64 class="input"
65 name="hide_people"
66 maxlength="500"
67 autocomplete="off"
68 value="${view.hiddenPeople.join(" ")}"
69 />
70 </label>
71 <div class="bar">
72 ${btn("Save", { size: "sm" })}
73 <span class="muted small"
74 >A muted app's asks still count on its own page.</span
75 >
76 </div>
77 </form>
78 </details>`;
79 }
80
81 // POST /view — save the row, back to the home.
82 export async function viewSubmit(ctx: Ctx): Promise<Response> {
83 const user = ctx.auth.user;
84 if (!user) return signInFirst(ctx);
85 const form = await readForm(ctx, "rw");
86 if (form instanceof Response) return form;
87 const db = ctx.app.db;
88 const saved = viewOf(db, user.id);
89 const strings = (name: string): string[] =>
90 form.getAll(name).filter((v): v is string => typeof v === "string");
91 // Only repositories the row listed were on offer: a chip left unchecked
92 // is muted, and a repository it did not list keeps what was saved. Ids
93 // are checked against the repositories this person can see.
94 const listed = new Set(strings("listed").slice(0, VIEW_MAX));
95 const shownRepos = new Set(strings("show_repo"));
96 const known = getReposByIds(db, [...listed]);
97 const readable = (id: string): boolean => {
98 const repo = known.get(id);
99 return repo !== undefined && canRead(db, repo, user);
100 };
101 const mutedRepos = [
102 ...saved.mutedRepos.filter((id) => !listed.has(id)),
103 ...[...listed].filter((id) => readable(id) && !shownRepos.has(id)),
104 ];
105 const shownKinds = new Set(strings("show_kind"));
106 saveView(db, user.id, {
107 mutedRepos,
108 hiddenKinds: VIEW_KINDS.filter((k) => !shownKinds.has(k) && isViewKind(k)),
109 hiddenPeople: field(form, "hide_people").split(/[\s,]+/).filter((p) => p !== "").slice(0, VIEW_MAX),
110 });
111 return redirect("/");
112 }
src/web/style/content.ts +5
@@ -1206,6 +1206,11 @@ textarea.editor:focus { outline: none; }
12061206 }
12071207 }
12081208 .needs-you .ask-group > summary { padding: 10px 14px; cursor: pointer; }
1209 .view-row .view-chip {
1210 display: inline-flex; align-items: center; gap: 4px; padding: 2px 10px;
1211 border: 1px solid var(--line); border-radius: 999px; font-size: 13px; cursor: pointer;
1212 }
1213 .view-row .view-chip:has(input:checked) { border-color: var(--accent); }
12091214 /* An ask's actions: the decider, then the rest. Wide: in a line, as ever.
12101215 The kind label is for a phone, where the sentence under the title goes. */
12111216 .ask-acts { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; margin-top: 12px; }
test/mcp.test.ts +2
@@ -161,6 +161,8 @@ describe("the forge over MCP", () => {
161161 "say",
162162 "edit",
163163 "asks",
164 "view",
165 "view_set",
164166 "asks_act",
165167 "seal",
166168 "now",
test/tui-view.test.ts added +150
@@ -0,0 +1,150 @@
1 /** The filter (#1112) at the terminal's door: the dashboard's "On you" obeys it, and the palette sets it. */
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 { assignIssue, openIssue } from "../src/actions/issues.ts";
7 import { createRepo } from "../src/actions/repos.ts";
8 import { setView } from "../src/actions/view.ts";
9 import { signUp } from "../src/actions/users.ts";
10 import { createApp, type App as Forge } from "../src/app.ts";
11 import { viewOf } from "../src/core/view.ts";
12 import type { User } from "../src/core/users.ts";
13 import { createForgeApp } from "../src/tui/forge.ts";
14 import { headlessTerminal } from "../src/tui/term/terminal.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16 import { settleApp } from "./helpers/tui.ts";
17
18 quietLogs();
19
20 let dir: string;
21 let forge: Forge;
22 let alice: User;
23
24 beforeAll(async () => {
25 dir = await mkdtemp(join(tmpdir(), "forge-tui-view-"));
26 forge = createApp({ dataDir: dir, port: 0 });
27 const a = await signUp(forge, {
28 username: "alice",
29 email: "[email protected]",
30 password: "a-long-passphrase",
31 });
32 if (!a.ok) throw new Error("signup failed");
33 alice = a.value;
34 for (const name of ["loud", "calm"]) {
35 const r = await createRepo(forge, alice, { name, visibility: "public" });
36 if (!r.ok) throw new Error("repo failed");
37 const i = openIssue(forge, alice, r.value, { title: `Task in ${name}` });
38 if (!i.ok) throw new Error("issue failed");
39 assignIssue(forge, alice, r.value, i.value, alice);
40 }
41 });
42
43 afterAll(async () => {
44 forge.close();
45 await rm(dir, { recursive: true, force: true });
46 });
47
48 function boot() {
49 const terminal = headlessTerminal(120, 32);
50 const { app } = createForgeApp(
51 forge,
52 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user: alice },
53 { terminal, exitHooks: false },
54 );
55 app.start();
56 const key = async (k: string): Promise<void> => {
57 app.dispatch({ type: "key", key: k, ctrl: false, alt: false, shift: false });
58 await settleApp(app);
59 };
60 const type = async (t: string): Promise<void> => {
61 for (const ch of t) app.dispatch({ type: "key", key: ch, ctrl: false, alt: false, shift: false });
62 await settleApp(app);
63 };
64 return { app, key, type, text: () => app.screen.toText() };
65 }
66
67 test("a muted app's assignment leaves the terminal's On you, and the palette mutes it", async () => {
68 const h = boot();
69 await settleApp(h.app);
70 expect(h.text()).toContain("Task in loud");
71 expect(h.text()).toContain("Task in calm");
72
73 await h.key(":");
74 await h.type("mute or unmute an app");
75 await h.key("enter");
76 await h.type("alice/loud");
77 await h.key("enter");
78 expect(viewOf(forge.db, alice.id).mutedRepos).toHaveLength(1);
79 expect(h.text()).not.toContain("Task in loud");
80 expect(h.text()).toContain("Task in calm");
81 h.app.stop();
82
83 // A fresh session reads the saved filter, not the palette's memory.
84 const again = boot();
85 await settleApp(again.app);
86 expect(again.text()).not.toContain("Task in loud");
87 again.app.stop();
88 });
89
90 test("the palette toggles a kind through setView", async () => {
91 const h = boot();
92 await settleApp(h.app);
93 await h.key(":");
94 await h.type("show or hide Releases");
95 await h.key("enter");
96 expect(viewOf(forge.db, alice.id).hiddenKinds).toEqual(["releases"]);
97 h.app.stop();
98 setView(forge.db, alice, { hidden_kinds: [], muted_repos: [] });
99 });
100
101 test("the palette hides people, reads them like the form, and refuses a bad name", async () => {
102 const h = boot();
103 await settleApp(h.app);
104 await h.key(":");
105 await h.type("hide people");
106 await h.key("enter");
107 await h.type("Bob, carol");
108 await h.key("enter");
109 expect(viewOf(forge.db, alice.id).hiddenPeople).toEqual(["bob", "carol"]);
110 await h.key(":");
111 await h.type("hide people");
112 await h.key("enter");
113 await h.key("enter");
114 expect(viewOf(forge.db, alice.id).hiddenPeople).toEqual([]);
115 h.app.stop();
116 });
117
118 test("unmuting is case-insensitive", async () => {
119 setView(forge.db, alice, { muted_repos: [] });
120 const h = boot();
121 await settleApp(h.app);
122 const toggle = async (spec: string): Promise<void> => {
123 await h.key(":");
124 await h.type("mute or unmute an app");
125 await h.key("enter");
126 await h.type(spec);
127 await h.key("enter");
128 };
129 await toggle("alice/loud");
130 expect(viewOf(forge.db, alice.id).mutedRepos).toHaveLength(1);
131 await toggle("Alice/Loud");
132 expect(viewOf(forge.db, alice.id).mutedRepos).toHaveLength(0);
133 h.app.stop();
134 });
135
136 test("a repository with upper case in its name unmutes from the palette", async () => {
137 const r = await createRepo(forge, alice, { name: "Shouty", visibility: "public" });
138 if (!r.ok) throw new Error("repo failed");
139 setView(forge.db, alice, { muted_repos: ["alice/Shouty"] });
140 expect(viewOf(forge.db, alice.id).mutedRepos).toHaveLength(1);
141 const h = boot();
142 await settleApp(h.app);
143 await h.key(":");
144 await h.type("mute or unmute an app");
145 await h.key("enter");
146 await h.type("alice/shouty");
147 await h.key("enter");
148 expect(viewOf(forge.db, alice.id).mutedRepos).toHaveLength(0);
149 h.app.stop();
150 });
test/view.test.ts added +234
@@ -0,0 +1,234 @@
1 /**
2 * What reaches a person (#1112): a filter they set once. A muted repository's
3 * pull is not on them, nor in their inbox, feed or phone — and still counts
4 * on its own page; a kind hides what it names; and it survives a restart.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { addToCrew, createAgent } from "../src/actions/crew.ts";
13 import { assignIssue } from "../src/actions/issues.ts";
14 import { openPull } from "../src/actions/pulls.ts";
15 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
16 import { recordDecision } from "../src/core/decisions.ts";
17 import type { Repo } from "../src/core/repos.ts";
18 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
19 import { createSession } from "../src/core/sessions.ts";
20 import { createToken } from "../src/core/tokens.ts";
21 import { getUserByName, type User } from "../src/core/users.ts";
22 import { NO_VIEW, parseView, reaches, viewKindOfFeed, viewOf } from "../src/core/view.ts";
23 import { readFeed } from "../src/feed/feed.ts";
24 import { askLinesFor } from "../src/web/studio/asks.ts";
25 import { serve, type Servers } from "../src/http/server.ts";
26 import { quietLogs } from "./helpers/globals.ts";
27
28 quietLogs();
29
30 describe("the filter the owner sets", () => {
31 let dataDir = "";
32 let app: App;
33 let servers: Servers;
34 let alice: User;
35 let repo: Repo;
36 let cookie = "";
37 let token = "";
38 let pullNumber = 0;
39
40 const get = (path: string, init: RequestInit = {}) =>
41 fetch(`${servers.url}${path}`, { redirect: "manual", ...init });
42 const api = (path: string, method = "GET", body?: unknown) =>
43 get(path, {
44 method,
45 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
46 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
47 });
48 const onYou = async (): Promise<string> =>
49 (await get("/live/on-you", { headers: { cookie } })).text();
50 const rows = async (): Promise<unknown[]> =>
51 ((await (await api("/api/v1/asks")).json()) as { rows: unknown[] }).rows;
52 const feedAsks = (): number =>
53 readFeed(app.db, alice, { limit: 50 }).items.filter((i) => i.id.startsWith("ask:")).length;
54
55 beforeAll(async () => {
56 dataDir = await mkdtemp(join(tmpdir(), "forge-view-"));
57 app = createApp({ dataDir, port: 0 });
58 servers = await serve(app);
59 const signup = await get("/signup", {
60 method: "POST",
61 body: new URLSearchParams({
62 username: "alice",
63 email: "[email protected]",
64 password: "a-long-view-passphrase",
65 }),
66 });
67 cookie = `${(signup.headers.get("set-cookie") ?? "").split(";")[0]!}; forge_mode=studio`;
68 alice = getUserByName(app.db, "alice")!;
69 token = createToken(app.db, alice.id, "rw", "rw").token;
70 const made = await createRepo(app, alice, { name: "garden", visibility: "public" });
71 if (!made.ok) throw new Error(String(made.error));
72 repo = made.value;
73 await commitToBranch(app, alice, repo, {
74 message: "seed",
75 files: [{ path: "README.md", content: "# garden\n" }],
76 });
77 await createAgent(app, alice, { username: "bot" });
78 addToCrew(app, alice, repo, "bot");
79 const bot = getUserByName(app.db, "bot")!;
80 await commitToBranch(app, alice, repo, {
81 branch: "bot/1-thing",
82 base: "main",
83 message: "Bot work",
84 files: [{ path: "BOT.md", content: "bot\n" }],
85 });
86 const opened = await openPull(app, bot, repo, {
87 title: "Bot did a thing",
88 body: "",
89 baseBranch: "main",
90 headBranch: "bot/1-thing",
91 });
92 if (!opened.ok) throw new Error(String(opened.error));
93 pullNumber = opened.value.number;
94 const run = createRun(app.db, {
95 repoId: repo.id,
96 kind: "check",
97 issueId: opened.value.id,
98 env: `pull-${pullNumber}`,
99 commitOid: opened.value.headOid,
100 reason: "pull",
101 });
102 claimRun(app.db, run.id);
103 finishRun(app.db, run.id, { state: "failed", summary: "red" });
104 recordDecision(app.db, {
105 kind: "retry",
106 repoId: repo.id,
107 issueId: opened.value.id,
108 state: {},
109 answer: "stop",
110 p: 1,
111 by: "rule",
112 ms: 1,
113 });
114 const assigned = assignIssue(app, alice, repo, opened.value, alice);
115 if (!assigned.ok) throw new Error(String(assigned.error));
116 }, 30_000);
117
118 afterAll(async () => {
119 await servers.stop();
120 await rm(dataDir, { recursive: true, force: true });
121 });
122
123 test("with no filter the pull is on you, in the inbox, and on the phone's list", async () => {
124 expect(await onYou()).toContain("Bot did a thing");
125 expect(await rows()).toHaveLength(1);
126 expect(feedAsks()).toBe(1);
127 expect(askLinesFor(app.db, alice)).toHaveLength(1);
128 });
129
130 test("a kind that is not the pull's leaves it; its own kind hides it", async () => {
131 const set = await api("/api/v1/view", "PUT", { hidden_kinds: ["releases", "decisions", "words"] });
132 expect(set.status).toBe(200);
133 expect(await rows()).toHaveLength(1);
134 expect(await onYou()).toContain("Bot did a thing");
135 await api("/api/v1/view", "PUT", { hidden_kinds: ["pulls"] });
136 expect(await rows()).toHaveLength(0);
137 expect(feedAsks()).toBe(0);
138 expect(askLinesFor(app.db, alice)).toHaveLength(0);
139 expect(await onYou()).not.toContain("Bot did a thing");
140 });
141
142 test("releases are a kind of their own, apart from decisions", () => {
143 const view = parseView({ hiddenKinds: ["releases"] });
144 expect(reaches(view, { repoId: "r", kind: viewKindOfFeed("milestone"), person: null })).toBe(false);
145 expect(reaches(view, { repoId: "r", kind: viewKindOfFeed("decision"), person: null })).toBe(true);
146 expect(reaches(view, { repoId: "r", kind: viewKindOfFeed("run"), person: null })).toBe(true);
147 });
148
149 test("a muted repository's pull is not on you, in the inbox or in the feed — and counts on its own page", async () => {
150 const set = await api("/api/v1/view", "PUT", { muted_repos: ["alice/garden"], hidden_kinds: [] });
151 expect(await set.json()).toMatchObject({ muted_repos: ["alice/garden"], hidden_kinds: [] });
152 expect(await onYou()).not.toContain("Bot did a thing");
153 expect(await rows()).toHaveLength(0);
154 expect(feedAsks()).toBe(0);
155 expect(readFeed(app.db, alice, { limit: 50 }).items.some((i) => i.app === "alice/garden" && i.kind === "milestone")).toBe(false);
156 const apps = await (await get("/live/apps", { headers: { cookie } })).text();
157 expect(apps).not.toContain("alice/garden");
158 // Its own page still carries the decision.
159 const page = await (
160 await get(`/alice/garden/changes/${pullNumber}`, { headers: { cookie } })
161 ).text();
162 expect(page).toContain("Bot did a thing");
163 expect(page).toContain("decider stopped rather than spend another run");
164 });
165
166 test("unmuting brings it back", async () => {
167 await api("/api/v1/view", "PUT", { muted_repos: [] });
168 expect(await rows()).toHaveLength(1);
169 expect(await onYou()).toContain("Bot did a thing");
170 });
171
172 test("the people it hides are the ones whose changes they are", async () => {
173 await api("/api/v1/view", "PUT", { hidden_people: ["Bot"] });
174 expect(await rows()).toHaveLength(0);
175 expect(await onYou()).not.toContain("Bot did a thing");
176 await api("/api/v1/view", "PUT", { hidden_people: [] });
177 });
178
179 test("the API validates, needs a viewer, and refuses another origin", async () => {
180 expect((await get("/api/v1/view")).status).toBe(401);
181 expect((await api("/api/v1/view", "PUT", { hidden_kinds: ["nope"] })).status).toBe(422);
182 expect((await api("/api/v1/view", "PUT", { muted_repos: "alice/garden" })).status).toBe(422);
183 expect((await api("/api/v1/view", "PUT", { muted_repos: ["nobody/nothing"] })).status).toBe(404);
184 expect((await api("/api/v1/view", "PUT", { hidden_people: ["a b"] })).status).toBe(422);
185 const session = createSession(app.db, alice.id);
186 const cross = await get("/api/v1/view", {
187 method: "PUT",
188 headers: {
189 origin: "http://evil.example",
190 cookie: `forge_session=${session.token}`,
191 "content-type": "application/json",
192 },
193 body: JSON.stringify({ hidden_kinds: ["pulls"] }),
194 });
195 expect(cross.status).toBe(403);
196 expect(viewOf(app.db, alice.id)).toEqual(NO_VIEW);
197 });
198
199 test("the home's filter row saves, and a cross-origin post is refused", async () => {
200 const home = await (await get("/", { headers: { cookie } })).text();
201 expect(home).toContain('id="view-row"');
202 expect(home).toContain('action="/view"');
203 const form = (extra: Record<string, string> = {}) =>
204 get("/view", {
205 method: "POST",
206 headers: { cookie, ...extra },
207 body: new URLSearchParams([
208 ["show_kind", "pulls"],
209 ["show_kind", "decisions"],
210 ["listed", repo.id],
211 ["hide_people", "mallory, eve"],
212 ]),
213 });
214 expect((await form({ origin: "http://evil.example" })).status).toBe(403);
215 expect((await form()).status).toBe(303);
216 const saved = viewOf(app.db, alice.id);
217 expect(saved.hiddenKinds).toEqual(["words", "releases"]);
218 expect(saved.mutedRepos).toEqual([repo.id]);
219 expect(saved.hiddenPeople).toEqual(["mallory", "eve"]);
220 // The row says what it holds, escaped.
221 expect(await (await get("/", { headers: { cookie } })).text()).toContain('value="mallory eve"');
222 });
223
224 test("the filter survives a restart", async () => {
225 const before = viewOf(app.db, alice.id);
226 expect(before.mutedRepos).toEqual([repo.id]);
227 await servers.stop();
228 app.close();
229 app = createApp({ dataDir, port: 0 });
230 servers = await serve(app);
231 expect(viewOf(app.db, alice.id)).toEqual(before);
232 expect(await rows()).toHaveLength(0);
233 }, 30_000);
234 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs