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

Registry: MCP registry_search and registry_install, and a src/tui listing (#6009) #17193

opened this

Check · Review · Land · Live — Its check is queued. Next: reviewer, pushed since the last review.

Ready to land

scout/forge:scout/17041-registry-mcp-registry-search-and-registr → main 7 commits fork

Review

Sign in to review this change.
14 files changed +508 −29
docs/features/component-registry.md +3 −1
@@ -12,4 +12,6 @@ The source is copied into the app, which owns it. Items: `tokens` (colours and r
1212
1313 From a terminal: `curl <this forge>/r/registry.json`.
1414
15 Which app holds which version, and the update pulls, are in `app-registry.md`. Not yet: private items, the gallery, MCP install.
15 Which app holds which version, and the update pulls, are in `app-registry.md`.
16
17 Searching and installing from the MCP and the terminal: `registry-search.md`.
docs/features/registry-search.md added +12
@@ -0,0 +1,12 @@
1 ---
2 topic: Your apps
3 row: Search the component registry and install an item as a pull (MCP and terminal)
4 ---
5 # Search and install from the registry (#17041)
6
7 - **MCP:** `registry_search` with `{ query? }` lists the items whose name, title, description or type hold every word (no query: all), each with its version and what it `dependsOn`. `registry_install` with `{ repo, item }` opens a pull on the branch `registry/install-<item>-<version>` that writes the item's files and those of the items it needs; the app owns the copy once it is merged. It needs an admin of the repository with an admin-scope token; asked twice it finds the first pull, and asked after the merge it notes the install so update pulls follow.
8 - **Terminal:** the palette's `Component registry` lists the items; `/` searches, `i` asks for an `owner/name` and opens the install pull. An app's `Registry items` screen reaches it with `a`.
9
10 Terminal screen: `src/tui/screens/registry_items.ts`. Not yet: private items, the gallery.
11
12 Try it: `registry_search` with `{ "query": "empty" }`, or open the palette's `Component registry`.
src/actions/registry_install.ts added +51
@@ -0,0 +1,51 @@
1 /**
2 * Install a registry item as a pull (#17041, a slice of #6009): one branch per item and version
3 * writes the item's files, and those of the items it depends on, into the app; nothing lands until
4 * a person merges. One gate for the MCP and the terminal, the admin of the repository as noting an
5 * install is. Asked twice, it finds the first pull (a closed one counts for nothing: a new branch,
6 * a new pull); once that is merged, the next ask notes the install (so updates are offered from
7 * then on).
8 */
9
10 import type { App } from "../app.ts";
11 import { installedItems, MAX_ITEMS, recordInstalled } from "../core/app_registry.ts";
12 import { pullForBranch } from "../core/pulls.ts";
13 import type { Repo } from "../core/repos.ts";
14 import type { User } from "../core/users.ts";
15 import { err, ok, type Result } from "../kernel/result.ts";
16 import { planInstall } from "../registry/search.ts";
17 import { requireRepoAdmin } from "./access.ts";
18 import { editFiles } from "./contents.ts";
19 import type { UpdateOutcome } from "./registry_updates.ts";
20
21 export async function installRegistryItem(app: App, actor: User | undefined, repo: Repo, name: string): Promise<Result<UpdateOutcome, "not_found" | { message: string }>> {
22 const gate = requireRepoAdmin(app, actor, repo);
23 if (!gate.ok) return gate;
24 const plan = planInstall(name);
25 if (plan === undefined) return err({ message: `The registry has no item "${name.slice(0, 48)}"; registry_search names them.` });
26 const to = plan.item.meta.version;
27 const held = installedItems(app.db, repo.id);
28 if (held.find((h) => h.item === plan.item.name)?.version === to) return ok({ item: plan.item.name, to, state: "refused", why: "already installed at that version" });
29 // A closed, unmerged pull is no pull: the next try goes to a fresh branch, `-2`, `-3`, ...
30 let branch = plan.branch;
31 let there = pullForBranch(app.db, repo.id, branch);
32 for (let n = 2; there !== undefined && there.mergedAt === null && there.state === "closed" && n < 100; n++) {
33 branch = `${plan.branch}-${n}`;
34 there = pullForBranch(app.db, repo.id, branch);
35 }
36 if (there !== undefined && there.mergedAt !== null) {
37 for (const i of plan.items) recordInstalled(app.db, repo.id, i.name, i.meta.version, gate.value.id);
38 return ok({ item: plan.item.name, to, state: "merged" });
39 }
40 if (there !== undefined) return ok({ item: plan.item.name, to, state: "already", pull: there.number });
41 if (held.length + plan.items.length > MAX_ITEMS) return err({ message: `An app holds at most ${MAX_ITEMS} items.` });
42 const done = await editFiles(app, gate.value, repo, {
43 newBranch: branch,
44 message: plan.title,
45 files: plan.items.flatMap((i) => i.files.map((f) => ({ path: f.target, content: f.content }))),
46 openPull: { title: plan.title, body: plan.body },
47 });
48 if (done.ok && done.value.pull !== undefined) return ok({ item: plan.item.name, to, state: "opened", pull: done.value.pull.number });
49 const why = done.ok ? "the pull did not open" : typeof done.error === "string" ? done.error : done.error.kind;
50 return ok({ item: plan.item.name, to, state: "refused", why });
51 }
src/generated/screens.ts +28 −26
@@ -100,32 +100,33 @@ import * as s95 from "../tui/screens/profile.ts";
100100 import * as s96 from "../tui/screens/quotas.ts";
101101 import * as s97 from "../tui/screens/recoverykit.ts";
102102 import * as s98 from "../tui/screens/refused.ts";
103 import * as s99 from "../tui/screens/repolist.ts";
104 import * as s100 from "../tui/screens/requests.ts";
105 import * as s101 from "../tui/screens/resilience.ts";
106 import * as s102 from "../tui/screens/returning.ts";
107 import * as s103 from "../tui/screens/returns.ts";
108 import * as s104 from "../tui/screens/scorecard.ts";
109 import * as s105 from "../tui/screens/scrapes.ts";
110 import * as s106 from "../tui/screens/secrets.ts";
111 import * as s107 from "../tui/screens/sentinel.ts";
112 import * as s108 from "../tui/screens/ship_time.ts";
113 import * as s109 from "../tui/screens/slowpages.ts";
114 import * as s110 from "../tui/screens/sold.ts";
115 import * as s111 from "../tui/screens/spend.ts";
116 import * as s112 from "../tui/screens/stalepulls.ts";
117 import * as s113 from "../tui/screens/subscriptions.ts";
118 import * as s114 from "../tui/screens/system.ts";
119 import * as s115 from "../tui/screens/teams.ts";
120 import * as s116 from "../tui/screens/telemetry.ts";
121 import * as s117 from "../tui/screens/tell_undo.ts";
122 import * as s118 from "../tui/screens/traffic.ts";
123 import * as s119 from "../tui/screens/trafficview.ts";
124 import * as s120 from "../tui/screens/valves.ts";
125 import * as s121 from "../tui/screens/waiting.ts";
126 import * as s122 from "../tui/screens/waiting_for_me.ts";
127 import * as s123 from "../tui/screens/wayback.ts";
128 import * as s124 from "../tui/screens/weekcard.ts";
103 import * as s99 from "../tui/screens/registry_items.ts";
104 import * as s100 from "../tui/screens/repolist.ts";
105 import * as s101 from "../tui/screens/requests.ts";
106 import * as s102 from "../tui/screens/resilience.ts";
107 import * as s103 from "../tui/screens/returning.ts";
108 import * as s104 from "../tui/screens/returns.ts";
109 import * as s105 from "../tui/screens/scorecard.ts";
110 import * as s106 from "../tui/screens/scrapes.ts";
111 import * as s107 from "../tui/screens/secrets.ts";
112 import * as s108 from "../tui/screens/sentinel.ts";
113 import * as s109 from "../tui/screens/ship_time.ts";
114 import * as s110 from "../tui/screens/slowpages.ts";
115 import * as s111 from "../tui/screens/sold.ts";
116 import * as s112 from "../tui/screens/spend.ts";
117 import * as s113 from "../tui/screens/stalepulls.ts";
118 import * as s114 from "../tui/screens/subscriptions.ts";
119 import * as s115 from "../tui/screens/system.ts";
120 import * as s116 from "../tui/screens/teams.ts";
121 import * as s117 from "../tui/screens/telemetry.ts";
122 import * as s118 from "../tui/screens/tell_undo.ts";
123 import * as s119 from "../tui/screens/traffic.ts";
124 import * as s120 from "../tui/screens/trafficview.ts";
125 import * as s121 from "../tui/screens/valves.ts";
126 import * as s122 from "../tui/screens/waiting.ts";
127 import * as s123 from "../tui/screens/waiting_for_me.ts";
128 import * as s124 from "../tui/screens/wayback.ts";
129 import * as s125 from "../tui/screens/weekcard.ts";
129130
130131 /** Each screen file that declares palette entries: its module and the export names. */
131132 export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readonly string[]])[] = [
@@ -254,4 +255,5 @@ export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readon
254255 [s122, ["entry"]],
255256 [s123, ["entry"]],
256257 [s124, ["entry"]],
258 [s125, ["entry"]],
257259 ];
src/http/mcp/tools/index.ts +2
@@ -155,6 +155,8 @@ export { tool as pulls } from "./pulls.ts";
155155 export { tool as queue_gates } from "./queue_gates.ts";
156156 export { tool as quotas } from "./quotas.ts";
157157 export { tool as read_file } from "./read_file.ts";
158 export { tool as registry_install } from "./registry_install.ts";
159 export { tool as registry_search } from "./registry_search.ts";
158160 export { tool as release_hold } from "./release_hold.ts";
159161 export { tool as release_keeper } from "./release_keeper.ts";
160162 export { tool as release_now } from "./release_now.ts";
src/http/mcp/tools/registry_install.ts added +19
@@ -0,0 +1,19 @@
1 import { installRegistryItem } from "../../../actions/registry_install.ts";
2 import { scopeAllows } from "../../../core/tokens.ts";
3 import { bad, good, isAnswer, REPO_ARG, repoArg, str, type Tool } from "../shared.ts";
4
5 export const tool: Tool = {
6 name: "registry_install",
7 doc: "`{ repo, item }`: open a pull that copies a registry item (and what it needs) into the app; the app owns the copy. Asked twice, it finds the first pull; once merged, asking again notes the install. Needs an admin of the repository with an admin-scope token",
8 description: "Install a component registry item into an app as a pull. Admin of the app.",
9 inputSchema: { type: "object", properties: { repo: REPO_ARG, item: { type: "string" } }, required: ["repo", "item"] },
10 writes: true,
11 async run(ctx, user, args) {
12 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin")) return bad("forbidden", "installing an item needs an admin-scope token");
13 const repo = repoArg(ctx, user, args);
14 if (isAnswer(repo)) return repo;
15 const done = await installRegistryItem(ctx.app, user, repo, str(args["item"]));
16 if (done.ok) return good({ install: done.value });
17 return done.error === "not_found" ? bad("not_found", "no such app or repository (owner/name)") : bad("invalid", done.error.message);
18 },
19 };
src/http/mcp/tools/registry_search.ts added +15
@@ -0,0 +1,15 @@
1 import { QUERY_MAX, searchItems } from "../../../registry/search.ts";
2 import { good, str, type Tool } from "../shared.ts";
3
4 export const tool: Tool = {
5 name: "registry_search",
6 doc: "`{ query? }`: the component registry's items (name, type, title, description, version, dependsOn) that every word of `query` names; no query lists them all. Reach for one before hand-rolling a part; `registry_install` opens the pull",
7 description: "Search the forge's component registry (shadcn format, served at /r/<name>.json).",
8 inputSchema: { type: "object", properties: { query: { type: "string", maxLength: QUERY_MAX } } },
9 writes: false,
10 readsWhen: () => true,
11 heldNotWhen: () => true,
12 async run(_ctx, _user, args) {
13 return good({ items: searchItems(str(args["query"])) });
14 },
15 };
src/registry/search.ts added +87
@@ -0,0 +1,87 @@
1 /**
2 * Finding and installing registry items (#17041, a slice of #6009): which items a few words name,
3 * and the branch, files and words of the pull that carries one item, with the items it depends on,
4 * into an app. Plain data in, plain data out; `actions/registry_install.ts` opens the pull.
5 */
6
7 import { ITEMS, findItem, type RegistryItem } from "./items.ts";
8
9 export const QUERY_MAX = 80;
10
11 export interface Found {
12 readonly name: string;
13 readonly type: string;
14 readonly title: string;
15 readonly description: string;
16 readonly version: string;
17 readonly dependsOn: string[];
18 }
19
20 const foundOf = (i: RegistryItem): Found => ({
21 name: i.name,
22 type: i.type,
23 title: i.title,
24 description: i.description,
25 version: i.meta.version,
26 dependsOn: i.registryDependencies ?? [],
27 });
28
29 /**
30 * The items every word of `query` appears in (name, title, description or type, any case), name
31 * matches first. An empty query is every item.
32 */
33 export function searchItems(query: string, items: readonly RegistryItem[] = ITEMS): Found[] {
34 const words = query.toLowerCase().slice(0, QUERY_MAX).split(/\s+/).filter(Boolean);
35 const hits: { item: RegistryItem; byName: boolean }[] = [];
36 for (const item of items) {
37 const hay = `${item.name} ${item.title} ${item.description} ${item.type}`.toLowerCase();
38 if (!words.every((w) => hay.includes(w))) continue;
39 hits.push({ item, byName: words.length > 0 && words.every((w) => item.name.includes(w)) });
40 }
41 return hits.sort((a, b) => Number(b.byName) - Number(a.byName)).map((h) => foundOf(h.item));
42 }
43
44 /** The item and, before it, every item it depends on, each once. */
45 export function withDependencies(name: string, items: readonly RegistryItem[] = ITEMS): RegistryItem[] {
46 const out: RegistryItem[] = [];
47 const visit = (n: string, depth: number): void => {
48 const item = items.find((i) => i.name === n);
49 if (item === undefined || depth > 8 || out.includes(item)) return;
50 for (const d of item.registryDependencies ?? []) visit(d, depth + 1);
51 out.push(item);
52 };
53 visit(name, 0);
54 return out;
55 }
56
57 export interface InstallPlan {
58 readonly item: RegistryItem;
59 /** The item and what it needs, in the order to write them. */
60 readonly items: RegistryItem[];
61 readonly branch: string;
62 readonly title: string;
63 readonly body: string;
64 }
65
66 /** One branch per item and version, so asking twice finds the first pull. */
67 export function installBranch(item: RegistryItem): string {
68 return `registry/install-${item.name}-${item.meta.version.replace(/[^0-9A-Za-z.-]/g, "-").replace(/\.+$/, "")}`;
69 }
70
71 /** The plan for `name`, or undefined when the registry has no such item. */
72 export function planInstall(name: string): InstallPlan | undefined {
73 const item = findItem(name);
74 if (item === undefined) return undefined;
75 const items = withDependencies(name);
76 const paths = items.flatMap((i) => i.files.map((f) => `- \`${f.target}\` (${i.name})`));
77 const title = `Registry: install ${item.name} ${item.meta.version}`;
78 const body = [
79 `Installs the registry's \`${item.name}\` (version ${item.meta.version}): ${item.description}`,
80 "",
81 "This pull writes the source of the item and what it needs into the app, which then owns it:",
82 ...paths,
83 "",
84 "Merging it notes the install, so later versions arrive as update pulls.",
85 ].join("\n");
86 return { item, items, branch: installBranch(item), title, body };
87 }
src/tui/screens/appregistry.ts +6 −1
@@ -19,6 +19,7 @@ import type { Session } from "../session.ts";
1919 import { style } from "../term/style.ts";
2020 import { wrap } from "../term/width.ts";
2121 import { fill, len, split } from "../ui/layout.ts";
22 import { registryItemsScreen } from "./registry_items.ts";
2223 import { ListState, confirmScreen, drawList, later, live, promptScreen, runAsync, type ListRow } from "./common.ts";
2324
2425 /** The palette's "Registry items", for a reader of a repository that is an app. */
@@ -101,7 +102,7 @@ export function appRegistryScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
101102 title: "Registry items",
102103 get keys() {
103104 return admin
104 ? [binding(["i"], "note an install"), binding(["x"], "forget the item"), binding(["u"], "open update pulls"), binding(["j", "k"], "move cursor")]
105 ? [binding(["i"], "note an install"), binding(["x"], "forget the item"), binding(["u"], "open update pulls"), binding(["a"], "browse the registry"), binding(["j", "k"], "move cursor")]
105106 : [binding(["j", "k"], "move cursor")];
106107 },
107108 async load(signal) {
@@ -123,6 +124,10 @@ export function appRegistryScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
123124 ctx.push(install());
124125 return true;
125126 }
127 if (e.key === "a") {
128 ctx.push(registryItemsScreen(f, ctx));
129 return true;
130 }
126131 if (e.key === "u") {
127132 update();
128133 return true;
src/tui/screens/registry_items.ts added +95
@@ -0,0 +1,95 @@
1 /**
2 * The component registry in the terminal (#17041, a slice of #6009): every item the forge serves at
3 * `/r`, read through `searchItems` as `registry_search` reads it. `/` filters by the words of a
4 * query; `i` asks for an `owner/name` and opens a pull that installs the item under the cursor,
5 * through `installRegistryItem`, the MCP's gate and words.
6 */
7
8 import { installRegistryItem } from "../../actions/registry_install.ts";
9 import type { UpdateOutcome } from "../../actions/registry_updates.ts";
10 import { canRead, getRepo } from "../../core/repos.ts";
11 import { searchItems, type Found } from "../../registry/search.ts";
12 import type { Ctx, Screen } from "../app/app.ts";
13 import { binding } from "../app/keys.ts";
14 import type { Session } from "../session.ts";
15 import { style } from "../term/style.ts";
16 import { fill, len, split } from "../ui/layout.ts";
17 import type { PaletteEntry } from "./entries.ts";
18 import { ListState, drawList, promptScreen, type ListRow } from "./common.ts";
19
20 const wording = (o: UpdateOutcome): string =>
21 o.state === "opened" ? `${o.item}: pull #${o.pull} opened` : o.state === "already" ? `${o.item}: pull #${o.pull} is already open` : o.state === "merged" ? `${o.item}: merged, noted at ${o.to}` : `${o.item}: ${o.why}`;
22
23 export function registryItemsScreen(f: Session, ctx: Ctx): Screen {
24 const state = new ListState();
25 let query = "";
26 let rows: Found[] = searchItems(query);
27 let note = "";
28 const reload = (): void => {
29 rows = searchItems(query);
30 state.clamp(rows.length);
31 ctx.invalidate();
32 };
33 const search = (): Screen =>
34 promptScreen(ctx, screen, {
35 title: "Search the registry",
36 label: "words in a name, title or description",
37 value: query,
38 onSubmit: (v) => {
39 query = v;
40 reload();
41 return undefined;
42 },
43 });
44 const install = (item: string): Screen =>
45 promptScreen(ctx, screen, {
46 title: `Install ${item}`,
47 label: "the app, as owner/name",
48 onSubmit: (v) => {
49 const [owner, name, ...rest] = v.trim().split("/");
50 const repo = owner && name && rest.length === 0 ? getRepo(f.app.db, owner, name) : undefined;
51 if (repo === undefined || !canRead(f.app.db, repo, f.user)) return "No such app; say it as owner/name.";
52 return (async () => {
53 const done = await installRegistryItem(f.app, f.user, repo, item);
54 note = done.ok ? wording(done.value) : done.error === "not_found" ? "Installing is the app's admin's." : done.error.message;
55 ctx.invalidate();
56 })();
57 },
58 });
59 const screen: Screen = {
60 title: "Component registry",
61 keys: [binding(["/"], "search"), binding(["i"], "install into an app"), binding(["j", "k"], "move cursor")],
62 render(area, s) {
63 const c = ctx.theme.c;
64 const lines: ListRow[] = rows.map((r) => ({ title: `${r.name} ${r.title}`, meta: `${r.type} v${r.version} · ${r.description}` }));
65 const head = note !== "" ? note : rows.length === 0 ? "Nothing in the registry matches." : `${rows.length} item${rows.length === 1 ? "" : "s"}${query === "" ? "" : ` for “${query}”`}.`;
66 const [top, list] = split(area, "v", [len(1), fill(1)]);
67 s.text(top!.x, top!.y, head, style(c.mutedFg, c.bg), top!.x + top!.w);
68 drawList(s, list!, c, state, lines);
69 },
70 key(e) {
71 if (state.key(e, rows.length)) return true;
72 if (e.ctrl || e.alt) return false;
73 if (e.key === "/") {
74 ctx.push(search());
75 return true;
76 }
77 const row = rows[state.index];
78 if (e.key === "i" && row !== undefined && f.user !== undefined) {
79 ctx.push(install(row.name));
80 return true;
81 }
82 return false;
83 },
84 };
85 return screen;
86 }
87
88 export const entry: PaletteEntry = {
89 rank: 610,
90 id: "registry-items",
91 title: "Component registry",
92 hint: "the forge's parts; install one into an app",
93 offered: () => true,
94 run: (session, ctx) => ctx.push(registryItemsScreen(session, ctx)),
95 };
test/conversation-confirm.test.ts +1 −1
@@ -127,7 +127,7 @@ describe("the one list of what asks first", () => {
127127 "asks", "assign", "attach_look", "bet", "board_pins", "board_write", "branches", "capacity", "changes", "valves", "cloud_accounts", "close", "confirm_wait",
128128 "crew", "decisions_by", "desk", "detach", "dxf_edit", "economics", "edit", "email_verify", "estimate", "feed_chips", "feed_dismiss", "feed_like", "flag_set", "flag_winner",
129129 "follow_mode", "forge", "fork", "front_page", "hold", "issue_teams", "keep_plan", "knobs", "labels", "lift", "limb", "maintenance", "make_it_yours", "map", "merge", "new_app",
130 "next_up", "week", "notify", "open_pull", "org_create", "origin_apps", "pins", "plan", "profile", "propose_to_parent_forge", "repo_labels", "reports",
130 "next_up", "week", "notify", "open_pull", "org_create", "origin_apps", "pins", "plan", "profile", "propose_to_parent_forge", "repo_labels", "reports", "registry_install",
131131 "repo", "request_review", "restore_drill", "review", "say", "scorecard", "signup", "snapshot_now", "spend", "steer", "sync", "system", "take_back", "take_updates",
132132 "teams", "tell", "templates", "threads", "trail", "upstream", "variant", "wait_for", "watch", "whoami_can", "write_file",
133133 ]);
test/mcp-forge-protocol.test.ts +2
@@ -143,6 +143,8 @@ describe("the forge over MCP: protocol", () => {
143143 "edit",
144144 "close",
145145 "read_file",
146 "registry_install",
147 "registry_search",
146148 "release_keeper",
147149 "write_file",
148150 "asks",
test/palette-roster.test.ts +4
@@ -226,6 +226,7 @@ test("a site-admin person is offered the whole roster", () => {
226226 ["lapsed", "Lapsed forges", "forges asleep until paid, when their data goes, pay again"],
227227 ["sold", "Sold forges", "what each bought forge costs, pays and leaves"],
228228 ["codes", "Gift codes", "make a code that gives a plan for free, and revoke one"],
229 ["registry-items", "Component registry", "the forge's parts; install one into an app"],
229230 ["archived", "Archived repositories", "put away, not gone: open one or restore it"],
230231 ["apps-crew", "What the crew is doing", "one plain sentence per app: who is on what"],
231232 ["planner", "Planner", "its last pass, its spend this week and what became of what it filed"],
@@ -345,6 +346,7 @@ test("a site-admin agent is offered the roster without the person-only entries",
345346 ["traffic-sources", "Traffic sources", "where people come from and where they go, for the forge"],
346347 ["audit", "Who can do what", "each app's doors from its contract.json: yes, own or no"],
347348 ["spend", "Spend", "what the crew's runs spent, by credential, app, agent, issue and kind"],
349 ["registry-items", "Component registry", "the forge's parts; install one into an app"],
348350 ["archived", "Archived repositories", "put away, not gone: open one or restore it"],
349351 ["apps-crew", "What the crew is doing", "one plain sentence per app: who is on what"],
350352 ["plan-row", "Plan", "this forge's plan, its last backup, and where its owner manages billing"],
@@ -466,6 +468,7 @@ test("a member person is offered the signed-in roster without the admin entries"
466468 ["tell-undo", "Take a tell back", "a tell you sent in the last minute, while nobody has read it"],
467469 ["buckets", "Buckets", "an object bucket's price a month, and binding it to an app"],
468470 ["audit", "Who can do what", "each app's doors from its contract.json: yes, own or no"],
471 ["registry-items", "Component registry", "the forge's parts; install one into an app"],
469472 ["archived", "Archived repositories", "put away, not gone: open one or restore it"],
470473 ["apps-crew", "What the crew is doing", "one plain sentence per app: who is on what"],
471474 ["claim-start", "Take an agent's work", "claim the repositories an agent started, from its one-time link"],
@@ -536,6 +539,7 @@ test("signed out, the palette offers sign-in and the public entries", () => {
536539 ["bugs", "Bugs", "open bugs and the bug clock"],
537540 ["health-voice", "Health — spoken", "how the forge is, in two plain sentences"],
538541 ["audit", "Who can do what", "each app's doors from its contract.json: yes, own or no"],
542 ["registry-items", "Component registry", "the forge's parts; install one into an app"],
539543 ["apps-crew", "What the crew is doing", "one plain sentence per app: who is on what"],
540544 ["design-gallery", "Component gallery", "every component the design names"],
541545 ["front", "Front page", "the apps a first visitor sees, ranked; an admin pins or hides"],
test/registry-install.test.ts added +183
@@ -0,0 +1,183 @@
1 /**
2 * The registry's other doors (#17041): `registry_search` and `registry_install` over the MCP, the
3 * action's gate, and the terminal's listing with its install prompt.
4 */
5 import { afterAll, beforeAll, describe, 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 { newApp } from "../src/actions/apps.ts";
10 import { installRegistryItem } from "../src/actions/registry_install.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { installedItems } from "../src/core/app_registry.ts";
13 import { pullForBranch } from "../src/core/pulls.ts";
14 import type { Repo } from "../src/core/repos.ts";
15 import { createToken } from "../src/core/tokens.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { ITEMS } from "../src/registry/items.ts";
19 import { installBranch, planInstall, searchItems, withDependencies } from "../src/registry/search.ts";
20 import { createForgeApp } from "../src/tui/forge.ts";
21 import { registryItemsScreen } from "../src/tui/screens/registry_items.ts";
22 import { headlessTerminal } from "../src/tui/term/terminal.ts";
23 import { seedAdmin } from "./helpers/admin.ts";
24 import { quietLogs } from "./helpers/globals.ts";
25 import { pollUntil } from "./helpers/poll.ts";
26 import { settleApp } from "./helpers/tui.ts";
27
28 quietLogs();
29
30 describe("registry search and install", () => {
31 let dir = "";
32 let app: App;
33 let servers: Servers;
34 let alice: User;
35 let bob: User;
36 let repo: Repo;
37 const tokens: Record<string, string> = {};
38 const emptyState = ITEMS.find((i) => i.name === "empty-state")!;
39
40 beforeAll(async () => {
41 dir = await mkdtemp(join(tmpdir(), "forge-registry-install-"));
42 app = createApp({ dataDir: dir, port: 0 });
43 servers = await serve(app);
44 const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "a-good-passphrase" });
45 if (!a.ok) throw new Error(a.error);
46 alice = a.value;
47 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
48 if (!b.ok) throw new Error(b.error);
49 bob = b.value;
50 const made = await newApp(app, alice, { name: "ledger" });
51 if (!made.ok) throw new Error(made.error);
52 repo = made.value.repo;
53 tokens["admin"] = createToken(app.db, alice.id, "t", "admin").token;
54 tokens["rw"] = createToken(app.db, alice.id, "t", "rw").token;
55 tokens["bob"] = createToken(app.db, bob.id, "t", "admin").token;
56 });
57 afterAll(async () => {
58 servers.stop();
59 app.close();
60 await rm(dir, { recursive: true, force: true });
61 });
62
63 const call = async (token: string, name: string, args: Record<string, unknown>): Promise<{ error: boolean; body: any }> => {
64 const res = await fetch(`${servers.url}/mcp`, {
65 method: "POST",
66 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
67 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
68 });
69 const out: any = await res.json();
70 const text = String(out.result.content[0].text);
71 let body: unknown = text;
72 try { body = JSON.parse(text); } catch { /* a refusal is words */ }
73 return { error: out.result.isError === true, body };
74 };
75
76 test("search matches every word, names first, and an empty query lists all", () => {
77 expect(searchItems("").map((i) => i.name)).toEqual(ITEMS.map((i) => i.name));
78 expect(searchItems("BUTTON").map((i) => i.name)[0]).toBe("button");
79 expect(searchItems("empty page").map((i) => i.name)).toEqual(["empty-state"]);
80 expect(searchItems("no-such-thing")).toEqual([]);
81 expect(searchItems("x".repeat(5000))).toEqual([]);
82 });
83
84 test("a plan brings the dependencies before the item, once each", () => {
85 expect(withDependencies("empty-state").map((i) => i.name)).toEqual(["tokens", "button", "empty-state"]);
86 expect(planInstall("nope")).toBeUndefined();
87 expect(planInstall("button")!.branch).toBe(installBranch(ITEMS.find((i) => i.name === "button")!));
88 });
89
90 test("the MCP searches without a token's scope mattering, and says what each item needs", async () => {
91 const got = await call(tokens["rw"]!, "registry_search", { query: "empty" });
92 expect(got.error).toBe(false);
93 expect(got.body.items).toMatchObject([{ name: "empty-state", dependsOn: ["tokens", "button"] }]);
94 });
95
96 test("registry_install is an admin-scope write for the app's admin only", async () => {
97 expect((await call(tokens["rw"]!, "registry_install", { repo: "alice/ledger", item: "button" })).error).toBe(true);
98 expect((await call(tokens["bob"]!, "registry_install", { repo: "alice/ledger", item: "button" })).error).toBe(true);
99 expect((await call(tokens["admin"]!, "registry_install", { repo: "alice/ledger", item: "../etc" })).body).toContain("registry_search");
100 expect(pullForBranch(app.db, repo.id, installBranch(emptyState))).toBeUndefined();
101 });
102
103 test("installing opens one pull with the item and its dependencies; twice finds it; a merge notes them", async () => {
104 const first = await call(tokens["admin"]!, "registry_install", { repo: "alice/ledger", item: "empty-state" });
105 expect(first.error).toBe(false);
106 const pull = pullForBranch(app.db, repo.id, installBranch(emptyState))!;
107 expect(first.body.install).toEqual({ item: "empty-state", to: emptyState.meta.version, state: "opened", pull: pull.number });
108 expect(pull.body).toContain("ui/button.ts");
109 expect(pull.body).toContain("styles/forge-tokens.css");
110 expect(installedItems(app.db, repo.id)).toEqual([]);
111
112 const again = await call(tokens["admin"]!, "registry_install", { repo: "alice/ledger", item: "empty-state" });
113 expect(again.body.install.state).toBe("already");
114
115 app.db.query("UPDATE pull SET merged_at = ?1 WHERE issue_id = ?2").run(new Date().toISOString(), pull.id);
116 const merged = await installRegistryItem(app, alice, repo, "empty-state");
117 expect(merged.ok && merged.value.state).toBe("merged");
118 expect(installedItems(app.db, repo.id).map((i) => i.item).sort()).toEqual(["button", "empty-state", "tokens"]);
119 const done = await installRegistryItem(app, alice, repo, "empty-state");
120 expect(done.ok && done.value).toMatchObject({ state: "refused", why: "already installed at that version" });
121 });
122
123 test("a closed, unmerged install pull does not block the item: a new pull opens on a new branch", async () => {
124 const made = await newApp(app, alice, { name: "closed" });
125 if (!made.ok) throw new Error(made.error);
126 const r = made.value.repo;
127 const button = ITEMS.find((i) => i.name === "button")!;
128 const first = await installRegistryItem(app, alice, r, "button");
129 expect(first.ok && first.value.state).toBe("opened");
130 const old = pullForBranch(app.db, r.id, installBranch(button))!;
131 app.db.query("UPDATE issue SET state = 'closed' WHERE id = ?1").run(old.id);
132 const second = await installRegistryItem(app, alice, r, "button");
133 expect(second.ok && second.value.state).toBe("opened");
134 const fresh = second.ok && second.value.state === "opened" ? second.value.pull : old.number;
135 expect(fresh).not.toBe(old.number);
136 const third = await installRegistryItem(app, alice, r, "button");
137 expect(third.ok && third.value).toEqual({ item: "button", to: button.meta.version, state: "already", pull: fresh });
138 });
139
140 const open = async (user: User, keys: string[]): Promise<string> => {
141 const terminal = headlessTerminal(120, 30);
142 const { app: tui, session } = createForgeApp(app, { sshUsername: user.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user }, { terminal, exitHooks: false });
143 tui.start();
144 tui.ctx.push(registryItemsScreen(session, tui.ctx));
145 await settleApp(tui);
146 for (const k of keys) {
147 terminal.feed(k);
148 await settleApp(tui);
149 }
150 const text = tui.screen.toText();
151 tui.stop?.();
152 return text;
153 };
154
155 test("the terminal lists the items, filters with /, and installs with i for an admin", async () => {
156 const all = await open(alice, []);
157 for (const i of ITEMS) expect(all).toContain(i.name);
158 const some = await open(alice, ["/", "empty", "\r"]);
159 expect(some).toContain("empty-state");
160 expect(some).not.toContain("Forge design tokens");
161 const text = await (async () => {
162 const lone = await newApp(app, alice, { name: "notes" });
163 if (!lone.ok) throw new Error(lone.error);
164 const shown = await open(alice, ["/", "button", "\r", "i", "alice/notes", "\r"]);
165 await pollUntil(() => pullForBranch(app.db, lone.value.repo.id, installBranch(ITEMS.find((i) => i.name === "button")!)) !== undefined, "the pull is opened", 5000);
166 return shown;
167 })();
168 expect(text).toContain("Component registry");
169 });
170
171 test("the terminal refuses a stranger's install in the admin's words", async () => {
172 const text = await open(bob, ["i", "alice/ledger", "\r"]);
173 expect(text).toContain("No such app");
174 });
175
176 test("a reader who is not the app's admin hears that installing is the admin's", async () => {
177 const shared = await newApp(app, alice, { name: "shared" });
178 if (!shared.ok) throw new Error(shared.error);
179 app.db.query("UPDATE repo SET visibility = 'public' WHERE id = ?1").run(shared.value.repo.id);
180 const text = await open(bob, ["i", "alice/shared", "\r"]);
181 expect(text).toContain("Installing is the app's admin's.");
182 });
183 });

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

Keyboard shortcuts

Docs