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

/explore filters by kind (apps, forges, people) with a ?kind= parameter and chips, and the MCP explore tool takes the same `kind` #15673

Merged opened this

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

Merged

scout/forge:scout/15653-explore-filters-by-kind-apps-forges-peop → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/15653-explore-filters-by-kind-apps-forges-peop was merged into main as 19172c9.

Review

Sign in to review this change.
6 files changed +122 −9
docs/features/explore.md +2 −2
@@ -65,13 +65,13 @@ What a person filters on `/explore` an agent filters with the same words. Each f
6565
6666 The one line still works everywhere: `?q=kind:app sort:forks garden` and `{ q: "kind:app sort:forks garden" }` read the same as the separate parameters, and old `/explore?q=…` links keep working. When a parameter and the same key in `q` are both given, the parameter wins (`?q=sort:name&sort=forks` sorts by forks). A parameter's value is one word; one the explorer does not take is an unknown word like any typed in `q`, and is refused the same way (below). The terminal's search line takes only the line. It takes `forks:N`, `ships:N` and `live:yes` there too (`screens/dashboard.ts` reads the line with `readExploreLine`): `forks:1 live:no` leaves the rows the page leaves, and `forks:abc` or `live:maybe` is named under `Read as:` as `forks:abc is not a count`, `live:maybe is not an answer`.
6767
68 A bad `min_forks`, `since`, `updated` or `kind` parameter (`?since=9y`, `?kind=nope`) is refused naming the parameter (#14046, #14392): the API answers `422`: `{ "error": "invalid", "field": "since", "message": "since is not a window — use 1d, 7d, 30d" }`, and the page answers `303` to the same address without it, then draws the same sentence once over the unfiltered list. The sentence names the parameter and never repeats the value. `since` is judged only when `updated` is not given, `min_forks` only when `forks` is not.
68 A bad `min_forks`, `since`, `updated` or `kind` parameter (`?since=9y`, `?kind=nope`) is refused naming the parameter (#14046, #14392): the API answers `422`: `{ "error": "invalid", "field": "since", "message": "since is not a window — use 1d, 7d, 30d" }`. The page answers `303` to the same address without it, then draws the same sentence once over the unfiltered list; a bad `kind` is the exception (#15653): the page answers `400` and draws `kind is not a kind — use app, person, forge` over the unfiltered list, with no redirect (still `422` from the API). A bad `kind:` typed in `q` takes the `303` like any unknown word (`test/explore-kind.test.ts`). The sentence names the parameter and never repeats the value. `since` is judged only when `updated` is not given, `min_forks` only when `forks` is not.
6969
7070 The three return the same ordered rows (`test/explore-parity.test.ts`; the URL form in `test/explore-url.test.ts`).
7171
7272 A `forks:` or `ships:` value that is not a whole number from 0 to 1000 (`abc`, `-1`, `1.5`, `1001`) and a `live:` that is not yes or no are unknown words like any other: refused naming the word (below). Spawned forges carry no numbers, so any of the three leaves them out. The page's filter chips, `Drop` links and `Clear filters` carry the three words.
7373
74 One rule for what `/explore` does not take (#14392): an unknown sort, kind, filter word, window, count or `page` is dropped, and said once. The page answers `303` to the address with it dropped (other parameters, tracking included, stay as they came) and the next page opens with one note and, when a word is near, the did-you-mean link; a `page` that is junk, zero or past the last says `page is not a page number` or `there is no page N — showing page M`. `GET /api/v1/explore` answers `422` for every one, naming the field and the allowed words: `{ "error": "invalid", "field": "sort", "message": "sort:bogus is not a sort — use score, forks, …" }` for a separate parameter, and for a word typed in `q` `{ "error": "unknown_filter", "field": "q", "message": …, "suggest"? }`. The MCP tool says the same words as an `unknown_filter` error. Known values are never redirected. Tests: `test/explore-unknown-params.test.ts`.
74 One rule for what `/explore` does not take (#14392): an unknown sort, kind in `q`, filter word, window, count or `page` is dropped, and said once. The page answers `303` to the address with it dropped (other parameters, tracking included, stay as they came) and the next page opens with one note and, when a word is near, the did-you-mean link; a `page` that is junk, zero or past the last says `page is not a page number` or `there is no page N — showing page M`. `GET /api/v1/explore` answers `422` for every one, naming the field and the allowed words: `{ "error": "invalid", "field": "sort", "message": "sort:bogus is not a sort — use score, forks, …" }` for a separate parameter, and for a word typed in `q` `{ "error": "unknown_filter", "field": "q", "message": …, "suggest"? }`. The MCP tool says the same words as an `unknown_filter` error. Known values are never redirected. Tests: `test/explore-unknown-params.test.ts`.
7575
7676 ## Mine (#13161)
7777
src/web/studio/explore.ts +5 −2
@@ -239,7 +239,10 @@ export async function explorePage(ctx: Ctx): Promise<Response> {
239239 const suggestion = exploreSuggestion(line);
240240 // One rule for what the explorer does not take: 303 to the address with it dropped, the note
241241 // said once as a flash. Other parameters (tracking, `page`) are left as they came.
242 if (unknown.length > 0) {
242 // A bad `kind` parameter is the exception (#15653): a 400 that names the kinds, below, with the
243 // unfiltered list beneath it.
244 const badKind = refused?.field === "kind";
245 if (unknown.length > 0 && !badKind) {

Behaviour change (303 to 400 for kind) must be reflected in docs/features/explore.md lines 68 and 74, which still say 303 for a bad kind.

243246 const to = new URL(ctx.url);
244247 for (const key of [...EXPLORE_PARAMS, "min_forks", "since", "q"]) to.searchParams.delete(key);
245248 for (const [k, v] of new URLSearchParams(exploreParams(query))) to.searchParams.set(k, v);
@@ -402,5 +405,5 @@ export async function explorePage(ctx: Ctx): Promise<Response> {
402405 })}${pager(query, shown.page, shown.pages)}</div>`;
403406 const drawn = page({ ctx, title: "Explore", description: "Public apps, forges and people on this forge, ranked by use, forks, deployments and recency.", body: compact(body), feed: { href: "/explore.atom", title: "Explore" }, ...(tag === undefined ? {} : { etag: tag }) });
404407 notePhase(ctx.request, "render", performance.now() - rendering);
405 return drawn;
408 return badKind ? new Response(drawn.body, { status: 400, headers: drawn.headers }) : drawn;
406409 }
test/explore-kind.test.ts added +111
@@ -0,0 +1,111 @@
1 /**
2 * /explore?kind= lists one kind, a bad one is a 400 naming the kinds, the chips are plain links,
3 * the tool takes `kind` (#15653).
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createApp as insertApp } from "../src/core/apps.ts";
12 import { createSession } from "../src/core/sessions.ts";
13 import { createToken } from "../src/core/tokens.ts";
14 import { createUser, getUserByName } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { promote } from "./helpers/members.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18
19 quietLogs();
20 let dir = "";
21 let app: App;
22 let servers: Servers;
23 let token = "";
24 let adminCookie = "";
25 let guestCookie = "";
26
27 beforeAll(async () => {
28 dir = await mkdtemp(join(tmpdir(), "forge-explore-kind-"));
29 app = createApp({ dataDir: dir, port: 0 });
30 servers = await serve(app);
31 const founder = await createUser(app.db, { origin: "seed", trusted: true, username: "founder", email: "[email protected]", password: "a-long-words-passphrase", adminIfFirst: true });
32 if (!founder.ok) throw new Error("founder");
33 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "olive", email: "[email protected]", password: "a-long-words-passphrase" });
34 if (!made.ok) throw new Error("user");
35 promote(app.db, made.value);
36 const olive = getUserByName(app.db, "olive")!;
37 const repo = await createRepo(app, olive, { name: "garden", visibility: "public" });
38 if (!repo.ok) throw new Error("repo");
39 const rec = insertApp(app.db, { repoId: repo.value.id, slug: "olive-garden", access: "public" });
40 if (!rec.ok) throw new Error("app");
41 adminCookie = `forge_session=${createSession(app.db, founder.value.id).token}`;
42 guestCookie = `forge_session=${createSession(app.db, made.value.id).token}`;
43 await mkdir(join(dir, "spawn"), { recursive: true });
44 await writeFile(join(dir, "spawn", "acme-shop.json"), JSON.stringify({ name: "acme-shop", bodyId: "b-acme-shop", done: true }));
45 token = createToken(app.db, olive.id, "t", "rw").token;
46 }, 30_000);
47 afterAll(async () => {
48 await servers.stop();
49 app.close();
50 await rm(dir, { recursive: true, force: true });
51 });
52
53 const get = async (qs: string) => {
54 const res = await fetch(`${servers.url}/explore${qs}`, { redirect: "manual" });
55 return { status: res.status, html: await res.text() };
56 };
57 const rows = (html: string) => [...html.matchAll(/<ul class="list">([\s\S]*?)<\/ul>/g)].flatMap((m) => [...m[1]!.matchAll(/<li[\s>]/g)]).length;
58 const call = async (args: unknown) => {
59 const res = await fetch(`${servers.url}/mcp`, {
60 method: "POST",
61 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
62 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "explore", arguments: args } }),
63 });
64 return ((await res.json()) as any).result as { isError?: boolean; content: { text: string }[] };
65 };
66
67 test("kind=app lists apps only, kind=person people only", async () => {
68 const apps = await get("?kind=app");
69 expect(apps.status).toBe(200);
70 expect(apps.html).toContain("/olive/garden");
71 expect(apps.html).not.toContain('href="/olive"');
72 const people = await get("?kind=person");
73 expect(people.status).toBe(200);
74 expect(people.html).not.toContain("/olive/garden");
75 expect(rows(people.html)).toBeGreaterThan(0);
76 });
77
78 test("an unknown kind is a 400 naming the allowed ones", async () => {
79 const res = await get("?kind=bogus");
80 expect(res.status).toBe(400);
81 expect(res.html).toContain("kind is not a kind — use app, person, forge");
82 });
83
84 test("kind=forge lists forge rows to an admin and none to anyone else", async () => {
85 const seen = async (cookie: string) => {
86 const res = await fetch(`${servers.url}/explore?kind=forge`, { headers: { cookie } });
87 return { status: res.status, html: await res.text() };
88 };
89 const admin = await seen(adminCookie);
90 expect(admin.status).toBe(200);
91 expect(admin.html).toMatch(/<a[^>]*>\s*acme-shop\s*<\/a>/);
92 const other = await seen(guestCookie);
93 expect(other.status).toBe(200);
94 expect(other.html).not.toContain("acme-shop");
95 expect((await get("?kind=forge")).html).not.toContain("acme-shop");
96 });
97
98 test("the kind chips are plain links and the current one is marked", async () => {
99 const res = await get("?kind=app");
100 expect(res.html).toMatch(/<a[^>]*href="\/explore\?kind=person"/);
101 expect(res.html).toMatch(/<a[^>]*aria-current="[^"]+"[^>]*>\s*Apps\s*<\/a>/);
102 });
103
104 test("the explore tool takes kind in the same words", async () => {
105 const people = JSON.parse((await call({ kind: "person" })).content[0]!.text) as { items: { kind: string }[] };
106 expect(people.items.length).toBeGreaterThan(0);
107 expect(people.items.every((i) => i.kind === "person")).toBe(true);
108 const r = await call({ kind: "bogus" });
109 expect(r.isError).toBe(true);
110 expect(r.content[0]!.text).toContain("kind:bogus is not a kind — use app, person, forge");
111 });
test/explore-unknown-params.test.ts +1 −2
@@ -42,8 +42,7 @@ test("page: ?sort=zzz is a 303 to the clean address, and the next page says why
4242
4343 test("page: an unknown kind or a typed word is dropped the same way; known ones are left alone", async () => {
4444 const kind = await fetch(`${servers.url}/explore?kind=nope`, { redirect: "manual" });
45 expect(kind.status).toBe(303);
46 expect(kind.headers.get("location")).toBe("/explore");
45 expect(kind.status).toBe(400);
4746 const typed = await fetch(`${servers.url}/explore?q=${encodeURIComponent("garden sort:zzz")}`, { redirect: "manual" });
4847 expect(typed.headers.get("location")).toBe("/explore?q=garden");
4948 expect((await fetch(`${servers.url}/explore?sort=forks`, { redirect: "manual" })).status).toBe(200);
test/explore-url-filters.test.ts +1 −1
@@ -98,7 +98,7 @@ test("a link with three filters renders the same rows as choosing them by hand",
9898
9999 test("an unknown filter value is ignored with a one-line note, never a 500 (a 303 to the address without it, then a 200, #14046)", async () => {
100100 const plain = listed((await get("/explore", olive)).html);
101 for (const [qs, status] of [["?mine=maybe", 200], ["?kind=zzz", 200], ["?sort=zzz", 200], ["?since=9y", 200]] as const) {
101 for (const [qs, status] of [["?mine=maybe", 200], ["?sort=zzz", 200], ["?since=9y", 200]] as const) {
102102 const res = await get(`/explore${qs}`, olive);
103103 expect(res.status).toBe(status);
104104 expect(res.html).toContain('role="status"');
test/explore-url.test.ts +2 −2
@@ -83,7 +83,7 @@ test("an unknown parameter is ignored; an invalid value is named and the default
8383 // address without it. The page under it is the same: the note and the unfiltered list, escaped.
8484 test("an unknown sort, kind or updated is a 303 to the address without it, then a 200 with a plain note and the unfiltered list, escaped (#11819, #14046)", async () => {
8585 const plain = listed((await page("")).html);
86 for (const [qs, status] of [["?kind=bogus", 200], ["?sort=bogus", 200], ["?updated=9y", 200], ["?since=9y", 200], [`?kind=${encodeURIComponent("<script>x</script>")}`, 200]] as const) {
86 for (const [qs, status] of [["?sort=bogus", 200], ["?updated=9y", 200], ["?since=9y", 200]] as const) {
8787 const res = await page(qs);
8888 expect(res.status).toBe(status);
8989 expect(res.html).toContain('role="status"');
@@ -172,7 +172,7 @@ test("since, updated and kind: a bad one is a 303 then a noted 200 on the page,
172172 ["kind=app&since=1y", "since", "since is not a window"],
173173 ] as const) {
174174 const res = await page(`?${qs}`);
175 expect(res.status).toBe(200);
175 expect(res.status).toBe(field === "kind" ? 400 : 200);
176176 expect(res.html).toContain(words);
177177 // The bad parameter never narrows; a good one beside it still does.
178178 expect(listed(res.html)).toEqual(qs.startsWith("kind=app&") ? listed((await page("?kind=app")).html) : plain);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs