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

Ship it and watch it go: a change's page follows its own merge to production #1026

Closed opened this
Closed without merging

scout/forge:scout/82-ship-it-and-watch-it-go-a-change-s-page → main 4 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +262 −89
src/http/server.ts +3 −1
@@ -244,7 +244,7 @@ import {
244244 crewPage,
245245 } from "../web/pages/crew.ts";
246246 import { newPullPage, newPullSubmit } from "../web/pages/pulls.ts";
247 import { changePage, pullPage } from "../web/studio/change.ts";
247 import { changePage, pullPage, pullStateFragment } from "../web/studio/change.ts";
248248 import {
249249 pullCommentSubmit,
250250 pullFilesPage,
@@ -930,6 +930,8 @@ export function buildRouter(): Router<Handler> {
930930 threadResolveSubmit(false),
931931 );
932932 router.add("POST", "/:owner/:name/pulls/:number/merge", pullMergeSubmit);
933 // The change page's live refresh: head, check line and preview, bare.
934 router.add("GET", "/:owner/:name/pulls/:number/state", pullStateFragment);
933935 router.add("POST", "/:owner/:name/pulls/:number/state", (ctx) =>
934936 stateSubmit(ctx, "pull"),
935937 );
src/web/live.ts +61
@@ -43,6 +43,13 @@ export interface LiveConfig {
4343 * rather than only offering the pill.
4444 */
4545 app?: boolean;
46 /**
47 * The studio change page: the pull's own merge, a deploy run for its
48 * preview, and production serving at its head (or the commit its merge
49 * made) fetch `<repo>/pulls/<n>/state` and swap the head and preview in
50 * place. Nothing else does.
51 */
52 change?: { head: string; merged: string | null };
4653 }
4754
4855 /** The config element, the polite status line, and the (hidden) activity pill. */
@@ -56,6 +63,9 @@ export function liveMount(config: LiveConfig): Html {
5663 data-number="${config.number ?? ""}"
5764 data-last="${config.lastCommentId ?? ""}"
5865 data-app="${config.app ? "1" : ""}"
66 data-change="${config.change ? "1" : ""}"
67 data-head="${config.change?.head ?? ""}"
68 data-merged="${config.change?.merged ?? ""}"
5969 ></div>
6070 <p
6171 class="live-status"
@@ -77,6 +87,9 @@ export const liveClientJs = /* js */ `
7787 var number = cfg.getAttribute('data-number');
7888 var lastId = cfg.getAttribute('data-last') || '';
7989 var isApp = cfg.getAttribute('data-app') === '1';
90 var isChange = cfg.getAttribute('data-change') === '1';
91 var headOid = cfg.getAttribute('data-head') || '';
92 var mergedOid = cfg.getAttribute('data-merged') || '';
8093 var pill = document.getElementById('live-pill');
8194 var status = document.getElementById('live-status');
8295 var conv = document.getElementById('conversation');
@@ -227,9 +240,57 @@ export const liveClientJs = /* js */ `
227240 });
228241 }
229242
243 // The change page: its head, check line and preview, refetched from
244 // <repo>/pulls/<n>/state when this pull merges, when its preview deploys,
245 // or when production serves this change's head or merge commit.
246 var changeBusy = false, changeQueued = false;
247 function isChangeEvent(data) {
248 if (!isChange || !data || !data.kind || !data.payload) return false;
249 var p = data.payload;
250 if (data.kind === 'pull.merged') {
251 if (String(p.number) !== String(number)) return false;
252 if (typeof p.mergeOid === 'string') mergedOid = p.mergeOid;
253 return true;
254 }
255 if (data.kind.indexOf('run.') === 0) return p.env === 'pull-' + number;
256 if (data.kind === 'app.serving') {
257 return p.env === 'production' && typeof p.commitOid === 'string' &&
258 (p.commitOid === headOid || (mergedOid !== '' && p.commitOid === mergedOid));
259 }
260 return false;
261 }
262 function refreshChange() {
263 if (changeBusy) { changeQueued = true; return; }
264 changeBusy = true;
265 fetch(repo + '/pulls/' + number + '/state', { headers: { accept: 'text/html' } })
266 .then(function (r) { return r.ok ? r.text() : ''; })
267 .then(function (text) {
268 if (!text) return;
269 var holder = document.createElement('div');
270 holder.innerHTML = text;
271 var before = textOf(document.getElementById('pull-check'));
272 ['pull-check', 'pull-preview'].forEach(function (id) {
273 var mine = document.getElementById(id);
274 var theirs = holder.querySelector('#' + id);
275 if (mine && theirs) mine.replaceWith(theirs);
276 });
277 var now = document.getElementById('pull-check');
278 var badge = now && now.querySelector('.studio-pull-check .badge');
279 if (status && badge && textOf(now) !== before) {
280 status.textContent = textOf(badge).charAt(0).toUpperCase() + textOf(badge).slice(1);
281 }
282 })
283 .catch(function () {})
284 .then(function () {
285 changeBusy = false;
286 if (changeQueued) { changeQueued = false; refreshChange(); }
287 });
288 }
289
230290 function onEvent(e) {
231291 var data;
232292 try { data = JSON.parse(e.data); } catch (_) { return; }
293 if (isChangeEvent(data)) { refreshChange(); return; }
233294 if (isDeploy(data) || isServing(data)) { refreshApp(); return; }
234295 if (relevant(data) && conv && (data.kind === thread + '.commented')) {
235296 appendNew();
src/web/studio/change.ts +31 −86
@@ -39,7 +39,7 @@ import {
3939 } from "../chrome.ts";
4040 import { html, when, type Html } from "../html.ts";
4141 import type { IconName as Glyph } from "../icons.ts";
42 import { page, redirect } from "../layout.ts";
42 import { fragment, page, redirect } from "../layout.ts";
4343 import { renderMarkdown } from "../markdown.ts";
4444 import { liveClientJs, liveMount } from "../live.ts";
4545 import {
@@ -74,11 +74,9 @@ import {
7474 KIND_TIER,
7575 type Decision,
7676 } from "./asks.ts";
77 import { tellLine, tellsAnswered } from "./branch_tell.ts";
7877 import { holdCard } from "./hold.ts";
79 import { pullMayRun } from "../../core/pull_trust.ts";
8078 import { changeHref } from "./nouns.ts";
81 import { pullWord, servingHistory, wordBadge, type WordCtx } from "./words.ts";
79 import { conflictWords, pullPanels } from "./previews.ts";
8280
8381 /** The pull and its repo, or the response that refuses to say why not. */
8482 export function pullContext(ctx: Ctx): { repo: Repo; pull: Pull } | Response {
@@ -232,15 +230,6 @@ export function changeTabs(
232230 </div>`;
233231 }
234232
235 /** What a conflicted change's own page says: the base it no longer merges
236 * into, the first few files (bounded, so a huge conflict never floods the
237 * page), and what fixes it. */
238 function conflictWords(baseBranch: string, files: readonly string[]): string {
239 const shown = files.slice(0, 3).join(", ");
240 const more = files.length > 3 ? `, and ${files.length - 3} more` : "";
241 return `it conflicts with ${baseBranch} in ${shown}${more} — bring the branch up to date and it can land`;
242 }
243
244233 /**
245234 * GET /:owner/:name/pulls/:number and /changes/:number: one page, two
246235 * addresses, for every repository and every viewer. An older `?rc=` link (an inline comment form
@@ -281,63 +270,14 @@ async function changeConversation(
281270 // `/pulls/:number`, whether a reader arrived there or at
282271 // `/changes/:number` (`changeHref`, nouns.ts).
283272 const thread = `${base}/pulls/${pull.number}`;
284 const wordCtx: WordCtx = {
285 db,
286 // The change is read where its objects are (`pullDir`).
287 dir: await pullDir(db, ctx.app.reposRoot, repo, pull),
288 runtime: appsRuntime(ctx.app),
289 record,
290 history: servingHistory(),
291 viewer: ctx.auth.user,
292 };
293 const { word, note: checkNote } = await pullWord(wordCtx, pull);
294 // Whether this change still merges into its base is asked here, on its own
295 // page, and nowhere a list of changes renders — a git call per open pull
296 // would undo the home's own bound (`askCandidatesFor`). Only an open,
297 // unmerged pull can conflict; a merged or closed one already has its word.
298 // The review gate rides along, so the decision below never offers Ship on
299 // a change `mergePull` would refuse for want of an approval.
300 const status =
301 pull.mergedAt === null && pull.state !== "closed"
302 ? await pullStatus(wordCtx.dir, pull, {
303 db,
304 requireReview: repo.requireReview,
305 })
306 : undefined;
273 const { panels, dir, word, note, status, conflicted } =
274 await pullPanels(ctx, repo, pull, record);
307275 // A change that loosens the policy is a person's call: said here, above
308276 // the decision, as well as on the Files step beside the merge box.
309277 const wall =
310278 status === undefined
311279 ? undefined
312 : await wallOf(wordCtx.dir, status.baseOid, status.headOid);
313 const conflicted =
314 status !== undefined && !status.mergeable && status.conflicts.length > 0;
315 // A reader's head runs nothing until a writer approves it (#777): say
316 // that, rather than leave a word waiting on something that will not come.
317 const waitingOnApproval =
318 status !== undefined && !pullMayRun(db, repo, pull, status.headOid);
319 const note = conflicted
320 ? conflictWords(pull.baseBranch, status.conflicts)
321 : waitingOnApproval
322 ? "checks and the preview wait for a writer to approve this head"
323 : checkNote;
324 // Before a merge the deploy worth linking is the preview's own check;
325 // after, it is production's — the preview's run may already be torn
326 // down, and the word above is judged by production regardless.
327 let deploy: { id: string; commitOid: string } | undefined;
328 if (pull.mergedAt === null) {
329 const run = checkSummary(db, pull.id, pull.headOid).run;
330 if (run) deploy = { id: run.id, commitOid: run.commitOid };
331 } else {
332 const production =
333 record === undefined
334 ? undefined
335 : envsFor(ctx.app, ctx.auth.user, record).find(
336 (e) => e.env === "production",
337 );
338 if (production?.runId)
339 deploy = { id: production.runId, commitOid: production.commitOid };
340 }
280 : await wallOf(dir, status.baseOid, status.headOid);
341281 const crewDecision = decisionsFor(ctx, [repo], { evenDismissed: true }).find(
342282 (d) => d.pull?.id === pull.id,
343283 );
@@ -397,25 +337,6 @@ async function changeConversation(
397337 ? note
398338 : undefined;
399339
400 const checkLine = card(
401 html`<p class="studio-pull-check">
402 ${wordBadge(word)} <span class="muted small">${note}</span>
403 ${when(
404 tellsAnswered(db, repo.id, [pull]).get(pull.number),
405 (t) => html`<span class="where-sep" aria-hidden="true">·</span
406 >${tellLine(base, t)}`,
407 )}
408 ${when(
409 deploy,
410 (d) =>
411 html`<span class="where-sep" aria-hidden="true">·</span
412 ><a href="${base}/runs/${d.id}"
413 >deploy ${d.commitOid.slice(0, 7)}</a
414 >`,
415 )}
416 </p>`,
417 );
418
419340 // A conflicted change never offers Ship as though it would work — pressing
420341 // it would only be refused. The button that helps posts to the very same
421342 // route (`/ship`): `shipSubmit` already turns a conflict there into the
@@ -497,7 +418,7 @@ async function changeConversation(
497418 ownTitle: true,
498419 })}
499420 ${changeHead(ctx, repo, pull)} ${changeTabs(repo, pull, "change")}
500 ${checkLine} ${holdCard(ctx, repo, pull, { act: true })}
421 ${panels.check} ${holdCard(ctx, repo, pull, { act: true })}
501422 ${when(wall, (w) => wallCard(w))} ${decisionSection}
502423 ${takeBackSection}
503424 ${when(record, (r) => lookCard(ctx, repo, r, pull, pull.headOid))}
@@ -518,7 +439,7 @@ async function changeConversation(
518439 crewNote: threadNote(ctx.app.db, repo, pull),
519440 })}
520441 </div>
521 <aside>${when(record, () => previewCard(ctx, repo, pull))}</aside>
442 ${panels.preview}
522443 </div>
523444 ${decision ? decisionForm(decision) : null}
524445 ${liveMount({
@@ -526,6 +447,7 @@ async function changeConversation(
526447 thread: "pull",
527448 number: pull.number,
528449 lastCommentId: talk.lastCommentId,
450 change: { head: pull.headOid, merged: pull.mergedOid },
529451 })}`;
530452
531453 return page({
@@ -537,3 +459,26 @@ async function changeConversation(
537459 scriptJs: liveClientJs,
538460 });
539461 }
462
463 /**
464 * GET /:owner/:name/pulls/:number/state — the check line and the preview
465 * card, bare. The change page's live client (`live.ts`) fetches this on the
466 * pull's own merge, on a deploy run for its preview, and on production
467 * serving, and swaps the two regions in place. Authorized as the page is
468 * (`pullContext`): a viewer who cannot see the repository or the pull gets
469 * the same 404.
470 */
471 export async function pullStateFragment(ctx: Ctx): Promise<Response> {
472 const found = pullContext(ctx);
473 if (found instanceof Response) return fragment(html``, { status: 404 });
474 const { repo, pull } = found;
475 const { panels } = await pullPanels(
476 ctx,
477 repo,
478 pull,
479 getAppByRepo(ctx.app.db, repo.id),
480 );
481 return fragment(html`<div>${panels.check}${panels.preview}</div>`, {
482 request: ctx.request,
483 });
484 }
src/web/studio/previews.ts +135 −2
@@ -15,9 +15,11 @@ import {
1515 type AppsRuntime,
1616 type EnvStatus, envsFor } from "../../apps/runtime.ts";
1717 import { getAppByRepo, type AppRecord } from "../../core/apps.ts";
18 import { listPulls, type Pull } from "../../core/pulls.ts";
18 import { listPulls, pullDir, pullStatus, type Pull } from "../../core/pulls.ts";
1919 import { canSeeOwnerFacts, type Repo } from "../../core/repos.ts";
20 import { listRuns } from "../../core/runs.ts";
20 import { pullMayRun } from "../../core/pull_trust.ts";
21 import { checkSummary, listRuns } from "../../core/runs.ts";
22 import { repoDir } from "../../git/repos.ts";
2123 import type { Ctx } from "../../http/context.ts";
2224 import { readRunLogTail } from "../../runs/log.ts";
2325 import { loadRepo, repoBase } from "../chrome.ts";
@@ -26,6 +28,7 @@ import { fragment } from "../layout.ts";
2628 import {
2729 badge,
2830 btn,
31 card,
2932 dormantNote,
3033 envActions,
3134 envFacts,
@@ -33,11 +36,20 @@ import {
3336 envPhrase,
3437 icon,
3538 listCard,
39 originTag,
40 stateBadge,
3641 previewDataNote,
3742 row,
3843 terminalLine,
44 time,
45 userLink,
3946 } from "../ui.ts";
4047 import { lookNow } from "../pages/looks.ts";
48 import { previewCard } from "../pages/apps.ts";
49 import { pullState } from "../pages/pulls.ts";
50 import { originGlyph } from "../pages/thread.ts";
51 import { tellLine, tellsAnswered } from "./branch_tell.ts";
52 import { pullWord, servingHistory, wordBadge, type Word, type WordCtx } from "./words.ts";
4153 import { LOG_TAIL_CAP, logBox, runVoice } from "./log.ts";
4254
4355 /**
@@ -348,3 +360,124 @@ export function appStateFragment(ctx: Ctx): Response {
348360 return fragment(html`<div id="app-head">${head}</div>
349361 <div id="app-previews">${previews}</div>`, { request: ctx.request });
350362 }
363
364 /** What a conflicted change's own page says: the base it no longer merges
365 * into, the first few files (bounded, so a huge conflict never floods the
366 * page), and what fixes it. */
367 export function conflictWords(
368 baseBranch: string,
369 files: readonly string[],
370 ): string {
371 const shown = files.slice(0, 3).join(", ");
372 const more = files.length > 3 ? `, and ${files.length - 3} more` : "";
373 return `it conflicts with ${baseBranch} in ${shown}${more} — bring the branch up to date and it can land`;
374 }
375
376 /**
377 * The change page's own facts: the check line (word, note, deploy link) and
378 * the preview card. One function, called for the page's first paint and for
379 * the fragment a merge or deploy event refreshes in place
380 * (`pullStateFragment`). Both regions keep their ids and their markup across
381 * a swap, so a change going ready → shipping → shipped moves words in place
382 * and never shifts the layout. The word, the merge status and the directory
383 * the change is read in come back too: the decision card is judged by them.
384 * No diff is computed; `pullWord` and one mergeability check are all the
385 * git it does, and only for a pull still open.
386 */
387 export async function pullPanels(
388 ctx: Ctx,
389 repo: Repo,
390 pull: Pull,
391 record: AppRecord | undefined,
392 ): Promise<{
393 panels: { check: Html; preview: Html };
394 dir: string;
395 word: Word;
396 note: string;
397 status: Awaited<ReturnType<typeof pullStatus>> | undefined;
398 conflicted: boolean;
399 }> {
400 const db = ctx.app.db;
401 const base = repoBase(repo);
402 const wordCtx: WordCtx = {
403 db,
404 // The change is read where its objects are (`pullDir`).
405 dir: await pullDir(db, ctx.app.reposRoot, repo, pull),
406 runtime: appsRuntime(ctx.app),
407 record,
408 history: servingHistory(),
409 viewer: ctx.auth.user,
410 };
411 const { word, note: checkNote } = await pullWord(wordCtx, pull);
412 // Whether this change still merges into its base is asked here, on its own
413 // page, and nowhere a list of changes renders — a git call per open pull
414 // would undo the home's own bound (`askCandidatesFor`). Only an open,
415 // unmerged pull can conflict; a merged or closed one already has its word.
416 // The review gate rides along, so the decision never offers Ship on a
417 // change `mergePull` would refuse for want of an approval.
418 const status =
419 pull.mergedAt === null && pull.state !== "closed"
420 ? await pullStatus(wordCtx.dir, pull, {
421 db,
422 requireReview: repo.requireReview,
423 })
424 : undefined;
425 const conflicted =
426 status !== undefined && !status.mergeable && status.conflicts.length > 0;
427 // A reader's head runs nothing until a writer approves it (#777): say
428 // that, rather than leave a word waiting on something that will not come.
429 const waitingOnApproval =
430 status !== undefined && !pullMayRun(db, repo, pull, status.headOid);
431 const note = conflicted
432 ? conflictWords(pull.baseBranch, status.conflicts)
433 : waitingOnApproval
434 ? "checks and the preview wait for a writer to approve this head"
435 : checkNote;
436 // Before a merge the deploy worth linking is the preview's own check;
437 // after, it is production's — the preview's run may already be torn
438 // down, and the word above is judged by production regardless.
439 let deploy: { id: string; commitOid: string } | undefined;
440 if (pull.mergedAt === null) {
441 const run = checkSummary(db, pull.id, pull.headOid).run;
442 if (run) deploy = { id: run.id, commitOid: run.commitOid };
443 } else {
444 const production =
445 record === undefined
446 ? undefined
447 : envsFor(ctx.app, ctx.auth.user, record).find(
448 (e) => e.env === "production",
449 );
450 if (production?.runId)
451 deploy = { id: production.runId, commitOid: production.commitOid };
452 }
453
454 const check = html`<div id="pull-check">${card(
455 html`<p class="studio-pull-check">
456 ${wordBadge(word)} <span class="muted small">${note}</span>
457 ${when(
458 tellsAnswered(db, repo.id, [pull]).get(pull.number),
459 (t) => html`<span class="where-sep" aria-hidden="true">·</span
460 >${tellLine(base, t)}`,
461 )}
462 ${when(
463 deploy,
464 (d) =>
465 html`<span class="where-sep" aria-hidden="true">·</span
466 ><a href="${base}/runs/${d.id}"
467 >deploy ${d.commitOid.slice(0, 7)}</a
468 >`,
469 )}
470 </p>`,
471 )}</div>`;
472 const preview = html`<aside id="pull-preview">${when(record, () =>
473 previewCard(ctx, repo, pull),
474 )}</aside>`;
475 return {
476 panels: { check, preview },
477 dir: wordCtx.dir,
478 word,
479 note,
480 status,
481 conflicted,
482 };
483 }
test/board-windows.test.ts +3
@@ -283,6 +283,9 @@ describe("efficiency and standing, grouped", () => {
283283 const now = Date.now();
284284 const ago = (h: number) => new Date(now - h * 3_600_000).toISOString();
285285 const live = seedRepo("live", "autonomous");
286 // The earlier test's fixed-date spend on "two" has aged out of the week;
287 // spend on it again, fresh, so it reads $0.40 whatever day this runs.
288 spend(repos.two!, ago(5), 0.4);
286289 spend(live, ago(30), 3);
287290 spend(live, ago(2), 1.5);
288291 merged(live, ago(20));
test/studio.test.ts +29
@@ -4,6 +4,7 @@ import { logBox } from "../src/web/studio/log.ts";
44 * The studio: apps as the unit, three verbs, and a switch to dev. The same
55 * URLs answer in both modes; the cookie decides which face they show.
66 */
7 import { liveClientJs } from "../src/web/live.ts";
78 import { afterAll, beforeAll, describe, expect, spyOn, test } from "bun:test";
89 import { mkdirSync, writeFileSync } from "node:fs";
910 import { mkdtemp, rm } from "node:fs/promises";
@@ -6407,6 +6408,34 @@ describe("a person's own change ships from its own studio page", () => {
64076408 expect(after).toContain('data-word="shipped"');
64086409 });
64096410
6411 test("the change page follows its own ship: a fragment route draws the current word, and the client names it (#82)", async () => {
6412 // The bench change above is shipped by now; its fragment says so,
6413 // drawn by the same `pullPanels` as the page.
6414 const res = await get("/alice/garden/pulls/1/state", ownerCookie);
6415 expect(res.status).toBe(200);
6416 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
6417 expect(res.headers.get("referrer-policy")).toBe("same-origin");
6418 expect(res.headers.get("content-security-policy")).toContain("default-src 'none'");
6419 const text = await res.text();
6420 expect(text).toContain('id="pull-check"');
6421 expect(text).toContain('id="pull-preview"');
6422 expect(text).toContain('data-word="shipped"');
6423 expect(text).not.toContain("<h2>Decide</h2>");
6424 // No such change: the same 404 the page gives.
6425 expect((await get("/alice/garden/pulls/999/state", ownerCookie)).status).toBe(404);
6426 expect((await get("/alice/garden/pulls/x/state", ownerCookie)).status).toBe(404);
6427 expect((await get("/alice/nope/pulls/1/state", ownerCookie)).status).toBe(404);
6428 // The page mounts the client for it, and the script names the path and
6429 // the three events it swaps on.
6430 const page = await (await get("/alice/garden/pulls/1", ownerCookie)).text();
6431 expect(page).toContain('data-change="1"');
6432 expect(page).toContain('id="pull-check"');
6433 expect(liveClientJs).toContain("'/pulls/' + number + '/state'");
6434 expect(liveClientJs).toContain("data.kind === 'pull.merged'");
6435 expect(liveClientJs).toContain("p.env === 'pull-' + number");
6436 expect(liveClientJs).toContain("data.kind === 'app.serving'");
6437 });
6438
64106439 test("a conflicted change alice opened herself offers the bring-up-to-date wording, never a Ship that would be refused", async () => {
64116440 const base1 = await commitToBranch(app, alice, repo, {
64126441 message: "Add a file two branches will fight over",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs