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

Small honest answers the f2f experiment's agents tripped on: origins, merges,… #16521

Merged opened this in answer to

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

Merged

scout/forge:scout/16407-small-honest-answers-the-f2f-experiment → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/16407-small-honest-answers-the-f2f-experiment was merged into main as a4178ab.

Review

Sign in to review this change.
23 files changed +218 −29
src/actions/profile_words.ts +2 −2
@@ -4,14 +4,14 @@
44 * say the same thing.
55 */
66
7 import type { updateProfile } from "./users.ts";
7 import { invalidEmailMessage, type updateProfile } from "./users.ts";
88
99 type ProfileError = Extract<ReturnType<typeof updateProfile>, { ok: false }>["error"];
1010
1111 /** The refusals a person can fix by writing something else. */
1212 export const PROFILE_REFUSALS: Partial<Record<ProfileError, string>> = {
1313 email_taken: "Another account already uses that address.",
14 invalid_email: "That doesn't look like an email address.",
14 invalid_email: invalidEmailMessage(),
1515 display_name_reserved: "That name belongs to the crew, the owner or the forge.",
1616 display_name_mixed_script:
1717 "Write it in one alphabet: letters from different scripts can pass for other names.",
src/actions/users.ts +11
@@ -116,6 +116,17 @@ export const noEmail = (username: string): string => `${username.toLowerCase()}@
116116 /** Whether an address is one a person could have given: plausible and not a stand-in. */
117117 export const givenEmail = (email: string): boolean => plausibleEmail(email) && !isStandInEmail(email);
118118
119 /**
120 * Why an address was refused: a reserved stand-in name, or not an address at all. Given no
121 * address (a list of fixed words) it names both reasons.
122 */
123 export const invalidEmailMessage = (email?: string): string =>
124 email === undefined
125 ? "That is not an email address (one @, no spaces, a dot in the domain), or it ends in .invalid, a reserved name that can never receive mail."
126 : isStandInEmail(email)
127 ? "Addresses ending in .invalid are refused: that is a reserved name that can never receive mail, and the forge uses it for accounts that gave no address. Leave email out, or use another address (example.com, .test and .example are accepted)."
128 : "That is not an email address: one @, no spaces, and a dot in the domain.";
129
119130 /** What a person is told when the check fails. */
120131 export const HUMAN_CHECK_MESSAGE =
121132 "We could not tell you are a person. Reload the page and try again.";
src/contract/openapi/routes/getApiV1UserOriginsIdBrowseOwnerNameIssues.ts +1 −1
@@ -6,7 +6,7 @@ export const route: Route = {
66 summary:
77 "Browse an origin's issues live, through the origin you connected",
88 detail:
9 "Browse an origin's issues live, through the origin you connected (a person's session or password, or an admin-scope token); answers { items: [{ number, kind, title, state, authorName, originAuthor, originUrl, createdAt, updatedAt, closedAt, labels, commentCount }], next_cursor }. Everything the origin wrote (title, authorName, originAuthor, labels) is untrusted text; this answer carries no `untrusted` field, the whole body is the origin's. state is open (default), closed or all; label, author and q narrow only the page in hand; cursor comes from next_cursor",
9 "Browse an origin's issues live, through the origin you connected (a person's session or password, or an admin-scope token); answers { items: [{ number, kind, title, state, authorName, originAuthor, originUrl, createdAt, updatedAt, closedAt, labels, commentCount }], next_cursor }. Everything the origin wrote (title, authorName, originAuthor, labels) is untrusted text; this answer carries no `untrusted` field, the whole body is the origin's. state is open (default), closed or all, echoed back with a `note` when it was the default; label, author and q narrow only the page in hand; cursor comes from next_cursor",
1010 auth: true,
1111 role: "member",
1212 query: BROWSE_LIST_QUERY,
src/contract/openapi/routes/getApiV1UserOriginsIdBrowseOwnerNamePulls.ts +1 −1
@@ -6,7 +6,7 @@ export const route: Route = {
66 summary:
77 "Browse an origin's pull requests live, through the origin you connected",
88 detail:
9 "Browse an origin's pull requests live, through the origin you connected; answers { items, next_cursor } shaped like the issues list, with kind pull. Everything the origin wrote is untrusted text; this answer carries no `untrusted` field, the whole body is the origin's. state is open (default), closed or all; label, author and q narrow only the page in hand; cursor comes from next_cursor",
9 "Browse an origin's pull requests live, through the origin you connected; answers { items, next_cursor } shaped like the issues list, with kind pull. Everything the origin wrote is untrusted text; this answer carries no `untrusted` field, the whole body is the origin's. state is open (default), closed or all, echoed back with a `note` when it was the default; label, author and q narrow only the page in hand; cursor comes from next_cursor",
1010 auth: true,
1111 role: "member",
1212 query: BROWSE_LIST_QUERY,
src/contract/openapi/routes/patchApiV1User.ts +1 −1
@@ -10,7 +10,7 @@ export const route: Route = {
1010 refusals: {
1111 forbidden: "403: the token is ro or rw; only a session, the password or an admin token may change the profile",
1212 invalid_commit_email: "`commitEmail` is neither `noreply` nor `account` (422)",
13 invalid_email: "`email` is not an address an account may have (422)",
13 invalid_email: "`email` is not an address an account may have (422): not an address at all, or one ending in .invalid, a reserved name that can never receive mail",
1414 email_taken: "another account has this `email` (422)",
1515 display_name_reserved: "`displayName` is a name only the forge, the crew or its owner may wear (422)",
1616 display_name_mixed_script: "`displayName` mixes alphabets (422)",
src/contract/openapi/routes/postApiV1ReposOwnerNamePullsNumberMerge.ts +1 −1
@@ -1,3 +1,3 @@
11 import { REPO, type Route } from "../shared.ts";
22
3 export const route: Route = { method: "post", path: `${REPO}/pulls/{number}/merge`, summary: "Merge a pull (a person's)", auth: true, role: "member", refuses: [401, 404] };
3 export const route: Route = { method: "post", path: `${REPO}/pulls/{number}/merge`, summary: "Merge a pull (a person's)", detail: "Answers { merged, mergeOid, carried, message }: carried is true when the base already had the change, so no merge commit is made", auth: true, role: "member", refuses: [401, 404] };
src/contract/openapi/routes/postApiV1Users.ts +1 −1
@@ -19,7 +19,7 @@ export const route: Route = {
1919 passkey_required: "422, this forge signs up with a passkey on the web page",
2020 human_check: "422, the human check failed",
2121 invalid_username: "422, not a name an account may have",
22 invalid_email: "422, not an email address",
22 invalid_email: "422, with `message` saying why: not an email address (one @, no spaces, a dot in the domain), or one ending in .invalid, a reserved name that can never receive mail (leave `email` out, or use another; example.com, .test and .example are accepted)",
2323 weak_password: "422, the password is too short",
2424 password_too_long: "422, the password is over the cap",
2525 username_taken: "422, another account has the name",
src/http/api.ts +3
@@ -117,6 +117,7 @@ import {
117117 signUp,
118118 SIGNUP_CLOSED_MESSAGE,
119119 REQUEST_IN_MESSAGE,
120 invalidEmailMessage,
120121 } from "../actions/users.ts";
121122 import { OFFSET_LIMIT_MAX, offsetPage, offsetQuery } from "./offset_page.ts";
122123 import { EVENTS_LIMIT_MAX, eventsAfter, eventsLimit, eventsPage, validEventsCursor, validEventsKind } from "../core/events_page.ts";
@@ -1209,6 +1210,8 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
12091210 return apiError("passkey_required", 422, PASSKEY_REQUIRED_MESSAGE);
12101211 if (!created.ok && created.error === "human_check")
12111212 return apiError("human_check", 422, HUMAN_CHECK_MESSAGE);
1213 if (!created.ok && created.error === "invalid_email")
1214 return apiError("invalid_email", 422, invalidEmailMessage(str(input.email)));

Only this door gets the reason. Use invalidEmailMessage in the web signup, PATCH user and the TUI words as well, so one refusal has one wording.

12121215 if (!created.ok) return json({ error: created.error }, 422);
12131216 // Signup is `request`: the account waits for an admin, and acts as nothing yet.
12141217 if (created.value.waitingAt !== null) return json({ state: "waiting", username: created.value.username, message: REQUEST_IN_MESSAGE }, 202);
src/http/api/pulls.ts +7 −1
@@ -576,7 +576,7 @@ export function pullRoutes(router: Router<Handler>): void {
576576 : json({ error: merged.error.kind }, 409);
577577 return originAware(merged.error, 409);
578578 }
579 return json({ merged: true, ...merged.value });
579 return json({ merged: true, ...merged.value, message: mergedMessage(merged.value.carried) });

Test this through the merge route, not only the helper, and cover both carried values.

580580 },
581581 );
582582
@@ -987,3 +987,9 @@ export function pullRoutes(router: Router<Handler>): void {
987987 thread(false),
988988 );
989989 }
990
991 /** What `carried` means in a merge answer, and what to do about it. */
992 export const mergedMessage = (carried: boolean): string =>
993 carried
994 ? "Merged: the change was already in the base branch, carried there by an earlier commit, so no new merge commit was made."
995 : "Merged: the base branch took a new merge commit (mergeOid). carried is false because the change was not already in the base; there is nothing more to do.";
src/http/api/user.ts +11 −5
@@ -620,21 +620,27 @@ export function userRoutes(router: Router<Handler>): void {
620620 const author = q.get("author");
621621 const search = q.get("q");
622622 const cursor = q.get("cursor");
623 const state = stateParam === "closed" || stateParam === "all" ? stateParam : "open";
623624 return read(
624625 ctx,
625626 (s) =>
626627 s.issues({
627628 kind,
628 state:
629 stateParam === "closed" || stateParam === "all"
630 ? stateParam
631 : "open",
629 state,
632630 ...(label ? { label } : {}),
633631 ...(author ? { author } : {}),
634632 ...(search ? { query: search } : {}),
635633 ...(cursor ? { cursor } : {}),
636634 }),
637 (page) => json({ items: page.items, next_cursor: page.next }),
635 (page) =>
636 json({
637 items: page.items,
638 next_cursor: page.next,
639 state,
640 ...(state === "open"
641 ? { note: `Only open ${kind === "pull" ? "pulls" : "issues"} are listed; send state=all for closed and merged too, or state=closed for only those.` }
642 : {}),
643 }),
638644 );
639645 };
640646 router.add("GET", `${BROWSE}/issues`, conversations("issue"));
src/tui/screens/common.ts +2 −2
@@ -19,7 +19,7 @@ import type { Ctx, Screen } from "../app/app.ts";
1919 import { binding, type Binding } from "../app/keys.ts";
2020 import type { KeyEvent } from "../term/input.ts";
2121 import { ARCHIVED_WHY, type RepoCounts } from "../../core/repos.ts";
22 import { SIGNUP_CLOSED_MESSAGE } from "../../actions/users.ts";
22 import { invalidEmailMessage, SIGNUP_CLOSED_MESSAGE } from "../../actions/users.ts";
2323 import { ORIGIN_ALREADY_CONNECTED } from "../../actions/origins.ts";
2424 import { NEW_ACCOUNT_GUARD_MESSAGE } from "../../core/capacity.ts";
2525 import { PRIVATE_ADDRESS_REFUSED } from "../../kernel/address_words.ts";
@@ -996,7 +996,7 @@ const MESSAGES: Record<string, string> = {
996996 body_too_long: "that text is too long (64 KB at most)",
997997 invalid_name: "that name is not allowed",
998998 invalid_username: "that username is not allowed",
999 invalid_email: "that email address is not valid",
999 invalid_email: invalidEmailMessage().toLowerCase(),
10001000 invalid_key: "that is not a valid public key",
10011001 invalid: "that is not valid",
10021002 name_taken: "that name is taken",
src/tui/screens/profile.ts +5 −1
@@ -8,6 +8,7 @@
88 * file written here would land on the forge's disk, not theirs.
99 */
1010
11 import { invalidEmailMessage } from "../../actions/users.ts";
1112 import { emailSavedWords, PROFILE_FALLBACK, PROFILE_REFUSALS } from "../../actions/profile_words.ts";
1213 import { askToClose, CLOSE_WORDS, closeRequestedAt, closesOn, closingSays, GRACE_DAYS, keepMyAccount, keptSays } from "../../actions/account_close.ts";
1314 import { updateProfile } from "../../actions/users.ts";
@@ -42,7 +43,10 @@ export function profileScreen(f: Session, ctx: Ctx): Screen {
4243 const save = (patch: { displayName: string } | { email: string }): string | undefined => {
4344 const r = updateProfile(f.app, f.user, patch);
4445 if (!r.ok) {
45 const words = PROFILE_REFUSALS[r.error] ?? PROFILE_FALLBACK;
46 const words =
47 r.error === "invalid_email" && "email" in patch
48 ? invalidEmailMessage(patch.email)
49 : (PROFILE_REFUSALS[r.error] ?? PROFILE_FALLBACK);
4650 ctx.toast(words, "danger");
4751 return words;
4852 }
src/web/pages/account.ts +2 −1
@@ -23,6 +23,7 @@ import {
2323 deleteToken,
2424 PASSWORD_CHANGED_WORDS,
2525 updateProfile,
26 invalidEmailMessage,
2627 } from "../../actions/users.ts";
2728 import {
2829 NOTIFY_ERRORS,
@@ -718,7 +719,7 @@ export async function accountUpdate(ctx: Ctx): Promise<Response> {
718719 commitEmail,
719720 });
720721 if (!updated.ok) {
721 const words = PROFILE_REFUSALS[updated.error];
722 const words = updated.error === "invalid_email" ? invalidEmailMessage(email) : PROFILE_REFUSALS[updated.error];
722723 const at = PROFILE_REFUSAL_FIELD[updated.error];
723724 const errors =
724725 words === undefined || at === undefined ? { form: PROFILE_FALLBACK } : { [at]: words };
src/web/pages/claim.ts +2 −2
@@ -28,7 +28,7 @@ import { USERNAME_PATTERN } from "../username_pattern.ts";
2828 import { crewNow, NEXT_STEPS } from "../../core/crew_now.ts";
2929 import { crewNowHtml } from "../crew_now.ts";
3030 import { PASSWORD_TOO_LONG, withinPasswordCap } from "../../core/hash-gate.ts";
31 import { givenEmail, MIN_SIGNUP_PASSWORD, noEmail } from "../../actions/users.ts";
31 import { givenEmail, invalidEmailMessage, MIN_SIGNUP_PASSWORD, noEmail } from "../../actions/users.ts";
3232 import type { Credential } from "../../auth/webauthn.ts";
3333 import { cookieValue, crossOrigin, type Ctx } from "../../http/context.ts";
3434 import { sendBeat } from "../../spawn/heartbeat.ts";
@@ -480,7 +480,7 @@ function problems(
480480 )
481481 errors.username = USERNAME_TAKEN;
482482 if (email !== "" && !givenEmail(email))
483 errors.email = "That does not look like an email address.";
483 errors.email = invalidEmailMessage(email);
484484 return errors;
485485 }
486486
src/web/pages/signup-passkey.ts +2 −3
@@ -7,7 +7,7 @@
77 */
88
99 import { newChallenge, verifyRegistration } from "../../auth/webauthn.ts";
10 import { givenEmail, signUpWithPasskey, signupClosed, HUMAN_CHECK_MESSAGE, SIGNUP_CLOSED_MESSAGE } from "../../actions/users.ts";
10 import { givenEmail, invalidEmailMessage, signUpWithPasskey, signupClosed, HUMAN_CHECK_MESSAGE, SIGNUP_CLOSED_MESSAGE } from "../../actions/users.ts";
1111 import { rotateSession } from "../../auth/session_rotate.ts";
1212 import { getUserByName } from "../../core/users.ts";
1313 import { isSafeName } from "../../git/guard.ts";
@@ -30,7 +30,6 @@ const WORDS: Record<string, string> = {
3030 username_taken: USERNAME_TAKEN,
3131 username_reserved: NAME_RESERVED,
3232 email_taken: EMAIL_TAKEN_MESSAGE,
33 invalid_email: "That does not look like an email address.",
3433 edge_name: EDGE_NAME_MESSAGE,
3534 human_check: HUMAN_CHECK_MESSAGE,
3635 passkey_taken: PASSKEY_TAKEN,
@@ -41,7 +40,7 @@ const WORDS: Record<string, string> = {
4140 function problem(ctx: Ctx, username: string, email: string): string | undefined {
4241 if (!isSafeName(username)) return WORDS.invalid_username;
4342 if (!pinnedTo(ctx, username, inviteOf(ctx))) return WORDS.edge_name;
44 if (email !== "" && !givenEmail(email)) return WORDS.invalid_email;
43 if (email !== "" && !givenEmail(email)) return invalidEmailMessage(email);
4544 if (getUserByName(ctx.app.db, username)) return WORDS.username_taken;
4645 return undefined;
4746 }
src/web/pages/site.ts +2 −2
@@ -25,7 +25,7 @@ import { STRANGER_MAX } from "../../http/limits.ts";
2525 import { createRepo, repositoryLimitMessage, resolveOwner } from "../../actions/repos.ts";
2626 import { REPO_DIR_IN_THE_WAY, REPO_INIT_FAILED, REPO_NAME_RULES } from "../../actions/repo_words.ts";
2727 import { NOTE_MAX, requestOf } from "../../core/requests.ts";
28 import { DECLINED_MESSAGE, REQUEST_IN_MESSAGE, STILL_WAITING_MESSAGE } from "../../actions/users.ts";
28 import { invalidEmailMessage, DECLINED_MESSAGE, REQUEST_IN_MESSAGE, STILL_WAITING_MESSAGE } from "../../actions/users.ts";
2929 import { inviteByToken } from "../../core/invites.ts";
3030 import { INVITE_SPENT, inviteExpiredLine, inviteExpiryLine, inviteRepo, joinRepo } from "../../actions/invites.ts";
3131 import { whenWords } from "../../core/when_words.ts";
@@ -837,7 +837,7 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> {
837837 email_taken: { email: EMAIL_TAKEN_MESSAGE },
838838 password_too_long: { password: PASSWORD_TOO_LONG },
839839 weak_password: { password: "Passwords need at least 12 characters." },
840 invalid_email: { email: "That does not look like an email address." },
840 invalid_email: { email: invalidEmailMessage(email) },
841841 human_check: { human: HUMAN_CHECK_MESSAGE },
842842 passkey_required: { human: PASSKEY_REQUIRED_MESSAGE },
843843 }[created.error] ?? { username: "Something went wrong." };
src/web/pages/start_claim.ts +2 −2
@@ -8,7 +8,7 @@
88 */
99 import { USERNAME_PATTERN } from "../username_pattern.ts";
1010 import { claimStart, CLAIM_WORDS, viewClaim } from "../../actions/claim.ts";
11 import { noEmail, plausibleEmail, signupClosed } from "../../actions/users.ts";
11 import { invalidEmailMessage, noEmail, plausibleEmail, signupClosed } from "../../actions/users.ts";
1212 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1313 import { rotateSession } from "../../auth/session_rotate.ts";
1414 import { createUser } from "../../core/users.ts";
@@ -92,7 +92,7 @@ async function makeAccountAndTake(ctx: Ctx): Promise<Response> {
9292 if (!mayMakeAccount(ctx)) return flashTo(ctx, `/claim/start/${encodeURIComponent(token)}`, { tone: "danger", message: "New accounts are not open here: sign in to take it." });
9393 const username = field(form, "username").trim();
9494 const given = field(form, "email").trim();
95 if (given !== "" && !plausibleEmail(given)) return startClaimPage(ctx, { email: "That does not look like an email address." }, 422);
95 if (given !== "" && !plausibleEmail(given)) return startClaimPage(ctx, { email: invalidEmailMessage(given) }, 422);
9696 const made = await createUser(ctx.app.db, {
9797 origin: "claimer",
9898 username,
test/account-profile-words.test.ts +2 −1
@@ -8,6 +8,7 @@ import { tmpdir } from "node:os";
88 import { join } from "node:path";
99 import { createApp, type App } from "../src/app.ts";
1010 import { PROFILE_REFUSALS } from "../src/actions/profile_words.ts";
11 import { invalidEmailMessage } from "../src/actions/users.ts";
1112 import { serve, type Servers } from "../src/http/server.ts";
1213 import { adminCookie } from "./helpers/admin.ts";
1314 import { quietLogs } from "./helpers/globals.ts";
@@ -47,5 +48,5 @@ test("the account page refuses in the shared words, in the field they belong to"
4748 expect(await reserved.text()).toContain(escaped(PROFILE_REFUSALS.display_name_reserved!).replace(/&amp;#39;/g, "&#39;"));
4849 const bad = await post({ displayName: "Alice", email: "nope" });
4950 expect(bad.status).toBe(422);
50 expect(await bad.text()).toContain(PROFILE_REFUSALS.invalid_email!.replace(/'/g, "&#39;"));
51 expect(await bad.text()).toContain(invalidEmailMessage("nope").replace(/'/g, "&#39;"));
5152 });
test/contract-openapi-tags.test.ts +1 −1
@@ -31,7 +31,7 @@ test("a slice keeps only its tag's operations and the rest of the document", ()
3131 expect(slice.tags.map((t) => t.name)).toEqual(["pulls"]);
3232 const n = Object.values(slice.paths).flatMap((o) => Object.values(o)).length;
3333 expect(n).toBe(ROUTES.filter((r) => tagOf(r.path) === "pulls").length);
34 expect(openapiSliceText("https://x.test", "v", "pulls", "admin").text.length).toBeLessThan(43_000);
34 expect(openapiSliceText("https://x.test", "v", "pulls", "admin").text.length).toBeLessThan(44_000);
3535 });
3636
3737 test("?tag= over HTTP: a slice, the whole, and a 400 naming the tags", async () => {
test/f2f-answers.test.ts added +59
@@ -0,0 +1,59 @@
1 /** Honest answers: a refused reserved address says why, and a merge says what `carried` means. */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { setLimit } from "../src/settings/limits.ts";
8 import { serve, type Servers } from "../src/http/server.ts";
9 import { mergedMessage } from "../src/http/api/pulls.ts";
10 import { quietLogs } from "./helpers/globals.ts";
11
12 quietLogs();
13
14 const EDGE = "edge-secret-for-f2f";
15 let dataDir = "";
16 let app: App, servers: Servers;
17
18 beforeAll(async () => {
19 dataDir = await mkdtemp(join(tmpdir(), "forge-f2f-"));
20 app = createApp({ dataDir, port: 0, url: "https://forge.example", edgeToken: EDGE });
21 servers = await serve(app);
22 setLimit(app.db, "signup.per_source", 1000, "setup");
23 });
24
25 afterAll(async () => {
26 servers?.stop();
27 app?.close();
28 await rm(dataDir, { recursive: true, force: true });
29 });
30
31 const signup = (name: string, email: string) =>
32 fetch(`${servers.url}/api/v1/users`, {
33 method: "POST",
34 headers: { "content-type": "application/json", "x-plat-user": name, "x-plat-edge-token": EDGE },
35 body: JSON.stringify({ username: name, email, password: "outsider-passphrase" }),
36 });
37
38 test(".invalid is refused with its reason; .test and .example are accepted", async () => {
39 const refused = await signup("maker", "[email protected]");
40 expect(refused.status).toBe(422);
41 const said = (await refused.json()) as { error: string; message: string };
42 expect(said.error).toBe("invalid_email");
43 expect(said.message).toContain("can never receive mail");
44 expect((await signup("maker2", "[email protected]")).status).toBe(201);
45 expect((await signup("maker3", "[email protected]")).status).toBe(201);
46 });
47
48 test("a malformed address is told apart from a reserved one", async () => {
49 const res = await signup("maker4", "not-an-address");
50 const said = (await res.json()) as { message: string };
51 expect(res.status).toBe(422);
52 expect(said.message).toContain("not an email address");
53 });
54
55 test("the merge answer says what carried means", () => {
56 expect(mergedMessage(true)).toContain("already in the base");
57 expect(mergedMessage(false)).toContain("new merge commit");
58 });
59
test/f2f-merge.test.ts added +80
@@ -0,0 +1,80 @@
1 /**
2 * The merge route sends `message` beside `carried`, for a new merge commit and for a carried one.
3 */
4 import { afterAll, beforeAll, 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 { openPull } from "../src/actions/pulls.ts";
10 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
11 import { PROFILE_REFUSALS } from "../src/actions/profile_words.ts";
12 import { invalidEmailMessage } from "../src/actions/users.ts";
13 import { createToken } from "../src/core/tokens.ts";
14 import { createUser, type User } from "../src/core/users.ts";
15 import { mergedMessage } from "../src/http/api/pulls.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18
19 quietLogs();
20
21 let dataDir = "";
22 let app: App, servers: Servers, alice: User;
23 let repo: Awaited<ReturnType<typeof createRepo>> extends { value: infer R } ? R : never;
24 let rw = "";
25
26 const pullFrom = async (branch: string, content: string) => {
27 await commitToBranch(app, alice, repo, { branch, base: "main", message: branch, files: [{ path: "code.txt", content }] });
28 const opened = await openPull(app, alice, repo, { title: branch, baseBranch: "main", headBranch: branch });
29 if (!opened.ok) throw new Error(JSON.stringify(opened.error));
30 return opened.value;
31 };
32
33 const merge = async (number: number) => {
34 const res = await fetch(`${servers.url}/api/v1/repos/alice/app/pulls/${number}/merge`, {
35 method: "POST",
36 headers: { origin: servers.url, authorization: `Bearer ${rw}`, "content-type": "application/json" },
37 body: "{}",
38 });
39 expect(res.status).toBe(200);
40 return (await res.json()) as { merged: boolean; carried: boolean; message: string };
41 };
42
43 beforeAll(async () => {
44 dataDir = await mkdtemp(join(tmpdir(), "forge-f2f-merge-"));
45 app = createApp({ dataDir, port: 0 });
46 servers = await serve(app);
47 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
48 if (!made.ok) throw new Error(made.error);
49 alice = made.value;
50 const r = await createRepo(app, alice, { name: "app", visibility: "public" });
51 if (!r.ok) throw new Error(String(r.error));
52 repo = r.value as typeof repo;
53 await commitToBranch(app, alice, repo, { branch: "main", message: "base", files: [{ path: "code.txt", content: "alpha\n" }] });
54 rw = createToken(app.db, alice.id, "rw", "rw").token;
55 }, 30_000);
56
57 afterAll(async () => {
58 await servers.stop();
59 app.close();
60 await rm(dataDir, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });
61 });
62
63 test("the merge route sends message for carried=false and carried=true", async () => {
64 const first = await pullFrom("one", "alpha\nbeta\n");
65 const twin = await pullFrom("two", "alpha\nbeta\n");
66 const landed = await merge(first.number);
67 expect(landed.carried).toBe(false);
68 expect(landed.message).toBe(mergedMessage(false));
69 const carried = await merge(twin.number);
70 expect(carried.carried).toBe(true);
71 expect(carried.message).toBe(mergedMessage(true));
72 expect(carried.message).not.toBe(landed.message);
73 });
74
75 test("one refusal of an address has one wording on every door", () => {
76 expect(invalidEmailMessage("[email protected]")).toContain("can never receive mail");
77 expect(invalidEmailMessage("nope")).toContain("not an email address");
78 expect(invalidEmailMessage()).toContain(".invalid");
79 expect(PROFILE_REFUSALS.invalid_email).toBe(invalidEmailMessage());
80 });
test/view-source.test.ts +18
@@ -910,6 +910,15 @@ describe("RepoSource: one repository, two places to read it from", () => {
910910 ),
911911 );
912912 expect(issues.items.map((i) => i.number)).toEqual([7]);
913 expect(issues).toMatchObject({ state: "all" });
914 expect(issues).not.toHaveProperty("note");
915
916 const openIssues = await read<{ state: string; note?: string }>(
917 await api(`/api/v1/user/origins/${originId}/browse/octo/widgets/issues`),
918 );
919 expect(openIssues.state).toBe("open");
920 expect(openIssues.note).toContain("Only open issues");
921 expect(openIssues.note).toContain("state=all");
913922
914923 const pulls = await read<{ items: { number: number }[] }>(
915924 await api(
@@ -917,6 +926,15 @@ describe("RepoSource: one repository, two places to read it from", () => {
917926 ),
918927 );
919928 expect(pulls.items.map((i) => i.number)).toEqual([9]);
929 expect(pulls).toMatchObject({ state: "all" });
930 expect(pulls).not.toHaveProperty("note");
931
932 // The default hides closed pulls, and the answer says so and names the filter.
933 const open = await read<{ state: string; note?: string }>(
934 await api(`/api/v1/user/origins/${originId}/browse/octo/widgets/pulls`),
935 );
936 expect(open.state).toBe("open");
937 expect(open.note).toContain("state=all");
920938
921939 const detail = await read<{
922940 number: number;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs