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

The /search page keeps to the repository repo:owner/name names in q, as /api/… #17932

opened this in answer to

Merged 24h 31m ago, live in production

mason/forge:mason/17931-the-search-page-keeps-to-the-repository → main 0 commits fork 7 threads · 7 unresolved

  • Merged. mason/17931-the-search-page-keeps-to-the-repository was merged into main as c310a25.

Review

Sign in to review this change.
7 files changed +110 −17
docs/features/search-finds-guides.md +4
@@ -28,3 +28,7 @@ To keep a search to one repository, `GET /api/v1/search?q=glow&repo=alice/pebble
2828 or `q=glow repo:alice/pebble` does it, as the MCP search tool does. It reaches
2929 past the cap on repositories an unscoped search reads. A malformed `repo` or two
3030 different ones is `invalid_repo` (422); an unreadable one is `not_found` (404).
31
32 ## Keeping to one repository
33
34 Write `repo:owner/name` in the query (`/search?q=repo:owner/name+parser`, or in the terminal's palette) and the search keeps to that repository, as the API and the MCP tool do. A repository you cannot read answers as a missing one.
src/core/search.ts +18 −1
@@ -34,7 +34,7 @@ import { MAX_QUERY_CHARS } from "./query_limit.ts";
3434 import { appsForRepos } from "./apps.ts";
3535 import { UNCLAIMED_OWNER } from "./offered.ts";
3636 import { likeEscape } from "./issues.ts";
37 import { enterableApps, listReposVisibleTo, type Repo } from "./repos.ts";
37 import { canRead, enterableApps, getRepo, listReposVisibleTo, type Repo } from "./repos.ts";
3838 import type { User } from "./users.ts";
3939
4040 /** The longest query we will run: the one limit every search door shares. */
@@ -93,6 +93,23 @@ export function repoQualifier(q: string): { readonly q: string; readonly repo?:
9393 return repo === undefined ? { q } : { q: rest.replace(/\s+/g, " ").trim(), repo };
9494 }
9595
96 /** The `owner` and `name` of an `owner/name`, or undefined when it is not exactly that. */
97 export function ownerAndName(named: string): readonly [string, string] | undefined {
98 const [owner, name, ...rest] = named.split("/");
99 return owner && name && rest.length === 0 ? [owner, name] : undefined;
100 }
101
102 /**
103 * The repository a `repo:owner/name` names if the viewer may read it; undefined alike for
104 * malformed, missing or unreadable, so a private one is never told. The one lookup the page, the
105 * API, the MCP tool and the terminal palette share (#17931).
106 */
107 export function readableRepoNamed(db: Database, user: User | undefined, named: string): Repo | undefined {
108 const parts = ownerAndName(named);
109 const repo = parts === undefined ? undefined : getRepo(db, parts[0], parts[1]);
110 return repo !== undefined && canRead(db, repo, user) ? repo : undefined;
111 }
112
96113 /**
97114 * What a caller who asked wrongly is told, in one sentence, or undefined when
98115 * the request was fine (an unknown kind or limit is `searchRefusal`'s 422, not a note). Plain text:
src/http/api.ts +3 −5
@@ -159,7 +159,7 @@ import {
159159 getRepoById,
160160 isLanding,
161161 } from "../core/repos.ts";
162 import { CODE_BUDGET_MS, greppable, repoQualifier, searchKind, searchNote } from "../core/search.ts";
162 import { CODE_BUDGET_MS, greppable, ownerAndName, readableRepoNamed, repoQualifier, searchKind, searchNote } from "../core/search.ts";
163163 import { strangerCodeSearch } from "./strangers.ts";
164164
165165 import { contributeMint } from "./api/contribute_token.ts";
@@ -1571,10 +1571,8 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
15711571 * one if unreadable.
15721572 */
15731573 function searchScope(ctx: Ctx, named: string): Repo | Response {
1574 const [owner, name, ...rest] = named.split("/");
1575 if (!owner || !name || rest.length > 0) return apiError("invalid_repo", 422, "repo is owner/name");
1576 const repo = getRepo(ctx.app.db, owner, name);
1577 return repo !== undefined && canRead(ctx.app.db, repo, ctx.auth.user) ? repo : notFound();
1574 if (ownerAndName(named) === undefined) return apiError("invalid_repo", 422, "repo is owner/name");
1575 return readableRepoNamed(ctx.app.db, ctx.auth.user, named) ?? notFound();
15781576 }
15791577
15801578 // ── search ───────────────────────────────────────────────────────────
src/http/mcp/shared.ts +3 −2
@@ -6,6 +6,7 @@ import { blockedFields, blockedText, type Blocked } from "../../kernel/blocked.t
66 import { mayView } from "../../core/sealed.ts";
77 import { getIssue, LIST_LIMIT_MAX } from "../../core/issues.ts";
88 import { canRead, canWrite, getRepo, type Repo } from "../../core/repos.ts";
9 import { readableRepoNamed } from "../../core/search.ts";
910 import { nearRepos } from "../../core/near_repos.ts";
1011 import { scopeAllows } from "../../core/tokens.ts";
1112 import { getUserByName, type User } from "../../core/users.ts";
@@ -465,8 +466,8 @@ export function repoArg(ctx: Ctx, user: User | undefined, args: Args): Repo | An
465466 : `${MISS}: ${owner} names more than one you can read (${found.map(named).join(", ")}); say which`,
466467 );
467468 }
468 const repo = owner && name && rest.length === 0 ? getRepo(ctx.app.db, owner, name) : undefined;
469 if (repo !== undefined && canRead(ctx.app.db, repo, user)) return repo;
469 const repo = owner && name && rest.length === 0 ? readableRepoNamed(ctx.app.db, user, `${owner}/${name}`) : undefined;
470 if (repo !== undefined) return repo;
470471 // One answer for "no such repository" and "not yours to see": it says both, and a guess names
471472 // only what the caller reads, so it is the same either way.
472473 const meant = owner && name && rest.length === 0 ? nearRepos(ctx.app.db, user, owner, name) : [];
src/tui/forge_parts.ts +18 −1
@@ -15,7 +15,7 @@ import { publicOrigin } from "../core/public_origin.ts";
1515 import { seesAnyBox } from "../games/store.ts";
1616 import { nearPages } from "../web/near_pages.ts";
1717 import { search } from "../actions/search.ts";
18 import { greppable } from "../core/search.ts";
18 import { greppable, readableRepoNamed, repoQualifier } from "../core/search.ts";
1919 import { guestCodeSearch } from "../http/strangers.ts";
2020 import { canRead, getRepo, type Repo } from "../core/repos.ts";
2121 import { nearRepos } from "../core/near_repos.ts";
@@ -849,6 +849,22 @@ export function forgeSearch(session: Session): (ctx: Ctx) => PaletteSearch {
849849 // limits as the page's and the API's (`http/strangers.ts`), counted
850850 // under its peer address. Refused, everything but the code is searched.
851851 // A one-letter query greps nothing (#11120), so it takes no slot either.
852 // `repo:owner/name` keeps the search to that repository, as on the page, the API and the MCP

This new comment block sits in the middle of the existing comment about the stranger code-search limits, which now trails off from the code it describes. Put the repo: block before that comment, or after the code it describes.

853 // tool (#17931); one the session cannot read answers as a missing one, in the page's words.
854 const qualified = repoQualifier(query);
855 const only = qualified.repo === undefined ? undefined : readableRepoNamed(session.db, session.user, qualified.repo);
856 if (qualified.repo !== undefined && only === undefined)
857 return [
858 {
859 id: "repo:unknown",
860 section: "Repos",
861 mark: G.ring,
862 title: `No repository you can read is called “${qualified.repo}”`,
863 hint: "repo: takes owner/name",
864 run: () => ctx.toast("repo: takes owner/name.", "secondary"),
865 },
866 ];
867 query = qualified.q;
852868 const greps = session.user === undefined && greppable(query);
853869 const held = greps
854870 ? guestCodeSearch(session.app, session.identity.remoteAddress)
@@ -862,6 +878,7 @@ export function forgeSearch(session: Session): (ctx: Ctx) => PaletteSearch {
862878 q,
863879 ...(pullsOnly ? { kind: "pulls" as const } : {}),
864880 limit: 8,
881 ...(only === undefined ? {} : { repo: only }),
865882 live,
866883 withCode: held === undefined || held.allowed,
867884 });
src/web/pages/search.ts +35 −8
@@ -25,12 +25,14 @@ import { getSnapshot } from "../../core/snapshots.ts";
2525 import { getSubscription } from "../../core/subscriptions.ts";
2626 import { openLabelCounts } from "../../core/issues.ts";
2727 import { getPull } from "../../core/pulls.ts";
28 import { canAdmin, canWrite, enterableApps, forkParentFor, getRepo } from "../../core/repos.ts";
28 import { canAdmin, canWrite, enterableApps, forkParentFor, getRepo, type Repo } from "../../core/repos.ts";
2929 import { followModeWords, followSwitchPreview } from "../../actions/follow_words.ts";
3030 import type { ForkFollowMode } from "../../core/fork_follow.ts";
3131 import { getMirrorTarget } from "../../core/migrate_mirror.ts";
3232 import {
3333 cleanQuery,
34 readableRepoNamed,
35 repoQualifier,
3436 CODE_BUDGET_MS,
3537 CODE_TOO_SHORT,
3638 greppable,
@@ -86,6 +88,8 @@ export const SEARCH_CSS = `[data-search] { overflow-wrap: anywhere; }
8688 /** What was asked — everything a link back needs. */
8789 interface Asked {
8890 readonly query: string;
91 /** What is searched for: `query` less its `repo:owner/name`, which is the scope (#16463). */
92 readonly words: string;
8993 readonly kind: SearchKind;
9094 readonly live: boolean;
9195 /** `?code=all`: grep every repository, not just what fits the budget. */
@@ -375,11 +379,13 @@ function section(
375379 </section>`;
376380 }
377381

Stray extra blank line; remove it.

382

Non-blocking: stray extra blank line.

378383 /** The same `search()` the API and the palette call, so the sources can
379384 * never disagree between surfaces. */
380385 async function find(
381386 ctx: Ctx,
outdated

Duplicate of searchScope in src/http/api.ts and the MCP read. Fold into one core function that returns the repo or undefined, and call it from here, the API and MCP. Only one way to do the thing.

382387 a: Asked,
388 only: Repo | undefined,
383389 ): Promise<{ found: SearchResults; busy?: number }> {
384390 // A stranger's code search takes a slot of its own (`http/strangers.ts`);
385391 // refused, the page still answers with everything but the code, and says so.
@@ -387,14 +393,15 @@ async function find(
387393 const greps =
388394 ctx.auth.user === undefined &&
389395 (a.kind === "code" || a.kind === "all") &&
390 greppable(a.query);
396 greppable(a.words);
391397 const held = greps
392398 ? timePhase(ctx.request, "gate", () => strangerCodeSearch(ctx.app, ctx.request))
393399 : undefined;
394400 const withCode = held === undefined || held.allowed;
395401 try {
396402 const found = await search(ctx.app, ctx.auth.user, {
397 q: a.query,
403 q: a.words,
404 ...(only === undefined ? {} : { repo: only }),
398405 kind: a.kind,
399406 live: a.live,
400407 withCode,
@@ -424,8 +431,12 @@ async function find(
424431 export async function searchPage(ctx: Ctx): Promise<Response> {
425432 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
426433 const params = ctx.url.searchParams;
434 const typed = cleanQuery(cappedQuery(params.get("q")));
435 // `repo:owner/name` keeps the search to that repository, as on the API and the MCP tool (#16463).
436 const qualified = repoQualifier(typed);
427437 const a: Asked = {
428 query: cleanQuery(cappedQuery(params.get("q"))),
438 query: typed,
439 words: qualified.q,
429440 kind: searchKind(params.get("kind")),
430441 live: params.get("live") === "1",
431442 codeAll: params.get("code") === "all",
@@ -474,7 +485,23 @@ export async function searchPage(ctx: Ctx): Promise<Response> {
474485 return blank;
475486 }
476487
477 const { found, busy } = await find(ctx, a);
488 const named = qualified.repo;
489 const only = named === undefined ? undefined : readableRepoNamed(ctx.app.db, ctx.auth.user, named);
490 if (named !== undefined && only === undefined) {
491 const rendering = performance.now();
492 const none = page({

The unknown-repo page has no kind chips, which the normal page has. A typo in repo: leaves no way to see the other kinds. Render the same chip row (links keep the full query) alongside the form.

493 ctx,
494 title: `Search · ${echoed(a.query)}`,
495 styleCss: SEARCH_CSS,
496 body: html`<div data-search>${pageHead(html`Results for “${echoed(a.query)}”`)} ${form}${trimmed}
497 <p class="muted" role="status" data-repo-unknown>No repository you can read is called “${echoed(named)}”; repo: takes owner/name.</p>

Principle 1 and 8: this says it twice, 'No repository you can read is called X; repo: takes owner/name.' Keep one plain sentence, for example: No repository you can read is called “X”. Use owner/name after repo:.

498 </div>`,
499 });
500 notePhase(ctx.request, "render", performance.now() - rendering);
501 return none;
502 }
503
504 const { found, busy } = await find(ctx, a, only);
478505 const apps: Apps = timePhase(ctx.request, "apps", () => {
479506 const seen = appsOf(ctx, ctx.auth.user);
480507 return {
outdated

The unknown-repo note is plain and in the right words (principle 8), as a muted status row, good. Make sure the TUI palette says the same thing for the same query; right now the terminal ignores repo: entirely.

@@ -536,7 +563,7 @@ export async function searchPage(ctx: Ctx): Promise<Response> {
536563 // Drawn in the issues section, which is what `pulls` shows.
537564 pulls: () => [[], false],
538565 code: () => [
539 found.code.map((hit) => codeHitRow(hit, a.query)),
566 found.code.map((hit) => codeHitRow(hit, a.words)),
540567 found.truncated.code,
541568 ],
542569 };
@@ -554,7 +581,7 @@ export async function searchPage(ctx: Ctx): Promise<Response> {
554581 a.kind === "all" &&
555582 found.repos.length + found.issues.length + found.code.length + found.docs.length + (found.pages?.length ?? 0) === 0;
556583 const guides = found.docs.length === 0 ? null : docsSection(found.docs);
557 const guidesFirst = guideTitleMatches(a.query, found.docs);
584 const guidesFirst = guideTitleMatches(a.words, found.docs);
558585 const sections = WORDS
559586 .filter(([kind]) => kind !== "all" && (a.kind === "all" || a.kind === kind || (a.kind === "pulls" && kind === "issues")))
560587 .map((w) => ({ kind: w[0], html: section(a, w, ...rows[w[0]](), w[0] === "code" ? moreCode : null) }));
@@ -579,7 +606,7 @@ export async function searchPage(ctx: Ctx): Promise<Response> {
579606 </p>`,
580607 )}
581608 ${when(
582 (a.kind === "code" || a.kind === "all") && !greppable(a.query),
609 (a.kind === "code" || a.kind === "all") && !greppable(a.words),
583610 () => html`<p class="muted small" role="status" data-code-short>${CODE_TOO_SHORT}</p>`,
584611 )}
585612 ${when(
test/mcp-search.test.ts +29
@@ -16,6 +16,9 @@ import { SEARCH_LIMIT } from "../src/actions/search.ts";
1616 import { getRepo } from "../src/core/repos.ts";
1717 import { createUser, getUserByName } from "../src/core/users.ts";
1818 import { serve, type Servers } from "../src/http/server.ts";
19 import { forgeSearch } from "../src/tui/forge_parts.ts";
20 import { Session } from "../src/tui/session.ts";
21 import type { Ctx } from "../src/tui/app/app.ts";
1922
2023 describe("MCP search", () => {
2124 let dataDir: string;
@@ -141,6 +144,32 @@ describe("MCP search", () => {
141144 expect((await api("q=glow&repo=alice/nothing-here", aliceRo)).status).toBe(404);
142145 });
143146
147 test("/search, the page, keeps to the repository repo: names in q; an unreadable one reads as a missing one", async () => {
148 const page = async (q: string) => (await fetch(`${servers.url}/search?${new URLSearchParams({ q, kind: "issues" })}`)).text();
149 expect(await page("glow")).not.toContain("alice/pebble #");
150 const scoped = await page("glow repo:alice/pebble");
151 expect(scoped).toContain("alice/pebble #1");
152 expect(scoped).not.toContain("alice/noisy #");
153 expect(await page("REPO:alice/pebble glow")).toContain("alice/pebble #1");
154 const secret = await page("glow repo:alice/secretpebble");
155 expect(secret).not.toContain("secretpebble #");
156 const said = (text: string) => /<p[^>]*data-repo-unknown[^>]*>([\s\S]*?)<\/p>/.exec(text)?.[1]?.replace(/secretpebble|nothing-here/, "X");
157 expect(said(secret)).toBeDefined();
158 expect(said(secret)).toBe(said(await page("glow repo:alice/nothing-here")));
159 expect(await page("glow repo:pebble")).toContain("data-repo-unknown");
160 });
161
162 test("the terminal's palette keeps to repo: names in q too, and says the page's words for an unreadable one", async () => {
163 const guest = new Session(app, { sshUsername: "anyone", remoteAddress: "198.51.100.7", fingerprint: "SHA256:none" });
164 const ctx = { icons: "plain", toast: () => {}, push: () => {}, invalidate: () => {} } as unknown as Ctx;
165 const ask = async (q: string) => (await forgeSearch(guest)(ctx)(q, false, new AbortController().signal)).map((i) => i.id);
166 expect(await ask("glow")).not.toContain("issue:alice/pebble#1");
167 expect(await ask("glow repo:alice/pebble")).toContain("issue:alice/pebble#1");
168 expect(await ask("REPO:alice/pebble glow")).toContain("issue:alice/pebble#1");
169 expect(await ask("glow repo:alice/secretpebble")).toEqual(["repo:unknown"]);
170 expect(await ask("glow repo:alice/nothing-here")).toEqual(["repo:unknown"]);
171 });
172
144173 test("/api/v1/search: a run token reaches only its own repositories; repo= outside them is 404, inside them is found; the qualifier's case is no second repository", async () => {
145174 const alice = getUserByName(app.db, "alice")!;
146175 const pebble = getRepo(app.db, "alice", "pebble")!;

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs