Public: anyone can read this; the crew can change it.
Working together across forges: copies elsewhere, changes coming, held proposals (#16417) #16453
Check · Review · Land · Live — Pushed since the last review.
talk-together-2 → main 2 commits 4 threads · 4 unresolved
33 files
changed +986
−87
docs/design/areas/talk.md +1
| @@ -115,6 +115,7 @@ Prior art: Claude and ChatGPT (one centred column, the person's words in a quiet | ||
| 115 | 115 | - `.talk-crew-fold`: the crew's block while it works, a `<details>` whose summary is its one working line; folded, the fold is kept per conversation. A hold or a failure is drawn without it, so it can never be folded away. |
| 116 | 116 | - `.talk-crew-reply`: a box in the crew's block whose words are said on the pull shown above, else the run's issue (a comment the crew member reads next); the same path as a receipt's Reply. |
| 117 | 117 | - `.together`: the together line (`web/together.ts`), under the pane's info line and on a repository's page, a live region of its own; nothing in it moves but its words, and it takes no room when the viewer is alone and nothing was done lately. |
| 118 | - `.together-elsewhere`: copies on other forges, counted (named only to a writer); `.together-held`: one quiet line per proposal from another forge a rule held, to a writer and the owner. Words only, muted. | |
| 118 | 119 | - `.together-here`: who else is here now (named, or counted on a public repository) and the crew building, in words only, on the muted colour. |
| 119 | 120 | - `.together-lately`: the last three things done on the repository, one line, each said once when drawn ("just now", "4 min ago"); never a counter. |
| 120 | 121 | - `.together-landed`: once, that someone's change landed ("ben's change landed: Live has it now."), with See Live, Reply to ben and Dismiss; on Live the one thing that reloads the frame. |
docs/features/talk.md +9 −1
| @@ -218,12 +218,20 @@ Under the preview, while the crew works, its block says who is working and strea | ||
| 218 | 218 | |
| 219 | 219 | ## Working together |
| 220 | 220 | |
| 221 | When others are on the same app or repository, the pane (and the repository's page) says so in one quiet line under the address bar: "ben and maya are here · juniper is building #15". Under it, the last three things done there, once each: "maya opened a pull request: #16 Water reflects the sky · 2 min ago", "#13 Fog: checks passing". Nothing ticks and nothing moves but the words; alone, with nothing done lately, the line takes no room. | |
| 221 | When others are on the same app or repository, Talk's pane and every page of the repository (its home, an app's page, a file, its issues and pulls, under the header) say so in one quiet line: "ben and maya are here · juniper is building #15". Under it, the last three things done there, once each: "maya opened a pull request: #16 Water reflects the sky · 2 min ago", "#13 Fog: checks passing". Nothing ticks and nothing moves but the words; alone, with nothing done lately, the line takes no room. The line rides the page's own live stream (a `together` frame, rendered by the server for that reader alone, so only the names they may see), sent as the stream opens and again whenever someone comes or goes. The page draws the line itself too, so it is there with JavaScript off and nothing moves when the stream opens: in full on the repository's home and in Talk's pane, and on every other page of the repository who is here alone, from the forge's memory of open pages. A mirrored pull is said by its origin author, never by the account that keeps the mirror. | |
| 222 | 222 | |
| 223 | 223 | When a change lands, the line says it once: "ben's change landed: Live has it now." with See Live, Reply to ben (the composer then says your words on ben's pull) and Dismiss. On Live the frame reloads under that line, and that is the only thing that ever reloads it there; on a pull's preview the frame stays where you put it. |
| 224 | 224 | |
| 225 | 225 | Who is here comes only from pages open now: each page's live stream takes a seat on the repository while it is open and gives it up when it closes, or after 45 seconds unanswered. Nothing is written down, so there is no history of who looked at what. It counts people, not tabs: the same person in two tabs, or on a phone and a desk, is one name (one seat, however many pages they open), and never shown to themselves. The line is shown only to people who may read the repository; a stranger and a signed-out visitor see nothing, and the crew shows only as what it builds. On a private repository everyone here is named. On a public repository only people who may write to it are named; any other signed-in reader is counted, never named: "ben is here · 2 others are reading". So what someone is reading is never shown to anyone, and the line still says the place is busy. |
| 226 | 226 | |
| 227 | **Across forges.** When someone brings a repository to work on from another forge (Talk's `bring`, the terminal's Work on a repository), their forge tells the origin, as their own account there, what they chose to share (`POST /api/v1/repos/:owner/:name/copies`, `src/core/copies.ts`): | |
| 228 | ||
| 229 | - **Counted** (the default): that a copy exists and the files its open work changes, never their name. | |
| 230 | - **Named**: their name and their forge too, to the origin's writers. | |
| 231 | - **None**: nothing; the origin keeps no row, and a copy told before is forgotten at once. A forge too old to send a choice is taken as none. | |
| 232 | ||
| 233 | The origin's line then says "2 people have copies elsewhere · 1 change coming for src/valid.ts". A reader reads counts and files only; a writer and the owner also read the names of copies shared as named, and one quiet line for each fork of it a rule held (the step a proposal from another forge takes): "rita tried to fork it; held by the new-account rule". The proposer hears the reason in their own answer (see Propose upstream in docs/features/contributors.md). A stranger reads nothing. The bring's own answer says what the origin says of the other copies. Bounded: at most 200 copies and 50 held proposals a repository and 50 files a copy; a copy fades 30 days after its forge last reported it, a held proposal after 7 days, on the forge's hourly prune. The files are re-sent each time the person plans a proposal. | |
| 234 | ||
| 227 | 235 | In the terminal, the Talk screen's pane prints the same lines ("Here:", "Lately:", and the landing), and `L` shows Live. |
| 228 | 236 | |
| 229 | 237 | ## Display (#15734) |
src/actions/bring.ts +17 −5
| @@ -32,6 +32,8 @@ import { settled, type MirrorJob } from "../origins/jobs.ts"; | ||
| 32 | 32 | import type { Origin, OriginSaid, Provider } from "../origins/types.ts"; |
| 33 | 33 | import { NEW_ACCOUNT_GUARD_MESSAGE } from "../core/capacity.ts"; |
| 34 | 34 | import { needsOf, originOnHost, parseBringLink } from "../origins/bring.ts"; |
| 35 | import { setCopyShare, tellOrigin } from "./copies.ts"; | |
| 36 | import { DEFAULT_SHARE, type Share } from "../core/copies.ts"; | |
| 35 | 37 | import { requireVerified } from "./verify.ts"; |
| 36 | 38 | import { appLimitWords } from "./app_limit.ts"; |
| 37 | 39 | import { enableApp, setAppEnvVar } from "./apps.ts"; |
| @@ -243,6 +245,8 @@ export interface BroughtIn { | ||
| 243 | 245 | readonly reused: { readonly mirror: boolean; readonly copy: boolean }; |
| 244 | 246 | /** Whether a mirror already here in public was made private by this bring. */ |
| 245 | 247 | readonly madePrivate: boolean; |
| 248 | /** What the origin says of the other copies elsewhere, when it is a forge and says any. */ | |
| 249 | readonly others?: string; | |
| 246 | 250 | } |
| 247 | 251 | |
| 248 | 252 | const OWNER_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}\/[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/; |
| @@ -271,7 +275,7 @@ function bringTarget(app: App, actor: User, repo: string, originId: string | und | ||
| 271 | 275 | export async function bringToWork( |
| 272 | 276 | app: App, |
| 273 | 277 | actor: User | undefined, |
| 274 | input: { readonly repo: string; readonly origin?: string }, | |
| 278 | input: { readonly repo: string; readonly origin?: string; readonly share?: Share }, | |
| 275 | 279 | ): Promise<Result<BroughtIn, BringError>> { |
| 276 | 280 | if (actor === undefined || !isActive(actor) || actor.kind === "agent") return err({ kind: "unauthorized" }); |
| 277 | 281 | if (!requireVerified(app, actor).ok) return err({ kind: "unverified" }); |
| @@ -317,7 +321,11 @@ export async function bringToWork( | ||
| 317 | 321 | if (!kept.ok) return keptPublic; |
| 318 | 322 | const copy = await workCopyOf(app, actor, kept.value.repo); |
| 319 | 323 | if (!copy.ok) return err({ kind: "invalid", message: `${fullName} is here, but your copy could not be made (${copy.error}).` }); |
| 320 | return ok({ name: fullName, from, mirror: kept.value.repo, copy: copy.value.repo, reused: { mirror: reusedMirror, copy: !copy.value.made }, madePrivate: kept.value.made }); | |
| 324 | // What the copy tells its origin (`core/copies.ts`): counted unless the person picks otherwise; a | |
| 325 | // copy already here keeps its choice unless one is given now. | |
| 326 | if (copy.value.made || input.share !== undefined) setCopyShare(app, copy.value.repo, input.share ?? DEFAULT_SHARE); | |
| 327 | const others = await tellOrigin(app, actor, copy.value.repo, kept.value.repo); | |
| 328 | return ok({ name: fullName, from, mirror: kept.value.repo, copy: copy.value.repo, reused: { mirror: reusedMirror, copy: !copy.value.made }, madePrivate: kept.value.made, ...(others === undefined ? {} : { others }) }); | |
| 321 | 329 | } |
| 322 | 330 | |
| 323 | 331 | /** |
| @@ -325,7 +333,7 @@ export async function bringToWork( | ||
| 325 | 333 | * never the two repositories it is made of. |
| 326 | 334 | */ |
| 327 | 335 | export function broughtWords(b: BroughtIn): string { |
| 328 | const madePrivate = b.madePrivate ? ` Its mirror here was public; it is private now.` : ""; | |
| 336 | const madePrivate = `${b.madePrivate ? ` Its mirror here was public; it is private now.` : ""}${b.others === undefined ? "" : ` At ${b.from}: ${b.others}.`}`; | |
| 329 | 337 | const copyPublic = b.copy !== undefined && b.copy.visibility !== "private" ? ` Your copy is public, as you set it.` : ""; |
| 330 | 338 | if (b.copy === undefined) return `${b.name} is still being copied from ${b.from}; your copy is made when you first ask for a change.${madePrivate}`; |
| 331 | 339 | 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}`; |
| @@ -370,7 +378,7 @@ const OVERLAP_PULLS_MAX = 10; | ||
| 370 | 378 | * list short, never the plan refused. The cost: one listing and up to `OVERLAP_PULLS_MAX` diffs at |
| 371 | 379 | * the origin on every plan, in parallel. |
| 372 | 380 | */ |
| 373 | async function overlapsAt(app: App, provider: Provider, origin: Origin, fullName: string, copy: Repo, mirror: Repo, branch: string): Promise<UpstreamOverlap[]> { | |
| 381 | async function overlapsAt(app: App, provider: Provider, origin: Origin, fullName: string, copy: Repo, mirror: Repo, branch: string, changed: (paths: readonly string[]) => void = () => {}): Promise<UpstreamOverlap[]> { | |
| 374 | 382 | const copyDir = repoDir(app.reposRoot, copy.ownerName, copy.name); |
| 375 | 383 | const [head, base] = await Promise.all([ |
| 376 | 384 | resolveOid(copyDir, `refs/heads/${branch}`), |
| @@ -378,6 +386,7 @@ async function overlapsAt(app: App, provider: Provider, origin: Origin, fullName | ||
| 378 | 386 | ]); |
| 379 | 387 | if (head === undefined || base === undefined) return []; |
| 380 | 388 | const mine = new Set((await diffBetween(copyDir, base, head)).diff.files.map((f) => f.path)); |
| 389 | changed([...mine]); | |
| 381 | 390 | if (mine.size === 0) return []; |
| 382 | 391 | const open = await provider.listIssues(fullName, { kind: "pull", state: "open" }); |
| 383 | 392 | if (!open.ok) return []; |
| @@ -449,7 +458,10 @@ export async function planUpstream( | ||
| 449 | 458 | if (live.ok && live.value.permissions.fork === false) return refuse("fork_held", forkHeldWords(fullName)); |
| 450 | 459 | } |
| 451 | 460 | const fork = route === "fork" ? (found?.fullName ?? `${origin.login}/${fullName.split("/")[1] ?? copy.name}`) : null; |
| 452 | const overlaps = await overlapsAt(app, provider, origin, fullName, copy, mirror, branch); | |
| 461 | let changed: readonly string[] = []; | |
| 462 | const overlaps = await overlapsAt(app, provider, origin, fullName, copy, mirror, branch, (paths) => (changed = paths)); | |
| 463 | // The origin hears which files this work changes, as the person chose to share (`tellOrigin`). | |
| 464 | await tellOrigin(app, actor, copy, mirror, changed); | |
| 453 | 465 | return ok({ copy, mirror, at: fullName, on: originWords(origin), branch, into: route === "direct" ? "branch" : "fork", fork, as, overlaps }); |
| 454 | 466 | } |
| 455 | 467 |
src/actions/copies.ts added +69
| @@ -0,0 +1,69 @@ | ||
| 1 | /** | |
| 2 | * An origin told of a copy on another forge (`core/copies.ts`): the bringer's own forge reports, as | |
| 3 | * the bringer's account, what they chose to share. A reader of the repository may report their own | |
| 4 | * copy and nobody else's; what comes back is what they may read of the others. | |
| 5 | */ | |
| 6 | import type { App } from "../app.ts"; | |
| 7 | import { copiesFor, copiesWords, PATHS_MAX, recordCopy, shareOf, type Share } from "../core/copies.ts"; | |
| 8 | import { ownHost } from "../core/trusted_sources.ts"; | |
| 9 | import { writeThroughFor } from "../origins/write-through.ts"; | |
| 10 | import { during } from "../perf/jobs.ts"; | |
| 11 | ||
| 12 | /** How long a person's own answer waits on an origin told of their copy. */ | |
| 13 | export const TELL_MS = 3_000; | |
| 14 | import { canRead, type Repo } from "../core/repos.ts"; | |
| 15 | import { isActive, type User } from "../core/users.ts"; | |
| 16 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 17 | ||
| 18 | /** Keep `actor`'s report of their copy of `repo`; answers the line they may read of the others. */ | |
| 19 | export function reportCopy( | |
| 20 | app: App, | |
| 21 | actor: User | undefined, | |
| 22 | repo: Repo, | |
| 23 | input: { readonly share?: unknown; readonly forge?: unknown; readonly paths?: unknown }, | |
| 24 | ): Result<{ readonly share: Share; readonly others: string | undefined }, "unauthorized" | "not_found"> { | |
| 25 | if (actor === undefined || !isActive(actor) || actor.kind !== "user") return err("unauthorized"); | |
| 26 | if (!canRead(app.db, repo, actor)) return err("not_found"); | |
| 27 | // A forge too old to send a choice told nothing: none. | |
| 28 | const share = shareOf(input.share); | |
| 29 | recordCopy(app.db, repo, actor, { share, forge: typeof input.forge === "string" ? input.forge : "", paths: Array.isArray(input.paths) ? input.paths : [] }); | |
| 30 | return ok({ share, others: copiesWords(copiesFor(app.db, repo, actor)) }); | |
| 31 | } | |
| 32 | ||
| 33 | /** What a copy here tells its origin: the person's choice, or nothing for a copy made before it (''). */ | |
| 34 | export function copyShareOf(app: App, copy: Pick<Repo, "id">): Share | undefined { | |
| 35 | const row = app.db.query<{ copy_share: string }, [string]>("SELECT copy_share FROM repo WHERE id = ?1").get(copy.id); | |
| 36 | return row === null || row.copy_share === "" ? undefined : shareOf(row.copy_share); | |
| 37 | } | |
| 38 | ||
| 39 | /** Set what a copy here tells its origin. */ | |
| 40 | export function setCopyShare(app: App, copy: Pick<Repo, "id">, share: Share): void { | |
| 41 | app.db.query("UPDATE repo SET copy_share = ?2 WHERE id = ?1").run(copy.id, share); | |
| 42 | } | |
| 43 | ||
| 44 | /** | |
| 45 | * Tell the copy's origin, as `actor`'s account there, what they chose to share (`copyShareOf`) and | |
| 46 | * the files `paths` their open work changes; nothing for a copy that chose nothing, or an origin | |
| 47 | * that is not a forge. Answers the line they may read of the others' copies, cleaned (it is another | |
| 48 | * forge's text); undefined when there is none or the origin did not answer. Never throws. | |
| 49 | */ | |
| 50 | export async function tellOrigin(app: App, actor: User, copy: Repo, mirror: Repo, paths: readonly string[] = []): Promise<string | undefined> { | |
| 51 | const share = copyShareOf(app, copy); | |
| 52 | if (share === undefined) return undefined; | |
| 53 | const through = writeThroughFor(app, actor, mirror); | |
| 54 | if (!through.ok || through.value === undefined || through.value.provider.tellCopy === undefined) return undefined; | |
| 55 | try { | |
| 56 | // A slow origin never holds the person's own answer: past `TELL_MS` the line is left unsaid. | |
| 57 | let timer: ReturnType<typeof setTimeout> | undefined; | |
| 58 | const late = new Promise<undefined>((resolve) => { | |
| 59 | timer = setTimeout(() => during("tell-origin-wait", () => resolve(undefined)), TELL_MS); | |
| 60 | }); | |
| 61 | const asked = through.value.provider.tellCopy(through.value.fullName, { share, forge: ownHost(app.config), paths: share === "none" ? [] : paths.slice(0, PATHS_MAX) }); | |
| 62 | const told = await Promise.race([asked, late]).finally(() => clearTimeout(timer)); | |
| 63 | if (told === undefined) return undefined; | |
| 64 | const said = told.ok ? (told.value.others ?? "").replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, " ").trim() : ""; | |
| 65 | return said === "" ? undefined : said; | |
| 66 | } catch { | |
| 67 | return undefined; | |
| 68 | } | |
| 69 | } |
src/actions/repos.ts +6 −1
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | 7 | import { mirrorCopyWords } from "./mirror_copy.ts"; |
| 8 | import { recordRefusal } from "../core/copies.ts"; | |
| 8 | 9 | import { retractBundles } from "../git/bundle_uri.ts"; |
| 9 | 10 | import { removeDrop } from "../drop/store.ts"; |
| 10 | 11 | import { getOriginById } from "../core/origins.ts"; |
| @@ -245,7 +246,11 @@ export async function forkRepo( | ||
| 245 | 246 | const proven = requireContributor(app, user.value); |
| 246 | 247 | if (!proven.ok) return proven; |
| 247 | 248 | const guarded = requireNewAccountGuard(app, user.value, parent); |
| 248 | if (!guarded.ok) return guarded; | |
| 249 | if (!guarded.ok) { | |
| 250 | // The owner's one quiet line: who tried and the rule that held it (`core/copies.ts`). | |
| 251 | recordRefusal(app.db, parent, user.value, "guard_new_accounts"); | |
This records a local new-account fork refusal, but the line reads 'tried to propose' from another forge. Align the words with the event. |
||
| 252 | return guarded; | |
| 253 | } | |
| 249 | 254 | // A guest forks to contribute: public parents only, always public, marked in |
| 250 | 255 | // the row's own write so the fork is never an ordinary one for a moment. |
| 251 | 256 | const contribution = !requireAbility(app, user.value, "make_it_yours").ok; |
src/contract/openapi/routes/index.ts +1
| @@ -375,6 +375,7 @@ export { route as postApiV1ReposOwnerNameChaptersChapterVerb } from "./postApiV1 | ||
| 375 | 375 | export { route as postApiV1ReposOwnerNameChecksRecheck } from "./postApiV1ReposOwnerNameChecksRecheck.ts"; |
| 376 | 376 | export { route as postApiV1ReposOwnerNameContents } from "./postApiV1ReposOwnerNameContents.ts"; |
| 377 | 377 | export { route as postApiV1ReposOwnerNameContribute } from "./postApiV1ReposOwnerNameContribute.ts"; |
| 378 | export { route as postApiV1ReposOwnerNameCopies } from "./postApiV1ReposOwnerNameCopies.ts"; | |
| 378 | 379 | export { route as postApiV1ReposOwnerNameDataEnvFileQuery } from "./postApiV1ReposOwnerNameDataEnvFileQuery.ts"; |
| 379 | 380 | export { route as postApiV1ReposOwnerNameDataImport } from "./postApiV1ReposOwnerNameDataImport.ts"; |
| 380 | 381 | export { route as postApiV1ReposOwnerNameDataMove } from "./postApiV1ReposOwnerNameDataMove.ts"; |
src/contract/openapi/routes/postApiV1ReposOwnerNameCopies.ts added +3
| @@ -0,0 +1,3 @@ | ||
| 1 | import { REPO, type Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { method: "post", path: `${REPO}/copies`, summary: "Tell a repository's origin of your copy on another forge", auth: true, role: "member", refuses: [401, 404] }; |
src/contract/tags.ts +1
| @@ -18,6 +18,7 @@ const ALIAS: Readonly<Record<string, string>> = { | ||
| 18 | 18 | "make-it-yours": "forks", |
| 19 | 19 | contribute: "forks", |
| 20 | 20 | offers: "forks", |
| 21 | copies: "forks", | |
| 21 | 22 | queue: "gates", |
| 22 | 23 | growth: "issues", |
| 23 | 24 | chapters: "issues", |
src/core/copies.ts added +238
| @@ -0,0 +1,238 @@ | ||
| 1 | /** | |
| 2 | * Together across forges: who keeps a copy of a repository on another forge, and the proposals from | |
| 3 | * there a rule held. Both are what an origin learns from the bringer's own forge (`POST | |
| 4 | * /api/v1/repos/:owner/:name/copies`, sent as the bringer's account) and from its own refusals, never | |
| 5 | * guessed. | |
| 6 | * | |
| 7 | * A bringer chooses what is told (`Share`): | |
| 8 | * - named: their name, their forge and the files their open work changes; | |
| 9 | * - counted, the default: that a copy exists and those files, never their name; | |
| 10 | * - none: nothing; no row is kept, and a copy told none before is forgotten at once. | |
| 11 | * A forge too old to send a choice is taken as none. | |
| 12 | * | |
| 13 | * Who reads what (`copiesFor`): a reader of the repository reads counts and files only; a writer and | |
| 14 | * the owner also read the names of copies told named, and the quiet line of each held proposal. A | |
| 15 | * stranger reads nothing (the caller's `canRead`). Bounded: at most `COPIES_MAX` copies and | |
| 16 | * `REFUSALS_MAX` held proposals a repository; a copy fades `FADE_MS` after its last report and a | |
| 17 | * held proposal after `REFUSAL_MS` (`pruneCopies`, on the forge's hourly prune). | |
| 18 | */ | |
| 19 | import type { Database } from "bun:sqlite"; | |
| 20 | import { id } from "../kernel/id.ts"; | |
| 21 | import { canWrite, type Repo } from "./repos.ts"; | |
| 22 | import { getUserById, isActive, type User } from "./users.ts"; | |
| 23 | ||
| 24 | export type Share = "named" | "counted" | "none"; | |
| 25 | export const SHARES: readonly Share[] = ["named", "counted", "none"]; | |
| 26 | /** What a new copy tells its origin unless its person picks otherwise. */ | |
| 27 | export const DEFAULT_SHARE: Share = "counted"; | |
| 28 | ||
| 29 | /** A choice as sent; anything else, or nothing (an older forge), is none. */ | |
| 30 | export const shareOf = (raw: unknown): Share => | |
| 31 | raw === "named" || raw === "counted" ? raw : "none"; | |
| 32 | ||
| 33 | export const COPIES_MAX = 200; | |
| 34 | export const REFUSALS_MAX = 50; | |
| 35 | /** The most files one copy's report names, and the longest path kept. */ | |
| 36 | export const PATHS_MAX = 50; | |
| 37 | export const PATH_CHARS = 300; | |
| 38 | export const FORGE_CHARS = 253; | |
| 39 | export const FADE_MS = 30 * 24 * 3_600_000; | |
| 40 | export const REFUSAL_MS = 7 * 24 * 3_600_000; | |
| 41 | ||
| 42 | /** The rules a held proposal is said by, as the owner's quiet line names them. */ | |
| 43 | export const HELD_BY: Readonly<Record<string, string>> = { | |
| 44 | guard_new_accounts: "held by the new-account rule", | |
| 45 | }; | |
| 46 | ||
| 47 | /** A copy's report, bounded: the files are repository paths, one line each. */ | |
| 48 | function cleanPaths(paths: readonly unknown[]): string[] { | |
| 49 | const out: string[] = []; | |
| 50 | for (const p of paths) { | |
| 51 | if ( | |
| 52 | typeof p !== "string" || | |
| 53 | p === "" || | |
| 54 | p.length > PATH_CHARS || | |
| 55 | /[\p{Cc}]/u.test(p) || | |
| 56 | p.startsWith("/") || | |
| 57 | p.split("/").includes("..") | |
| 58 | ) | |
| 59 | continue; | |
| 60 | if (!out.includes(p)) out.push(p); | |
| 61 | if (out.length >= PATHS_MAX) break; | |
| 62 | } | |
| 63 | return out; | |
| 64 | } | |
| 65 | ||
| 66 | /** | |
| 67 | * Keep what `user`'s copy of `repo` on `forge` tells: named or counted keeps (or refreshes) its row; | |
| 68 | * none forgets it. Past `COPIES_MAX` the copy reported longest ago goes. | |
| 69 | */ | |
| 70 | export function recordCopy( | |
| 71 | db: Database, | |
| 72 | repo: Pick<Repo, "id">, | |
| 73 | user: Pick<User, "id">, | |
| 74 | report: { | |
| 75 | readonly share: Share; | |
| 76 | readonly forge: string; | |
| 77 | readonly paths: readonly unknown[]; | |
| 78 | }, | |
| 79 | now = new Date(), | |
| 80 | ): void { | |
| 81 | if (report.share === "none") { | |
| 82 | db.query("DELETE FROM repo_copy WHERE repo_id = ?1 AND user_id = ?2").run( | |
| 83 | repo.id, | |
| 84 | user.id, | |
| 85 | ); | |
| 86 | return; | |
| 87 | } | |
| 88 | const at = now.toISOString(); | |
| 89 | const forge = report.forge.trim().toLowerCase().slice(0, FORGE_CHARS); | |
| 90 | db.transaction(() => { | |
| 91 | db.query( | |
| 92 | `INSERT INTO repo_copy (repo_id, user_id, share, forge, paths, brought_at, seen_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6) | |
| 93 | ON CONFLICT (repo_id, user_id) DO UPDATE SET share = excluded.share, forge = excluded.forge, paths = excluded.paths, seen_at = excluded.seen_at`, | |
| 94 | ).run( | |
| 95 | repo.id, | |
| 96 | user.id, | |
| 97 | report.share, | |
| 98 | forge, | |
| 99 | JSON.stringify(cleanPaths(report.paths)), | |
| 100 | at, | |
| 101 | ); | |
| 102 | db.query( | |
| 103 | `DELETE FROM repo_copy WHERE repo_id = ?1 AND user_id IN ( | |
| 104 | SELECT user_id FROM repo_copy WHERE repo_id = ?1 ORDER BY seen_at DESC, user_id LIMIT -1 OFFSET ?2)`, | |
| 105 | ).run(repo.id, COPIES_MAX); | |
| 106 | })(); | |
| 107 | } | |
| 108 | ||
| 109 | /** A proposal from another forge that `rule` held: one quiet row for the owner, kept a week. */ | |
| 110 | export function recordRefusal( | |
| 111 | db: Database, | |
| 112 | repo: Pick<Repo, "id">, | |
| 113 | user: Pick<User, "id">, | |
| 114 | rule: keyof typeof HELD_BY, | |
| 115 | now = new Date(), | |
| 116 | ): void { | |
| 117 | db.transaction(() => { | |
| 118 | db.query( | |
| 119 | "INSERT INTO repo_refusal (id, repo_id, user_id, rule, at) VALUES (?1, ?2, ?3, ?4, ?5)", | |
| 120 | ).run(id(), repo.id, user.id, rule, now.toISOString()); | |
| 121 | db.query( | |
| 122 | "DELETE FROM repo_refusal WHERE repo_id = ?1 AND id IN (SELECT id FROM repo_refusal WHERE repo_id = ?1 ORDER BY at DESC, id DESC LIMIT -1 OFFSET ?2)", | |
| 123 | ).run(repo.id, REFUSALS_MAX); | |
| 124 | })(); | |
| 125 | } | |
| 126 | ||
| 127 | /** The fade: copies not reported for `FADE_MS`, held proposals past `REFUSAL_MS`. Answers how many went. */ | |
| 128 | export function pruneCopies(db: Database, now = Date.now()): number { | |
| 129 | const copies = db | |
| 130 | .query("DELETE FROM repo_copy WHERE seen_at < ?1") | |
| 131 | .run(new Date(now - FADE_MS).toISOString()).changes; | |
| 132 | const refusals = db | |
| 133 | .query("DELETE FROM repo_refusal WHERE at < ?1") | |
| 134 | .run(new Date(now - REFUSAL_MS).toISOString()).changes; | |
| 135 | return copies + refusals; | |
| 136 | } | |
| 137 | ||
| 138 | export interface CopiesView { | |
| 139 | /** Copies elsewhere, the viewer's own left out. */ | |
| 140 | readonly count: number; | |
| 141 | /** Names of copies told named, for a writer or the owner; empty for anyone else. */ | |
| 142 | readonly named: readonly string[]; | |
| 143 | /** How many copies have open work, and the files it changes (bounded). */ | |
| 144 | readonly working: number; | |
| 145 | readonly paths: readonly string[]; | |
| 146 | /** Held proposals, for a writer or the owner: who, and the rule's words. */ | |
| 147 | readonly held: readonly { | |
| 148 | readonly who: string; | |
| 149 | readonly words: string; | |
| 150 | readonly at: string; | |
| 151 | }[]; | |
| 152 | } | |
| 153 | ||
| 154 | /** What `viewer`, a reader of `repo`, may read of its copies elsewhere and its held proposals. */ | |
| 155 | export function copiesFor( | |
| 156 | db: Database, | |
| 157 | repo: Repo, | |
| 158 | viewer: User, | |
| 159 | now = Date.now(), | |
| 160 | ): CopiesView { | |
| 161 | const since = new Date(now - FADE_MS).toISOString(); | |
| 162 | const rows = db | |
| 163 | .query< | |
| 164 | { user_id: string; share: string; paths: string }, | |
| 165 | [string, string, string] | |
| 166 | >(`SELECT user_id, share, paths FROM repo_copy WHERE repo_id = ?1 AND user_id <> ?2 AND seen_at >= ?3 ORDER BY seen_at DESC LIMIT ${String(COPIES_MAX)}`) | |
| 167 | .all(repo.id, viewer.id, since); | |
| 168 | const writes = canWrite(db, repo, viewer); | |
| 169 | const named: string[] = []; | |
| 170 | const paths: string[] = []; | |
| 171 | let working = 0; | |
| 172 | for (const r of rows) { | |
| 173 | let ps: string[] = []; | |
| 174 | try { | |
| 175 | ps = (JSON.parse(r.paths) as unknown[]).filter( | |
| 176 | (p): p is string => typeof p === "string", | |
| 177 | ); | |
| 178 | } catch { | |
| 179 | ps = []; | |
| 180 | } | |
| 181 | if (ps.length > 0) working++; | |
| 182 | for (const p of ps) | |
| 183 | if (!paths.includes(p) && paths.length < PATHS_MAX) paths.push(p); | |
| 184 | if (writes && r.share === "named") { | |
| 185 | const u = getUserById(db, r.user_id); | |
| 186 | if (u !== undefined && isActive(u)) named.push(u.username); | |
| 187 | } | |
| 188 | } | |
| 189 | const held = !writes | |
| 190 | ? [] | |
| 191 | : db | |
| 192 | .query<{ user_id: string; rule: string; at: string }, [string, string]>( | |
| 193 | "SELECT user_id, rule, at FROM repo_refusal WHERE repo_id = ?1 AND at >= ?2 ORDER BY at DESC LIMIT 3", | |
| 194 | ) | |
| 195 | .all(repo.id, new Date(now - REFUSAL_MS).toISOString()) | |
| 196 | .flatMap((r) => { | |
| 197 | const u = getUserById(db, r.user_id); | |
| 198 | const by = HELD_BY[r.rule]; | |
| 199 | return u === undefined || by === undefined | |
| 200 | ? [] | |
| 201 | : [ | |
| 202 | { | |
| 203 | who: u.username, | |
| 204 | words: `${u.username} tried to fork it; ${by}`, | |
| 205 | at: r.at, | |
| 206 | }, | |
| 207 | ]; | |
| 208 | }); | |
| 209 | return { count: rows.length, named, working, paths, held }; | |
| 210 | } | |
| 211 | ||
| 212 | /** | |
| 213 | * The together line's sentence for copies elsewhere: "2 people have copies elsewhere · 1 change | |
| 214 | * coming for src/valid.ts", with names for a writer where they were told; undefined for none. | |
| 215 | */ | |
| 216 | export function copiesWords(v: CopiesView): string | undefined { | |
| 217 | if (v.count === 0) return undefined; | |
| 218 | const others = v.count - v.named.length; | |
| 219 | const who = | |
| 220 | v.named.length === 0 | |
| 221 | ? v.count === 1 | |
| 222 | ? "1 person has a copy elsewhere" | |
| 223 | : `${String(v.count)} people have copies elsewhere` | |
| 224 | : `${[...v.named.slice(0, 2), ...(v.named.length > 2 ? [`${String(v.named.length - 2)} more`] : [])].join(", ")}${others === 0 ? "" : ` and ${String(others)} ${others === 1 ? "other" : "others"}`} ${v.count === 1 ? "has a copy" : "have copies"} elsewhere`; | |
| 225 | if (v.working === 0) return who; | |
| 226 | const files = | |
| 227 | v.paths.length === 1 | |
| 228 | ? v.paths[0]! | |
| 229 | : `${v.paths[0]!} and ${String(v.paths.length - 1)} more ${v.paths.length === 2 ? "file" : "files"}`; | |
| 230 | return `${who} · ${String(v.working)} ${v.working === 1 ? "change" : "changes"} coming for ${files}`; | |
| 231 | } | |
| 232 | ||
| 233 | /** Each choice in its own words, where the person picks it (the terminal's bring). */ | |
| 234 | export const SHARE_SHORT: Readonly<Record<Share, string>> = { | |
| 235 | counted: "Counted: files, never your name", | |
| 236 | named: "Named: your name too, to its writers", | |
| 237 | none: "None: nothing at all", | |
| 238 | }; |
src/core/migration-pins/20261125200000-copies-elsewhere.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | cbe1ad2db98ba64181a9e69882558a5abe737f5f27eba9523f83e45d89dfb361 |
src/core/migrations/20261125200000-copies-elsewhere.ts added +28
| @@ -0,0 +1,28 @@ | ||
| 1 | // Together across forges (core/copies.ts). On an origin: repo_copy, one row per account that keeps a | |
| 2 | // copy of a repository on another forge and chose to say so (share named or counted; none keeps no | |
| 3 | // row), with that forge's host and the files its open work changes, faded 30 days after its last | |
| 4 | // report; repo_refusal, one quiet row when a proposal from another forge was held by a rule, kept 7 | |
| 5 | // days. On a bringer's forge: repo.copy_share, what a copy tells its origin ('' for a copy made | |
| 6 | // before this, which tells nothing). Additive. | |
| 7 | export default ` | |
| 8 | CREATE TABLE IF NOT EXISTS repo_copy ( | |
| 9 | repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE, | |
| 10 | user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE, | |
| 11 | share TEXT NOT NULL CHECK (share IN ('named', 'counted')), | |
| 12 | forge TEXT NOT NULL DEFAULT '', | |
| 13 | paths TEXT NOT NULL DEFAULT '[]', | |
| 14 | brought_at TEXT NOT NULL, | |
| 15 | seen_at TEXT NOT NULL, | |
| 16 | PRIMARY KEY (repo_id, user_id) | |
| 17 | ); | |
| 18 | CREATE INDEX IF NOT EXISTS repo_copy_seen ON repo_copy (seen_at); | |
| 19 | CREATE TABLE IF NOT EXISTS repo_refusal ( | |
| 20 | id TEXT PRIMARY KEY, | |
| 21 | repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE, | |
| 22 | user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE, | |
| 23 | rule TEXT NOT NULL, | |
| 24 | at TEXT NOT NULL | |
| 25 | ); | |
| 26 | CREATE INDEX IF NOT EXISTS repo_refusal_repo ON repo_refusal (repo_id, at); | |
| 27 | ALTER TABLE repo ADD COLUMN copy_share TEXT NOT NULL DEFAULT ''; | |
| 28 | `; |
src/design/together.ts +34 −7
| @@ -13,6 +13,7 @@ import { audienceFilter } from "../core/event_audience.ts"; | ||
| 13 | 13 | import { listEvents, type ForgeEvent } from "../core/events.ts"; |
| 14 | 14 | import { getIssue, getIssueById } from "../core/issues.ts"; |
| 15 | 15 | import { usersHere } from "../core/presence.ts"; |
| 16 | import { copiesFor, copiesWords } from "../core/copies.ts"; | |
| 16 | 17 | import { canRead, canWrite, type Repo } from "../core/repos.ts"; |
| 17 | 18 | import { liveHasIt, PULL_CHECKS } from "../core/talk_work.ts"; |
| 18 | 19 | import { getUserById, isActive, type User } from "../core/users.ts"; |
| @@ -31,6 +32,13 @@ export interface Together { | ||
| 31 | 32 | readonly here?: { readonly names: readonly string[]; readonly words: string }; |
| 32 | 33 | /** The newest few things done on the repository, newest first, each with when (said by `agoWords`). */ |
| 33 | 34 | readonly lately: readonly { readonly id: string; readonly words: string; readonly at: string }[]; |
| 35 | /** | |
| 36 | * Copies on other forges (`core/copies.ts`): "2 people have copies elsewhere · 1 change coming for | |
| 37 | * src/valid.ts", names only for a writer and only where told; undefined for none. | |
| 38 | */ | |
| 39 | readonly elsewhere?: string; | |
| 40 | /** For a writer or the owner: proposals from another forge a rule held, one quiet line each. */ | |
| 41 | readonly held: readonly string[]; | |
| 34 | 42 | /** A change that landed on Live lately: said once by the page, and the one thing that moves the frame. */ |
| 35 | 43 | readonly landed?: { readonly id: string; readonly words: string; readonly number: number; readonly author: string; readonly mine: boolean }; |
| 36 | 44 | } |
| @@ -47,8 +55,14 @@ const people = (names: readonly string[]): string => | ||
| 47 | 55 | /** Readers counted and not named: "1 other is reading", "2 others are reading". */ |
| 48 | 56 | const reading = (n: number): string => (n === 1 ? "1 other is reading" : `${String(n)} others are reading`); |
| 49 | 57 | |
| 50 | /** What the together line says to `viewer` on `repo`, a repository they may read. */ | |
| 51 | export function togetherOf(db: Database, repo: Repo, viewer: User, now = Date.now()): Together { | |
| 58 | /** | |
| 59 | * What the together line says to `viewer` on `repo`, a repository they may read. `full` reads | |
| 60 | * the crew building, what was done lately and a landing; without it, only who is here, from the | |
| 61 | * forge's memory of open pages (a query only for each person here): what any page of a repository | |
| 62 | * but its home draws. `elsewhere` reads the copies on other forges and the held proposals | |
| 63 | * (`core/copies.ts`): the home's alone. | |
| 64 | */ | |
| 65 | export function togetherOf(db: Database, repo: Repo, viewer: User, now = Date.now(), full = true, elsewhere = full): Together { | |
| 52 | 66 | const readers = usersHere(db, repo.id, now) |
| 53 | 67 | .filter((id) => id !== viewer.id) |
| 54 | 68 | .flatMap((id) => { |
| @@ -58,27 +72,36 @@ export function togetherOf(db: Database, repo: Repo, viewer: User, now = Date.no | ||
| 58 | 72 | // On a public repository a reader is anyone signed in: only its writers are named. |
| 59 | 73 | const others = readers.filter((u) => repo.visibility !== "public" || canWrite(db, repo, u)).map((u) => u.username); |
| 60 | 74 | const counted = readers.length - others.length; |
| 61 | const building = db | |
| 75 | const building = !full | |
| 76 | ? [] | |
| 77 | : db | |
| 62 | 78 | .query<{ name: string; number: number | null }, [string]>( |
| 63 | 79 | "SELECT u.username AS name, i.number AS number FROM run r JOIN user u ON u.id = r.actor_id LEFT JOIN issue i ON i.id = r.issue_id WHERE r.repo_id = ?1 AND r.kind = 'agent' AND r.state = 'running' ORDER BY r.id DESC LIMIT 2", |
| 64 | 80 | ) |
| 65 | 81 | .all(repo.id) |
| 66 | 82 | .map((r) => `${r.name} is building${r.number === null ? "" : ` #${String(r.number)}`}`); |
| 83 | // Copies elsewhere: counts and files to a reader, names and held proposals to a writer. | |
| 84 | const away = elsewhere ? copiesFor(db, repo, viewer, now) : { count: 0, named: [], working: 0, paths: [], held: [] }; | |
| 85 | const copies = copiesWords(away); | |
| 67 | 86 | const said = [...(others.length === 0 ? [] : [people(others)]), ...(counted === 0 ? [] : [reading(counted)]), ...building]; |
| 68 | const events = listEvents(db, { repoId: repo.id, limit: 40, kinds: ["pull.opened", "pull.merged", "run.finished"] }); | |
| 87 | const events = !full ? [] : listEvents(db, { repoId: repo.id, limit: 40, kinds: ["pull.opened", "pull.merged", "run.finished"] }); | |
| 69 | 88 | const meant = audienceFilter(db, viewer, events); |
| 70 | 89 | const kept = events.filter((e) => meant(e) && (e.kind !== "run.finished" || (e.payload["kind"] === "check" && (e.payload["state"] === "ok" || e.payload["state"] === "failed")))); |
| 71 | 90 | const lately = kept.slice(0, LATELY).map((e) => ({ id: e.id, words: eventWords(db, repo, e), at: e.createdAt })); |
| 72 | 91 | const merged = kept.find((e) => e.kind === "pull.merged" && now - Date.parse(e.createdAt) < LANDED_NEWS_MS); |
| 73 | 92 | const number = typeof merged?.payload["number"] === "number" ? merged.payload["number"] : undefined; |
| 74 | 93 | const pull = number === undefined ? undefined : getIssue(db, repo.id, number); |
| 75 | const author = pull === undefined ? undefined : getUserById(db, pull.authorId)?.username; | |
| 94 | // A mirrored pull is its origin author's, never the account that keeps the mirror (#16437). | |
| 95 | const author = pull === undefined ? undefined : (pull.originAuthor ?? getUserById(db, pull.authorId)?.username); | |
| 96 | const mine = pull !== undefined && pull.originAuthor === null && pull.authorId === viewer.id; | |
| 76 | 97 | return { |
| 77 | 98 | ...(said.length === 0 ? {} : { here: { names: others, words: said.join(" · ") } }), |
| 78 | 99 | lately, |
| 100 | ...(copies === undefined ? {} : { elsewhere: copies }), | |
| 101 | held: away.held.map((h) => h.words), | |
| 79 | 102 | ...(merged === undefined || pull === undefined || author === undefined |
| 80 | 103 | ? {} |
| 81 | : { landed: { id: merged.id, number: pull.number, author, mine: pull.authorId === viewer.id, words: liveHasIt(pull.authorId === viewer.id ? "Your change" : `${author}'s change`) } }), | |
| 104 | : { landed: { id: merged.id, number: pull.number, author, mine, words: liveHasIt(mine ? "Your change" : `${author}'s change`) } }), | |
| 82 | 105 | }; |
| 83 | 106 | } |
| 84 | 107 | |
| @@ -90,6 +113,10 @@ function eventWords(db: Database, repo: Repo, e: ForgeEvent): string { | ||
| 90 | 113 | } |
| 91 | 114 | const number = typeof e.payload["number"] === "number" ? e.payload["number"] : undefined; |
| 92 | 115 | const pull = number === undefined ? undefined : getIssue(db, repo.id, number); |
| 116 | const what = pull === undefined ? "" : `: #${String(pull.number)} ${pull.title}`; | |
| 117 | // On a mirror the event's actor is the account that keeps it, not who did it: a pull opened there | |
| 118 | // is its origin author's, and who merged it there is not known here (#16437). | |
| 119 | if (pull?.originAuthor != null) return e.kind === "pull.opened" ? `${pull.originAuthor} ${eventVerb(e)}${what}` : `A pull request was merged${what}`; | |
| 93 | 120 | const who = eventActor(e, e.actorId === null ? undefined : getUserById(db, e.actorId)?.username); |
| 94 | return `${who} ${eventVerb(e)}${pull === undefined ? "" : `: #${String(pull.number)} ${pull.title}`}`; | |
| 121 | return `${who} ${eventVerb(e)}${what}`; | |
| 95 | 122 | } |
src/engine/duties.ts +8 −1
| @@ -13,6 +13,7 @@ | ||
| 13 | 13 | * list back (`takeBack`): the forge is then one thread that serves and works. |
| 14 | 14 | */ |
| 15 | 15 | |
| 16 | import { pruneCopies } from "../core/copies.ts"; | |
| 16 | 17 | import type { App } from "../app.ts"; |
| 17 | 18 | import { runModelReview } from "../actions/model_review.ts"; |
| 18 | 19 | import { expireCrewHolds } from "../actions/holds.ts"; |
| @@ -61,7 +62,13 @@ export function startDuties(app: App, options: { onWorker: boolean }): () => voi | ||
| 61 | 62 | // Estimates of "done" come due as time passes (#11955). |
| 62 | 63 | timers.push(setInterval(() => during("estimates-due", () => void settleDue(app.db), undefined, app), 300_000)); |
| 63 | 64 | // Outsider status links past their 90 days are freed on a slow tick (#15768). |
| 64 | timers.push(setInterval(() => during("outsider-status-prune", () => void pruneOutsiderStatus(app.db), undefined, app), 3_600_000)); | |
| 65 | // Copies elsewhere fade and held proposals expire on the same hourly prune (`core/copies.ts`). | |
| 66 | timers.push( | |
outdated
Comma expression inside void is hard to read; give pruneCopies its own during() entry. |
||
| 67 | setInterval(() => { | |
| 68 | during("outsider-status-prune", () => void pruneOutsiderStatus(app.db), undefined, app); | |
| 69 | during("copies-prune", () => void pruneCopies(app.db), undefined, app); | |
| 70 | }, 3_600_000), | |
| 71 | ); | |
| 65 | 72 | // An issue snoozed behind the Later gate comes back on its day (#13113). |
| 66 | 73 | timers.push(setInterval(() => during("gate-snooze", () => void returnSnoozed(app), undefined, app), 60_000)); |
| 67 | 74 | during("gate-snooze", () => void returnSnoozed(app), undefined, app); |
src/http/api/upstream.ts +13
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | import { DELETING_SAYS } from "../../core/repo_deleting.ts"; |
| 10 | 10 | import { nestedForks } from "../../actions/fork_nested.ts"; |
| 11 | 11 | import { forksSince } from "../../core/repos.ts"; |
| 12 | import { reportCopy } from "../../actions/copies.ts"; | |
| 12 | 13 | import { forkRepo, FORKS_PER_DAY, repositoryLimitMessage } from "../../actions/repos.ts"; |
| 13 | 14 | import { |
| 14 | 15 | checkUpstreamNow, |
| @@ -145,6 +146,18 @@ export function upstreamRoutes(router: Router<Handler>): void { | ||
| 145 | 146 | }); |
| 146 | 147 | }); |
| 147 | 148 | |
| 149 | // Another forge tells this one, as the bringer's account, of their copy (`actions/copies.ts`). | |
| 150 | router.add("POST", "/api/v1/repos/:owner/:name/copies", async (ctx) => { | |
| 151 | const denied = requireScope(ctx, "rw"); | |
| 152 | if (denied) return denied; | |
| 153 | const repo = loadRepo(ctx); | |
| 154 | if (!repo) return notFound(); | |
| 155 | const input = await body(ctx.request); | |
| 156 | const told = reportCopy(ctx.app, ctx.auth.user, repo, { share: input.share, forge: input.forge, paths: input.paths }); | |
| 157 | if (!told.ok) return told.error === "not_found" ? notFound() : respondAccess(told.error, 422); | |
| 158 | return json({ share: told.value.share, ...(told.value.others === undefined ? {} : { others: told.value.others }) }); | |
| 159 | }); | |
| 160 | ||
| 148 | 161 | router.add("POST", "/api/v1/repos/:owner/:name/forks", async (ctx) => { |
| 149 | 162 | const denied = requireScope(ctx, "rw"); |
| 150 | 163 | if (denied) return denied; |
src/http/mcp/tools/bring.ts +4 −2
| @@ -3,19 +3,21 @@ import { good, bad, str, type Tool } from "../shared.ts"; | ||
| 3 | 3 | |
| 4 | 4 | export const tool: Tool = { |
| 5 | 5 | name: "bring", |
| 6 | description: "Bring in `repo` (link, or owner/name on `origin`) to work on.", | |
| 6 | description: "Bring `repo` (link, or owner/name on `origin`) to work on; `share` tells the origin: counted (default), named, none.", | |
| 7 | 7 | inputSchema: { |
| 8 | 8 | type: "object", |
| 9 | 9 | properties: { |
| 10 | 10 | repo: { type: "string", maxLength: 300 }, |
| 11 | 11 | origin: { type: "string", maxLength: 300 }, |
| 12 | share: { type: "string", enum: ["counted", "named", "none"] }, | |
| 12 | 13 | }, |
| 13 | 14 | required: ["repo"], |
| 14 | 15 | }, |
| 15 | 16 | writes: true, |
| 16 | 17 | async run(ctx, user, args) { |
| 17 | 18 | const origin = str(args["origin"]); |
| 18 | const brought = await bringToWork(ctx.app, user, { repo: str(args["repo"]), ...(origin === "" ? {} : { origin }) }); | |
| 19 | const share = str(args["share"]); | |
| 20 | const brought = await bringToWork(ctx.app, user, { repo: str(args["repo"]), ...(origin === "" ? {} : { origin }), ...(share === "named" || share === "counted" || share === "none" ? { share } : {}) }); | |
| 19 | 21 | if (!brought.ok) return bad(brought.error.kind === "unauthorized" ? "forbidden" : brought.error.kind, bringWords(brought.error)); |
| 20 | 22 | const b = brought.value; |
| 21 | 23 | const at = (r: { ownerName: string; name: string }) => `/${r.ownerName}/${r.name}`; |
src/http/server.ts +2 −2
| @@ -5,7 +5,7 @@ | ||
| 5 | 5 | * verdict. Auth is resolved once per request and handed to handlers as data. |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | import { togetherFragment } from "../web/together.ts"; | |
| 8 | import { togetherFragment, togetherLine, togethernessOf } from "../web/together.ts"; | |
| 9 | 9 | import { outsiderStatusPage } from "./offer_routes.ts"; |
| 10 | 10 | import { standingFragment } from "../web/pages/fork-standing.ts"; |
| 11 | 11 | import { carrySent, InvalidJson } from "./json_body.ts"; |
| @@ -1716,7 +1716,7 @@ export function buildRouter(): Router<Handler> { | ||
| 1716 | 1716 | // Live event stream for a repo the viewer can read. |
| 1717 | 1717 | // Everything the viewer may see, live. Pages with live regions listen here. |
| 1718 | 1718 | router.add("GET", "/events", (ctx) => |
| 1719 | viewerStream(ctx.app, ctx.auth.user, ctx.request), | |
| 1719 | viewerStream(ctx.app, ctx.auth.user, ctx.request, (repo, viewer, as) => togetherLine(ctx.app.db, repo, viewer, togethernessOf(as)).text), | |
| 1720 | 1720 | ); |
| 1721 | 1721 | |
| 1722 | 1722 | router.add("GET", "/:owner/:name/stream", (ctx) => { |
src/http/sse.ts +20 −6
| @@ -209,6 +209,11 @@ export function viewerStream( | ||
| 209 | 209 | app: App, |
| 210 | 210 | viewer: User | undefined, |
| 211 | 211 | request: Request, |
| 212 | /** | |
| 213 | * The together line for a reader, as HTML (the web's `togetherLine`, handed in by the route so | |
| 214 | * this layer draws nothing): what a `together` frame carries. Absent, no frame is sent. | |
| 215 | */ | |
| 216 | render?: (repo: NonNullable<ReturnType<typeof getRepoById>>, viewer: User, as: string) => string, | |
| 212 | 217 | ): Response { |
| 213 | 218 | const seen = new Map<string, boolean>(); |
| 214 | 219 | const visible = (repoId: string): boolean => { |
| @@ -239,10 +244,17 @@ export function viewerStream( | ||
| 239 | 244 | const here = hereOf(app, viewer, request); |
| 240 | 245 | return eventStream(app, request, (emit, _close, ready) => { |
| 241 | 246 | // The page is on a repository its viewer may read (`?here=owner/name`): a seat on its together |
| 242 | // line while this stream is open, proved read every `PING_MS`. Someone else coming or going is | |
| 243 | // told as a `presence.changed` frame with no id: it is not history, and never replayed. | |
| 247 | // line while this stream is open, proved read every `PING_MS`. The line itself rides the stream | |
| 248 | // as a `together` frame, rendered for this reader alone (only the names they may see): once as | |
| 249 | // the stream opens, and again whenever someone comes or goes. No id: it is not history. | |
| 250 | const line = (): void => { | |
| 251 | if (here === undefined || viewer === undefined) return; | |
| 252 | const repo = getRepoById(app.db, here.repo.id); | |
| 253 | if (repo === undefined || !canRead(app.db, repo, viewer)) return; | |
| 254 | if (render !== undefined) emit("together", { repo: here.name, html: render(repo, viewer, here.as) }); | |
| 255 | }; | |
| 244 | 256 | const seat = here === undefined ? undefined : takeSeat(app.db, here.repo.id, here.userId, () => { |
| 245 | if (ready()) emit("forge", { kind: "presence.changed", repo: here.name, payload: {} }); | |
| 257 | if (ready()) line(); | |
| 246 | 258 | }); |
| 247 | 259 | const pinging = seat === undefined || here === undefined ? undefined : setInterval(() => during("presence-ping", () => { |
| 248 | 260 | if (ready()) stillHere(app.db, here.repo.id, seat.key); |
| @@ -289,6 +301,7 @@ export function viewerStream( | ||
| 289 | 301 | for (const event of missed) |
| 290 | 302 | if (meant(event)) send(event, false); |
| 291 | 303 | } |
| 304 | line(); | |
| 292 | 305 | return () => { |
| 293 | 306 | gone.abort(); |
| 294 | 307 | unsubscribe(); |
| @@ -302,12 +315,13 @@ export function viewerStream( | ||
| 302 | 315 | * The repository a page says it is on (`?here=owner/name`), when its viewer is a signed-in, active |
| 303 | 316 | * person (never an agent: the crew shows as what it builds) who may read it; anyone else takes no seat. |
| 304 | 317 | */ |
| 305 | function hereOf(app: App, viewer: User | undefined, request: Request): { repo: NonNullable<ReturnType<typeof getRepo>>; name: string; userId: string } | undefined { | |
| 306 | const asked = new URL(request.url).searchParams.get("here") ?? ""; | |
| 318 | function hereOf(app: App, viewer: User | undefined, request: Request): { repo: NonNullable<ReturnType<typeof getRepo>>; name: string; userId: string; as: string } | undefined { | |
| 319 | const query = new URL(request.url).searchParams; | |
| 320 | const asked = query.get("here") ?? ""; | |
| 307 | 321 | const [owner, name, extra] = asked.split("/"); |
| 308 | 322 | if (viewer === undefined || viewer.kind !== "user" || !isActive(viewer) || owner === undefined || name === undefined || extra !== undefined) return undefined; |
| 309 | 323 | const repo = getRepo(app.db, owner, name); |
| 310 | return repo === undefined || !canRead(app.db, repo, viewer) ? undefined : { repo, name: `${repo.ownerName}/${repo.name}`, userId: viewer.id }; | |
| 324 | return repo === undefined || !canRead(app.db, repo, viewer) ? undefined : { repo, name: `${repo.ownerName}/${repo.name}`, userId: viewer.id, as: (query.get("as") ?? "").slice(0, 8) }; | |
| 311 | 325 | } |
| 312 | 326 | |
| 313 | 327 | export function sseStream( |
src/origins/providers/forge.ts +10
| @@ -248,6 +248,16 @@ export class ForgeProvider extends ForgejoProvider { | ||
| 248 | 248 | return succeed(this.repoFrom(result.value.data, undefined)); |
| 249 | 249 | } |
| 250 | 250 | |
| 251 | /** A copy here, told to the forge it came from (`POST …/copies`); an older forge answers 404. */ | |
| 252 | async tellCopy(fullName: string, report: { readonly share: "named" | "counted" | "none"; readonly forge: string; readonly paths: readonly string[] }): Promise<ProviderResult<{ readonly others?: string }>> { | |
| 253 | const base = this.repoPath(fullName); | |
| 254 | if (base === undefined) return fail("not_found", `not a repository name: ${fullName}`); | |
| 255 | const result = await this.api.call({ path: `${base}/copies`, method: "POST", body: report }); | |
| 256 | if (!result.ok) return result; | |
| 257 | const others = asString(field(result.value.data, "others")); | |
| 258 | return succeed(others === "" ? {} : { others: others.slice(0, 300) }); | |
| 259 | } | |
| 260 | ||
| 251 | 261 | /** The forks there, in a forge's own JSON and cursor pages. */ |
| 252 | 262 | override async listForks(fullName: string): Promise<ProviderResult<readonly RemoteRepo[]>> { |
| 253 | 263 | const base = this.repoPath(fullName); |
src/origins/types.ts +6
| @@ -567,6 +567,12 @@ export interface Provider { | ||
| 567 | 567 | * `forbidden` and nothing changed. |
| 568 | 568 | */ |
| 569 | 569 | archiveRepo(fullName: string): Promise<ProviderResult<void>>; |
| 570 | /** | |
| 571 | * Tell the origin, as this account, of its copy here (`core/copies.ts`): what the person chose to | |
| 572 | * share, this forge's host and the files their open work changes. Answers the line they may read | |
| 573 | * of the others' copies. Another forge only; an origin without it is never told. | |
| 574 | */ | |
| 575 | tellCopy?(fullName: string, report: { readonly share: "named" | "counted" | "none"; readonly forge: string; readonly paths: readonly string[] }): Promise<ProviderResult<{ readonly others?: string }>>; | |
| 570 | 576 | /** One page of the repositories this token sees archived. Forgejo and Gitea only. */ |
| 571 | 577 | listArchived?(options: { |
| 572 | 578 | query: string; |
src/tui/screens/bringwork.ts +19 −6
| @@ -8,7 +8,8 @@ | ||
| 8 | 8 | import { bringToWork, bringWords, broughtWords } from "../../actions/bring.ts"; |
| 9 | 9 | import type { Ctx, Screen } from "../app/app.ts"; |
| 10 | 10 | import type { Session } from "../session.ts"; |
| 11 | import { promptScreen } from "./common.ts"; | |
| 11 | import { later, pickerScreen, promptScreen, runAsync } from "./common.ts"; | |
| 12 | import { DEFAULT_SHARE, SHARE_SHORT, SHARES } from "../../core/copies.ts"; | |
| 12 | 13 | |
| 13 | 14 | export function bringWorkScreen(f: Session, ctx: Ctx, parent: Screen): Screen { |
| 14 | 15 | return promptScreen(ctx, parent, { |
| @@ -18,11 +19,23 @@ export function bringWorkScreen(f: Session, ctx: Ctx, parent: Screen): Screen { | ||
| 18 | 19 | hint: "Kept on GitHub or another forge you connected. It stays private here; the origin is unchanged.", |
| 19 | 20 | onSubmit: (repo) => { |
| 20 | 21 | if (repo.trim() === "") return "Paste the link, or owner/name."; |
| 21 | ctx.toast(`Bringing ${repo.trim()} in…`); | |
| 22 | return bringToWork(f.app, f.user, { repo }).then((brought) => { | |
| 23 | ctx.toast(brought.ok ? broughtWords(brought.value) : bringWords(brought.error), brought.ok ? "success" : "danger"); | |
| 24 | if (brought.ok) ctx.pop(); | |
| 25 | }); | |
| 22 | // What the origin hears of the copy, in each choice's own words (`core/copies.ts`). | |
| 23 | return later(ctx, () => | |
| 24 | pickerScreen(ctx, parent, { | |
| 25 | title: "What the origin hears of your copy", | |
| 26 | // Counted first, the default: Enter takes it. | |
| 27 | items: [DEFAULT_SHARE, ...SHARES.filter((s) => s !== DEFAULT_SHARE)].map((s) => ({ id: s, label: SHARE_SHORT[s] })), | |
| 28 | onPick: ([picked]) => { | |
| 29 | const share = SHARES.find((s) => s === picked) ?? DEFAULT_SHARE; | |
| 30 | ctx.toast(`Bringing ${repo.trim()} in…`); | |
| 31 | runAsync(ctx, () => | |
| 32 | bringToWork(f.app, f.user, { repo, share }).then((brought) => { | |
| 33 | ctx.toast(brought.ok ? broughtWords(brought.value) : bringWords(brought.error), brought.ok ? "success" : "danger"); | |
| 34 | }), | |
| 35 | ); | |
| 36 | }, | |
| 37 | }), | |
| 38 | ); | |
| 26 | 39 | }, |
| 27 | 40 | }); |
| 28 | 41 | } |
src/tui/screens/talk_chats.ts +1 −1
| @@ -266,7 +266,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr | ||
| 266 | 266 | paneInfo(f.app.db, ws.repo, ws.shows), |
| 267 | 267 | ...(fell === undefined ? [] : [fell]), |
| 268 | 268 | // Who else is here and what was done lately, in the page's words (`togetherOf`). |
| 269 | ...((t) => [...(t.here === undefined ? [] : [`Here: ${t.here.words}`]), ...(t.lately.length === 0 ? [] : [`Lately: ${t.lately.map((l) => `${l.words} · ${agoWords(l.at, Date.now())}`).join(" · ")}`]), ...(t.landed === undefined ? [] : [`${t.landed.words} (L shows Live)`])])(togetherOf(f.app.db, ws.repo, f.user)), | |
| 269 | ...((t) => [...(t.here === undefined ? [] : [`Here: ${t.here.words}`]), ...(t.lately.length === 0 ? [] : [`Lately: ${t.lately.map((l) => `${l.words} · ${agoWords(l.at, Date.now())}`).join(" · ")}`]), ...(t.elsewhere === undefined ? [] : [`Elsewhere: ${t.elsewhere}`]), ...t.held, ...(t.landed === undefined ? [] : [`${t.landed.words} (L shows Live)`])])(togetherOf(f.app.db, ws.repo, f.user)), | |
| 270 | 270 | "o picks the repository, w the version, l a path, L Live.", |
| 271 | 271 | "", |
| 272 | 272 | url === undefined ? "Nothing running yet." : `Preview: ${url}`, |
src/web/chrome.ts +7 −1
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | * `ui.ts` may not. That is the line between the two files. |
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | import { togetherHtml } from "./together.ts"; | |
| 11 | 12 | import { repoOnRequest } from "../http/request_repo.ts"; |
| 12 | 13 | import { hereAddress, returnTo, withReturn } from "./return_to.ts"; |
| 13 | 14 | import { MACHINE_PREFIX, typedMiss } from "../http/asset_miss.ts"; |
| @@ -213,6 +214,11 @@ export { repoPalette }; | ||
| 213 | 214 | export type { RepoTab }; |
| 214 | 215 | |
| 215 | 216 | export interface RepoHeaderOptions { |
| 217 | /** | |
| 218 | * The together line under the header in full (who is here, the crew, what was done lately, a | |
| 219 | * landing): the repository's home. Elsewhere it draws only who is here, which reads no table. | |
| 220 | */ | |
| 221 | together?: "full"; | |
| 216 | 222 | /** Rendered at the right of the title line (fork, clone, watch). */ |
| 217 | 223 | actions?: Html; |
| 218 | 224 | /** Suppress the description/lineage block on deep pages. */ |
| @@ -360,7 +366,7 @@ export function scopeHeader( | ||
| 360 | 366 | )} |
| 361 | 367 | ${studio ? studioOriginNote(repo) : options.quiet ? null : whereRow(ctx, scope)} |
| 362 | 368 | ${repoNav(items)} |
| 363 | </header>`; | |
| 369 | </header>${repo === undefined || scope.kind !== "local" || ctx.auth.user === undefined ? null : togetherHtml(ctx.app.db, repo, ctx.auth.user, options.together === "full" ? "full" : "here")}`; | |
| 364 | 370 | } |
| 365 | 371 | |
| 366 | 372 | /** The siblings the viewer may read, and whether they own a node in `parent`'s tree to land on. */ |
src/web/client.ts +5 −1
| @@ -2562,7 +2562,7 @@ export const liveRegionsJs = /* js */ ` | ||
| 2562 | 2562 | // A page on a repository says so (data-presence): the stream takes a seat on its together line. |
| 2563 | 2563 | var on = document.querySelector ? document.querySelector('[data-presence]') : null; |
| 2564 | 2564 | here = on ? on.getAttribute('data-presence') : ''; |
| 2565 | var seat = here ? 'here=' + encodeURIComponent(here) : ''; | |
| 2565 | var seat = here ? 'here=' + encodeURIComponent(here) + (on.getAttribute('data-presence-as') ? '&as=' + on.getAttribute('data-presence-as') : '') : ''; | |
| 2566 | 2566 | source = since ? new EventSource('/events?since=' + encodeURIComponent(since) + (seat ? '&' + seat : '')) : seat ? new EventSource('/events?' + seat) : new EventSource('/events'); |
| 2567 | 2567 | source.addEventListener('open', function () { state('open'); }); |
| 2568 | 2568 | source.addEventListener('error', function () { |
| @@ -2570,6 +2570,10 @@ export const liveRegionsJs = /* js */ ` | ||
| 2570 | 2570 | if (source.readyState === 2 && retry === null) retry = setTimeout(connect, 3000); |
| 2571 | 2571 | }); |
| 2572 | 2572 | source.addEventListener('forge', onForge); |
| 2573 | source.addEventListener('together', function (e) { | |
| 2574 | var d = JSON.parse(e.data), el = document.getElementById('together'); | |
| 2575 | if (el && el.getAttribute('data-presence') === d.repo) { el.innerHTML = d.html; el.dispatchEvent(new CustomEvent('forge:swapped', { bubbles: true })); } | |
| 2576 | }); | |
| 2573 | 2577 | // New lines of a run's log: not history, so no id to resume from. Handed |
| 2574 | 2578 | // to whoever tails a run on this page (\`appTailJs\`). |
| 2575 | 2579 | source.addEventListener('run.log', function (event) { |
src/web/pages/repo.ts +4 −6
| @@ -8,7 +8,6 @@ | ||
| 8 | 8 | * path segment and can never smuggle a path of its own. |
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | import { togetherHtml } from "../together.ts"; | |
| 12 | 11 | import { DELETING_SAYS } from "../../core/repo_deleting.ts"; |
| 13 | 12 | import { downloadHeaders } from "../../drop/store.ts"; |
| 14 | 13 | import type { BlobForRender } from "../../git/read.ts"; |
| @@ -98,7 +97,7 @@ import { blobHoldsPrivateKey, holdsPrivateKey, PRIVATE_KEY_NOTICE } from "../../ | ||
| 98 | 97 | import { countLines, highlightPrefix } from "../code.ts"; |
| 99 | 98 | import { tailOf, tailSentence } from "../log_tail.ts"; |
| 100 | 99 | import { latestWave } from "../../story/waves.ts"; |
| 101 | import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts"; | |
| 100 | import { notePhase, takeSessionTime, timePhaseAsync } from "../../core/route_timing.ts"; | |
| 102 | 101 | import { liveClientJs, liveMount } from "../live.ts"; |
| 103 | 102 | import { appStrip } from "./apps.ts"; |
| 104 | 103 | import { growthBody, isAdmin } from "./growth_panel.ts"; |
| @@ -1552,7 +1551,7 @@ async function codeHome(ctx: Ctx, repo: Repo, appOf: { readonly isApp: boolean; | ||
| 1552 | 1551 | |
| 1553 | 1552 | if (refs.branches.length === 0) { |
| 1554 | 1553 | const emptyRendering = performance.now(); |
| 1555 | const body = html`${scopeHeader(ctx, scope, "code")}${archivedLine(ctx, repo)}${walletLine(ctx, repo)}${reportLine(ctx, repo)}${movedLine(ctx, repo)}${noApp} | |
| 1554 | const body = html`${scopeHeader(ctx, scope, "code", { together: "full" })}${archivedLine(ctx, repo)}${walletLine(ctx, repo)}${reportLine(ctx, repo)}${movedLine(ctx, repo)}${noApp} | |
| 1556 | 1555 | <div class="mt"> |
| 1557 | 1556 | ${empty({ |
| 1558 | 1557 | icon: "repo", |
| @@ -1628,15 +1627,14 @@ async function codeHome(ctx: Ctx, repo: Repo, appOf: { readonly isApp: boolean; | ||
| 1628 | 1627 | creditLine(ctx, repo, scope.source, ref), |
| 1629 | 1628 | ); |
| 1630 | 1629 | const standing = await timePhaseAsync(ctx.request, "behind", () => standingRegion(ctx, repo)); |
| 1631 | // Who else is here and what was done lately: a signed-in reader's live line (`web/together.ts`). | |
| 1632 | const together = ctx.auth.user === undefined ? null : timePhase(ctx.request, "together", () => togetherHtml(ctx.app.db, repo, ctx.auth.user!)); | |
| 1633 | 1630 | const gets = repo.template ? await timePhaseAsync(ctx.request, "template", () => templateCard(ctx.app, repo)) : null; |
| 1634 | 1631 | const offersHere = forkOffers(ctx.app.db, repo, ctx.auth.user); |
| 1635 | 1632 | const sizes = await offerSizes(ctx.app, repo, offersHere.map((o) => o.number)); |
| 1636 | 1633 | const rendering = performance.now(); |
| 1637 | 1634 | const body = html`${scopeHeader(ctx, scope, "code", { |
| 1638 | 1635 | branchCount: refs.branches.length, |
| 1639 | })}${credit}${together}${standing}${archivedLine(ctx, repo)}${walletLine(ctx, repo)}${reportLine(ctx, repo)}${movedLine(ctx, repo)}${noApp}${gets} | |
| 1636 | together: "full", | |
| 1637 | })}${credit}${standing}${archivedLine(ctx, repo)}${walletLine(ctx, repo)}${reportLine(ctx, repo)}${movedLine(ctx, repo)}${noApp}${gets} | |
| 1640 | 1638 | ${offerUpstream(repo, parent, offer)} |
| 1641 | 1639 | ${forkOffersCard(repo, offersHere, sizes)} |
| 1642 | 1640 | ${parent === undefined ? "" : sentOffersCard(repo, parent, sentOffers(ctx.app.db, repo, ctx.auth.user))} |
src/web/pages/talk_preview.ts +1 −1
| @@ -130,7 +130,7 @@ export async function talkPane(ctx: Ctx, user: User, name: string | undefined, w | ||
| 130 | 130 | ${url === undefined ? null : btn(icon("external"), { href: url, label: `Open ${name} on its own`, title: "Open on its own", variant: "ghost", external: true, extra: "btn-icon" })} |
| 131 | 131 | </div> |
| 132 | 132 | <p class="talk-pane-info small muted" data-pane-info>${paneInfo(ctx.app.db, ws.repo, ws.shows)}${ws.shows === undefined ? null : html` · <a href="/${name}/pulls/${String(ws.shows)}">the pull</a>`}</p> |
| 133 | ${togetherHtml(ctx.app.db, ws.repo, user, `?pane=preview&repo=${encodeURIComponent(name)}&show=live`)} | |
| 133 | ${togetherHtml(ctx.app.db, ws.repo, user, "live")} | |
| 134 | 134 | ${fellLine} |
| 135 | 135 | ${panel} |
| 136 | 136 | </aside>`, |
src/web/together.ts +53 −35
| @@ -18,55 +18,73 @@ import { notePhase, takeSessionTime } from "../core/route_timing.ts"; | ||
| 18 | 18 | import { html, type Html } from "./html.ts"; |
| 19 | 19 | import { fragment } from "./layout.ts"; |
| 20 | 20 | |
| 21 | /** Where See Live goes from the line in Talk's pane: the pane's own Live view of `name`. */ | |
| 22 | export const talkLiveHref = (name: string): string => `?pane=preview&repo=${encodeURIComponent(name)}&show=live`; | |
| 23 | ||
| 21 | 24 | /** |
| 22 | * The region, for `viewer` on `repo` (a repository they may read). `live` is where See Live goes, and | |
| 23 | * Talk's pane passes it: there the script also dismisses the landing line; elsewhere it is plain. | |
| 25 | * The region's box, around `line`. `as` is how much it draws (`Togetherness`), and how its stream | |
| 26 | * (`?here=&as=`) and its swap ask for it again: the stream sends the line as a `together` frame when | |
| 27 | * it opens and when someone comes or goes; work moving (`pull.*`, `run.*`) reads it again. | |
| 24 | 28 | */ |
| 25 | export function togetherHtml( | |
| 26 | db: Parameters<typeof togetherOf>[0], | |
| 27 | repo: Repo, | |
| 28 | viewer: User, | |
| 29 | live?: string, | |
| 30 | ): Html { | |
| 31 | const now = Date.now(); | |
| 32 | const t = togetherOf(db, repo, viewer, now); | |
| 33 | const name = `${repo.ownerName}/${repo.name}`; | |
| 29 | function region(name: string, line: Html, as: Togetherness): Html { | |
| 34 | 30 | return html`<div |
| 35 | 31 | class="together" |
| 36 | 32 | id="together" |
| 37 | data-live="presence.*,pull.*,run.*" | |
| 33 | data-live="pull.*,run.*" | |
| 38 | 34 | data-live-repo="${name}" |
| 39 | data-live-src="/${name}/together" | |
| 40 | data-presence="${name}" | |
| 41 | > | |
| 42 | ${t.here === undefined | |
| 35 | data-live-src="/${name}/together${as === "full" ? "" : `?as=${as}`}" | |
| 36 | data-presence="${name}"${as === "full" ? null : html` data-presence-as="${as}"`} | |
| 37 | >${line}</div>`; | |
| 38 | } | |
| 39 | ||
| 40 | /** | |
| 41 | * The line itself, for `viewer` on `repo` (a repository they may read): who else is here, what | |
| 42 | * was done lately, a landing. `live`: in Talk's pane, with See Live and Dismiss. Also what a | |
| 43 | * `together` frame carries (`http/sse.ts`), rendered for that frame's reader alone. | |
| 44 | */ | |
| 45 | export function togetherLine(db: Parameters<typeof togetherOf>[0], repo: Repo, viewer: User, as: Togetherness = "full"): Html { | |
| 46 | const now = Date.now(); | |
| 47 | // Copies elsewhere and held proposals are the repository home's alone (its page budget has room). | |
| 48 | const t = togetherOf(db, repo, viewer, now, as !== "here", as === "full"); | |
| 49 | const name = `${repo.ownerName}/${repo.name}`; | |
| 50 | const see = as === "live" ? talkLiveHref(name) : undefined; | |
| 51 | return html`${t.here === undefined | |
| 43 | 52 | ? null |
| 44 | 53 | : html`<p class="together-here small muted">${t.here.words}</p>`}${t.lately.length === 0 |
| 45 | 54 | ? null |
| 46 | 55 | : html`<p class="together-lately small muted"> |
| 47 | 56 | <span class="sr-only">Lately: </span>${t.lately.map((l, i) => html`${i === 0 ? null : "; "}<span>${l.words} · ${time(l.at, { text: agoWords(l.at, now) })}</span>`)} |
| 48 | </p>`}${t.landed === undefined | |
| 57 | </p>`}${t.elsewhere === undefined ? null : html`<p class="together-elsewhere small muted">${t.elsewhere}</p>`}${t.held.map((h) => html`<p class="together-held small muted">${h}</p>`)}${t.landed === undefined | |
| 49 | 58 | ? null |
| 50 | : html`<p | |
| 51 | class="together-landed small" | |
| 52 | role="status" | |
| 53 | data-landed="${t.landed.id}" | |
| 54 | > | |
| 55 | ${t.landed.words}${live === undefined | |
| 59 | : html`<p class="together-landed small" role="status" data-landed="${t.landed.id}"> | |
| 60 | ${t.landed.words}${see === undefined ? null : html` <a href="${see}">See Live</a>`}${t.landed.mine | |
| 56 | 61 | ? null |
| 57 | : html` <a href="${live}">See Live</a>`}${t.landed.mine | |
| 58 | ? null | |
| 59 | : html` <a | |
| 60 | href="/${name}/pulls/${String(t.landed.number)}#comment-body" | |
| 61 | data-reply="/${name}/pulls/${String(t.landed.number)}" | |
| 62 | data-reply-to="${t.landed.author}" | |
| 63 | >Reply to ${t.landed.author}</a | |
| 64 | >`} | |
| 65 | ${live === undefined ? null : html` <button class="btn js-only" data-size="sm" data-variant="ghost" type="button" data-landed-off>Dismiss</button>`} | |
| 66 | </p>`} | |
| 67 | </div>`; | |
| 62 | : html` <a href="/${name}/pulls/${String(t.landed.number)}#comment-body" data-reply="/${name}/pulls/${String(t.landed.number)}" data-reply-to="${t.landed.author}">Reply to ${t.landed.author}</a>`} | |
| 63 | ${see === undefined ? null : html` <button class="btn js-only" data-size="sm" data-variant="ghost" type="button" data-landed-off>Dismiss</button>`} | |
| 64 | </p>`}`; | |
| 68 | 65 | } |
| 69 | 66 | |
| 67 | /** | |
| 68 | * The region drawn with its line, for `viewer` on `repo` (Talk's pane: `live`), so the page has | |
| 69 | * it with JavaScript off. `full` (the repository's home, Talk's pane) draws all of it; elsewhere | |
| 70 | * (every other page of a repository, under its header) only who is here, which reads no table: | |
| 71 | * the page's stream then brings the rest and keeps it current. | |
| 72 | */ | |
| 73 | export function togetherHtml(db: Parameters<typeof togetherOf>[0], repo: Repo, viewer: User, as: Togetherness = "full"): Html { | |
| 74 | return region(`${repo.ownerName}/${repo.name}`, togetherLine(db, repo, viewer, as), as); | |
| 75 | } | |
outdated
Empty slot: the line is absent with JavaScript off and the box grows after first paint (layout shift). Render togetherHtml for the viewer here and let the SSE frame only update it. |
||
| 76 | ||
| 77 | /** | |
| 78 | * How much of the line a region draws: `full` (a repository's home), `live` (Talk's pane: full, | |
| 79 | * with See Live and Dismiss), `here` (every other page of a repository: who is here alone, which | |
| 80 | * reads no table, so the page costs what it did and nothing shifts when the stream opens). | |
| 81 | */ | |
| 82 | export type Togetherness = "full" | "live" | "here"; | |
| 83 | ||
| 84 | /** A region's `as`, from a query (`?as=`); anything else is full. */ | |
| 85 | export const togethernessOf = (raw: string | null): Togetherness => (raw === "live" || raw === "here" ? raw : "full"); | |
| 86 | ||
| 87 | ||
| 70 | 88 | /** GET /:owner/:name/together: the region alone, for its live swap. */ |
| 71 | 89 | export function togetherFragment(ctx: Ctx): Response { |
| 72 | 90 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| @@ -74,7 +92,7 @@ export function togetherFragment(ctx: Ctx): Response { | ||
| 74 | 92 | const repo = getRepo(ctx.app.db, ctx.params["owner"] ?? "", ctx.params["name"] ?? ""); |
| 75 | 93 | if (user === undefined || repo === undefined || !canRead(ctx.app.db, repo, user)) return notFoundPage(ctx, { plain: true }); |
| 76 | 94 | const rendering = performance.now(); |
| 77 | const region = togetherHtml(ctx.app.db, repo, user, `?show=live`); | |
| 95 | const region = togetherHtml(ctx.app.db, repo, user, togethernessOf(ctx.url.searchParams.get("as"))); | |
| 78 | 96 | notePhase(ctx.request, "render", performance.now() - rendering); |
| 79 | 97 | return fragment(region, { request: ctx.request }); |
| 80 | 98 | } |
test/copies-elsewhere.test.ts added +357
| @@ -0,0 +1,357 @@ | ||
| 1 | /** | |
| 2 | * Together across forges (`core/copies.ts`). An origin is told of copies on other forges by the | |
| 3 | * bringer's own forge, as the bringer, and keeps only what they chose: named, counted (paths, never a | |
| 4 | * name) or none (nothing; an older forge that sends no choice is none). Who reads what, across a | |
| 5 | * reader, a writer, the owner and a stranger; a proposal the new-account rule held leaves the owner | |
| 6 | * one quiet line; rows are bounded and fade on the forge's hourly prune. Then two real forges: a | |
| 7 | * bring through Talk's tool tells the origin, and the bring's answer says what the origin says of | |
| 8 | * the others. | |
| 9 | */ | |
| 10 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 11 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 12 | import { tmpdir } from "node:os"; | |
| 13 | import { join } from "node:path"; | |
| 14 | import { changeCapacity } from "../src/actions/capacity.ts"; | |
| 15 | import { connectOrigin } from "../src/actions/origins.ts"; | |
| 16 | import { createRepo } from "../src/actions/repos.ts"; | |
| 17 | import { createApp, type App } from "../src/app.ts"; | |
| 18 | import { | |
| 19 | copiesFor, | |
| 20 | COPIES_MAX, | |
| 21 | FADE_MS, | |
| 22 | PATHS_MAX, | |
| 23 | pruneCopies, | |
| 24 | recordRefusal, | |
| 25 | REFUSAL_MS, | |
| 26 | REFUSALS_MAX, | |
| 27 | } from "../src/core/copies.ts"; | |
| 28 | import { addTeamMember, createOrg, createTeam } from "../src/core/orgs.ts"; | |
| 29 | import { getRepo, type Repo } from "../src/core/repos.ts"; | |
| 30 | import { createSession } from "../src/core/sessions.ts"; | |
| 31 | import { createToken } from "../src/core/tokens.ts"; | |
| 32 | import { ownHost } from "../src/core/trusted_sources.ts"; | |
| 33 | import { createUser, type User } from "../src/core/users.ts"; | |
| 34 | import { togetherOf } from "../src/design/together.ts"; | |
| 35 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 36 | import { syncsSettled } from "../src/origins/sync.ts"; | |
| 37 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 38 | import { promote } from "./helpers/members.ts"; | |
| 39 | import { proveAll } from "./helpers/verified.ts"; | |
| 40 | ||
| 41 | let originDir: string; | |
| 42 | let origin: App; | |
| 43 | let originServers: Servers; | |
| 44 | let homeDir: string; | |
| 45 | let home: App; | |
| 46 | let homeServers: Servers; | |
| 47 | let voxel: Repo; | |
| 48 | let keeper: User; | |
| 49 | const at: Record<string, User> = {}; | |
| 50 | let rpc = 1; | |
| 51 | ||
| 52 | const person = async (app: App, username: string): Promise<User> => { | |
| 53 | const made = await createUser(app.db, { | |
| 54 | origin: "seed", | |
| 55 | trusted: true, | |
| 56 | username, | |
| 57 | email: `${username}@forge.test`, | |
| 58 | password: `${username}-passphrase-long`, | |
| 59 | }); | |
| 60 | if (!made.ok) throw new Error(made.error); | |
| 61 | promote(app.db, made.value); | |
| 62 | proveAll(app); | |
| 63 | return made.value; | |
| 64 | }; | |
| 65 | ||
| 66 | /** `who` tells the origin of their copy, as another forge does. */ | |
| 67 | const tell = ( | |
| 68 | who: User, | |
| 69 | report: Record<string, unknown>, | |
| 70 | repo = "team/voxel", | |
| 71 | ) => | |
| 72 | fetch(`${originServers.url}/api/v1/repos/${repo}/copies`, { | |
| 73 | method: "POST", | |
| 74 | headers: { | |
| 75 | "content-type": "application/json", | |
| 76 | authorization: `Bearer ${createToken(origin.db, who.id, "t", "rw").token}`, | |
| 77 | }, | |
| 78 | body: JSON.stringify(report), | |
| 79 | }); | |
| 80 | ||
| 81 | beforeAll(async () => { | |
| 82 | originDir = await mkdtemp(join(tmpdir(), "forge-copies-origin-")); | |
| 83 | origin = createApp({ dataDir: originDir, port: 0 }); | |
| 84 | originServers = await serve(origin); | |
| 85 | const admin = await seedAdmin(origin, { | |
| 86 | username: "keeper", | |
| 87 | email: "[email protected]", | |
| 88 | password: "keeper-passphrase-long", | |
| 89 | }); | |
| 90 | if (!admin.ok) throw new Error(admin.error); | |
| 91 | keeper = admin.value; | |
| 92 | // A private repository of a team: owen owns the team, wes writes, rita and the bringers read, sam is a stranger. | |
| 93 | for (const name of [ | |
| 94 | "owen", | |
| 95 | "wes", | |
| 96 | "rita", | |
| 97 | "sam", | |
| 98 | "nell", | |
| 99 | "cole", | |
| 100 | "xena", | |
| 101 | "olds", | |
| 102 | ]) | |
| 103 | at[name] = await person(origin, name); | |
| 104 | const org = createOrg(origin.db, "team", at["owen"]!.id); | |
| 105 | if (!org.ok) throw new Error(org.error); | |
| 106 | const writers = createTeam(origin.db, org.value.id, "writers", "write"); | |
| 107 | const readers = createTeam(origin.db, org.value.id, "readers", "read"); | |
| 108 | if (!writers.ok || !readers.ok) throw new Error("teams"); | |
| 109 | addTeamMember(origin.db, writers.value, at["wes"]!.id); | |
| 110 | for (const name of ["rita", "nell", "cole", "xena", "olds"]) | |
| 111 | addTeamMember(origin.db, readers.value, at[name]!.id); | |
| 112 | const made = await createRepo(origin, at["owen"]!, { | |
| 113 | name: "voxel", | |
| 114 | visibility: "private", | |
| 115 | owner: "team", | |
| 116 | }); | |
| 117 | if (!made.ok) throw new Error(String(made.error)); | |
| 118 | voxel = made.value; | |
| 119 | homeDir = await mkdtemp(join(tmpdir(), "forge-copies-home-")); | |
| 120 | home = createApp({ dataDir: homeDir, port: 0 }); | |
| 121 | homeServers = await serve(home); | |
| 122 | const homeAdmin = await seedAdmin(home, { | |
| 123 | username: "ada", | |
| 124 | email: "[email protected]", | |
| 125 | password: "ada-passphrase-long", | |
| 126 | }); | |
| 127 | if (!homeAdmin.ok) throw new Error(homeAdmin.error); | |
| 128 | }); | |
| 129 | ||
| 130 | afterAll(async () => { | |
| 131 | await syncsSettled(); | |
| 132 | originServers.stop(); | |
| 133 | homeServers.stop(); | |
| 134 | origin.close(); | |
| 135 | home.close(); | |
| 136 | await rm(originDir, { recursive: true, force: true, maxRetries: 5 }); | |
| 137 | await rm(homeDir, { recursive: true, force: true, maxRetries: 5 }); | |
| 138 | }); | |
| 139 | ||
| 140 | describe("what an origin keeps, and who reads it", () => { | |
| 141 | test("named, counted, none and an older forge, across a reader, a writer, the owner and a stranger", async () => { | |
| 142 | expect( | |
| 143 | ( | |
| 144 | await tell(at["nell"]!, { | |
| 145 | share: "named", | |
| 146 | forge: "home.test", | |
| 147 | paths: ["src/valid.ts"], | |
| 148 | }) | |
| 149 | ).status, | |
| 150 | ).toBe(200); | |
| 151 | const counted = await tell(at["cole"]!, { | |
| 152 | share: "counted", | |
| 153 | forge: "elsewhere.test", | |
| 154 | paths: ["src/valid.ts", "src/world.ts"], | |
| 155 | }); | |
| 156 | // The answer is what cole may read of the others: a reader, so a count and files, never a name. | |
| 157 | expect(await counted.json()).toEqual({ | |
| 158 | share: "counted", | |
| 159 | others: | |
| 160 | "1 person has a copy elsewhere · 1 change coming for src/valid.ts", | |
| 161 | }); | |
| 162 | expect( | |
| 163 | ( | |
| 164 | await tell(at["xena"]!, { | |
| 165 | share: "none", | |
| 166 | forge: "quiet.test", | |
| 167 | paths: ["secret.ts"], | |
| 168 | }) | |
| 169 | ).status, | |
| 170 | ).toBe(200); | |
| 171 | // A forge too old to send a choice is taken as none. | |
| 172 | expect( | |
| 173 | await ( | |
| 174 | await tell(at["olds"]!, { forge: "old.test", paths: ["old.ts"] }) | |
| 175 | ).json(), | |
| 176 | ).toMatchObject({ share: "none" }); | |
| 177 | ||
| 178 | const line = (u: User) => togetherOf(origin.db, voxel, u).elsewhere; | |
| 179 | // A reader: counts and files, no names. | |
| 180 | expect(line(at["rita"]!)).toBe( | |
| 181 | "2 people have copies elsewhere · 2 changes coming for src/valid.ts and 1 more file", | |
| 182 | ); | |
| 183 | // A writer and the owner: the named one by name, the counted one counted. | |
| 184 | expect(line(at["wes"]!)).toBe( | |
| 185 | "nell and 1 other have copies elsewhere · 2 changes coming for src/valid.ts and 1 more file", | |
| 186 | ); | |
| 187 | expect(line(at["owen"]!)).toBe(line(at["wes"]!)); | |
| 188 | // None and the older forge left nothing; cole's name is nowhere, and xena's files are nowhere. | |
| 189 | for (const u of ["rita", "wes", "owen"]) { | |
| 190 | expect(line(at[u]!)).not.toContain("cole"); | |
| 191 | expect(line(at[u]!)).not.toContain("secret.ts"); | |
| 192 | expect(line(at[u]!)).not.toContain("old.ts"); | |
| 193 | } | |
| 194 | // A stranger: the line is not theirs to read, and they cannot tell the origin anything. | |
| 195 | const cookie = { | |
| 196 | cookie: `forge_session=${createSession(origin.db, at["sam"]!.id).token}`, | |
| 197 | }; | |
| 198 | expect( | |
| 199 | ( | |
| 200 | await fetch(`${originServers.url}/team/voxel/together`, { | |
| 201 | headers: cookie, | |
| 202 | }) | |
| 203 | ).status, | |
| 204 | ).toBe(404); | |
| 205 | expect( | |
| 206 | (await tell(at["sam"]!, { share: "named", forge: "x.test", paths: [] })) | |
| 207 | .status, | |
| 208 | ).toBe(404); | |
| 209 | // Choosing none later forgets the copy at once. | |
| 210 | await tell(at["nell"]!, { share: "none", forge: "home.test" }); | |
| 211 | expect(line(at["owen"]!)).toBe( | |
| 212 | "1 person has a copy elsewhere · 1 change coming for src/valid.ts and 1 more file", | |
| 213 | ); | |
| 214 | }); | |
| 215 | ||
| 216 | test("a proposal the new-account rule held leaves the owner one quiet line; a reader reads none", async () => { | |
| 217 | expect( | |
| 218 | changeCapacity(origin, keeper, "guard_new_accounts", "on").ok, | |
| 219 | ).toBe(true); | |
| 220 | const res = await fetch( | |
| 221 | `${originServers.url}/api/v1/repos/team/voxel/forks`, | |
| 222 | { | |
| 223 | method: "POST", | |
| 224 | headers: { | |
| 225 | "content-type": "application/json", | |
| 226 | authorization: `Bearer ${createToken(origin.db, at["rita"]!.id, "t", "rw").token}`, | |
| 227 | }, | |
| 228 | body: "{}", | |
| 229 | }, | |
| 230 | ); | |
| 231 | expect(res.status).toBe(403); | |
| 232 | expect(togetherOf(origin.db, voxel, at["owen"]!).held).toEqual([ | |
| 233 | "rita tried to fork it; held by the new-account rule", | |
| 234 | ]); | |
| 235 | expect(togetherOf(origin.db, voxel, at["wes"]!).held).toEqual([ | |
| 236 | "rita tried to fork it; held by the new-account rule", | |
| 237 | ]); | |
| 238 | expect(togetherOf(origin.db, voxel, at["rita"]!).held).toEqual([]); | |
| 239 | expect(togetherOf(origin.db, voxel, at["cole"]!).held).toEqual([]); | |
| 240 | }); | |
| 241 | }); | |
| 242 | ||
| 243 | describe("bounded, and faded on the hourly prune", () => { | |
| 244 | test("files and held proposals are capped; copies fade after 30 days and held proposals after 7", async () => { | |
| 245 | const many = Array.from( | |
| 246 | { length: PATHS_MAX + 10 }, | |
| 247 | (_, i) => `f${String(i)}.ts`, | |
| 248 | ); | |
| 249 | await tell(at["cole"]!, { | |
| 250 | share: "counted", | |
| 251 | forge: "elsewhere.test", | |
| 252 | paths: ["../up.ts", "/abs.ts", ...many], | |
| 253 | }); | |
| 254 | const seen = copiesFor(origin.db, voxel, at["owen"]!); | |
| 255 | expect(seen.paths).toHaveLength(PATHS_MAX); | |
| 256 | expect(seen.paths).not.toContain("../up.ts"); | |
| 257 | expect(seen.paths).not.toContain("/abs.ts"); | |
| 258 | for (let i = 0; i < REFUSALS_MAX + 10; i++) | |
| 259 | recordRefusal(origin.db, voxel, at["sam"]!, "guard_new_accounts"); | |
| 260 | expect( | |
| 261 | origin.db | |
| 262 | .query< | |
| 263 | { n: number }, | |
| 264 | [string] | |
| 265 | >("SELECT COUNT(*) AS n FROM repo_refusal WHERE repo_id = ?1") | |
| 266 | .get(voxel.id)!.n, | |
| 267 | ).toBe(REFUSALS_MAX); | |
| 268 | expect(COPIES_MAX).toBeGreaterThan(0); | |
| 269 | // A week on, the held proposals are gone and the copies stay; a month on, the copies too. | |
| 270 | pruneCopies(origin.db, Date.now() + REFUSAL_MS + 60_000); | |
| 271 | expect( | |
| 272 | origin.db | |
| 273 | .query<{ n: number }, []>("SELECT COUNT(*) AS n FROM repo_refusal") | |
| 274 | .get()!.n, | |
| 275 | ).toBe(0); | |
| 276 | expect(copiesFor(origin.db, voxel, at["owen"]!).count).toBeGreaterThan(0); | |
| 277 | pruneCopies(origin.db, Date.now() + FADE_MS + 60_000); | |
| 278 | expect( | |
| 279 | origin.db | |
| 280 | .query<{ n: number }, []>("SELECT COUNT(*) AS n FROM repo_copy") | |
| 281 | .get()!.n, | |
| 282 | ).toBe(0); | |
| 283 | }); | |
| 284 | }); | |
| 285 | ||
| 286 | describe("two forges", () => { | |
| 287 | test("a bring through Talk's tool tells the origin as the person chose; none tells it nothing", async () => { | |
| 288 | expect( | |
| 289 | changeCapacity(origin, keeper, "guard_new_accounts", "off").ok, | |
| 290 | ).toBe(true); | |
| 291 | // Cole's counted copy is told again, so the bring's answer has someone to speak of. | |
| 292 | await tell(at["cole"]!, { | |
| 293 | share: "counted", | |
| 294 | forge: "elsewhere.test", | |
| 295 | paths: ["src/valid.ts"], | |
| 296 | }); | |
| 297 | const bring = async ( | |
| 298 | homeName: string, | |
| 299 | originName: string, | |
| 300 | share: string, | |
| 301 | ) => { | |
| 302 | const who = await person(home, homeName); | |
| 303 | const connected = await connectOrigin(home, who, { | |
| 304 | host: originServers.url, | |
| 305 | token: createToken(origin.db, at[originName]!.id, "t", "rw").token, | |
| 306 | }); | |
| 307 | if (!connected.ok) throw new Error(JSON.stringify(connected.error)); | |
| 308 | const res = await fetch(`${homeServers.url}/mcp`, { | |
| 309 | method: "POST", | |
| 310 | headers: { | |
| 311 | "content-type": "application/json", | |
| 312 | accept: "application/json, text/event-stream", | |
| 313 | authorization: `Bearer ${createToken(home.db, who.id, "t", "rw").token}`, | |
| 314 | }, | |
| 315 | body: JSON.stringify({ | |
| 316 | jsonrpc: "2.0", | |
| 317 | id: rpc++, | |
| 318 | method: "tools/call", | |
| 319 | params: { | |
| 320 | name: "bring", | |
| 321 | arguments: { repo: `${originServers.url}/team/voxel`, share }, | |
| 322 | }, | |
| 323 | }), | |
| 324 | }); | |
| 325 | const r = ( | |
| 326 | (await res.json()) as { | |
| 327 | result: { content: { text: string }[]; isError?: boolean }; | |
| 328 | } | |
| 329 | ).result; | |
| 330 | if (r.isError === true) throw new Error(r.content[0]!.text); | |
| 331 | return JSON.parse(r.content[0]!.text) as { says: string; copy: string }; | |
| 332 | }; | |
| 333 | const named = await bring("gina", "nell", "named"); | |
| 334 | expect(getRepo(home.db, "gina", "voxel-work")).toBeDefined(); | |
| 335 | const row = origin.db | |
| 336 | .query< | |
| 337 | { share: string; forge: string }, | |
| 338 | [string, string] | |
| 339 | >("SELECT share, forge FROM repo_copy WHERE repo_id = ?1 AND user_id = ?2") | |
| 340 | .get(voxel.id, at["nell"]!.id); | |
| 341 | expect(row).toEqual({ share: "named", forge: ownHost(home.config) }); | |
| 342 | // The bring's answer says what the origin says of the others, as nell may read it. | |
| 343 | expect(named.says).toContain( | |
| 344 | "1 person has a copy elsewhere · 1 change coming for src/valid.ts", | |
| 345 | ); | |
| 346 | expect(togetherOf(origin.db, voxel, at["owen"]!).elsewhere).toStartWith( | |
| 347 | "nell and 1 other have copies elsewhere", | |
| 348 | ); | |
| 349 | // None: the origin is told to keep nothing, and keeps nothing. | |
| 350 | await bring("hugo", "xena", "none"); | |
| 351 | expect( | |
| 352 | origin.db | |
| 353 | .query("SELECT 1 FROM repo_copy WHERE repo_id = ?1 AND user_id = ?2") | |
| 354 | .get(voxel.id, at["xena"]!.id), | |
| 355 | ).toBeNull(); | |
| 356 | }); | |
| 357 | }); |
test/job-slices.test.ts +2
| @@ -261,6 +261,8 @@ function jobs(): Record<string, () => unknown> { | ||
| 261 | 261 | * on. |
| 262 | 262 | */ |
| 263 | 263 | const UNTIMED: Record<string, string> = { |
| 264 | "copies-prune": "two DELETEs on indexed time columns (core/copies.ts pruneCopies), hourly on the outsider prune's own timer; copies-elsewhere.test.ts drives both fades", | |
| 265 | "tell-origin-wait": "a one-shot timer that only resolves the race when an origin has not answered a copy's report in TELL_MS; no work of its own; copies-elsewhere.test.ts tells a forge that answers", | |
| 264 | 266 | "presence-ping": "a per-stream timer (one per open Talk or repository page) that only refreshes its own seat's time in an in-memory map (core/presence.ts stillHere): no query, no write; together.test.ts drives the seat it keeps", |
| 265 | 267 | "deploy-permit-ceiling": "a one-shot timer armed per deploy that only aborts it and resolves the race when a deploy outlives 30 minutes; permit-ceiling.test.ts and deploy-permit-ceiling.test.ts drive it with a short ceiling", |
| 266 | 268 | "upstream-wait": "a one-shot timer that only aborts one proxied request when its app sends no headers in 30 s; no work of its own, cleared when the headers arrive; the upstream-wait tests drive it with a short wait", |
test/repo-timing.test.ts +2 −2
| @@ -52,10 +52,10 @@ afterAll(async () => { | ||
| 52 | 52 | await rm(dataDir, { recursive: true, force: true }); |
| 53 | 53 | }); |
| 54 | 54 | |
| 55 | test("a repository home names session, appof, refs, tree, readme, following, wave, credit, behind, together and render in order", async () => { | |
| 55 | test("a repository home names session, appof, refs, tree, readme, following, wave, credit, behind and render in order", async () => { | |
| 56 | 56 | const res = await fetch(`${servers.url}/alice/r`, { headers: { cookie } }); |
| 57 | 57 | expect(res.status).toBe(200); |
| 58 | 58 | await res.arrayBuffer(); |
| 59 | 59 | const names = requestTiming(res).split(", ").map((p) => p.split(";")[0]!); |
| 60 | expect(names).toEqual(["app", "session", "appof", "refs", "tree", "readme", "following", "wave", "credit", "behind", "together", "render"]); | |
| 60 | expect(names).toEqual(["app", "session", "appof", "refs", "tree", "readme", "following", "wave", "credit", "behind", "render"]); | |
| 61 | 61 | }); |
test/talk-bring.test.ts +3
| @@ -281,6 +281,9 @@ describe("bring keeps its promises", () => { | ||
| 281 | 281 | forgeCommands(session)(tui.ctx).find((c) => c.id === "bring-work")!.run(); |
| 282 | 282 | await settleApp(tui); |
| 283 | 283 | terminal.feed(`${link}\r`); |
| 284 | await settleApp(tui); | |
| 285 | // What the origin hears: empty takes counted. | |
| 286 | terminal.feed("\r"); | |
| 284 | 287 | await pollUntil(() => getRepo(w.app.db, p.user.username, "widgets-work") !== undefined, "the copy"); |
| 285 | 288 | await settleApp(tui); |
| 286 | 289 | expect(tui.screen.toText()).toContain("as your copy, private"); |
test/talk-live-pane.test.ts +10 −1
| @@ -398,11 +398,20 @@ describe("the pane, by the crew's newest run on the repository", () => { | ||
| 398 | 398 | handlers["forge"]!({ lastEventId: "1", data: JSON.stringify({ kind: "run.started", repo: name }) }); |
| 399 | 399 | await pollUntil(() => doc.querySelector("#talk-crew-now .talk-crew-working") !== null, "the next run in the crew region"); |
| 400 | 400 | // The crew region reads the pane once; the together line, a region of its own, reads its own. |
| 401 | expect(asked.sort()).toEqual([`/${name}/together`, "?pane=preview&fragment=pane"]); | |
| 401 | expect(asked.sort()).toEqual([`/${name}/together?as=live`, "?pane=preview&fragment=pane"]); | |
| 402 | 402 | expect(doc.querySelector("#talk-crew-now")!.textContent).toContain("Changed src/a.ts"); |
| 403 | 403 | // The frame is the same element at the same address: never redrawn for the crew. |
| 404 | 404 | expect(doc.querySelector("iframe")).toBe(frame); |
| 405 | 405 | expect(frame!.getAttribute("src")).toBe("https://clicker.apps.test/"); |
| 406 | // A together frame draws its line into the region of the repository it names, and no other. | |
| 407 | const before = doc.querySelector("#together")!.innerHTML; | |
| 408 | handlers["together"]!({ data: JSON.stringify({ repo: "someone/else", html: "<p>not here</p>" }) }); | |
| 409 | expect(doc.querySelector("#together")!.innerHTML).toBe(before); | |
| 410 | let swapped = 0; | |
| 411 | doc.addEventListener("forge:swapped", () => (swapped += 1)); | |
| 412 | handlers["together"]!({ data: JSON.stringify({ repo: name, html: '<p class="together-here small muted">ben is here</p>' }) }); | |
| 413 | expect(doc.querySelector("#together")!.textContent).toBe("ben is here"); | |
| 414 | expect(swapped).toBe(1); | |
| 406 | 415 | }); |
| 407 | 416 | |
| 408 | 417 | test("the terminal's c says words where the crew box does: on the issue the crew's run works", async () => { |
test/together.test.ts +46 −8
| @@ -196,11 +196,11 @@ describe("who is here", () => { | ||
| 196 | 196 | () => usersHere(app.db, repo.id).includes(carol.id), |
| 197 | 197 | "carol's seat", |
| 198 | 198 | ); |
| 199 | await pollUntil( | |
| 200 | () => | |
| 201 | mine.heard().includes('"kind":"presence.changed","repo":"team/voxel"'), | |
| 202 | "alice told carol came", | |
| 203 | ); | |
| 199 | // The line rides alice's stream, rendered for her: carol came. | |
| 200 | const frames = (s: { heard: () => string }) => s.heard().split("event: together").slice(1); | |
| 201 | await pollUntil(() => frames(mine).some((f) => f.includes("carol is here")), "alice's stream carries carol"); | |
| 202 | // And carol's own stream carried hers as it opened. | |
| 203 | await pollUntil(() => frames(theirs).some((f) => f.includes("alice is here")), "carol's stream carries alice"); | |
| 204 | 204 | expect((await line(alice)).text).toContain("carol is here"); |
| 205 | 205 | expect((await line(carol)).text).toContain("alice is here"); |
| 206 | 206 | // A stranger asks for a seat on a private repository: none, and the line is a not-found to them. |
| @@ -241,15 +241,15 @@ describe("who is here", () => { | ||
| 241 | 241 | expect(withCrew.match(/juniper/g)).toHaveLength(1); |
| 242 | 242 | app.db.run("UPDATE run SET state = 'ok' WHERE id = ?1", [run.id]); |
| 243 | 243 | // carol leaves: her seat goes with her stream, and alice's page is told. |
| 244 | const before = mine.heard().split("presence.changed").length; | |
| 244 | const before = frames(mine).length; | |
| 245 | 245 | theirs.close(); |
| 246 | 246 | await pollUntil( |
| 247 | 247 | () => !usersHere(app.db, repo.id).includes(carol.id), |
| 248 | 248 | "carol's seat given up", |
| 249 | 249 | ); |
| 250 | 250 | await pollUntil( |
| 251 | () => mine.heard().split("presence.changed").length > before, | |
| 252 | "alice told carol left", | |
| 251 | () => frames(mine).length > before && !frames(mine).at(-1)!.includes("carol"), | |
| 252 | "alice's stream says carol left", | |
| 253 | 253 | ); |
| 254 | 254 | expect((await line(alice)).text).not.toContain("carol"); |
| 255 | 255 | for (const s of [mine, stranger, outsider, agent]) s.close(); |
| @@ -299,6 +299,44 @@ describe("what was done lately, and a landing", () => { | ||
| 299 | 299 | `data-reply="/team/voxel/pulls/${String(opened.value.number)}"`, |
| 300 | 300 | ); |
| 301 | 301 | }); |
| 302 | ||
| 303 | test("on a mirror, a pull is its origin author's, never the account that keeps the mirror", async () => { | |
| 304 | const made = await createRepo(app, alice, { name: "mirrorish", visibility: "private", owner: "team" }); | |
| 305 | if (!made.ok) throw new Error(String(made.error)); | |
| 306 | const mirror = made.value; | |
| 307 | const mirrored = createIssue(app.db, { repoId: mirror.id, authorId: alice.id, title: "Names in any script", body: "b", kind: "pull" }); | |
| 308 | if (!mirrored.ok) throw new Error("pull"); | |
| 309 | app.db.run("UPDATE issue SET origin_author = 'f2f-maker' WHERE id = ?1", [mirrored.value.id]); | |
| 310 | for (const kind of ["pull.opened", "pull.merged"] as const) app.bus.append({ kind, repoId: mirror.id, actorId: alice.id, payload: { number: mirrored.value.number } }); | |
| 311 | const t = togetherOf(app.db, mirror, alice); | |
| 312 | expect(t.lately.slice(0, 2).map((l) => l.words)).toEqual([`A pull request was merged: #${String(mirrored.value.number)} Names in any script`, `f2f-maker opened a pull request: #${String(mirrored.value.number)} Names in any script`]); | |
| 313 | // Its landing is f2f-maker's, not "Your change" to the mirror's keeper. | |
| 314 | expect(t.landed?.words).toBe("f2f-maker's change landed: Live has it now."); | |
| 315 | }); | |
| 316 | }); | |
| 317 | ||
| 318 | describe("every page of a repository", () => { | |
| 319 | test("draws the line for a signed-in reader with the page (JavaScript off), and the stream keeps it, rendered for that reader", async () => { | |
| 320 | const page = async (u: User | undefined, path: string) => (await fetch(`${servers.url}${path}`, { headers: u === undefined ? {} : cookie(u) })).text(); | |
| 321 | const theirs = stream(carol); | |
| 322 | await pollUntil(() => usersHere(app.db, repo.id).includes(carol.id), "carol's seat"); | |
| 323 | // The repository's home, its issues and its pulls: the line is under the header on each, drawn | |
| 324 | // with the page, and carol is in it; none signed out. | |
| 325 | for (const path of ["/team/voxel", "/team/voxel/issues", "/team/voxel/pulls"]) { | |
| 326 | const drawn = (await page(alice, path)).replace(/\s+/g, " "); | |
| 327 | expect(drawn).toContain('data-presence="team/voxel"'); | |
| 328 | expect(drawn).toMatch(/id="together"[^>]*>\s*<p class="together-here small muted">carol is here<\/p>/); | |
| 329 | } | |
| 330 | // Only the home draws what was done lately; every other page leaves it to the stream. | |
| 331 | expect(await page(alice, "/team/voxel")).toContain("together-lately"); | |
| 332 | expect(await page(alice, "/team/voxel/issues")).not.toContain("together-lately"); | |
| 333 | expect(await page(undefined, "/team/voxel")).not.toContain('data-presence="team/voxel"'); | |
| 334 | // The stream's first frame is the line itself, for its reader: carol is here, to alice. | |
| 335 | const mine = stream(alice); | |
| 336 | await pollUntil(() => mine.heard().includes("event: together") && mine.heard().includes("carol is here"), "alice's first frame names carol"); | |
| 337 | expect(mine.heard()).not.toContain("presence.changed"); | |
| 338 | for (const s of [mine, theirs]) s.close(); | |
| 339 | }); | |
| 302 | 340 | }); |
| 303 | 341 | |
| 304 | 342 | describe("the terminal's pane", () => { |
test/tui-bring.test.ts +5
| @@ -60,6 +60,11 @@ describe("work on a repository", () => { | ||
| 60 | 60 | expect(tui.screen.toText()).toContain("Paste the link, or owner/name."); |
| 61 | 61 | terminal.feed("octo/widgets\r"); |
| 62 | 62 | await settleApp(tui); |
| 63 | // What the origin hears of the copy, asked in its own words; empty takes counted. | |
| 64 | expect(tui.screen.toText()).toContain("What the origin hears"); | |
| 65 | expect(tui.screen.toText()).toContain("never your name"); | |
| 66 | terminal.feed("\r"); | |
| 67 | await settleApp(tui); | |
| 63 | 68 | expect(tui.screen.toText()).toContain("/settings/origins"); |
| 64 | 69 | } finally { |
| 65 | 70 | tui.stop(); |
new above
offline
The origin call is awaited with no timeout; a slow origin delays the bring and the plan answer. Add a short timeout.