Skip to content

The agent that grows with you

feat(icons): distinguish desktop build flavors

ethernetcfa142f3e021
diff --git a/scripts/generate_icons.py b/scripts/generate_icons.py
index 49f60b7c5cb..b53eaa819c0 100644
--- a/scripts/generate_icons.py
+++ b/scripts/generate_icons.py
@@ -25,6 +25,12 @@ Sources of truth — two axes, composed per target:
squircle on Apple's 824x824 (r=185.4) grid — centered in 1024 with 100px
margins — so the icon matches the size of Apple-template neighbors.
+Desktop build identity comes from HERMES_PAYLOAD_TAG / HERMES_BUILD_COMMIT:
+Canary uses yellow/dark-yellow backgrounds. Commit builds use red/dark-red
+and a seven-character SHA badge. The girl and tile geometry do not change.
+Only apps/desktop outputs use this identity. Website, bootstrap, dashboard,
+and the shared master SVGs retain the default brand.
+
The girl is nested via its art bbox as viewBox, so it always lands centered in
the box (824 safe zone for squircles / height-fitted for the marks) without
distortion. The girl art corners sit ~185px from the squircle arc centers vs
@@ -84,6 +90,7 @@ from __future__ import annotations
import argparse
import io
+import os
import re
import sys
from pathlib import Path
@@ -188,8 +195,10 @@ TARGETS: list[tuple[str, str, object]] = [
class IconArt:
"""One generation's rendering inputs and caches; never writes to source."""
- def __init__(self, source: Path):
+ def __init__(self, source: Path, *, colors: tuple[str, str] | None = None, commit: str = ""):
assets = source / "assets"
+ self.colors = colors
+ self.commit = commit
self.girls = {color: assets / f"nous-girl-{color}.svg" for color in ("black", "white")}
self.backgrounds = assets / "backgrounds"
self.paths: dict[str, str] = {}
@@ -241,6 +250,9 @@ def girl_layer(art: IconArt, girl: str, box: tuple[float, float, float, float])
def background_inner(art: IconArt, name: str) -> tuple[str, int, int]:
"""Inner content + (width, height) of a background SVG asset."""
text = (art.backgrounds / name).read_text(encoding="utf-8")
+ if art.colors:
+ text = text.replace('fill="#ffffff"', f'fill="{art.colors[0]}"')
+ text = text.replace(f'fill="{DARK_HEX}"', f'fill="{art.colors[1]}"')
m = re.search(r'<svg\b[^>]*viewBox="0 0 (\d+(?:\.\d+)?) (\d+(?:\.\d+)?)"[^>]*>', text)
assert m, f"cannot parse viewBox of {name}"
w, h = float(m.group(1)), float(m.group(2))
@@ -249,15 +261,55 @@ def background_inner(art: IconArt, name: str) -> tuple[str, int, int]:
return inner, int(w), int(h)
+# Five-by-seven lowercase hexadecimal glyphs, one five-bit row at a time.
+# Vector cells keep release builds deterministic without any installed fonts.
+HEX_GLYPHS = {
+ "0": (14, 17, 19, 21, 25, 17, 14),
+ "1": (4, 12, 4, 4, 4, 4, 14),
+ "2": (14, 17, 1, 2, 4, 8, 31),
+ "3": (30, 1, 1, 14, 1, 1, 30),
+ "4": (2, 6, 10, 18, 31, 2, 2),
+ "5": (31, 16, 16, 30, 1, 1, 30),
+ "6": (14, 16, 16, 30, 17, 17, 14),
+ "7": (31, 1, 2, 4, 8, 8, 8),
+ "8": (14, 17, 17, 14, 17, 17, 14),
+ "9": (14, 17, 17, 15, 1, 1, 14),
+ "a": (0, 0, 14, 1, 15, 17, 15),
+ "b": (16, 16, 30, 17, 17, 17, 30),
+ "c": (0, 0, 14, 16, 16, 17, 14),
+ "d": (1, 1, 15, 17, 17, 17, 15),
+ "e": (0, 0, 14, 17, 31, 16, 14),
+ "f": (6, 9, 8, 28, 8, 8, 8),
+}
+
+
+def commit_layer(commit: str, bg: str) -> str:
+ cells = []
+ for index, char in enumerate(commit[:7]):
+ for row, bits in enumerate(HEX_GLYPHS[char]):
+ for col in range(5):
+ if bits & (1 << (4 - col)):
+ x, y = 184 + (index * 6 + col) * 16, 48 + row * 16
+ cells.append(f"M{x} {y}h16v16h-16z")
+ # The badge follows the tile's mac HIG inset, never the outer canvas.
+ transform = f' transform="translate(100 100) scale({824 / 1024})"' if "-mac-" in bg else ""
+ return (
+ f'<g{transform}><rect x="160" y="28" width="704" height="152" rx="24" fill="#29090c"/>'
+ f'<path fill="#ffffff" d="{"".join(cells)}"/></g>'
+ )
+
+
def compose_svg(art: IconArt, girl: str, bg: str) -> str:
"""Full svg text: background + girl layer, in the background's native
coordinate space (resvg scales to whatever output size is requested, so
the composition is size-agnostic — no manual box scaling)."""
inner, w, h = background_inner(art, bg)
+ badge = f" {commit_layer(art.commit, bg)}\n" if art.commit else ""
return (
f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}">\n'
f" {inner.strip()}\n"
f" {girl_layer(art, girl, GIRL_BOXES[bg])}\n"
+ f"{badge}"
"</svg>\n"
)
@@ -374,16 +426,34 @@ def target_bytes(art: IconArt, kind: str, arg: object) -> bytes:
return buf.getvalue()
+def build_art(source: Path) -> tuple[IconArt, IconArt]:
+ """Only desktop outputs carry build identity. Shared branding stays stable."""
+ art = IconArt(source)
+ tag = os.environ.get("HERMES_PAYLOAD_TAG", "")
+ commit = os.environ.get("HERMES_BUILD_COMMIT", "")
+ if commit:
+ if tag:
+ raise ValueError("Commit builds cannot also select HERMES_PAYLOAD_TAG")
+ if not re.fullmatch(r"[a-f0-9]{40}", commit):
+ raise ValueError("HERMES_BUILD_COMMIT requires an exact full 40-character SHA")
+ return art, IconArt(source, colors=("#e34850", "#4a1117"), commit=commit)
+ # Match the desktop/feed identity, including historical date-only tags.
+ if re.search(r"-canary\.20\d{6}(?:\d{6})?$", tag):
+ return art, IconArt(source, colors=("#f5cc32", "#443808"))
+ return art, art
+
+
def cmd_write(source: Path, out: Path) -> int:
"""Return failure when any target cannot be generated or verified."""
- art = IconArt(source)
+ art, desktop_art = build_art(source)
written = 0
failures = 0
for rel, kind, arg in TARGETS:
path = out / rel
try:
path.parent.mkdir(parents=True, exist_ok=True)
- path.write_bytes(target_bytes(art, kind, arg))
+ selected = desktop_art if rel.startswith("apps/desktop/") else art
+ path.write_bytes(target_bytes(selected, kind, arg))
written += 1
except Exception as exc: # noqa: BLE001 - report all, then fail
failures += 1
@@ -422,13 +492,14 @@ def cmd_check(source: Path, out: Path) -> int:
"""Structural verification: regenerate every target in memory and assert
the invariants that actually matter (there are no committed bytes to
byte-compare — outputs are generated on demand)."""
- art = IconArt(source)
+ art, desktop_art = build_art(source)
problems: list[str] = []
# every target must generate without error
for rel, kind, arg in TARGETS:
try:
- target_bytes(art, kind, arg)
+ selected = desktop_art if rel.startswith("apps/desktop/") else art
+ target_bytes(selected, kind, arg)
except Exception as exc: # noqa: BLE001
problems.append(f"{rel}: REGENERATE FAILED ({exc})")
diff --git a/tests-js/generate-icons.test.mjs b/tests-js/generate-icons.test.mjs
index 5a1ac7539da..2e34054ba05 100644
--- a/tests-js/generate-icons.test.mjs
+++ b/tests-js/generate-icons.test.mjs
@@ -1,5 +1,7 @@
import { spawnSync } from 'node:child_process'
import path from 'node:path'
+import fs from 'node:fs'
+import os from 'node:os'
import { fileURLToPath } from 'node:url'
import { expect, test, vi } from 'vitest'
import { generateIcons } from '../scripts/generate-icons.mjs'
@@ -63,6 +65,41 @@ with TemporaryDirectory() as directory:
expect(result.status, result.stderr).toBe(0)
})
+test.each([
+ { HERMES_PAYLOAD_TAG: 'v1.2.3', HERMES_BUILD_COMMIT: '' },
+ { HERMES_PAYLOAD_TAG: 'v1.2.3-canary.20260911010203', HERMES_BUILD_COMMIT: '' },
+ { HERMES_PAYLOAD_TAG: '', HERMES_BUILD_COMMIT: 'abcdef0'.padEnd(40, '1') }
+])('build identity reaches the child unchanged with separate source/output roots: %j', (identity) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-icon-env-'))
+ try {
+ const source = path.join(root, 'separate source')
+ const out = path.join(root, 'generated output')
+ const driver = path.join(root, 'scripts', 'build')
+ fs.mkdirSync(driver, { recursive: true })
+ fs.mkdirSync(source)
+ // Observe the real subprocess environment at the PM-driver boundary.
+ fs.writeFileSync(path.join(driver, 'icon_environment.py'), `
+import json, os, pathlib, sys
+out = pathlib.Path(sys.argv[sys.argv.index('--out') + 1])
+out.mkdir()
+(out / 'child.json').write_text(json.dumps({
+ 'identity': {key: os.environ.get(key) for key in ['HERMES_PAYLOAD_TAG', 'HERMES_BUILD_COMMIT']},
+ 'source': sys.argv[sys.argv.index('--source') + 1],
+ 'cwd': os.getcwd(),
+}))
+`)
+ expect(generateIcons(['--source', source, '--out', out], {
+ root, env: { ...process.env, ...identity }
+ })).toBe(0)
+ expect(JSON.parse(fs.readFileSync(path.join(out, 'child.json'), 'utf8'))).toEqual({
+ identity, source, cwd: source
+ })
+ expect(fs.readdirSync(source)).toEqual([])
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
test('failed icon processes cannot report a successful build', () => {
expect(generateIcons([], { run: () => ({ status: 7 }), env: {} })).toBe(7)
expect(generateIcons([], { run: () => ({ status: null, signal: 'SIGTERM' }), env: {} })).toBe(1)
diff --git a/tests/scripts/test_icon_flavors.py b/tests/scripts/test_icon_flavors.py
new file mode 100644
index 00000000000..06e50a34218
--- /dev/null
+++ b/tests/scripts/test_icon_flavors.py
@@ -0,0 +1,172 @@
+"""Build native icons with PM's locked renderer. Measure pixels, not SVG text."""
+import colorsys
+import io
+import itertools
+import os
+from pathlib import Path
+import struct
+import subprocess
+import sys
+
+from PIL import Image, ImageChops, ImageDraw, ImageFilter
+import pytest
+
+
+ROOT = Path(__file__).resolve().parents[2]
+
+
[email protected](scope="module")
+def generate(tmp_path_factory):
+ root = tmp_path_factory.mktemp("icon-flavors")
+ outputs = {}
+ sequence = itertools.count()
+
+ def build(tag="", commit="", *, rejected=False):
+ key = (tag, commit)
+ if key not in outputs:
+ out = root / str(next(sequence))
+ env = {**os.environ, "HERMES_HOME": str(root / "home"),
+ "HERMES_RUNTIME_DIR": str(root / "tools"),
+ "HERMES_PAYLOAD_TAG": tag, "HERMES_BUILD_COMMIT": commit}
+ command = [sys.executable, str(ROOT / "scripts/build/icon_environment.py"),
+ "--source", str(ROOT), "--out", str(out)]
+ result = subprocess.run(command, env=env, capture_output=True, text=True, timeout=180)
+ if rejected:
+ assert result.returncode != 0, "invalid build identity generated icons"
+ assert not out.exists()
+ return
+ assert result.returncode == 0, result.stdout + result.stderr
+ outputs[key] = out
+ return outputs[key]
+
+ return build
+
+
+def frames(path):
+ """Read every native frame, including ICO entries Pillow's n_frames misses."""
+ data = path.read_bytes()
+ if path.suffix == ".ico":
+ count = struct.unpack_from("<H", data, 4)[0]
+ assert {data[6 + i * 16] or 256 for i in range(count)} == {16, 24, 32, 48, 64, 128, 256}
+ for index in range(count):
+ width, height, _, _, _, _, length, offset = struct.unpack_from("<BBBBHHII", data, 6 + index * 16)
+ image = Image.open(io.BytesIO(data[offset:offset + length])).convert("RGBA")
+ assert image.size == (width or 256, height or 256)
+ yield image
+ elif path.suffix == ".icns":
+ assert data[:4] == b"icns"
+ assert struct.unpack_from(">I", data, 4)[0] == len(data)
+ image = Image.open(path)
+ assert {w * scale for w, h, scale in image.info["sizes"]} == {32, 64, 128, 256, 512, 1024}
+ for size in image.info["sizes"]:
+ frame = image.icns.getimage(size).convert("RGBA")
+ alpha = frame.getchannel("A").point(lambda a: 255 if a >= 128 else 0)
+ expected = [frame.width * x / 1024 for x in (100, 100, 924, 924)]
+ assert all(abs(a - b) <= 1 for a, b in zip(alpha.getbbox(), expected, strict=True))
+ if frame.width == 1024:
+ template = Image.new("L", frame.size)
+ ImageDraw.Draw(template).rounded_rectangle((100, 100, 923, 923), radius=185.4, fill=255)
+ # A three-pixel AA band around Apple's rounded-square template.
+ assert ImageChops.subtract(alpha, template.filter(ImageFilter.MaxFilter(7))).getbbox() is None
+ yield frame
+ else:
+ yield Image.open(path).convert("RGBA")
+
+
+def tile_color(image):
+ # Sample below the artwork, inside the tile (also works for mac margins
+ # and the centered wide Appx tile). Ignore sub-visible resampling alpha.
+ x0, y0, x1, y1 = image.getchannel("A").point(lambda a: 255 if a >= 128 else 0).getbbox()
+ return image.getpixel(((x0 + x1) // 2, y1 - 1))[:3]
+
+
+def assert_same_geometry(original, flavored):
+ assert original.size == flavored.size
+ assert original.getchannel("A").tobytes() == flavored.getchannel("A").tobytes()
+ # LANCZOS container downscales can leave sub-visible alpha at corners.
+ assert flavored.getpixel((0, 0))[3] <= 3
+ assert flavored.getpixel((flavored.width - 1, flavored.height - 1))[3] <= 3
+
+
+def assert_unbranded_outputs(stable, flavored):
+ for directory in ("assets", "website", "web", "apps/bootstrap-installer"):
+ for path in (stable / directory).rglob("*"):
+ if path.is_file():
+ assert path.read_bytes() == (flavored / path.relative_to(stable)).read_bytes(), path
+
+
+def test_canary_changes_only_desktop_background_preserving_art_and_native_geometry(generate):
+ stable = generate("v1.2.3")
+ canary = generate("v1.2.3-canary.20260911010203")
+ legacy = generate("v1.2.3-canary.20260911")
+ assert (canary / "apps/desktop/assets/icon.png").read_bytes() == (legacy / "apps/desktop/assets/icon.png").read_bytes()
+ for path in (stable / "apps/desktop").rglob("*"):
+ if not path.is_file():
+ continue
+ original_frames = list(frames(path))
+ canary_frames = list(frames(canary / path.relative_to(stable)))
+ assert len(original_frames) == len(canary_frames)
+ for original, yellow in zip(original_frames, canary_frames, strict=True):
+ assert_same_geometry(original, yellow)
+ hue, saturation, value = colorsys.rgb_to_hsv(*(v / 255 for v in tile_color(yellow)))
+ assert 0.10 < hue < 0.18 and saturation > 0.65, (path, yellow.size, tile_color(yellow))
+ assert (value < 0.4) if "dark" in path.name else (value > 0.8)
+ # Compare art in direct renders. Tiny container frames use LANCZOS,
+ # whose ringing legitimately depends on adjacent background colors.
+ if path.suffix == ".png" and original.width >= 256:
+ ink = (255, 255, 255, 255) if "dark" in path.name else (0, 0, 0, 255)
+ assert [p == ink for p in original.get_flattened_data()] == [p == ink for p in yellow.get_flattened_data()]
+ assert_unbranded_outputs(stable, canary)
+
+
+def test_commit_icons_are_red_and_print_only_the_actual_seven_digit_prefix(generate):
+ stable = generate("v1.2.3")
+ first = generate(commit="0123456" + "a" * 33)
+ changed = generate(commit="abcdef9" + "a" * 33)
+ same_prefix = generate(commit="0123456" + "b" * 33)
+ for path in (first / "apps/desktop").rglob("*"):
+ if not path.is_file():
+ continue
+ rel = path.relative_to(first)
+ assert path.read_bytes() == (same_prefix / rel).read_bytes(), rel
+ first_frames = list(frames(path))
+ other_frames = list(frames(changed / rel))
+ stable_frames = list(frames(stable / rel))
+ for original, red, other in zip(stable_frames, first_frames, other_frames, strict=True):
+ assert_same_geometry(original, red)
+ hue, saturation, value = colorsys.rgb_to_hsv(*(v / 255 for v in tile_color(red)))
+ assert (hue < 0.05 or hue > 0.95) and saturation > 0.6, (rel, tile_color(red))
+ assert (value < 0.4) if "dark" in path.name else (value > 0.8)
+ # No SHA change may move the tile/art or alter the region below its top quarter.
+ bbox = red.getchannel("A").point(lambda a: 255 if a >= 128 else 0).getbbox()
+ diff = ImageChops.difference(red.convert("RGB"), other.convert("RGB")).convert("L")
+ opaque = red.getchannel("A").point(lambda a: 255 if a >= 128 else 0)
+ changed_box = ImageChops.multiply(diff, opaque).getbbox()
+ assert changed_box is not None, (rel, red.size)
+ assert changed_box[1] >= bbox[1]
+ assert changed_box[3] <= bbox[1] + (bbox[3] - bbox[1]) * 0.25 + 3
+ # At full resolution, read back each glyph's bitmap from pixels. These
+ # digit forms spell 0123456, not a generic badge or a hash of the SHA.
+ expected = (
+ (14, 17, 19, 21, 25, 17, 14), (4, 12, 4, 4, 4, 4, 14),
+ (14, 17, 1, 2, 4, 8, 31), (30, 1, 1, 14, 1, 1, 30),
+ (2, 6, 10, 18, 31, 2, 2), (31, 16, 16, 30, 1, 1, 30),
+ (14, 16, 16, 30, 17, 17, 14),
+ )
+ for name in ("icon.png", "icon-dark.png"):
+ image = Image.open(first / "apps/desktop/assets" / name).convert("RGB")
+ for digit, rows in enumerate(expected):
+ for y, row in enumerate(rows):
+ for x in range(5):
+ pixel = image.getpixel((184 + (digit * 6 + x) * 16 + 8, 48 + y * 16 + 8))
+ assert (min(pixel) > 240) == bool(row & (1 << (4 - x))), (digit, x, y)
+ assert_unbranded_outputs(stable, first)
+
+
[email protected]("tag,commit", [
+ ("", "abcdef0"), ("", "a" * 41), ("", "A" * 40),
+ ("", "a" * 39 + "g"), ("", "a" * 40 + "\n"),
+ ("v1.2.3", "a" * 40),
+])
+def test_invalid_or_conflicting_build_identity_cannot_emit_icons(generate, tag, commit):
+ generate(tag=tag, commit=commit, rejected=True)