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

Working together across forges: copies elsewhere, changes coming, held proposals (#16417) #16453

opened this

Check · Review · Land · Live — Pushed since the last review. Next: reviewer, pushed since the last review.

Ready to land

talk-together-2 → main 2 commits 4 threads · 4 unresolved

Review

Sign in to review this change.
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
115115 - `.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.
116116 - `.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.
117117 - `.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.
118119 - `.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.
119120 - `.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.
120121 - `.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
218218
219219 ## Working together
220220
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.
222222
223223 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.
224224
225225 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.
226226
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
227235 In the terminal, the Talk screen's pane prints the same lines ("Here:", "Lately:", and the landing), and `L` shows Live.
228236
229237 ## Display (#15734)
src/actions/bring.ts +17 −5
@@ -32,6 +32,8 @@ import { settled, type MirrorJob } from "../origins/jobs.ts";
3232 import type { Origin, OriginSaid, Provider } from "../origins/types.ts";
3333 import { NEW_ACCOUNT_GUARD_MESSAGE } from "../core/capacity.ts";
3434 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";
3537 import { requireVerified } from "./verify.ts";
3638 import { appLimitWords } from "./app_limit.ts";
3739 import { enableApp, setAppEnvVar } from "./apps.ts";
@@ -243,6 +245,8 @@ export interface BroughtIn {
243245 readonly reused: { readonly mirror: boolean; readonly copy: boolean };
244246 /** Whether a mirror already here in public was made private by this bring. */
245247 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;
246250 }
247251
248252 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
271275 export async function bringToWork(
272276 app: App,
273277 actor: User | undefined,
274 input: { readonly repo: string; readonly origin?: string },
278 input: { readonly repo: string; readonly origin?: string; readonly share?: Share },
275279 ): Promise<Result<BroughtIn, BringError>> {
276280 if (actor === undefined || !isActive(actor) || actor.kind === "agent") return err({ kind: "unauthorized" });
277281 if (!requireVerified(app, actor).ok) return err({ kind: "unverified" });
@@ -317,7 +321,11 @@ export async function bringToWork(
317321 if (!kept.ok) return keptPublic;
318322 const copy = await workCopyOf(app, actor, kept.value.repo);
319323 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 }) });
321329 }
322330
323331 /**
@@ -325,7 +333,7 @@ export async function bringToWork(
325333 * never the two repositories it is made of.
326334 */
327335 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}.`}`;
329337 const copyPublic = b.copy !== undefined && b.copy.visibility !== "private" ? ` Your copy is public, as you set it.` : "";
330338 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}`;
331339 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;
370378 * list short, never the plan refused. The cost: one listing and up to `OVERLAP_PULLS_MAX` diffs at
371379 * the origin on every plan, in parallel.
372380 */
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[]> {
374382 const copyDir = repoDir(app.reposRoot, copy.ownerName, copy.name);
375383 const [head, base] = await Promise.all([
376384 resolveOid(copyDir, `refs/heads/${branch}`),
@@ -378,6 +386,7 @@ async function overlapsAt(app: App, provider: Provider, origin: Origin, fullName
378386 ]);
379387 if (head === undefined || base === undefined) return [];
380388 const mine = new Set((await diffBetween(copyDir, base, head)).diff.files.map((f) => f.path));
389 changed([...mine]);
381390 if (mine.size === 0) return [];
382391 const open = await provider.listIssues(fullName, { kind: "pull", state: "open" });
383392 if (!open.ok) return [];
@@ -449,7 +458,10 @@ export async function planUpstream(
449458 if (live.ok && live.value.permissions.fork === false) return refuse("fork_held", forkHeldWords(fullName));
450459 }
451460 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);
453465 return ok({ copy, mirror, at: fullName, on: originWords(origin), branch, into: route === "direct" ? "branch" : "fork", fork, as, overlaps });
454466 }
455467
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> {
outdated

The origin call is awaited with no timeout; a slow origin delays the bring and the plan answer. Add a short timeout.

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 @@
55 */
66
77 import { mirrorCopyWords } from "./mirror_copy.ts";
8 import { recordRefusal } from "../core/copies.ts";
89 import { retractBundles } from "../git/bundle_uri.ts";
910 import { removeDrop } from "../drop/store.ts";
1011 import { getOriginById } from "../core/origins.ts";
@@ -245,7 +246,11 @@ export async function forkRepo(
245246 const proven = requireContributor(app, user.value);
246247 if (!proven.ok) return proven;
247248 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 }
249254 // A guest forks to contribute: public parents only, always public, marked in
250255 // the row's own write so the fork is never an ordinary one for a moment.
251256 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
375375 export { route as postApiV1ReposOwnerNameChecksRecheck } from "./postApiV1ReposOwnerNameChecksRecheck.ts";
376376 export { route as postApiV1ReposOwnerNameContents } from "./postApiV1ReposOwnerNameContents.ts";
377377 export { route as postApiV1ReposOwnerNameContribute } from "./postApiV1ReposOwnerNameContribute.ts";
378 export { route as postApiV1ReposOwnerNameCopies } from "./postApiV1ReposOwnerNameCopies.ts";
378379 export { route as postApiV1ReposOwnerNameDataEnvFileQuery } from "./postApiV1ReposOwnerNameDataEnvFileQuery.ts";
379380 export { route as postApiV1ReposOwnerNameDataImport } from "./postApiV1ReposOwnerNameDataImport.ts";
380381 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>> = {
1818 "make-it-yours": "forks",
1919 contribute: "forks",
2020 offers: "forks",
21 copies: "forks",
2122 queue: "gates",
2223 growth: "issues",
2324 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";
1313 import { listEvents, type ForgeEvent } from "../core/events.ts";
1414 import { getIssue, getIssueById } from "../core/issues.ts";
1515 import { usersHere } from "../core/presence.ts";
16 import { copiesFor, copiesWords } from "../core/copies.ts";
1617 import { canRead, canWrite, type Repo } from "../core/repos.ts";
1718 import { liveHasIt, PULL_CHECKS } from "../core/talk_work.ts";
1819 import { getUserById, isActive, type User } from "../core/users.ts";
@@ -31,6 +32,13 @@ export interface Together {
3132 readonly here?: { readonly names: readonly string[]; readonly words: string };
3233 /** The newest few things done on the repository, newest first, each with when (said by `agoWords`). */
3334 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[];
3442 /** A change that landed on Live lately: said once by the page, and the one thing that moves the frame. */
3543 readonly landed?: { readonly id: string; readonly words: string; readonly number: number; readonly author: string; readonly mine: boolean };
3644 }
@@ -47,8 +55,14 @@ const people = (names: readonly string[]): string =>
4755 /** Readers counted and not named: "1 other is reading", "2 others are reading". */
4856 const reading = (n: number): string => (n === 1 ? "1 other is reading" : `${String(n)} others are reading`);
4957
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 {
5266 const readers = usersHere(db, repo.id, now)
5367 .filter((id) => id !== viewer.id)
5468 .flatMap((id) => {
@@ -58,27 +72,36 @@ export function togetherOf(db: Database, repo: Repo, viewer: User, now = Date.no
5872 // On a public repository a reader is anyone signed in: only its writers are named.
5973 const others = readers.filter((u) => repo.visibility !== "public" || canWrite(db, repo, u)).map((u) => u.username);
6074 const counted = readers.length - others.length;
61 const building = db
75 const building = !full
76 ? []
77 : db
6278 .query<{ name: string; number: number | null }, [string]>(
6379 "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",
6480 )
6581 .all(repo.id)
6682 .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);
6786 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"] });
6988 const meant = audienceFilter(db, viewer, events);
7089 const kept = events.filter((e) => meant(e) && (e.kind !== "run.finished" || (e.payload["kind"] === "check" && (e.payload["state"] === "ok" || e.payload["state"] === "failed"))));
7190 const lately = kept.slice(0, LATELY).map((e) => ({ id: e.id, words: eventWords(db, repo, e), at: e.createdAt }));
7291 const merged = kept.find((e) => e.kind === "pull.merged" && now - Date.parse(e.createdAt) < LANDED_NEWS_MS);
7392 const number = typeof merged?.payload["number"] === "number" ? merged.payload["number"] : undefined;
7493 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;
7697 return {
7798 ...(said.length === 0 ? {} : { here: { names: others, words: said.join(" · ") } }),
7899 lately,
100 ...(copies === undefined ? {} : { elsewhere: copies }),
101 held: away.held.map((h) => h.words),
79102 ...(merged === undefined || pull === undefined || author === undefined
80103 ? {}
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`) } }),
82105 };
83106 }
84107
@@ -90,6 +113,10 @@ function eventWords(db: Database, repo: Repo, e: ForgeEvent): string {
90113 }
91114 const number = typeof e.payload["number"] === "number" ? e.payload["number"] : undefined;
92115 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}`;
93120 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}`;
95122 }
src/engine/duties.ts +8 −1
@@ -13,6 +13,7 @@
1313 * list back (`takeBack`): the forge is then one thread that serves and works.
1414 */
1515
16 import { pruneCopies } from "../core/copies.ts";
1617 import type { App } from "../app.ts";
1718 import { runModelReview } from "../actions/model_review.ts";
1819 import { expireCrewHolds } from "../actions/holds.ts";
@@ -61,7 +62,13 @@ export function startDuties(app: App, options: { onWorker: boolean }): () => voi
6162 // Estimates of "done" come due as time passes (#11955).
6263 timers.push(setInterval(() => during("estimates-due", () => void settleDue(app.db), undefined, app), 300_000));
6364 // 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 );
6572 // An issue snoozed behind the Later gate comes back on its day (#13113).
6673 timers.push(setInterval(() => during("gate-snooze", () => void returnSnoozed(app), undefined, app), 60_000));
6774 during("gate-snooze", () => void returnSnoozed(app), undefined, app);
src/http/api/upstream.ts +13
@@ -9,6 +9,7 @@
99 import { DELETING_SAYS } from "../../core/repo_deleting.ts";
1010 import { nestedForks } from "../../actions/fork_nested.ts";
1111 import { forksSince } from "../../core/repos.ts";
12 import { reportCopy } from "../../actions/copies.ts";
1213 import { forkRepo, FORKS_PER_DAY, repositoryLimitMessage } from "../../actions/repos.ts";
1314 import {
1415 checkUpstreamNow,
@@ -145,6 +146,18 @@ export function upstreamRoutes(router: Router<Handler>): void {
145146 });
146147 });
147148
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
148161 router.add("POST", "/api/v1/repos/:owner/:name/forks", async (ctx) => {
149162 const denied = requireScope(ctx, "rw");
150163 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";
33
44 export const tool: Tool = {
55 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.",
77 inputSchema: {
88 type: "object",
99 properties: {
1010 repo: { type: "string", maxLength: 300 },
1111 origin: { type: "string", maxLength: 300 },
12 share: { type: "string", enum: ["counted", "named", "none"] },
1213 },
1314 required: ["repo"],
1415 },
1516 writes: true,
1617 async run(ctx, user, args) {
1718 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 } : {}) });
1921 if (!brought.ok) return bad(brought.error.kind === "unauthorized" ? "forbidden" : brought.error.kind, bringWords(brought.error));
2022 const b = brought.value;
2123 const at = (r: { ownerName: string; name: string }) => `/${r.ownerName}/${r.name}`;
src/http/server.ts +2 −2
@@ -5,7 +5,7 @@
55 * verdict. Auth is resolved once per request and handed to handlers as data.
66 */
77
8 import { togetherFragment } from "../web/together.ts";
8 import { togetherFragment, togetherLine, togethernessOf } from "../web/together.ts";
99 import { outsiderStatusPage } from "./offer_routes.ts";
1010 import { standingFragment } from "../web/pages/fork-standing.ts";
1111 import { carrySent, InvalidJson } from "./json_body.ts";
@@ -1716,7 +1716,7 @@ export function buildRouter(): Router<Handler> {
17161716 // Live event stream for a repo the viewer can read.
17171717 // Everything the viewer may see, live. Pages with live regions listen here.
17181718 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),
17201720 );
17211721
17221722 router.add("GET", "/:owner/:name/stream", (ctx) => {
src/http/sse.ts +20 −6
@@ -209,6 +209,11 @@ export function viewerStream(
209209 app: App,
210210 viewer: User | undefined,
211211 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,
212217 ): Response {
213218 const seen = new Map<string, boolean>();
214219 const visible = (repoId: string): boolean => {
@@ -239,10 +244,17 @@ export function viewerStream(
239244 const here = hereOf(app, viewer, request);
240245 return eventStream(app, request, (emit, _close, ready) => {
241246 // 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 };
244256 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();
246258 });
247259 const pinging = seat === undefined || here === undefined ? undefined : setInterval(() => during("presence-ping", () => {
248260 if (ready()) stillHere(app.db, here.repo.id, seat.key);
@@ -289,6 +301,7 @@ export function viewerStream(
289301 for (const event of missed)
290302 if (meant(event)) send(event, false);
291303 }
304 line();
292305 return () => {
293306 gone.abort();
294307 unsubscribe();
@@ -302,12 +315,13 @@ export function viewerStream(
302315 * The repository a page says it is on (`?here=owner/name`), when its viewer is a signed-in, active
303316 * person (never an agent: the crew shows as what it builds) who may read it; anyone else takes no seat.
304317 */
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") ?? "";
307321 const [owner, name, extra] = asked.split("/");
308322 if (viewer === undefined || viewer.kind !== "user" || !isActive(viewer) || owner === undefined || name === undefined || extra !== undefined) return undefined;
309323 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) };
311325 }
312326
313327 export function sseStream(
src/origins/providers/forge.ts +10
@@ -248,6 +248,16 @@ export class ForgeProvider extends ForgejoProvider {
248248 return succeed(this.repoFrom(result.value.data, undefined));
249249 }
250250
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
251261 /** The forks there, in a forge's own JSON and cursor pages. */
252262 override async listForks(fullName: string): Promise<ProviderResult<readonly RemoteRepo[]>> {
253263 const base = this.repoPath(fullName);
src/origins/types.ts +6
@@ -567,6 +567,12 @@ export interface Provider {
567567 * `forbidden` and nothing changed.
568568 */
569569 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 }>>;
570576 /** One page of the repositories this token sees archived. Forgejo and Gitea only. */
571577 listArchived?(options: {
572578 query: string;
src/tui/screens/bringwork.ts +19 −6
@@ -8,7 +8,8 @@
88 import { bringToWork, bringWords, broughtWords } from "../../actions/bring.ts";
99 import type { Ctx, Screen } from "../app/app.ts";
1010 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";
1213
1314 export function bringWorkScreen(f: Session, ctx: Ctx, parent: Screen): Screen {
1415 return promptScreen(ctx, parent, {
@@ -18,11 +19,23 @@ export function bringWorkScreen(f: Session, ctx: Ctx, parent: Screen): Screen {
1819 hint: "Kept on GitHub or another forge you connected. It stays private here; the origin is unchanged.",
1920 onSubmit: (repo) => {
2021 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 );
2639 },
2740 });
2841 }
src/tui/screens/talk_chats.ts +1 −1
@@ -266,7 +266,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
266266 paneInfo(f.app.db, ws.repo, ws.shows),
267267 ...(fell === undefined ? [] : [fell]),
268268 // 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)),
270270 "o picks the repository, w the version, l a path, L Live.",
271271 "",
272272 url === undefined ? "Nothing running yet." : `Preview: ${url}`,
src/web/chrome.ts +7 −1
@@ -8,6 +8,7 @@
88 * `ui.ts` may not. That is the line between the two files.
99 */
1010
11 import { togetherHtml } from "./together.ts";
1112 import { repoOnRequest } from "../http/request_repo.ts";
1213 import { hereAddress, returnTo, withReturn } from "./return_to.ts";
1314 import { MACHINE_PREFIX, typedMiss } from "../http/asset_miss.ts";
@@ -213,6 +214,11 @@ export { repoPalette };
213214 export type { RepoTab };
214215
215216 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";
216222 /** Rendered at the right of the title line (fork, clone, watch). */
217223 actions?: Html;
218224 /** Suppress the description/lineage block on deep pages. */
@@ -360,7 +366,7 @@ export function scopeHeader(
360366 )}
361367 ${studio ? studioOriginNote(repo) : options.quiet ? null : whereRow(ctx, scope)}
362368 ${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")}`;
364370 }
365371
366372 /** 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 */ `
25622562 // A page on a repository says so (data-presence): the stream takes a seat on its together line.
25632563 var on = document.querySelector ? document.querySelector('[data-presence]') : null;
25642564 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') : '') : '';
25662566 source = since ? new EventSource('/events?since=' + encodeURIComponent(since) + (seat ? '&' + seat : '')) : seat ? new EventSource('/events?' + seat) : new EventSource('/events');
25672567 source.addEventListener('open', function () { state('open'); });
25682568 source.addEventListener('error', function () {
@@ -2570,6 +2570,10 @@ export const liveRegionsJs = /* js */ `
25702570 if (source.readyState === 2 && retry === null) retry = setTimeout(connect, 3000);
25712571 });
25722572 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 });
25732577 // New lines of a run's log: not history, so no id to resume from. Handed
25742578 // to whoever tails a run on this page (\`appTailJs\`).
25752579 source.addEventListener('run.log', function (event) {
src/web/pages/repo.ts +4 −6
@@ -8,7 +8,6 @@
88 * path segment and can never smuggle a path of its own.
99 */
1010
11 import { togetherHtml } from "../together.ts";
1211 import { DELETING_SAYS } from "../../core/repo_deleting.ts";
1312 import { downloadHeaders } from "../../drop/store.ts";
1413 import type { BlobForRender } from "../../git/read.ts";
@@ -98,7 +97,7 @@ import { blobHoldsPrivateKey, holdsPrivateKey, PRIVATE_KEY_NOTICE } from "../../
9897 import { countLines, highlightPrefix } from "../code.ts";
9998 import { tailOf, tailSentence } from "../log_tail.ts";
10099 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";
102101 import { liveClientJs, liveMount } from "../live.ts";
103102 import { appStrip } from "./apps.ts";
104103 import { growthBody, isAdmin } from "./growth_panel.ts";
@@ -1552,7 +1551,7 @@ async function codeHome(ctx: Ctx, repo: Repo, appOf: { readonly isApp: boolean;
15521551
15531552 if (refs.branches.length === 0) {
15541553 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}
15561555 <div class="mt">
15571556 ${empty({
15581557 icon: "repo",
@@ -1628,15 +1627,14 @@ async function codeHome(ctx: Ctx, repo: Repo, appOf: { readonly isApp: boolean;
16281627 creditLine(ctx, repo, scope.source, ref),
16291628 );
16301629 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!));
16331630 const gets = repo.template ? await timePhaseAsync(ctx.request, "template", () => templateCard(ctx.app, repo)) : null;
16341631 const offersHere = forkOffers(ctx.app.db, repo, ctx.auth.user);
16351632 const sizes = await offerSizes(ctx.app, repo, offersHere.map((o) => o.number));
16361633 const rendering = performance.now();
16371634 const body = html`${scopeHeader(ctx, scope, "code", {
16381635 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}
16401638 ${offerUpstream(repo, parent, offer)}
16411639 ${forkOffersCard(repo, offersHere, sizes)}
16421640 ${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
130130 ${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" })}
131131 </div>
132132 <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")}
134134 ${fellLine}
135135 ${panel}
136136 </aside>`,
src/web/together.ts +53 −35
@@ -18,55 +18,73 @@ import { notePhase, takeSessionTime } from "../core/route_timing.ts";
1818 import { html, type Html } from "./html.ts";
1919 import { fragment } from "./layout.ts";
2020
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
2124 /**
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.
2428 */
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 {
3430 return html`<div
3531 class="together"
3632 id="together"
37 data-live="presence.*,pull.*,run.*"
33 data-live="pull.*,run.*"
3834 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
4352 ? null
4453 : html`<p class="together-here small muted">${t.here.words}</p>`}${t.lately.length === 0
4554 ? null
4655 : html`<p class="together-lately small muted">
4756 <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
4958 ? 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
5661 ? 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>`}`;
6865 }
6966
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
7088 /** GET /:owner/:name/together: the region alone, for its live swap. */
7189 export function togetherFragment(ctx: Ctx): Response {
7290 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
@@ -74,7 +92,7 @@ export function togetherFragment(ctx: Ctx): Response {
7492 const repo = getRepo(ctx.app.db, ctx.params["owner"] ?? "", ctx.params["name"] ?? "");
7593 if (user === undefined || repo === undefined || !canRead(ctx.app.db, repo, user)) return notFoundPage(ctx, { plain: true });
7694 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")));
7896 notePhase(ctx.request, "render", performance.now() - rendering);
7997 return fragment(region, { request: ctx.request });
8098 }
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> {
261261 * on.
262262 */
263263 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",
264266 "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",
265267 "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",
266268 "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 () => {
5252 await rm(dataDir, { recursive: true, force: true });
5353 });
5454
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 () => {
5656 const res = await fetch(`${servers.url}/alice/r`, { headers: { cookie } });
5757 expect(res.status).toBe(200);
5858 await res.arrayBuffer();
5959 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"]);
6161 });
test/talk-bring.test.ts +3
@@ -281,6 +281,9 @@ describe("bring keeps its promises", () => {
281281 forgeCommands(session)(tui.ctx).find((c) => c.id === "bring-work")!.run();
282282 await settleApp(tui);
283283 terminal.feed(`${link}\r`);
284 await settleApp(tui);
285 // What the origin hears: empty takes counted.
286 terminal.feed("\r");
284287 await pollUntil(() => getRepo(w.app.db, p.user.username, "widgets-work") !== undefined, "the copy");
285288 await settleApp(tui);
286289 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", () => {
398398 handlers["forge"]!({ lastEventId: "1", data: JSON.stringify({ kind: "run.started", repo: name }) });
399399 await pollUntil(() => doc.querySelector("#talk-crew-now .talk-crew-working") !== null, "the next run in the crew region");
400400 // 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"]);
402402 expect(doc.querySelector("#talk-crew-now")!.textContent).toContain("Changed src/a.ts");
403403 // The frame is the same element at the same address: never redrawn for the crew.
404404 expect(doc.querySelector("iframe")).toBe(frame);
405405 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);
406415 });
407416
408417 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", () => {
196196 () => usersHere(app.db, repo.id).includes(carol.id),
197197 "carol's seat",
198198 );
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");
204204 expect((await line(alice)).text).toContain("carol is here");
205205 expect((await line(carol)).text).toContain("alice is here");
206206 // 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", () => {
241241 expect(withCrew.match(/juniper/g)).toHaveLength(1);
242242 app.db.run("UPDATE run SET state = 'ok' WHERE id = ?1", [run.id]);
243243 // 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;
245245 theirs.close();
246246 await pollUntil(
247247 () => !usersHere(app.db, repo.id).includes(carol.id),
248248 "carol's seat given up",
249249 );
250250 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",
253253 );
254254 expect((await line(alice)).text).not.toContain("carol");
255255 for (const s of [mine, stranger, outsider, agent]) s.close();
@@ -299,6 +299,44 @@ describe("what was done lately, and a landing", () => {
299299 `data-reply="/team/voxel/pulls/${String(opened.value.number)}"`,
300300 );
301301 });
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 });
302340 });
303341
304342 describe("the terminal's pane", () => {
test/tui-bring.test.ts +5
@@ -60,6 +60,11 @@ describe("work on a repository", () => {
6060 expect(tui.screen.toText()).toContain("Paste the link, or owner/name.");
6161 terminal.feed("octo/widgets\r");
6262 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);
6368 expect(tui.screen.toText()).toContain("/settings/origins");
6469 } finally {
6570 tui.stop();

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs