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

Working together, visible: who is here, a quiet live strip, a landing said once #16415

Merged opened this

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

Merged

talk-together → main 0 commits 1 thread · 1 unresolved

  • Merged. talk-together was merged into main as 9206427.

Review

Sign in to review this change.
19 files changed +775 −19
docs/design/areas/talk.md +4
@@ -114,6 +114,10 @@ Prior art: Claude and ChatGPT (one centred column, the person's words in a quiet
114114 - `.talk-diff-change`: in Diff, one pull this conversation's work led to: a `<details>` whose summary links the pull and says landed, open or closed, the newest open.
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.
117 - `.together`: the together line (`web/together.ts`), under the pane's info line and on a repository's page, a live region of its own; nothing in it moves but its words, and it takes no room when the viewer is alone and nothing was done lately.
118 - `.together-here`: who else is here now (named, or counted on a public repository) and the crew building, in words only, on the muted colour.
119 - `.together-lately`: the last three things done on the repository, one line, each said once when drawn ("just now", "4 min ago"); never a counter.
120 - `.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.
117121 - `.talk-reload`: Reload the preview, an icon button drawn `js-only`.
118122 - `.talk-try`: the agent's one line of what to try in the frame (`pane`), above the stage: plain small muted text (`--muted-fg`), no box; text only, never a link.
119123 - `.talk-stage`: the frame's surface, on the card colour with a hairline; `data-busy` dims the frame while it loads again.
docs/features/talk.md +10
@@ -216,6 +216,16 @@ Diff shows what this conversation's work changed: the pulls its receipts led to,
216216
217217 Under the preview, while the crew works, its block says who is working and streams its steps and words. Its line folds the rest away (the fold is kept per conversation in the browser), and a box under the steps says your words on the pull shown above, or else on the issue the run works: a comment the crew member reads next, the same as a receipt's Reply. A hold (with the control that changes it) or a failed run is never folded away. Without the script the box posts the comment itself and you land on that issue's or pull's page; Back returns to Talk. In the terminal, `c` says words on the same place: the pull the pane shows, else the issue the crew's run works, else the newest receipt's issue.
218218
219 ## Working together
220
221 When others are on the same app or repository, the pane (and the repository's page) says so in one quiet line under the address bar: "ben and maya are here · juniper is building #15". Under it, the last three things done there, once each: "maya opened a pull request: #16 Water reflects the sky · 2 min ago", "#13 Fog: checks passing". Nothing ticks and nothing moves but the words; alone, with nothing done lately, the line takes no room.
222
223 When a change lands, the line says it once: "ben's change landed: Live has it now." with See Live, Reply to ben (the composer then says your words on ben's pull) and Dismiss. On Live the frame reloads under that line, and that is the only thing that ever reloads it there; on a pull's preview the frame stays where you put it.
224
225 Who is here comes only from pages open now: each page's live stream takes a seat on the repository while it is open and gives it up when it closes, or after 45 seconds unanswered. Nothing is written down, so there is no history of who looked at what. It counts people, not tabs: the same person in two tabs, or on a phone and a desk, is one name (one seat, however many pages they open), and never shown to themselves. The line is shown only to people who may read the repository; a stranger and a signed-out visitor see nothing, and the crew shows only as what it builds. On a private repository everyone here is named. On a public repository only people who may write to it are named; any other signed-in reader is counted, never named: "ben is here · 2 others are reading". So what someone is reading is never shown to anyone, and the line still says the place is busy.
226
227 In the terminal, the Talk screen's pane prints the same lines ("Here:", "Lately:", and the landing), and `L` shows Live.
228
219229 ## Display (#15734)
220230
221231 Four preferences of the person's own, at the end of the conversation menu (⋯ → Display), one plain form that works without the script (`POST /talk/display`, signed in, same origin): spacing (comfortable or compact: the spacing scale only, never the type size), motion (as the system says, or reduced: Talk's arrivals, the head's slide and the shimmer stop whatever the system says), what Enter does (sends, or adds a line with Ctrl or Cmd+Enter sending) and whether a reply's steps start folded or open. They are the person's `user_setting` rows (`talk.density`, `talk.motion`, `talk.enter`, `talk.steps`, read by `talkDisplay` in `src/core/settings.ts`), applied by the server so the first paint is right; a value that is not one of a preference's own choices is never kept. No theme builder, no colours. The terminal honours the same steps choice: a conversation opened in `forge talk` shows a run of steps as one line ("3 steps") or each step, and `v` there flips the choice for both places, while `D` opens Talk display to set all four (docs/features/talk-display.md); spacing, motion and Enter are the page's own (the terminal has its own rows, no animation, and its `s` prompt always sends on Enter).
src/core/presence.ts added +114
@@ -0,0 +1,114 @@
1 /**
2 * Who is on a repository now (the together line): the people whose page holds a live stream open on
3 * it. Held in memory per forge (keyed by its database, as `region_memory.ts` holds its state), never
4 * written down: there is no history of who looked at what. One seat per person per repository,
5 * however many streams they open: a stream joins its person's seat when it opens on a repository its
6 * viewer may read and leaves it when it closes, and a person whose every stream has stopped answering
7 * (its pings go unread) is left out after `SILENT_MS`, so a crashed tab never stays on the line.
8 * Memory grows with the people on a repository, not with their streams: a person's seat keeps at most
9 * `TABS` streams to tell, the oldest let go past that (it still counts them as here). Plain data; who
10 * may see the names is the caller's (`design/together.ts`).
11 */
12 import type { Database } from "bun:sqlite";
13
14 /** A stream unanswered this long is left out of the line. */
15 export const SILENT_MS = 45_000;
16 /** How often a seat's stream proves it is still read. */
17 export const PING_MS = 15_000;
outdated

MAX_SEATS counts streams, not people. One user opening 64 streams locks everyone else out of the room. Key seats by user, so a user has one seat however many tabs they open, and drop the cap (and MAX_ROOMS).

18 /** The most streams one person's seat keeps to tell when someone comes or goes. */
19 export const TABS = 8;
20
21 interface Stream {
22 seen: number;
23 /** Tells this stream's page the line changed. */
24 readonly tell: () => void;
25 }
26
27 /** One person's seat on one repository: their open streams, newest last. */
28 type Seat = Map<symbol, Stream>;
29
30 const rooms = new WeakMap<Database, Map<string, Map<string, Seat>>>();
31
32 const roomsOf = (db: Database): Map<string, Map<string, Seat>> => {
33 let r = rooms.get(db);
34 if (r === undefined) rooms.set(db, (r = new Map()));
35 return r;
36 };
37
38 /** Whether a seat has a stream that answered within `SILENT_MS`. */
39 const alive = (seat: Seat | undefined, now: number): boolean =>
40 seat !== undefined &&
41 [...seat.values()].some((s) => now - s.seen < SILENT_MS);
42
43 /** Tell every stream of everyone else in the room that the line changed. */
44 function tellOthers(room: Map<string, Seat>, but: string): void {
45 for (const [userId, seat] of room)
46 if (userId !== but) for (const s of seat.values()) s.tell();
47 }
48
49 /**
50 * Join `userId`'s seat on `repoId` with one stream; the answer leaves it (idempotent). `tell` is
51 * called when someone else comes or goes. A person arriving tells the others; a second tab of theirs
52 * does not.
53 */
54 export function takeSeat(
55 db: Database,
56 repoId: string,
57 userId: string,
58 tell: () => void,
59 now = Date.now(),
60 ): { readonly key: symbol; readonly leave: () => void } {
61 const all = roomsOf(db);
62 let room = all.get(repoId);
63 if (room === undefined) all.set(repoId, (room = new Map()));
64 let seat = room.get(userId);
65 const fresh = !alive(seat, now);
66 if (seat === undefined) room.set(userId, (seat = new Map()));
67 // Past `TABS` the oldest stream is let go: still here as long as one of its newer tabs is.
68 if (seat.size >= TABS) seat.delete(seat.keys().next().value!);
69 const key = Symbol(userId);
70 seat.set(key, { seen: now, tell });
71 if (fresh) tellOthers(room, userId);
72 const here = room,
73 mine = seat;
74 return {
75 key,
76 leave: () => {
77 if (!mine.delete(key)) return;
78 const gone = !alive(mine, Date.now());
79 if (mine.size === 0 && here.get(userId) === mine) here.delete(userId);
80 if (here.size === 0 && all.get(repoId) === here) all.delete(repoId);
81 else if (gone) tellOthers(here, userId);
82 },
83 };
84 }
85
86 /** The seat's stream was read just now. */
87 export function stillHere(
88 db: Database,
89 repoId: string,
90 key: symbol,
91 now = Date.now(),
92 ): void {
93 for (const seat of rooms.get(db)?.get(repoId)?.values() ?? []) {
94 const s = seat.get(key);
95 if (s !== undefined) {
96 s.seen = now;
97 return;
98 }
99 }
100 }
101
102 /** The people on `repoId` now, each once, in the order they came; never anyone silent past `SILENT_MS`. */
103 export function usersHere(
104 db: Database,
105 repoId: string,
106 now = Date.now(),
107 ): string[] {
108 const room = rooms.get(db)?.get(repoId);
109 return room === undefined
110 ? []
111 : [...room]
112 .filter(([, seat]) => alive(seat, now))
113 .map(([userId]) => userId);
114 }
src/core/talk_work.ts +4 −1
@@ -222,10 +222,13 @@ const forMinutes = (at: string | null, now: number): string =>
222222 export function paneFell(db: Database, repoId: string, n: number | undefined): string | undefined {
223223 const pull = n === undefined ? undefined : getPull(db, repoId, n);
224224 if (pull === undefined) return undefined;
225 if (pull.mergedAt !== null) return `#${String(pull.number)} landed: Live has it now.`;
225 if (pull.mergedAt !== null) return liveHasIt(`#${String(pull.number)}`);
226226 return pull.state === "closed" ? `#${String(pull.number)} was closed: Live is shown.` : undefined;
227227 }
228228
229 /** That a change landed and the pane's Live shows it: "#2 landed: …", "ben's change landed: …". Both doors. */
230 export const liveHasIt = (subject: string): string => `${subject} landed: Live has it now.`;
231
229232 /** A pull's checks in words: the Diff tab's head and the pane's line say them alike. */
230233 export const PULL_CHECKS: Readonly<Record<string, string>> = {
231234 ok: "checks passing",
src/design/together.ts added +95
@@ -0,0 +1,95 @@
1 /**
2 * The together line (Talk's pane and a repository's page, and the terminal's pane): who else is on
3 * the repository now and the crew building on it, the last few things done there, and, once, that
4 * someone's change landed on Live. Every sentence is said here once for both surfaces, from the
5 * words the forge already uses: `eventVerb` for what was done, `PULL_CHECKS` for checks, `liveHasIt`
6 * for a landing. Read only for a reader of the repository (the caller's to check). The people here are
7 * only those who may read it too, and an agent only as what it builds. On a public repository only
8 * those who may write to it are named: any other signed-in reader is counted, never named, so the
9 * line never tells anyone what a stranger is looking at (defaults never publish personal data).
10 */
11 import type { Database } from "bun:sqlite";
12 import { audienceFilter } from "../core/event_audience.ts";
13 import { listEvents, type ForgeEvent } from "../core/events.ts";
14 import { getIssue, getIssueById } from "../core/issues.ts";
15 import { usersHere } from "../core/presence.ts";
16 import { canRead, canWrite, type Repo } from "../core/repos.ts";
17 import { liveHasIt, PULL_CHECKS } from "../core/talk_work.ts";
18 import { getUserById, isActive, type User } from "../core/users.ts";
19 import { eventActor, eventVerb } from "./activity.ts";
20
21 /** How long a landing is news: past this it is only in the strip. */
22 export const LANDED_NEWS_MS = 15 * 60_000;
23 /** How many things done lately the strip shows. */
24 export const LATELY = 3;
25
26 export interface Together {
27 /**
28 * "ben is here · 2 others are reading · juniper is building #15"; undefined when the viewer is
29 * alone. `names` are only the people named; the others are only counted.
30 */
31 readonly here?: { readonly names: readonly string[]; readonly words: string };
32 /** The newest few things done on the repository, newest first, each with when (said by `agoWords`). */
33 readonly lately: readonly { readonly id: string; readonly words: string; readonly at: string }[];
34 /** A change that landed on Live lately: said once by the page, and the one thing that moves the frame. */
35 readonly landed?: { readonly id: string; readonly words: string; readonly number: number; readonly author: string; readonly mine: boolean };
36 }
37
38 /** "just now", "4 min ago", "2 h ago": said once when drawn, never a clock that ticks. */
39 export const agoWords = (at: string, now: number): string => {
40 const min = Math.floor((now - Date.parse(at)) / 60_000);
41 return min < 1 ? "just now" : min < 60 ? `${String(min)} min ago` : `${String(Math.floor(min / 60))} h ago`;
42 };
43
44 const people = (names: readonly string[]): string =>
45 names.length === 1 ? `${names[0]!} is here` : names.length === 2 ? `${names[0]!} and ${names[1]!} are here` : `${names.slice(0, 2).join(", ")} and ${String(names.length - 2)} more are here`;
46
47 /** Readers counted and not named: "1 other is reading", "2 others are reading". */
48 const reading = (n: number): string => (n === 1 ? "1 other is reading" : `${String(n)} others are reading`);
49
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 {
52 const readers = usersHere(db, repo.id, now)
53 .filter((id) => id !== viewer.id)
54 .flatMap((id) => {
55 const u = getUserById(db, id);
56 return u !== undefined && u.kind === "user" && isActive(u) && canRead(db, repo, u) ? [u] : [];
57 });
58 // On a public repository a reader is anyone signed in: only its writers are named.
59 const others = readers.filter((u) => repo.visibility !== "public" || canWrite(db, repo, u)).map((u) => u.username);
60 const counted = readers.length - others.length;
61 const building = db
62 .query<{ name: string; number: number | null }, [string]>(
63 "SELECT u.username AS name, i.number AS number FROM run r JOIN user u ON u.id = r.actor_id LEFT JOIN issue i ON i.id = r.issue_id WHERE r.repo_id = ?1 AND r.kind = 'agent' AND r.state = 'running' ORDER BY r.id DESC LIMIT 2",
64 )
65 .all(repo.id)
66 .map((r) => `${r.name} is building${r.number === null ? "" : ` #${String(r.number)}`}`);
67 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"] });
69 const meant = audienceFilter(db, viewer, events);
70 const kept = events.filter((e) => meant(e) && (e.kind !== "run.finished" || (e.payload["kind"] === "check" && (e.payload["state"] === "ok" || e.payload["state"] === "failed"))));
71 const lately = kept.slice(0, LATELY).map((e) => ({ id: e.id, words: eventWords(db, repo, e), at: e.createdAt }));
72 const merged = kept.find((e) => e.kind === "pull.merged" && now - Date.parse(e.createdAt) < LANDED_NEWS_MS);
73 const number = typeof merged?.payload["number"] === "number" ? merged.payload["number"] : undefined;
74 const pull = number === undefined ? undefined : getIssue(db, repo.id, number);
75 const author = pull === undefined ? undefined : getUserById(db, pull.authorId)?.username;
76 return {
77 ...(said.length === 0 ? {} : { here: { names: others, words: said.join(" · ") } }),
78 lately,
79 ...(merged === undefined || pull === undefined || author === undefined
80 ? {}
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`) } }),
82 };
83 }
84
85 /** One thing done, in the forge's words: who, what (`eventVerb`), and the pull it was done to. */
86 function eventWords(db: Database, repo: Repo, e: ForgeEvent): string {
87 if (e.kind === "run.finished") {
88 const on = typeof e.payload["issueId"] === "string" ? getIssueById(db, e.payload["issueId"]) : undefined;
89 return `${on === undefined ? "A pull" : `#${String(on.number)} ${on.title}`}: ${PULL_CHECKS[String(e.payload["state"])] ?? "checks done"}`;
90 }
91 const number = typeof e.payload["number"] === "number" ? e.payload["number"] : undefined;
92 const pull = number === undefined ? undefined : getIssue(db, repo.id, number);
93 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}`}`;
95 }
src/http/server.ts +2
@@ -5,6 +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";
89 import { outsiderStatusPage } from "./offer_routes.ts";
910 import { standingFragment } from "../web/pages/fork-standing.ts";
1011 import { carrySent, InvalidJson } from "./json_body.ts";
@@ -1459,6 +1460,7 @@ export function buildRouter(): Router<Handler> {
14591460 router.add("POST", "/:owner/:name/issues/new", newIssueSubmit);
14601461 router.add("GET", "/:owner/:name/issues/:number", tellPage);
14611462 router.add("GET", "/:owner/:name/issues/:number/thread", issueThreadFragment);
1463 router.add("GET", "/:owner/:name/together", togetherFragment);
14621464 router.add("GET", "/:owner/:name/issues/:number/picture", issuePicture);
14631465 router.add(
14641466 "POST",
src/http/sse.ts +28 −1
@@ -20,7 +20,10 @@ import type { App } from "../app.ts";
2020 import type { User } from "../core/users.ts";
2121 import { listEvents, listEventsVisibleTo } from "../core/events.ts";
2222 import { audienceFilter, eventForReader } from "../core/event_audience.ts";
23 import { canRead, getRepoById } from "../core/repos.ts";
23 import { canRead, getRepo, getRepoById } from "../core/repos.ts";
24 import { isActive } from "../core/users.ts";
25 import { PING_MS, stillHere, takeSeat } from "../core/presence.ts";
26 import { during } from "../perf/jobs.ts";
2427 import { mayReadLogOfRun } from "../actions/runs.ts";
2528 import { getRun } from "../core/runs.ts";
2629 import { frameOf, tapRunLogs } from "../runs/log.ts";
@@ -233,7 +236,17 @@ export function viewerStream(
233236 };
234237 };
235238 const after = resumeFrom(request);
239 const here = hereOf(app, viewer, request);
236240 return eventStream(app, request, (emit, _close, ready) => {
241 // 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.
244 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: {} });
246 });
247 const pinging = seat === undefined || here === undefined ? undefined : setInterval(() => during("presence-ping", () => {
248 if (ready()) stillHere(app.db, here.repo.id, seat.key);
249 }), PING_MS);
237250 // Subscribed before the replay is read, so no event falls between them; an
238251 // event both hold is sent once, in the replay.
239252 const replayed = new Set<string>();
@@ -279,10 +292,24 @@ export function viewerStream(
279292 return () => {
280293 gone.abort();
281294 unsubscribe();
295 clearInterval(pinging);
296 seat?.leave();
282297 };
283298 });
284299 }
285300
301 /**
302 * The repository a page says it is on (`?here=owner/name`), when its viewer is a signed-in, active
303 * person (never an agent: the crew shows as what it builds) who may read it; anyone else takes no seat.
304 */
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") ?? "";
307 const [owner, name, extra] = asked.split("/");
308 if (viewer === undefined || viewer.kind !== "user" || !isActive(viewer) || owner === undefined || name === undefined || extra !== undefined) return undefined;
309 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 };
311 }
312
286313 export function sseStream(
287314 app: App,
288315 repoId: string,
src/tui/screens/talk_chats.ts +15 −2
@@ -51,6 +51,7 @@ import { style } from "../term/style.ts";
5151 import { truncate, wrap } from "../term/width.ts";
5252 import type { Session } from "../session.ts";
5353 import type { User } from "../../core/users.ts";
54 import { agoWords, togetherOf } from "../../design/together.ts";
5455 import { fill, len, split } from "../ui/layout.ts";
5556 import { ListState, Scroll, ago, confirmScreen, drawLines, drawList, errorText, later, pickerScreen, promptScreen, runAsync, type ListRow, type PickItem } from "./common.ts";
5657 import { answerWall } from "../../actions/pulls.ts";
@@ -264,7 +265,9 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
264265 `${name} · ${ws.shows === undefined ? "Production" : `Pull #${String(ws.shows)}`}${pointedAt(picked, steer).path === undefined ? "" : ` · ${pointedAt(picked, steer).path ?? ""}`}`,
265266 paneInfo(f.app.db, ws.repo, ws.shows),
266267 ...(fell === undefined ? [] : [fell]),
267 "o picks the repository, w the version, l a path.",
268 // Who else is here and what was done lately, in the page's words (`togetherOf`).
269 ...((t) => [...(t.here === undefined ? [] : [`Here: ${t.here.words}`]), ...(t.lately.length === 0 ? [] : [`Lately: ${t.lately.map((l) => `${l.words} · ${agoWords(l.at, Date.now())}`).join(" · ")}`]), ...(t.landed === undefined ? [] : [`${t.landed.words} (L shows Live)`])])(togetherOf(f.app.db, ws.repo, f.user)),
270 "o picks the repository, w the version, l a path, L Live.",
268271 "",
269272 url === undefined ? "Nothing running yet." : `Preview: ${url}`,
270273 ...(url === undefined || steer === undefined || steer.try === "" ? [] : [`Try: ${steer.try}`]),
@@ -349,7 +352,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
349352 binding(["1", "2", "3"], "starter"),
350353 binding(["r"], "reload"),
351354 binding(["p"], "pane"),
352 binding(["o", "w", "l"], "in the pane: repository, version, path"),
355 binding(["o", "w", "l", "L"], "in the pane: repository, version, path, Live"),
353356 binding(["b"], "a result's buttons"),
354357 binding(["v"], "steps open or folded"),
355358 binding(["D"], "display"),
@@ -425,6 +428,16 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
425428 );
426429 return true;
427430 }
431 if (pane && e.key === "L") {
432 // Live, as the together line's "See Live" does: the person's own move, never one made for them.
433 const { pull: _was, ...rest } = choice();
434 at = { ...rest, live: true };
435 runAsync(ctx, async () => {
436 await readChanged();
437 ctx.invalidate();
438 });
439 return true;
440 }
428441 if (pane && e.key === "l") {
429442 ctx.push(
430443 promptScreen(ctx, screen, {
src/web/client.ts +11 −1
@@ -2559,7 +2559,11 @@ export const liveRegionsJs = /* js */ `
25592559 function connect() {
25602560 if (retry) { clearTimeout(retry); retry = null; }
25612561 if (source) source.close();
2562 source = since ? new EventSource('/events?since=' + encodeURIComponent(since)) : new EventSource('/events');
2562 // A page on a repository says so (data-presence): the stream takes a seat on its together line.
2563 var on = document.querySelector ? document.querySelector('[data-presence]') : null;
2564 here = on ? on.getAttribute('data-presence') : '';
2565 var seat = here ? 'here=' + encodeURIComponent(here) : '';
2566 source = since ? new EventSource('/events?since=' + encodeURIComponent(since) + (seat ? '&' + seat : '')) : seat ? new EventSource('/events?' + seat) : new EventSource('/events');
25632567 source.addEventListener('open', function () { state('open'); });
25642568 source.addEventListener('error', function () {
25652569 state('reconnecting');
@@ -2601,6 +2605,12 @@ export const liveRegionsJs = /* js */ `
26012605 });
26022606 // Back online: reconnect from the last id and look at every region once,
26032607 // in case the replay window no longer reaches back that far.
2608 // The page moved to another repository: the stream moves its seat, resuming from the last id.
2609 var here = '';
2610 document.addEventListener('forge:here', function () {
2611 var on = document.querySelector ? document.querySelector('[data-presence]') : null;
2612 if ((on ? on.getAttribute('data-presence') : '') !== here) connect();
2613 });
26042614 window.addEventListener('online', function () {
26052615 connect();
26062616 Array.prototype.forEach.call(document.querySelectorAll('[data-live]'), function (r) { if (r.id) due[r.id] = true; });
src/web/pages/repo.ts +5 −2
@@ -8,6 +8,7 @@
88 * path segment and can never smuggle a path of its own.
99 */
1010
11 import { togetherHtml } from "../together.ts";
1112 import { DELETING_SAYS } from "../../core/repo_deleting.ts";
1213 import { downloadHeaders } from "../../drop/store.ts";
1314 import type { BlobForRender } from "../../git/read.ts";
@@ -97,7 +98,7 @@ import { blobHoldsPrivateKey, holdsPrivateKey, PRIVATE_KEY_NOTICE } from "../../
9798 import { countLines, highlightPrefix } from "../code.ts";
9899 import { tailOf, tailSentence } from "../log_tail.ts";
99100 import { latestWave } from "../../story/waves.ts";
100 import { notePhase, takeSessionTime, timePhaseAsync } from "../../core/route_timing.ts";
101 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
101102 import { liveClientJs, liveMount } from "../live.ts";
102103 import { appStrip } from "./apps.ts";
103104 import { growthBody, isAdmin } from "./growth_panel.ts";
@@ -1627,13 +1628,15 @@ async function codeHome(ctx: Ctx, repo: Repo, appOf: { readonly isApp: boolean;
16271628 creditLine(ctx, repo, scope.source, ref),
16281629 );
16291630 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!));
16301633 const gets = repo.template ? await timePhaseAsync(ctx.request, "template", () => templateCard(ctx.app, repo)) : null;
16311634 const offersHere = forkOffers(ctx.app.db, repo, ctx.auth.user);
16321635 const sizes = await offerSizes(ctx.app, repo, offersHere.map((o) => o.number));
16331636 const rendering = performance.now();
16341637 const body = html`${scopeHeader(ctx, scope, "code", {
16351638 branchCount: refs.branches.length,
1636 })}${credit}${standing}${archivedLine(ctx, repo)}${walletLine(ctx, repo)}${reportLine(ctx, repo)}${movedLine(ctx, repo)}${noApp}${gets}
1639 })}${credit}${together}${standing}${archivedLine(ctx, repo)}${walletLine(ctx, repo)}${reportLine(ctx, repo)}${movedLine(ctx, repo)}${noApp}${gets}
16371640 ${offerUpstream(repo, parent, offer)}
16381641 ${forkOffersCard(repo, offersHere, sizes)}
16391642 ${parent === undefined ? "" : sentOffersCard(repo, parent, sentOffers(ctx.app.db, repo, ctx.auth.user))}
src/web/pages/talk_client.ts +43 −6
@@ -402,7 +402,7 @@ export const liveJs = `
402402 * Runs after DOMContentLoaded (`pageScriptAsset`). Reads the page's own `data-talk-*`; sends with
403403 * fetch, follows with EventSource.
404404 */
405 export const talkJs = `
405 const talkSource = `
406406 const root = document.querySelector("[data-talk]");
407407 if (root) {
408408 const log = root.querySelector(".talk-log");
@@ -707,7 +707,8 @@ if (root) {
707707 log.removeAttribute("aria-busy");
708708 mode(false); dropActs(true); if (hush) hush = false; else say("The forge replied."); source.close(); source = null;
709709 setTimeout(() => { if (status.textContent === "The forge replied.") say(""); }, 4000);
710 reframe();
710 // A turn's end reloads only a build's own frame: nothing else moves the frame but a landing.
711 if (document.querySelector(".talk-build")) reframe();
711712 pullBuild();
712713 const o = JSON.parse(e.data), c = root.querySelector("[data-context]"), t = root.querySelector("[data-total]");
713714 // A reply that made an app or set the crew on one opens the pane: the page is drawn again once,
@@ -741,7 +742,8 @@ if (root) {
741742 toLine.firstElementChild.textContent = href ? "To " + who + ": it is said on the issue, to whoever works on it." : "";
742743 box.focus();
743744 };
744 root.addEventListener("click", (e) => {
745 // A Reply anywhere on the page (a receipt, the together line's "Reply to ben") points the composer.
746 document.addEventListener("click", (e) => {
745747 const r = e.target.closest && e.target.closest("[data-reply]");
746748 if (r && !e.metaKey && !e.ctrlKey && !e.shiftKey) { e.preventDefault(); talkTo(r.dataset.reply, r.dataset.replyTo); }
747749 if (e.target.closest && e.target.closest("[data-to-off]")) talkTo("", "");
@@ -966,10 +968,37 @@ ${dictateJs}
966968 }
967969 while (steps.children.length > ${STEPS_SHOWN}) steps.firstElementChild.remove();
968970 });
971 // The together line's landing: said once per landing; when the pane is on Live it is the one thing
972 // that reloads the frame: now, if production deployed since the last merge, else at its deploy (no
973 // clock). Dismissed landings are kept per person, so a later swap does not say them again.
974 let landing = "", live = false;
975 const offKey = "together-off:" + (root.dataset.user || "");
976 const offs = () => { try { return JSON.parse(localStorage.getItem(offKey) || "[]"); } catch (_) { return []; } };
977 const landSaid = new Set([...document.querySelectorAll("[data-landed]")].map((p) => p.dataset.landed));
978 const quiet = () => document.querySelectorAll("[data-landed]").forEach((p) => { p.hidden = offs().includes(p.dataset.landed); });
979 document.addEventListener("forge:swapped", (e) => {
980 const p = e.target.id === "together" && e.target.querySelector("[data-landed]");
981 quiet();
982 if (!p || landSaid.has(p.dataset.landed)) return;
983 landSaid.add(p.dataset.landed);
984 const stage = document.querySelector("[data-stage][data-env]");
985 if (!stage || stage.dataset.env !== "production") return;
986 if (live) reframe(); else landing = p.dataset.landed;
987 });
988 document.addEventListener("click", (e) => {
989 const off = e.target.closest && e.target.closest("[data-landed-off]"), p = off && off.closest("[data-landed]");
990 if (!p) return;
991 try { localStorage.setItem(offKey, JSON.stringify([p.dataset.landed, ...offs()].slice(0, 20))); } catch (_) {}
992 quiet();
993 });
994 quiet();
969995 document.addEventListener("forge:event", (e) => {
970996 const d = e.detail, pane = document.querySelector("[data-pane-of]"), stage = pane && pane.querySelector("[data-stage][data-env]");
997 if (d && pane && d.kind === "pull.merged" && d.repo === pane.dataset.paneOf) live = false;
971998 if (!d || !stage || d.kind !== "run.finished" || !d.payload || d.payload.kind !== "deploy" || d.payload.state !== "ok" || d.repo !== pane.dataset.paneOf) return;
972 if (d.payload.env === stage.dataset.env) { reframe(); return; }
999 if (d.payload.env === "production") live = true;
1000 // On Live, only a landing the together line has said moves the frame; a preview moves with its pushes.
1001 if (d.payload.env === stage.dataset.env) { if (d.payload.env !== "production") reframe(); else if (landing) { landing = ""; reframe(); } return; }
9731002 if (answering || box.value.trim()) return;
9741003 // Another of the repository's environments came up (a draft's preview as its builder pushes, or
9751004 // production once the pull lands): the pane is read again. When it now frames another
@@ -1005,6 +1034,7 @@ ${dictateJs}
10051034 if (head && mine && !mine.contains(document.activeElement)) mine.replaceWith(head);
10061035 shell.append(work);
10071036 shell.setAttribute("data-split", "");
1037 document.dispatchEvent(new Event("forge:here"));
10081038 } catch (_) {}
10091039 }
10101040 // A deploy that turns running swaps the frame into the waiting pane; one on another origin than the
@@ -1128,7 +1158,7 @@ ${dictateJs}
11281158 const t = document.createElement("template");
11291159 t.innerHTML = await (await fetch(href + "&fragment=pane")).text();
11301160 const p = t.content.querySelector(".talk-pane");
1131 if (p) { shell.querySelector(".talk-pane").replaceWith(p); codePane(); p.querySelectorAll("[data-frame]").forEach(watchFrame); p.dispatchEvent(new Event("forge:swapped", { bubbles: true })); }
1161 if (p) { shell.querySelector(".talk-pane").replaceWith(p); codePane(); p.querySelectorAll("[data-frame]").forEach(watchFrame); p.dispatchEvent(new Event("forge:swapped", { bubbles: true })); document.dispatchEvent(new Event("forge:here")); }
11321162 } catch (_) { say("Could not load that; no connection."); }
11331163 });
11341164 // The pane's address bar: a pick (a repository, a version, a path) swaps the pane in place, the
@@ -1149,7 +1179,7 @@ ${dictateJs}
11491179 const t = document.createElement("template");
11501180 t.innerHTML = await (await fetch("?" + q)).text();
11511181 const p = t.content.querySelector(".talk-pane");
1152 if (p && now.isConnected) { now.replaceWith(p); codePane(); p.querySelectorAll("[data-frame]").forEach(watchFrame); p.dispatchEvent(new Event("forge:swapped", { bubbles: true })); }
1182 if (p && now.isConnected) { now.replaceWith(p); codePane(); p.querySelectorAll("[data-frame]").forEach(watchFrame); p.dispatchEvent(new Event("forge:swapped", { bubbles: true })); document.dispatchEvent(new Event("forge:here")); }
11531183 } catch (_) { say("Could not load that; no connection."); }
11541184 };
11551185 const picked = (form, repoChanged) => { const q = new URLSearchParams(); for (const k of AT) if (form.elements[k]) q.set(k, form.elements[k].value); const at = atOf(q); if (repoChanged) at.delete("show"); return at; };
@@ -1217,3 +1247,10 @@ ${dictateJs}
12171247 codePane();
12181248 }
12191249 `;
1250
1251 /**
1252 * The page's script as it is sent: its source without its whole-line `//` comments, which stay here
1253 * for whoever reads the code and cost the reader's browser nothing. A comment after code on the same
1254 * line is kept, so nothing a line means can be cut.
1255 */
1256 export const talkJs = talkSource.replace(/^[ \t]*\/\/.*\n/gm, "");
src/web/pages/talk_preview.ts +3 −1
@@ -26,6 +26,7 @@ import { emptyLine } from "../empty_words.ts";
2626 import { btn, icon, iconBtn } from "../ui.ts";
2727 import type { ChatBuild } from "../../core/chat_build.ts";
2828 import { codeView, diffView } from "../talk_code.ts";
29 import { togetherHtml } from "../together.ts";
2930
3031 export interface Pane {
3132 readonly html: Html;
@@ -121,7 +122,7 @@ export async function talkPane(ctx: Ctx, user: User, name: string | undefined, w
121122 frame: ws.origin ?? (going ? productionOrigin(ctx, ws.repo.id) : undefined),
122123 live: url !== undefined,
123124 crew: going,
124 html: html`<aside class="talk-pane" id="talk-pane" aria-label="Preview of ${name}" data-pane-of="${name}" data-pane-q="${q}"${waiting ? html` data-live="run.*" data-live-repo="${ws.repo.ownerName}/${ws.repo.name}" data-live-src="${liveSrc}"` : null}>
125 html: html`<aside class="talk-pane" id="talk-pane" aria-label="Preview of ${name}" data-pane-of="${name}" data-presence="${name}" data-pane-q="${q}"${waiting ? html` data-live="run.*" data-live-repo="${ws.repo.ownerName}/${ws.repo.name}" data-live-src="${liveSrc}"` : null}>
125126 <div class="talk-pane-bar">
126127 <nav class="seg" aria-label="Preview, code or diff">${tab("preview", "Preview")}${tab("code", "Code")}${tab("diff", "Diff")}</nav>
127128 ${bar}
@@ -129,6 +130,7 @@ export async function talkPane(ctx: Ctx, user: User, name: string | undefined, w
129130 ${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" })}
130131 </div>
131132 <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`)}
132134 ${fellLine}
133135 ${panel}
134136 </aside>`,
src/web/together.ts added +80
@@ -0,0 +1,80 @@
1 /**
2 * The together line on the page (Talk's pane, a repository's page): who else is here and the crew
3 * building, the last few things done, and once, that someone's change landed. A live region of its
4 * own (`presence.*` when someone comes or goes, `pull.*` and `run.*` as work moves), read from
5 * `/:owner/:name/together`, so nothing else on the page is redrawn for it. Quiet: when the viewer is
6 * alone and nothing was done lately it is empty and takes no room (it needs no styles of its own:
7 * lines of the shared `.small` and `.muted`); nothing in it moves but its words.
8 * Only for a signed-in reader of the repository; anyone else is answered as a repository they cannot
9 * see is.
10 */
11 import { canRead, getRepo, type Repo } from "../core/repos.ts";
12 import type { User } from "../core/users.ts";
13 import { agoWords, togetherOf } from "../design/together.ts";
14 import { time } from "./time_element.ts";
15 import type { Ctx } from "../http/context.ts";
16 import { notFoundPage } from "./chrome.ts";
17 import { notePhase, takeSessionTime } from "../core/route_timing.ts";
18 import { html, type Html } from "./html.ts";
19 import { fragment } from "./layout.ts";
20
21 /**
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.
24 */
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}`;
34 return html`<div
35 class="together"
36 id="together"
37 data-live="presence.*,pull.*,run.*"
38 data-live-repo="${name}"
39 data-live-src="/${name}/together"
40 data-presence="${name}"
41 >
42 ${t.here === undefined
43 ? null
44 : html`<p class="together-here small muted">${t.here.words}</p>`}${t.lately.length === 0
45 ? null
46 : html`<p class="together-lately small muted">
47 <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
49 ? 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
56 ? 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>`;
68 }
69
70 /** GET /:owner/:name/together: the region alone, for its live swap. */
71 export function togetherFragment(ctx: Ctx): Response {
72 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
73 const user = ctx.auth.user;
74 const repo = getRepo(ctx.app.db, ctx.params["owner"] ?? "", ctx.params["name"] ?? "");
75 if (user === undefined || repo === undefined || !canRead(ctx.app.db, repo, user)) return notFoundPage(ctx, { plain: true });
76 const rendering = performance.now();
77 const region = togetherHtml(ctx.app.db, repo, user, `?show=live`);
78 notePhase(ctx.request, "render", performance.now() - rendering);
79 return fragment(region, { request: ctx.request });
80 }
test/job-slices.test.ts +1
@@ -261,6 +261,7 @@ function jobs(): Record<string, () => unknown> {
261261 * on.
262262 */
263263 const UNTIMED: Record<string, string> = {
264 "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",
264265 "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",
265266 "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",
266267 "bring-wait": "a one-shot timer that only resolves a promise when a bring's mirror is still copying after 60 s, so the answer says it is copying (actions/bring.ts, bringToWork); no work of its own; talk-bring.test.ts brings a repository that settles first",
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 and render in order", async () => {
55 test("a repository home names session, appof, refs, tree, readme, following, wave, credit, behind, together 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", "render"]);
60 expect(names).toEqual(["app", "session", "appof", "refs", "tree", "readme", "following", "wave", "credit", "behind", "together", "render"]);
6161 });
test/talk-live-pane.test.ts +2 −1
@@ -397,7 +397,8 @@ describe("the pane, by the crew's newest run on the repository", () => {
397397 new Function("document", "window", "EventSource", "CustomEvent", "fetch", "location", "setTimeout", "Date", "DOMParser", liveRegionsJs)(doc, window, ES, window.CustomEvent, fetchFn, { href: "http://localhost/talk/c1" }, now, Date, window.DOMParser);
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");
400 expect(asked).toEqual(["?pane=preview&fragment=pane"]);
400 // The crew region reads the pane once; the together line, a region of its own, reads its own.
401 expect(asked.sort()).toEqual([`/${name}/together`, "?pane=preview&fragment=pane"]);
401402 expect(doc.querySelector("#talk-crew-now")!.textContent).toContain("Changed src/a.ts");
402403 // The frame is the same element at the same address: never redrawn for the crew.
403404 expect(doc.querySelector("iframe")).toBe(frame);
test/talk-page.test.ts +32 −1
@@ -635,13 +635,14 @@ describe("the page", () => {
635635 expect(t.doc.activeElement).not.toBe(t.box);
636636 });
637637
638 test("when a turn ends the preview frame is loaded again (a push has deployed)", async () => {
638 test("when a turn ends beside a build its frame is loaded again (a push has deployed); with no build a turn moves no frame", async () => {
639639 const t = await boot();
640640 const loads: string[] = [];
641641 const frame = t.doc.createElement("div");
642642 frame.setAttribute("data-frame", "");
643643 Object.defineProperty(frame, "src", { get: () => "https://x.example/", set: (v: string) => loads.push(v) });
644644 t.doc.body.appendChild(frame);
645 t.doc.body.insertAdjacentHTML("beforeend", '<section class="talk-build"></section>');
645646 t.sources.at(-1)!.on["running"]!({ data: "{}" });
646647 expect(loads).toEqual([]);
647648 // Never the address it was opened with: its grant has run out by now. The pane names a fresh one.
@@ -1313,10 +1314,40 @@ describe("the page", () => {
13131314 const deploy = (env: string, repo = "alice/x") => t.doc.dispatchEvent(new t.window.CustomEvent("forge:event", { detail: { kind: "run.finished", repo, payload: { kind: "deploy", state: "ok", env } } }));
13141315 deploy("production", "bob/other");
13151316 expect(t.doc.querySelector("[data-stage]").hasAttribute("data-busy")).toBe(false);
1317 // On Live, a deploy alone never moves the frame: only a landing the together line has said does.
1318 deploy("production");
1319 expect(t.doc.querySelector("[data-stage]").hasAttribute("data-busy")).toBe(false);
1320 t.doc.body.insertAdjacentHTML("beforeend", '<div id="together"></div>');
1321 const together = t.doc.querySelector("#together");
1322 together.innerHTML = '<p data-landed="e9">ben&#39;s change landed: Live has it now.</p>';
1323 together.dispatchEvent(new t.window.CustomEvent("forge:swapped", { bubbles: true }));
1324 // Said after production deployed (no merge since): the frame moves now, once.
1325 expect(t.doc.querySelector("[data-stage]").hasAttribute("data-busy")).toBe(true);
1326 t.doc.querySelector("[data-stage]").removeAttribute("data-busy");
1327 together.dispatchEvent(new t.window.CustomEvent("forge:swapped", { bubbles: true }));
1328 expect(t.doc.querySelector("[data-stage]").hasAttribute("data-busy")).toBe(false);
1329 // On a pull's preview a landing is said and the frame stays where the person put it.
1330 t.doc.querySelector("[data-stage]").setAttribute("data-env", "pull-2");
1331 together.innerHTML = '<p data-landed="e12">ben&#39;s change landed: Live has it now.</p>';
1332 together.dispatchEvent(new t.window.CustomEvent("forge:swapped", { bubbles: true }));
1333 expect(t.doc.querySelector("[data-stage]").hasAttribute("data-busy")).toBe(false);
1334 t.doc.querySelector("[data-stage]").setAttribute("data-env", "production");
1335 // Merged, and said before production has deployed it: nothing moves until the deploy, which
1336 // then moves it once. The order of the events decides, never a clock.
1337 t.doc.dispatchEvent(new t.window.CustomEvent("forge:event", { detail: { kind: "pull.merged", repo: "alice/x", payload: { number: 11 } } }));
1338 together.innerHTML = '<p data-landed="e11">maya&#39;s change landed: Live has it now.</p>';
1339 together.dispatchEvent(new t.window.CustomEvent("forge:swapped", { bubbles: true }));
1340 expect(t.doc.querySelector("[data-stage]").hasAttribute("data-busy")).toBe(false);
1341 deploy("production");
1342 expect(t.doc.querySelector("[data-stage]").hasAttribute("data-busy")).toBe(true);
1343 t.doc.querySelector("[data-stage]").removeAttribute("data-busy");
13161344 // The frame's address holds a grant signed for two minutes: the reload asks the pane again and
13171345 // loads the fresh address it names, never the one it was opened with (0.7.648's white frame).
13181346 const frame = t.doc.querySelector("[data-frame]");
13191347 t.page.html = '<aside class="talk-pane"><div class="talk-stage" data-stage data-env="production"><iframe data-frame src="http://app.test/__forge/grant?t=fresh"></iframe></div></aside>';
1348 // Another landing said just after production deployed: it moves the frame, to the fresh address.
1349 together.innerHTML = '<p data-landed="e10">maya&#39;s change landed: Live has it now.</p>';
1350 together.dispatchEvent(new t.window.CustomEvent("forge:swapped", { bubbles: true }));
13201351 deploy("production");
13211352 expect([t.doc.querySelector("[data-stage]").hasAttribute("data-busy"), reloads]).toEqual([true, 0]);
13221353 await pollUntil(() => frame.getAttribute("src") === "http://app.test/__forge/grant?t=fresh", "the frame on a fresh grant");
test/talk-pane-bar.test.ts +1 −1
@@ -444,7 +444,7 @@ describe("the terminal's pane", () => {
444444 await press(":", "Conversations", "\r", "\r", "p");
445445 let text = tui.screen.toText();
446446 expect(text).toContain("team/shared · Production");
447 expect(text).toContain("o picks the repository, w the version, l a path.");
447 expect(text).toContain("o picks the repository, w the version, l a path, L Live.");
448448 // Diff: the pull this conversation's issue led to, from the same core read as the page's tab.
449449 expect(text).toContain(`#${String(pr.value.number)} The header · open /team/shared/pulls/${String(pr.value.number)}`);
450450 // Another repository the bar offers.
test/together.test.ts added +323
@@ -0,0 +1,323 @@
1 /**
2 * Working together on a repository (the together line): who else is here now, from live streams
3 * only, never stored; what was done lately, in the forge's own words; and once, that someone's change
4 * landed. Exact about who may see whom: a member is named to other readers, a stranger and a signed-out
5 * visitor take no seat and see nothing, and an agent is only ever what it builds.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { createAgent } from "../src/actions/crew.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import { createIssue } from "../src/core/issues.ts";
15 import { addTeamMember, createOrg, createTeam } from "../src/core/orgs.ts";
16 import {
17 SILENT_MS,
18 takeSeat,
19 TABS,
20 usersHere,
21 } from "../src/core/presence.ts";
22 import type { Repo } from "../src/core/repos.ts";
23 import { createRun } from "../src/core/runs.ts";
24 import { createSession } from "../src/core/sessions.ts";
25 import { createUser, type User } from "../src/core/users.ts";
26 import { togetherOf } from "../src/design/together.ts";
27 import { serve, type Servers } from "../src/http/server.ts";
28 import { promote } from "./helpers/members.ts";
29 import { pollUntil } from "./helpers/poll.ts";
30 import { appendTurn, createConversation } from "../src/core/conversations.ts";
31 import { createForgeApp } from "../src/tui/forge.ts";
32 import { headlessTerminal } from "../src/tui/term/terminal.ts";
33 import { settleApp } from "./helpers/tui.ts";
34
35 let dir: string;
36 let app: App;
37 let servers: Servers;
38 let alice: User;
39 let carol: User;
40 let bob: User;
41 let bot: User;
42 let repo: Repo;
43
44 const user = async (name: string, admin = false): Promise<User> => {
45 const made = await createUser(app.db, {
46 origin: "seed",
47 trusted: true,
48 username: name,
49 email: `${name}@forge.local`,
50 password: "a-good-passphrase",
51 adminIfFirst: admin,
52 });
53 if (!made.ok) throw new Error(made.error);
54 promote(app.db, made.value);
55 return made.value;
56 };
57
58 beforeAll(async () => {
59 dir = await mkdtemp(join(tmpdir(), "forge-together-"));
60 app = createApp({ dataDir: dir, port: 0 });
61 servers = await serve(app);
62 const keeper = await user("keeper", true);
63 alice = await user("alice");
64 carol = await user("carol");
65 bob = await user("bob");
66 const agent = await createAgent(app, keeper, { username: "juniper", brief: "builds" });
67 if (!agent.ok) throw new Error(String(agent.error));
68 bot = agent.value.user;
69 // A private repository of a team: alice owns the team, carol writes as a member, bob is a stranger.
70 const org = createOrg(app.db, "team", alice.id);
71 if (!org.ok) throw new Error(org.error);
72 const writers = createTeam(app.db, org.value.id, "writers", "write");
73 if (!writers.ok) throw new Error(writers.error);
74 addTeamMember(app.db, writers.value, carol.id);
75 const made = await createRepo(app, alice, {
76 name: "voxel",
77 visibility: "private",
78 owner: "team",
79 });
80 if (!made.ok) throw new Error(String(made.error));
81 repo = made.value;
82 });
83 afterAll(async () => {
84 servers.stop();
85 app.close();
86 await rm(dir, { recursive: true, force: true });
87 });
88
89 const cookie = (u: User) => ({
90 cookie: `forge_session=${createSession(app.db, u.id).token}`,
91 });
92
93 /** A page's stream on the repository, open until `close`; what it was sent, as text. */
94 function stream(
95 u: User | undefined,
96 here = "team/voxel",
97 ): { close: () => void; heard: () => string } {
98 const stop = new AbortController();
99 let text = "";
100 void fetch(`${servers.url}/events?here=${encodeURIComponent(here)}`, {
101 headers: {
102 accept: "text/event-stream",
103 ...(u === undefined ? {} : cookie(u)),
104 },
105 signal: stop.signal,
106 })
107 .then(async (res) => {
108 const reader = res.body!.getReader();
109 for (;;) {
110 const chunk = await reader.read();
111 if (chunk.done) return;
112 text += new TextDecoder().decode(chunk.value);
113 }
114 })
115 .catch(() => undefined);
116 return { close: () => stop.abort(), heard: () => text };
117 }
118
119 const line = async (
120 u: User | undefined,
121 ): Promise<{ status: number; text: string }> => {
122 const res = await fetch(`${servers.url}/team/voxel/together`, {
123 headers: u === undefined ? {} : cookie(u),
124 });
125 return { status: res.status, text: await res.text() };
126 };
127
128 describe("a public repository", () => {
129 test("only its writers are named; any other signed-in reader is counted, never named, to anyone", async () => {
130 const made = await createRepo(app, alice, { name: "open", visibility: "public", owner: "team" });
131 if (!made.ok) throw new Error(String(made.error));
132 const open = made.value;
133 const dana = await user("dana");
134 const seats = [carol, bob, dana].map((u) => takeSeat(app.db, open.id, u.id, () => undefined));
135 try {
136 // carol writes there (the team's writers); bob and dana only read, as anyone signed in may.
137 expect(togetherOf(app.db, open, alice).here).toEqual({ names: ["carol"], words: "carol is here · 2 others are reading" });
138 expect(togetherOf(app.db, open, bob).here).toEqual({ names: ["carol"], words: "carol is here · 1 other is reading" });
139 expect(togetherOf(app.db, open, carol).here).toEqual({ names: [], words: "2 others are reading" });
140 // The page's region says the same, and never a reader's name.
141 const res = await fetch(`${servers.url}/team/open/together`, { headers: cookie(bob) });
142 const text = await res.text();
143 expect(text).toContain("carol is here · 1 other is reading");
144 expect(text).not.toContain("dana");
145 } finally {
146 for (const s of seats) s.leave();
147 }
148 });
149 });
150
151 describe("who is here", () => {
152 test("a seat is held in memory while a stream is open, given up when it closes, left out after a silence, ", () => {
153 const told: string[] = [];
154 const a = takeSeat(app.db, "r-mem", "u1", () => told.push("u1"));
155 const b = takeSeat(app.db, "r-mem", "u2", () => told.push("u2"));
156 expect(usersHere(app.db, "r-mem")).toEqual(["u1", "u2"]);
157 // The one already there is told someone came; nobody is told of themselves.
158 expect(told).toEqual(["u1"]);
159 b!.leave();
160 expect(told).toEqual(["u1", "u1"]);
161 expect(usersHere(app.db, "r-mem")).toEqual(["u1"]);
162 // A stream that stopped answering is left out, as if gone.
163 expect(usersHere(app.db, "r-mem", Date.now() + SILENT_MS + 1)).toEqual([]);
164 a!.leave();
165 a!.leave();
166 expect(usersHere(app.db, "r-mem")).toEqual([]);
167 });
168
169 test("one seat per person: a hundred streams of one person are one seat, keep at most TABS to tell, and a second person still appears", () => {
170 const told: number[] = [];
171 const many = Array.from({ length: 100 }, (_, i) => takeSeat(app.db, "r-one", "hog", () => told.push(i)));
172 expect(usersHere(app.db, "r-one")).toEqual(["hog"]);
173 // Their own later tabs tell nobody: the person was already here.
174 expect(told).toEqual([]);
175 const late = takeSeat(app.db, "r-one", "late", () => undefined);
176 expect(usersHere(app.db, "r-one")).toEqual(["hog", "late"]);
177 // The person's newest TABS streams are told someone came; the ones let go are not.
178 expect(told).toEqual(Array.from({ length: TABS }, (_, i) => 100 - TABS + i));
179 // Every stream closing but one keeps them here; the last one closing takes them off the line.
180 for (const s of many.slice(0, -1)) s.leave();
181 expect(usersHere(app.db, "r-one")).toEqual(["hog", "late"]);
182 many.at(-1)!.leave();
183 expect(usersHere(app.db, "r-one")).toEqual(["late"]);
184 late.leave();
185 expect(usersHere(app.db, "r-one")).toEqual([]);
186 });
187
188 test("a member is named to another reader, and the reader's page is told; a stranger, a signed-out visitor and an agent take no seat", async () => {
189 const mine = stream(alice);
190 await pollUntil(
191 () => usersHere(app.db, repo.id).includes(alice.id),
192 "alice's seat",
193 );
194 const theirs = stream(carol);
195 await pollUntil(
196 () => usersHere(app.db, repo.id).includes(carol.id),
197 "carol's seat",
198 );
199 await pollUntil(
200 () =>
201 mine.heard().includes('"kind":"presence.changed","repo":"team/voxel"'),
202 "alice told carol came",
203 );
204 expect((await line(alice)).text).toContain("carol is here");
205 expect((await line(carol)).text).toContain("alice is here");
206 // A stranger asks for a seat on a private repository: none, and the line is a not-found to them.
207 const stranger = stream(bob);
208 const outsider = stream(undefined);
209 const agent = stream(bot);
210 for (let i = 0; i < 20; i++) await Promise.resolve();
211 await pollUntil(
212 async () => (await line(alice)).text.includes("carol is here"),
213 "the line read again",
214 );
215 expect(usersHere(app.db, repo.id).sort()).toEqual(
216 [alice.id, carol.id].sort(),
217 );
218 expect((await line(alice)).text).not.toContain("bob");
219 expect((await line(bob)).status).toBe(404);
220 expect((await line(undefined)).status).toBe(404);
221 // The agent is only what it builds.
222 const issue = createIssue(app.db, {
223 repoId: repo.id,
224 authorId: alice.id,
225 title: "Shadows",
226 body: "b",
227 });
228 if (!issue.ok) throw new Error("issue");
229 const run = createRun(app.db, {
230 repoId: repo.id,
231 kind: "agent",
232 issueId: issue.value.id,
233 reason: "assigned",
234 actorId: bot.id,
235 });
236 app.db.run("UPDATE run SET state = 'running' WHERE id = ?1", [run.id]);
237 const withCrew = (await line(alice)).text.replace(/\s+/g, " ");
238 expect(withCrew).toContain(
239 `carol is here · juniper is building #${String(issue.value.number)}`,
240 );
241 expect(withCrew.match(/juniper/g)).toHaveLength(1);
242 app.db.run("UPDATE run SET state = 'ok' WHERE id = ?1", [run.id]);
243 // carol leaves: her seat goes with her stream, and alice's page is told.
244 const before = mine.heard().split("presence.changed").length;
245 theirs.close();
246 await pollUntil(
247 () => !usersHere(app.db, repo.id).includes(carol.id),
248 "carol's seat given up",
249 );
250 await pollUntil(
251 () => mine.heard().split("presence.changed").length > before,
252 "alice told carol left",
253 );
254 expect((await line(alice)).text).not.toContain("carol");
255 for (const s of [mine, stranger, outsider, agent]) s.close();
256 });
257 });
258
259 describe("what was done lately, and a landing", () => {
260 test("in the forge's own words, newest first; a landing said once, by whose change it was", async () => {
261 const opened = createIssue(app.db, {
262 repoId: repo.id,
263 authorId: carol.id,
264 title: "Water reflects the sky",
265 body: "b",
266 kind: "pull",
267 });
268 if (!opened.ok) throw new Error("pull");
269 app.bus.append({
270 kind: "pull.opened",
271 repoId: repo.id,
272 actorId: carol.id,
273 payload: { number: opened.value.number },
274 });
275 let t = togetherOf(app.db, repo, alice);
276 expect(t.lately[0]?.words).toBe(
277 `carol opened a pull request: #${String(opened.value.number)} Water reflects the sky`,
278 );
279 expect(t.landed).toBeUndefined();
280 app.bus.append({
281 kind: "pull.merged",
282 repoId: repo.id,
283 actorId: alice.id,
284 payload: { number: opened.value.number },
285 });
286 t = togetherOf(app.db, repo, alice);
287 expect(t.landed?.words).toBe("carol's change landed: Live has it now.");
288 expect(t.landed?.author).toBe("carol");
289 expect(togetherOf(app.db, repo, carol).landed?.words).toBe(
290 "Your change landed: Live has it now.",
291 );
292 // Past its news window it is only in the strip.
293 expect(
294 togetherOf(app.db, repo, alice, Date.now() + 16 * 60_000).landed,
295 ).toBeUndefined();
296 const page = (await line(alice)).text.replace(/\s+/g, " ");
297 expect(page).toContain("carol&#39;s change landed: Live has it now.");
298 expect(page).toContain(
299 `data-reply="/team/voxel/pulls/${String(opened.value.number)}"`,
300 );
301 });
302 });
303
304 describe("the terminal's pane", () => {
305 test("prints who is here, what was done lately and the landing, in the page's words", async () => {
306 const seat = takeSeat(app.db, repo.id, carol.id, () => undefined);
307 const chat = createConversation(app.db, alice.id);
308 if (!chat.ok) throw new Error(chat.error);
309 appendTurn(app.db, alice.id, chat.value.id, { role: "tool", text: `mcp__forge__read_file ${JSON.stringify({ repo: "team/voxel", path: "a" })}` });
310 const terminal = headlessTerminal(160, 40);
311 const { app: tui } = createForgeApp(app, { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice }, { terminal, exitHooks: false });
312 tui.start();
313 for (const k of [":", "Conversations", "\r", "\r", "p"]) {
314 terminal.feed(k);
315 await settleApp(tui);
316 }
317 const text = tui.screen.toText();
318 expect(text).toContain("Here: carol is here");
319 expect(text).toContain("Lately: alice merged a pull request: #2 Water reflects the sky · just now · carol opened a pull request:");
320 expect(text).toContain("carol's change landed: Live has it now. (L shows Live)");
321 seat!.leave();
322 });
323 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs