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

Describe an app in one sentence in the terminal and it is made, named from the sentence, with the crew on it, as New app does on the web #8060

Parked opened this
Closed without merging

scout/forge:scout/8047-describe-an-app-in-one-sentence-in-the-t → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
9 files changed +325 −94
src/actions/apps.ts +91 −1
@@ -9,7 +9,14 @@
99 import { pullDir } from "../core/pulls.ts";
1010 import { getIssue } from "../core/issues.ts";
1111 import { mayView } from "../core/sealed.ts";
12 import { requireVerified } from "./verify.ts";
12 import { storageLimitMessage } from "../core/storage.ts";
13 import { getUserByName } from "../core/users.ts";
14 import { REPO_INIT_FAILED, REPO_NAME_RULES } from "./repo_words.ts";
15 import { NO_SUCH_AGENT } from "./crew_limit_words.ts";
16 import { appLimitWords } from "./app_limit.ts";
17 import { deriveAppName } from "../web/pages/apps-name.ts";
18 import { NOT_A_MEMBER } from "../core/roles.ts";
19 import { requireVerified, UNVERIFIED_MESSAGE } from "./verify.ts";
1320 import { requireAppRoom } from "./app_limit.ts";
1421 import type { App } from "../app.ts";
1522 import { checkWord, type CheckWord } from "../apps/check_word.ts";
@@ -70,6 +77,7 @@ import {
7077 commitToBranch,
7178 createRepo,
7279 deleteRepo,
80 repositoryLimitMessage,
7381 resolveOwner,
7482 type CreateRepoActionError,
7583 } from "./repos.ts";
@@ -436,6 +444,88 @@ export async function newApp(
436444 });
437445 }
438446
447 /** Nothing in the sentence a slug can carry: punctuation only, or a script `[a-z0-9]` cannot. */
448 export const NO_NAME_ERROR =
449 "That doesn't leave anything to make a name from — type one below.";
450
451 /** How many suffixed names (`x-2`, `x-3`, …) a derived name will try before giving up. */
452 const MAX_NAME_ATTEMPTS = 30;
453
454 const NEW_APP_ERRORS: Record<string, string> = {
455 name_taken: "That owner already has a repository by that name.",
456 invalid_name: REPO_NAME_RULES,
457 git_init_failed: REPO_INIT_FAILED,
458 invalid_slug:
459 "That name makes no usable hostname — start it with a letter or digit.",
460 slug_taken:
461 "Another app already answers to that hostname. Pick another name.",
462 already_app: "That repository is already an app.",
463 scaffold_failed: "The starter app could not be committed.",
464 no_such_agent: NO_SUCH_AGENT,
465 };
466
467 /** The words for a refused new app: the web form's and the terminal's alike. */
468 export function newAppWords(
469 app: App,
470 actor: User | undefined,
471 owner: string,
472 error: string,
473 ): string {
474 if (error === "unverified") return UNVERIFIED_MESSAGE;
475 if (error === "not_member") return `Not made: ${NOT_A_MEMBER}.`;
476 if (error === "repository_limit" && actor)
477 return `Not made: ${repositoryLimitMessage(app, actor)}.`;
478 if (error === "storage_limit" && actor)
479 return `Not made: ${storageLimitMessage(app, actor.id)}.`;
480 const ownerId = getUserByName(app.db, owner || actor?.username || "")?.id;
481 if (error === "app_limit" && ownerId !== undefined)
482 return appLimitWords(app, ownerId);
483 return NEW_APP_ERRORS[error] ?? "That app could not be created.";
484 }
485
486 /** What was made, in a sentence: where the app starts and who has the first issue. */
487 export function newAppNote(app: App, made: NewAppResult): string {
488 const { repo, app: record, issue, plan } = made;
489 const url = appsRuntime(app)?.urlFor(record, "production");
490 const first =
491 url === undefined
492 ? `${repo.name} is an app, but nothing is serving apps on this forge.`
493 : `${repo.name} is starting at ${url}.`;
494 const second =
495 issue === undefined
496 ? ""
497 : issue.assigneeName === null
498 ? ` #${issue.number} is waiting for someone.`
499 : plan
500 ? ` ${plan.agent} was picked for #${issue.number} — ${plan.summary}`
501 : ` #${issue.number} is assigned to ${issue.assigneeName}.`;
502 return `${first}${second}`;
503 }
504
505 /**
506 * `newApp` from a sentence: an explicit `name` is never second-guessed;
507 * left blank, the sentence names the app, and a taken derived name tries
508 * `base-2`, `base-3`, … — the same `name_taken` check, run more than once.
509 */
510 export async function newAppFromSentence(
511 app: App,
512 actor: User | undefined,
513 input: Omit<NewAppInput, "name"> & { name?: string },
514 onPhase: (name: string, ms: number) => void = () => {},
515 ): Promise<Result<NewAppResult, NewAppError | "unverified" | "no_name">> {
516 const explicit = (input.name ?? "").trim();
517 const base = explicit === "" ? deriveAppName(input.description ?? "") : explicit;
518 if (base === undefined) return err("no_name");
519 let made = await newApp(app, actor, { ...input, name: base }, onPhase);
520 for (
521 let n = 2;
522 explicit === "" && !made.ok && made.error === "name_taken" && n <= MAX_NAME_ATTEMPTS;
523 n++
524 )
525 made = await newApp(app, actor, { ...input, name: `${base}-${n}` }, onPhase);
526 return made;
527 }
528
439529 export interface AppView {
440530 readonly app: AppRecord;
441531 readonly environments: EnvStatus[];
src/tui/forge.ts +9
@@ -76,6 +76,7 @@ import { newPullScreen } from "./screens/newpull.ts";
7676 import { newForgeScreen } from "./screens/newforge.ts";
7777 import { newOrgScreen } from "./screens/neworg.ts";
7878 import { migrateScreen } from "./screens/migrate.ts";
79 import { newAppScreen } from "./screens/newapp.ts";
7980 import { newRepoScreen } from "./screens/newrepo.ts";
8081 import { repoScreen } from "./screens/repo.ts";
8182 import { signInScreen } from "./screens/signin.ts";
@@ -211,6 +212,14 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
211212 ctx.push(signInScreen(session, ctx, () => ctx.invalidate())),
212213 },
213214 );
215 // As /apps/new makes one: a person's sentence, an app and its crew.
216 if (session.user !== undefined && session.user.kind !== "agent")
217 commands.push({
218 id: "new-app",
219 title: "New app",
220 hint: "say what it does in a sentence; the crew starts on it",
221 run: () => ctx.push(newAppScreen(session, ctx, blank("New app"))),
222 });
214223 // An organization you own, as /organizations/new and MCP `org_create` make it: a person's, never an agent's (#7260).
215224 if (session.user !== undefined && session.user.kind !== "agent")
216225 commands.push({
src/tui/screens/newapp.ts added +71
@@ -0,0 +1,71 @@
1 /**
2 * "New app" in the terminal: one sentence, and the app is made, named from
3 * the sentence, with the crew on it — `newAppFromSentence`, as the web form
4 * calls it, so the name rule, the limits and the refusals are the same
5 * words. Someone in organizations is asked for the owner first.
6 */
7
8 import {
9 newAppFromSentence,
10 newAppNote,
11 newAppWords,
12 NO_NAME_ERROR,
13 } from "../../actions/apps.ts";
14 import { listOrgsForUser } from "../../core/orgs.ts";
15 import { deriveAppName } from "../../web/pages/apps-name.ts";
16 import type { Ctx, Screen } from "../app/app.ts";
17 import type { Session } from "../session.ts";
18 import { later, promptScreen, runAsync } from "./common.ts";
19 import { repoScreen } from "./repo.ts";
20 import { local } from "./where.ts";
21
22 export function newAppScreen(f: Session, ctx: Ctx, parent: Screen): Screen {
23 const user = f.user;
24 const owners = user
25 ? [user.username, ...listOrgsForUser(f.db, user.id).map((o) => o.username)]
26 : [];
27
28 const make = (owner: string): Screen =>
29 promptScreen(ctx, parent, {
30 title: "New app",
31 label: owner === user?.username ? "What should it do?" : `What should it do? (under ${owner})`,
32 placeholder: "a place to keep my reading list",
33 hint: "One sentence. It names the app, and the crew starts on it.",
34 onSubmit: (sentence) => {
35 if (deriveAppName(sentence) === undefined) return NO_NAME_ERROR;
36 ctx.toast("Making your app…");
37 runAsync(ctx, async () => {
38 const made = await newAppFromSentence(f.app, user, {
39 owner,
40 description: sentence,
41 visibility: "private",
42 pickAgent: true,
43 });
44 if (!made.ok) {
45 ctx.toast(
46 made.error === "no_name"
47 ? NO_NAME_ERROR
48 : newAppWords(f.app, user, owner, made.error),
49 "danger",
50 );
51 return;
52 }
53 ctx.toast(newAppNote(f.app, made.value), "success");
54 ctx.push(repoScreen(f, ctx, local(f, made.value.repo)));
55 });
56 return undefined;
57 },
58 });
59
60 if (owners.length < 2) return make(owners[0] ?? "");
61 return promptScreen(ctx, parent, {
62 title: "New app",
63 label: "Owner",
64 value: owners[0] ?? "",
65 hint: `One of: ${owners.join(", ")}`,
66 onSubmit: (owner) =>
67 owners.includes(owner)
68 ? later(ctx, () => make(owner))
69 : `Pick one of: ${owners.join(", ")}`,
70 });
71 }
src/web/pages/apps.ts +35 −90
@@ -12,23 +12,20 @@
1212 * 404 for everyone.
1313 */
1414
15 import { storageLimitMessage } from "../../core/storage.ts";
16 import { repositoryLimitMessage } from "../../actions/repos.ts";
17 import { REPO_INIT_FAILED, REPO_NAME_RULES } from "../../actions/repo_words.ts";
18 import { appLimitWords } from "../../actions/app_limit.ts";
19 import { NO_SUCH_AGENT } from "../../actions/crew_limit_words.ts";
20 import { getUserByName } from "../../core/users.ts";
2115 import {
2216 appView,
23 newApp,
2417 openEnvUrl,
2518 redeployEnv,
2619 stopEnv,
2720 terminalFor,
21 newAppFromSentence,
22 newAppNote,
23 newAppWords,
24 NO_NAME_ERROR,
2825 } from "../../actions/apps.ts";
2926 import { listAllAgents } from "../../actions/crew.ts";
3027 import { planningAvailable } from "../../crew/plan.ts";
31 import { appNameJs, deriveAppName } from "./apps-name.ts";
28 import { appNameJs } from "./apps-name.ts";
3229 import { STARTERS, starterFromQuery, starterHref } from "./apps-starters.ts";
3330 import { previewEnv, type EnvName } from "../../apps/data.ts";
3431 import { envRefusalText, redeployedText, stoppedText } from "../../actions/env_words.ts";
@@ -443,26 +440,6 @@ export function newAppPage(ctx: Ctx): Response {
443440 return response;
444441 }
445442
446 /** Nothing in the sentence a slug can carry: punctuation only, or a script `[a-z0-9]` cannot. */
447 const NO_NAME_ERROR =
448 "That doesn't leave anything to make a name from — type one below.";
449
450 /** How many suffixed names (`x-2`, `x-3`, …) a derived name will try before giving up. */
451 const MAX_NAME_ATTEMPTS = 30;
452
453 const NEW_APP_ERRORS: Record<string, string> = {
454 name_taken: "That owner already has a repository by that name.",
455 invalid_name: REPO_NAME_RULES,
456 git_init_failed: REPO_INIT_FAILED,
457 invalid_slug:
458 "That name makes no usable hostname — start it with a letter or digit.",
459 slug_taken:
460 "Another app already answers to that hostname. Pick another name.",
461 already_app: "That repository is already an app.",
462 scaffold_failed: "The starter app could not be committed.",
463 no_such_agent: NO_SUCH_AGENT,
464 };
465
466443 // POST /apps/new
467444 export async function newAppSubmit(ctx: Ctx): Promise<Response> {
468445 if (!ctx.auth.user) return signInFirst(ctx);
@@ -481,49 +458,35 @@ export async function newAppSubmit(ctx: Ctx): Promise<Response> {
481458 // An explicit name is never second-guessed; left blank, the sentence
482459 // names the app — and the server derives that name itself (never trusting
483460 // whatever the field carried in): the field is only a client-side preview.
484 const explicitName = values.name.trim();
485 const base = explicitName === "" ? deriveAppName(values.description) : explicitName;
486 if (base === undefined) {
487 return page(
488 {
489 ctx,
490 title: "New app",
491 body: newAppForm(ctx, values, plannerOffered(ctx), NO_NAME_ERROR),
492 scriptJs: appNameJs,
493 },
494 422,
495 );
496 }
497 const rest = {
498 owner: values.owner,
499 description: values.description,
500 visibility: values.visibility === "public" ? "public" : "private",
501 ...(pickAgent
502 ? { pickAgent: true }
503 : values.agent === ""
504 ? {}
505 : { agent: values.agent }),
506 } as const;
507 let made = await newApp(ctx.app, ctx.auth.user, { ...rest, name: base }, phase);
508 // A derived name that collides tries `base-2`, `base-3`, … — the same
509 // `name_taken` check an explicit name gets, just run more than once.
510 for (
511 let n = 2;
512 explicitName === "" && !made.ok && made.error === "name_taken" && n <= MAX_NAME_ATTEMPTS;
513 n++
514 ) {
515 made = await newApp(ctx.app, ctx.auth.user, {
516 ...rest,
517 name: `${base}-${n}`,
518 }, phase);
519 }
461 const made = await newAppFromSentence(
462 ctx.app,
463 ctx.auth.user,
464 {
465 owner: values.owner,
466 name: values.name,
467 description: values.description,
468 visibility: values.visibility === "public" ? "public" : "private",
469 ...(pickAgent
470 ? { pickAgent: true }
471 : values.agent === ""
472 ? {}
473 : { agent: values.agent }),
474 },
475 phase,
476 );
520477 if (!made.ok) {
478 if (made.error === "no_name")
479 return page(
480 {
481 ctx,
482 title: "New app",
483 body: newAppForm(ctx, values, plannerOffered(ctx), NO_NAME_ERROR),
484 scriptJs: appNameJs,
485 },
486 422,
487 );
521488 if (made.error === "forbidden_owner" || made.error === "unauthorized")
522489 return new Response("forbidden", { status: 403 });
523 const ownerId = getUserByName(
524 ctx.app.db,
525 values.owner || ctx.auth.user.username,
526 )?.id;
527490 return page(
528491 {
529492 ctx,
@@ -532,36 +495,18 @@ export async function newAppSubmit(ctx: Ctx): Promise<Response> {
532495 ctx,
533496 values,
534497 plannerOffered(ctx),
535 made.error === "repository_limit"
536 ? `Not made: ${repositoryLimitMessage(ctx.app, ctx.auth.user!)}.`
537 : made.error === "storage_limit"
538 ? `Not made: ${storageLimitMessage(ctx.app, ctx.auth.user!.id)}.`
539 : made.error === "app_limit" && ownerId !== undefined
540 ? appLimitWords(ctx.app, ownerId)
541 : (NEW_APP_ERRORS[made.error] ?? "That app could not be created."),
498 newAppWords(ctx.app, ctx.auth.user, values.owner, made.error),
542499 ),
543500 scriptJs: appNameJs,
544501 },
545502 422,
546503 );
547504 }
548 const { repo, app: record, issue, plan } = made.value;
549 const url = appsRuntime(ctx.app)?.urlFor(record, "production");
550 const first =
551 url === undefined
552 ? `${repo.name} is an app, but nothing is serving apps on this forge.`
553 : `${repo.name} is starting at ${url}.`;
554 const second =
555 issue === undefined
556 ? ""
557 : issue.assigneeName === null
558 ? ` #${issue.number} is waiting for someone.`
559 : plan
560 ? ` ${plan.agent} was picked for #${issue.number} — ${plan.summary}`
561 : ` #${issue.number} is assigned to ${issue.assigneeName}.`;
505 const { repo } = made.value;
506 const message = newAppNote(ctx.app, made.value);
562507 // The repository's home is the app page (repoHome), once the record
563508 // exists; the code is its Files step.
564 return flashTo(ctx, repoBase(repo), { message: `${first}${second}` });
509 return flashTo(ctx, repoBase(repo), { message });
565510 }
566511
567512 // ---- the repo home's strip ----
test/crew-limit-words.test.ts +1 −1
@@ -19,7 +19,7 @@ const read = (file: string): string => readFileSync(join(root, file), "utf8");
1919 const readers: Record<string, Record<string, string>> = {
2020 "src/actions/migrate.ts": { AT_REPOSITORY_LIMIT, NO_SUCH_AGENT },
2121 "src/actions/repos.ts": { AT_REPOSITORY_LIMIT },
22 "src/web/pages/apps.ts": { NO_SUCH_AGENT },
22 "src/actions/apps.ts": { NO_SUCH_AGENT },
2323 "src/fleet/verbs.ts": { AGENT_NOT_ON_CREW },
2424 "src/tui/screens/common.ts": { AGENT_NOT_ON_CREW },
2525 "src/http/mcp/tools/assign.ts": { AGENT_NOT_ON_CREW },
test/palette-roster.test.ts +2
@@ -57,6 +57,7 @@ test("a site-admin person is offered the whole roster", () => {
5757 ["new-pull", "New pull request", "owner/name"],
5858 ["settings", "Repository settings", "owner/name"],
5959 ["new-repo", "New repository", undefined],
60 ["new-app", "New app", "say what it does in a sentence; the crew starts on it"],
6061 ["new-org", "New organization", "an organization you own, for a client's apps"],
6162 ["migrate", "Migrate a repository", "bring one in from an origin or a URL, pick its branch, put a crew on it"],
6263 ["new-forge", "New forge", "spawn a client's forge and get its claim link"],
@@ -175,6 +176,7 @@ test("a member person is offered the signed-in roster without the admin entries"
175176 ["new-pull", "New pull request", "owner/name"],
176177 ["settings", "Repository settings", "owner/name"],
177178 ["new-repo", "New repository", undefined],
179 ["new-app", "New app", "say what it does in a sentence; the crew starts on it"],
178180 ["new-org", "New organization", "an organization you own, for a client's apps"],
179181 ["migrate", "Migrate a repository", "bring one in from an origin or a URL, pick its branch, put a crew on it"],
180182 ["new-forge", "New forge", "spawn a client's forge and get its claim link"],
test/repo-words.test.ts +1 −1
@@ -10,7 +10,7 @@ import { join } from "node:path";
1010 import { REPO_INIT_FAILED, REPO_NAME_RULES } from "../src/actions/repo_words.ts";
1111
1212 const WORDS = { REPO_NAME_RULES, REPO_INIT_FAILED };
13 const READERS = ["src/actions/migrate.ts", "src/web/pages/apps.ts", "src/web/pages/site.ts"];
13 const READERS = ["src/actions/migrate.ts", "src/actions/apps.ts", "src/web/pages/site.ts"];
1414
1515 describe("a repository's refusal words", () => {
1616 for (const [name, words] of Object.entries(WORDS)) {
test/tui-apps.test.ts +1 −1
@@ -463,7 +463,7 @@ describe("terminal: apps, runs and the crew", () => {
463463 await h.until("On you");
464464 // alice is the site admin, so the crew entry would have been there.
465465 const ids = forgeCommands(h.session)(h.app.ctx).map((c) => c.id);
466 for (const gone of ["apps", "app", "runs", "new-app", "crew"])
466 for (const gone of ["apps", "app", "runs", "crew"])
467467 expect(ids).not.toContain(gone);
468468 expect(ids).toContain("repo");
469469 expect(ids).toContain("pulls");
test/tui-newapp.test.ts added +114
@@ -0,0 +1,114 @@
1 /**
2 * "New app" in the terminal: a sentence makes an app named from it through
3 * `newAppFromSentence`, the function the web form calls; a taken name takes
4 * `-2`; an empty sentence is refused in the web's words.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { NO_NAME_ERROR } from "../src/actions/apps.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { getAppByRepo } from "../src/core/apps.ts";
13 import { markVerified } from "../src/core/verify.ts";
14 import { getRepo } from "../src/core/repos.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { createForgeApp, forgeCommands, Session } from "../src/tui/forge.ts";
17 import { blank } from "../src/tui/screens/common.ts";
18 import { newAppScreen } from "../src/tui/screens/newapp.ts";
19 import { deriveAppName } from "../src/web/pages/apps-name.ts";
20 import { headlessTerminal } from "../src/tui/term/terminal.ts";
21 import { quietLogs } from "./helpers/globals.ts";
22 import { settleApp } from "./helpers/tui.ts";
23
24 quietLogs();
25 const planWas = process.env["FORGE_APP_PLAN"];
26
27 let dir: string;
28 let app: App;
29 let alice: User;
30
31 const identity = (user?: User) => ({
32 sshUsername: user?.username ?? "git",
33 remoteAddress: "127.0.0.1",
34 fingerprint: "SHA256:test",
35 user,
36 });
37
38 beforeAll(async () => {
39 process.env["FORGE_APP_PLAN"] = "0";
40 dir = await mkdtemp(join(tmpdir(), "forge-tui-newapp-"));
41 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
42 const made = await createUser(app.db, {
43 origin: "seed",
44 trusted: true,
45 username: "alice",
46 email: "[email protected]",
47 password: "a-good-passphrase",
48 adminIfFirst: true,
49 });
50 if (!made.ok) throw new Error(made.error);
51 alice = made.value;
52 markVerified(app.db, alice.id, new Date().toISOString());
53 });
54 afterAll(async () => {
55 if (planWas === undefined) delete process.env["FORGE_APP_PLAN"];
56 else process.env["FORGE_APP_PLAN"] = planWas;
57 app.db.close();
58 await rm(dir, { recursive: true, force: true });
59 });
60
61 async function withScreen(
62 body: (h: { text: () => string; feed: (s: string) => Promise<void> }) => Promise<void>,
63 ) {
64 const terminal = headlessTerminal(120, 30);
65 const { app: tui, session } = createForgeApp(app, identity(alice), { terminal, exitHooks: false });
66 tui.start();
67 tui.ctx.push(newAppScreen(session, tui.ctx, blank("New app")));
68 try {
69 await settleApp(tui);
70 await body({
71 text: () => tui.screen.toText(),
72 feed: async (s) => {
73 terminal.feed(s);
74 await settleApp(tui);
75 },
76 });
77 } finally {
78 tui.stop?.();
79 }
80 }
81
82 const sentence = "A tiny reading list tracker";
83
84 describe("the new app screen", () => {
85 test("the palette offers it to a signed-in person, never an agent or a guest", () => {
86 const ids = (u?: User) => forgeCommands(new Session(app, identity(u)))({} as never).map((c) => c.id);
87 expect(ids(alice)).toContain("new-app");
88 expect(ids({ ...alice, kind: "agent" })).not.toContain("new-app");
89 expect(ids()).not.toContain("new-app");
90 });
91
92 test("a sentence makes an app named from it, and a second makes name-2", async () => {
93 const name = deriveAppName(sentence)!;
94 expect(name).toBeDefined();
95 await withScreen(async ({ feed }) => {
96 await feed(`${sentence}\r`);
97 const repo = getRepo(app.db, "alice", name);
98 expect(repo).toBeDefined();
99 expect(getAppByRepo(app.db, repo!.id)).toBeDefined();
100 });
101 await withScreen(async ({ feed }) => {
102 await feed(`${sentence}\r`);
103 const repo = getRepo(app.db, "alice", `${name}-2`);
104 expect(repo).toBeDefined();
105 expect(getAppByRepo(app.db, repo!.id)).toBeDefined();
106 });
107 });
108
109 test("an empty sentence is refused in the web's words and nothing is made", () =>
110 withScreen(async ({ text, feed }) => {
111 await feed("\r");
112 expect(text()).toContain(NO_NAME_ERROR.slice(0, 40));
113 }));
114 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs