Public: anyone can read this; the crew can change it.
Talk proposes the person's copy upstream: a pull request at the origin, its branch pushed there or to their fork there #16403
Check · Review · Land · Live done — Landed and live in production.
talk/origins-propose → main 0 commits
19 files
changed +585
−19
docs/features/propose-upstream.md added +42
| @@ -0,0 +1,42 @@ | ||
| 1 | --- | |
| 2 | topic: Tell the crew | |
| 3 | row: Propose your copy's work upstream, where the repository is kept | |
| 4 | --- | |
| 5 | ||
| 6 | # Propose upstream | |
| 7 | ||
| 8 | When the crew has worked on **your copy** of a repository you brought in | |
| 9 | (`bring`, [](bring.md)), the work goes back to | |
| 10 | where the repository is kept as a pull request there. | |
| 11 | ||
| 12 | **What you say.** In Talk: "open a PR upstream", or "propose hello to GitHub". | |
| 13 | Talk first plans and tells you, in one sentence, what will happen: | |
| 14 | ||
| 15 | - _Open a pull request on octo/widgets from your copy's hello: the branch is | |
| 16 | pushed to octo/widgets on GitHub as hello._ Your account there may push to the | |
| 17 | repository, so the branch goes up into it. | |
| 18 | - _… the branch is pushed to your fork you/widgets on GitHub._ Your account may | |
| 19 | only read it, so the branch goes to your own fork there (made if you have | |
| 20 | none) and the pull request comes from it. | |
| 21 | ||
| 22 | Your copy's default branch never goes up under the origin's default branch's | |
| 23 | name: it goes up as `you/main`, so a proposal never moves the origin's `main`. | |
| 24 | ||
| 25 | **The title.** Talk asks for one, or takes the one you gave: one line, at most | |
| 26 | 256 characters. Then Talk shows the Do it and Not now buttons with the sentence | |
| 27 | above; nothing is pushed before your yes. If what the origin says has changed | |
| 28 | since the plan (you may push now, or no longer), the yes is refused and Talk | |
| 29 | plans again. | |
| 30 | ||
| 31 | **What comes back.** The pull request's address at the origin. Its checks and | |
| 32 | reviews come back to the mirror as the origin's sync reads them. | |
| 33 | ||
| 34 | **In the terminal.** The palette's **Propose upstream** asks for your copy (and | |
| 35 | a branch after a space), shows the same sentence with Do it and Not now, then | |
| 36 | asks for the title and shows the address (`src/tui/screens/proposeupstream.ts`). | |
| 37 | ||
| 38 | **Through MCP.** `propose_upstream { repo, branch? }` plans; the same call with | |
| 39 | the answer's `plan` and a `title` opens it, held behind a confirm for Talk's | |
| 40 | agent. The crew never proposes upstream. Code: `planUpstream` and | |
| 41 | `proposeUpstream` in `src/actions/bring.ts`, `openPull` in | |
| 42 | `src/actions/pulls.ts`. Test: `test/talk-bring.test.ts`. |
src/actions/bring.ts +115 −3
| @@ -16,7 +16,11 @@ import type { App } from "../app.ts"; | ||
| 16 | 16 | import { getAppByRepo, slugFor, getAppBySlug, SLUG_MAX, type AppRecord } from "../core/apps.ts"; |
| 17 | 17 | import { listAppEnvNames } from "../core/app_env.ts"; |
| 18 | 18 | import { getOriginFor, listOrigins, mirrorOf } from "../core/origins.ts"; |
| 19 | import { canRead, getRepoById, listForks, type Repo } from "../core/repos.ts"; | |
| 19 | import { canRead, getRepo, getRepoById, listForks, type Repo } from "../core/repos.ts"; | |
| 20 | import { existingFork } from "../origins/fork-route.ts"; | |
| 21 | import { upstreamWords } from "../origins/words.ts"; | |
| 22 | import { writeThroughFor } from "../origins/write-through.ts"; | |
| 23 | import { isSafeRef } from "../git/guard.ts"; | |
| 20 | 24 | import { isActive, type User } from "../core/users.ts"; |
| 21 | 25 | import { readerFor } from "../git/read.ts"; |
| 22 | 26 | import { repoDir } from "../git/repos.ts"; |
| @@ -28,6 +32,7 @@ import { needsOf, originOnHost, parseBringLink } from "../origins/bring.ts"; | ||
| 28 | 32 | import { requireVerified } from "./verify.ts"; |
| 29 | 33 | import { appLimitWords } from "./app_limit.ts"; |
| 30 | 34 | import { enableApp, setAppEnvVar } from "./apps.ts"; |
| 35 | import { openPull, proposalRoute } from "./pulls.ts"; | |
| 31 | 36 | import { forkRepo, updateRepoSettings } from "./repos.ts"; |
| 32 | 37 | import { seatEmptyCrew } from "./seat_crew.ts"; |
| 33 | 38 | import { during } from "../perf/jobs.ts"; |
| @@ -175,6 +180,12 @@ export async function setBroughtEnv( | ||
| 175 | 180 | // branches are the origin's, so no crew run writes there). Both private, whatever the origin's |
| 176 | 181 | // visibility. The person is shown one thing: the origin's name, "your copy". |
| 177 | 182 | |
| 183 | /** Where an origin is, as a person says it: `GitHub`, or its host. */ | |
| 184 | const originWords = (origin: Origin): string => { | |
| 185 | const host = URL.parse(origin.webUrl)?.host ?? origin.webUrl; | |
| 186 | return host === "github.com" ? "GitHub" : host; | |
| 187 | }; | |
| 188 | ||
| 178 | 189 | /** The name a work copy takes beside its mirror. */ |
| 179 | 190 | export const workName = (mirror: Repo): string => `${mirror.name}-work`; |
| 180 | 191 | |
| @@ -267,8 +278,7 @@ export async function bringToWork( | ||
| 267 | 278 | const target = bringTarget(app, actor, input.repo, input.origin); |
| 268 | 279 | if (!target.ok) return target; |
| 269 | 280 | const { origin, fullName } = target.value; |
| 270 | const host = URL.parse(origin.webUrl)?.host ?? origin.webUrl; | |
| 271 | const from = host === "github.com" ? "GitHub" : host; | |
| 281 | const from = originWords(origin); | |
| 272 | 282 | const here = mirrorOf(app.db, origin.id, fullName); |
| 273 | 283 | let mirror = here === undefined ? undefined : getRepoById(app.db, here); |
| 274 | 284 | if (mirror !== undefined && !canRead(app.db, mirror, actor)) mirror = undefined; |
| @@ -318,3 +328,105 @@ export function broughtWords(b: BroughtIn): string { | ||
| 318 | 328 | if (b.reused.mirror && b.reused.copy) return `${b.name} was already here, with your copy; nothing new was made. Ask for a change and the crew works on your copy.${madePrivate}${copyPublic}`; |
| 319 | 329 | return `${b.name} from ${b.from} is here as your copy, private, with the crew on it${b.reused.mirror ? " (it was already mirrored)" : ""}. Ask for a change and the crew works there; ${b.from} is unchanged until you propose it upstream.${madePrivate}`; |
| 320 | 330 | } |
| 331 | ||
| 332 | // ---- proposing upstream ---- | |
| 333 | ||
| 334 | /** How a copy's branch goes to its origin, as the person is told before they say yes. */ | |
| 335 | export interface UpstreamPlan { | |
| 336 | readonly copy: Repo; | |
| 337 | readonly mirror: Repo; | |
| 338 | /** `owner/name` at the origin, the repository the pull request is opened on. */ | |
| 339 | readonly at: string; | |
| 340 | /** Where that is: `GitHub`, or the host. */ | |
| 341 | readonly on: string; | |
| 342 | readonly branch: string; | |
| 343 | /** `branch`, a branch pushed into `at`; `fork`, pushed to the person's fork there first. */ | |
| 344 | readonly into: "branch" | "fork"; | |
| 345 | /** With `fork`: the fork at the origin, the one there or the name it is made under. */ | |
| 346 | readonly fork: string | null; | |
| 347 | /** The name the branch goes up under: never the origin's default branch. */ | |
| 348 | readonly as: string; | |
| 349 | } | |
| 350 | ||
| 351 | export type UpstreamError = { readonly code: string; readonly words: string }; | |
| 352 | ||
| 353 | /** The longest branch name and pull request title a proposal sends to an origin. */ | |
| 354 | const UPSTREAM_BRANCH_MAX = 200; | |
| 355 | const UPSTREAM_TITLE_MAX = 256; | |
| 356 | ||
| 357 | const refuse = (code: string, words: string): Result<never, UpstreamError> => err({ code, words }); | |
| 358 | ||
| 359 | /** A repository named as `owner/name`, the person's copy or its mirror: the pair, or why not. */ | |
| 360 | function pairOf(app: App, actor: User, named: string): Result<{ copy: Repo; mirror: Repo }, UpstreamError> { | |
| 361 | const [owner, name, ...rest] = named.trim().replace(/^\//, "").split("/"); | |
| 362 | const repo = owner && name && rest.length === 0 ? getRepo(app.db, owner, name) : undefined; | |
| 363 | if (repo === undefined || !canRead(app.db, repo, actor)) return refuse("not_found", `No repository ${named} here.`); | |
| 364 | if (repo.origin !== null) { | |
| 365 | const copy = listForks(app.db, repo.id).find((r) => r.ownerId === actor.id && r.origin === null); | |
| 366 | return copy === undefined ? refuse("no_copy", `${named} has no copy of yours yet: bring it in, or ask for a change, first.`) : ok({ copy, mirror: repo }); | |
| 367 | } | |
| 368 | const parent = repo.forkParentId === null ? undefined : getRepoById(app.db, repo.forkParentId); | |
| 369 | if (parent === undefined || parent.origin === null || repo.ownerId !== actor.id) | |
| 370 | return refuse("not_a_copy", `${named} is not your copy of a repository kept elsewhere, so there is no upstream to propose to.`); | |
| 371 | return ok({ copy: repo, mirror: parent }); | |
| 372 | } | |
| 373 | ||
| 374 | /** | |
| 375 | * Plan a proposal: which repository at the origin, and whether the branch is pushed there or to | |
| 376 | * the person's fork there (the origin's own answer to whether they may push, as `openPull` asks | |
| 377 | * it). Reads only: nothing is pushed or made. | |
| 378 | */ | |
| 379 | export async function planUpstream( | |
| 380 | app: App, | |
| 381 | actor: User | undefined, | |
| 382 | input: { readonly repo: string; readonly branch?: string }, | |
| 383 | ): Promise<Result<UpstreamPlan, UpstreamError>> { | |
| 384 | if (actor === undefined || !isActive(actor) || actor.kind === "agent") return refuse("forbidden", "Only a person proposes upstream: the crew proposes to your copy."); | |
| 385 | const pair = pairOf(app, actor, input.repo); | |
| 386 | if (!pair.ok) return pair; | |
| 387 | const { copy, mirror } = pair.value; | |
| 388 | const through = writeThroughFor(app, actor, mirror); | |
| 389 | if (!through.ok || through.value === undefined) | |
| 390 | return refuse(through.ok ? "not_a_copy" : through.error, `The account that holds ${mirror.name} is not yours to propose through, or it cannot be reached now; see /settings/origins.`); | |
| 391 | const { origin, provider, fullName } = through.value; | |
| 392 | const branch = (input.branch ?? "").trim() || copy.defaultBranch; | |
| 393 | // It becomes a push at the origin: a branch name git takes, short, never a flag. | |
| 394 | if (!isSafeRef(branch) || branch.length > UPSTREAM_BRANCH_MAX || branch.startsWith("refs/")) | |
| 395 | return refuse("invalid", `${branch.slice(0, 60)} is not a branch name to propose: letters, digits, dashes, dots and slashes, at most ${String(UPSTREAM_BRANCH_MAX)} characters.`); | |
| 396 | const as = branch === mirror.defaultBranch ? `${copy.ownerName}/${branch}` : branch; | |
| 397 | const route = await proposalRoute(app, through.value); | |
| 398 | const fork = route === "fork" ? ((await existingFork(app, origin, provider, fullName))?.fullName ?? `${origin.login}/${fullName.split("/")[1] ?? copy.name}`) : null; | |
| 399 | return ok({ copy, mirror, at: fullName, on: originWords(origin), branch, into: route === "direct" ? "branch" : "fork", fork, as }); | |
| 400 | } | |
| 401 | ||
| 402 | /** | |
| 403 | * Propose a copy's branch upstream, as planned: refused when the plan the person said yes to is | |
| 404 | * no longer what would happen. Answers the pull request's address at the origin. | |
| 405 | */ | |
| 406 | export async function proposeUpstream( | |
| 407 | app: App, | |
| 408 | actor: User | undefined, | |
| 409 | input: { readonly repo: string; readonly branch?: string; readonly title: string; readonly body?: string; readonly told: Pick<UpstreamPlan, "at" | "on" | "into" | "fork" | "as"> }, | |
| 410 | ): Promise<Result<{ url: string; plan: UpstreamPlan }, UpstreamError>> { | |
| 411 | const planned = await planUpstream(app, actor, input); | |
| 412 | if (!planned.ok) return planned; | |
| 413 | const plan = planned.value; | |
| 414 | const told = input.told; | |
| 415 | if (plan.at !== told.at || plan.on !== told.on || plan.into !== told.into || plan.as !== told.as || (plan.into === "fork" && plan.fork !== told.fork)) | |
| 416 | return refuse("plan_changed", `The way to ${plan.at} is now: ${upstreamWords(plan)}. Plan again and ask once more.`); | |
| 417 | const title = input.title.trim(); | |
| 418 | if (title === "") return refuse("empty_title", "Give the pull request a title."); | |
| 419 | // It is sent to another forge's API as the pull request's title: one line, bounded. | |
| 420 | if (title.length > UPSTREAM_TITLE_MAX || /[\p{Cc}\p{Cf}\u2028\u2029]/u.test(title)) | |
| 421 | return refuse("invalid", `The title is one line of at most ${String(UPSTREAM_TITLE_MAX)} characters.`); | |
| 422 | const opened = await openPull(app, actor, plan.mirror, { | |
| 423 | title, | |
| 424 | ...(input.body === undefined ? {} : { body: input.body }), | |
| 425 | baseBranch: plan.mirror.defaultBranch, | |
| 426 | headBranch: plan.branch, | |
| 427 | headRepo: plan.copy, | |
| 428 | route: plan.into === "branch" ? "direct" : "fork", | |
| 429 | }); | |
| 430 | if (!opened.ok) return refuse(String(opened.error), `${plan.on} did not open it (${String(opened.error)}).`); | |
| 431 | return ok({ url: opened.value.originUrl ?? `${plan.mirror.ownerName}/${plan.mirror.name}/pulls/${opened.value.number}`, plan }); | |
| 432 | } |
src/actions/pulls.ts +15 −3
| @@ -126,7 +126,7 @@ const log = createLog("pulls"); | ||
| 126 | 126 | * cached one, and failing that the direct way, whose refusal falls back to |
| 127 | 127 | * the fork. |
| 128 | 128 | */ |
| 129 | async function proposalRoute( | |
| 129 | export async function proposalRoute( | |
| 130 | 130 | app: App, |
| 131 | 131 | through: WriteThrough, |
| 132 | 132 | ): Promise<"direct" | "fork"> { |
| @@ -169,6 +169,13 @@ export interface OpenPullInput { | ||
| 169 | 169 | * reports in its private repository. |
| 170 | 170 | */ |
| 171 | 171 | confirmPublic?: boolean; |
| 172 | /** | |
| 173 | * For a fork of a mirror proposing upstream: the way the person was told it goes (`direct`, a | |
| 174 | * branch pushed into the origin repository, or `fork`, through their fork there). Another answer | |
| 175 | * from the origin now is refused (`route_changed`) rather than taken, so what they said yes to | |
| 176 | * is what happens. | |
| 177 | */ | |
| 178 | route?: "direct" | "fork"; | |
| 172 | 179 | } |
| 173 | 180 | |
| 174 | 181 | export async function openPull( |
| @@ -185,6 +192,7 @@ export async function openPull( | ||
| 185 | 192 | | "unauthorized" |
| 186 | 193 | | "unverified" |
| 187 | 194 | | "sealed_in_public" |
| 195 | | "route_changed" | |
| 188 | 196 | | WriteThroughError |
| 189 | 197 | > |
| 190 | 198 | > { |
| @@ -216,6 +224,7 @@ async function createThePull( | ||
| 216 | 224 | | "not_found" |
| 217 | 225 | | "unauthorized" |
| 218 | 226 | | "sealed_in_public" |
| 227 | | "route_changed" | |
| 219 | 228 | | WriteThroughError |
| 220 | 229 | > |
| 221 | 230 | > { |
| @@ -247,10 +256,13 @@ async function createThePull( | ||
| 247 | 256 | // rather than a proposal — so it goes up under the fork owner's: |
| 248 | 257 | // `trevato/main`, proposing into `main`. Any other branch keeps its |
| 249 | 258 | // name. |
| 250 | if (input.headBranch === input.baseBranch) | |
| 259 | // Nor under the origin's default branch's name, whatever the base: a proposal never moves | |
| 260 | // the origin's default branch. | |
| 261 | if (input.headBranch === input.baseBranch || input.headBranch === baseRepo.defaultBranch) | |
| 251 | 262 | carriedAs = `${head.ownerName}/${input.headBranch}`; |
| 252 | 263 | pullHead = carriedAs; |
| 253 | 264 | const route = await proposalRoute(app, through.value); |
| 265 | if (input.route !== undefined && input.route !== route) return err("route_changed"); | |
| 254 | 266 | let viaFork = route === "fork"; |
| 255 | 267 | if (route === "direct") { |
| 256 | 268 | const carried = await carryBranchThrough( |
| @@ -263,7 +275,7 @@ async function createThePull( | ||
| 263 | 275 | ); |
| 264 | 276 | // The origin said no to the push itself: the account cannot write |
| 265 | 277 | // there after all. Reading is enough to propose, from a fork. |
| 266 | if (!carried.ok && carried.error.byOrigin !== true) | |
| 278 | if (!carried.ok && (carried.error.byOrigin !== true || input.route === "direct")) | |
| 267 | 279 | return err(refusal(carried.error.message)); |
| 268 | 280 | viaFork = !carried.ok; |
| 269 | 281 | } |
src/core/repo_fields.ts +3
| @@ -53,6 +53,9 @@ export const SINGLE_READER_FIELDS = { | ||
| 53 | 53 | audience: "object", |
| 54 | 54 | upstream: "object|null", |
| 55 | 55 | credit: "object|null", |
| 56 | // The caller's own rights here, `{ push, admin }`: what this viewer may do, never another's; | |
| 57 | // a reader learns only that they may not push. Another forge reads it to choose how it proposes. | |
| 58 | permissions: "object", | |
| 56 | 59 | } as const satisfies Readonly<Record<string, string>>; |
| 57 | 60 | |
| 58 | 61 | /** Every field a reader may ever be handed: the allow-list `readerView` cuts to. */ |
src/crew/conversation_ask.ts +9
| @@ -13,6 +13,8 @@ | ||
| 13 | 13 | * a secret (no form reads one). |
| 14 | 14 | */ |
| 15 | 15 | |
| 16 | import { upstreamWords } from "../origins/words.ts"; | |
| 17 | ||
| 16 | 18 | type Args = Record<string, unknown>; |
| 17 | 19 | |
| 18 | 20 | /** The words of a call: the start of a sentence, capitalised, without its full stop. */ |
| @@ -152,6 +154,13 @@ export const ASKED_AS: Readonly<Record<string, Form>> = { | ||
| 152 | 154 | write_file: (a) => `Commit ${val(a, "path") || "a file"} to ${val(a, "branch") || "a branch"} in ${repo(a)}`, |
| 153 | 155 | open_pull: (a) => `Open a pull in ${repo(a)}${clause(": ", quote(a, "title"))}`, |
| 154 | 156 | bring: (a) => `Bring ${val(a, "repo") || "the repository"} in to work on: a mirror and your copy, both private here`, |
| 157 | // Held only with a plan (`conversation_confirm.ts`); the sentence is the plan's own. | |
| 158 | propose_upstream: (a) => { | |
| 159 | const plan = a["plan"]; | |
| 160 | if (typeof plan !== "object" || plan === null) return "Open a pull request at the origin from your copy"; | |
| 161 | const p: Args = Object.fromEntries(Object.entries(plan)); | |
| 162 | return upstreamWords({ at: val(p, "at"), on: val(p, "on"), branch: val(a, "branch"), into: p["into"] === "fork" ? "fork" : "branch", fork: val(p, "fork"), as: val(p, "as") }); | |
| 163 | }, | |
| 155 | 164 | new_app: (a) => `Make a new app${clause(" called ", val(a, "name"))}${clause(": ", quote(a, "sentence"))}`, |
| 156 | 165 | asks_act: (a) => `${capital(verb(a, "action", { dismiss: "dismiss", decline: "decline", mute: "mute", listen: "unmute", undo: "undo", ship: "ship", close: "close", replan: "replan" }, "decide"))} ${a["action"] === "listen" ? repo(a) : a["action"] === "undo" ? "the last decision on your asks" : count(a["items"], "ask", "asks")}`, |
| 157 | 166 | asks: () => "Change the filter on what waits on you", |
src/crew/conversation_confirm.ts +2
| @@ -128,6 +128,8 @@ export const ASKING: Readonly<Record<string, Asking>> = { | ||
| 128 | 128 | migrate: {}, |
| 129 | 129 | // A repository kept elsewhere, mirrored and copied here: the person's credential spent on it. |
| 130 | 130 | bring: {}, |
| 131 | // A pull request opened at the origin, its branch pushed there or to the person's fork there. | |
| 132 | propose_upstream: { asks: (a) => a["plan"] !== undefined }, | |
| 131 | 133 | account_suspend: {}, |
| 132 | 134 | account_access: { |
| 133 | 135 | once: "The link was shown once, to you, and is not kept here.", |
src/http/api.ts +6 −2
| @@ -1664,8 +1664,12 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo | ||
| 1664 | 1664 | notePhase(ctx.request, "credit", performance.now() - credited); |
| 1665 | 1665 | const rendering = performance.now(); |
| 1666 | 1666 | const upstream = upstreamFacts(ctx.app.db, repo, ctx.auth.user); |
| 1667 | // `facts` is already cut to the viewer; the three added are reader fields. | |
| 1668 | const res = json({ ...facts, audience, upstream, credit }); | |
| 1667 | // `facts` is already cut to the viewer; the rest are reader fields. `permissions` is what this | |
| 1668 | // viewer may do here, as a Gitea client reads it: another forge connected to this one as an | |
| 1669 | // origin asks it before proposing, to push a branch here or to its own fork (#10262). | |
| 1670 | const viewer = ctx.auth.user; | |
| 1671 | const permissions = { push: viewer !== undefined && canWrite(ctx.app.db, repo, viewer), admin: viewer !== undefined && canAdmin(ctx.app.db, repo, viewer) }; | |
| 1672 | const res = json({ ...facts, audience, upstream, credit, permissions }); | |
| 1669 | 1673 | notePhase(ctx.request, "render", performance.now() - rendering); |
| 1670 | 1674 | return res; |
| 1671 | 1675 | }); |
src/http/mcp/catalog.ts +5 −4
| @@ -28,9 +28,9 @@ export const DEFAULT_TOOLS: readonly string[] = [ | ||
| 28 | 28 | * page the person linked), and the everyday writes on that work (comment, close or reopen, assign, |
| 29 | 29 | * labels, edit, review, merge, the plan on an issue, a word to or a stop of a crew run, a |
| 30 | 30 | * branch, a file and a pull for an app built in Talk, a new app, a repository kept elsewhere |
| 31 | * brought in to work on). Each write is held as any write | |
| 32 | * of this token is: after the agent has read text someone else wrote, a write the person's own | |
| 33 | * words do not ask for comes back `needs_confirm`, and the asked-first list | |
| 31 | * brought in to work on, and a pull request from its copy at the origin). Each write is held as any | |
| 32 | * write of this token is: after the agent has read text someone else wrote, a write the person's | |
| 33 | * own words do not ask for comes back `needs_confirm`, and the asked-first list | |
| 34 | 34 | * (`crew/conversation_confirm.ts`) holds its tools always; `test/mcp-talk-tools.test.ts` calls |
| 35 | 35 | * every write listed here after a hostile read and fails if one runs. Left out: what runs the forge |
| 36 | 36 | * itself (accounts, subscriptions, backups, cutting or rolling back a release, child forges, flags, |
| @@ -49,7 +49,7 @@ export const TALK_TOOLS: readonly string[] = [ | ||
| 49 | 49 | "issue", "issues", "pull", "pulls", "commits", "threads", "search", "read_file", "repo", "run_log", |
| 50 | 50 | "preview", "assigned", "health", "releases", "person", "whoami_can", "show", "pane", "origins", "invite", "wall", |
| 51 | 51 | "close", "assign", "labels", "edit", "review", "merge", "keep_plan", "steer", "stop", |
| 52 | "write_file", "branches", "open_pull", "new_app", "fetch_url", "bring", | |
| 52 | "write_file", "branches", "open_pull", "new_app", "fetch_url", "bring", "propose_upstream", | |
| 53 | 53 | ]; |
| 54 | 54 | |
| 55 | 55 | /** |
| @@ -107,6 +107,7 @@ export const KEYWORDS: Readonly<Record<string, string>> = { | ||
| 107 | 107 | run_log: "failed failure why log output", |
| 108 | 108 | origins: "github gitlab codeberg gitea forgejo connected account accounts elsewhere outside external", |
| 109 | 109 | bring: "github import mirror copy work fork elsewhere", |
| 110 | propose_upstream: "github pr pull request upstream origin send contribute", | |
| 110 | 111 | }; |
| 111 | 112 | |
| 112 | 113 | /** Entries matching every word of `query`, best first; a name weighs more than a description. */ |
src/http/mcp/tools/index.ts +1
| @@ -139,6 +139,7 @@ export { tool as profile } from "./profile.ts"; | ||
| 139 | 139 | export { tool as prompts } from "./prompts.ts"; |
| 140 | 140 | export { tool as proposal_tokens } from "./proposal_tokens.ts"; |
| 141 | 141 | export { tool as propose_to_parent_forge } from "./propose_to_parent_forge.ts"; |
| 142 | export { tool as propose_upstream } from "./propose_upstream.ts"; | |
| 142 | 143 | export { tool as pull } from "./pull.ts"; |
| 143 | 144 | export { tool as pulls } from "./pulls.ts"; |
| 144 | 145 | export { tool as queue_gates } from "./queue_gates.ts"; |
src/http/mcp/tools/propose_upstream.ts added +46
| @@ -0,0 +1,46 @@ | ||
| 1 | import { planUpstream, proposeUpstream } from "../../../actions/bring.ts"; | |
| 2 | import { upstreamWords } from "../../../origins/words.ts"; | |
| 3 | import { good, bad, str, type Tool } from "../shared.ts"; | |
| 4 | ||
| 5 | export const tool: Tool = { | |
| 6 | name: "propose_upstream", | |
| 7 | description: "Your copy `repo`'s `branch` as a pull request (`title`) at its origin; without `plan`, plans.", | |
| 8 | inputSchema: { | |
| 9 | type: "object", | |
| 10 | properties: { | |
| 11 | repo: { type: "string" }, | |
| 12 | branch: { type: "string" }, | |
| 13 | title: { type: "string", maxLength: 256 }, | |
| 14 | plan: { type: "object" }, | |
| 15 | }, | |
| 16 | required: ["repo"], | |
| 17 | }, | |
| 18 | writes: true, | |
| 19 | // Without `plan` it only plans: nothing is pushed or opened, and nothing holds it. | |
| 20 | readsWithout: "plan", | |
| 21 | async run(ctx, user, args) { | |
| 22 | const repo = str(args["repo"]); | |
| 23 | const branch = str(args["branch"]); | |
| 24 | const named = { repo, ...(branch === "" ? {} : { branch }) }; | |
| 25 | if (args["plan"] === undefined) { | |
| 26 | const planned = await planUpstream(ctx.app, user, named); | |
| 27 | if (!planned.ok) return bad(planned.error.code, planned.error.words); | |
| 28 | const p = planned.value; | |
| 29 | const plan = { into: p.into, at: p.at, on: p.on, as: p.as, ...(p.fork === null ? {} : { fork: p.fork }) }; | |
| 30 | // The next call carries the plan, so the sentence the person says yes to is the plan. | |
| 31 | return good({ says: upstreamWords(p), plan, next: { repo, branch: p.branch, title: "", plan } }); | |
| 32 | } | |
| 33 | const plan = (typeof args["plan"] === "object" && args["plan"] !== null ? args["plan"] : {}) as Record<string, unknown>; | |
| 34 | const into = plan["into"]; | |
| 35 | if (into !== "branch" && into !== "fork") return bad("invalid", "send `plan` as the plan answered it: call without `plan` first"); | |
| 36 | const fork = str(plan["fork"]); | |
| 37 | if (into === "fork" && fork === "") return bad("invalid", "a plan that goes through your fork names it: send `plan` as the plan answered it"); | |
| 38 | const done = await proposeUpstream(ctx.app, user, { | |
| 39 | ...named, | |
| 40 | title: str(args["title"]), | |
| 41 | told: { at: str(plan["at"]), on: str(plan["on"]), as: str(plan["as"]), into, fork: fork === "" ? null : fork }, | |
| 42 | }); | |
| 43 | if (!done.ok) return bad(done.error.code, done.error.words); | |
| 44 | return good({ says: `Opened on ${done.value.plan.on}: ${done.value.url}`, url: done.value.url }); | |
| 45 | }, | |
| 46 | }; |
src/origins/providers/forge.ts +31 −4
| @@ -17,6 +17,7 @@ import type { | ||
| 17 | 17 | RemoteIdentity, |
| 18 | 18 | RemoteLabel, |
| 19 | 19 | RemoteMilestone, |
| 20 | RemoteBranch, | |
| 20 | 21 | RemoteIssue, |
| 21 | 22 | RemoteRepo, |
| 22 | 23 | RemoteReviewState, |
| @@ -27,6 +28,10 @@ import { FORGE_PULL_CHECK_NEEDS, NO_ACCOUNT } from "../words.ts"; | ||
| 27 | 28 | import { forgeCursor, toForgeComment, toForgeWork } from "./forge-work.ts"; |
| 28 | 29 | import { asArray, asId, asString, asTime, dig, fail, field, seg, splitFullName, succeed } from "./http.ts"; |
| 29 | 30 | |
| 31 | /** A page of branches as a forge serves it at most (`eventsLimit`), and how many pages are read. */ | |
| 32 | const BRANCH_LIMIT = 200; | |
| 33 | const BRANCH_PAGES = 20; | |
| 34 | ||
| 30 | 35 | const MAX_COMMENT_PAGES = 1000; |
| 31 | 36 | const OLDER_PAGES = 10; |
| 32 | 37 | const MAX_LABEL_PAGES = 100; |
| @@ -176,14 +181,36 @@ export class ForgeProvider extends ForgejoProvider { | ||
| 176 | 181 | default_branch: field(raw, "defaultBranch"), |
| 177 | 182 | clone_url: `${web}.git`, |
| 178 | 183 | html_url: web, |
| 179 | // A forge's repository JSON carries no rights. Unknown is not | |
| 180 | // "cannot push": the direct way is tried, and its refusal falls | |
| 181 | // back to the account's own fork. | |
| 182 | permissions: { push: true, admin: false }, | |
| 184 | // A forge's repository answer says what the caller may do there; an older forge's says | |
| 185 | // nothing, and unknown is not "cannot push": the direct way is tried, and its refusal | |
| 186 | // falls back to the account's own fork. | |
| 187 | permissions: { push: dig(raw, "permissions", "push") !== false, admin: dig(raw, "permissions", "admin") === true }, | |
| 183 | 188 | }) |
| 184 | 189 | ); |
| 185 | 190 | } |
| 186 | 191 | |
| 192 | /** | |
| 193 | * The branches, as a forge lists them: `{ items, next_cursor }` paged by cursor (Gitea's `page` | |
| 194 | * is refused there), each `{ name, oid }`; a bare array from a forge older than that. | |
| 195 | */ | |
| 196 | override async listBranches(fullName: string): Promise<ProviderResult<readonly RemoteBranch[]>> { | |
| 197 | const base = this.repoPath(fullName); | |
| 198 | if (base === undefined) return fail("not_found", `not a repository name: ${fullName}`); | |
| 199 | const branches: RemoteBranch[] = []; | |
| 200 | let cursor: string | undefined; | |
| 201 | for (let page = 0; page < BRANCH_PAGES; page++) { | |
| 202 | const result = await this.api.call({ path: `${base}/branches`, query: { limit: BRANCH_LIMIT, cursor } }); | |
| 203 | if (!result.ok) return result; | |
| 204 | const data = result.value.data; | |
| 205 | const rows = Array.isArray(data) ? data : asArray(field(data, "items")); | |
| 206 | for (const raw of rows) branches.push({ name: asString(field(raw, "name")), oid: asString(field(raw, "oid")) || asString(dig(raw, "commit", "id")) }); | |
| 207 | const next = Array.isArray(data) ? "" : asString(field(data, "next_cursor")); | |
| 208 | if (next === "") break; | |
| 209 | cursor = next; | |
| 210 | } | |
| 211 | return succeed(branches); | |
| 212 | } | |
| 213 | ||
| 187 | 214 | /** One repository, from a forge's own JSON. */ |
| 188 | 215 | override async getRepo(fullName: string): Promise<ProviderResult<RemoteRepo>> { |
| 189 | 216 | const named = splitFullName(fullName); |
src/origins/words.ts +17
| @@ -47,3 +47,20 @@ export const FORGE_SIGN_IN_ON_PAGE = | ||
| 47 | 47 | /** A forge older than 0.7.355 reports no check on a pull; said so, with the release that does. */ |
| 48 | 48 | export const FORGE_PULL_CHECK_NEEDS = |
| 49 | 49 | "this forge is older than 0.7.355 and does not report a pull's check; it needs 0.7.355 or later"; |
| 50 | ||
| 51 | /** | |
| 52 | * The one sentence a proposal upstream is said in before the yes (`propose_upstream`, its | |
| 53 | * terminal door and Talk's confirm): which repository at the origin, and whether the branch is | |
| 54 | * pushed there or to the person's fork there. | |
| 55 | */ | |
| 56 | export function upstreamWords(p: { | |
| 57 | readonly at: string; | |
| 58 | readonly on: string; | |
| 59 | readonly branch: string; | |
| 60 | readonly into: "branch" | "fork"; | |
| 61 | readonly fork: string | null; | |
| 62 | readonly as: string; | |
| 63 | }): string { | |
| 64 | const where = p.into === "fork" ? `the branch is pushed to your fork ${p.fork ?? ""} on ${p.on}` : `the branch is pushed to ${p.at} on ${p.on} as ${p.as}`; | |
| 65 | return `Open a pull request on ${p.at} from your copy's ${p.branch}: ${where}`; | |
| 66 | } |
src/tui/forge.ts +9
| @@ -133,6 +133,7 @@ import { newOrgScreen } from "./screens/neworg.ts"; | ||
| 133 | 133 | import { migrateScreen } from "./screens/migrate.ts"; |
| 134 | 134 | import { bringScreen } from "./screens/bring.ts"; |
| 135 | 135 | import { bringWorkScreen } from "./screens/bringwork.ts"; |
| 136 | import { proposeUpstreamScreen } from "./screens/proposeupstream.ts"; | |
| 136 | 137 | import { openNewApp, templateAppScreen } from "./screens/newapp.ts"; |
| 137 | 138 | import { newRepoScreen } from "./screens/newrepo.ts"; |
| 138 | 139 | import { repoScreen } from "./screens/repo.ts"; |
| @@ -400,6 +401,14 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] { | ||
| 400 | 401 | hint: "from GitHub or another forge: your private copy here, the crew on it", |
| 401 | 402 | run: () => ctx.push(bringWorkScreen(session, ctx, blank("Work on a repository"))), |
| 402 | 403 | }); |
| 404 | // A pull request at the origin from that copy, as Talk's `propose_upstream` does: a person's. | |
| 405 | if (session.user !== undefined && session.user.kind !== "agent") | |
| 406 | commands.push({ | |
| 407 | id: "propose-upstream", | |
| 408 | title: "Propose upstream", | |
| 409 | hint: "your copy's branch as a pull request where the repository is kept", | |
| 410 | run: () => ctx.push(proposeUpstreamScreen(session, ctx, blank("Propose upstream"))), | |
| 411 | }); | |
| 403 | 412 | // An organization you own, as /organizations/new and MCP `org_create` make it: a person's, |
| 404 | 413 | // never an agent's (#7260). |
| 405 | 414 | if (session.user !== undefined && session.user.kind !== "agent") |
src/tui/screens/proposeupstream.ts added +60
| @@ -0,0 +1,60 @@ | ||
| 1 | /** | |
| 2 | * "Propose upstream" in the terminal: the door beside Talk's `propose_upstream`. Name your copy | |
| 3 | * (or the repository it copies), and the plan is said in the sentence Talk says before the yes: | |
| 4 | * the repository at the origin, and whether the branch is pushed there or to your fork there. | |
| 5 | * Yes asks for a title, then opens the pull request at the origin and toasts its address. | |
| 6 | */ | |
| 7 | ||
| 8 | import { planUpstream, proposeUpstream, type UpstreamPlan } from "../../actions/bring.ts"; | |
| 9 | import { upstreamWords } from "../../origins/words.ts"; | |
| 10 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 11 | import type { Session } from "../session.ts"; | |
| 12 | import { confirmScreen, later, promptScreen } from "./common.ts"; | |
| 13 | import { wrap } from "../term/width.ts"; | |
| 14 | ||
| 15 | function askTitle(f: Session, ctx: Ctx, parent: Screen, repo: string, plan: UpstreamPlan): Screen { | |
| 16 | return promptScreen(ctx, parent, { | |
| 17 | title: "Propose upstream", | |
| 18 | label: "Title of the pull request", | |
| 19 | hint: `On ${plan.at}, ${plan.on}.`, | |
| 20 | onSubmit: (title) => { | |
| 21 | if (title.trim() === "") return "Give it a title."; | |
| 22 | return proposeUpstream(f.app, f.user, { repo, branch: plan.branch, title, told: plan }).then((done) => { | |
| 23 | ctx.toast(done.ok ? `Opened on ${done.value.plan.on}: ${done.value.url}` : done.error.words, done.ok ? "success" : "danger"); | |
| 24 | if (done.ok) ctx.pop(); | |
| 25 | }); | |
| 26 | }, | |
| 27 | }); | |
| 28 | } | |
| 29 | ||
| 30 | export function proposeUpstreamScreen(f: Session, ctx: Ctx, parent: Screen): Screen { | |
| 31 | return promptScreen(ctx, parent, { | |
| 32 | title: "Propose upstream", | |
| 33 | label: "Your copy (owner/name), and a branch after a space", | |
| 34 | placeholder: "alice/widgets-work main", | |
| 35 | hint: "Its branch becomes a pull request on the repository it copies.", | |
| 36 | onSubmit: (value) => { | |
| 37 | const [repo = "", branch] = value.trim().split(/\s+/); | |
| 38 | if (repo === "") return "Name your copy."; | |
| 39 | return planUpstream(f.app, f.user, { repo, ...(branch === undefined ? {} : { branch }) }).then((plan) => { | |
| 40 | if (!plan.ok) { | |
| 41 | ctx.toast(plan.error.words, "danger"); | |
| 42 | return; | |
| 43 | } | |
| 44 | void later(ctx, () => | |
| 45 | confirmScreen(ctx, parent, { | |
| 46 | title: "Propose upstream", | |
| 47 | // The whole sentence, wrapped: it is what the person says yes to. | |
| 48 | body: wrap(`${upstreamWords(plan.value)}.`, 84), | |
| 49 | actions: [{ label: "Do it" }, { label: "Not now" }], | |
| 50 | yesNo: true, | |
| 51 | width: 90, | |
| 52 | onChoose: (i) => { | |
| 53 | if (i === 0) ctx.push(askTitle(f, ctx, parent, repo, plan.value)); | |
| 54 | }, | |
| 55 | }), | |
| 56 | ); | |
| 57 | }); | |
| 58 | }, | |
| 59 | }); | |
| 60 | } |
test/conversation-ask.test.ts +5
| @@ -163,6 +163,11 @@ const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [ | ||
| 163 | 163 | { repo: "https://github.com/marin/cakes" }, |
| 164 | 164 | "Bring https://github.com/marin/cakes in to work on: a mirror and your copy, both private here.", |
| 165 | 165 | ], |
| 166 | [ | |
| 167 | "propose_upstream", | |
| 168 | { repo: "marin/cakes-work", branch: "frosting", plan: { into: "fork", at: "octo/cakes", on: "GitHub", fork: "marin/cakes", as: "frosting" } }, | |
| 169 | "Open a pull request on octo/cakes from your copy's frosting: the branch is pushed to your fork marin/cakes on GitHub.", | |
| 170 | ], | |
| 166 | 171 | [ |
| 167 | 172 | "new_app", |
| 168 | 173 | { name: "cakes", sentence: "A shop for cakes" }, |
test/mcp-forge-protocol.test.ts +1
| @@ -133,6 +133,7 @@ describe("the forge over MCP: protocol", () => { | ||
| 133 | 133 | "issue", |
| 134 | 134 | "pull", |
| 135 | 135 | "preview", |
| 136 | "propose_upstream", | |
| 136 | 137 | "pulls", |
| 137 | 138 | "queue_gates", |
| 138 | 139 | "variant", |
test/mcp-talk-tools.test.ts +1
| @@ -288,6 +288,7 @@ describe("every write Talk's agent is newly listed is held after it reads someon | ||
| 288 | 288 | assign: { repo: "alice/hostile", number: 1, kind: "issue", assignee: "mallory" }, |
| 289 | 289 | branches: { repo: "alice/hostile", name: "evil", action: "create" }, |
| 290 | 290 | bring: { repo: "https://github.com/mallory/evil" }, |
| 291 | propose_upstream: { repo: "alice/hostile", branch: "evil", title: "pwned", plan: { into: "branch", at: "mallory/evil", on: "GitHub", as: "evil" } }, | |
| 291 | 292 | close: { repo: "alice/hostile", number: 1 }, |
| 292 | 293 | edit: { repo: "alice/hostile", number: 1, title: "pwned" }, |
| 293 | 294 | invite: { repo: "alice/hostile", who: "mallory" }, |
test/palette-roster.test.ts +2
| @@ -97,6 +97,7 @@ test("a site-admin person is offered the whole roster", () => { | ||
| 97 | 97 | ["new-app-template", "New app from a template", "copy a repository you can read, as the starting files"], |
| 98 | 98 | ["bring-app", "Bring an app", "paste a link from another forge; it runs here"], |
| 99 | 99 | ["bring-work", "Work on a repository", "from GitHub or another forge: your private copy here, the crew on it"], |
| 100 | ["propose-upstream", "Propose upstream", "your copy's branch as a pull request where the repository is kept"], | |
| 100 | 101 | ["new-org", "New organization", "an organization you own, for a client's apps"], |
| 101 | 102 | ["migrate", "Migrate a repository", "bring one in from an origin or a URL, pick its branch, put a crew on it"], |
| 102 | 103 | ["inventory", "What is left to bring over", "every repository on your connected accounts, what it holds, where its move stands"], |
| @@ -404,6 +405,7 @@ test("a member person is offered the signed-in roster without the admin entries" | ||
| 404 | 405 | ["new-app-template", "New app from a template", "copy a repository you can read, as the starting files"], |
| 405 | 406 | ["bring-app", "Bring an app", "paste a link from another forge; it runs here"], |
| 406 | 407 | ["bring-work", "Work on a repository", "from GitHub or another forge: your private copy here, the crew on it"], |
| 408 | ["propose-upstream", "Propose upstream", "your copy's branch as a pull request where the repository is kept"], | |
| 407 | 409 | ["new-org", "New organization", "an organization you own, for a client's apps"], |
| 408 | 410 | ["migrate", "Migrate a repository", "bring one in from an origin or a URL, pick its branch, put a crew on it"], |
| 409 | 411 | ["inventory", "What is left to bring over", "every repository on your connected accounts, what it holds, where its move stands"], |
test/talk-bring.test.ts +215 −3
| @@ -12,8 +12,13 @@ import { tmpdir } from "node:os"; | ||
| 12 | 12 | import { join } from "node:path"; |
| 13 | 13 | import { sayYes } from "../src/actions/conversation_confirms.ts"; |
| 14 | 14 | import { bringWait } from "../src/actions/bring.ts"; |
| 15 | import { createRepo } from "../src/actions/repos.ts"; | |
| 15 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 16 | 16 | import { connectOrigin, startMirrorJob } from "../src/actions/origins.ts"; |
| 17 | import { openPull } from "../src/actions/pulls.ts"; | |
| 18 | import { ForgeProvider } from "../src/origins/providers/forge.ts"; | |
| 19 | import { staticCredential } from "../src/origins/types.ts"; | |
| 20 | import { proposeUpstreamScreen } from "../src/tui/screens/proposeupstream.ts"; | |
| 21 | import { blank } from "../src/tui/screens/common.ts"; | |
| 17 | 22 | import { createApp, type App } from "../src/app.ts"; |
| 18 | 23 | import { listCrewRoles } from "../src/core/agents.ts"; |
| 19 | 24 | import { appendTurn, createConversation, listTurns } from "../src/core/conversations.ts"; |
| @@ -23,6 +28,8 @@ import { listPulls } from "../src/core/pulls.ts"; | ||
| 23 | 28 | import { getRepo, listForks } from "../src/core/repos.ts"; |
| 24 | 29 | import { createToken } from "../src/core/tokens.ts"; |
| 25 | 30 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; |
| 31 | import { resolveOid } from "../src/git/merge.ts"; | |
| 32 | import { repoDir } from "../src/git/repos.ts"; | |
| 26 | 33 | import { mintViaToken } from "../src/core/via_token.ts"; |
| 27 | 34 | import type { Ctx } from "../src/http/context.ts"; |
| 28 | 35 | import { serve, type Servers } from "../src/http/server.ts"; |
| @@ -43,6 +50,8 @@ let friendServers: Servers; | ||
| 43 | 50 | let w: StandInCrew; |
| 44 | 51 | let link = ""; |
| 45 | 52 | let bobToken = ""; |
| 53 | let carolToken = ""; | |
| 54 | let bobMain: string | undefined; | |
| 46 | 55 | let rpc = 1; |
| 47 | 56 | /** A forge whose crew can run seats one on a new copy (`crewCanRun`): a model key says it can. */ |
| 48 | 57 | const KEY = process.env["ANTHROPIC_API_KEY"]; |
| @@ -75,6 +84,13 @@ beforeAll(async () => { | ||
| 75 | 84 | expect((await fetch(`${friendServers.url}/api/v1/repos`, { method: "POST", headers: auth, body: JSON.stringify({ name, visibility: "public" }) })).status).toBeLessThan(300); |
| 76 | 85 | expect((await fetch(`${friendServers.url}/api/v1/repos/bob/${name}/contents`, { method: "POST", headers: auth, body: JSON.stringify({ branch: "main", message: "first", files: [{ path: "README.md", content: `# ${name}\n` }] }) })).status).toBeLessThan(300); |
| 77 | 86 | } |
| 87 | bobMain = await resolveOid(repoDir(friend.reposRoot, "bob", "widgets"), "refs/heads/main"); | |
| 88 | // Carol, on bob's forge, may read bob/widgets and not push to it. | |
| 89 | const carol = await createUser(friend.db, { origin: "seed", trusted: true, username: "carol", email: "[email protected]", password: "carol-passphrase-long" }); | |
| 90 | if (!carol.ok) throw new Error(carol.error); | |
| 91 | promote(friend.db, carol.value); | |
| 92 | proveAll(friend); | |
| 93 | carolToken = createToken(friend.db, carol.value.id, "t", "rw").token; | |
| 78 | 94 | |
| 79 | 95 | w = await startStandInCrew(); |
| 80 | 96 | proveAll(w.app); |
| @@ -165,13 +181,13 @@ describe("bring, then tell: the crew works on the person's copy", () => { | ||
| 165 | 181 | |
| 166 | 182 | /** A person on this forge with bob's account connected as their origin, and an rw token. */ |
| 167 | 183 | let people = 0; |
| 168 | const person = async (proven = true): Promise<{ user: User; token: string; originId: string }> => { | |
| 184 | const person = async (proven = true, token = bobToken): Promise<{ user: User; token: string; originId: string }> => { | |
| 169 | 185 | const name = `p${String(++people)}`; |
| 170 | 186 | const made = await createUser(w.app.db, { origin: "seed", trusted: true, username: name, email: `${name}@forge.local`, password: "a-good-passphrase" }); |
| 171 | 187 | if (!made.ok) throw new Error(made.error); |
| 172 | 188 | promote(w.app.db, made.value); |
| 173 | 189 | if (proven) proveAll(w.app); |
| 174 | const connected = await connectOrigin(w.app, made.value, { host: friendServers.url, token: bobToken }); | |
| 190 | const connected = await connectOrigin(w.app, made.value, { host: friendServers.url, token }); | |
| 175 | 191 | if (!connected.ok) throw new Error(JSON.stringify(connected.error)); |
| 176 | 192 | return { user: made.value, token: createToken(w.app.db, made.value.id, "t", "rw").token, originId: connected.value.id }; |
| 177 | 193 | }; |
| @@ -291,3 +307,199 @@ describe("bring keeps its promises", () => { | ||
| 291 | 307 | expect(listIssues(w.app.db, getRepo(w.app.db, p.user.username, "widgets")!.id, { state: "all" })).toEqual([]); |
| 292 | 308 | }); |
| 293 | 309 | }); |
| 310 | ||
| 311 | /** A conversation of `u`'s and its turn token. */ | |
| 312 | const talk = (u: User, words: string) => { | |
| 313 | const c = createConversation(w.app.db, u.id); | |
| 314 | if (!c.ok) throw new Error(c.error); | |
| 315 | appendTurn(w.app.db, u.id, c.value.id, { role: "person", text: words }); | |
| 316 | const via = `conversation:${c.value.id}`; | |
| 317 | const minted = mintViaToken(w.app.db, u.id, via, words, new Date(Date.now() + 600_000).toISOString()); | |
| 318 | if (!minted.ok) throw new Error(minted.error); | |
| 319 | return { id: c.value.id, via, token: minted.value.token }; | |
| 320 | }; | |
| 321 | const yesTo = async (u: User, via: string) => { | |
| 322 | const url = new URL(w.servers.url); | |
| 323 | const ctx: Ctx = { app: w.app, request: new Request(url.href), url, params: {}, auth: { user: u, scope: undefined, via: "session" }, theme: undefined }; | |
| 324 | const waiting = waitingFor(w.app.db, u.id).find((h) => h.via === via)!; | |
| 325 | return sayYes(ctx, u, waiting.id); | |
| 326 | }; | |
| 327 | ||
| 328 | describe("propose upstream: the copy's branch as a pull request at the origin", () => { | |
| 329 | test("bob may push to bob/widgets: the plan pushes a branch there, the yes opens the pull request and answers its address", async () => { | |
| 330 | const copy = getRepo(w.app.db, "alice", "widgets-work")!; | |
| 331 | expect((await commitToBranch(w.app, w.alice, copy, { branch: "hello", message: "Say hello", files: [{ path: "README.md", content: "# widgets\nhello\n" }] })).ok).toBe(true); | |
| 332 | const t = talk(w.alice, "open a PR upstream from hello"); | |
| 333 | // Planned with a plain token, whose answer is not fenced; held and said yes to in Talk. | |
| 334 | const plain = createToken(w.app.db, w.alice.id, "t", "rw").token; | |
| 335 | const plan = JSON.parse((await post(plain, "propose_upstream", { repo: "alice/widgets-work", branch: "hello" })).text) as { plan: { into: string }; says: string; next: Record<string, unknown> }; | |
| 336 | expect(plan.plan.into).toBe("branch"); | |
| 337 | expect(plan.says).toContain("the branch is pushed to bob/widgets"); | |
| 338 | const held = await post(t.token, "propose_upstream", { ...plan.next, title: "Say hello" }); | |
| 339 | expect(held.text).toContain("needs_confirm"); | |
| 340 | const turns = listTurns(w.app.db, w.alice.id, t.id, { limit: 50 }); | |
| 341 | const confirm = turns.ok ? turns.value.find((x) => x.role === "confirm") : undefined; | |
| 342 | expect(confirm?.text).toContain(plan.says); | |
| 343 | expect(listPulls(friend.db, getRepo(friend.db, "bob", "widgets")!.id, { state: "all" })).toEqual([]); | |
| 344 | ||
| 345 | const yes = await yesTo(w.alice, t.via); | |
| 346 | expect(yes.ok && yes.done).toBe(true); | |
| 347 | const theirs = getRepo(friend.db, "bob", "widgets")!; | |
| 348 | const pulls = listPulls(friend.db, theirs.id, { state: "all" }); | |
| 349 | expect(pulls.map((p) => p.title)).toEqual(["Say hello"]); | |
| 350 | expect(JSON.stringify(yes.ok ? yes.result : null)).toContain(`${friendServers.url}/bob/widgets/pulls/${pulls[0]!.number}`); | |
| 351 | expect(await resolveOid(repoDir(friend.reposRoot, "bob", "widgets"), "refs/heads/hello")).toBeDefined(); | |
| 352 | expect(await resolveOid(repoDir(friend.reposRoot, "bob", "widgets"), "refs/heads/main")).toBe(bobMain); | |
| 353 | }); | |
| 354 | ||
| 355 | test("the copy's default branch never moves the origin's: it goes up under alice/main", async () => { | |
| 356 | const copy = getRepo(w.app.db, "alice", "widgets-work")!; | |
| 357 | expect((await commitToBranch(w.app, w.alice, copy, { branch: "main", message: "On main", files: [{ path: "MAIN.md", content: "x\n" }] })).ok).toBe(true); | |
| 358 | const token = createToken(w.app.db, w.alice.id, "t", "rw").token; | |
| 359 | const plan = JSON.parse((await post(token, "propose_upstream", { repo: "alice/widgets-work" })).text) as { plan: { as: string }; next: Record<string, unknown> }; | |
| 360 | expect(plan.plan.as).toBe("alice/main"); | |
| 361 | const done = await post(token, "propose_upstream", { ...plan.next, title: "From main" }); | |
| 362 | expect(done.error).toBe(false); | |
| 363 | expect(await resolveOid(repoDir(friend.reposRoot, "bob", "widgets"), "refs/heads/main")).toBe(bobMain); | |
| 364 | expect(await resolveOid(repoDir(friend.reposRoot, "bob", "widgets"), "refs/heads/alice/main")).toBeDefined(); | |
| 365 | }); | |
| 366 | ||
| 367 | test("a plan that no longer holds is refused, not taken another way", async () => { | |
| 368 | const token = createToken(w.app.db, w.alice.id, "t", "rw").token; | |
| 369 | const stale = await post(token, "propose_upstream", { repo: "alice/widgets-work", branch: "hello", title: "x", plan: { into: "fork", at: "bob/widgets", on: "elsewhere", fork: "alice/widgets", as: "hello" } }); | |
| 370 | expect(stale.error).toBe(true); | |
| 371 | expect(stale.text).toContain("plan_changed"); | |
| 372 | }); | |
| 373 | ||
| 374 | test("carol may only read: the plan forks bob/widgets to carol's account there and the pull request comes from it", async () => { | |
| 375 | const dave = await createUser(w.app.db, { origin: "seed", trusted: true, username: "dave", email: "[email protected]", password: "dave-passphrase-long" }); | |
| 376 | if (!dave.ok) throw new Error(dave.error); | |
| 377 | promote(w.app.db, dave.value); | |
| 378 | proveAll(w.app); | |
| 379 | const connected = await connectOrigin(w.app, dave.value, { host: friendServers.url, token: carolToken }); | |
| 380 | if (!connected.ok) throw new Error(JSON.stringify(connected.error)); | |
| 381 | const token = createToken(w.app.db, dave.value.id, "t", "rw").token; | |
| 382 | const brought = JSON.parse((await post(token, "bring", { repo: link })).text) as { copy: string }; | |
| 383 | expect(brought.copy).toBe("/dave/widgets-work"); | |
| 384 | const copy = getRepo(w.app.db, "dave", "widgets-work")!; | |
| 385 | expect((await commitToBranch(w.app, dave.value, copy, { branch: "typo", message: "Fix a typo", files: [{ path: "README.md", content: "# Widgets\n" }] })).ok).toBe(true); | |
| 386 | const plan = JSON.parse((await post(token, "propose_upstream", { repo: "dave/widgets-work", branch: "typo" })).text) as { plan: { into: string; fork: string }; says: string; next: Record<string, unknown> }; | |
| 387 | expect(plan.plan.into).toBe("fork"); | |
| 388 | expect(plan.plan.fork).toBe("carol/widgets"); | |
| 389 | expect(plan.says).toContain("pushed to your fork carol/widgets"); | |
| 390 | const done = await post(token, "propose_upstream", { ...plan.next, title: "Fix a typo" }); | |
| 391 | expect(done.error).toBe(false); | |
| 392 | expect(getRepo(friend.db, "carol", "widgets")?.forkParentId).toBe(getRepo(friend.db, "bob", "widgets")!.id); | |
| 393 | const pulls = listPulls(friend.db, getRepo(friend.db, "bob", "widgets")!.id, { state: "all" }); | |
| 394 | expect(pulls.map((p) => p.title)).toContain("Fix a typo"); | |
| 395 | expect(await resolveOid(repoDir(friend.reposRoot, "bob", "widgets"), "refs/heads/typo")).toBeUndefined(); | |
| 396 | }); | |
| 397 | ||
| 398 | test("the crew never proposes upstream, and a repository that is no copy has no upstream", async () => { | |
| 399 | const token = createToken(w.app.db, w.alice.id, "t", "rw").token; | |
| 400 | expect((await post(token, "propose_upstream", { repo: "alice/garden" })).text).toContain("not_a_copy"); | |
| 401 | const bot = createToken(w.app.db, w.bot.id, "t", "rw").token; | |
| 402 | expect((await post(bot, "propose_upstream", { repo: "alice/widgets-work" })).error).toBe(true); | |
| 403 | }); | |
| 404 | }); | |
| 405 | ||
| 406 | describe("propose upstream: the rest of what it promises", () => { | |
| 407 | test("the repository GET says the caller's own rights: owner push and admin, a reader and a stranger neither", async () => { | |
| 408 | const get = async (token?: string) => | |
| 409 | ((await (await fetch(`${friendServers.url}/api/v1/repos/bob/widgets`, { headers: token === undefined ? {} : { authorization: `Bearer ${token}` } })).json()) as { permissions: { push: boolean; admin: boolean } }).permissions; | |
| 410 | expect(await get(bobToken)).toEqual({ push: true, admin: true }); | |
| 411 | expect(await get(carolToken)).toEqual({ push: false, admin: false }); | |
| 412 | expect(await get()).toEqual({ push: false, admin: false }); | |
| 413 | }); | |
| 414 | ||
| 415 | test("a forge's answers, canned: rights read when sent and unknown (push) when not; branches by cursor and as a bare array", async () => { | |
| 416 | const answers: Record<string, unknown> = { | |
| 417 | "/api/v1/repos/ana/said": { ownerName: "ana", name: "said", visibility: "public", permissions: { push: false, admin: false } }, | |
| 418 | "/api/v1/repos/ana/older": { ownerName: "ana", name: "older", visibility: "public" }, | |
| 419 | "/api/v1/repos/ana/said/branches": { items: [{ name: "main", oid: "a".repeat(40) }], next_cursor: "main" }, | |
| 420 | "/api/v1/repos/ana/said/branches?main": { items: [{ name: "dev", oid: "b".repeat(40) }], next_cursor: null }, | |
| 421 | "/api/v1/repos/ana/older/branches": [{ name: "main", commit: { id: "c".repeat(40) } }], | |
| 422 | }; | |
| 423 | const canned = Bun.serve({ | |
| 424 | port: 0, | |
| 425 | fetch: (req) => { | |
| 426 | const u = new URL(req.url); | |
| 427 | const cursor = u.searchParams.get("cursor"); | |
| 428 | const body = answers[`${u.pathname}${cursor === null ? "" : `?${cursor}`}`]; | |
| 429 | return body === undefined ? new Response("no", { status: 404 }) : Response.json(body); | |
| 430 | }, | |
| 431 | }); | |
| 432 | try { | |
| 433 | const provider = new ForgeProvider(staticCredential({ kind: "forgejo", apiUrl: `http://127.0.0.1:${String(canned.port)}/api/v1`, webUrl: `http://127.0.0.1:${String(canned.port)}`, token: "canned" })); | |
| 434 | const said = await provider.getRepo("ana/said"); | |
| 435 | expect(said.ok && said.value.permissions).toEqual({ push: false, admin: false }); | |
| 436 | const older = await provider.getRepo("ana/older"); | |
| 437 | expect(older.ok && older.value.permissions.push).toBe(true); | |
| 438 | const paged = await provider.listBranches("ana/said"); | |
| 439 | expect(paged.ok && paged.value.map((b) => `${b.name}:${b.oid[0]!}`)).toEqual(["main:a", "dev:b"]); | |
| 440 | const bare = await provider.listBranches("ana/older"); | |
| 441 | expect(bare.ok && bare.value.map((b) => `${b.name}:${b.oid[0]!}`)).toEqual(["main:c"]); | |
| 442 | } finally { | |
| 443 | canned.stop(true); | |
| 444 | } | |
| 445 | }); | |
| 446 | ||
| 447 | test("openPull takes the told way or refuses: route_changed, and a refused push on the direct way is an error, never a fork", async () => { | |
| 448 | const mirror = getRepo(w.app.db, "alice", "widgets")!; | |
| 449 | const copy = getRepo(w.app.db, "alice", "widgets-work")!; | |
| 450 | const changed = await openPull(w.app, w.alice, mirror, { title: "Told fork", baseBranch: "main", headBranch: "hello", headRepo: copy, route: "fork" }); | |
| 451 | expect(changed.ok ? "" : changed.error).toBe("route_changed"); | |
| 452 | // Erin connected bob's account with a read-only token: the forge says bob may push, the push is | |
| 453 | // refused. | |
| 454 | const ro = createToken(friend.db, getUserByName(friend.db, "bob")!.id, "ro", "ro").token; | |
| 455 | const erin = await person(true, ro); | |
| 456 | expect((await post(erin.token, "bring", { repo: link })).error).toBe(false); | |
| 457 | const theirs = getRepo(w.app.db, erin.user.username, "widgets-work")!; | |
| 458 | expect((await commitToBranch(w.app, erin.user, theirs, { branch: "erin-hello", message: "Hi", files: [{ path: "E.md", content: "e\n" }] })).ok).toBe(true); | |
| 459 | const direct = await openPull(w.app, erin.user, getRepo(w.app.db, erin.user.username, "widgets")!, { title: "Erin's", baseBranch: "main", headBranch: "erin-hello", headRepo: theirs, route: "direct" }); | |
| 460 | expect(direct.ok).toBe(false); | |
| 461 | const bobs = getRepo(friend.db, "bob", "widgets")!; | |
| 462 | expect(listPulls(friend.db, bobs.id, { state: "all" }).map((p) => p.title)).not.toContain("Erin's"); | |
| 463 | expect(getRepo(friend.db, "bob", "widgets-2")).toBeUndefined(); | |
| 464 | }); | |
| 465 | ||
| 466 | test("a branch or a title that is not one line of a sane size never reaches the origin", async () => { | |
| 467 | const token = createToken(w.app.db, w.alice.id, "t", "rw").token; | |
| 468 | expect((await post(token, "propose_upstream", { repo: "alice/widgets-work", branch: "--upload-pack=x" })).text).toContain("not a branch name"); | |
| 469 | expect((await post(token, "propose_upstream", { repo: "alice/widgets-work", branch: "a..b" })).text).toContain("not a branch name"); | |
| 470 | const plan = JSON.parse((await post(token, "propose_upstream", { repo: "alice/widgets-work", branch: "hello" })).text) as { next: Record<string, unknown> }; | |
| 471 | expect((await post(token, "propose_upstream", { ...plan.next, title: "one\ntwo" })).text).toContain("one line"); | |
| 472 | expect((await post(token, "propose_upstream", { ...plan.next, plan: { ...(plan.next["plan"] as object), into: "fork", fork: "" }, title: "x" })).text).toContain("names it"); | |
| 473 | }); | |
| 474 | ||
| 475 | test("the terminal's Propose upstream: the plan sentence, Do it, a title, then the address; a non-copy is a toast", async () => { | |
| 476 | const copy = getRepo(w.app.db, "alice", "widgets-work")!; | |
| 477 | expect((await commitToBranch(w.app, w.alice, copy, { branch: "tui-hello", message: "From the terminal", files: [{ path: "T.md", content: "t\n" }] })).ok).toBe(true); | |
| 478 | const terminal = headlessTerminal(160, 40); | |
| 479 | const { app: tui, session } = createForgeApp(w.app, { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: w.alice }, { terminal, exitHooks: false, toastMs: 10 * 60_000 }); | |
| 480 | tui.start(); | |
| 481 | try { | |
| 482 | await settleApp(tui); | |
| 483 | tui.ctx.push(proposeUpstreamScreen(session, tui.ctx, blank("Propose upstream"))); | |
| 484 | await settleApp(tui); | |
| 485 | terminal.feed("alice/garden\r"); | |
| 486 | await settleApp(tui); | |
| 487 | expect(tui.screen.toText()).toContain("not your copy"); | |
| 488 | tui.ctx.push(proposeUpstreamScreen(session, tui.ctx, blank("Propose upstream"))); | |
| 489 | await settleApp(tui); | |
| 490 | terminal.feed("alice/widgets-work tui-hello\r"); | |
| 491 | // The dialog wraps the sentence: read it as one line. | |
| 492 | const flat = () => tui.screen.toText().replace(/[\s│]+/g, " "); | |
| 493 | await pollUntil(() => flat().includes("the branch is pushed to bob/widgets"), "the plan sentence"); | |
| 494 | terminal.feed("y"); | |
| 495 | await settleApp(tui); | |
| 496 | terminal.feed("From the terminal\r"); | |
| 497 | const bobs = getRepo(friend.db, "bob", "widgets")!; | |
| 498 | await pollUntil(() => listPulls(friend.db, bobs.id, { state: "all" }).some((p) => p.title === "From the terminal"), "the pull at the origin"); | |
| 499 | await settleApp(tui); | |
| 500 | expect(flat()).toContain(`${friendServers.url}/bob/widgets/pulls/`); | |
| 501 | } finally { | |
| 502 | tui.stop(); | |
| 503 | } | |
| 504 | }); | |
| 505 | }); |
new above
offline