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

Presence works on every repository page: a per-reader together frame (#16415) #16470

opened this

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

Ready to land

talk-presence-frame → main 1 commit 1 thread · 1 unresolved

Review

Sign in to review this change.
12 files changed +169 −70
docs/features/talk.md +1 −1
@@ -218,7 +218,7 @@ 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
src/design/together.ts +20 −7
@@ -47,8 +47,13 @@ const people = (names: readonly string[]): string =>
4747 /** Readers counted and not named: "1 other is reading", "2 others are reading". */
4848 const reading = (n: number): string => (n === 1 ? "1 other is reading" : `${String(n)} others are reading`);
4949
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 {
50 /**
51 * What the together line says to `viewer` on `repo`, a repository they may read. `full` reads
52 * the crew building, what was done lately and a landing; without it, only who is here, from the
53 * forge's memory of open pages (a query only for each person here): what any page of a repository
54 * draws first, before its stream brings the rest.
55 */
56 export function togetherOf(db: Database, repo: Repo, viewer: User, now = Date.now(), full = true): Together {
5257 const readers = usersHere(db, repo.id, now)
5358 .filter((id) => id !== viewer.id)
5459 .flatMap((id) => {
@@ -58,27 +63,31 @@ export function togetherOf(db: Database, repo: Repo, viewer: User, now = Date.no
5863 // On a public repository a reader is anyone signed in: only its writers are named.
5964 const others = readers.filter((u) => repo.visibility !== "public" || canWrite(db, repo, u)).map((u) => u.username);
6065 const counted = readers.length - others.length;
61 const building = db
66 const building = !full
67 ? []
68 : db
6269 .query<{ name: string; number: number | null }, [string]>(
6370 "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",
6471 )
6572 .all(repo.id)
6673 .map((r) => `${r.name} is building${r.number === null ? "" : ` #${String(r.number)}`}`);
6774 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"] });
75 const events = !full ? [] : listEvents(db, { repoId: repo.id, limit: 40, kinds: ["pull.opened", "pull.merged", "run.finished"] });
6976 const meant = audienceFilter(db, viewer, events);
7077 const kept = events.filter((e) => meant(e) && (e.kind !== "run.finished" || (e.payload["kind"] === "check" && (e.payload["state"] === "ok" || e.payload["state"] === "failed"))));
7178 const lately = kept.slice(0, LATELY).map((e) => ({ id: e.id, words: eventWords(db, repo, e), at: e.createdAt }));
7279 const merged = kept.find((e) => e.kind === "pull.merged" && now - Date.parse(e.createdAt) < LANDED_NEWS_MS);
7380 const number = typeof merged?.payload["number"] === "number" ? merged.payload["number"] : undefined;
7481 const pull = number === undefined ? undefined : getIssue(db, repo.id, number);
75 const author = pull === undefined ? undefined : getUserById(db, pull.authorId)?.username;
82 // A mirrored pull is its origin author's, never the account that keeps the mirror (#16437).
83 const author = pull === undefined ? undefined : (pull.originAuthor ?? getUserById(db, pull.authorId)?.username);
84 const mine = pull !== undefined && pull.originAuthor === null && pull.authorId === viewer.id;
7685 return {
7786 ...(said.length === 0 ? {} : { here: { names: others, words: said.join(" · ") } }),
7887 lately,
7988 ...(merged === undefined || pull === undefined || author === undefined
8089 ? {}
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`) } }),
90 : { landed: { id: merged.id, number: pull.number, author, mine, words: liveHasIt(mine ? "Your change" : `${author}'s change`) } }),
8291 };
8392 }
8493
@@ -90,6 +99,10 @@ function eventWords(db: Database, repo: Repo, e: ForgeEvent): string {
9099 }
91100 const number = typeof e.payload["number"] === "number" ? e.payload["number"] : undefined;
92101 const pull = number === undefined ? undefined : getIssue(db, repo.id, number);
102 const what = pull === undefined ? "" : `: #${String(pull.number)} ${pull.title}`;
103 // On a mirror the event's actor is the account that keeps it, not who did it: a pull opened there
104 // is its origin author's, and who merged it there is not known here (#16437).
105 if (pull?.originAuthor != null) return e.kind === "pull.opened" ? `${pull.originAuthor} ${eventVerb(e)}${what}` : `A pull request was merged${what}`;
93106 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}`}`;
107 return `${who} ${eventVerb(e)}${what}`;
95108 }
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/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 +51 −34
@@ -18,28 +18,36 @@ 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 const t = togetherOf(db, repo, viewer, now, as !== "here");
48 const name = `${repo.ownerName}/${repo.name}`;
49 const see = as === "live" ? talkLiveHref(name) : undefined;
50 return html`${t.here === undefined
4351 ? null
4452 : html`<p class="together-here small muted">${t.here.words}</p>`}${t.lately.length === 0
4553 ? null
@@ -47,26 +55,35 @@ export function togetherHtml(
4755 <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>`)}
4856 </p>`}${t.landed === undefined
4957 ? 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
58 : html`<p class="together-landed small" role="status" data-landed="${t.landed.id}">
59 ${t.landed.words}${see === undefined ? null : html` <a href="${see}">See Live</a>`}${t.landed.mine
5660 ? 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>`;
61 : 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>`}
62 ${see === undefined ? null : html` <button class="btn js-only" data-size="sm" data-variant="ghost" type="button" data-landed-off>Dismiss</button>`}
63 </p>`}`;
6864 }
6965
66 /**
67 * The region drawn with its line, for `viewer` on `repo` (Talk's pane: `live`), so the page has
68 * it with JavaScript off. `full` (the repository's home, Talk's pane) draws all of it; elsewhere
69 * (every other page of a repository, under its header) only who is here, which reads no table:
70 * the page's stream then brings the rest and keeps it current.
71 */
72 export function togetherHtml(db: Parameters<typeof togetherOf>[0], repo: Repo, viewer: User, as: Togetherness = "full"): Html {
73 return region(`${repo.ownerName}/${repo.name}`, togetherLine(db, repo, viewer, as), as);
74 }
75
76 /**
77 * How much of the line a region draws: `full` (a repository's home), `live` (Talk's pane: full,
78 * with See Live and Dismiss), `here` (every other page of a repository: who is here alone, which
79 * reads no table, so the page costs what it did and nothing shifts when the stream opens).
80 */
81 export type Togetherness = "full" | "live" | "here";
82
83 /** A region's `as`, from a query (`?as=`); anything else is full. */
84 export const togethernessOf = (raw: string | null): Togetherness => (raw === "live" || raw === "here" ? raw : "full");
85
86
7087 /** GET /:owner/:name/together: the region alone, for its live swap. */
7188 export function togetherFragment(ctx: Ctx): Response {
7289 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
@@ -74,7 +91,7 @@ export function togetherFragment(ctx: Ctx): Response {
7491 const repo = getRepo(ctx.app.db, ctx.params["owner"] ?? "", ctx.params["name"] ?? "");
7592 if (user === undefined || repo === undefined || !canRead(ctx.app.db, repo, user)) return notFoundPage(ctx, { plain: true });
7693 const rendering = performance.now();
77 const region = togetherHtml(ctx.app.db, repo, user, `?show=live`);
94 const region = togetherHtml(ctx.app.db, repo, user, togethernessOf(ctx.url.searchParams.get("as")));
7895 notePhase(ctx.request, "render", performance.now() - rendering);
7996 return fragment(region, { request: ctx.request });
8097 }
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-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", () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs