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 #997

Closed opened this
Closed without merging

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

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
5 files changed +248 −83
src/http/server.ts +3 −1
@@ -125,7 +125,7 @@ import { liveFeedFragment } from "../web/studio/feed.ts";
125125 import { serviceWorker } from "../web/sw.ts";
126126 import { liveAppsFragment, liveOnYouFragment } from "../web/studio/home.ts";
127127 import { appNowFragment } from "../web/studio/now.ts";
128 import { appStateFragment } from "../web/studio/previews.ts";
128 import { appStateFragment, pullStateFragment } from "../web/studio/previews.ts";
129129 import { changesList, tellsList } from "../web/studio/lists.ts";
130130 import { DEFAULT_MODE, isMode, modeCookie, type Mode } from "../web/mode.ts";
131131 import { dependencySubmit } from "../web/pages/thread.ts";
@@ -738,6 +738,8 @@ export function buildRouter(): Router<Handler> {
738738 threadResolveSubmit(false),
739739 );
740740 router.add("POST", "/:owner/:name/pulls/:number/merge", pullMergeSubmit);
741 // The change page's live refresh: head, check line and preview, bare.
742 router.add("GET", "/:owner/:name/pulls/:number/state", pullStateFragment);
741743 router.add("POST", "/:owner/:name/pulls/:number/state", (ctx) =>
742744 stateSubmit(ctx, "pull"),
743745 );
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-head'));
272 ['pull-head', '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-head');
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 +9 −80
@@ -38,16 +38,7 @@ import {
3838 decisionsFor,
3939 type Decision,
4040 } from "./asks.ts";
41 import { pullWord, servingHistory, wordBadge, type WordCtx } from "./words.ts";
42
43 /** What a conflicted change's own page says: the base it no longer merges
44 * into, the first few files (bounded, so a huge conflict never floods the
45 * page), and what fixes it. */
46 function conflictWords(baseBranch: string, files: readonly string[]): string {
47 const shown = files.slice(0, 3).join(", ");
48 const more = files.length > 3 ? `, and ${files.length - 3} more` : "";
49 return `it conflicts with ${baseBranch} in ${shown}${more} — bring the branch up to date and it can land`;
50 }
41 import { conflictWords, pullPanels } from "./previews.ts";
5142
5243 /**
5344 * GET /:owner/:name/pulls/:number in studio mode: a change is judged by
@@ -71,41 +62,12 @@ export async function studioPull(
7162 // `/pulls/:number`, whether a reader arrived there or at
7263 // `/changes/:number` (`changeHref`, nouns.ts).
7364 const thread = `${base}/pulls/${pull.number}`;
74 const wordCtx: WordCtx = {
75 db,
76 dir: repoDir(ctx.app.reposRoot, repo.ownerName, repo.name),
77 runtime: appsRuntime(ctx.app),
65 const { panels, word, note, status, conflicted } = await pullPanels(
66 ctx,
67 repo,
68 pull,
7869 record,
79 history: servingHistory(),
80 };
81 const { word, note: checkNote } = await pullWord(wordCtx, pull);
82 // Whether this change still merges into its base is asked here, on its own
83 // page, and nowhere a list of changes renders — a git call per open pull
84 // would undo the home's own bound (`askCandidatesFor`). Only an open,
85 // unmerged pull can conflict; a merged or closed one already has its word.
86 const status =
87 pull.mergedAt === null && pull.state !== "closed"
88 ? await pullStatus(wordCtx.dir, pull)
89 : undefined;
90 const conflicted =
91 status !== undefined && !status.mergeable && status.conflicts.length > 0;
92 const note = conflicted
93 ? conflictWords(pull.baseBranch, status.conflicts)
94 : checkNote;
95 // Before a merge the deploy worth linking is the preview's own check;
96 // after, it is production's — the preview's run may already be torn
97 // down, and the word above is judged by production regardless.
98 let deploy: { id: string; commitOid: string } | undefined;
99 if (pull.mergedAt === null) {
100 const run = checkSummary(db, pull.id, pull.headOid).run;
101 if (run) deploy = { id: run.id, commitOid: run.commitOid };
102 } else {
103 const production = wordCtx.runtime
104 ?.status(record)
105 .find((e) => e.env === "production");
106 if (production?.runId)
107 deploy = { id: production.runId, commitOid: production.commitOid };
108 }
70 );
10971 const crewDecision = decisionsFor(ctx, [repo]).find(
11072 (d) => d.pull?.id === pull.id,
11173 );
@@ -144,40 +106,6 @@ export async function studioPull(
144106 ? note
145107 : undefined;
146108
147 const head = html`<div class="issue-head">
148 <h1>${pull.title} <span class="number">#${pull.number}</span></h1>
149 <div class="issue-meta">
150 ${stateBadge(pullState(pull))}
151 <span
152 >${pull.originAuthor
153 ? originTag(pull.originAuthor, originGlyph(repo))
154 : userLink(pull.authorName)}
155 opened this ${time(pull.createdAt)}</span
156 >
157 ${when(
158 pull.originUrl,
159 (url) =>
160 html`<a class="origin-link" href="${url}" rel="noreferrer noopener"
161 >${icon("external")}view on origin</a
162 >`,
163 )}
164 </div>
165 </div>`;
166
167 const checkLine = card(
168 html`<p class="studio-pull-check">
169 ${wordBadge(word)} <span class="muted small">${note}</span>
170 ${when(
171 deploy,
172 (d) =>
173 html`<span class="where-sep" aria-hidden="true">·</span
174 ><a href="${base}/runs/${d.id}"
175 >deploy ${d.commitOid.slice(0, 7)}</a
176 >`,
177 )}
178 </p>`,
179 );
180
181109 // A conflicted change never offers Ship as though it would work — pressing
182110 // it would only be refused. The button that helps posts to the very same
183111 // route (`/ship`): `shipSubmit` already turns a conflict there into the
@@ -242,7 +170,7 @@ export async function studioPull(
242170 compact: true,
243171 ownTitle: true,
244172 })}
245 ${head} ${checkLine} ${decisionSection} ${takeBackSection}
173 ${panels.head} ${decisionSection} ${takeBackSection}
246174 ${lookCard(ctx, repo, record, pull, pull.headOid)}
247175 <div class="split">
248176 <div>
@@ -255,7 +183,7 @@ export async function studioPull(
255183 closeLabel: "Close change",
256184 })}
257185 </div>
258 <aside>${previewCard(ctx, repo, pull)}</aside>
186 ${panels.preview}
259187 </div>
260188 <p class="muted small mt">
261189 <a href="${thread}?mode=dev">${icon("code")}Read the code</a> — every
@@ -267,6 +195,7 @@ export async function studioPull(
267195 thread: "pull",
268196 number: pull.number,
269197 lastCommentId: talk.lastCommentId,
198 change: { head: pull.headOid, merged: pull.mergedOid },
270199 })}`;
271200
272201 return page({
src/web/studio/previews.ts +146 −2
@@ -15,9 +15,10 @@ import {
1515 type EnvStatus,
1616 } from "../../apps/runtime.ts";
1717 import { getAppByRepo, type AppRecord } from "../../core/apps.ts";
18 import { listPulls, type Pull } from "../../core/pulls.ts";
18 import { getPull, listPulls, 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 { checkSummary, listRuns } from "../../core/runs.ts";
21 import { repoDir } from "../../git/repos.ts";
2122 import type { Ctx } from "../../http/context.ts";
2223 import { readRunLogTail } from "../../runs/log.ts";
2324 import { loadRepo, repoBase } from "../chrome.ts";
@@ -26,6 +27,7 @@ import { fragment } from "../layout.ts";
2627 import {
2728 badge,
2829 btn,
30 card,
2931 dormantNote,
3032 envActions,
3133 envFacts,
@@ -33,11 +35,19 @@ import {
3335 envPhrase,
3436 icon,
3537 listCard,
38 originTag,
39 stateBadge,
3640 previewDataNote,
3741 row,
3842 terminalLine,
43 time,
44 userLink,
3945 } from "../ui.ts";
4046 import { lookNow } from "../pages/looks.ts";
47 import { previewCard } from "../pages/apps.ts";
48 import { pullState } from "../pages/pulls.ts";
49 import { originGlyph } from "../pages/thread.ts";
50 import { pullWord, servingHistory, wordBadge, type Word, type WordCtx } from "./words.ts";
4151 import { LOG_TAIL_CAP, logBox, runVoice } from "./log.ts";
4252
4353 /**
@@ -344,3 +354,137 @@ export function appStateFragment(ctx: Ctx): Response {
344354 return fragment(html`<div id="app-head">${head}</div>
345355 <div id="app-previews">${previews}</div>`, { request: ctx.request });
346356 }
357
358 /** What a conflicted change's own page says: the base it no longer merges
359 * into, the first few files (bounded, so a huge conflict never floods the
360 * page), and what fixes it. */
361 export function conflictWords(
362 baseBranch: string,
363 files: readonly string[],
364 ): string {
365 const shown = files.slice(0, 3).join(", ");
366 const more = files.length > 3 ? `, and ${files.length - 3} more` : "";
367 return `it conflicts with ${baseBranch} in ${shown}${more} — bring the branch up to date and it can land`;
368 }
369
370 /**
371 * The change page's own facts: the head (title, state, who opened it), the
372 * check line (word, note, deploy link) and the preview card. One function,
373 * called for the page's first paint and for the fragment a merge or deploy
374 * event refreshes in place (`pullStateFragment`). Both regions keep their
375 * ids and their markup across a swap, so a change going ready → shipping →
376 * shipped moves words in place and never shifts the layout. The word and
377 * the merge status come back too: the decision card is judged by them.
378 * No diff is computed; `pullWord` and one mergeability check are all the
379 * git it does, and only for a pull still open.
380 */
381 export async function pullPanels(
382 ctx: Ctx,
383 repo: Repo,
384 pull: Pull,
385 record: AppRecord,
386 ): Promise<{
387 panels: { head: Html; preview: Html };
388 word: Word;
389 note: string;
390 status: Awaited<ReturnType<typeof pullStatus>> | undefined;
391 conflicted: boolean;
392 }> {
393 const db = ctx.app.db;
394 const base = repoBase(repo);
395 const wordCtx: WordCtx = {
396 db,
397 dir: repoDir(ctx.app.reposRoot, repo.ownerName, repo.name),
398 runtime: appsRuntime(ctx.app),
399 record,
400 history: servingHistory(),
401 };
402 const { word, note: checkNote } = await pullWord(wordCtx, pull);
403 // Whether this change still merges into its base is asked here, on its own
404 // page, and nowhere a list of changes renders — a git call per open pull
405 // would undo the home's own bound (`askCandidatesFor`). Only an open,
406 // unmerged pull can conflict; a merged or closed one already has its word.
407 const status =
408 pull.mergedAt === null && pull.state !== "closed"
409 ? await pullStatus(wordCtx.dir, pull)
410 : undefined;
411 const conflicted =
412 status !== undefined && !status.mergeable && status.conflicts.length > 0;
413 const note = conflicted
414 ? conflictWords(pull.baseBranch, status.conflicts)
415 : checkNote;
416 // Before a merge the deploy worth linking is the preview's own check;
417 // after, it is production's — the preview's run may already be torn
418 // down, and the word above is judged by production regardless.
419 let deploy: { id: string; commitOid: string } | undefined;
420 if (pull.mergedAt === null) {
421 const run = checkSummary(db, pull.id, pull.headOid).run;
422 if (run) deploy = { id: run.id, commitOid: run.commitOid };
423 } else {
424 const production = wordCtx.runtime
425 ?.status(record)
426 .find((e) => e.env === "production");
427 if (production?.runId)
428 deploy = { id: production.runId, commitOid: production.commitOid };
429 }
430
431 const head = html`<div id="pull-head">
432 <div class="issue-head">
433 <h1>${pull.title} <span class="number">#${pull.number}</span></h1>
434 <div class="issue-meta">
435 ${stateBadge(pullState(pull))}
436 <span
437 >${pull.originAuthor
438 ? originTag(pull.originAuthor, originGlyph(repo))
439 : userLink(pull.authorName)}
440 opened this ${time(pull.createdAt)}</span
441 >
442 ${when(
443 pull.originUrl,
444 (url) =>
445 html`<a class="origin-link" href="${url}" rel="noreferrer noopener"
446 >${icon("external")}view on origin</a
447 >`,
448 )}
449 </div>
450 </div>
451 ${card(
452 html`<p class="studio-pull-check">
453 ${wordBadge(word)} <span class="muted small">${note}</span>
454 ${when(
455 deploy,
456 (d) =>
457 html`<span class="where-sep" aria-hidden="true">·</span
458 ><a href="${base}/runs/${d.id}"
459 >deploy ${d.commitOid.slice(0, 7)}</a
460 >`,
461 )}
462 </p>`,
463 )}
464 </div>`;
465 const preview = html`<aside id="pull-preview">${previewCard(ctx, repo, pull)}</aside>`;
466 return { panels: { head, preview }, word, note, status, conflicted };
467 }
468
469 /**
470 * GET /:owner/:name/pulls/:number/state — the change's head, check line and
471 * preview card, bare. The change page's live client (`live.ts`) fetches this
472 * on the pull's own merge, on a deploy run for its preview, and on
473 * production serving, and swaps the two regions in place. Authorized as the
474 * page is: a viewer who cannot see the repository, the pull, or an app
475 * gets the same 404.
476 */
477 export async function pullStateFragment(ctx: Ctx): Promise<Response> {
478 const repo = loadRepo(ctx);
479 const number = /^[1-9][0-9]{0,9}$/.test(ctx.params.number ?? "")
480 ? Number(ctx.params.number)
481 : undefined;
482 const pull =
483 repo && number !== undefined ? getPull(ctx.app.db, repo.id, number) : undefined;
484 const record = repo ? getAppByRepo(ctx.app.db, repo.id) : undefined;
485 if (!repo || !pull || !record) return fragment(html``, { status: 404 });
486 const { panels } = await pullPanels(ctx, repo, pull, record);
487 return fragment(html`<div>${panels.head}${panels.preview}</div>`, {
488 request: ctx.request,
489 });
490 }
test/studio.test.ts +29
@@ -2,6 +2,7 @@
22 * The studio: apps as the unit, three verbs, and a switch to dev. The same
33 * URLs answer in both modes; the cookie decides which face they show.
44 */
5 import { liveClientJs } from "../src/web/live.ts";
56 import { afterAll, beforeAll, describe, expect, spyOn, test } from "bun:test";
67 import { mkdirSync, writeFileSync } from "node:fs";
78 import { mkdtemp, rm } from "node:fs/promises";
@@ -5547,6 +5548,34 @@ describe("a person's own change ships from its own studio page", () => {
55475548 expect(after).toContain('data-word="shipped"');
55485549 });
55495550
5551 test("the change page follows its own ship: a fragment route draws the current word, and the client names it (#82)", async () => {
5552 // The bench change above is shipped by now; its fragment says so,
5553 // drawn by the same `pullPanels` as the page.
5554 const res = await get("/alice/garden/pulls/1/state", ownerCookie);
5555 expect(res.status).toBe(200);
5556 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
5557 expect(res.headers.get("referrer-policy")).toBe("same-origin");
5558 expect(res.headers.get("content-security-policy")).toContain("default-src 'none'");
5559 const text = await res.text();
5560 expect(text).toContain('id="pull-head"');
5561 expect(text).toContain('id="pull-preview"');
5562 expect(text).toContain('data-word="shipped"');
5563 expect(text).not.toContain("<h2>Decide</h2>");
5564 // No such change: the same 404 the page gives.
5565 expect((await get("/alice/garden/pulls/999/state", ownerCookie)).status).toBe(404);
5566 expect((await get("/alice/garden/pulls/x/state", ownerCookie)).status).toBe(404);
5567 expect((await get("/alice/nope/pulls/1/state", ownerCookie)).status).toBe(404);
5568 // The page mounts the client for it, and the script names the path and
5569 // the three events it swaps on.
5570 const page = await (await get("/alice/garden/pulls/1", ownerCookie)).text();
5571 expect(page).toContain('data-change="1"');
5572 expect(page).toContain('id="pull-head"');
5573 expect(liveClientJs).toContain("'/pulls/' + number + '/state'");
5574 expect(liveClientJs).toContain("data.kind === 'pull.merged'");
5575 expect(liveClientJs).toContain("p.env === 'pull-' + number");
5576 expect(liveClientJs).toContain("data.kind === 'app.serving'");
5577 });
5578
55505579 test("a conflicted change alice opened herself offers the bring-up-to-date wording, never a Ship that would be refused", async () => {
55515580 const base1 = await commitToBranch(app, alice, repo, {
55525581 message: "Add a file two branches will fight over",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs