an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions
HTML agent-harnessagent-orchestrationagentsai-agentsautonomous-agentsclaude-codecodexcoding-agentsdesktop-appdeveloper-toolselectrongemini-cliharnessharness-engineeringlocal-firstmemorymulti-agentopencodeorchestrationtypescript
feat(updates): tell people what's actually in the update
Chaitanya Giria7b6e4f853b8
diff --git a/package.json b/package.jsonindex 42f7ff4a..07d93a9b 100644--- a/package.json+++ b/package.json@@ -19,7 +19,7 @@"typecheck:node": "tsc --noEmit -p tsconfig.node.json","typecheck:web": "tsc --noEmit -p tsconfig.web.json","typecheck": "npm run typecheck:node && npm run typecheck:web",- "test:focused": "node --test test/codex-remote.test.cjs test/control.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs test/terminal-selection.test.cjs test/roster.test.cjs test/proc-kill.test.cjs test/expand-tilde.test.cjs test/hive-cwd.test.cjs test/hive-task-mutation.test.cjs test/hive-hook-node.test.cjs test/hive-roster-injection.test.cjs test/hive-runtime-path.test.cjs test/cli-install-ladder.test.cjs test/node-install.test.cjs test/office-gl-recovery.test.cjs test/update-state.test.cjs test/transcript-project-dir.test.cjs test/commit-graph.test.cjs",+ "test:focused": "node --test test/codex-remote.test.cjs test/control.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs test/terminal-selection.test.cjs test/roster.test.cjs test/proc-kill.test.cjs test/expand-tilde.test.cjs test/hive-cwd.test.cjs test/hive-task-mutation.test.cjs test/hive-hook-node.test.cjs test/hive-roster-injection.test.cjs test/hive-runtime-path.test.cjs test/cli-install-ladder.test.cjs test/node-install.test.cjs test/office-gl-recovery.test.cjs test/update-state.test.cjs test/release-notes.test.cjs test/transcript-project-dir.test.cjs test/commit-graph.test.cjs","check:links": "node tools/check-release-links.cjs","dist": "npm run build && electron-builder","dist:mac": "npm run build && electron-builder --mac",diff --git a/src/main/updater.ts b/src/main/updater.tsindex e79daf91..2427267a 100644--- a/src/main/updater.ts+++ b/src/main/updater.ts@@ -135,14 +135,18 @@ function fallbackCheck(reason: string | undefined, force = false): void {res.on('data', (d) => { body += d; if (body.length > 262_144) req.destroy(); });res.on('end', () => {try {- const rel = JSON.parse(body) as { tag_name?: string; html_url?: string };+ const rel = JSON.parse(body) as { tag_name?: string; html_url?: string; body?: string };const tag = rel.tag_name ?? '';if (tag && isNewer(tag, app.getVersion())) {emit({state: 'available-manual',version: tag.replace(/^v/, ''),url: rel.html_url ?? `https://github.com/${REPO}/releases/latest`,- reason+ reason,+ // Already in the response we just parsed — carrying it costs+ // nothing and lets the notify-only toast show "What's new" too.+ // NOT a new request: see TELEMETRY.md, this app never adds one.+ notes: typeof rel.body === 'string' ? rel.body : undefined});}} catch { /* malformed body — try again next interval */ }diff --git a/src/renderer/src/components/UpdateToast.tsx b/src/renderer/src/components/UpdateToast.tsxindex f00863b3..b19d3c6e 100644--- a/src/renderer/src/components/UpdateToast.tsx+++ b/src/renderer/src/components/UpdateToast.tsx@@ -10,9 +10,33 @@* Mirrors CompletionToast: self-contained + self-subscribing, mounted once in* App.tsx, renders nothing when idle. Installation is ALWAYS user-initiated —* "later" just hides the toast until the next app start (or the 6h re-check).+ *+ * ─── v0.4.4: "What's new" ───────────────────────────────────────────────────+ * Both states already carried `notes` (the GitHub release body) and the toast+ * dropped it on the floor, so the only notification this app ever raises said+ * nothing but a version number. It now renders a digest of that body —+ * summarizeReleaseNotes() in src/shared/releaseNotes.ts does the parsing, and+ * lives there rather than here so it can be unit-tested without a renderer.+ *+ * Three rules this block obeys:+ * 1. No notes, no block. A release body that is missing, empty, or pure+ * structure yields an empty digest and the toast renders EXACTLY as it did+ * before — no orphan heading, no shifted buttons. Most bodies are like+ * that, so this is the common path, not the edge case.+ * 2. Bounded height. The digest is capped in releaseNotes.ts AND clamped with+ * a scroll here, because a toast that grows with the release notes is a+ * dialog that covers the app.+ * 3. The star ask is shown AT MOST ONCE EVER, not once per release. A repeated+ * ask is the kind of nagging that gets a notification muted, which would+ * cost the updater its only channel. See STAR_ASK_KEY below.+ *+ * No new IPC and no new network call: "read more" reuses `updateOpenRelease`+ * (the same bridge the manual state's button has always used) and the star link+ * goes through the existing `openExternal` opener.*/-import { useEffect, useState } from 'react';+import { useEffect, useMemo, useState } from 'react';import { Icon } from '@/components/Icon';+import { summarizeReleaseNotes } from '@shared/releaseNotes';import type { UpdateStatus } from '@shared/updateState';/** The toast is the LOUD half — it only interrupts for the two states a user has@@ -24,9 +48,45 @@ function toastable(s: UpdateStatus): ToastStatus | null {return s.state === 'downloaded' || s.state === 'available-manual' ? s : null;}+const GITHUB_REPO_URL = 'https://github.com/chaitanyagiri/munder-difflin';+/** Only ever the `href` — the click is handled by `updateOpenRelease`, which+ * resolves `undefined` to this same page in main. */+const GITHUB_RELEASES_URL = `${GITHUB_REPO_URL}/releases/latest`;++/** One-time flag for the star ask. `cth.`-prefixed localStorage is this app's+ * convention for renderer-only UI memory (see App.tsx's skipHivePickerOnce and+ * design/theme.ts) — and SettingsModal's "reset & start over" clears every+ * `cth.` key, which is right: a wiped install is a new user who has not been+ * asked yet. It is deliberately NOT a HarnessConfig key; that file is the+ * agent runtime's contract, hand-mirrored across main/preload/renderer, and a+ * cosmetic nudge does not belong in it. */+const STAR_ASK_KEY = 'cth.updateStarAsked';++function starAskPending(): boolean {+ try {+ return window.localStorage.getItem(STAR_ASK_KEY) !== '1';+ } catch {+ // Storage unavailable means we cannot honour "at most once, ever" — so ask+ // zero times rather than risk asking on every single update.+ return false;+ }+}++function markStarAsked(): void {+ try { window.localStorage.setItem(STAR_ASK_KEY, '1'); } catch { /* nothing to do */ }+}+export function UpdateToast() {const [status, setStatus] = useState<ToastStatus | null>(null);const [busy, setBusy] = useState(false);+ // Read once per window, so persisting the flag below cannot make the link+ // vanish from under the cursor of the person currently looking at it.+ const [starAsk] = useState(starAskPending);+ /** The version the ask was spent on. A version rather than a boolean because+ * flipping a boolean the moment we persist would yank the link out from+ * under the cursor of the person looking at it — this keeps it on the toast+ * that is showing it, and withholds it from any later one. */+ const [starSpentOn, setStarSpentOn] = useState<string | null>(null);useEffect(() => window.cth.onUpdateStatus?.((next) => {const t = toastable(next);@@ -35,6 +95,18 @@ export function UpdateToast() {if (t) setStatus(t);}), []);+ const notes = useMemo(() => summarizeReleaseNotes(status?.notes), [status?.notes]);+ const version = status?.version ?? null;+ // Shown = spent. Not "clicked" — an ask the user read and ignored is an+ // answer too, and asking again next release is exactly what rule 3 forbids.+ const showStar = starAsk && notes.length > 0 && (starSpentOn === null || starSpentOn === version);+ useEffect(() => {+ if (showStar && version && starSpentOn === null) {+ setStarSpentOn(version);+ markStarAsked();+ }+ }, [showStar, version, starSpentOn]);+if (!status) return null;const restart = async () => {@@ -45,6 +117,12 @@ export function UpdateToast() {} catch { setBusy(false); }};+ /** Same call the manual state's button makes: main resolves `undefined` to+ * the releases page and refuses any URL outside this repo. */+ const openRelease = () => {+ void window.cth.updateOpenRelease(status.state === 'available-manual' ? status.url : undefined);+ };+const buttonStyle: React.CSSProperties = {padding: '3px 10px 1px',background: 'var(--cth-mint-light, #d0f0e0)',@@ -53,6 +131,11 @@ export function UpdateToast() {color: 'var(--cth-ink-900)', cursor: 'pointer', border: 'none'};+ const linkStyle: React.CSSProperties = {+ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-900)',+ textDecoration: 'underline', cursor: 'pointer'+ };+return (<div style={{position: 'fixed', right: 16, bottom: 16, zIndex: 400,@@ -76,6 +159,49 @@ export function UpdateToast() {? 'Restart Munder Difflin whenever you like to apply it — nothing restarts on its own.': 'This install can’t update itself — grab the new build from the releases page.'}</span>++ {notes.length > 0 && (+ <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>+ <div style={{+ fontFamily: 'var(--cth-font-display)', fontSize: 8, lineHeight: '12px',+ color: 'var(--cth-ink-500)', textTransform: 'uppercase'+ }}>+ What’s new+ </div>+ {/* The digest is already capped at ~280 chars; the clamp is the second+ belt, for the day a release body defeats the parser. */}+ <ul style={{+ listStyle: 'none', margin: 0, padding: '0 0 0 2px',+ maxHeight: 96, overflowY: 'auto',+ display: 'flex', flexDirection: 'column', gap: 4+ }}>+ {notes.map((line, i) => (+ <li key={i} style={{+ display: 'flex', gap: 6,+ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-700)'+ }}>+ <span aria-hidden style={{ color: 'var(--cth-ink-300)' }}>•</span>+ <span>{line}</span>+ </li>+ ))}+ </ul>+ <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>+ <a+ href={status.state === 'available-manual' ? status.url : GITHUB_RELEASES_URL}+ onClick={(e) => { e.preventDefault(); openRelease(); }}+ style={linkStyle}+ >Read more</a>+ {showStar && (+ <a+ href={GITHUB_REPO_URL}+ onClick={(e) => { e.preventDefault(); void window.cth.openExternal(GITHUB_REPO_URL); }}+ style={linkStyle}+ >⭐ Star us on GitHub</a>+ )}+ </div>+ </div>+ )}+<div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}><buttononClick={() => setStatus(null)}@@ -89,7 +215,7 @@ export function UpdateToast() {</button>) : (<button- onClick={() => { void window.cth.updateOpenRelease(status.url); }}+ onClick={openRelease}style={buttonStyle}>open releasesdiff --git a/src/renderer/src/components/UpdatesSection.tsx b/src/renderer/src/components/UpdatesSection.tsxindex ee1e5b92..c536a72b 100644--- a/src/renderer/src/components/UpdatesSection.tsx+++ b/src/renderer/src/components/UpdatesSection.tsx@@ -11,7 +11,8 @@* differs (`describeUpdateSettings` vs `describeUpdate`), so the two can never* disagree about what is installed.*/-import { useCallback, useEffect, useState } from 'react';+import { useCallback, useEffect, useMemo, useState } from 'react';+import { summarizeReleaseNotes } from '@shared/releaseNotes';import { describeUpdateSettings, reduceStatus, type UpdateStatus } from '@shared/updateState';import { PixelButton } from './PixelButton';@@ -33,6 +34,15 @@ export function UpdatesSection() {const view = describeUpdateSettings(status, __APP_VERSION__);+ // Same digest the update toast renders (src/shared/releaseNotes.ts), for the+ // same reason: the release body is already in hand, and "what would I get?"+ // is the second question anyone asks after "is there a new version?". Only+ // the states that carry notes have any — the rest render nothing extra.+ const notes = useMemo(+ () => summarizeReleaseNotes(status && 'notes' in status ? status.notes : undefined),+ [status]+ );+const onClick = useCallback(async () => {if (view.action === 'none' || busy) return;setBusy(true);@@ -80,6 +90,22 @@ export function UpdatesSection() {</PixelButton>)}</div>+ {notes.length > 0 && (+ <ul style={{+ listStyle: 'none', margin: '8px 0 0', padding: 0,+ display: 'flex', flexDirection: 'column', gap: 4+ }}>+ {notes.map((line, i) => (+ <li key={i} style={{+ display: 'flex', gap: 6,+ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-500)'+ }}>+ <span aria-hidden style={{ color: 'var(--cth-ink-300)' }}>•</span>+ <span>{line}</span>+ </li>+ ))}+ </ul>+ )}</div>);}diff --git a/src/shared/releaseNotes.ts b/src/shared/releaseNotes.tsnew file mode 100644index 00000000..1937f1f6--- /dev/null+++ b/src/shared/releaseNotes.ts@@ -0,0 +1,235 @@+/**+ * Release-note digest — turns a GitHub release body into 3-5 short lines.+ *+ * The updater has always carried `notes` (electron-updater's+ * `info.releaseNotes`, i.e. the release body) on the `available` /+ * `downloaded` / `available-manual` states, and the UI has always thrown it+ * away. The update toast is the only notification this app ever raises, so the+ * one moment we have someone's attention we were spending on a version number.+ *+ * Why this is not just `body.slice(0, 280)`:+ *+ * 1. The body is RELEASE.md (see .github/workflows/release.yml → `body_path`),+ * which is ~200 lines: a tagline, a link, download tables for three+ * platforms, build-from-source instructions, a "Previously" list. The+ * actual news sits under a `## What's new in <version>` heading a third of+ * the way down. Taking "the first lines" of that body gives you the+ * product tagline — text the user has already read. So when the body has a+ * "what's new" heading we start there, and stop at the next heading or+ * horizontal rule so we don't bleed into "Still new in 0.4.2".+ *+ * 2. It is markdown, and the toast renders plain text. Links have to collapse+ * to their label (a raw `https://github.com/...` eats the whole budget),+ * images and badges have to disappear entirely, and emphasis markers have+ * to go — but ONLY when they are emphasis. `DO_NOT_TRACK` and `first_run`+ * are real strings in this project's release notes and must survive.+ *+ * 3. Release bullets wrap across source lines. Splitting on `\n` and clipping+ * would cut a sentence at the author's line break, which is arbitrary, so+ * continuation lines are folded back into their bullet before clipping.+ *+ * Deliberately pure and electron-free (same contract as updateState.ts): no DOM,+ * no `window`, no imports. The toast and the Settings block both call it, and+ * test/release-notes.test.cjs pins the behaviour without booting anything.+ */++/** At most this many lines in the digest — a toast, not a changelog. */+export const RELEASE_NOTES_MAX_BULLETS = 5;+/** Total character budget across all lines. Sized so the 340px toast stays+ * roughly six lines tall even before the block's own scroll clamp. */+export const RELEASE_NOTES_MAX_CHARS = 280;+/** No single line may hog the whole budget. Tuned against this project's own+ * release notes, whose bullets lead with a bolded sentence and then explain+ * themselves for another two lines: 110 keeps the lead plus a clause, and+ * leaves room for the two or three bullets after it. */+export const RELEASE_NOTES_MAX_BULLET_CHARS = 110;+/** Below this, a clipped tail is unreadable ("Icons are nat…") — stop instead. */+const MIN_PARTIAL_CHARS = 40;++export interface ReleaseNotesOptions {+ maxBullets?: number;+ maxChars?: number;+ maxBulletChars?: number;+}++const FENCE_RE = /^\s{0,3}(?:```|~~~)/;+const HEADING_RE = /^\s{0,3}#{1,6}\s+/;+/** `---`, `***`, `___` (and spaced variants). Checked BEFORE the bullet test,+ * because `- - -` is a rule and `- x` is a bullet. */+const RULE_RE = /^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/;+const BULLET_RE = /^\s*(?:[-*+]|\d{1,2}[.)])\s+/;+const TABLE_ROW_RE = /^\s*\|/;+/** Setext underline (`====` under a title) — structure, never content. */+const SETEXT_RE = /^\s{0,3}=+\s*$/;+const WHATS_NEW_RE = /^\s{0,3}#{1,6}\s+.*what[’']?s\s+new/i;+/** GitHub appends this to auto-generated bodies; it is a URL, not news. */+const FULL_CHANGELOG_RE = /^\s*\**\s*full\s+changelog\s*\**\s*:/i;+const BARE_URL_RE = /^\s*<?https?:\/\/\S+>?\s*$/i;++/**+ * Markdown → plain text for one already-joined line.+ *+ * Exported for the tests: this is where every "the toast showed a raw URL"+ * class of bug lives, and it is far easier to pin here than through the digest.+ */+export function stripMarkdown(md: string): string {+ return String(md ?? '')+ .replace(/!\[[^\]]*\]\([^)]*\)/g, '') // images/badges: gone entirely+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') // inline links → their label+ .replace(/\[([^\]]*)\]\[[^\]]*\]/g, '$1') // reference links → their label+ .replace(/<https?:\/\/[^>]*>/g, '') // autolinks: the URL is noise here+ .replace(/<[^>\s][^>]*>/g, '') // stray inline HTML+ .replace(/`([^`]*)`/g, '$1') // inline code, backticks only+ .replace(/\*\*\*([^*]+)\*\*\*/g, '$1')+ .replace(/\*\*([^*]+)\*\*/g, '$1')+ // Struck-through text is retracted, not emphasised — "on ~~Windows~~ macOS"+ // must not come out as "on Windows macOS".+ .replace(/~~[^~]+~~/g, '')+ // Single-marker emphasis needs the word-boundary guards, otherwise+ // `DO_NOT_TRACK` and `agent_spawned` come out mangled.+ .replace(/(?<![\w*])\*([^*\n]+)\*(?!\w)/g, '$1')+ .replace(/(?<![\w_])__([^_\n]+)__(?!\w)/g, '$1')+ .replace(/(?<![\w_])_([^_\n]+)_(?!\w)/g, '$1')+ .replace(/^\s{0,3}#{1,6}\s*/, '') // a heading marker that slipped through+ .replace(/ /g, ' ')+ .replace(/\s+/g, ' ')+ .replace(/^[\s—–:.,;·-]+/, '') // leading orphan punctuation from a stripped link+ .trim();+}++/** Anything with at least one word character and enough of it to be a sentence. */+function isMeaningful(text: string): boolean {+ return text.length >= 3 && /[A-Za-z0-9]/.test(text);+}++/**+ * Drop everything that is markup rather than prose: fenced code, HTML comments,+ * download/checksum tables, blockquote wrappers and GitHub's `[!NOTE]` markers.+ * Blockquotes are unwrapped rather than dropped — this project's release notes+ * put real caveats ("Appearance only. No functional change") inside one.+ */+function usableLines(body: string): string[] {+ const out: string[] = [];+ let inFence = false;+ for (const raw of body.replace(/\r\n?/g, '\n').split('\n')) {+ if (FENCE_RE.test(raw)) { inFence = !inFence; continue; }+ if (inFence) continue;+ const line = raw+ .replace(/<!--[\s\S]*?-->/g, '')+ .replace(/^\s{0,3}>\s?/, '')+ .replace(/^\s*\[![A-Za-z]+\]\s*/, '');+ if (TABLE_ROW_RE.test(line)) continue;+ if (SETEXT_RE.test(line)) continue;+ if (FULL_CHANGELOG_RE.test(line)) continue;+ if (BARE_URL_RE.test(line)) continue;+ out.push(line);+ }+ return out;+}++/**+ * The slice of the body that is actually "what's new".+ *+ * Starts after the first `what's new` heading when there is one, otherwise at+ * the top; either way headings and rules are skipped while we're still in the+ * preamble and END the section once content has been collected.+ */+function firstSection(lines: string[]): string[] {+ const marker = lines.findIndex((l) => WHATS_NEW_RE.test(l));+ const start = marker >= 0 ? marker + 1 : 0;+ const out: string[] = [];+ let seenContent = false;+ for (let i = start; i < lines.length; i++) {+ const line = lines[i];+ if (HEADING_RE.test(line) || RULE_RE.test(line)) {+ if (seenContent) break;+ continue;+ }+ if (!seenContent && isMeaningful(stripMarkdown(line))) seenContent = true;+ out.push(line);+ }+ return out;+}++/**+ * Fold the section into digest items.+ *+ * Bullets win when the section has any: a changelog's bullets ARE the summary,+ * and the paragraph above them is usually scene-setting that would eat two of+ * the five slots. A release with no bullets at all falls back to its+ * paragraphs, so a one-line "Fixes the crash on launch." body still says+ * something.+ */+function collectItems(section: string[]): string[] {+ const bullets: string[] = [];+ const prose: string[] = [];+ let current: string[] = [];+ let currentIsBullet = false;++ const flush = (): void => {+ if (current.length === 0) return;+ const text = stripMarkdown(current.join(' '));+ if (isMeaningful(text)) (currentIsBullet ? bullets : prose).push(text);+ current = [];+ };++ for (const line of section) {+ if (line.trim() === '') { flush(); continue; }+ const bullet = line.match(BULLET_RE);+ if (bullet && !RULE_RE.test(line)) {+ flush();+ current = [line.slice(bullet[0].length)];+ currentIsBullet = true;+ } else if (current.length > 0) {+ current.push(line.trim()); // a wrapped continuation of the item above+ } else {+ current = [line.trim()];+ currentIsBullet = false;+ }+ }+ flush();++ return bullets.length > 0 ? bullets : prose;+}++/** Clip to `max` chars on a word boundary, ellipsis included in the count. */+function clip(text: string, max: number): string {+ if (text.length <= max) return text;+ const cut = text.slice(0, max - 1);+ const space = cut.lastIndexOf(' ');+ const head = space > max * 0.5 ? cut.slice(0, space) : cut;+ return `${head.replace(/[\s,;:.—–-]+$/, '')}…`;+}++/**+ * Parse a GitHub release body into a short "What's new" digest.+ *+ * Returns `[]` — never a placeholder — for a missing, empty, or+ * structure-only body, so callers can render nothing at all rather than an+ * empty heading. Most releases in the wild have no usable body.+ */+export function summarizeReleaseNotes(+ body: string | null | undefined,+ opts: ReleaseNotesOptions = {}+): string[] {+ const maxBullets = opts.maxBullets ?? RELEASE_NOTES_MAX_BULLETS;+ const maxChars = opts.maxChars ?? RELEASE_NOTES_MAX_CHARS;+ const maxBulletChars = opts.maxBulletChars ?? RELEASE_NOTES_MAX_BULLET_CHARS;+ if (typeof body !== 'string' || body.trim() === '') return [];++ const items = collectItems(firstSection(usableLines(body)));++ const out: string[] = [];+ let used = 0;+ for (const item of items) {+ if (out.length >= maxBullets) break;+ const room = Math.min(maxBulletChars, maxChars - used);+ // The first line always gets rendered (clipped if it must be); after that a+ // stub too short to read is worse than one bullet fewer.+ if (out.length > 0 && room < MIN_PARTIAL_CHARS) break;+ const text = clip(item, Math.max(room, 1));+ out.push(text);+ used += text.length;+ }+ return out;+}diff --git a/src/shared/updateState.ts b/src/shared/updateState.tsindex 7e86b4d8..2e33d1dd 100644--- a/src/shared/updateState.ts+++ b/src/shared/updateState.ts@@ -17,8 +17,11 @@ export type UpdateStatus =| { state: 'downloading'; version: string; percent: number }| { state: 'downloaded'; version: string; notes?: string }/** This install can't self-update (win-portable, or the native path failed):- * notify-only, link to the release page. `reason` is the underlying error. */- | { state: 'available-manual'; version: string; url: string; reason?: string }+ * notify-only, link to the release page. `reason` is the underlying error.+ * `notes` is the release body — the notify-only poll already reads the same+ * `releases/latest` JSON that carries it, so the toast can show "what's new"+ * here too without a second request. */+ | { state: 'available-manual'; version: string; url: string; reason?: string; notes?: string }| { state: 'error'; message: string };export type UpdateAction = 'none' | 'check' | 'download' | 'restart' | 'open-release';diff --git a/test/release-notes.test.cjs b/test/release-notes.test.cjsnew file mode 100644index 00000000..f5872099--- /dev/null+++ b/test/release-notes.test.cjs@@ -0,0 +1,240 @@+'use strict';++/**+ * Release-note digest (src/shared/releaseNotes.ts).+ *+ * The update toast is the only notification this app raises, and it now renders+ * whatever this function returns — straight from the GitHub release body, with+ * no chance for a human to look at it first. So the failure modes are all+ * "shipped to every user at once":+ *+ * - a 200-line RELEASE.md dumped into a 340px toast;+ * - a digest of the release template's boilerplate (tagline, download links)+ * instead of the release's actual news;+ * - raw markdown or a bare URL rendered as text;+ * - an empty "What's new" heading on the many releases whose body is a+ * structural stub — the toast has to look untouched in that case.+ *+ * Each of those is pinned below.+ */++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const loadTs = require('./load-ts.cjs');++const {+ summarizeReleaseNotes,+ stripMarkdown,+ RELEASE_NOTES_MAX_BULLETS,+ RELEASE_NOTES_MAX_CHARS+} = loadTs('src/shared/releaseNotes.ts');++/** Total rendered length, the number the toast's height actually depends on. */+const total = (lines) => lines.join('').length;++test('no body, no digest — the toast must render exactly as it did before', () => {+ assert.deepEqual(summarizeReleaseNotes(undefined), []);+ assert.deepEqual(summarizeReleaseNotes(null), []);+ assert.deepEqual(summarizeReleaseNotes(''), []);+ assert.deepEqual(summarizeReleaseNotes(' \n\n\t\n '), []);+ // Not a string at all — `releaseNotes` is `string | ReleaseNoteInfo[]` in+ // electron-updater's types and main only forwards the string case, but a+ // renderer must never explode on a shape it didn't expect.+ assert.deepEqual(summarizeReleaseNotes(42), []);+ assert.deepEqual(summarizeReleaseNotes({ note: 'hi' }), []);+});++test('a body of nothing but structure yields nothing', () => {+ assert.deepEqual(summarizeReleaseNotes('# v1.2.3\n\n## Changes\n\n---\n\n***\n'), []);+ assert.deepEqual(summarizeReleaseNotes('---\n\n<!-- release notes go here -->\n\n---'), []);+ // A download table and a compare link are markup, not news.+ assert.deepEqual(summarizeReleaseNotes([+ '## Assets',+ '| Build | File |',+ '|---|---|',+ '| macOS | app.dmg |',+ '',+ '**Full Changelog**: https://github.com/o/r/compare/v1.0.0...v1.1.0'+ ].join('\n')), []);+});++test('markdown is stripped down to what a plain-text toast can render', () => {+ const digest = summarizeReleaseNotes([+ '## Fixed',+ '- Fixed the [crash on launch](https://github.com/o/r/issues/12)',+ '- `DO_NOT_TRACK` and `agent_spawned` are **respected** in _every_ build',+ '-  Signed builds on ~~Windows~~ macOS'+ ].join('\n'));++ assert.deepEqual(digest, [+ 'Fixed the crash on launch',+ 'DO_NOT_TRACK and agent_spawned are respected in every build',+ 'Signed builds on macOS'+ ]);+ // The regression this guards: a URL that eats the whole character budget.+ for (const line of digest) assert.doesNotMatch(line, /https?:\/\//);+ // `_` is excluded on purpose — it is a real character in DO_NOT_TRACK, and+ // stripping it as emphasis is the bug the next test pins.+ for (const line of digest) assert.doesNotMatch(line, /[*`~[\]]/);+});++test('emphasis markers go, snake_case identifiers stay', () => {+ assert.equal(stripMarkdown('**Bold lead.** then _italic_ text'), 'Bold lead. then italic text');+ assert.equal(stripMarkdown('set `DO_NOT_TRACK=1` to opt out'), 'set DO_NOT_TRACK=1 to opt out');+ assert.equal(stripMarkdown('events: first_run, app_launched'), 'events: first_run, app_launched');+ assert.equal(stripMarkdown('see [the contract](https://x/TELEMETRY.md)'), 'see the contract');+ assert.equal(stripMarkdown(''), '');+});++test("the 'What's new' section wins over the release template's preamble", () => {+ // This is the shape of RELEASE.md: a tagline and a site link come first, and+ // taking "the first lines" of the body would digest the boilerplate the user+ // has already read instead of the release's news.+ const body = [+ '# Munder Difflin v0.4.4',+ '',+ '**A local hive of agents that run themselves** — the product tagline.',+ '',+ '### → [**munderdiffl.in**](https://munderdiffl.in/) — see it in action',+ '',+ '---',+ '',+ "## What's new in 0.4.4 — *the toast says something*",+ '',+ '- The update toast shows what changed.',+ '- The star ask is shown once, ever.',+ '',+ '---',+ '',+ '## Still new in 0.4.3 — *Michael is the logo*',+ '',+ '- The mark is a face now.'+ ].join('\n');++ assert.deepEqual(summarizeReleaseNotes(body), [+ 'The update toast shows what changed.',+ 'The star ask is shown once, ever.'+ ]);+});++test('a body with no "what\'s new" heading digests from the top', () => {+ const body = [+ '## Highlights',+ '',+ '- Agents restart cleanly after a GPU context loss',+ '- Slack triggers respect the queue'+ ].join('\n');+ assert.deepEqual(summarizeReleaseNotes(body), [+ 'Agents restart cleanly after a GPU context loss',+ 'Slack triggers respect the queue'+ ]);+});++test('bullets are the summary when a release has them; prose is the fallback', () => {+ const withBullets = [+ 'This release is mostly about the updater and how it talks to you.',+ '',+ '- The toast shows release notes',+ '- Settings shows them too'+ ].join('\n');+ assert.deepEqual(summarizeReleaseNotes(withBullets), [+ 'The toast shows release notes',+ 'Settings shows them too'+ ]);++ // A one-liner body still says something rather than nothing.+ assert.deepEqual(summarizeReleaseNotes('Fixes the crash on launch.'), ['Fixes the crash on launch.']);+});++test('a bullet wrapped across source lines is folded back into one', () => {+ // Clipping at the author's line break would cut the sentence at an arbitrary+ // column that has nothing to do with the toast's width.+ const body = [+ "## What's new",+ '',+ '- **One mark, everywhere.** The dock icon on macOS, Windows and',+ ' Linux, the site favicon, and the README all render the same',+ ' portrait.',+ '- Second bullet.'+ ].join('\n');+ const digest = summarizeReleaseNotes(body);+ assert.equal(digest.length, 2);+ assert.match(digest[0], /^One mark, everywhere\. The dock icon on macOS, Windows and Linux/);+ assert.equal(digest[1], 'Second bullet.');+});++test('bullets are capped in count', () => {+ const body = `## Changes\n${Array.from({ length: 20 }, (_, i) => `- Change number ${i}`).join('\n')}`;+ const digest = summarizeReleaseNotes(body);+ assert.ok(digest.length <= RELEASE_NOTES_MAX_BULLETS, `${digest.length} bullets`);+ assert.equal(digest[0], 'Change number 0');+});++test('a long body is truncated to the character budget, on a word boundary', () => {+ const body = [+ "## What's new",+ '',+ ...Array.from({ length: 12 }, (_, i) =>+ `- Bullet ${i}: ${'a fairly wordy sentence that keeps going and going '.repeat(4)}`)+ ].join('\n');++ const digest = summarizeReleaseNotes(body);+ assert.ok(digest.length > 0, 'a long body must still produce something');+ assert.ok(digest.length <= RELEASE_NOTES_MAX_BULLETS);+ assert.ok(total(digest) <= RELEASE_NOTES_MAX_CHARS, `${total(digest)} chars over budget`);+ assert.match(digest[0], /…$/);+ // Word boundary, not mid-word: the char before the ellipsis is never a+ // half-typed word followed by a space-less cut of the next one.+ assert.doesNotMatch(digest[0], /\s…$/);+});++test('one enormous bullet is clipped rather than dropped', () => {+ const digest = summarizeReleaseNotes(`- ${'word '.repeat(400)}`);+ assert.equal(digest.length, 1);+ assert.ok(total(digest) <= RELEASE_NOTES_MAX_CHARS);+ assert.match(digest[0], /…$/);+});++test('code fences, comments and quoted callouts are handled', () => {+ const body = [+ "## What's new",+ '',+ '> [!NOTE]',+ '> **Appearance only.** No functional change in this release.',+ '',+ '```bash',+ 'npm install && npm run dev',+ '```'+ ].join('\n');+ const digest = summarizeReleaseNotes(body);+ assert.deepEqual(digest, ['Appearance only. No functional change in this release.']);+ for (const line of digest) assert.doesNotMatch(line, /npm install/);+});++test("the project's own RELEASE.md digests to something a toast can hold", () => {+ // The body electron-updater actually hands us is this file (see+ // .github/workflows/release.yml → `body_path: RELEASE.md`), so it is the one+ // fixture guaranteed to stay realistic.+ const body = fs.readFileSync(path.resolve(__dirname, '..', 'RELEASE.md'), 'utf8');+ const digest = summarizeReleaseNotes(body);++ assert.ok(digest.length > 0, 'the shipped release notes must produce a digest');+ assert.ok(digest.length <= RELEASE_NOTES_MAX_BULLETS);+ assert.ok(total(digest) <= RELEASE_NOTES_MAX_CHARS, `${total(digest)} chars over budget`);+ for (const line of digest) {+ assert.doesNotMatch(line, /https?:\/\//, 'a raw URL reached the toast');+ assert.doesNotMatch(line, /\]\(/, 'an unparsed markdown link reached the toast');+ assert.doesNotMatch(line, /^\s*[-*#|]/, 'a markdown marker reached the toast');+ }+ // The tagline and the download table live above/below the news; neither is+ // what "What's new" should say.+ assert.ok(!digest.some((l) => /Downloads|Requirements|Build from source/i.test(l)));+});++test('options are honoured so a roomier surface can ask for more', () => {+ const body = `## Changes\n${Array.from({ length: 10 }, (_, i) => `- Change ${i}`).join('\n')}`;+ assert.equal(summarizeReleaseNotes(body, { maxBullets: 2 }).length, 2);+ assert.ok(total(summarizeReleaseNotes(body, { maxChars: 60 })) <= 60);+});