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

A fork's maker can withdraw an offer they sent upstream, in one confirmed receipted action #14627

Merged opened this

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

Merged

torque/forge:torque/14575-a-fork-s-maker-can-withdraw-an-offer-the → main 10 commits fork 5 threads · 5 unresolved

  • Merged. torque/14575-a-fork-s-maker-can-withdraw-an-offer-the was merged into main as fb80987.

Review

Sign in to review this change.
14 files changed +413 −34
docs/features/withdraw-offer.md added +30
@@ -0,0 +1,30 @@
1 ---
2 topic: Agents: MCP, git, or the terminal
3 row: Taking back an offer you sent upstream
4 ---
5 # Withdraw an offer
6
7 A fork's maker can take back an offer they sent to the parent (see `offer-commit-upstream.md`)
8 while nobody upstream has merged it. The pull closes as dropped, the receipt reads
9 **Withdrawn**, and the commits stay in the fork, so the same commit can be offered again.
10
11 Only the one who sent the offer, or the fork's owner, may. Anyone else meets a 404 on the page;
12 over MCP an upstream writer who can read the receipt is told `forbidden`. A merged offer is the
13 upstream's and is refused. The close and the receipt's mark are one transaction.
14
15 ## On the web
16

Non-blocking: stale after the merge with main. The card lists all the fork's sent offers (waiting, taken, declined, withdrawn); the Withdraw button appears only on waiting ones you may withdraw.

17 The fork's page lists **Sent upstream**: every offer the fork has sent, each with its state
18 (waiting, taken, declined or withdrawn). **Withdraw** shows only beside a waiting offer you may
19 withdraw; press it and confirm. You land on the receipt at `/offers/<receipt>`.
20
21 ## In the terminal
22
23 Open the palette's **Offers upstream**, move with `j`/`k` to the offer and press `w` twice: the
24 first press says what it will do, the second withdraws. Any other key cancels. The screen is
25 `src/tui/screens/offers.ts`; it calls `withdrawByReceipt`, the page's action.
26
27 ## Over MCP
28
29 `fork` with `{ "action": "withdraw", "receipt": "<id>" }` returns the receipt with
30 `state: "withdrawn"`. A second try says the offer is no longer open.
src/actions/offer_withdraw.ts added +76
@@ -0,0 +1,76 @@
1 /**
2 * A fork's offer taken back (#14575): the pull it opened upstream is closed, the receipt says
3 * "withdrawn", and the fork's commits stay. Only the offer's maker or the fork's owner may; a
4 * landed offer is the upstream's and cannot be taken back. One action for the page and the MCP,
5 * the refusals in `OFFER_WITHDRAW_WORDS`. The upstream's incoming list reads open pulls, so a
6 * closed one leaves it with no further step.
7 */
8 import type { App } from "../app.ts";
9 import { markForkOfferWithdrawn, mayWithdrawOffer, readForkOffer, type ForkOfferReceipt } from "../core/fork_offer.ts";
10 import { getIssue, setIssueState } from "../core/issues.ts";
11 import { getPull } from "../core/pulls.ts";
12 import { getRepo, type Repo } from "../core/repos.ts";
13 import type { User } from "../core/users.ts";
14 import { err, ok, type Result } from "../kernel/result.ts";
15
16 export type OfferWithdrawRefusal = "not_found" | "unauthorized" | "forbidden" | "already_landed" | "not_open";
17
18 export const OFFER_WITHDRAW_WORDS: Readonly<Record<OfferWithdrawRefusal, string>> = {
19 not_found: "No such offer of yours to withdraw.",
20 unauthorized: "Sign in to withdraw an offer.",
21 forbidden: "Only the one who sent this offer, or the fork's owner, may withdraw it.",
22 already_landed: "The upstream already took this offer; it cannot be withdrawn.",
23 not_open: "This offer is no longer open, so there is nothing to withdraw.",
24 };
25
26 /** Withdraw pull `number` of `upstream`, which must come from `fork`. */
27 export function withdrawOffer(
28 app: App,
29 actor: User | undefined,
30 fork: Repo,
31 upstream: Repo,
32 number: number,
33 ): Result<ForkOfferReceipt, OfferWithdrawRefusal> {
34 if (actor === undefined) return err("unauthorized");
35 // One transaction: the reads, the close and the receipt's mark stand or fall together, so a
36 // failure leaves the pull open and never closed-but-unmarked (which would read as declined).
37 const done = app.db.transaction((): Result<string, OfferWithdrawRefusal> => {
38 const issue = getIssue(app.db, upstream.id, number);
39 const pull = issue === undefined ? undefined : getPull(app.db, upstream.id, number);
40 if (issue === undefined || pull === undefined || pull.headRepoId !== fork.id) return err("not_found");
41 if (!mayWithdrawOffer(actor, fork, issue.authorId)) return err("not_found");
42 if (pull.mergedAt !== null) return err("already_landed");
outdated

Closing the pull here and marking the receipt on the next line are separate writes. If recordForkOffer or the update throws, the pull is closed with no 'withdrawn' mark and reads as 'declined'. Do both in one db.transaction. Re-check mergedAt inside it, so a merge that lands between the read and the close is not closed over.

43 if (issue.state !== "open") return err("not_open");
44 if (setIssueState(app.db, issue.id, "closed", "dropped") === undefined) return err("not_open");
45 return ok(markForkOfferWithdrawn(app.db, issue.id, issue.authorId));
46 })();
47 if (!done.ok) return done;
48 const receipt = done.value;
49 app.bus.append({
50 kind: "issue.closed",
51 repoId: upstream.id,
52 actorId: actor.id,
53 payload: { number, withdrawn: true },
54 });
55 const read = readForkOffer(app.db, actor, receipt);
56 return read === undefined ? err("not_found") : ok(read);
57 }
58
59 /** The same, from a receipt id (the MCP's `receipt`): unknown to the actor is `not_found`. */
60 export function withdrawByReceipt(
61 app: App,
62 actor: User | undefined,
63 receipt: string,
64 ): Result<ForkOfferReceipt, OfferWithdrawRefusal> {
65 if (actor === undefined) return err("unauthorized");
66 const got = readForkOffer(app.db, actor, receipt);
67 if (got === undefined) return err("not_found");
68 const [uo = "", un = ""] = got.upstream.split("/");
69 const [fo = "", fn = ""] = got.fork.split("/");
70 const upstream = getRepo(app.db, uo, un);
71 const fork = getRepo(app.db, fo, fn);
72 if (upstream === undefined || fork === undefined) return err("not_found");
73 const done = withdrawOffer(app, actor, fork, upstream, got.pull);
74 // Someone who may read the receipt but not withdraw it (an upstream writer) is told so.
75 return !done.ok && done.error === "not_found" ? err("forbidden") : done;
76 }
src/core/fork_offer.ts +37 −5
@@ -11,7 +11,7 @@ import { canWrite, getRepoById, type Repo } from "./repos.ts";
1111 import { listReviews } from "./reviews.ts";
1212 import { getUserById, type User } from "./users.ts";
1313
14 export type ForkOfferState = "sent" | "seen" | "taken" | "declined";
14 export type ForkOfferState = "sent" | "seen" | "taken" | "declined" | "withdrawn";
1515
1616 /** The words said once for each state, for the page, the MCP and the terminal alike. */
1717 export const FORK_OFFER_WORDS: Readonly<Record<ForkOfferState, string>> = {
@@ -19,6 +19,7 @@ export const FORK_OFFER_WORDS: Readonly<Record<ForkOfferState, string>> = {
1919 seen: "Seen. Someone who can write upstream has reviewed or commented on it.",
2020 taken: "Taken. The upstream merged it.",
2121 declined: "Declined. The upstream closed it without merging.",
22 withdrawn: "Withdrawn. The offerer took it back; the commits stay in the fork.",
2223 };
2324
2425 export interface ForkOfferReceipt {
@@ -59,8 +60,8 @@ const repoName = (r: Repo): string => `${r.ownerName}/${r.name}`;
5960 export function readForkOffer(db: Database, viewer: User | undefined, id: string): ForkOfferReceipt | undefined {
6061 if (viewer === undefined || !ID.test(id)) return undefined;
6162 const row = db
62 .query<{ issue_id: string; offerer_id: string; created_at: string }, [string]>(
63 "SELECT issue_id, offerer_id, created_at FROM fork_offer WHERE id = ?1",
63 .query<{ issue_id: string; offerer_id: string; created_at: string; withdrawn_at: string | null }, [string]>(
64 "SELECT issue_id, offerer_id, created_at, withdrawn_at FROM fork_offer WHERE id = ?1",
6465 )
6566 .get(id);
6667 if (row === null) return undefined;
@@ -68,8 +69,8 @@ export function readForkOffer(db: Database, viewer: User | undefined, id: string
6869 const upstream = issue === undefined ? undefined : getRepoById(db, issue.repoId);
6970 const pull = issue === undefined ? undefined : getPull(db, issue.repoId, issue.number);
7071 if (issue === undefined || upstream === undefined || pull === undefined) return undefined;
71 if (viewer.id !== row.offerer_id && !canWrite(db, upstream, viewer)) return undefined;
7272 const fork = getRepoById(db, pull.headRepoId);
73 if (viewer.id !== row.offerer_id && fork?.ownerId !== viewer.id && !canWrite(db, upstream, viewer)) return undefined;
7374 // Only someone who can write to the upstream speaks for it: a stranger's comment on a public
7475 // upstream is neither an answer nor a reason.
7576 const voices = new Map<string, boolean>();
@@ -86,7 +87,15 @@ export function readForkOffer(db: Database, viewer: User | undefined, id: string
8687 const said = listComments(db, issue.id, { kind: "comment" }).filter((c) => speaksUpstream(c.authorId));
8788 const answered = said.length > 0 || listReviews(db, pull.id).some((r) => speaksUpstream(r.authorId));
8889 const state: ForkOfferState =
89 pull.mergedAt !== null ? "taken" : pull.state === "closed" ? "declined" : answered ? "seen" : "sent";
90 pull.mergedAt !== null
91 ? "taken"
92 : row.withdrawn_at !== null && pull.state === "closed"
93 ? "withdrawn"
94 : pull.state === "closed"
95 ? "declined"
96 : answered
97 ? "seen"
98 : "sent";
9099 const reasonText = state === "declined" ? (said.at(-1)?.body.trim() ?? "") : "";
91100 const reason = reasonText === "" ? null : reasonText;
92101 return {
@@ -122,3 +131,26 @@ export function listForkOffers(db: Database, viewer: User, limit = 20): ForkOffe
122131 .all(viewer.id, Math.max(1, Math.min(100, Math.floor(limit))))
123132 .flatMap((r) => readForkOffer(db, viewer, r.id) ?? []);
124133 }
134
135 /** The receipt id of the offer behind pull `issueId`, if one was kept. */
136 export function forkOfferOfPull(db: Database, issueId: string): string | undefined {
137 return db.query<{ id: string }, [string]>("SELECT id FROM fork_offer WHERE issue_id = ?1").get(issueId)?.id;
138 }
139
140 /**
141 * Mark the offer behind `issueId` withdrawn now, keeping a receipt (for `offererId`) when the
142 * pull was offered by the pull form and has none. Returns the receipt id.
143 */
144 export function markForkOfferWithdrawn(db: Database, issueId: string, offererId: string): string {
145 const id = forkOfferOfPull(db, issueId) ?? recordForkOffer(db, issueId, offererId);
146 db.query("UPDATE fork_offer SET withdrawn_at = ?2 WHERE id = ?1").run(id, new Date().toISOString());
147 return id;
148 }
149
150 /**
151 * Who may withdraw an offer: the one who sent it, or the fork's owner. The page and the action
152 * share this.
153 */
154 export function mayWithdrawOffer(actor: Pick<User, "id">, fork: Pick<Repo, "ownerId">, offerAuthorId: string): boolean {
155 return actor.id === offerAuthorId || actor.id === fork.ownerId;
156 }
src/core/fork_offers.ts +28 −11
@@ -8,6 +8,7 @@
88 import type { Database } from "bun:sqlite";
99 import { forkParentFor, visibleForks, type Repo } from "./repos.ts";
1010 import type { User } from "./users.ts";
11 import { mayWithdrawOffer } from "./fork_offer.ts";
1112
1213 export const MAX_FORK_OFFERS = 20;
1314
@@ -47,20 +48,22 @@ export function forkOffers(
4748 }));
4849 }
4950
50 export type SentOfferState = "waiting" | "taken" | "declined";
51 export type SentOfferState = "waiting" | "taken" | "declined" | "withdrawn";
5152
5253 export interface SentOffer {
5354 readonly number: number;
5455 readonly title: string;
5556 readonly state: SentOfferState;
5657 readonly createdAt: string;
58 /** The viewer may withdraw it: still waiting, and theirs or their fork's (`mayWithdrawOffer`). */
59 readonly mayWithdraw: boolean;
5760 }
5861
5962 /**
6063 * The offers this fork has sent its upstream, newest first: the pulls into
6164 * the parent whose head lives here. Open is waiting, merged is taken, closed
62 * unmerged is declined. Nothing when the parent is gone or unreadable to the
63 * viewer — the pulls are the parent's to show.
65 * unmerged is declined, unless its maker took it back: withdrawn. Nothing when the parent is gone
66 * or unreadable to the viewer — the pulls are the parent's to show.
6467 */
6568 export function sentOffers(
6669 db: Database,
@@ -71,19 +74,33 @@ export function sentOffers(
7174 if (parent === undefined) return [];
7275 return db
7376 .query<
74 { number: number; title: string; created_at: string; state: string; merged_at: string | null },
77 {
78 number: number;
79 title: string;
80 created_at: string;
81 state: string;
82 merged_at: string | null;
83 author_id: string;
84 withdrawn_at: string | null;
85 },
7586 [string, string]
7687 >(
77 `SELECT issue.number, issue.title, issue.created_at, issue.state, pull.merged_at
88 `SELECT issue.number, issue.title, issue.created_at, issue.state, pull.merged_at, issue.author_id,
89 (SELECT withdrawn_at FROM fork_offer WHERE fork_offer.issue_id = issue.id) AS withdrawn_at
7890 FROM pull JOIN issue ON issue.id = pull.issue_id
7991 WHERE issue.repo_id = ?1 AND pull.head_repo_id = ?2
8092 ORDER BY issue.created_at DESC, issue.number DESC LIMIT ${MAX_FORK_OFFERS}`,
8193 )
8294 .all(parent.id, fork.id)
83 .map((r) => ({
84 number: r.number,
85 title: r.title,
86 createdAt: r.created_at,
87 state: r.merged_at !== null ? "taken" : r.state === "open" ? "waiting" : "declined",
88 }));
95 .map((r) => {
96 const state: SentOfferState =
97 r.merged_at !== null ? "taken" : r.withdrawn_at !== null ? "withdrawn" : r.state === "open" ? "waiting" : "declined";
98 return {
99 number: r.number,
100 title: r.title,
101 createdAt: r.created_at,
102 state,
103 mayWithdraw: state === "waiting" && viewer !== undefined && mayWithdrawOffer(viewer, fork, r.author_id),
104 };
105 });
89106 }
src/core/migration-pins/20261120120000-fork-offer-withdrawn.pin added +1
@@ -0,0 +1,1 @@
1 6493d38ab8851f17f11811c518f0973f24dd264123dd367aaead59b3ac57f08a
src/core/migrations/20261120120000-fork-offer-withdrawn.ts added +5
@@ -0,0 +1,5 @@
1 // A fork's maker can take an offer back (#14575): when it was withdrawn, so the receipt says
2 // "withdrawn" and not "declined". Null until then; the pull stays closed, its commits stay.
3 export default `
4 ALTER TABLE fork_offer ADD COLUMN withdrawn_at TEXT;
5 `;
src/http/mcp/tools/fork.ts +7 −2
@@ -4,6 +4,7 @@ import { GUEST_REFUSALS, isGuestRefusal } from "../../../core/contribute.ts";
44 import { NOT_A_MEMBER } from "../../../core/roles.ts";
55 import { storageLimitMessage } from "../../../core/storage.ts";
66 import { offerCommit, OFFER_COMMIT_WORDS } from "../../../actions/offer_commit.ts";
7 import { OFFER_WITHDRAW_WORDS, withdrawByReceipt } from "../../../actions/offer_withdraw.ts";
78 import { readForkOffer } from "../../../core/fork_offer.ts";
89 import { isSafeOid } from "../../../git/guard.ts";
910 import { resolveOid } from "../../../git/merge.ts";
@@ -14,14 +15,14 @@ import { good, bad, type Tool, str, REPO_ARG, repoArg, isAnswer } from "../share
1415 /** The MCP door to `POST /api/v1/repos/:owner/:name/forks`: the same action, the same refusals. */
1516 export const tool: Tool = {
1617 name: "fork",
17 doc: "`{ repo, name? }`: fork a repository you can read into your account, as POST `/api/v1/repos/:owner/:name/forks` does. For a guest this is Help build this: a public fork that runs nothing, to change with `write_file` or git and send back with `open_pull`; a refusal says what to do instead. `{ repo, action: \"offer\", commit }` sends a full commit id of your fork to its parent as a pull and returns its receipt `{ receipt, state: sent|seen|taken|declined, says, reason, upstream, url }`; `{ action: \"receipt\", receipt }` reads it again (offerer and upstream writers only; the page is `/offers/<receipt>`)",
18 doc: "`{ repo, name? }`: fork a repository you can read into your account, as POST `/api/v1/repos/:owner/:name/forks` does. For a guest this is Help build this: a public fork that runs nothing, to change with `write_file` or git and send back with `open_pull`; a refusal says what to do instead. `{ repo, action: \"offer\", commit }` sends a full commit id of your fork to its parent as a pull and returns its receipt `{ receipt, state: sent|seen|taken|declined|withdrawn, says, reason, upstream, url }`; `{ action: \"receipt\", receipt }` reads it again, `{ action: \"withdraw\", receipt }` takes a pending offer back (commits stay; not once taken; offerer or fork owner only). Page: `/offers/<receipt>`",
outdated

The doc string still lists state: sent|seen|taken|declined. Add withdrawn. The sentence placing withdraw before '(offerer and upstream writers only…)' is also misleading: only the offerer or the fork's owner may withdraw, and upstream writers are told forbidden.

1819 description: "Fork a repository into your account; `action` offer sends a fork's commit upstream, receipt reads it.",
1920 inputSchema: {
2021 type: "object",
2122 properties: {
2223 repo: REPO_ARG,
2324 name: { type: "string" },
24 action: { type: "string", enum: ["offer", "receipt"] },
25 action: { type: "string", enum: ["offer", "receipt", "withdraw"] },
2526 commit: { type: "string", maxLength: 40 },
2627 receipt: { type: "string", maxLength: 32 },
2728 },
@@ -32,6 +33,10 @@ export const tool: Tool = {
3233 const got = readForkOffer(ctx.app.db, user, str(args["receipt"]));
3334 return got === undefined ? bad("not_found", "no such receipt for you") : good({ ...got, says: got.words });
3435 }
36 if (args["action"] === "withdraw") {
37 const done = withdrawByReceipt(ctx.app, user, str(args["receipt"]));
38 return done.ok ? good({ ...done.value, says: done.value.words }) : bad(done.error, OFFER_WITHDRAW_WORDS[done.error]);
39 }
3540 if (args["action"] === "offer") {
3641 const fork = repoArg(ctx, user, args);
3742 if (isAnswer(fork)) return fork;
src/http/server.ts +2 −1
@@ -250,7 +250,7 @@ import {
250250 branchDelete,
251251 branchesPage,
252252 } from "../web/pages/branches.ts";
253 import { offerCommitPost } from "../web/pages/offer-upstream.ts";
253 import { offerCommitPost, offerWithdrawPost } from "../web/pages/offer-upstream.ts";
254254 import { offerReceiptPage } from "../web/pages/offer-receipt.ts";
255255 import { iterationsPage, noteSubmit } from "../web/pages/iterations.ts";
256256 import { mainSubmit, registerSubmit, retireSubmit, valuesSubmit, variantBoardPage } from "../web/pages/app_variants.ts";
@@ -1715,6 +1715,7 @@ export function buildRouter(): Router<Handler> {
17151715 router.add("GET", "/:owner/:name/waves/:version", wavePage);
17161716 router.add("POST", "/:owner/:name/branches", branchCreate);
17171717 router.add("POST", "/:owner/:name/commit/:oid/offer", offerCommitPost);
1718 router.add("POST", "/:owner/:name/offers/:number/withdraw", offerWithdrawPost);
17181719 router.add("POST", "/:owner/:name/branches/:branch/delete", branchDelete);
17191720
17201721 // Editing a file: the page, the one write, and the delete's own confirm.
src/tui/screens/offers.ts +49 −8
@@ -2,9 +2,11 @@
22 * Offers upstream, from the palette: the receipts of the offers the signed-in person made from
33 * their forks (#14156), read through `listForkOffers`/`readForkOffer`, so the gate (the offerer
44 * or an upstream writer) and the words (`FORK_OFFER_WORDS`) are the page's at `/offers/<id>`.
5 * Read-only.
5 * `w` withdraws the offer under the cursor, pressed twice to confirm, through `withdrawByReceipt`:
6 * the page's action, gate and words (`OFFER_WITHDRAW_WORDS`).
67 */
78
9 import { OFFER_WITHDRAW_WORDS, withdrawByReceipt } from "../../actions/offer_withdraw.ts";
810 import { offerDay, listForkOffers, type ForkOfferReceipt } from "../../core/fork_offer.ts";
911 import type { Ctx, Screen } from "../app/app.ts";
1012 import { binding } from "../app/keys.ts";
@@ -27,20 +29,59 @@ export function offerLines(r: ForkOfferReceipt): string[] {
2729 ];
2830 }
2931
30 export function offersScreen(ctx: Ctx, receipts: readonly ForkOfferReceipt[]): Screen {
32 /** Only a sent or seen offer can be taken back; the rest are settled. */
33 const pending = (r: ForkOfferReceipt | undefined): r is ForkOfferReceipt => r?.state === "sent" || r?.state === "seen";
34
35 export function offersScreen(ctx: Ctx, initial: readonly ForkOfferReceipt[], session?: Session): Screen {
3136 const scroll = new Scroll();
32 const lines = receipts.length === 0 ? ["You have offered nothing upstream."] : receipts.flatMap(offerLines);
37 let receipts = initial;
38 let at = 0;
39 let armed = false;
40 const lines = (): string[] => (receipts.length === 0 ? ["You have offered nothing upstream."] : receipts.flatMap(offerLines));
41 const start = (i: number): number => receipts.slice(0, i).reduce((n, r) => n + offerLines(r).length, 0);
42 const withdraw = (): void => {
43 const r = receipts[at];
44 if (session === undefined || !pending(r)) {
45 ctx.toast("Only an offer still waiting can be withdrawn.", "danger");
46 return;
47 }
48 if (!armed) {
49 armed = true;
50 ctx.toast(`Press w again to withdraw ${r.upstream}#${String(r.pull)}.`);
51 return;
52 }
53 armed = false;
54 const done = withdrawByReceipt(session.app, session.user, r.receipt);
55 ctx.toast(done.ok ? "Offer withdrawn. Its commits stay in your fork." : OFFER_WITHDRAW_WORDS[done.error], done.ok ? undefined : "danger");
56 if (done.ok && session.user !== undefined) receipts = listForkOffers(session.app.db, session.user);
57 ctx.invalidate();
58 };
3359 return {
3460 title: "Offers upstream",
35 keys: [binding(["j", "k"], "scroll"), binding(["esc", "q"], "back")],
61 keys: [binding(["j", "k"], "move"), binding(["w"], "withdraw (twice to confirm)"), binding(["esc", "q"], "back")],
3662 render(area, s) {
3763 const c = ctx.theme.c;
38 const spans = lines.map((text) => [{ text, style: style(text.startsWith(" ") || receipts.length === 0 ? c.mutedFg : c.fg, c.bg) }]);
64 const from = start(at);
65 const n = receipts.length === 0 ? 0 : offerLines(receipts[at]!).length;
66 const text = lines();
67 const spans = text.map((t, i) => [
68 { text: t, style: style(t.startsWith(" ") || receipts.length === 0 ? c.mutedFg : c.fg, i >= from && i < from + n ? c.muted : c.bg) },
69 ]);
3970 drawLines(s, area, c, scroll, spans);
40 hitScroll(ctx, area, scroll, lines.length);
71 hitScroll(ctx, area, scroll, text.length);
4172 },
4273 key(e) {
43 if (scroll.key(e, lines.length)) return true;
74 if (e.key === "w" && !e.ctrl && !e.alt) {
75 withdraw();
76 return true;
77 }
78 armed = false;
79 if (e.key === "j" || e.key === "k" || e.key === "down" || e.key === "up") {
80 at = Math.max(0, Math.min(receipts.length - 1, at + (e.key === "j" || e.key === "down" ? 1 : -1)));
81 scroll.to(start(at), lines().length);
82 return true;
83 }
84 if (scroll.key(e, lines().length)) return true;
4485 if (e.key === "esc" || e.key === "q") {
4586 ctx.pop();
4687 return true;
@@ -59,6 +100,6 @@ export const entry: PaletteEntry = {
59100 offered: mayRead,
60101 run: (session, ctx) => {
61102 if (session.user === undefined) return;
62 ctx.push(offersScreen(ctx, listForkOffers(session.app.db, session.user)));
103 ctx.push(offersScreen(ctx, listForkOffers(session.app.db, session.user), session));
63104 },
64105 };
src/web/pages/fork-offers.ts +7 −2
@@ -5,7 +5,7 @@ import type { ForkOffer, SentOffer } from "../../core/fork_offers.ts";
55 import type { Repo } from "../../core/repos.ts";
66 import { repoBase } from "../chrome.ts";
77 import { html, type Html } from "../html.ts";
8 import { time } from "../ui.ts";
8 import { confirmAction, time } from "../ui.ts";
99
1010 export function forkOffersCard(repo: Pick<Repo, "ownerName" | "name">, offers: readonly ForkOffer[]): Html | null {
1111 if (offers.length === 0) return null;
@@ -21,8 +21,12 @@ export function forkOffersCard(repo: Pick<Repo, "ownerName" | "name">, offers: r
2121 </section>`;
2222 }
2323
24 /** A fork's page: the offers it has sent upstream and where each stands. */
24 /**
25 * A fork's page: the offers it has sent upstream and where each stands, with a Withdraw button on
26 * the waiting ones the viewer may take back (`offerWithdrawPost`).
27 */
2528 export function sentOffersCard(
29 fork: Pick<Repo, "ownerName" | "name">,
2630 parent: Pick<Repo, "ownerName" | "name">,
2731 offers: readonly SentOffer[],
2832 ): Html | null {
@@ -34,6 +38,7 @@ export function sentOffersCard(
3438 <a class="row" href="${repoBase(parent)}/pulls/${o.number}"
3539 ><span class="row-main"><span class="row-title">${o.title}</span>
3640 <span class="row-meta"><span>${o.state}</span> <span>${time(o.createdAt, { text: agoWords(o.createdAt) })}</span></span></span></a>
41 ${o.mayWithdraw ? confirmAction({ action: `${repoBase(fork)}/offers/${o.number}/withdraw`, verb: "Withdraw", size: "sm", label: `Withdraw offer #${o.number}` }) : null}
3742 </li>`,
3843 )}</ul>
3944 </section>`;
src/web/pages/offer-upstream.ts +21 −1
@@ -7,8 +7,9 @@
77 */
88
99 import { OFFER_COMMIT_WORDS, offerCommit } from "../../actions/offer_commit.ts";
10 import { OFFER_WITHDRAW_WORDS, withdrawOffer } from "../../actions/offer_withdraw.ts";
1011 import type { UpstreamOffer } from "../../actions/offer_upstream.ts";
11 import { canWrite, type Repo } from "../../core/repos.ts";
12 import { canWrite, getRepoById, type Repo } from "../../core/repos.ts";
1213 import { isSafeOid } from "../../git/guard.ts";
1314 import { commitLog } from "../../git/read.ts";
1415 import { repoDir } from "../../git/repos.ts";
@@ -78,3 +79,22 @@ export async function offerCommitPost(ctx: Ctx): Promise<Response> {
7879 message: `Offered upstream as #${offered.value.pull.number}.`,
7980 });
8081 }
82
83 // POST /:owner/:name/offers/:number/withdraw — `:number` is the pull upstream; confirmed first at
84 // /-/confirm. Anyone but the maker and the fork's owner meets the page of a pull never made.
85 export async function offerWithdrawPost(ctx: Ctx): Promise<Response> {
86 const fork = loadRepo(ctx);
87 if (!fork) return notFoundPage(ctx);
88 if (!ctx.auth.user) return signInFirst(ctx);
89 const form = await readForm(ctx, "rw");
90 if (form instanceof Response) return form;
91 const number = Number(ctx.params.number);
92 const parent = fork.forkParentId === null ? undefined : getRepoById(ctx.app.db, fork.forkParentId);
93 if (parent === undefined || !Number.isSafeInteger(number)) return notFoundPage(ctx);
94 const done = withdrawOffer(ctx.app, ctx.auth.user, fork, parent, number);
95 if (!done.ok) {
96 if (done.error === "not_found") return notFoundPage(ctx);
97 return flashTo(ctx, repoBase(fork), { tone: "danger", message: OFFER_WITHDRAW_WORDS[done.error] });
98 }
99 return flashTo(ctx, `/offers/${done.value.receipt}`, { message: "Offer withdrawn. Its commits stay in this fork." });
100 }
src/web/pages/repo.ts +1 −1
@@ -1571,7 +1571,7 @@ async function codeHome(ctx: Ctx, repo: Repo): Promise<Response> {
15711571 })}${credit}${standing}${archivedLine(ctx, repo)}${walletLine(ctx, repo)}${reportLine(ctx, repo)}${movedLine(ctx, repo)}${noApp}${gets}
15721572 ${offerUpstream(repo, parent, offer)}
15731573 ${forkOffersCard(repo, forkOffers(ctx.app.db, repo, ctx.auth.user))}
1574 ${parent === undefined ? "" : sentOffersCard(parent, sentOffers(ctx.app.db, repo, ctx.auth.user))}
1574 ${parent === undefined ? "" : sentOffersCard(repo, parent, sentOffers(ctx.app.db, repo, ctx.auth.user))}
15751575 ${latest === null
15761576 ? ""
15771577 : html`<p class="muted latest-wave">Latest:
outdated

ctx.auth.user! non-null assertions, plus access policy inlined in page markup. Move the 'maker or fork owner' rule into core (one function, also used by withdrawOffer) so the card and the action cannot disagree.

src/web/pages/search.ts +10
@@ -606,6 +606,16 @@ const DESTRUCTIVE: {
606606 pattern: RegExp;
607607 describe: (m: RegExpMatchArray, ctx: Ctx) => Destructive;
608608 }[] = [
609 {
610 pattern: /^\/([^/]+)\/([^/]+)\/offers\/(\d+)\/withdraw$/,
611 describe: (m) => ({
612 verb: "Withdraw",
613 title: `Withdraw offer #${m[3]} from ${m[1]}/${m[2]}?`,
614 detail:
615 "The offer leaves the upstream's incoming list and shows as withdrawn here. The commits stay in this fork, and you can offer them again.",
616 phrase: "",
617 }),
618 },
609619 {
610620 pattern: /^\/([^/]+)\/([^/]+)\/archive$/,
611621 describe: (m) => ({
test/fork-offer-receipt.test.ts +139 −3
@@ -7,10 +7,12 @@ import { afterAll, beforeAll, expect, test } from "bun:test";
77 import { mkdtemp, rm } from "node:fs/promises";
88 import { tmpdir } from "node:os";
99 import { join } from "node:path";
10 import { withdrawOffer, withdrawByReceipt } from "../src/actions/offer_withdraw.ts";
1011 import { offerCommit } from "../src/actions/offer_commit.ts";
1112 import { commitToBranch, createRepo, forkRepo } from "../src/actions/repos.ts";
1213 import { setRole } from "../src/actions/roles.ts";
1314 import { createApp, type App } from "../src/app.ts";
15 import { sentOffers } from "../src/core/fork_offers.ts";
1416 import { FORK_OFFER_WORDS, listForkOffers, offerDay, readForkOffer, type ForkOfferState } from "../src/core/fork_offer.ts";
1517 import { addComment, setIssueState } from "../src/core/issues.ts";
1618 import { getRepo, type Repo } from "../src/core/repos.ts";
@@ -19,9 +21,12 @@ import { createToken } from "../src/core/tokens.ts";
1921 import { createUser, type User } from "../src/core/users.ts";
2022 import { serve, type Servers } from "../src/http/server.ts";
2123 import type { Ctx } from "../src/tui/app/app.ts";
22 import { entry as offersEntry, offerLines } from "../src/tui/screens/offers.ts";
24 import type { KeyEvent } from "../src/tui/term/input.ts";
25 import { entry as offersEntry, offerLines, offersScreen } from "../src/tui/screens/offers.ts";
2326 import type { Session } from "../src/tui/session.ts";
2427 import { theme } from "../src/tui/ui/theme.ts";
28 import { commitLog } from "../src/git/read.ts";
29 import { repoDir } from "../src/git/repos.ts";
2530 import { quietLogs } from "./helpers/globals.ts";
2631
2732 quietLogs();
@@ -70,7 +75,7 @@ afterAll(async () => {
7075 });
7176
7277 test("a receipt exists for each state, in its own words", async () => {
73 const seen: Record<ForkOfferState, string> = { sent: "", seen: "", taken: "", declined: "" };
78 const seen: Record<ForkOfferState, string> = { sent: "", seen: "", taken: "", declined: "", withdrawn: "" };
7479
7580 const sent = await offered();
7681 expect(read(sent.receipt).state).toBe("sent");
@@ -100,8 +105,13 @@ test("a receipt exists for each state, in its own words", async () => {
100105 expect(d.reason).toBeNull();
101106 seen.declined = d.words;
102107
108 const withdrawn = await offered();
109 expect(withdrawOffer(app, users[2]!, forkOf(), getRepo(app.db, "olive", "yard")!, withdrawn.pull.number).ok).toBe(true);
110 expect(read(withdrawn.receipt).state).toBe("withdrawn");
111 seen.withdrawn = read(withdrawn.receipt).words;
112
103113 expect(seen).toEqual(FORK_OFFER_WORDS);
104 expect(new Set(Object.values(seen)).size).toBe(4);
114 expect(new Set(Object.values(seen)).size).toBe(5);
105115 });
106116
107117 test("a declined offer shows the reason when one was given", async () => {
@@ -217,3 +227,129 @@ test("the terminal's Offers upstream lists the offerer's receipts in the page's
217227 offersEntry.run(session(users[2]!), ctx);
218228 expect(pushed.map((s) => s.title)).toEqual(["Offers upstream"]);
219229 });
230
231 const post = async (who: string, path: string) =>
232 fetch(`${servers.url}${path}`, { method: "POST", headers: { cookie: await signIn(who), origin: servers.url }, redirect: "manual" });
233
234 test("the maker withdraws a pending offer from the fork's page: confirmed, receipted, gone upstream, commits stay", async () => {
235 const o = await offered();
236 const cookie = await signIn("ravi");
237 const home = await (await fetch(`${servers.url}/ravi/yard`, { headers: { cookie } })).text();
238 expect(home).toContain("Sent upstream");
239 expect(home).toContain(`/-/confirm?to=%2Fravi%2Fyard%2Foffers%2F${o.pull.number}%2Fwithdraw`);
240 const confirm = await (await fetch(`${servers.url}/-/confirm?to=${encodeURIComponent(`/ravi/yard/offers/${o.pull.number}/withdraw`)}`, { headers: { cookie } })).text();
241 expect(confirm).toContain("Withdraw offer");
242 const upstreamBefore = await (await fetch(`${servers.url}/olive/yard`)).text();
243 expect(upstreamBefore).toContain(`/olive/yard/pulls/${o.pull.number}`);
244
245 const res = await post("ravi", `/ravi/yard/offers/${o.pull.number}/withdraw`);
246 expect(res.status).toBe(303);
247 expect(res.headers.get("location")).toBe(`/offers/${o.receipt}`);
248 expect(read(o.receipt).state).toBe("withdrawn");
249 const receipt = await (await fetch(`${servers.url}/offers/${o.receipt}`, { headers: { cookie } })).text();
250 expect(receipt).toContain("Withdrawn.");
251 const upstreamAfter = await (await fetch(`${servers.url}/olive/yard`)).text();
252 expect(upstreamAfter).not.toContain(`/olive/yard/pulls/${o.pull.number}"`);
253 const homeAfter = await (await fetch(`${servers.url}/ravi/yard`, { headers: { cookie } })).text();
254 expect(homeAfter).toContain("withdrawn");
255 expect(homeAfter).not.toContain(`offers%2F${o.pull.number}%2Fwithdraw`);
256 const branches = await commitLog(repoDir(app.reposRoot, "ravi", "yard"), o.pull.headBranch, { limit: 1 });
257 expect(branches.ok && branches.value.length).toBe(1);
258 });
259
260 test("a stranger is refused as the page of a pull never made; an upstream writer is told no", async () => {
261 const o = await offered();
262 const path = `/ravi/yard/offers/${o.pull.number}/withdraw`;
263 expect((await post("zed", path)).status).toBe(404);
264 expect(read(o.receipt).state).toBe("sent");
265 const anon = await fetch(`${servers.url}${path}`, { method: "POST", headers: { origin: servers.url }, redirect: "manual" });
266 expect(anon.headers.get("location") ?? "").not.toContain("/offers/");
267 expect(read(o.receipt).state).toBe("sent");
268 const cross = await fetch(`${servers.url}${path}`, { method: "POST", headers: { cookie: await signIn("ravi"), origin: "https://evil.example" }, redirect: "manual" });
269 expect(cross.status).toBe(403);
270 expect(read(o.receipt).state).toBe("sent");
271 const viaMcp = withdrawByReceipt(app, users[1]!, o.receipt);
272 expect(viaMcp.ok).toBe(false);
273 expect(!viaMcp.ok && viaMcp.error).toBe("forbidden");
274 expect(read(o.receipt).state).toBe("sent");
275 });
276
277 test("an offer the upstream already took cannot be withdrawn", async () => {
278 const o = await offered();
279 app.db.query("UPDATE pull SET merged_at = ?2 WHERE issue_id = ?1").run(o.pull.id, new Date().toISOString());
280 setIssueState(app.db, o.pull.id, "closed");
281 const res = await post("ravi", `/ravi/yard/offers/${o.pull.number}/withdraw`);
282 expect(res.status).toBe(303);
283 expect(res.headers.get("location")).toBe("/ravi/yard");
284 expect(read(o.receipt).state).toBe("taken");
285 const again = withdrawByReceipt(app, users[2]!, o.receipt);
286 expect(!again.ok && again.error).toBe("already_landed");
287 });
288
289 test("the MCP fork tool withdraws with action withdraw, and a second try says it is closed", async () => {
290 const o = await offered();
291 const token = createToken(app.db, users[2]!.id, "t", "rw");
292 const call = async (args: unknown, bearer?: string) => {
293 const r = await fetch(`${servers.url}/mcp`, {
294 method: "POST",
295 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${bearer ?? (await token).token}`, "x-forwarded-for": `10.9.0.${n++}` },
296 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "fork", arguments: args } }),
297 });
298 return (await r.json()) as any;
299 };
300 const upstreamWriter = createToken(app.db, users[1]!.id, "u", "rw").token;
301 const stranger = createToken(app.db, users[3]!.id, "s", "rw").token;
302 const writer = await call({ action: "withdraw", receipt: o.receipt }, upstreamWriter);
303 expect(writer.result.isError).toBe(true);
304 expect(writer.result.content[0].text).toContain("forbidden");
305 const nobody = await call({ action: "withdraw", receipt: o.receipt }, stranger);
306 expect(nobody.result.isError).toBe(true);
307 expect(read(o.receipt).state).toBe("sent");
308 const first = await call({ action: "withdraw", receipt: o.receipt });
309 expect(first.result.isError).toBeUndefined();
310 expect(JSON.parse(first.result.content[0].text).state).toBe("withdrawn");
311 expect(read(o.receipt).state).toBe("withdrawn");
312 const second = await call({ action: "withdraw", receipt: o.receipt });
313 expect(second.result.isError).toBe(true);
314 expect(second.result.content[0].text).toContain("not_open");
315 });
316
317 test("the terminal withdraws the offer under the cursor on the second w, with the action's gate and words", async () => {
318 const o = await offered();
319 const toasts: string[] = [];
320 const ctx = { theme: theme("dark"), toast: (t: string) => void toasts.push(t), invalidate: () => {}, pop: () => {} } as unknown as Ctx;
321 const session = (user: User) => ({ user, app }) as unknown as Session;
322 const key = (k: string): KeyEvent => ({ type: "key", key: k, ctrl: false, alt: false, shift: false });
323 const screen = offersScreen(ctx, listForkOffers(app.db, users[2]!), session(users[2]!));
324 screen.key(key("w"));
325 expect(read(o.receipt).state).toBe("sent"); // armed only
326 expect(toasts.at(-1)).toContain(`olive/yard#${o.pull.number}`);
327 screen.key(key("j")); // any other key disarms
328 screen.key(key("k"));
329 screen.key(key("w"));
330 expect(read(o.receipt).state).toBe("sent");
331 screen.key(key("w"));
332 expect(read(o.receipt).state).toBe("withdrawn");
333 expect(toasts.at(-1)).toBe("Offer withdrawn. Its commits stay in your fork.");
334 // a stranger's screen over the same receipt is refused in the action's words
335 const strange = offersScreen(ctx, [read(o.receipt)], session(users[3]!));
336 strange.key(key("w"));
337 expect(toasts.at(-1)).toBe("Only an offer still waiting can be withdrawn.");
338 expect(withdrawByReceipt(app, users[3]!, o.receipt).ok).toBe(false);
339 });
340
341 test("the list says who may withdraw, and a failed mark closes nothing", async () => {
342 const forkRow = forkOf();
343 const mine = await offered();
344 const rowOf = (u: User) => sentOffers(app.db, forkRow, u).find((x) => x.number === mine.pull.number)!;
345 expect(rowOf(users[2]!)).toMatchObject({ state: "waiting", mayWithdraw: true });
346 expect(rowOf(users[1]!).mayWithdraw).toBe(false);
347 // atomic: a throwing mark rolls the close back
348 app.db.exec("CREATE TRIGGER boom BEFORE UPDATE OF withdrawn_at ON fork_offer BEGIN SELECT RAISE(ABORT, 'boom'); END");
349 try {
350 expect(() => withdrawOffer(app, users[2]!, forkRow, getRepo(app.db, "olive", "yard")!, mine.pull.number)).toThrow();
351 } finally {
352 app.db.exec("DROP TRIGGER boom");
353 }
354 expect(read(mine.receipt).state).toBe("sent");
355 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs