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

The feed filters by one app with a plain link, kept in the URL, and a filtered feed says which app it shows and how to clear it #13439

Merged opened this

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

Merged

scout/forge:scout/13426-the-feed-filters-by-one-app-with-a-plain → main 6 commits fork 4 threads · 4 unresolved

  • Merged. scout/13426-the-feed-filters-by-one-app-with-a-plain was merged into main as 8e1544d.

Review

Sign in to review this change.
10 files changed +301 −20
docs/features/README.md +1
@@ -25,6 +25,7 @@ Read with the guide page [What a forge is](../guide-what-a-forge-is.md).
2525 - [/docs](docs-link.md)
2626 - [Engine shape](engine-shape.md)
2727 - [Feed fold](feed-fold.md)
28 - [Filter the feed by one app](feed-app-filter.md)
2829 - [Questions on an issue](question.md)
2930 - [A feed post has a permalink](feed-permalink.md)
3031 - [A run post opens its log](feed-run-log.md)
docs/features/feed-app-filter.md added +21
@@ -0,0 +1,21 @@
1 # Filter the feed by one app
2
3 Open `/feed?app=owner/name` to see only that app's posts. A "Showing" line names
4 the app and carries a Clear link back to `/feed`. The app name on each card links
5 there too.
6
outdated

Principle 1 and the doc must match the code: unknown and private show the whole feed plus the line "No app by that name here...", not an empty feed.

7 - It is a plain link, so it works without JavaScript and can be shared.
8 - An unknown app and a private one you cannot see answer alike: the whole feed
9 plus one line, "No app by that name here, so this is the whole feed.", so the
10 filter never reveals that a private app exists. A signed-out visitor is sent
11 to sign in as for any feed address and sees nothing of the filter.
12 - The value is validated in `src/feed/app_filter.ts` (`appFilterOf`); anything
outdated

Both doors: the terminal must offer the same filter (src/tui/ screen or key using appFilterOf). Remove this exemption and add the screen.

13 that is not `owner/name` is ignored and the whole feed shows.
14 - A filtered feed is the ranked page of that app. It does not take `?before=`
15 or `?show=mine`: the timeline reads every app, so those are dropped while an
16 app is chosen. Older posts go through the ranked "Older posts" link, which
17 keeps the filter; Clear returns to the unfiltered feed and its timeline.
18
19 Terminal: on the Feed screen `a` shows only the app of the post under the cursor
20 (through the same `appFilterOf`), a "Showing" line says which, and a second `a`
21 shows every app again. `t` and `m` switch the filter off as they switch lists.
src/feed/app_filter.ts added +31
@@ -0,0 +1,31 @@
1 /**
2 * The feed's one-app filter: `?app=owner/name`, kept in the URL. A name that
3 * does not parse, is unknown, or names an app the viewer cannot read all
4 * answer the same way — the whole feed and one line that never says which of
5 * the three it was, so the filter cannot tell a private app from a missing one.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { canRead, getRepo, type Repo } from "../core/repos.ts";
10 import type { User } from "../core/users.ts";
11
12 const APP = /^([A-Za-z0-9][A-Za-z0-9_.-]{0,38})\/([A-Za-z0-9][A-Za-z0-9_.-]{0,99})$/;
13
14 export const APP_UNKNOWN_LINE = "No app by that name here, so this is the whole feed.";
15
16 export type AppFilter =
17 | { readonly kind: "none" }
18 | { readonly kind: "app"; readonly repo: Repo; readonly app: string }
19 | { readonly kind: "unknown" };
20
21 /** What `?app=` asks for, as this viewer may have it. */
22 export function appFilterOf(db: Database, viewer: User, raw: string | null): AppFilter {
23 if (raw === null || raw === "") return { kind: "none" };
24 const m = APP.exec(raw);
25 const repo = m === null ? undefined : getRepo(db, m[1]!, m[2]!);
26 if (repo === undefined || !canRead(db, repo, viewer)) return { kind: "unknown" };
27 return { kind: "app", repo, app: `${repo.ownerName}/${repo.name}` };
28 }
29
30 /** Whether `raw` is shaped like an app name: what a variant key may carry. */
31 export const isAppName = (raw: string): boolean => raw.length <= 140 && APP.test(raw);
src/tui/screens/feed.ts +23 −4
@@ -12,11 +12,14 @@
1212 * (`permalinkOf`, the page's time link) in a toast. `o` opens the log of the run a run post is
1313 * about, the page's headline link (`runTarget`). Twenty posts at a time; `t` switches to every
1414 * post, newest first (`readTimeline`); `m` narrows that to only mine (its `mine` option, the page's
15 * `?show=mine`); `n` reads the next page from the cursor the last returned.
15 * `?show=mine`); `a` shows only the app of the post under the cursor, through the page's
16 * `appFilterOf` (`?app=`), and a second `a` shows every app again; `n` reads the next page from the
17 * cursor the last returned.
1618 */
1719
1820 import { addCommentThrough } from "../../actions/issues.ts";
1921 import { getIssue } from "../../core/issues.ts";
22 import { appFilterOf } from "../../feed/app_filter.ts";
2023 import { parseCursor, readFeed } from "../../feed/feed.ts";
2124 import { parseBefore, readTimeline, TIMELINE_START } from "../../feed/timeline.ts";
2225 import type { FeedItem } from "../../feed/rank.ts";
@@ -65,10 +68,12 @@ export function feedScreen(f: Session, ctx: Ctx): Screen {
6568 let timeline = false;
6669 // `m`: only mine (`feed/mine.ts`), the page's `?show=mine`; read as the timeline is.
6770 let mine = false;
71 // `a`: one app's posts (`feed/app_filter.ts`), the page's `?app=`; the ranked page, as there.
72 let only: { repoId: string; app: string } | undefined;
6873
6974 const read = (cursor?: string): void => {
7075 if (f.user === undefined) return;
71 if (timeline || mine) {
76 if (only === undefined && (timeline || mine)) {
7277 const from = parseBefore(cursor ?? TIMELINE_START);
7378 const page = readTimeline(f.db, f.user, {
7479 limit: PAGE,
@@ -81,7 +86,7 @@ export function feedScreen(f: Session, ctx: Ctx): Screen {
8186 return;
8287 }
8388 const parsed = cursor === undefined ? undefined : parseCursor(cursor);
84 const page = readFeed(f.db, f.user, { limit: PAGE, ...(parsed ? { cursor: parsed } : {}) });
89 const page = readFeed(f.db, f.user, { limit: PAGE, ...(only === undefined ? {} : { repoId: only.repoId }), ...(parsed ? { cursor: parsed } : {}) });
8590 items.push(...page.items);
8691 next = page.next_cursor;
8792 ctx.invalidate();
@@ -189,6 +194,7 @@ export function feedScreen(f: Session, ctx: Ctx): Screen {
189194 ...(next === null ? [] : [binding(["n"], "next page")]),
190195 binding(["t"], timeline || mine ? "ranked" : "newest first"),
191196 binding(["m"], mine ? "everyone's" : "only mine"),
197 ...(only !== undefined || items[state.index] !== undefined ? [binding(["a"], only === undefined ? "only this app" : "every app")] : []),
192198 binding(["esc", "q"], "back"),
193199 ];
194200 },
@@ -214,7 +220,8 @@ export function feedScreen(f: Session, ctx: Ctx): Screen {
214220 s.text(area.x, area.y + area.h - 1, truncate(history.more ? "m older · esc back" : "esc back", area.w), style(c.mutedFg, c.bg), area.x + area.w);
215221 return;
216222 }
217 const [list, box] = split(area, "v", [fill(1), len(composer.height())]);
223 const [head, list, box] = split(area, "v", [len(only === undefined ? 0 : 1), fill(1), len(composer.height())]);
224 if (only !== undefined) s.text(head!.x, head!.y, truncate(`Showing ${only.app} · a shows every app`, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
218225 const rows: ListRow[] = items.map((item) => ({
219226 title: oneLine(`${item.actor ?? item.app} ${item.what}`),
220227 secondary: item.app,
@@ -253,6 +260,7 @@ export function feedScreen(f: Session, ctx: Ctx): Screen {
253260 else if (e.key === "p") permalink();
254261 else if (e.key === "o") openLog();
255262 else if (e.key === "t" || e.key === "m") {
263 only = undefined;
256264 if (e.key === "m") mine = !mine;
257265 else {
258266 timeline = mine ? false : !timeline;
@@ -262,6 +270,17 @@ export function feedScreen(f: Session, ctx: Ctx): Screen {
262270 state.index = 0;
263271 state.offset = 0;
264272 read();
273 } else if (e.key === "a") {
274 const item = items[state.index];
275 const found = only !== undefined ? undefined : item === undefined || f.user === undefined ? undefined : appFilterOf(f.db, f.user, item.app);
276 if (only === undefined && found?.kind !== "app") return true;
277 only = found?.kind === "app" ? { repoId: found.repo.id, app: found.app } : undefined;
278 timeline = false;
279 mine = false;
280 items.length = 0;
281 state.index = 0;
282 state.offset = 0;
283 read();
265284 } else if (e.key === "n") {
266285 if (next !== null) read(next);
267286 } else state.key(e, items.length);
src/web/studio/feed.ts +31 −10
@@ -17,6 +17,7 @@ import type { Ctx } from "../../http/context.ts";
1717 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1818 import { placementsOf, type Placement } from "../../core/placements.ts";
1919 import { recentThoughts, type Thought } from "../../core/thoughts.ts";
20 import { appFilterOf, APP_UNKNOWN_LINE, type AppFilter } from "../../feed/app_filter.ts";
2021 import { parseCursor, readFeedPage } from "../../feed/feed.ts";
2122 import { parseShow, type Show } from "../../feed/mine.ts";
2223 import { parseBefore, readTimeline, TIMELINE_START } from "../../feed/timeline.ts";
@@ -170,7 +171,7 @@ export function feedCard(
170171 const head = html`${avatar(item.actor ?? item.app)}
171172 <strong class="break">${item.actor ?? item.app}</strong
172173 >${nameMark(item.actor === null ? undefined : marks.get(item.actor))}
173 <span class="muted small break">${item.app} · <a href="${permalinkOf(item.link)}" class="muted permalink" aria-label="Open post" data-permalink>${time(item.at)}</a></span>
174 <span class="muted small break"><a href="/feed?app=${item.app}" class="muted" data-filter-app>${item.app}</a> · <a href="${permalinkOf(item.link)}" class="muted permalink" aria-label="Open post" data-permalink>${time(item.at)}</a></span>
174175 ${settledBadge(item.settled)}
175176 <span class="spacer"></span>

The app link is a small muted inline link, a hard tap on a 360px phone. Give it a padded hit area; keep the single accent for interaction.

176177 <span class="badge">${KIND_LABEL[item.kind]}</span>`;
@@ -369,6 +370,19 @@ function mineChip(show: Show | undefined): Html {
369370 </p>`;
370371 }
371372
373 /**
374 * The line a filtered feed starts with: which app it shows and the way back, or that the name found
375 * nothing.
376 */
377 function filterLine(filter: AppFilter): Html | null {
378 if (filter.kind === "none") return null;
379 if (filter.kind === "unknown") return html`<p class="small muted" data-app-filter="unknown">${APP_UNKNOWN_LINE}</p>`;
380 return html`<p class="bar small" data-app-filter="${filter.app}">
381 <span>Showing <a href="/${filter.app}">${filter.app}</a></span>
382 <a href="/feed">Clear</a>
383 </p>`;
384 }
385
372386 /** What the region shows, read: the posts, the thoughts, where they sit, who posted. */
373387 function readRegion(user: User, ctx: Ctx) {
374388 // What needs you is pinned above the timeline (`needsYouSection`), so an
@@ -380,15 +394,20 @@ function readRegion(user: User, ctx: Ctx) {
380394 // (`feed/timeline.ts`). `?show=mine` narrows the timeline to the viewer's own, so it is the
381395 // timeline.
382396 const show = parseShow(ctx.url.searchParams.get("show"));

A filtered feed ignores ?before= and ?show=mine, so a person on the timeline loses their place and the way to older posts in time order. Keep the timeline filterable, or say plainly in the doc that it does not.

397 const filter = appFilterOf(ctx.app.db, user, ctx.url.searchParams.get("app"));
398 // One app's feed is the ranked page of that app; the timeline reads every app.
383399 const before =
384 parseBefore(ctx.url.searchParams.get("before") ?? "") ??
385 (show === undefined ? undefined : { id: undefined });
400 filter.kind === "app"
401 ? undefined
402 : (parseBefore(ctx.url.searchParams.get("before") ?? "") ??
403 (show === undefined ? undefined : { id: undefined }));
386404 const page =
387405 before === undefined
388406 ? readFeedPage(ctx.app.db, user, {
389407 limit: FEED_FIRST_PAGE,
390408 withoutAsks: true,
391409 phase: (name, ms) => notePhase(ctx.request, name, ms),
410 ...(filter.kind === "app" ? { repoId: filter.repo.id } : {}),
392411 ...(cursor === undefined ? {} : { cursor }),
393412 })
394413 : {
@@ -417,7 +436,7 @@ function readRegion(user: User, ctx: Ctx) {
417436 const quiet = page.quiet;
418437 const quietRepo = quiet.repoId === null ? undefined : getRepoById(ctx.app.db, quiet.repoId);
419438 const quietLink = quietRepo === undefined ? "/explore" : `/${quietRepo.ownerName}/${quietRepo.name}/runs?kind=agent`;
420 return { items, next: page.next_cursor, cursor, timeline, show, asked, lastDayOnPage, thoughts, placed, marks, pictures: picturesFor(ctx, items), quiet: quiet.count, quietLink };
439 return { filter, items, next: page.next_cursor, cursor, timeline, show, asked, lastDayOnPage, thoughts, placed, marks, pictures: picturesFor(ctx, items), quiet: quiet.count, quietLink };
421440 }
422441
423442 /** The one line an empty timeline says; the tell box above it is the action. */
@@ -432,19 +451,19 @@ export function feedRegion(user: User, ctx: Ctx): Html {
432451 * The line under the last post: how far back the page reaches and the way
433452 * to older ones, or that there is nothing older.
434453 */
435 export function caughtUp(items: readonly FeedItem[], next: string | null, cursor?: unknown, timeline = false, show?: Show): Html | null {
454 export function caughtUp(items: readonly FeedItem[], next: string | null, cursor?: unknown, timeline = false, show?: Show, app?: string): Html | null {
436455 const keep = show === undefined ? "" : `&show=${show}`;
437456 const only = show === undefined ? "" : `?show=${show}`;
438457 // Ranked by score, not time: the last card is not always the oldest.
439458 const oldest = items.reduce<string | undefined>((min, item) => (min === undefined || item.at < min ? item.at : min), undefined);
440459 // A page the filters emptied can still have older posts behind it: keep the way on.
441460 if (oldest === undefined && next === null) return null;
442 const newest = cursor === undefined && !timeline ? html`` : html`<a href="/feed${only}">Newest</a>`;
461 const newest = cursor === undefined && !timeline ? html`` : html`<a href="/feed${app === undefined ? only : `?app=${encodeURIComponent(app)}`}">Newest</a>`;
443462 // The ranked page ends where its window does; the log goes on, newest first.
444463 const deeper = timeline ? html`` : html`<a href="/feed?before=${TIMELINE_START}">Everything, newest first</a>`;
445464 const older = (n: string) => timeline
446465 ? html`<a href="/feed?before=${encodeURIComponent(n)}${keep}">Older posts</a>`
447 : html`<a href="/feed?cursor=${encodeURIComponent(n)}&day=${encodeURIComponent(items[items.length - 1]?.at ?? "")}">Older posts</a>`;
466 : html`<a href="/feed?cursor=${encodeURIComponent(n)}&day=${encodeURIComponent(items[items.length - 1]?.at ?? "")}${app === undefined ? "" : `&app=${encodeURIComponent(app)}`}">Older posts</a>`;
448467 return next === null
449468 ? html`<p class="bar muted small" data-caught-up="end"><span>${timeline ? html`That's every post` : html`That's everything`}</span><span class="spacer"></span>${newest}${deeper}</p>`
450469 : html`<p class="bar muted small" data-caught-up="more">
@@ -456,7 +475,7 @@ export function caughtUp(items: readonly FeedItem[], next: string | null, cursor
456475 }
457476
458477 function drawRegion(user: User, ctx: Ctx, read: ReturnType<typeof readRegion>): Html {
459 const { items, next, cursor, timeline, show, asked, lastDayOnPage, thoughts, placed, marks, pictures, quiet, quietLink } = read;
478 const { filter, items, next, cursor, timeline, show, asked, lastDayOnPage, thoughts, placed, marks, pictures, quiet, quietLink } = read;
460479 const now = new Date();
461480 // One divider per change of day between neighbours, in the order the feed already has.
462481 const posts: Html[] = [];
@@ -477,6 +496,7 @@ function drawRegion(user: User, ctx: Ctx, read: ReturnType<typeof readRegion>):
477496 const liveQuery = [
478497 timeline ? `before=${encodeURIComponent(asked)}` : "",
479498 show === undefined ? "" : `show=${show}`,
499 filter.kind === "app" ? `app=${encodeURIComponent(filter.app)}` : "",
480500 cursor === undefined ? "" : `cursor=${encodeURIComponent(`${cursor.score}|${cursor.id}`)}`,
481501 cursor === undefined || lastDayOnPage === undefined ? "" : `day=${encodeURIComponent(lastDayOnPage)}`,
482502 ].filter(Boolean).join("&");
@@ -489,7 +509,8 @@ function drawRegion(user: User, ctx: Ctx, read: ReturnType<typeof readRegion>):
489509 data-live-hold
490510 data-live-src="/live/feed${liveQuery === "" ? "" : `?${liveQuery}`}"
491511 >
492 ${mineChip(show)}
512 ${filterLine(filter)}
513 ${filter.kind === "app" ? null : mineChip(show)}
493514 ${chipsBar(user, ctx, items)}
494515 ${thoughts.map((t) => thoughtCard(t, user.username, placed.get(t.id)))}
495516 ${items.length === 0 && thoughts.length === 0
@@ -498,7 +519,7 @@ function drawRegion(user: User, ctx: Ctx, read: ReturnType<typeof readRegion>):
498519 ${quiet === 0
499520 ? ""
500521 : html`<p class="small muted"><a href="${quietLink}">${quiet} quiet ${quiet === 1 ? "run" : "runs"} in the last 24 h</a></p>`}
501 ${caughtUp(items, next, cursor, timeline, show)}
522 ${caughtUp(items, next, cursor, timeline, show, filter.kind === "app" ? filter.app : undefined)}
502523 </section>`;
503524 }
504525
src/web/studio/home_last.ts +12 −3
@@ -16,6 +16,7 @@ import type { Database } from "bun:sqlite";
1616 import { notePhase } from "../../core/route_timing.ts";
1717 import { forgetAll, recall, remember } from "../../core/region_memory.ts";
1818 import { writeStamp } from "../../core/write_clock.ts";
19 import { isAppName } from "../../feed/app_filter.ts";
1920 import { parseCursor } from "../../feed/feed.ts";
2021 import { parseShow } from "../../feed/mine.ts";
2122 import { parseBefore } from "../../feed/timeline.ts";
@@ -26,7 +27,10 @@ import { HOME_MAX_AGE_MS } from "./home_cache.ts";
2627 export const HOME_REGIONS = ["waiting", "panels", "asked", "feed"] as const;
2728 export type HomeRegion = (typeof HOME_REGIONS)[number];
2829
29 /** A region is redrawn after a response at most this often; the page's own swap draws it fresh in between. */
30 /**
31 * A region is redrawn after a response at most this often; the page's own swap draws it fresh in
32 * between.
33 */
3034 const REDRAW_GAP_MS = 5_000;
3135 const drawing = new Map<string, number>();
3236
@@ -47,6 +51,8 @@ export function homeVariant(url: URL): string {
4751 if (before.length <= 26 && parseBefore(before) !== undefined) q.set("before", before);
4852 const show = parseShow(url.searchParams.get("show"));
4953 if (show !== undefined) q.set("show", show);
54 const app = url.searchParams.get("app") ?? "";
55 if (isAppName(app)) q.set("app", app);
5056 const text = q.toString();
5157 return text === "" ? "" : `?${text}`;
5258 }
@@ -83,7 +89,8 @@ export async function homeRegion(
8389 if (!current && Date.now() - (drawing.get(key) ?? 0) >= REDRAW_GAP_MS) {
8490 if (drawing.size > 1024) for (const [k, at] of drawing) if (at !== Number.MAX_SAFE_INTEGER) drawing.delete(k);
8591 drawing.set(key, Number.MAX_SAFE_INTEGER);
86 // Read when the redraw is decided, not when the timer fires: a write that lands in between must leave the copy stale, not current.
92 // Read when the redraw is decided, not when the timer fires: a write that lands in between
93 // must leave the copy stale, not current.
8794 const before = stamp;
8895 setTimeout(
8996 () =>
@@ -122,7 +129,9 @@ export async function homeFresh(
122129 return body;
123130 }
124131
125 /** The page's half: a region served from memory that has gone stale is drawn fresh and swapped in. */
132 /**
133 * The page's half: a region served from memory that has gone stale is drawn fresh and swapped in.
134 */
126135 export const refreshJs = /* js */ `
127136 (function () {
128137 if (!window.fetch || !window.HTMLTemplateElement) return;
src/web/style/components.ts +1 −1
@@ -458,7 +458,7 @@ a.sha:hover { color: var(--accent); }
458458 .look img { display: block; width: 100%; height: auto; }
459459 .look[data-slot="thumb"] { flex: none; width: 30px; height: 40px; border-radius: 4px; }
460460 .look[data-slot="thumb"] img { height: 100%; object-fit: cover; object-position: top; }
461 .permalink { display: inline-block; padding: 12px 6px; margin: -12px -6px; }
461 .permalink, [data-filter-app] { display: inline-block; padding: 12px 6px; margin: -12px -6px; }
462462 .look[data-slot="feed"] { width: 160px; height: 100px; margin-top: 6px; }
463463 .look[data-slot="feed"] img { height: 100%; object-fit: cover; object-position: top; }
464464 .look[data-slot="now"] { flex: none; width: 168px; }
test/feed-card-markup.test.ts +5 −2
@@ -1,4 +1,7 @@
1 /** The home feed's cards are drawn from §5's parts: no `.fcard-*` class is left in the markup (#4267). */
1 /**
2 * The home feed's cards are drawn from §5's parts: no `.fcard-*` class is left in the markup
3 * (#4267).
4 */
25 import { describe, expect, test } from "bun:test";
36 import type { Placement } from "../src/core/placements.ts";
47 import type { Thought } from "../src/core/thoughts.ts";
@@ -37,7 +40,7 @@ describe("feed card markup", () => {
3740 const long = "a".repeat(120);
3841 const out = feedCard(item({ actor: long, app: `alice/${long}` })).text;
3942 expect(out).toContain(`<strong class="break">${long}</strong`);
40 expect(out).toContain(`<span class="muted small break">alice/${long} · `);
43 expect(out).toContain(`<span class="muted small break"><a href="/feed?app=alice/${long}" class="muted" data-filter-app>alice/${long}</a> · `);
4144 });
4245
4346 test("a tell form posts to the app's own tell", () => {
test/feed-filter.test.ts added +102
@@ -0,0 +1,102 @@
1 /**
2 * `/feed?app=owner/name`: one app's items, a clear link, and one answer for unknown and private.
3 */
4 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
5 import { mkdtemp, rm } from "node:fs/promises";
6 import { tmpdir } from "node:os";
7 import { join } from "node:path";
8 import { createApp, type App } from "../src/app.ts";
9 import { createRepo } from "../src/actions/repos.ts";
10 import { createSession } from "../src/core/sessions.ts";
11 import { promote } from "./helpers/members.ts";
12 import { createUser, type User } from "../src/core/users.ts";
13 import { appFilterOf, APP_UNKNOWN_LINE } from "../src/feed/app_filter.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15
16 describe("the one-app feed filter", () => {
17 let dir: string;
18 let app: App;
19 let servers: Servers;
20 let alice: User;
21 let bob: User;
22 let bobCookie: string;
23
24 const get = async (path: string, cookie = bobCookie) =>
25 fetch(`${servers.url}${path}`, { headers: { cookie }, redirect: "manual" });
26 const tell = (repoId: string, text: string) =>
27 app.bus.append({ kind: "run.finished", repoId, actorId: alice.id, payload: { kind: "deploy", state: "ok", summary: text, runId: `r-${text}` } });
28
29 beforeAll(async () => {
30 dir = await mkdtemp(join(tmpdir(), "feed-filter-"));
31 app = createApp({ dataDir: dir, port: 0 });
32 servers = await serve(app);
33 const mk = async (username: string, first = false) => {
34 const r = await createUser(app.db, {
35 origin: "seed", trusted: true, username, allowReserved: true,
36 email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first,
37 });
38 if (!r.ok) throw new Error(r.error);
39 promote(app.db, r.value);
40 return r.value;
41 };
42 await mk("root", true);
43 alice = await mk("alice");
44 bob = await mk("bob");
45 for (const [name, visibility] of [["open", "public"], ["other", "public"], ["secret", "private"]] as const) {
46 const r = await createRepo(app, alice, { name, visibility });
47 if (!r.ok) throw new Error("repo");
48 tell(r.value.id, `hello from ${name}`);
49 }
50 bobCookie = `forge_session=${createSession(app.db, bob.id).token}`;
51 });
52 afterAll(async () => {
53 servers.stop();
54 app.close();
55 await rm(dir, { recursive: true, force: true });
56 });
57
58 test("a readable app shows only its items, with the line and a clear link", async () => {
59 const body = await (await get("/feed?app=alice/open")).text();
60 expect(body).toContain('data-app-filter="alice/open"');
61 expect(body).toContain("Showing");
62 expect(body).toContain('href="/feed">Clear');
63 expect(body).toContain("hello from open");
64 expect(body).not.toContain("hello from other");
65 });
66
67 test("an unknown app and a private one answer alike, without a name", async () => {
68 const unknown = await (await get("/feed?app=alice/nothing")).text();
69 const priv = await (await get("/feed?app=alice/secret")).text();
70 for (const body of [unknown, priv]) {
71 expect(body).toContain(APP_UNKNOWN_LINE);
72 expect(body).not.toContain("Showing");
73 expect(body).not.toContain("hello from secret");
74 expect(body).toContain("hello from other");
75 }
76 expect(priv).not.toContain("alice/secret");
77 expect(appFilterOf(app.db, bob, "alice/secret")).toEqual({ kind: "unknown" });
78 expect(appFilterOf(app.db, bob, "../etc")).toEqual({ kind: "unknown" });
79 expect(appFilterOf(app.db, bob, null)).toEqual({ kind: "none" });
80 });
81
82 test("the owner sees their private app through the filter", async () => {
83 const own = `forge_session=${createSession(app.db, alice.id).token}`;
84 const body = await (await get("/feed?app=alice/secret", own)).text();
85 expect(body).toContain('data-app-filter="alice/secret"');
86 });
87
88 test("a signed-out visitor gets none of the filter, nor a word of a private app", async () => {
89 for (const name of ["open", "secret"]) {
90 const res = await fetch(`${servers.url}/feed?app=alice/${name}`, { redirect: "manual" });
91 const body = res.status >= 300 && res.status < 400 ? "" : await res.text();
92 expect(body).not.toContain("data-app-filter");
93 expect(body).not.toContain("hello from");
94 expect(body).not.toContain("alice/secret");
95 }
96 });
97
98 test("the app link on a card has a padded hit area", async () => {
99 const src = await Bun.file(join(import.meta.dir, "../src/web/style/components.ts")).text();
100 expect(src).toContain("[data-filter-app] { display: inline-block; padding: 12px 6px;");
101 });
102 });
test/tui-feed-app.test.ts added +74
@@ -0,0 +1,74 @@
1 /**
2 * In the terminal `a` shows only the app of the post under the cursor, and a second `a` shows every
3 * app.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createRepo } from "../src/actions/repos.ts";
10 import { createApp, type App } from "../src/app.ts";
11 import { createUser, getUserByName } from "../src/core/users.ts";
12 import { createForgeApp } from "../src/tui/forge.ts";
13 import { headlessTerminal } from "../src/tui/term/terminal.ts";
14 import { quietLogs } from "./helpers/globals.ts";
15 import { promote } from "./helpers/members.ts";
16 import { settleApp } from "./helpers/tui.ts";
17
18 quietLogs();
19
20 let dir = "";
21 let forge: App;
22
23 beforeAll(async () => {
24 dir = await mkdtemp(join(tmpdir(), "forge-tui-feed-app-"));
25 forge = createApp({ dataDir: dir, port: 0 });
26 for (const [username, first] of [["root", true], ["alice", false], ["bob", false]] as const) {
27 const made = await createUser(forge.db, {
28 origin: "seed", trusted: true, allowReserved: true, username, email: `${username}@forge.local`,
29 password: "a-good-passphrase", adminIfFirst: first,
30 });
31 if (!made.ok) throw new Error(made.error);
32 promote(forge.db, made.value);
33 }
34 const alice = getUserByName(forge.db, "alice")!;
35 for (const name of ["open", "other"]) {
36 const r = await createRepo(forge, alice, { name, visibility: "public" });
37 if (!r.ok) throw new Error(String(r.error));
38 forge.bus.append({ kind: "run.finished", repoId: r.value.id, actorId: alice.id, payload: { kind: "deploy", state: "ok", summary: `hello from ${name}`, runId: `r-${name}` } });
39 }
40 });
41
42 afterAll(async () => {
43 forge.db.close();
44 await rm(dir, { recursive: true, force: true });
45 });
46
47 test("a narrows the feed to the post's app, and a second a brings every app back", async () => {
48 const terminal = headlessTerminal(140, 32);
49 const identity = { sshUsername: "t", remoteAddress: "127.0.0.1", user: getUserByName(forge.db, "bob")! };
50 const { app } = createForgeApp(forge, identity, { terminal, exitHooks: false });
51 app.start();
52 const press = async (...keys: string[]) => {
53 for (const k of keys) app.dispatch({ type: "key", key: k, ctrl: false, alt: false, shift: false });
54 await settleApp(app);
55 };
56 app.dispatch({ type: "key", key: "k", ctrl: true, alt: false, shift: false });
57 await settleApp(app);
58 await press(..."Feed", "enter");
59 const all = app.screen.toText();
60 expect(all).toContain("alice/open");
61 expect(all).toContain("alice/other");
62 await press("a");
63 const one = app.screen.toText();
64 expect(one).toContain("Showing alice/");
65 const shown = /Showing (alice\/\w+)/.exec(one)![1]!;
66 const gone = shown === "alice/open" ? "alice/other" : "alice/open";
67 expect(one.replace(/Showing .*/, "")).not.toContain(gone);
68 await press("a");
69 const back = app.screen.toText();
70 expect(back).toContain("alice/open");
71 expect(back).toContain("alice/other");
72 expect(back).not.toContain("Showing");
73 app.stop();
74 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs