Compare commits

...
Sign in to create a new pull request.
Author SHA1 Message Date
8f4d935346 Merge pull request 'Release candidate a6: dev 24883997 into main' (#173) from dev into main 2026-11-20 20:57:39 +00:00
Meta Vens
248839974b Idunn recipe: pin dist f562f8fa (release a6: painterly cel-3 look, real night sky, more sky in the frame)
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m9s
Build pull request / Build pull request (pull_request) Successful in 3m28s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:56:14 +01:00
f562f8fae9 Merge pull request 'Ridge look and night sky: painterly cel-3, fitted tone curve, real stars and moon, more sky' (#172) from void/ridge-night-sky into dev
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
2026-11-20 20:51:22 +00:00
Meta Vens
d84a31ce79 Delete the unused MARGIN constant
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m43s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 21:50:36 +01:00
Meta Vens
01d74b8188 Delete the sky-backdrop contrast apparatus, the sun-disc floor and dead star/tone code; keep stars out of the moon disc
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
skyBackdrop/BACKDROPS and the tests that held login text against sky bounds are gone (the bounds were false: the look is tuned by eye). The vertex-carry guard asserts placement only. d3-celestial's BSD-3 text is in THIRD_PARTY_NOTICES.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 21:50:20 +01:00
Meta Vens
0089cd956a Ridge framing: horizon at 0.85 of the viewport (operator, by eye)
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m56s
About 31 degrees of sky in a 16:9 cell. The vertex-star guard drops to 0.8:
low vertices sit in the moonlit haze at this framing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:33:04 +01:00
Meta Vens
53910b1e5b Brighter stars, second step: point spread 1.5 arcmin, contrast exponent 0.8; the test now asks for a visible lift (20 of 255) at the vertices, not just a drawn star
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 21:15:25 +01:00
Meta Vens
3185ea90c1 Brighter stars: smaller point spread, gentler contrast compression, larger points (starting values; the operator tunes by eye)
Under a full moon at the new framing every constellation-line vertex in the sky strip now carries a drawn star (was 24 of 34); a test pins it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 21:12:47 +01:00
Meta Vens
0fd1ec45ae Frame: the horizon sits at one authored fraction of the viewport (HORIZON_AT 0.95), set by windowFor alone
windowFor places the plane so its horizon row lands at HORIZON_AT of the height, the same for every sky state and viewport; the plane runs below the viewport bottom (negative bottom) and the near plain is cropped. Every consumer already read the camera and plane from windowFor; the sheet's card placement now reads plane.bottom too, and takes ?h= for a phone-shaped cell. Tests pin the constant horizon, ~35 degrees of sky in a 16:9 cell, and plane coverage with baked ground to spare at 1024x768, 1920x1080, 375x812.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 21:11:31 +01:00
Meta Vens
9d0764f23a Harness: ?labels=1 debug option names each constellation chain in frame (ids fetched from d3-celestial at run time; not shipped)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 21:03:29 +01:00
Meta Vens
5e64e83389 Pin the night bodies under the cards: still paints every line, star and moon before any card; live keeps them in the host canvas under the twinkle canvas and the rig
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 20:57:52 +01:00
Meta Vens
c18d3e3e9d Harness README: night sets and the night look's knobs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 20:53:23 +01:00
Meta Vens
52a085143b Harness: ridge sheet pins moments (?moments=, ?night=1) and shows stars, moon and lines (?lines=1); night key at its targets, airglow neutral
The night set renders new, first-quarter and full moon at four hours each plus deep dusk. Night exposure keys the sky to where the curve wants it so the per-channel curve does not turn the scotopic blue shift into a saturated sky.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 20:52:23 +01:00
Meta Vens
bf71489968 Constellation lines: hidden extra toggled by re-picking Night, persisted per viewer; credits for the star data
pickSkyState (the menu's pick): Night while the choice is Night toggles the lines, stored in ratatoskr.skyLines (storage wrapped), told to listeners as a sky change; the rebuild key carries ':lines' at night so the scene is rebuilt with the option. Sky menu Data section credits BSC5 and d3-celestial (BSD-3-Clause).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 20:49:37 +01:00
Meta Vens
05cff53959 Stars, moon and constellation lines drawn through the sky's display; the seeded star field and NIGHT_LUMA gating are deleted
nightBodies.ts places the catalogue stars for the sky's own moment, adds their radiance (extinction, B-V colour, point spread) to the dome behind them and takes the sky's display, so twilight hides them; the moon is drawn with its terminator and earthshine; lines over the stars when asked. stars.ts keeps the twinkle schedule, now a gain on a star's flux. Ridge.ts bakes the bodies and takes a lines option.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 20:48:29 +01:00
Meta Vens
fe12e10f7c Night: moon as key light, airglow floor, adapting exposure with partial adaptation and a scotopic grade
nightSky.ts holds the night's photometry (moon magnitude by phase, Krisciunas & Schaefer; airglow; star radiance; colour from B-V). The moon gets its own atmosphere bake for the night state and lights the dome, the clouds, the haze lookup and the cards (replacing nightAmbient and the cel bands' sun at night). Night loses its fixed knots and 0.043 ceiling: it adapts like day with the targets scaled by partial adaptation, a scotopic grade (Jensen 2001 luminance, blue shift) before exposure in CPU and shader, NIGHT_CEILING tunable (1). The ink-ceiling test for night is dropped with the ceiling.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 20:44:11 +01:00
Meta Vens
8c377b58ec Night sky data: BSC5 naked-eye stars and constellation lines, packed by a committed generator; star placement by the sun's sidereal transform
2887 stars (Vmag <= 5.5) and 150 line chains, 21 KB packed. Placement precesses J2000 to the date and uses sun.js equatorialToHorizontal; tests hold five stars and the moon to astropy's altitude/azimuth within half a degree.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 20:36:24 +01:00
Meta Vens
18ad84aff5 Sky: one sidereal transform for sun, moon and stars; low-precision moon ephemeris and phase
sun.js exports daysSinceJ2000, gmstRad, sunEquatorial and equatorialToHorizontal (sunPosition is now their composition, unchanged in value). moon.js adds the Astronomical Almanac low-precision moon, phase from elongation (Meeus 48.3), topocentric position. Tests against Meeus ex. 47.a and USNO phases.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 20:32:24 +01:00
Meta Vens
d44bf032ca Ridge look: cel-shaded relief, painterly cel is the default look
RidgeLook gains celBands/celSoftness/celBandLevels and a coarse ambient step; DEFAULT_LOOK is painterly with cel 3, PHYSICAL_LOOK keeps the old Lambert look. Sheet presets: physical, swiss, poster, painterly, painterly-cel-2/3/4.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 16:13:05 +01:00
Meta Vens
3232c866ca Tone curve: fitted monotone curve with a small black lift replaces the additive lift and the 0.47 day floor; night ambient
Per-sky monotone cubic through five knots (black lift, p5/p50/p95 of the sky grid to target luminances, white or the night ceiling), shared by sky and cards. Night gets a fixed-knot curve and a RidgeLook.nightAmbient term.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 16:11:44 +01:00
Meta Vens
fa8f2a163b Harness: ridge look sheet (sky states x looks, four art-direction presets)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 14:46:56 +01:00
Meta Vens
d4be09c2b2 Ridge look: art-pass axes as uniforms (relief, fixed light, tints, tone, noise)
reliefWeight, reliefLight, hazeTint, nearWarm, contrastByDistance,
cardToneStep, cardGradient, inkScale, groundNoise, cloudShadows; all default to
today's look. makePhysicalSky takes an optional sun for the look sheet.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 14:41:14 +01:00
Meta Vens
9adcd6fe63 Ridge lighting: one RidgeLook record, shader reads it as uniforms
The look constants (ink geometry, ink keeps, sun cut-off) become RidgeLook with
DEFAULT_LOOK; lightCards and lightingOf take an optional look. hazeScale and
ambientScale are new axes (default 1 = today). A recording-GL test proves an
override reaches the shader uniforms.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 14:38:14 +01:00
967d987eac Merge pull request 'Ridge runtime: lit G-buffer cards, camera on a circle (plane path deleted)' (#171) from void/ridge-runtime-cards into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 4m2s
2026-11-20 13:09:30 +00:00
Meta Vens
2e3e9133c0 Ridge baker tests: check wall distance and albedo in every wall column
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m36s
The face-up albedo mutant still survives (no fixture has a wall under a face steep enough to move the
albedo: not yet reached); the card-0 wall mutant is killed by the near-hill fixture.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 13:59:43 +01:00
Meta Vens
3b5c2a2487 Ridge baker tests: kill the card-0 wall and face-up wall albedo mutants
A near hill makes every row of card 0 lie below its first sample (so a flagged card 0 would show);
a ramp under card 1's first sample makes its face steep (so albedo from the face normal would show).
The geometry channel-swap mutant follows the encoder's new spelling.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 13:49:10 +01:00
Meta Vens
e48a2bf76b Ridge runtime: the card rig and still, scene wiring, v2 asset gate and docs
startRig puts one element per lit card, farthest first, at its rows with transform-origin on the
horizon centre, animated by +-scale_i x heading with scale(scale_i); the still draws the same cards at
heading 0. index.ts lights in prepare, so a sky-change rebuild lights again and any failure (no WebGL2
included) is planesFail and the sky alone. ridgeAssets.test gates the committed v2 bake.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 13:48:53 +01:00
Meta Vens
32c127cd2a Ridge runtime: light the baked cards once per sky in WebGL2, and the K-card loader
lightCards.ts: one program on its own canvas, per card sun and ambient in the column frame,
aerial perspective from the geometry distance and the atmosphere's extinction, contour ink,
the sky's own display; wall code is the face up. Context released after the last card.
Backdrop.ts fetches and decodes every card straight and lights once; any failure is null.
toneMap exports its ACES constants and earthAtmosphere its ground extinction, so the shader copies no number.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 13:48:50 +01:00
Meta Vens
53b0394f89 Ridge runtime: cardMotion, the one owner of pan reach, heading range and card scale
Heading each side is the baker's range capped so every card still covers the viewport;
card i pans scale_i x heading about the horizon centre. Tests on phone, tablet, desktop
and ultrawide viewports and for the cap.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 13:48:46 +01:00
Meta Vens
6a31b716b3 Ridge bake: rebake Vienna with wall rows, camera and per-card scale (vienna-6815bb9dca99)
Three cards (splits 6, 40 km), camera r +200 m, heading range 23 deg, per-card scale
1.156 / 1.018 / 1.004. The six-key sun-frame bake vienna-12e733dc9f09 is removed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 13:37:51 +01:00
Meta Vens
8ed2088a21 Ridge baker: wall rows, the camera on a circle, per-card distance and scale
Cards i > 0 flag the extruded face under their first sample as wall (R = G = 255 in the
geometry file, albedo with the face up); the manifest gains camera {r_m, heading_max_deg} and
per-card distance_m (non-wall median) and scale = d / (d - r). The baker refuses |r| >= half the
nearest distance and any camera that uncovers the frame. Tests and mutants for each rule.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 13:37:24 +01:00
Meta Vens
19be8ec492 Ridge runtime: delete the v1 sun-key planes (frames, crossfade, two-frame Backdrop) and parse manifest v2
frameChoice, frameLuma, the two-frame Backdrop, the v1 ridgeAssets gate, DRIFT_DEPTH,
the plane rig and paintPlanes are gone; parseManifest reads schema 2 (K cards, encoding,
camera.heading_max_deg, pxPerDegV). Until the lit-card rig lands the scene is the sky alone.
The plane/index tests of the deleted behaviour are removed here and return rewritten.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 13:19:04 +01:00
030a4a9231 Merge pull request 'Ridge baker: G-buffer cards from seams through the ray march (chain painter deleted)' (#170) from void/ridge-gbuffer-baker into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m7s
2026-11-20 03:36:48 +00:00
Meta Vens
a9eb9acbf9 ridge-bake tests: the Vienna fixture no longer cuts for a slide
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m23s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:31:17 +01:00
Meta Vens
a320f17431 ridge-bake tests: delete the slide-reveal tests and mutants
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:30:30 +01:00
Meta Vens
14ad4d14f9 ridge-bake: delete the reveal mask, max_slide_px and SLIDE_PCT (verdict s2)
The slide contract (viewport-aspect drift, simultaneous slides) lives in the runtime cut; a baker
bound of 5% of the card width was unsound and did not lower the decode total. cards() is again one
rectangle of rows with coverage; the schema is regenerated and committed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:30:29 +01:00
Meta Vens
37b40c89b0 ridge-bake tests: four slide scenes so each part of the cut is needed
Side-by-side nearer ridges, overlap at the edge of their union and a ridge across the window each
need a different term of the cut (single-card slide, slide width, frame edge). The frame-edge mutant
now treats what lies beyond the frame as held (the old one was equivalent).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:06:31 +01:00
Meta Vens
4c9064d50e ridge-bake tests: slide shifts move columns, the swept-rows term is pinned under a stronger pull
The slide check shifted the albedo along rows, so erosion 0, single-card and frame-edge mutants
survived; it now shifts the last axis. A second test sets the seam prior to 0.1 on the 4 to 15 km
ridge, where only the swept-rows term prevents the hop (at 0.02 the mutant without it cannot tear).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 03:51:13 +01:00
Meta Vens
1e52bd3e68 ridge-bake: commit the regenerated schema (max_slide_px)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 03:43:24 +01:00
Meta Vens
f0f7263e9e ridge-bake tests: written-card round trip, six receding ridges, slide bound, rules that survived
Decode the written WebPs against the cards (channels, range, straight alpha); the six receding-ridge
fixtures with the 0.35 alpha-jump metric; no slide within the bound reveals a cut pixel; empty card;
SEAM_SEP, elev curvature, coverage rows, interpolation and renormalisation. mutate.py grows to 33
mutants. README describes the reveal bound.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 03:40:00 +01:00
Meta Vens
1df9222e28 ridge-bake: reveal-bounded cards, manifest max_slide_px, prior 0.02, empty-card refusal
cards() cuts from each card the pixels the nearer cards hide at every offset within MAX_SLIDE_PX
(ceil(5% of the card width), the runtime's DRIFT_FRAC), also when one card slides alone; the composite
at rest is unchanged. Manifest v2 carries max_slide_px. pack() refuses an empty card naming its splits.
coverage() no longer counts the rows below the first sample twice. SEAM_PRIOR 0.02.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 03:40:00 +01:00
Meta Vens
f2c10ff798 ridge-bake: seam prior 0.1, card mutants, README for cards
The prior is the value where the side-by-side test passes with the swept-rows term and fails without it
(0.05 and below let a seam without the term follow the ridge, 0.15 and above hop across it with the term).
mutate.py holds 16 mutants of the card rules, the cache keys and the export checks, every one killed.
README rewritten for cards, manifest v2, the seam rule and the low-pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 03:09:24 +01:00
Meta Vens
9bcd7f0db7 ridge-bake: K+1 layered-depth G-buffer cards split by K authored seams; manifest v2
ridge.py: elev (shared by march and prefilter), prefilter, normals, set_view from the march skyline,
coverage, seams (one forward-energy DP per authored split), cards (first visible hit at or beyond the
near seam, crest coverage, cross-fade over seam +- XF, nested alphas so the composite equals the opaque
coverage, cropped to the row band). load_preset requires card_split_km (strictly increasing, at most
MAX_CARDS - 1). export.py: manifest v2, two WebPs per card, check_cover, check_budget on count, total
bytes and decoded bytes, sheet. places.json: Vienna card_split_km [6, 40], prefilter_m 100.
The seam prior is 0.05 rows/nat^2 (tie-break only): at 2.0 the seam hopped across a receding ridge
between two columns, which the spec's own side-by-side test forbids.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 03:01:41 +01:00
Meta Vens
568f6c19d3 ridge-bake: delete the chain stage-flat painter, the sun keys and their tests
Cut 1 of ridge-gbuffer-baker (rulings ridge-bake-gbuffer-depth-bands, ridge-cards-runtime-lit,
ridge-cast-shadows-dropped-for-now). Deletes first: extract, chains, sweep, slots, tapers, the painter,
the relight family, shadows, sun.py, sun_set, luma_range, check_near_cover, the painter inputs in
places.json, and every test and mutant that exercised them. export.py is left unrunnable until the
card writer replaces write_bake; the ray caches stay valid (march, rays_key, stage0 unchanged).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 02:47:21 +01:00
Meta Vens
0766f107ab client-build-install: the carried config equals the pin after release a5
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m24s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 02:20:55 +01:00
5544fcfd6c Merge pull request 'Release candidate a5: dev e8e9cbbc into main' (#169) from dev into main 2026-11-20 01:17:02 +00:00
Meta Vens
e8e9cbbcb8 Idunn recipe: pin dist a1fdfee3 (release a5: ridge only, Commons row, file sharing on)
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 2m50s
Build pull request / Build pull request (pull_request) Successful in 3m27s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 02:16:41 +01:00
Meta Vens
a1fdfee3cc Config: file sharing on (fileZoneShare.enabled); the Commons row and share rows ship lit
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m31s
Operator 2026-11-20: "members and minds post, ship it lit"
(ratatoskr:ruling:commons-members-and-minds-post-ship-lit).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 02:13:08 +01:00
829c94de63 Merge pull request 'Release a5: serve the ridge only (terrain style deleted) + Commons files row' (#168) from void/rc-a5 into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 2m52s
2026-11-20 00:53:20 +00:00
Meta Vens
b36173005b Merge remote-tracking branch 'origin/void/commons-files-row' into void/rc-a5
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m31s
2026-11-20 01:39:32 +01:00
Meta Vens
02f3bc0f2f client-build-install: the served-style question is answered (ridge only)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:09:16 +01:00
Meta Vens
c1628468a3 Serve the ridge scene only: delete the terrain style and its picker
Removes scene/terrain/, the temporary sceneStyle.ts localStorage override, the Terrain/Ridges
picker in SkyStateControl, terrainSkyFor/terrainDrawn and the terrain reach, 'terrain' from
SceneStyle, and skyBand.ts (the band shaping only the terrain sky used; FixedSkyState now lives
in skyState.ts). A config or stored value that says anything but 'raymarch' is the ridges.
skyBackdrop keeps its constants: the bounds are at least as wide as the ridge budgets, now
asserted directly instead of against the terrain union. The raymarch scene is untouched.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 16:05:19 +01:00
Meta Vens
87993ad36e Commons row: found by alias only; the file-zone create type is the one owner of 'is a zone'
Provisioning creates #commons with type org.gamecult.file_zone and records no
id for it, so the invented file_zones.commons carried id and the isFileZone
alias clause were second owners. Doc says members need the poster level.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:01:51 +01:00
Meta Vens
d7ed9ffb43 Add the Commons entry row: found by alias or carried id, opens the album view
Commons is found by file_zones.commons in the stewardships state, else the
alias #commons:<server>, through lookupZoneRoom (shared with the Media row).
Gated on fileZoneShare.enabled; shown above the tiers; nothing when absent.
isFileZone accepts the Commons alias on the home server.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 15:59:41 +01:00
77e95c2826 Merge pull request 'Release candidate: dev c2cdde1e into main' (#166) from dev into main 2026-11-14 12:59:10 +00:00
Void
c2cdde1ee7 Idunn recipe: pin dist b30ddac0 (ridge plane rebake, #165)
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m47s
Build pull request / Build pull request (pull_request) Successful in 4m35s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 12:55:17 +00:00
b30ddac052 Ridge baker: near plane opaque to the horizon, occlusion-matched far planes, near-cover check; rebake Vienna (#165)
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
2026-11-14 12:52:20 +00:00
786b41ddf1 Merge pull request 'Release candidate: dev eefaa871 into main' (#164) from dev into main 2026-11-14 11:33:46 +00:00
Void
eefaa8716d Idunn recipe: pin dist 5b7b4c2e (ridge backdrop A+D, #163)
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m27s
Build pull request / Build pull request (pull_request) Successful in 4m4s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 11:19:59 +00:00
5b7b4c2eeb Ridge backdrop A+D: baked ridge planes over the live sky (Vienna) (#163)
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m6s
2026-11-14 11:07:58 +00:00
39c9924042 Merge pull request 'Release candidate: dev c6fb57d9 into main' (#146) from dev into main 2026-11-14 08:09:08 +00:00
Void
c6fb57d9f9 Idunn recipe: correct the config.json comment (the carried file is aliased over the tree's)
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 5m2s
Build pull request / Build pull request (pull_request) Successful in 4m18s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 07:59:09 +00:00
Void
5310f606cd Idunn recipe: Ratatoskr static release from the pinned dist tarball (934f8238)
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Rat dev preview / Build dev preview (push) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 07:55:39 +00:00
934f82386d Merge pull request 'Scene sky-change test: stay inside the timeout under load (bake each sky once)' (#162) from void/scene-test-flake into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 4m57s
Build pull request / Build pull request (pull_request) Successful in 3m9s
2026-11-14 02:47:33 +00:00
Void
a61252e664 Scene test: pin the stand-down of a replaced rebuild deterministically
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m44s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 02:32:31 +00:00
Void
1b101c2889 Scene sky-change sweep: bake each state's sky once so the test stays inside its timeout under load
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 02:27:25 +00:00
b13080ebd2 Merge pull request 'Files desk: name loose files the album list cannot show; pin the old publisher wire shape' (#161) from void/files-desk-loose-files into dev
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
Build pull request / Build pull request (pull_request) Has been cancelled
2026-11-14 02:18:49 +00:00
Void
ed2205d6d6 Loose-files note: gating is a tested function; a redaction refreshes it
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m37s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 02:18:47 +00:00
Void
33e31a6102 Files desk: name loose files the album list cannot show; pin the old publisher wire shape
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 02:14:21 +00:00
d5b9e33536 Merge pull request 'docs: harvest physical-room row and sources for the 41 s and degraded-score claims' (#160) from void/harvest-physical-room into dev
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
Build pull request / Build pull request (pull_request) Has been cancelled
2026-11-14 01:54:37 +00:00
Void
6b40809f9d docs: harvest polarity row loses the shotgun claim; physical room run row; sources for the 41 s and degraded-score claims
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m21s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 01:54:29 +00:00
38b2c064b2 Merge pull request 'Upload failures tell the sender a reason and a next step' (#159) from void/upload-failure-reasons into dev
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
Build pull request / Build pull request (pull_request) Has been cancelled
2026-11-14 01:53:57 +00:00
Void
ec2637a2bb Upload reasons: offline and background-tab only explain a dropped request; Details lays out in the card
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m54s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 01:53:47 +00:00
Void
c36b6e2cd9 Upload failures tell the sender a reason and a next step; diagnostics behind Details
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
uploadFailure attaches what the client observed (unreadable, offline, hidden tab, aborted,
progressed, stopped) and keeps a homeserver errcode; uploadReason turns that into a cause and an
action. The upload cards and the share panel's refusal list use it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 01:52:06 +00:00
bc097d0490 Merge pull request 'docs: Kiko's corrections to the symphony grammar harvest' (#158) from void/harvest-corrections into dev
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
Build pull request / Build pull request (pull_request) Has been cancelled
2026-11-14 01:47:42 +00:00
398b172e21 Merge pull request 'Files desk: refuse files over the server's upload cap before sending' (#157) from void/files-desk-cut5 into dev
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
2026-11-14 01:47:41 +00:00
Void
907635917e Size refusal: a failed run still names the refused files; a cap that is not a positive number is no cap
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m59s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 01:47:07 +00:00
Void
d3894f5b51 docs: apply Kiko's corrections to the symphony grammar harvest
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m21s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 01:46:39 +00:00
Void
65d7e7a46a Files desk: refuse files over the server's upload cap before sending
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
A file larger than m.upload.size is named in the note and dropped from the pick before any
upload or album root; a pick of only such files sends nothing. No stated cap or no file size
refuses nothing.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 01:45:42 +00:00
da822e9e4e Merge pull request 'Phone-hit guard: no blind spots for aliased, namespace and non-tsx IconButton; scope-aware PhoneHit check' (#156) from void/phone-hit-guard-hardening into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 5m5s
Build pull request / Build pull request (pull_request) Successful in 5m12s
2026-11-13 23:46:37 +00:00
Void
0271d5f692 Phone hit guard: see every spelling of IconButton, read scope and the AST
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m54s
The coverage guard now scans every script file under src, resolves aliased and
namespace-member IconButton tags, and fails loudly on any other mention
(as={IconButton}, rebinding, re-export, destructuring, element access). A
PhoneHit that an inner scope rebinds, or that is imported as a type, no longer
counts. drawnPx/sizeProp read the parsed tag, not its text. The emoji Sidebar
column's 4 px gap is pinned.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 23:34:49 +00:00
08be0a792d Merge pull request 'Desk: one owner for the open count, derived row fold state, guest and settled fixtures' (#155) from void/desk-slice-1-findings into dev
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
Build pull request / Build pull request (pull_request) Has been cancelled
2026-11-13 23:33:40 +00:00
Void
6a209649dc Desk Soul fixes: memoize the navigator's list so the hash check runs once; a check that cannot run withdraws every card; pin the navigator's verified count
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 23:33:39 +00:00
Void
b8741f9dcc Desk: one verified count, rotation-safe row fold, fixtures for guest and settled
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m35s
The navigator's 'Desk · N open' counted cards the desk withdraws on an
options_hash mismatch. buildDesk now owns the count (open_count less the
withdrawn open cards) and the navigator reads it through the same
useUnverified check the page uses; before the check lands it shows no count.
A row's fold is derived from the screen size and a tap, so rotation cannot
leave it stale. Adds guest and settled-while-answered fixtures and tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 23:29:06 +00:00
0b3e2294ca Merge pull request 'docs: Mimir bioacoustic research harvest for the symphony grammar' (#154) from void/symphony-grammar-harvest into dev
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
Build pull request / Build pull request (pull_request) Has been cancelled
2026-11-13 23:28:25 +00:00
Void
d42584cd72 docs: harvest of Mimir's bioacoustic research for Aqua's activity grammar
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m17s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 23:28:20 +00:00
f3d0ebdb06 Merge pull request 'Media row reads room ids from @rooms.file_zones' (#153) from void/stewardships-rooms-key into dev
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
Build pull request / Build pull request (pull_request) Has been cancelled
2026-11-13 23:25:20 +00:00
Void
cf1ecd64da Media row reads the room id from @rooms.file_zones, the shape provisioning writes
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m42s
The provisional media[<mind>] key was never written by anything; gamecult-ops #111 records ids under @rooms. The old key is no longer read.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 23:24:00 +00:00
ca3046e662 Merge pull request 'docs: Files desk status after cuts 1-4 and Stop' (#152) from void/files-desk-doc-status into dev
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
Build pull request / Build pull request (pull_request) Has been cancelled
2026-11-13 23:18:19 +00:00
Void
817f2e46d6 docs: Files desk status names what is built and that the Commons row is not
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m25s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 23:18:17 +00:00
a078346ecc Merge pull request 'Files desk: Stop a send in flight, show replaces loops, freshest last event on add' (#151) from void/files-desk-send-cancel into dev
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
Build pull request / Build pull request (pull_request) Has been cancelled
2026-11-13 23:17:42 +00:00
Void
c98d0175ff Soul fixes: sent-but-unechoed events count for the freshest last event; pre-aborted send starts no upload
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 5m33s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 23:17:40 +00:00
Void
e406ec7dc4 Files desk: Stop a send in flight; files in a replaces loop all show; Add files threads after the freshest event
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Stop aborts the running upload (onPromise + mx.cancelUpload) and leaves it and the rest picked as 'stopped'. foldVersions shows files caught in a replaces loop with no head instead of hiding them. An add reads the room timeline at send time for the newest event in the thread.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 23:14:42 +00:00
d12e7bd578 Merge pull request 'Files desk cut 4: add files to an open album, named upload refusals' (#150) from void/files-desk-cut4 into dev
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
Build pull request / Build pull request (pull_request) Has been cancelled
2026-11-13 23:11:35 +00:00
Void
90c6d5e278 Cut 4: pin that ShareSet sends into an existing album
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 5m22s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 23:11:33 +00:00
Void
0622d7d65d Files desk cut 4: add files to an open album; name the upload refusals
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
sendShareSet takes a title or an existing album (no new root; the first file threads after the album's newest event). Failed files carry the refusal for M_TOO_LARGE, M_FORBIDDEN and M_LIMIT_EXCEEDED in the result note. AlbumView mounts an Add files panel inside an open album.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 23:05:37 +00:00
f491df04f9 Merge pull request 'Files desk cut 3: versions via org.gamecult.publish.replaces' (#149) from void/files-desk-cut3 into dev
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
Build pull request / Build pull request (pull_request) Has been cancelled
2026-11-13 23:03:48 +00:00
Void
5835e565cd Cut 3 Soul fixes: replaces counts only from the same sender; tests for the loop guard and the cover
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 6m20s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 23:03:33 +00:00
Void
796bc161a9 Cut 3: doc marks versions done
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 23:00:10 +00:00
Void
ac6018b57c Files desk cut 3: show the latest version of a file chain, earlier versions folded under it
A file event naming org.gamecult.publish.replaces supersedes the event it names. foldVersions reads the chain from the events alone; buildAlbums lists heads (count too) and AlbumView unfolds 'N earlier versions'. Both events stay ordinary files for other clients.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 22:59:52 +00:00
143bcc2dc6 Merge pull request 'Files desk cut 2: pagination in useAlbums, ShareSet folder test' (#148) from void/files-desk-cut2 into dev
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
Build pull request / Build pull request (pull_request) Has been cancelled
2026-11-13 22:59:50 +00:00
Void
6aaee8badd Cut 2: doc names the page cap; truncation note says albums or files
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 5m20s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 22:59:33 +00:00
Void
01dfb155c5 Files desk cut 2: read every page of threads and replies; pin folder -> album title in ShareSet
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
useAlbums followed no next_batch, so a zone past 100 albums or 100 files per album was silently cut. readPages follows the token up to 20 pages per endpoint and says when the cap stopped it; AlbumView shows a dim note then.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 22:55:30 +00:00
cf8b16ff5d Merge pull request 'docs: Commons and per-Persona Files desk' (#142) from void/commons-files-desk into dev
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
Build pull request / Build pull request (pull_request) Has been cancelled
2026-11-13 22:47:34 +00:00
Void
036146ce40 docs: fold Eureka's answers into the Files desk doc (room, cap, poster, final marker, Range unverified)
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m56s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 22:47:25 +00:00
bb6155709a Merge pull request 'Files desk cut 1: folders by album title path, share into the current folder' (#147) from void/files-desk-view into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 4m34s
Build pull request / Build pull request (pull_request) Successful in 4m31s
2026-11-13 21:46:36 +00:00
Void
b8eed50bd7 Soul fixes: a folder that empties keeps its Back row, blank titles get a label
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m1s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 21:46:28 +00:00
Void
53a724ae27 Files desk cut 1 under Matrix authority: folders by album title path, share into the current folder
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Albums titled a/b/c group into folders in AlbumView; ShareSet prefixes the
current folder onto the album title it sends. No wire change.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 21:45:00 +00:00
229591e22c Merge pull request 'Soft logout keeps local data; MAS front hides register and reset' (#145) from void/mas-client-fixes into dev
Some checks failed
Rat dev preview / Build dev preview (push) Successful in 3m39s
Build pull request / Build pull request (pull_request) Has been cancelled
2026-11-13 19:32:10 +00:00
Void
cd30c3dc40 wipeLocalData test: lint-clean never-settling store
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m23s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 19:13:14 +00:00
Void
8fb95402f5 wipeLocalData: bounded clearStores, storage clear that cannot reject; tests that bite
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 19:13:04 +00:00
Void
31d58075db Second Soul pass: soft event without a session wipes, wipe never rejects, rendered MAS tests
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
wipeLocalData moves to its own module with injectable ports: per-database failures are contained and localStorage clears in a finally. A soft logout with no session to remember is treated as hard. Login/PasswordLoginForm/ResetPassword MAS behavior is now tested by rendering. Login and register completion settle once per response.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 18:56:08 +00:00
Void
3a5258c3ef Soul fixes: idempotent logout handler, keep register consent entry under MAS, settle stores on register
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
First SessionLoggedOut decides; later events are ignored so a second soft event cannot fall into the wipe. Under MAS a configured registrationEntry (with its training notice) is kept; the MAS notice replaces only the in-client form and bare link. Registration goes through the same keep-or-wipe settle as login. Soft record drops its unused baseUrl. One shared https-or-localhost predicate.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 18:40:59 +00:00
Void
4fd83fb4c4 Soft logout keeps local data and re-logs in on the same device; MAS front hides register and reset
Soft (soft_logout === true) drops only the access token and records the device; sign-in is fixed to that user and sends device_id; same user and device keeps the stores, anything else wipes via the one wipeLocalData. Hard logout still wipes. When discovery advertises an msc2965 account or issuer, the register and forgot-password entries give way to a notice pointing at the account page.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 18:36:51 +00:00
dc9a541820 Merge pull request 'Phone glyphs: bigger icons in IconButtons and nav chevrons on phones' (#144) from void/phone-glyphs into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m49s
2026-11-13 18:24:24 +00:00
Void
9d65a34507 phoneGlyph test: pin each Icon size's px to folds' own CSS
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m3s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 18:20:12 +00:00
Void
9db91378c5 Phone glyphs: icons inside IconButtons and the nav chevron draw larger on phones, box unchanged
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 5m0s
folds draws a glyph at 16-24 px; on a phone the 16/18/20 px ones read small in their buttons. One global
rule per folds Icon size scales the glyph (22/24/24/26/28 px) at paint time inside an IconButton, so no
button, PhoneHit area or row changes size and desktop is untouched. phoneGlyph.test.ts pins the folds
class names, the px range and that the rule is a phone-only scale.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 17:52:10 +00:00
Void
1455988a83 Merge dev 8ba407cd into main
No content change: tree equals dev's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 15:48:20 +00:00
Void
a8e3acbde0 docs: Files desk decided as Matrix-only (A); Eureka's notes folded in; cut 1 recorded
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m20s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 15:46:23 +00:00
Void
0ab185bb57 docs: Files desk as a comparison, Matrix as the single authority (A) against the host service (B); publisher rule
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m19s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 14:48:01 +00:00
Void
a8fc78ff55 docs: Files desk upload flow (approved for members and Minds), codes and caps as placeholders
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 14:31:47 +00:00
Void
88fd0a889a docs: Commons and per-Persona Files desk, design only
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 14:30:46 +00:00
8ba407cd2a Merge pull request 'Phone hit: repo-wide guard for bare IconButtons, PhoneHitInPlace for preview arrows, drop dead Editor.preview' (#141) from void/phone-hit-guard into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m39s
2026-11-13 13:51:43 +00:00
Void
d5a0c1b4ff Phone hit: a repo-wide guard for bare IconButtons, PhoneHitInPlace for the preview arrows, drop the dead Editor.preview
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m22s
phoneHit.coverage.test.ts walks every .tsx under src/app and fails on any IconButton without a PhoneHit class
unless it is named with its reason (EstateNavigator Find a room, LobbyHeader Members). UrlPreviewCard's two
absolute arrows take PhoneHitInPlace, which adds the hit area without PhoneHit's position: relative.
Editor.preview.tsx was imported nowhere and held 11 bare IconButtons.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 13:46:44 +00:00
ad9172a311 Merge pull request 'Phone hit: page back buttons (group 3)' (#133) from void/phone-hit-pages into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 4m11s
2026-11-13 13:43:43 +00:00
4e6b4f0c90 Merge branch 'dev' into void/phone-hit-pages
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m12s
2026-11-13 13:34:34 +00:00
1a3eedf6cb Merge pull request 'Phone hit: editor toolbar, emoji sidebar, upload cards, client root' (#139) from void/phone-hit-editor into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 4m43s
2026-11-13 13:34:32 +00:00
9153ee945d Merge branch 'dev' into void/phone-hit-editor
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m57s
2026-11-13 13:26:44 +00:00
d5ad73fa5e Merge pull request 'Phone hit: message content and data editors (group 10)' (#138) from void/phone-hit-content into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m43s
2026-11-13 13:26:43 +00:00
4c16e51559 Merge branch 'dev' into void/phone-hit-content
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m11s
2026-11-13 12:58:51 +00:00
f0c8dc2122 Merge pull request 'Phone hit: room/space settings, lobby, message search, explore (group 7)' (#137) from void/phone-hit-room-space into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m12s
2026-11-13 12:58:50 +00:00
d6a6e300a4 Merge pull request 'Phone hit: settings B, auth and verification icon buttons' (#136) from void/phone-hit-settings-b into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m40s
2026-11-13 12:49:59 +00:00
91993ace99 Merge branch 'dev' into void/phone-hit-room-space
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m14s
2026-11-13 12:49:59 +00:00
145e268894 Merge branch 'dev' into void/phone-hit-settings-b
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m50s
2026-11-13 12:42:11 +00:00
8d25db2775 Merge pull request 'Phone hit: viewer headers and UIA stages (group 9)' (#135) from void/phone-hit-viewers into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m13s
2026-11-13 12:42:10 +00:00
6c395d7aef Merge branch 'dev' into void/phone-hit-viewers
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m10s
2026-11-13 12:11:44 +00:00
a7ac67683f Merge pull request 'Phone hit: common-settings IconButtons (group 6)' (#134) from void/phone-hit-common-settings into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m58s
2026-11-13 12:11:43 +00:00
8a52fa9353 Merge branch 'dev' into void/phone-hit-common-settings
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m46s
2026-11-13 10:16:51 +00:00
32b95fb60b Merge pull request 'Phone hit: dialogs and prompts (group 8)' (#132) from void/phone-hit-dialogs into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m34s
2026-11-13 10:16:50 +00:00
Void
ff1a29dbec Merge dev into phone-hit-pages (kit: dev's AST reader already accepts null entries)
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m23s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 10:15:31 +00:00
2c39f89fe4 Merge branch 'dev' into void/phone-hit-dialogs
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m5s
2026-11-13 09:31:02 +00:00
fd2626d366 Merge pull request 'Phone hit: settings A icon buttons (group 4)' (#131) from void/phone-hit-settings-a into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 4m37s
2026-11-13 09:31:00 +00:00
09e85fad02 Merge branch 'dev' into void/phone-hit-settings-a
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m5s
2026-11-13 09:05:41 +00:00
b2a970f987 Merge pull request 'Phone hit: call controls (audit group 1)' (#130) from void/phone-hit-call into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m7s
2026-11-13 09:05:39 +00:00
45939d544b Merge branch 'dev' into void/phone-hit-call
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m23s
2026-11-13 08:28:38 +00:00
0f7faa902c Merge pull request 'Phone hit kit: pin the className expression, not its source text' (#140) from void/phone-hit-kit-strict into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 4m48s
2026-11-13 08:28:35 +00:00
Void
4eaa6f9c55 Phone hit kit: read IconButton className off the TypeScript AST
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m53s
className must appear once, with no spread after it, as the imported PhoneHit*
identifier bare, a classNames/clsx/cx direct argument, or a template span, and
the identifier must occur nowhere else in the expression. Tag enumeration uses
the same AST. expectPhoneHitClasses takes (string|null)[] (null = no class), as
the phone-hit-pages branch does, and is exercised by a test on a temp source.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 07:28:37 +00:00
Void
761d13fac5 Phone hit editor tests: pin estate Targets nesting and selector, ClientRoot inline absolute, sidebar gap
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m33s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 07:21:57 +00:00
Void
d13cbc9b2e Phone hit kit: read the className expression, not its source text
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
A PhoneHit name inside a string, built by concatenation, behind ?:/&&/||/??, or
followed by a props spread that can override className no longer satisfies the pin.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 07:21:00 +00:00
Void
da05210db2 Phone hit: editor toolbar, emoji sidebar, upload cards, client root
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 07:16:46 +00:00
Void
a0d047c139 Phone hit: message content and data editor icon buttons
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m30s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 07:16:41 +00:00
Void
84ee800e3f Phone hit: room/space settings, lobby, message search, explore icon buttons
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m25s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 07:16:31 +00:00
Void
32dc46c21f Phone hit: PhoneHit on the settings B, auth and verification icon buttons
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m44s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 07:16:11 +00:00
Void
200cf8fdb8 Phone hit: viewer headers and UIA stages
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m58s
Back/close buttons beside non-tappable titles take PhoneHit; the zoom out/in
buttons beside the zoom Chip take PhoneHitSpread24. Test pins each variant and
ties the sized ones to the drawn size.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 07:16:07 +00:00
Void
e209688de1 Phone hit: common-settings IconButtons get PhoneHit, with a pinning test
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m31s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 07:16:02 +00:00
Void
cd90a044ed Phone hit: page back buttons and Lobby/Notifications lone buttons
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m59s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 07:16:02 +00:00
Void
0b40f4c66f Phone hit: PhoneHit on the ten dialog and prompt close buttons, with a pinning test
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 5m26s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 07:15:44 +00:00
Void
b8bef8c175 Phone hit: settings A icon buttons get PhoneHit, with a pinning test
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m32s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 07:15:25 +00:00
Void
351d1bc745 Phone hit: call controls get their hit-area variants, with a test pinning them
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m31s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 07:15:10 +00:00
54ac1ba480 Merge pull request 'Phone hit: Spread28/36, Room36, shared test kit and size-tie check' (#129) from void/phone-hit-foundation into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m56s
2026-11-13 07:13:33 +00:00
Void
fe12d8a4b1 Phone hit kit: pin Room composition, spread props are undetermined, tighter tag match
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m4s
Room<N> throws when no Spread of its size exists, and a test reads the compiled class lists to prove Room<N>
composes Spread<N> and PhoneHit. Props spread into an IconButton or Icon make the size undetermined (allow-list
entry required). <IconButton and <Icon match only before whitespace, > or /. iconButtonTags derives from iconButtons.
expectSizeTie fails on a file with no IconButton. Fixture tests live in phoneHitTestKit.test.ts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 07:05:58 +00:00
b77efddcdc Merge pull request 'buildSha: an explicit BUILD_SHA no longer masks a dirty tree; temp-file exclusion is untracked-only' (#128) from void/build-sha-untracked-filter into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 4m39s
2026-11-13 07:02:44 +00:00
Void
d917ccd3bb Phone hit tests: shared kit, size tie, pinned new variants
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 2m11s
The helpers moved to phoneHitTestKit.ts so each later group adds its own phoneHit.<group>.test.ts. A new
check ties PhoneHitSpread<N>/Room<N> to the px the button draws (IconButton size padding + Icon size); a size the
source does not state needs an explicit allow-list entry. It found RoomInput's reply-cancel (16 px icon, 24 px
button) carrying Spread32; it is Spread24 now. Room<N> takes its inline margin from the Spread class of the same
size, so the two axes cannot disagree.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 06:59:50 +00:00
Void
2b019a4302 Phone hit: Spread28, Spread36 and Room36 variants
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 06:58:48 +00:00
Void
eff894a89c docs: BUILD_SHA also stands where git cannot be read
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m39s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 06:57:45 +00:00
Void
c82193f0fb buildSha: git speaks only for a tree it roots, mismatch and git failure fail closed, temp-file name matched exactly
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Soul found: explicit sha stamped clean over a different HEAD; status failure returned the bare explicit
sha; an archive inside another repo got that repo's verdict; the temp regex let any untracked .mjs pass.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 06:56:27 +00:00
Void
c45cdc7bd7 buildSha: BUILD_SHA no longer masks a dirty tree; the vite temp-file exclusion is untracked-only
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m24s
The pathspec exclude hid a tracked file of that name; the status lines are filtered instead.
Tests against a real repo: explicit sha plus stray file, stray file beside the temp file in root and
subfolder, tracked file of the temp name, new folder. Six mutants of the logic each fail a test.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 06:52:32 +00:00
14ee4bee03 Merge pull request 'Phone: 44 px hit areas for the chat path's remaining icon buttons, and tests that pin them' (#127) from void/phone-hit-areas-2 into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m38s
2026-11-13 05:50:20 +00:00
Void
0c8474231e phoneTapTargets: each Spread class owns its margin, ::after declaration set is exact, no phone rule moves position, import must not be aliased
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m1s
Soul re-gate of 446306b1: swapped Spread24/26 definitions, display:none or overflow on the ::after, position:static on a
Spread rule and an aliased import all passed; all killed now.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 05:50:10 +00:00
Void
446306b1e7 PhoneHit: Spread24 for the nav row's 24 px buttons, Spread26 for the unpin button; tests pin position, ::after declarations, className and import alias
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Soul pass on fc92809e: RoomNavItem's buttons are 24 px, not 32 (36 px pitch, hit areas overlapped); the unpin button is 26 px
beside the Open chip. Six mutants survived (position: relative, pointer-events, z-index, title for className, aliased
import); all now killed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 05:46:21 +00:00
Void
fc92809eb9 Phone: 44 px hit areas for the chat path's remaining icon buttons; pin variant, import and ::after content
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
MessageEditor, RoomNavItem, MembersDrawer, ReactionViewer, RoomPinMenu, RoomViewTyping, CallChatView and JumpToTime
get PhoneHit (alone) or PhoneHitSpread32 (two neighbours in a row). phoneTapTargets.test.ts now lists them, plus
PasswordInput, Desk, SkyStateControl and PasswordLoginForm, which had no test, checks each class is imported from
styles/PhoneHit.css, and pins the ::after content (a mutant without it passed before).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 05:40:21 +00:00
2aa468c36a Merge pull request 'Consumer-side tests for #123: RoomOutbox as rendered; hung send to watchdog reload to resend' (#124) from void/stall-consumer-tests into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m18s
2026-11-13 04:11:32 +00:00
67f1267653 Merge pull request 'Phone: 44 px hit areas for icon buttons, reaction chips and short sender names' (#125) from void/phone-hit-areas into dev
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
2026-11-13 04:11:26 +00:00
Void
ae3760fcc7 RoomOutbox actions test: Resend keeps the entry in the outbox, pending again
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m14s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 04:11:15 +00:00
Void
bd2d980023 phoneTapTargets: pin top, left and transform of the hit-area box
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 4m32s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 04:10:46 +00:00
Void
da9ef70c03 Consumer tests: startClient wiring, Resend/Discard handlers, the 30 s slow-send threshold
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 04:04:45 +00:00
Void
0e3115809e phoneTapTargets: pin the exact PhoneHit variant of each IconButton
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 04:02:30 +00:00
Void
e04c7c074f stallRecovery test: a held SDK echo makes the resend use a fresh txn id
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 04:01:36 +00:00
Void
fab6a04894 stallRecovery test: lint clean
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 04:01:36 +00:00
Void
09b062d7be stallRecovery test: distinct txn ids per send; pin visible/online guards and own-tab pending filter; fix TS2698
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 04:01:36 +00:00
Void
9d1d39922c stallRecovery test: lint clean 2026-11-13 04:01:36 +00:00
Void
76c1f56bd8 stallRecovery test: lint 2026-11-13 04:01:36 +00:00
Void
2a1f2c6b17 Consumer-side tests: RoomOutbox as rendered; hung send to watchdog reload to resend
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 04:01:36 +00:00
Void
21ff167177 phoneTapTargets: every IconButton in Message, RoomInput, RoomViewHeader carries a PhoneHit class
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 04:01:35 +00:00
Void
ee55c32214 Phone: quick-reaction emoji buttons and delete/report dialog close buttons get a 44 px hit area
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 04:01:35 +00:00
Void
856096e215 Desk back button: phone hit area
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 04:01:35 +00:00
Void
f7395f12e3 Phone: icon buttons, reaction chips and short sender names get a 44 px hit area
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 04:01:35 +00:00
95f79a0517 Merge pull request 'Build stamps its git sha into index.html (build-sha meta tag)' (#126) from void/build-sha-stamp into dev
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
2026-11-13 04:01:23 +00:00
Void
917f9a0da2 buildSha test: remove the temp repos after each test
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m54s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 03:48:22 +00:00
Void
46e96500e4 buildSha: ignore vite's temp config file, run git in the repo dir
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 03:20:59 +00:00
Void
ccb7a8ebb6 Build stamps its git sha into index.html as a build-sha meta tag
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m52s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 01:40:05 +00:00
b6b1d522ab Merge pull request 'client: unconfirmed sends are visible and recovered; watchdog for a dead connection' (#123) from void/resume-reload into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m43s
2026-11-12 21:35:47 +00:00
Void
bb6391a70b initMatrix: resolve sessionStorage inside the guard's try; ownPendingAges tested
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m39s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 21:35:46 +00:00
Void
69d752ff0b watchdog: send stall only, own-page entries, online only; resume sync nudges and never restarts
Soul pass on 77edebff: the watchdog no longer counts interrupted entries from
a previous page (reload loop at startup), no longer reloads on sync ERROR/STOPPED
(js-sdk recovers offline by itself) or while offline, refuses instead of
throwing when sessionStorage is unusable, startClient is idempotent, and the
slow-send label says Resend may duplicate. resumeSync drops its health check
and recover hook: nudge only.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 21:34:21 +00:00
Void
77edebff9c client: watchdog, resend on reload, outbox for every send, no in-place client restart
Sends have no timeout and sync polls do, so a dead connection leaves a send
SENDING forever with no request reaching the server while its echo looked
delivered. A watchdog (send pending past 20 s, sync ERROR/STOPPED for 30 s)
calls a guarded reload; what the reload interrupts is sent again under its
own txn id. Uploads and stickers go through the outbox. Resend takes a fresh
txn id while the SDK still holds the failed echo. The resume-sync recovery no
longer calls stopClient/startClient, which closes the rust crypto for good
("null pointer passed to rust" on later encrypted sends).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 21:31:29 +00:00
Void
a92f6c4294 timeline: hide unconfirmed local echoes; the outbox is the one place they show
The SDK puts a local echo in the live timeline on sendMessage and marks it
NOT_SENT on failure; the timeline rendered it like any delivered message and a
reload dropped it, so a send killed with the page looked sent and vanished.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 21:25:50 +00:00
92a98664c9 Merge pull request 'composer: persist the draft on input, keep unconfirmed sends in a durable outbox' (#122) from void/draft-persist into dev
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
2026-11-12 21:17:30 +00:00
Void
a531976675 lint: import order, explicit no-op test stubs
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m9s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 21:17:26 +00:00
Void
350ec987e0 outbox: survive a refused storage write, mark reload-interrupted sends, hide Resend on live sends
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Soul pass findings: a failed localStorage write no longer loses the entry
(memory copy wins until a write succeeds), a stale draft is dropped when
its rewrite fails, storage reads/removes cannot throw, and pending entries
older than the page load read as interrupted with Resend available.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 21:17:06 +00:00
Void
7316c92ff3 composer: persist the draft on input, keep unconfirmed sends in a durable outbox
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
The draft lived in a memory-only jotai atom written only when RoomInput
unmounted, so a reload lost it. A sent message was cleared from the editor
at once and held nowhere durable. The draft is now written to localStorage
(debounced, flushed on pagehide/hidden) and restored on load; a send stays
in a per-account outbox under its txn id until the server confirms, shown
above the composer with Resend and Discard.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 21:14:16 +00:00
a8d39ee917 Merge pull request 'pwa: installable manifest and Web Push stages 0-1 (dark by default)' (#121) from void/pwa-push-stage-0-1 into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m46s
2026-11-12 20:05:41 +00:00
Void
695a016d4f push: keep the token only while subscribed; toggle reads the account's pusher; replace a stale VAPID subscription
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m14s
Soul pass findings on the stage 0-1 branch: the worker stored the token on every deployment, push configured or not
(now only while the browser holds a push subscription; the page re-sends its session after the toggle changes it);
the toggle read the browser's subscription, not the account's pusher (now both); a subscription under an old VAPID
key was reused (now replaced); a failing client list now still shows the notification.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 20:05:10 +00:00
Void
64a2656ad7 pwa: installable manifest fixes and Web Push stage 0-1 (worker handlers, session in IndexedDB, settings toggle, dark config block)
Stage 0: manifest gains id "/" (what Chrome already derives from start_url), scope, a 512 maskable
icon, and drops the portrait lock. The service worker keeps the session ({baseUrl, accessToken}) in
IndexedDB `ratatoskr-sw` so a push can wake a worker with no tab; the page's existing logout message
deletes it.

Stage 1: `push` and `notificationclick` handlers (src/app/features/push), a pusher toggle in
notification settings, `push` block in config.json shipped empty (off). Tested against a mock
homeserver and Matrix gateway body.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 19:58:40 +00:00
f79613ca5f Merge pull request 'docs: chat shell compression, measured state and brotli plan' (#120) from void/chat-shell-compression into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m44s
2026-11-12 18:16:04 +00:00
Void
74fc2fbcd4 docs: fix build id, SW claim, step order, twin size after Soul pass
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m48s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 18:15:59 +00:00
Void
9297ba08dd docs: chat shell compression, measured state and brotli plan
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 18:09:47 +00:00
3d8c98e1c8 Merge pull request 'runbook: handoff build ships the repo config.json; live check always runs' (#119) from void/runbook-config-flow into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m33s
2026-11-12 17:08:05 +00:00
Void
3543b1013b runbook: sha256sum --ignore-missing hides nothing; name the config compare
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m26s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 17:07:54 +00:00
Void
45579b8ec8 runbook: the handoff build ships the repo's config.json and its live check always runs
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 16:54:58 +00:00
5cce38f38b Merge pull request 'docs: client build, install, verify and rollback runbook' (#118) from void/client-config-runbook into dev
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
2026-11-12 16:51:49 +00:00
Void
45facff436 runbook: handoff build ships its own pinned config; drift check is not a pass check
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m36s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 16:51:41 +00:00
Void
fef7d34fdb runbook: record the served-config drift as observed
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 16:50:28 +00:00
Void
3751adcb64 docs: Ratatoskr client build, install, verify and rollback runbook
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 16:50:16 +00:00
02a0c10665 Merge pull request 'Phone and desk visual findings: notice scrim, tap areas stop at neighbours, desk affordance' (#117) from void/phone-desk-visual-fixes into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 6m5s
2026-11-12 14:31:17 +00:00
Void
96954c0fb5 Desk: fold chevron, quiet text 0.9, solid note border, recorded rulings on their own ground
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m58s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 14:28:34 +00:00
Void
d4463a80cf Phone and desk visual findings: notice line owns its ground, tap hit areas stop at their neighbours, nav rows as tall as their targets
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 14:19:25 +00:00
494d2a7ed4 File zone share: component tests, state machine moved out of ShareSet (#116)
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
2026-11-12 13:15:49 +00:00
c5d1b9c90f File zone: share a set of files as one album (flag off) (#115)
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
2026-11-12 13:01:46 +00:00
f9f94808d5 An explicit theme choice (even Midnight Sky) wins over the sky (#114)
Some checks failed
Rat dev preview / Build dev preview (push) Has been cancelled
2026-11-12 11:41:43 +00:00
08bf515997 Merge pull request 'Release candidate: dev into main' (#88) from dev into main 2026-11-11 02:13:08 +00:00
683d3b92f8 Merge pull request 'Release candidate: dev 64edacac to main' (#71) from release/dev-64edacac into main 2026-11-10 17:42:15 +00:00
348 changed files with 17524 additions and 7745 deletions

View file

@ -18,10 +18,14 @@ jobs:
- name: Setup node - name: Setup node
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with: with:
node-version-file: ".node-version" node-version-file: '.node-version'
package-manager-cache: false package-manager-cache: false
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm ci
- name: Ridge asset gate
run: |
npx vitest run src/app/features/scene/ridge/ridgeAssets.test.ts
echo "ridge assets: $(find public/ridge -type f | wc -l) files, $(du -sb public/ridge | cut -f1) bytes"
- name: Build app - name: Build app
env: env:
NODE_OPTIONS: '--max_old_space_size=4096' NODE_OPTIONS: '--max_old_space_size=4096'

21
THIRD_PARTY_NOTICES.md Normal file
View file

@ -0,0 +1,21 @@
# Third-party notices
## d3-celestial (constellation lines)
The constellation line chains in `src/app/features/scene/ridge/nightSkyData.ts` are derived from
`data/constellations.lines.json` of d3-celestial, https://github.com/ofrohn/d3-celestial,
under the licence below.
```
Copyright (c) 2015, Olaf Frohn
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.```

View file

@ -25,6 +25,14 @@
"dings": { "dings": {
"enabled": false "enabled": false
}, },
"fileZoneShare": {
"enabled": true
},
"push": {
"vapidPublicKey": "",
"gatewayUrl": "",
"appId": ""
},
"registration": { "registration": {
"enabled": false, "enabled": false,
"url": "" "url": ""

View file

@ -0,0 +1,34 @@
schema = "gamecult.idunn.target_declaration.v1"
target = "ratatoskr"
# Idunn stamps the source commit into the build environment under this name. The release is not built from source: the
# dist tarball below is built by scripts the release owner runs (build-prod-dist.sh) and enters pinned by sha256, so
# each release is a recipe commit whose pin is its provenance. The stamp the served index carries is the commit the
# tarball was built from, which is not this commit.
source_stamp_environment = "RATATOSKR_BUILD_COMMIT"
# Release dist f562f8fae9a294e04354801538ed7a595133f480: the output of build-prod-dist.sh (live config check passed), packed
# as dist/ at the top of one gzip tar. The tree carries the repo's own config.json; what is served is the operator's
# carried file, which Idunn copies beside dist/ and the vhost aliases over the tree's (a vhost without that alias would
# serve the repo config).
[[external_inputs]]
id = "dist-tarball"
url = "https://eureka.gamecult.org/forge/GameCult/Ratatoskr/releases/download/dist-f562f8fa/ratatoskr-f562f8fa-dist.tar.gz"
sha256 = "ec4f4fc3e64dfeb7ba6509b386d2a5efc318211f66de663c061e1240b1f610f0"
runner = "unpack"
destination = "release/dist.tar.gz"
[[steps]]
id = "unpack-dist"
phase = "prepare"
runner = "unpack"
argv = ["tar", "-xzf", "release/dist.tar.gz", "-C", "release"]
[[artifacts]]
id = "dist"
source_kind = "runner-output"
runner = "unpack"
source = "release/dist"
destination = "dist"
[static_release]
artifact = "dist"

291
docs/commons-files-desk.md Normal file
View file

@ -0,0 +1,291 @@
# Files desk: Commons and per-Persona file zones, two designs compared
Status: **decided: Option A, Matrix as the single authority** (Meta, #swarm 2026-11-13 14:44Z: "Let's try matrix shaped"). Design only; no Files desk code is merged and nothing is deployed. Option B (the host service) is parked, not deleted: Eureka's branch `eureka-self/commons-host` at `a391960d` has no PR and a Soul verdict of NOT READY with fixes owed, and is woken only if Meta later wants a real file store. PR #143 (B's cut 1 in this repo) is closed unmerged. Items marked **UNKNOWN** are not verified; **Q-E** are questions for Eureka, **Q-M** for Meta.
### Eureka's answers (`/opt/commons/handoff/commons-matrix-notes-20261113.md`, read 2026-11-13; final answers folded in 2026-11-13)
- **Upload cap (Q-E1, read).** Synapse 1.164.1; the repo template `homeserver.yaml` has `max_upload_size: 50M` and the nginx vhost `client_max_body_size 50m`; the live runtime file is root-only and was not read. No per-room or per-user per-file cap exists; `media_upload_limits` is a per-user time-window quota. `GET /_matrix/client/v1/media/config` returns `m.upload.size` to an authenticated client, which is what the client reads. Raising the cap takes the config line, a Synapse restart and nginx at least as large.
- **Posting (Q-E1, read).** A Self holds no Matrix credentials, so the publisher needs its own bot account and token (a MAS compatibility token via `mas-cli`). It uploads with `POST /_matrix/media/v3/upload` and sends `m.room.message` with `msgtype` `m.file` or `m.image`. The Persona mouth sends `m.text` only today, so file events are new for it too.
- **Room (Q-E3, answered).** The Commons room is `#commons:gamecult.org` (create type `org.gamecult.file_zone`, unencrypted, membership by the estate Space, publisher bot at power level 50). Provisioning and push muting are Eureka's.
- **Cap (Q-E1, answered).** 50 MiB per file. The client reads it live from `m.upload.size`, not from this document.
- **Poster (Q-E1, answered).** The publisher posts as the owning Mind: each file appears under the Mind whose tree it came from, not under a generic bot.
- **Final marker (Q-E2, answered).** A handoff document is final when a sibling `NAME.final` holds its sha256; the publisher watches for that, posts once, and carries `org.gamecult.publish.replaces` (prior event id and sha256) on a later final version.
- **Range (Q-E4, unverified).** Whether Synapse media honours `Range` has not been checked against a live mxc. Playback therefore stays on the blob download until it is.
- **Edited-doc stale copies:** a redacted file's media persists unless purged; the publisher dedupes by sha256.
Source: Meta, #swarm 2026-11-13 14:28Z and 14:40Z; ruling `ratatoskr:ruling:persona-file-sharing-zone` (a browsable, previewing collection per Persona; the Self writes to her outbox, her Persona decides what is shared, the Self never holds Matrix credentials).
## What exists on Matrix today (the base A must fit)
Read from this repo at dev `8ba407cd`:
- **Zone = a room** whose `m.room.create` type is `org.gamecult.file_zone` (`isFileZone.ts`), or one listed in config `fileZoneRooms`. One per Mind, `#<mind>-files:<server>`, found by alias or by the carried id in the root Space's `org.gamecult.stewardships` (`mediaRoom.ts`, `MediaRow.tsx`); rendered as the Media row of each Mind's group.
- **Album = a thread root** (a text event; its `body`, or its latest `m.replace` edit, is the title); **file = a thread reply** with `msgtype` `m.audio|m.image|m.video|m.file` (`buildAlbums.ts`). A redacted event or an `m.replace` is never a file. Loose room messages are not shown.
- **Read** = `GET /rooms/{id}/threads` and `/relations/{root}/m.thread`, every page, 100 per request, at most 20 pages per endpoint (`useAlbums.ts`, `readPages.ts`; a capped read shows a note in the list). Unencrypted rooms only.
- **Write** = `sendShareSet` (`shareSet.ts`, behind `fileZoneShare.enabled`): a root, then one thread reply per file, content from `getMsgContent` with `info.sha256`.
- **Media** = authenticated Matrix media fetched to a blob (`downloadMedia` in `FileContent.tsx`): so the "media element cannot send a header" problem that Option B needed a ticket for is already solved this way, at the cost that a file is fully downloaded before it plays.
- **Receipts** = `org.gamecult.file_received` from a Mind's mouth after it fetches and verifies the sha256 (`docs/file-zone-mind-contract.md`); the mouth enforces the Mind's membership in the room.
Option A is an extension of this, not a second system.
## The two options
**A. Matrix is the only authority.** Commons is one more file-zone room; each Mind's zone is the room she already has. Audience is room membership. Upload is the ordinary Matrix upload. Folders are albums (thread roots). A small publisher service with its own Matrix account posts allowlisted handoff documents into the Commons room. The Files desk is a view over file events in those rooms.
**B. The host service.** A file host on Yggdrasil serves allowlisted directories (`GET /index`, `GET /file`, a capped `PUT`), authenticated by Matrix OpenID; the client browses it as a tree. Written out in full below the line.
| | A: Matrix only | B: host service |
| -------------------------- | ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------- |
| Authorities | one (Matrix: identity, audience, storage, audit) | two (Matrix for identity, the host for files and access) |
| Audience | room membership and power levels | the host derives a role from Matrix identity and enforces it again |
| Audit of writes | the event `sender`, kept by the homeserver | the host's own log |
| Overwriting someone's file | impossible: events are immutable and only the sender's own edit counts; a redaction is a steward's act | host rule, host code |
| Upload size cap | the homeserver's `m.upload.size`, global, 50 MiB (Eureka) | the host's own, chosen freely |
| Type allowlist | not enforceable by the homeserver; client-side courtesy, steward redaction | enforced by the host (sniffed) |
| What is browsable | what was posted (published or uploaded) | what is on disk under the allowlist, live |
| Mind-written handoff docs | a publisher posts them once, when final (below) | the host serves the tree |
| Per-Persona zone | the existing Media room; the Self's outbox reaches it through the mouth, as the ruling says | a `shared/` directory the host serves |
| Folders | albums; nesting by path in the album title | real directories |
| Mind fetch | unchanged (mouth, room id and event id, receipts) | a second route the mouth would need |
| Media playback | blob download, as today; no seeking before the whole file arrives | ranges and a ticket, or the same blob |
| New moving parts | a room, a publisher | a host service, OpenID verification, CORS, tickets, path containment, rate limits |
## Recommendation: A (decided)
Confidence: high on the authority question (it agrees with Meta's ruling, with Eureka's lean, with the standing ruling that the Self never holds credentials while her Persona decides what is shared, and with the fact that everything built so far reads Matrix); moderate on the details below, which Eureka's answers can change.
What A gives up, stated plainly:
- **A live view of what is on disk.** Only what was published or uploaded appears. A handoff doc that was never marked final is not in the Commons.
- **Files over the homeserver's upload cap.** B had no Matrix limit; A has exactly one.
- **A server-side type allowlist.** Under A a member can upload any type the homeserver accepts; the client shows a refusal for types it does not want, and stewards redact. If a strict allowlist matters, a gating bot (post, check, redact) would have to exist, and it is a second authority again.
- **Seeking inside a large audio or video file** until Matrix media supports ranges for the client (**UNKNOWN**; the blob route is what runs today).
- **Hierarchy beyond the album level** as a native structure; see Folders.
What it buys: one identity, one audience, one audit trail, immutable files, existing receipts and the mouth's fetch, and no new service to keep secure.
## Option A in detail
**Rooms.** Commons is a room with create type `org.gamecult.file_zone`, alias `#commons:gamecult.org`, join rule `restricted` to the estate Space so members join without an invite and Minds are invited, history `shared`, unencrypted (the zones are, and `info.sha256` is written only there). Power levels: `events_default` 0 so members post; `redact` and `state_default` at steward level. The room is muted for push by provisioning: file posts are thread replies, which can raise unread counts and notifications (**UNKNOWN** under this server's push rules), so the room must not shout. Per-Persona zones are the rooms Eureka already provisions; nothing new.
**Folders.** Four ways to have folders on Matrix, in order of preference:
1. _Albums are folders; nesting is a path in the album title_ (`handoff/2026-11`, `cast-art/poses`). Zero wire change: `buildAlbums` already reads it, and the client groups albums by title path as a pure view. Cost: a thread root per folder, and the rule that a folder's root is posted once by whoever opens the folder. **Recommended.**
2. A `org.gamecult.file.path` key on each file event. Gives a real tree with files anywhere; needs every poster to write it and every client to honour it; other Matrix clients ignore it and show a flat thread.
3. A room per folder, in a Space. Native hierarchy and per-folder audience; heavy (a room is a membership, a sync entry and provisioning each) and it multiplies the sync load on a phone.
4. A state event per folder (`org.gamecult.file_folder`). Mutable folder metadata (title, order), writable only at steward level; useful later if folders need descriptions, not needed for a first cut.
**Albums in each Mind's room** are the same mechanism: a Mind's Media room holds that Mind's albums, the Commons holds the shared ones. The Files desk is the same view over either room; a zone differs only by room, not by code.
**The publisher.** A small service on Yggdrasil with its own Matrix account (a bot account that posts as the owning Mind, per Eureka's answer above). The Self never holds this account; the publisher holds it. It owns the allowlist.
- **When it posts.** Handoff documents are edited in place, so mirroring every save would spam the room with drafts. The rule (Eureka's lean, adopted): **post once, when the document is marked final**; a later final version posts again with a `replaces` relation to the earlier event. "Final" is a sibling `NAME.final` holding the document's sha256 (answered Q-E2); the client must not know.
- **Allowlist.** Lives on the publisher: a list of source roots and patterns, read by the publisher only. `handoff-private` is not on it and the publisher never lists, reads or posts from it. The client holds no path to anything on disk.
- **The event.** A file event in the thread of the folder's album, built the way `getMsgContent` builds them (`msgtype`, `body`, `filename`, `url` from the media repo, `info.mimetype|size|sha256`), plus one extra key `org.gamecult.publish`: `{ source, sha256, replaces? }` where `source` is a path relative to the allowlisted root, never absolute, and `replaces` is the event id of the version it supersedes.
- **`replaces`, not `m.replace`.** `m.replace` is the stock edit relation, but Ratatoskr's `buildAlbums` deliberately never treats an edit as a file, several clients do not render an edited file, and an edit hides the earlier version. A custom key keeps both events as files; the view shows the latest of a chain and a "N earlier versions" row under it, and other Matrix clients see two ordinary file posts. A chain is read from the events themselves (each carries its `replaces`), not from a table, and a `replaces` counts only when its event has the same sender as the event it names, so nobody else in the thread can fold a file away.
- **Idempotence.** The publisher's own state (a typed CultCache document of `source`, `sha256`, `event_id`) says what it posted; if that is lost, it rebuilds by reading its own events back from the room (`org.gamecult.publish.source` plus `sha256`) rather than guessing. The same `sha256` never posts twice.
- **Receipts and fetch** work unchanged: the event is an ordinary file event in a file-zone room, so a Mind's mouth can fetch it by room id and event id (5 MiB cap there) and tick `fetched for`.
**Uploads (approved for members and Minds).** The ordinary Matrix upload, through the composer pipeline and `ShareSet`. The host rules Eureka gave map onto Matrix as follows:
| Host rule | Under A |
| ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
| only under an `uploads/` subtree | an album (folder) named `uploads/...`; the client offers upload only there (and in a Mind's own zone) |
| never overwrite Mind-written handoff files | free: other people's events cannot be replaced; a duplicate name is just another post in the thread |
| size cap | the homeserver's `m.upload.size`, shown from `MediaConfigLoader`; the client refuses a larger file before sending |
| type allowlist | client-side only; see "gives up" |
| explicit flag to overwrite | no overwrite exists; a new version is a new post, optionally with `replaces` set by the same sender |
| audit log with the Matrix id | the event `sender` |
What A adds to `ShareSet`: sharing into an existing album ("add files", listed as not built in `docs/file-zone.md`), progress per file, cancel, and per-error refusal messages written against the SDK's `MatrixError` (`M_TOO_LARGE`, `M_FORBIDDEN`, `M_LIMIT_EXCEEDED`) instead of host codes. The draft refusal table of Option B's upload flow carries over with those codes. **UNKNOWN:** whether the SDK exposes upload progress and abort for media (it does for `uploadContent` with a progress callback; the composer already shows progress, `state/upload.ts`).
## What each costs on the phone
Under both, the phone design is the same shape (one column, rows 56 px or more, hidden controls, in-place preview; see the Option B sections below, which are written against the host but whose layout applies).
- **A, new cost:** the Commons room is one more room in sync and it must be muted; albums and files are read to a cap of 20 pages of 100 per endpoint (a Commons past that shows a truncation note); a folder tree is a title-path grouping, so a deep tree is a long list of albums with breadcrumbs, not true directories; a file plays after a full download (small audio and images are fine; a 40 MB clip is not).
- **A, no cost:** no second sign-in, no ticket, no CORS, no new fetch layer, no host-unreachable state beyond the homeserver's own. The album list, album view, share panel and receipts exist and are tested; the view is their extension.
- **B, new cost:** every screen is a second client against a second service with its own errors, token refresh and unreachable state; media needs the ticket or the blob; the tree and preview are new UI.
- **B, benefit:** a tree that is live and complete, ranges, and no Matrix size limit.
## Changes to Eureka's host work
Under A the paused service is not built, and most of its list disappears:
- **Dropped:** `/index`, `/file`, `PUT`, OpenID verification pinned to the server name, CORS, path containment and sniff rules, tickets, the `uploads/` write rules, the role response, the per-path audit log (Q-E3, Q-E4, Q-E6, Q-E7, Q-E8 to Q-E11 of the Option B list).
- **Kept:** the Commons allowlist decision (Q-E1 of that list), moved to the publisher: which roots, and that `handoff` is only ever published through the final-marker rule, never browsed.
- **New:** (1) provision the Commons room (type, alias, restricted join to the estate Space, power levels, push muted); (2) the publisher: account, allowlist, final-marker rule, media upload, posting into folder threads, the `org.gamecult.publish` key, idempotence from its own events; (3) confirm the homeserver upload cap and whether the account may post file events from Yggdrasil (**Q-E1**, asked on the PR); (4) the per-Persona path stays the one already specified (`album-outbox-ops`: outbox, Persona decision, mouth post), so the `shared/` convention of Option B is retired.
## Cuts under A
Status 2026-11-14 (dev da822e9e plus the size-refusal cut): built: folders by album title path with navigation and breadcrumb (#147), pagination (#148), version folding (#149), add-to-album with named refusals (#150), Stop for a send in flight, replaces loops shown, freshest last event on add (#151), and the pre-send size refusal: a file larger than the server's `m.upload.size` is named and left unsent before any upload or album root, and a server stating no cap refuses nothing. The Commons entry row is built (item 1): `useCommons` in `MediaRow.tsx` finds the room by the alias `#commons:<server>` (provisioning records no id for it), through `lookupZoneRoom` (the one lookup `lookupMediaRoom` also uses); `EstateNavigator` shows it above the tiers as a Commons link when joined, a join row when invited or not joined, and nothing when the room is absent, the lookup failed or is out. It is gated on the existing `fileZoneShare.enabled`, not a new `filesDesk.enabled` flag. The album view and ShareSet work there because provisioning creates the Commons with the `org.gamecult.file_zone` create type. Members can share only once the room's power levels let them post: provisioning gives the poster level to the Minds alone.
1. **Commons entry**: a Commons row in the navigator (like `MediaRow`, found by alias), opening the room's album view. Flagged, no new data layer.
2. **Pagination** of albums and files in `useAlbums` (done, PR #148).
3. **Folders by title path** and the album list grouped by it.
4. **Versions**: read `org.gamecult.publish.replaces`, show the latest of a chain with the earlier versions folded under it (done, PR #149).
5. **Add files to an existing album**, with per-file progress, cancel and the refusal messages above (the upload flow). Done: adding to an open album and the three refusal messages (PR #150); Stop for a send in flight is in too (PR for follow-up `files-desk-release-146-and-send-cancel`): it cancels the running upload through `onPromise` and `mx.cancelUpload`.
PR #143 (Option B cut 1: contract types, host client, fake host) is **held**; under A it is not needed and would be closed. Its Soul pass found, and a revived B would have to close, an unvalidated `host` that could send the bearer to the wrong origin, hostile-looking entry names beyond separators, loose numeric checks and missing CSP and `Content-Disposition` headers in the fake.
## Not in scope
The Mind-side fetch (the mouth's); encrypted rooms; deletion and rename by this client; search across zones; any permission model of our own beyond Matrix room membership and power levels.
## Open questions
**Eureka:** answered; see "Eureka's answers" at the top. Still open on Eureka's side: Range support (Q-E4) and the live runtime `max_upload_size`.
**Meta:**
- **Q-M1.** Commons audience: members and Minds as proposed; Users and Patrons never, or later?
- **Q-M2.** Is a Persona's zone visible to all members or to her stewards and Minds? (The Matrix zone's audience question, `ratatoskr:question:file-zone-audience`, is the same fork.)
- **Q-M3.** May Users or Patrons upload if they are ever let in?
- **Q-M4.** Names: "Files" for the view, "Commons" for the shared room.
- **Q-M5.** A type allowlist is not enforceable under A without a gating bot; is a client-side refusal plus steward redaction enough?
---
# Option B in full (kept for the comparison; superseded in part by Option A above)
The sections below were written against the host service. Where they speak of a host, a role, a ticket, a token, `/index` or `/file`, they are Option B. The phone layout, the zone table and the refusal wording carry over to A with the Matrix equivalents given above.
### What exists, and what this adds
| | Matrix file zone (`docs/file-zone.md`, built) | Files desk (this page) |
| -------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| Storage | Matrix media in a `#files-<mind>` room, albums as threads | Directories on Yggdrasil, served by a small host |
| Listing | thread roots, `buildAlbums` | `GET /index?path=` |
| Unit | album of posted files | file in a directory tree |
| Strength | marks (keep / fix / drop), receipts (`fetched for`), any Matrix client works | whole trees without N uploads, no Matrix size limit, `/opt/commons` material becomes visible to people on a phone |
| Entry | Media row per Mind (`MediaRow.tsx`) | Files row (below) |
They do not compete. The Matrix zone stays where a file needs a mark or a receipt (Aqua's listening kits); the Files desk is for browsing and fetching what is already on disk. Neither replaces the other, and the Files desk does not write Matrix events. The ruling left "Matrix media plus a listing versus a served directory" open; this page is the served-directory half, built beside the Matrix half already live.
### Zones (host)
| Zone | Contents | Who sees it |
| ---------------- | ------------------------------------------------------------ | -------------------------------------------------------------- |
| Commons | a curated tree of `/opt/commons` | members and Minds |
| Persona `<slug>` | what that Persona has chosen to share from her Self's outbox | **Q-M:** all members, or the Persona's stewards and Minds only |
| handoff-private | `/opt/commons/handoff-private` (0750) | never: not a zone, not listed, not a path the host resolves |
Layout of `/opt/commons` today (read 2026-11-13): `backlog` (755, per-Mind backlog md and summary.json), `bin`, `cast-art` (setgid, group-writable: poses, busts), `handoff` (setgid, group-writable, 92 entries of briefs, patches, receipts, dings, kits), `handoff-private` (0750, ACL), `opt` (toolchains, root-owned), `situation` (0750, setgid), all `nobody:nogroup`. **`handoff` is not a publishable tree:** it holds ops notes, custody receipts (`bifrost-appsecret-custody-receipt-*`) and patches written for Minds, with no sticky bit. Serving it wholesale shows secrets-adjacent notes to every member and lets any Mind with group write change what a phone user sees. The Commons zone is therefore an allowlist of roots (candidate: `cast-art`, `backlog`, and a new `commons/` directory Minds publish into on purpose), not `/opt/commons` itself. **Q-E:** which roots; whether `handoff` ever, and if so through a reviewed `published/` subdirectory.
Per-Persona source is the outbox from `ratatoskr:follow_up:album-outbox-ops-and-persona-specs`: `/var/lib/mind-<slug>-outbox`, owned by `mind-<slug>-self`, 0750, ACL read for `mind-<slug>` and the host user. The Self writes there; the Persona decides what is shared. Making that decision a filesystem fact (a `shared/` subdirectory the Persona's turn populates by copy or hardlink, the host serves only `shared/`) keeps the host dumb: it never learns what "decides" means. **Q-E:** `shared/` subdirectory versus a per-file marker.
### Phone-first UI (host)
Phone width is the design width; desktop adds the navigator beside it (as `Desk` does in `Router.tsx`). Vertical space is cheap, so a screen shows one thing and hides what is not in use.
- **Entry.** A `Files` row pinned in the navigator beside `DeskEntry` and `MindMedia`: one at the estate level (Commons) and one inside each Mind's group (her zone), same `NavItem` anatomy as `DeskEntry`, dim when the zone has no items. Route `/files/:zone/*path`, sibling of `DESK_PATH`.
- **List.** One column. Row = icon or thumbnail, name (truncates in the middle, keeping the extension), size and age on a second dim line. Directories first. Rows are at least 56 px tall; the tap target is the whole row (the `PhoneHit` variants and the repo-wide guard test from `phoneHit.coverage.test.ts` apply to any IconButton inside).
- **Hidden until needed.** Breadcrumb is one line (current folder, a back arrow; the full path on tap). Search, sort and the grid toggle sit behind a single icon in the header and open inline above the list. Download and share appear on the open file, not on every row. Nothing is permanently stacked in the header.
- **Preview.** Tap a file: it opens in place below its row, full width, and pushes the rows below it down (vertical room is the cheap axis). Image: fitted, tap for the existing `ImageViewer`. Audio: the `AudioContent` controls rehosted (`renderMediaControl`), one player at a time, a mini-player pinned to the bottom only while something plays. Video: native controls. Text, md, json, patch: monospace, first 64 KiB, "show all" below. PDF: open in a new tab. Anything else: name, size, hash, one Download button.
- **Honesty rows.** Loading, empty, "host unreachable", "not allowed" are rows that say so (as `MediaNote` does); no spinner without a name for what it waits on.
- **Role-driven.** The index response carries the caller's role; the client uses it only to hide controls (upload), never to decide access.
### Host contract
The host is a service on Yggdrasil that Eureka owns. The client holds no filesystem knowledge. All JSON here is the xenos boundary between a browser and a file server, not state.
- `GET /index?path=<p>` returns `{ role, zone, path, entries: [{ name, kind: "file"|"dir", size, mtime, mime, hash }] }`. `mtime` is unix seconds. `hash` is the lower-case hex sha256 of the plaintext bytes, absent for directories, and may be absent for a file whose hash is not computed yet (client shows nothing, never blocks on it). `mime` is sniffed by the host from magic bytes, not guessed from the extension.
- `GET /file?path=<p>` streams the bytes with `Accept-Ranges: bytes` and 206 for `Range` (audio and video seek; a phone on mobile data does not fetch 40 MB to play 10 seconds). `Content-Type` is the sniffed mime, `X-Content-Type-Options: nosniff`, `Content-Disposition: attachment` for anything that can run in the origin (`html`, `svg`, `js`, `xhtml`), and a `Content-Security-Policy: sandbox` on every response.
- `path` is `<zone>/<relative path>`, with the zone one of the names the host announces. The host resolves the real path of every request and refuses anything that leaves the zone's root: `..`, absolute paths, NUL, symlinks that cross the root, dotfiles, and `handoff-private`, which is not on any allowlist. Errors are typed (`401 unauthenticated`, `403 zone not allowed`, `404`, `416`), and a path outside the allowlist is 404, not 403, so it says nothing about what exists.
- **Auth: Matrix OpenID.** The client calls `mx.getOpenIdToken()` (already used in `CallWidgetDriver.ts`) and sends it as `Authorization: Bearer <token>`. The host verifies it against the homeserver's federation `openid/userinfo` endpoint, **pinned to our server name** (an `@void:evil.example` token must fail), caches the verified `sub` for the token's lifetime, and derives the role. It never sees the user's access token, and a Mind's Self never holds a token (ruling above): Minds reach the same bytes through the filesystem or the mouth, not this host.
- **Role** in the response: `member`, `mind`, `steward` (host decides from the Matrix id and the room/space membership the host reads; the client trusts none of it for access). **Q-E:** exact source of membership (estate Space membership read by the host with a service account, versus the Persona catalogue file for Minds).
- **Uploads** (Meta approved for members and Minds, #swarm 2026-11-13 14:30Z; rules are Eureka's, below). `PUT /file?path=<p>` writes only under an `uploads/` subtree of a zone, with `Content-Length` required; the host enforces a size cap, a type allowlist (sniffed, not the client's claim), no overwrite unless the request carries an explicit flag, and never replaces a file a Mind wrote into the handoff tree; every write is audit-logged with the caller's Matrix id. Reads cover the whole allowlisted tree, so an uploaded file is listed like any other. Success is `201` with the stored name, size and hash. The `role` in the index response gates the upload control; the host gates the write.
### The one problem the contract leaves: media elements cannot send headers
`<audio src>`, `<video src>` and `<img src>` cannot attach `Authorization`. Options, none free:
1. **Fetch to a blob.** Works with the contract as written. No seeking before the whole file is in memory; bad for a 40 MB clip on a phone. Fine for images and small audio.
2. **Short-lived path ticket.** `POST /ticket?path=` with the bearer token returns a URL with an unguessable token valid for a few minutes for that one path and its ranges. The player gets a normal URL and seeks. One more endpoint on the host and one more thing to expire and log.
3. **Service worker adds the header** to `/files-host/*` requests. The PWA already has a worker (`src/sw.ts`); no host change, but the worker must carry a fresh OpenID token and range requests through it are fiddly.
Recommendation: 2 for audio and video, 1 for images and text. Confidence moderate: I have not tested a service worker against range requests on the target phone, and 2 is the usual answer for authenticated media (signed URLs). **Q-E.**
### Upload flow (host)
Design only. Every number and error code is a named placeholder until Eureka gives them on the PR: `<CAP_FILE>` (per-file size), `<CAP_BATCH>` (per-pick total, if any), `<TYPES>` (the allowlist), `<OVERWRITE_FLAG>` (the explicit query flag), and the codes `<E_AUTH>`, `<E_ROLE>`, `<E_PATH>`, `<E_TYPE>`, `<E_SIZE>`, `<E_EXISTS>`, `<E_PROTECTED>`, `<E_QUOTA>`, `<E_SERVER>`.
**Where.** The control exists only where an upload is allowed: inside a folder under a zone's `uploads/` subtree (or at the `uploads/` row itself), and only when the index `role` is member or mind. Elsewhere there is no button; the list does not carry a disabled one. A folder outside `uploads/` shows a one-line dim note, "Uploads go in uploads/", which links to that folder. Creating subfolders under `uploads/` is not in this design (**Q-E8**).
**Pick or drop.** One `Upload` row at the top of an `uploads/` folder opens the native picker (any number of files; on a phone this is the OS file sheet, camera roll included). On wide screens the list is also a drop target; the drop highlight appears only while a drag is over it. Nothing starts on pick: the picked files appear as a staging list (name, size, a type icon) with `Upload` and `Cancel` as full-width rows, as `ShareSet` does for a Matrix set. Files that already fail the client's cheap checks (over `<CAP_FILE>`, a type outside `<TYPES>`) are marked in the staging list with the reason and left out of the send; the client mirrors the cap and allowlist as a courtesy only, the host is the authority, and the list is read from the host (**Q-E9**: an `/index` field or a `/limits` call) rather than hard-coded.
**Send.** Files go one at a time, in pick order, each a `PUT /file?path=<folder>/<name>` with the bearer token. One at a time keeps a phone on mobile data from starving every transfer, and a refusal names exactly one file. The transport is `XMLHttpRequest`, not `fetch`: `fetch` has no upload progress and the row needs it. The body is the `File` itself (streamed by the browser, not read into memory; unlike the Matrix path, the client computes no hash first, the host returns one). The name is the file's own name, with path separators and control characters replaced, never a path the user typed.
**Progress.** The staging list becomes the progress list: per file a thin bar and "412 KB of 3.1 MB", per batch "2 of 5". Finished files show a tick and the stored name; refused ones show the refusal in place; waiting ones are dim. Only the active file animates. The list stays on screen after the last file until dismissed, so a refusal is not lost to a refresh of the folder underneath it. The folder listing refetches after each success, so the file appears in the list as it lands.
**Cancel.** `Cancel` on the active file aborts the request (`xhr.abort()`) and goes on to the next; `Cancel all` on the batch aborts the active file and drops the rest. The host must discard an aborted partial write and never leave a half file in the listing (**Q-E10**, written to a temporary name and renamed on completion). Leaving the page aborts whatever runs, as the Matrix share does; the client does not resume.
**Overwrite.** A name that already exists is refused with `<E_EXISTS>` and shown as "<name> is already there". A `Replace` row appears under that refusal only for a file the caller wrote themselves, and sends the same `PUT` with `<OVERWRITE_FLAG>`; a Mind-written handoff file refuses with `<E_PROTECTED>` and offers only "Keep both", which re-sends under a suffixed name (`name (2).ext`) chosen by the client. Whether the client can tell "mine" from the index (an `owner` field with the Matrix id) or learns it only from the refusal is **Q-E11**; absent an owner field, `Replace` is simply offered after `<E_EXISTS>` and the host's answer decides.
**Refusal messages.** One plain sentence per code, shown in the file's row; nothing says "error" without saying why, and none names a server path.
| Code | Message (draft) |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `<E_AUTH>` | Sign-in expired. Reload to upload again. (The client fetches a fresh OpenID token once and retries before showing this.) |
| `<E_ROLE>` | Uploads are for members and Minds. |
| `<E_PATH>` | That folder does not take uploads. |
| `<E_TYPE>` | "<name>" is a <type> file; allowed types are <TYPES>. |
| `<E_SIZE>` | "<name>" is <size>; the limit is <CAP_FILE>. |
| `<E_EXISTS>` | "<name>" is already there. |
| `<E_PROTECTED>` | "<name>" was written by a Mind and cannot be replaced. |
| `<E_QUOTA>` | The shared space is full. Tell a steward. |
| `<E_SERVER>` / network / timeout | Could not reach the file host. The file was not saved. |
Retry is one tap on a failed row; the batch never retries on its own. An unknown code shows the host's status text as it is, still without a path.
**Honest end state.** Done means the host answered `201` and the stored name, size and hash are shown. "Saved" is not said earlier; the hash the host returns is displayed so a sender can compare it with their own.
**Reuse and not.** `ShareSet`'s state machine (staging, one-send-per-zone guard, failed files kept by position) is the model, but the Matrix share path and its `createUploadAtom` are tied to the SDK's media upload and are not reused; the new controller sits in `features/files/uploadController.ts` with the same injected-port shape, so order, refusal and cancel rules are tested against a fake `PUT` without a browser. Real transfer progress and a real range of a phone's picker stay a phone check.
### Client shape (host)
Under `src/app/features/files`, mirroring `features/albums`:
- `filesHost.ts`: ports, `list(path)`, `url(path)`, `ticket(path)`, `put(path, file, onProgress, signal)`; the only module that knows the contract. Injected, so the UI is tested against a fake and the real client never runs in a test.
- `useFilesZone.ts`: react-query on `['files', zone, path]`, `staleTime` 30 s; the role comes with every index.
- `FilesDesk.tsx`, `FileRow.tsx`, `FilePreview.tsx`: pure rendering from the above; the preview picks its renderer from the host's `mime`, not the extension.
- `config.json`: `filesDesk: { enabled: false, host: "https://…" }`, dark by default as `fileZoneShare.enabled` is. With it off, no row mounts and no request leaves the client.
- Test host: `src/preview-demo` already answers for a pretend homeserver through a fetch guard (`install.ts`); it gains a fake `/index` and `/file` with ranges so the previews are checked in a real browser before the real host exists.
### Cuts (host)
1. **Contract and fake host** (no UI): `filesHost.ts`, types, `preview-demo` fake, path tests (traversal strings from the host side are Eureka's; the client must only build `path` from entries it was given).
2. **Read-only Commons desk**: route, row, list, breadcrumb, role display, flagged off.
3. **Preview and player**: image, audio with ranges, text, video; the ticket if Q-E settles on 2.
4. **Per-Persona rows** in each Mind's group, once the outbox `shared/` convention and the zone provisioning exist.
5. **Uploads**: the flow above; needs Eureka's codes and caps and the host's `PUT`.
Each is its own PR. Slices 1 to 3 need no host to build and test; slice 2 needs the real host to be useful, not to land.
### Not in scope (host)
The Matrix file zone (marks, receipts, `ShareSet`); any Mind-side fetch (the mouth's); encrypted rooms; deletion and rename (a read surface first; the files belong to whoever wrote them on disk); search across zones; a permission model of our own beyond what the host derives from Matrix identity.
### Open questions (host)
**For Eureka (host):**
- **Q-E1.** Which roots form Commons: the allowlist, and whether `handoff` is ever served (it holds custody receipts and ops notes; recommendation: no, a reviewed `commons/` directory instead).
- **Q-E2.** Where the host runs and what it is: Rust by default per doctrine; nginx with `auth_request` to a verifier is smaller if the sniff, range and role logic fit there. Which user; read-only mounts; ACLs on the outboxes.
- **Q-E3.** Media-element auth: blob, ticket or service worker (above).
- **Q-E4.** Role source: how the host learns membership and which Minds are Minds; token verification pinned to `gamecult.org`.
- **Q-E5.** Per-Persona publishing: a `shared/` subdirectory versus a marker, and who populates it when the Persona decides.
- **Q-E6.** Hash cost: compute lazily and cache by (path, mtime, size), or at publish time.
- **Q-E7.** CORS for `chat.gamecult.org` and the dev previews, rate limits, and the `Content-Disposition` list.
- **Q-E8.** Subfolders under `uploads/`: can a client create them (by a `PUT` path that implies them, or a `MKCOL`-like call), or is `uploads/` flat?
- **Q-E9.** Cap and allowlist discovery: fields in the index response, or a `/limits` endpoint; and the exact codes and cap numbers behind every placeholder in the upload flow.
- **Q-E10.** Partial writes: temporary name then rename, so an aborted or failed upload never appears in a listing.
- **Q-E11.** Does the index carry an `owner` Matrix id per file (so `Replace` is offered only on one's own files), and is the audit log readable by stewards from the client or only on the host?
**For Meta:**
- **Q-M1.** Audience: Commons for members and Minds as proposed; are Users and Patrons ever in (the Matrix zone's audience question, `ratatoskr:question:file-zone-audience`, is the same fork)?
- **Q-M2.** Is a Persona's zone visible to all members or to her stewards and Minds?
- **Q-M3.** ~~Uploads~~ approved for members and Minds (2026-11-13 14:30Z); open only: may Users or Patrons upload if they are ever let in?
- **Q-M4.** Name: "Files" for the row, "Commons" for the shared zone.
- **Q-M5.** Does the Matrix Media row stay beside the Files row on each Mind, or does one absorb the other once the Files desk exists (recommendation: both stay; marks and receipts are Matrix's).

View file

@ -77,7 +77,7 @@ Reuse the composer's pipeline, pointed at an album instead of the main timeline:
## Existing code to reuse (verified present in the repo) ## Existing code to reuse (verified present in the repo)
| need | where | | need | where |
|---|---| | --------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| audio player (play/seek/volume, encrypted download) | `src/app/components/message/content/AudioContent.tsx` (210 lines) | | audio player (play/seek/volume, encrypted download) | `src/app/components/message/content/AudioContent.tsx` (210 lines) |
| video, image, generic file | `.../content/VideoContent.tsx`, `ImageContent.tsx`, `FileContent.tsx` | | video, image, generic file | `.../content/VideoContent.tsx`, `ImageContent.tsx`, `FileContent.tsx` |
| full-screen image viewer | `src/app/components/image-viewer/ImageViewer.tsx` | | full-screen image viewer | `src/app/components/image-viewer/ImageViewer.tsx` |
@ -104,3 +104,20 @@ Slices 1+2 serve the first use case. Each is its own PR. Because marks are ordin
- How the client identifies the zone room (config id recommended). - How the client identifies the zone room (config id recommended).
- Whether exports are per listener (proposed) or a merged all-listeners file. - Whether exports are per listener (proposed) or a merged all-listeners file.
- Where `device` comes from, now that reactions cannot carry it (export dialog, proposed). - Where `device` comes from, now that reactions cannot carry it (export dialog, proposed).
## Share a set (built, behind `fileZoneShare.enabled`)
The ruling `ratatoskr:ruling:persona-file-sharing-zone` asks that a set of files arrive together, not one attachment at a time. The zone already holds one thread per album, so a set is an album: **one root text message plus one `m.thread` reply per file**, the exact shape `buildAlbums` reads. Nothing new on the wire and no homeserver change; a Mind's mouth that posts into the zone room and a person using the client produce the same events.
Matrix options checked: (a) a thread, chosen: stock, rendered by every client, already the zone's album; (b) `m.gallery` (MSC4274) puts several items in one event, but it is unstable, most clients and this one do not render it, and each item still needs its own upload; (c) a shared custom relation: no client groups by it. A thread costs one extra event per set (the root) and nothing else.
Client, `src/app/features/albums`:
- `shareSet.ts`: `sendShareSet(port, title, files)`. Sends the root, then each file in pick order, each reply falling back to the previous event (`threadRelation`). A file whose upload fails is named in the result and the rest still go; a root that fails to send throws before any upload. The root alone is not an album in the list (`/threads` returns only roots that have a reply), so a share where every upload failed leaves a lone text message in the timeline. After a send the panel keeps only the failed files picked; a retry makes a second album. Ports are injected, so the order and failure rules are tested without a homeserver (`shareSet.test.ts` reads the sent events back through `buildAlbums`).
- `shareController.ts`: the panel's state machine (picked files, phase, the one-send-per-room guard, the encrypted refusal, failed files kept by position), apart from React so tests drive it without a DOM; `shareController.test.ts` and `ShareSet.test.tsx` (static render of each state, the flag) pin it. No DOM test environment exists in this repo, so a real tap on a real input is covered by the phone check, not by tests.
- `ShareSet.tsx`: phone layout. Idle, it is one text row, "Share files". Picking files (any number from the native picker; a second pick replaces the first) mounts a title field, the picked names on one dim line, and Send / Cancel as full-width rows; progress is "Sending 2 of 5". It is shown only on the album list (kept mounted but hidden while an album is open, so a running send keeps its state), one send at a time per room (tracked outside the component; leaving the page does not stop a send, it only loses its progress and result), and never in an encrypted zone (re-checked when Send is tapped) (the plaintext `info.sha256` the Mind verifies against is written in unencrypted rooms only).
- Content per file comes from `getMsgContent` in `features/room/msgContent.ts`, now also used by the composer, so a shared file and an attached file carry the same `info` including `sha256`.
Flag: `fileZoneShare.enabled` in `config.json`, default `false`. With it off nothing mounts.
Not built: a Mind's own path into the zone (outbox, Persona decision, mouth post) belongs to gamecult-ops / Huginn / the mouth, not this client; Built since: Stop for a send in flight (aborts the running upload, leaves it and the rest picked as "stopped"), pagination to 20 pages of 100 per endpoint (PR #148), adding files to an open album with named refusals (`M_TOO_LARGE`, `M_FORBIDDEN`, `M_LIMIT_EXCEEDED`).

View file

@ -0,0 +1,108 @@
# chat.gamecult.org: shell compression and caching
Follow-up `ratatoskr:follow_up:chat-shell-compression`. Measured 2026-11-12 against the live
host, which serves release `ratatoskr-nemesis-9b9b495d` (the `index-CAataSJe.js` bundle; the offline table
below also uses the `f8115609` handoff build, `index-D0yL0Dgy.js`, and says which row is which). The host config is
`nginx/chat.gamecult.org.conf` in `gamecult-ops`, owned by Eureka; nothing here is applied
to the host.
## What the host serves now
The 2026-10-31 probe (no Content-Encoding, no Cache-Control on `/assets/`) is stale: the
`nginx.conf` has `gzip on`, the site file sets level 5, `gzip_vary` and `gzip_types` for js, css, json, svg and wasm, and carries an immutable
`Cache-Control` on `/assets/` and `/preview/assets/`. Probed with `curl -H 'Accept-Encoding: X'`.
| Resource | raw | gzip (served now) | brotli (served now) |
|---|---|---|---|
| `/assets/index-CAataSJe.js` | 3,732,771 | 956,085 | none: `br` is ignored, identity returned |
| `/assets/index-BLdKqKqx.css` | 111,267 | 19,952 | none |
| `/assets/matrix_sdk_crypto_wasm_bg-DwIieW7K.wasm` | 5,573,870 | 1,878,147 | none |
| `/` (index.html, no-cache) | 3,066 | gzip | none |
Headers: hashed `/assets/` answer `Cache-Control: public, max-age=31536000, immutable`;
`/`, `index.html`, `sw.js`, `manifest.json`, `config.json` answer `no-cache`; compressed
responses carry `Vary: Accept-Encoding` and a weak ETag. `config.json` (424 B) is below
`gzip_min_length 1024` and goes uncompressed, which is correct.
So the original ask is done. What is left is brotli, which nginx 1.26.3 here cannot serve:
`/usr/sbin/nginx -V` shows `--with-http_gzip_static_module` and no brotli module.
## What brotli buys
Level-5 gzip is what the host does per request. Offline measurement on the same files
(node `zlib`, 2026-11-12):
| File | raw | gzip 5 (node) | gzip 9 | brotli 11 | brotli vs live |
|---|---|---|---|---|---|
| live main chunk `index-CAataSJe.js` | 3,732,771 | 957,199 | 945,424 | 725,167 | -24% |
| handoff main chunk `index-D0yL0Dgy.js` | 3,868,313 | 1,015,680 | 1,001,446 | 773,992 | -24% |
| crypto wasm | 5,573,870 | 1,868,282 | 1,851,108 | 1,343,595 | -28% |
| `ReactPrism-Dm2uRF4v.js` | 577,517 | 209,339 | 208,376 | 163,525 | -22% |
A cold load of the two big files falls from about 2.8 MB to about 2.1 MB on the wire; the
saving is ~0.7 MB once per hashed build per device while the HTTP cache keeps the file (immutable; the
service worker does no precaching, so eviction or a new device pays again). gzip 9 alone buys 1-2%, so
`gzip_static` without brotli is not worth a build step. Brotli is the whole prize, and it
needs one root step.
Cost: brotli q11 takes about 12 s for the wasm and 8 s for the main chunk on one core, so
the whole dist is about two minutes at build time (measured, 84 files) and zero CPU per request. Do not use q11
on the fly; that is why the plan is precompressed twins.
## Root list for Eureka (host)
1. `apt install libnginx-mod-http-brotli-filter libnginx-mod-http-brotli-static` (trixie/main, 1.0.0~rc-6,
depend on `nginx-abi-1.26.3-1`, which the installed nginx provides; apt may offer an nginx patch upgrade
alongside, say so before accepting). Do not enable the config yet.
2. Install a build with twins (`PRECOMPRESS=1`, below) the usual way
(`docs/gamecult/client-build-install.md`). Twins for files that are not there change nothing.
3. In the `chat.gamecult.org` `server` block, beside the existing gzip lines:
```nginx
brotli_static on; # serve <file>.br when the client sends br
gzip_static on; # serve <file>.gz; falls back to the on-the-fly gzip above
brotli on; # on-the-fly br for files with no twin (index.html, small files)
brotli_comp_level 5;
brotli_types text/css application/javascript text/javascript application/json application/manifest+json image/svg+xml application/wasm;
```
The `location ^~ /assets/` block and `/preview/`, `/element/` and `/mockups/` inherit these; they only add headers.
No other change: the `Cache-Control` and `Vary` lines stay as they are, and
`gzip_vary on` already makes the on-the-fly and static paths vary correctly.
4. `nginx -t && systemctl reload nginx`. Twins first, config second: with `brotli on` and no twins every
client gets on-the-fly q5 brotli of the 3.7 and 5.6 MB files, which costs CPU per request.
Rollback: remove the five lines and reload. The `.br`/`.gz` files can stay on disk, unused.
## Build side
`build-prod-dist.sh` (Void's, in `/opt/commons/handoff/ratatoskr-main-build/`) gains
`PRECOMPRESS=1`, which runs `precompress.cjs <dist>` before the manifest is written. It
writes `<file>.br` (q11) and `<file>.gz` (level 9, no mtime, deterministic for one node) next
to each js, css, wasm, json, svg, html file over 1 KiB, only when smaller than the original.
Default is off, so builds installed before the host change do not ship ~27 MB of twins that
nothing serves. The twins appear in `SHA256SUMS`; the determinism compare still applies.
Tested on `ReactPrism-Dm2uRF4v.js` (gzip roundtrip identical to the original); a full
`PRECOMPRESS=1` build has not been run because it waits on step 1.
The script is not in this repo; its placement is a standing open item of the build handoff.
## Before/after measurement
Run from any machine; `X` is the asset URL. Before = today's table above.
```sh
for ae in identity gzip br; do
printf '%s ' "$ae"; curl -s -o /dev/null -H "Accept-Encoding: $ae" -w '%{size_download} %header{content-encoding}\n' "$X"
done
curl -sI -H 'Accept-Encoding: br' "$X" | grep -iE 'content-encoding|vary|etag|cache-control'
```
Pass: with `br` the main chunk is about 774 KB and the wasm about 1.34 MB with
`Content-Encoding: br`; with `gzip` the bytes are no larger than today; with `identity`
the file is the raw size; `Vary: Accept-Encoding` and the immutable `Cache-Control` are
still present on all three; `index.html`, `sw.js` and `config.json` still `no-cache`.
The service worker's registration and an existing session must still work (open chat on
the operator's phone, hard reload once, check the network panel's "transferred" column).
Check `/preview/assets/` the same way, but `/preview/` is served from `/srv/cinny/preview`, which this build
script does not produce: it gets on-the-fly brotli, not twins, until a preview build carries them.

View file

@ -0,0 +1,120 @@
# Ratatoskr client: build, install, verify, roll back
Who does what. The steward (Void) builds and hands off; Void holds no root and does not deploy.
Eureka installs on the chat.gamecult.org host, which is Eureka's. This page is the shared
procedure. Nothing here is run by the build step against the live host.
## Facts about the host
- Web root: `/srv/cinny/`. `current` is a symlink to one directory under `releases/`; the web
server serves `current`. Releases are `releases/ratatoskr-<8hex>` (older ones are
`ratatoskr-nemesis-<8hex>`). Previous releases stay on disk; that is the rollback.
- The client is static. `config.json` sits in the release root beside `index.html` and is read
at load. Cinny's `Dockerfile` and `docker-nginx.conf` are upstream's container path, not the
chat.gamecult.org path.
- Check the pointer before anything else: `readlink /srv/cinny/current`.
## 1. Build (steward)
Two builds exist, and they treat `config.json` differently.
**By hand (the repo's config).** `vite build` copies the repo's `config.json` into `dist/`
(`vite.config.js`, static copy of `config.json`). Ratatoskr #103 made the repo file the intended
served config, and #106 set `backgroundScene.style` to `ridge`; the served file has not caught up
(see Open). Do not hand-edit `dist/config.json`.
```sh
git clone https://eureka.gamecult.org/forge/GameCult/Ratatoskr.git && cd Ratatoskr
git checkout <full-40-hex-sha> # build a named commit, not a branch tip
npm ci --ignore-scripts # .npmrc sets legacy-peer-deps; skips husky's prepare hook
node scripts/sync-poses.mjs # pose art is not committed; this also rewrites the tracked
# src/app/components/message/pose/catalogue.json
NODE_OPTIONS=--max_old_space_size=6144 npm run build # writes dist/
```
Skip `sync-poses` and the build ships with no poses. Do not use `npm run build:preview` for
production: it rewrites `dist/config.json` for preview (hash router, chosen tier and style).
**The handoff build (what the host installs).**
`/opt/commons/handoff/ratatoskr-main-build/build-prod-dist.sh <full-sha>` (see its `README.md`)
writes `/opt/commons/handoff/ratatoskr-main-<full-sha>/{dist,SHA256SUMS,BUILD-INFO,build.log}`,
locks the files read-only and refuses to overwrite. The dist carries the repo's `config.json` at
that sha (BUILD-INFO `config_json_source`, `config_json_sha256`); there is no separate pinned copy.
Its live check always runs: it fetches the served config and compares it byte for byte with the
repo's. A difference prints the diff and stops the build. `ALLOW_CONFIG_DRIFT=1` builds anyway and
BUILD-INFO records `config_json_live_check: DIFFERS ...` and `config_json_live_sha256`, so the
handoff states which config differs and the installer decides. From Yggdrasil the public name does
not resolve: pass `LIVE_CURL_ARGS="--resolve chat.gamecult.org:443:127.0.0.1"`.
The folder, with the three pins (`SHA256SUMS` sha256, `BUILD-INFO` sha256, lockfile sha256) and
the node and npm versions, is what the install request names.
Every build stamps its commit into `index.html` (`scripts/buildSha.js`): `<meta name="build-sha" content="<40-hex>">`,
with `-dirty` appended when the tree had uncommitted changes and `unknown` when there was no git. Where git governs the tree it decides: an explicit `BUILD_SHA` naming a different commit than HEAD stamps `<sha>-mismatch`, a git failure stamps `unknown`. A full-sha `BUILD_SHA` stands only for a tree git does not govern (a source archive) or cannot read (unusable git, for example a dubious-ownership refusal). The handoff
build refuses a dist whose stamp differs from the sha it was asked for, and prints the stamp in its block.
To read it from anywhere: `curl -s https://chat.gamecult.org/ | grep -o 'build-sha" content="[^"]*'`.
Before handing off:
```sh
cd <folder>/dist && sha256sum -c ../SHA256SUMS # 0 failures
grep -rl 'demo.invalid\|demo-preview-token' <folder>/dist # must print nothing
# from Yggdrasil the public name may not resolve; --resolve points it at the local server
diff <(curl -fsS --resolve chat.gamecult.org:443:127.0.0.1 https://chat.gamecult.org/config.json) <folder>/dist/config.json
```
A config difference is a finding to report, not something to paper over: either live drifted or
the repo is wrong, and a ruling (Meta, for `backgroundScene.style`) says which ships.
## 2. Install (host owner, root, by hand)
Note the rollback target first: `readlink /srv/cinny/current`.
Unpack beside the live release; do not touch the live directory. The target must not exist, or
`cp -r` nests `dist` inside it.
```sh
R=ratatoskr-<8hex>
H=/opt/commons/handoff/ratatoskr-main-<full-sha>
test ! -e /srv/cinny/releases/$R
cp -r $H/dist /srv/cinny/releases/$R
cmp /srv/cinny/current/config.json /srv/cinny/releases/$R/config.json
(cd /srv/cinny/releases/$R && sha256sum -c $H/SHA256SUMS)
```
`cmp` is a drift check, not a pass check. Live has no trailing newline; the repo's file has one,
so even equal content differs. Read the difference (`diff` the two) and settle which config
ships. To keep the host's config byte-for-byte, as past installs did,
`cp /srv/cinny/current/config.json /srv/cinny/releases/$R/config.json`; `sha256sum -c` then flags
`config.json` only (read that one line; `--ignore-missing` does not hide a mismatch).
Switch (a single symlink swap; `ln -sfn` unlinks then links, so there is a moment with no link):
```sh
ln -sfn releases/$R /srv/cinny/current
```
## 3. Verify
- `readlink /srv/cinny/current` names `releases/$R`.
- `curl -s https://chat.gamecult.org/config.json | sha256sum` equals `sha256sum /srv/cinny/releases/$R/config.json`.
- Load https://chat.gamecult.org/ and hard-refresh (the service worker, `sw.js`, can hold the
previous assets). Sign-in card shows, the background scene draws, the browser console has no
page errors, a poses/asset request returns 200 and not index.html.
## 4. Roll back
Point `current` at the release noted before the switch. Live at the time of writing is
`ratatoskr-nemesis-9b9b495d`:
```sh
ln -sfn releases/ratatoskr-nemesis-9b9b495d /srv/cinny/current
```
Hard-refresh to clear `sw.js`. Do not delete the failed release; leave it for diagnosis.
## Open
- Release a5 (2026-11-20, dist `a1fdfee3`, receipt `/opt/commons/handoff/rat146-a5-receipt-20261120.md`)
replaced the carried config with the repo's `config.json` (ridge, `fileZoneShare` on; ruling
`ratatoskr:ruling:ridge-only-scene-terrain-cut`). The carried file and the build pin are equal, so a
handoff build passes its live check without `ALLOW_CONFIG_DRIFT=1`. A release that changes
`config.json` changes the carried file deliberately, as a5's `carry.sh` did.

View file

@ -97,9 +97,11 @@ Probes run by Imagination on 2026-10-31, session `self-2026-10-29-eureka`.
events from the Minds' stewardship documents; each project room's alias is events from the Minds' stewardship documents; each project room's alias is
`#<repo lowercased>` (runbook 146-150). This is the only place the client `#<repo lowercased>` (runbook 146-150). This is the only place the client
can learn a not-yet-joined room's steward today: hierarchy `canonical_alias` can learn a not-yet-joined room's steward today: hierarchy `canonical_alias`
joined to the root `org.gamecult.stewardships`. Follow-up joined to the root `org.gamecult.stewardships`. The
`ratatoskr:follow_up:stewardships-carry-room-ids` asks the projection to projection now also names room ids under `@rooms.projects` and
name room ids so the client stops leaning on the alias convention. `@rooms.file_zones` (gamecult-ops #111); the client reads `file_zones` for
the Media row (`mediaRoom.ts`) and still joins projects by alias, since
nothing yet consumes `@rooms.projects`.
5. **Sync and storage** (`src/client/initMatrix.ts`). The client uses 5. **Sync and storage** (`src/client/initMatrix.ts`). The client uses
matrix-js-sdk 41.7.0 with `IndexedDBStore` (`web-sync-store`, 15-19) and the matrix-js-sdk 41.7.0 with `IndexedDBStore` (`web-sync-store`, 15-19) and the
Rust crypto store, and `startClient({ lazyLoadMembers: true })` (43-47): v2 Rust crypto store, and `startClient({ lazyLoadMembers: true })` (43-47): v2

View file

@ -0,0 +1,16 @@
# Ridge backdrop target
The scene's bottom silhouette is replaced by baked A+D ridge planes. The baker is Python and offline; the browser composes pre-lit planes over the live physical sky. Typed state for this campaign (ideas, questions, rulings, cuts) lives in the instance mind `nibu`, campaign `ratatoskr-backdrop`; this file keeps only the ends.
## Why
The live noise ridge is nearly invisible on a phone (about 1.35:1 against the darkest sky) because every ridge pixel is lifted to the text-contrast floor, and the star dots show between nav and header glyphs because the shell is transparent. Meta, 2026-11-13: do not polish the old backdrop; ship the A+D ridge pipeline (round 2 mockup: https://minds.gamecult.org/nibu/ridge-mockups-ad/).
## Ends
- One owner per decision: the baker owns ridge geometry and shading; the runtime owns only frame choice, blending, camera drift and compositing. No ridge geometry is computed in the browser.
- Nothing from the scene paints above app content: the scene is one stacking context at the back of the app, and nothing it creates has its own z-index or lives outside it.
- Phone cost is bounded: no per-frame script for the ridge, decoded size and fetched size gated in CI.
- The baker has fixtures with known right answers (the far-plateau spike, chain-end taper, slot union, seam) and a mutation runner that must kill each re-introduced cause.
- A baked asset names its baker version, DEM source and licence in a validated manifest; the credits shown in the Sky menu come from the manifest.
## Not in scope
Button size (Void's). Patching the old noise-ridge path. Cone sampling. Live DEM access from the browser.

View file

@ -0,0 +1,101 @@
# Symphony grammar harvest: Mimir's bioacoustic research
Follow-up: `ratatoskr:follow_up:symphony-grammar-harvest-mimir`. Source: GameCult/Mimir at
commit c6f4541eea61 (exists; read at that ref, not main), read-only through the forge API.
Paths below are Mimir paths. Written for Aqua (AquaSynth) before the generative activity grammar. It lives here because the symphony is a Ratatoskr cut (dings, then orbiting personas) and this repo is where its spec will be read; the follow-up named AquaSynth, where void holds no push right, so move it there if Aqua prefers.
## 1. The problem
One Mind's identity has to be a timbre plus a contour that stays recognisable after it is mixed with
the other Minds and passed through a lossy path. The symphony adds harmony (several Minds sounding
together as music), which Mimir never needed: Mimir emits one voice at a time, a low-gain song per speaker.
## 2. What Mimir found that transfers
Confidence: A = measured number in a receipt, B = measured but synthetic or single run,
C = design claim or authored opinion with no measurement behind it.
| Claim | Evidence | Conf. |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |
| Tidy lab beeps are the wrong signal for a room; a birdsong-like motif replaced them. | `docs/bioacoustic-timeline-watermark.md` L3-10 (stated as a decision, no listening test). | C |
| Identity is carried redundantly: contour survives pitch shift, rhythm survives bad frequency response, formant envelope survives a dead band, speaker variants expose room asymmetry. | same doc L82-95. Argument, not an ablation. | C |
| A word needs no sequence grammar: one heard word identifies its event directly (128 words x 2 speaker variants, 4 syllables each), in an event slot that repeats about every 41 s (derived, not reported: 128 words x 2 speakers = 256 events at 0.16 s spacing = 40.96 s, from `MimirBioacousticTimeline.cs` L34-39 and `SymbolForEvent` L735-739; no receipt or doc states it). No de Bruijn grammar. | same doc L26-33; `src/Mimir.Runtime/Synchronization/MimirBioacousticTimeline.cs` (WordCount, SymbolCount = WordCount\*SpeakerCount, BuildMotifs ~L690-730). | B |
| Word identity survives mel-cepstral warp/blur degradation; timing does not unless fitted as one global clock/delay hypothesis. | `docs/bioacoustic-training-harness.md` L58-112: identity 0.908-0.997 on clean input only; degraded identity 0.532-0.908 and timing 0.187-0.728 for compact-fast-index across the four degraded cases in `artifacts/bioacoustic-training/bioacoustic-20260524-150729/compact-fast-index/*/summary.json` (`IdentityScore`, `TimingScore`); clean timing 0.357 before vs 0.905 after the global clock fit. | A (synthetic, clean-only range) |
| Contestant shapes were scored against the same decoder family and damage panel; the best scorer was the six-syllable "canary-packet-trill", a hypothesis not confirmed on a physical room (two timing chips plus four payload-coloured formant notes), not the literal bird imitations. | `research/bioacoustic-contestants-2026-05-24.md` L24-38, L128-174 (honest floor 88.4 language_score, 19 bps, payload 1.000 clean), L487-489 (96 ms motif is the best tradeoff). | B |
| Too-short or too-tight songs fail under blur: 0.100 s event spacing lost anchors to overlap; 0.105 s kept; 78 ms motif and 5-syllable finch-burst-packet collapsed (blur-light 4.358, the razor decoder; 218.368 with the sprint decoder, L453-454). | contestants doc L169-171, L446-455, L487-489. | A |
| A 3-bit payload variant (separate band/rhythm bit) did not survive degradation (best 12.849, clean 8.084). | contestants doc L183-185. | A |
| Real birds carry identity through redundant contour, roughness, onset statistics and cepstral envelope together; Redpoll is dense chatter with short vertical attacks, not a neat token stream; Guan is a slow broad curved phrase, good for probing the channel, poor for bitrate. The packet song was judged "still too ladder-like". | contestants doc L565-581 (two Xeno-canto mirrors via Wikimedia; Brown Thornbill file invalid, L511-513, L534-539). Flux numbers L549-562. | B (two recordings, hand reading) |
| Positive log-mel spectral flux is a good onset/anchor surface; sustained bands recede, attacks and glides light up. | contestants doc L541-545, L577-581; but the naive flux decoder lost on speed (33.466 vs 88.129 score, clean roundtrip, L158 and L231-237). | B |
| Once the schedule is known, the receiver only discriminates among a few local candidates; wide identity search is only for acquisition. Streaming decoder reached 1121 score at 62.6x realtime, payload 1.000 on all nine damage cases. | contestants doc L248-309. | A (synthetic damage) |
| Polarity must be a nuisance variable; mic paths flip sign. | contestants doc L391-395. | B (physical, one capture) |
| Physical room run: with per-channel acquisition offsets the co-streamer shotgun mic (ch1) locked 37/37 events, payload 1.000, timing 0.828; the cardioid/near mic (ch0) reached 26/37, payload 0.595, and stayed unreliable. | contestants doc L371-388. | B (physical, one capture) |
| Speaker split: left and right vocabularies differ in root (x0.94 / x1.08) and syllable weights, so each side is separable. | `MimirBioacousticTimeline.cs` BuildMotifs ~L704-725 (read as code, no experiment isolates the benefit). | C |
Rendering recipe actually in code (`MimirBioacousticTimeline.cs` AddSyllable ~L610-640): each syllable is
a log-frequency glide (exponential sweep) with a raised-cosine envelope, summed partials at
1, 1.5, 2, 2.75 times the glide (weights 1, 0.42, 0.24, 0.10) plus 0.08 weight of a slow "air" term,
20-32 ms long, four per word, gain 0.030 (canary profile 0.024 in `MimirBioacousticContestant.cs`).
Word roots are log-spaced 2.6 to 9.6 kHz; syllable frequencies are clamped 2.3 to 14.6 kHz;
word length 118 ms. Contours come from a small hand-written bank (8 contour shapes and 8 rhythm
offset sets, chosen by hash of word and speaker).
## 3. Design constraints for Aqua's grammar
1. Identity lives in several channels at once: contour (syllable glide shapes), log-frequency position
(root), formant envelope (the partial ratios), rhythm (inter-syllable offsets) and per-speaker
timbre. No single channel may be load-bearing. Place Minds on a log-frequency axis, not linear.
2. Do not build a sequence grammar for identity (de Bruijn or otherwise). The whole word is the unit;
a hearer should identify the Mind from one short phrase. (watermark doc L31-33.) What it gives up:
a de Bruijn code has a provable recovery property from a symbol stream; per-word identity has only
an empirical one.
3. Keep words short and distinct, but not so tight that they overlap: Mimir's measured edge was about
100 to 105 ms event spacing and a 96 ms six-syllable motif; below that identity decayed. Aqua's
events need not carry timing, so it can relax this, which is untested.
4. Use sharp onsets for placement but avoid a ladder of evenly spaced rungs; Mimir's own verdict was
that its packet song was still too ladder-like and real birds use irregular, redundant contour
(contestants doc L573-576). Vary rhythm and syllable length per word as the code already does.
5. Reject: row of tidy lab beeps (watermark doc L3-6); literal bird imitation as an end in itself (the
prettiest contestant, nightingale-cascade, was expensive and easy to confuse under smearing, per
`MimirBioacousticContestant.cs` profile note); a third payload bit on a second axis (measured loss).
6. Keep the generator deterministic from a typed description (contour, root, rhythm, speaker tint),
authored once and rendered, not regenerated in the audio callback. Contestants doc L493-496 states
this as the AquaSynth lesson: separate authoring intent from realtime DSP.
## 4. What does not transfer, or is unknown
- Harmony. Mimir emits one voice per speaker and decodes one stream; nothing in the research tests
simultaneous voices, intervals between Minds, consonance, or masking between concurrent songs.
Searched for "harmon"; the only hit is the `HarmonicNotch` anchor kind (an envelope notch used as a
timing anchor, `MimirBioacousticContestant.cs` ~L33, L231), not musical harmony.
- Orbiting spatialisation. Mimir's left/right split is a calibration device (one vocabulary per
speaker to learn each side of the room), not a perceptual pan or orbit. Nothing here informs it.
- Pleasantness. There is no listening test, no psychoacoustic metric, and no loudness-weighted score
in any file read. The only pleasantness evidence is the authored one-line verdicts on each profile in
`MimirBioacousticContestant.cs` L52-170 ("lab bird with a clipboard", "most plausible room sound",
"prettiest contestant") and the "wrong animal for a room" sentence. The score is
`realtime * timing * frequency * payload_bitrate` (contestants doc L39-59): decodability only.
Gain 0.021-0.030 is chosen for low audibility, not for pleasing anyone.
- Mimir's numbers are synthetic damage (mel-cepstral and log-mel warp/blur) plus a few Scarlett loopback
runs. The first physical room runs decoded mics only partially (contestants doc L355-395), and the
later live receipt's cardioid result was retracted as noise
(`calibration/bioacoustic/complex-contour-live-20260525-063229.md`, correction at watermark doc L225-230).
- The pipeline decodes against a known schedule and tiny candidate set; Aqua's listener is a human
mix, so none of the decoder scores say how distinguishable Minds are to a person.
- Not read: `src/Mimir.BufferSmoke` (the harness executable). It does not match a "bioacoustic" path
filter on the tree listing, so I read its documentation (`docs/bioacoustic-training-harness.md`) and
the `MimirBioacoustic*.cs` sources instead. The `artifacts/bioacoustic-training/` receipts were listed
but not opened beyond the summary text in the docs.
## 5. Open questions for Aqua
- What is the "decoder" for Aqua: a human listener, a classifier, or both? Constraints above only
hold against a machine decoder.
- Does a Mind keep one word for life, or does the grammar generate many songs sharing a timbre and root
(activity-dependent contour over a fixed identity)? Mimir only has fixed words.
- How many Minds, and how are roots allocated on the log axis when several sound at once? Mimir used 2
speaker variants per word and 128 words; harmony will change the spacing rule.
- Which dimension bends with activity (contour, rhythm density, gain) and which must stay fixed
(timbre, root)? Mimir has no activity channel to copy.
- Is a measured pleasantness proxy wanted (roughness, masking, loudness-weighted)? Mimir has none to reuse.
- Spatialised orbit plus a speaker-keyed timbre: if the pan moves, does identity still rest on timbre
alone? Mimir's per-side vocabulary is not a precedent.

View file

@ -20,3 +20,30 @@ directory whose ancestors hold no empty `package.json` (esbuild reads them).
Timings from SwiftShader are CPU time: use them for the split between passes and for before and Timings from SwiftShader are CPU time: use them for the split between passes and for before and
after of one change, never as a phone frame time. after of one change, never as a phone frame time.
## Ridge look sheet
Renders the Vienna cards (`public/ridge/vienna-6815bb9dca99`) lit for six sky states (dawn 2, morning 15, noon 55, golden 6, dusk -3, night -30 degrees of sun)
by a set of looks (`RidgeLook`, `src/app/features/scene/ridge/lightCards.ts`, the one owner of look values), one 480x270 canvas per cell at heading 0. The sky
behind a cell is the app's own (`makePhysicalSky` + `paintSky`, upscaled), without the sun disc, stars or clouds. Not shipped.
npx vite --port 5199 # from the repo root; the app's vite config serves the page and public/
http://localhost:5199/harness/scene/ridgeSheet.html # four presets x six skies
...ridgeSheet.html?preset=swiss # one preset (physical|swiss|poster|painterly)
...ridgeSheet.html?looks=%5B%7B%22label%22%3A%22no-ink%22%2C%22inkScale%22%3A0%7D%2C%7B%22label%22%3A%22hazy%22%2C%22hazeScale%22%3A8%7D%5D
...?w=640 # cell width
`looks=` is a url-encoded or base64 JSON array of `{label, ...partial RidgeLook}` and replaces the preset rows (`inkKeep` and `reliefLight` merge by key).
A cell costs one WebGL2 context and a card decode, so the full sheet takes tens of seconds (much longer in a background tab).
Presets (`PRESETS` in `ridgeSheet.ts`; swiss and poster take every key not named from `PHYSICAL_LOOK`, the rest from `DEFAULT_LOOK`, the painterly cel look), chosen by reasoning, not by eye, for Self to tune:
| preset | values |
| --- | --- |
| physical | PHYSICAL_LOOK (Lambert, no noise, sky haze, full ink) |
| swiss | reliefLight {mix 0.7, azimuthDeg -45, elevationDeg 40}, contrastByDistance 0.9, hazeScale 6, hazeTint [0, 0.05, 0.25], nearWarm 0.5, inkScale 0.6 |
| poster | reliefWeight 0.15, cardToneStep 0.25, cardGradient 0.5, inkKeep {edge 0.25, occlude 0.9, crease 1}, hazeScale 4 |
| painterly | DEFAULT_LOOK: groundNoise 0.35, cloudShadows 0.5, nearWarm 0.6, hazeScale 2, inkScale 0.4, celBands 3, celSoftness 0.05, celAmbientAway 0.7 |
| painterly-cel-2 / -3 / -4 | painterly with celBands 2 / 3 / 4 |
Night sets (`ridgeSheet.html`): `?moments=2026-11-24T22:00Z,2026-12-09T20:00Z` pins explicit UTC moments (the sun, moon and stars are those of the moment); `?night=1` renders the next new moon, first quarter and full moon from today (`&from=YYYY-MM-DD`) at four hours each (`&hours=18,21,0,4`, UTC) plus deep dusk of the full-moon evening; `&lines=1` draws the constellation lines (the Sky menu's hidden toggle). Use `&w=300` for the 13-column set. The night look's knobs: `NIGHT_LOOK` in `ridge/nightSky.ts` (star point spread, contrast exponents, moon size, earthshine, line opacity), `NIGHT_CEILING` and `SCOTOPIC` in `ridge/toneMap.ts`, the night `Budget` (key, targets, partial adaptation).

View file

@ -1,6 +1,5 @@
// Standalone page for the ridge scene: full window, no host app. `?tier=still|low|full` picks the // Standalone page for the ridge scene: full window, no host app. `?tier=still|low|full` picks the
// tier, `?probe=1` shows the rAF median/p95 readout. The bake record (each chunk's cost, from // tier, `?probe=1` shows the rAF median/p95 readout. The long tasks the page saw are on `window.longTasks`
// the scene's `onBake`) and the long tasks the page saw are on `window.bakes` and `window.longTasks`
// for a driver to read. Not shipped. // for a driver to read. Not shipped.
import { startBackgroundScene } from '../../src/app/features/scene'; import { startBackgroundScene } from '../../src/app/features/scene';
import type { SceneTier } from '../../src/app/features/scene'; import type { SceneTier } from '../../src/app/features/scene';
@ -8,8 +7,7 @@ import type { SceneTier } from '../../src/app/features/scene';
const q = new URLSearchParams(location.search); const q = new URLSearchParams(location.search);
const tier = (q.get('tier') ?? 'full') as SceneTier; const tier = (q.get('tier') ?? 'full') as SceneTier;
const canvas = document.getElementById('c') as HTMLCanvasElement; const canvas = document.getElementById('c') as HTMLCanvasElement;
const w = window as unknown as { scene: unknown; bakes: unknown[]; longTasks: number[]; firstViewMs: number }; const w = window as unknown as { scene: unknown; longTasks: number[]; firstViewMs: number };
w.bakes = [];
w.longTasks = []; w.longTasks = [];
try { try {
new PerformanceObserver((l) => l.getEntries().forEach((e) => w.longTasks.push(e.duration))).observe({ new PerformanceObserver((l) => l.getEntries().forEach((e) => w.longTasks.push(e.duration))).observe({
@ -21,7 +19,6 @@ try {
const t0 = performance.now(); const t0 = performance.now();
startBackgroundScene({ tier }, {}, { startBackgroundScene({ tier }, {}, {
canvas, canvas,
onBake: (b: unknown) => w.bakes.push(b),
} as never).then((scene) => { } as never).then((scene) => {
w.firstViewMs = performance.now() - t0; w.firstViewMs = performance.now() - t0;
w.scene = scene; w.scene = scene;

View file

@ -0,0 +1,8 @@
<!doctype html>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Ridge look sheet</title>
<body style="margin:0;background:#111;color:#ddd;font:12px monospace">
<div id="sheet" style="padding:8px"></div>
<script type="module" src="./ridgeSheet.ts"></script>
</body>

282
harness/scene/ridgeSheet.ts Normal file
View file

@ -0,0 +1,282 @@
// Look sheet for the lit ridge cards: the Vienna bake lit for a grid of sky states (or pinned moments) x looks, each cell a small canvas at heading 0. Not shipped.
// `?preset=all|physical|swiss|poster|painterly|painterly-cel-2|painterly-cel-3|painterly-cel-4` (default all: one row each; painterly is DEFAULT_LOOK); `?looks=<JSON array, url-encoded or base64>` replaces the rows with
// the given `{label, ...partial RidgeLook}` entries (inkKeep and reliefLight merge by key). `?w=480` sets the cell width, 16:9 unless `?h=` gives the height (`?w=375&h=812` is a phone).
// The sky behind a cell is the app's own: `makePhysicalSky` + `paintSky` upscaled smoothly, with the real stars and the moon (`nightBodies`),
// without the sun disc or clouds. Columns are the SKIES below (a sun elevation each, the stars and moon of the moment the sheet was opened), or:
// `?moments=2026-11-24T22:00Z,2026-12-09T20:00Z` explicit UTC moments: the sun, moon and stars are those of the moment, the state follows the sun's elevation
// `?night=1` the night set: the next new moon, first quarter and full moon from today (or from `?from=YYYY-MM-DD`), each at four night hours
// (`?hours=18,21,0,4` UTC), plus deep dusk (sun at -10 degrees) of the evening of the full moon
// `?labels=1` DEBUG: label each constellation chain in frame with its d3-celestial abbreviation (fetched from the source repository at run time; not shipped)
// `?lines=1` constellation lines over the stars, as the Sky menu's hidden toggle does (night cells only)
import { DEFAULT_LOOK, PHYSICAL_LOOK, lightCards } from '../../src/app/features/scene/ridge/lightCards';
import type { RidgeLook } from '../../src/app/features/scene/ridge/lightCards';
import { parseManifest } from '../../src/app/features/scene/ridge/manifest';
import { makePhysicalSky, paintSky } from '../../src/app/features/scene/ridge/physicalSky';
import { windowFor } from '../../src/app/features/scene/ridge/view';
import { nightBodies, onScreen, paintNightBodies } from '../../src/app/features/scene/ridge/nightBodies';
import { sunAt } from '../../src/app/features/scene/ridge/sunAt';
import { linesAt } from '../../src/app/features/scene/ridge/starCatalogue';
import { moonPhase } from '../../src/sky/moon.js';
import { DAY_FROM } from '../../src/app/features/scene/skyState';
import type { FixedSkyState } from '../../src/app/features/scene/skyState';
const DIR = '/public/ridge/vienna-6815bb9dca99/';
type Override = Partial<Omit<RidgeLook, 'inkKeep' | 'reliefLight'>> & {
label: string;
/** The look the unnamed keys come from (DEFAULT_LOOK, the painterly cel look, if absent). */
base?: 'physical';
inkKeep?: Partial<RidgeLook['inkKeep']>;
reliefLight?: Partial<RidgeLook['reliefLight']>;
};
interface Column {
label: string;
elevation?: number;
azimuth?: number;
/** A moment: the sun is the real one of it. */
time?: Date;
}
/** Sun elevation and compass azimuth of each column; the cards look at 214 +- 36. Elevation picks the display budget (day from DAY_FROM, night below its negative). */
const SKIES: Column[] = [
{ label: 'dawn 2 deg', elevation: 2, azimuth: 100 },
{ label: 'morning 15 deg', elevation: 15, azimuth: 135 },
{ label: 'noon 55 deg', elevation: 55, azimuth: 190 },
{ label: 'golden 6 deg', elevation: 6, azimuth: 244 },
{ label: 'dusk -3 deg', elevation: -3, azimuth: 262 },
{ label: 'night -30 deg', elevation: -30, azimuth: 0 },
];
/** The art directions, chosen by reasoning, not by eye: Self tunes them (values listed in harness/scene/README.md). */
const PRESETS: Record<string, Override> = {
physical: { label: 'physical', base: 'physical' },
swiss: {
label: 'swiss',
base: 'physical',
reliefLight: { mix: 0.7, azimuthDeg: -45, elevationDeg: 40 },
contrastByDistance: 0.9,
hazeScale: 6,
hazeTint: [0, 0.05, 0.25],
nearWarm: 0.5,
inkScale: 0.6,
},
poster: {
label: 'poster',
base: 'physical',
reliefWeight: 0.15,
cardToneStep: 0.25,
cardGradient: 0.5,
inkKeep: { edge: 0.25, occlude: 0.9, crease: 1 },
hazeScale: 4,
},
painterly: { label: 'painterly (default, cel 3)' },
'painterly-cel-2': { label: 'painterly-cel-2', celBands: 2 },
'painterly-cel-3': { label: 'painterly-cel-3', celBands: 3 },
'painterly-cel-4': { label: 'painterly-cel-4', celBands: 4 },
};
const merge = (o: Override): { label: string; look: RidgeLook } => {
const { label, base: baseName, inkKeep, reliefLight, ...rest } = o;
const base = baseName === 'physical' ? PHYSICAL_LOOK : DEFAULT_LOOK;
return {
label,
look: {
...base,
...rest,
inkKeep: { ...base.inkKeep, ...inkKeep },
reliefLight: { ...base.reliefLight, ...reliefLight },
},
};
};
function parseLooks(raw: string): Override[] {
const tries = [() => decodeURIComponent(raw), () => atob(raw.replace(/-/g, '+').replace(/_/g, '/'))];
for (const t of tries) {
try {
const v = JSON.parse(t());
if (Array.isArray(v)) return v.map((e, i) => ({ label: `look ${i + 1}`, ...e }));
} catch {
// try the next encoding
}
}
throw new Error('looks= is neither a url-encoded nor a base64 JSON array');
}
const q = new URLSearchParams(location.search);
const HOUR = 3_600_000;
/** The first moment at or after `from` the moon's elongation passes `target` degrees (new 0, first quarter 90, full 180). */
function nextPhase(from: Date, target: number): Date {
const err = (t: number) => ((moonPhase(t).elongationDeg - target + 540) % 360) - 180;
let t = from.getTime();
while (!(err(t) < 0 && err(t + HOUR) >= 0)) t += HOUR;
let a = t;
let b = t + HOUR;
for (let i = 0; i < 20; i += 1) {
const m = (a + b) / 2;
if (err(m) < 0) a = m;
else b = m;
}
return new Date(b);
}
/** The first evening moment (UTC hour steps of 10 minutes from `day`) the sun is at `deg` below the horizon, going down. */
function sunDownTo(place: Parameters<typeof sunAt>[0], day: Date, deg: number): Date {
let t = Date.UTC(day.getUTCFullYear(), day.getUTCMonth(), day.getUTCDate(), 12);
while (sunAt(place, new Date(t)).elevation > -deg) t += 10 * 60_000;
return new Date(t);
}
const fmt = (d: Date) => d.toISOString().slice(0, 16).replace('T', ' ') + 'Z';
function momentsFrom(params: URLSearchParams, place: Parameters<typeof sunAt>[0]): Column[] | undefined {
const list = params.get('moments');
if (list)
return list.split(',').map((iso) => {
const time = new Date(iso.trim());
if (Number.isNaN(time.getTime())) throw new Error(`moments=: ${iso} is not a date`);
return { label: fmt(time), time };
});
if (!params.get('night')) return undefined;
const from = params.get('from') ? new Date(`${params.get('from')}T00:00:00Z`) : new Date();
const hours = (params.get('hours') ?? '18,21,0,4').split(',').map(Number);
const cols: Column[] = [];
const phases: [string, number][] = [['new', 0], ['first quarter', 90], ['full', 180]];
phases.forEach(([name, deg]) => {
const peak = nextPhase(from, deg);
const day = Date.UTC(peak.getUTCFullYear(), peak.getUTCMonth(), peak.getUTCDate());
hours.forEach((h) => {
// Hours before 12 belong to the night that ends the day of the phase, so the hours run on from the evening.
const time = new Date(day + (h < 12 ? 24 + h : h) * HOUR);
cols.push({ label: `${name} ${fmt(time)}`, time });
});
if (deg === 180) cols.push({ label: `deep dusk, full moon ${fmt(sunDownTo(place, peak, 10))}`, time: sunDownTo(place, peak, 10) });
});
return cols;
}
const preset = q.get('preset');
const pinned = q.get('moments') || q.get('night');
const rows = (q.get('looks')
? parseLooks(q.get('looks') as string)
: preset && preset !== 'all'
? [PRESETS[preset] ?? PRESETS.physical]
: pinned
? [PRESETS.painterly] // a night set is read in the default look unless a preset or looks say otherwise
: Object.values(PRESETS)
).map(merge);
const withLines = q.get('lines') === '1';
const LINES_JSON = 'https://raw.githubusercontent.com/ofrohn/d3-celestial/master/data/constellations.lines.json';
/** Debug: the constellation id of each packed chain, in the generator's order (feature by feature, chain by chain). */
async function chainIds(): Promise<string[]> {
const gj = await (await fetch(LINES_JSON)).json();
return gj.features.flatMap((f: { id: string; geometry: { coordinates: unknown[] } }) => f.geometry.coordinates.map(() => f.id));
}
const W = Number(q.get('w') ?? 480);
const H = q.get('h') ? Number(q.get('h')) : Math.round((W * 9) / 16);
const root = document.getElementById('sheet') as HTMLElement;
const stateOf = (el: number): FixedSkyState =>
el >= DAY_FROM ? 'day' : el <= -DAY_FROM ? 'night' : 'dusk';
async function main() {
const manifest = parseManifest(await (await fetch(`${DIR}manifest.json`)).json(), DIR);
const blobs = await Promise.all(
manifest.cards.map(async (c) => ({
colour: await (await fetch(`${DIR}${c.colour}`)).blob(),
geometry: await (await fetch(`${DIR}${c.geometry}`)).blob(),
}))
);
const decode = (b: Blob) =>
createImageBitmap(b, { premultiplyAlpha: 'none', colorSpaceConversion: 'none' });
const { view } = manifest;
const win = windowFor(view, W, H);
const now = new Date();
const columns = momentsFrom(q, view.place) ?? SKIES;
const ids = q.get('labels') === '1' ? await chainIds() : undefined;
const table = document.createElement('table');
table.style.borderSpacing = '4px';
root.append(table);
const head = table.insertRow();
head.insertCell();
columns.forEach((c) => (head.insertCell().textContent = c.label));
const tr = rows.map((r) => {
const row = table.insertRow();
row.insertCell().textContent = r.label;
return row;
});
for (const col of columns) {
const time = col.time ?? now;
const sun =
col.time !== undefined
? sunAt(view.place, col.time)
: { elevation: col.elevation as number, azimuth: col.azimuth as number, time };
const physical = makePhysicalSky(stateOf(sun.elevation), time, 0, view, sun);
const px = paintSky(physical, W, H, win.camera);
const bodies = nightBodies(physical, px, withLines);
const small = document.createElement('canvas');
small.width = px.w;
small.height = px.h;
const sctx = small.getContext('2d') as CanvasRenderingContext2D;
const img = sctx.createImageData(px.w, px.h);
img.data.set(px.data);
sctx.putImageData(img, 0, 0);
for (let r = 0; r < rows.length; r += 1) {
const bitmaps = await Promise.all(
blobs.map(async (b) => ({
colour: await decode(b.colour),
geometry: await decode(b.geometry),
}))
);
const cards = lightCards(manifest, bitmaps, physical, rows[r].look);
const cell = document.createElement('canvas');
cell.width = W;
cell.height = H;
const ctx = cell.getContext('2d') as CanvasRenderingContext2D;
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(small, 0, 0, W, H);
paintNightBodies(ctx, bodies, W, H, 1);
if (ids) {
// Debug labels: each chain's id at the mean of its vertices that lie in the frame.
ctx.font = '11px monospace';
ctx.fillStyle = '#ffd24a';
linesAt(physical.sun.time, view.place.lat, view.place.lon).forEach((chain, i) => {
const pts = chain.map((p) => onScreen(win.camera, p.azimuth, p.elevation)).filter((a) => a.x >= 0 && a.x <= 1 && a.y >= 0 && a.y <= 1);
if (!pts.length) return;
const mx = pts.reduce((a, p) => a + p.x, 0) / pts.length;
const my = pts.reduce((a, p) => a + p.y, 0) / pts.length;
ctx.fillText(`${ids[i]} ${pts.length}/${chain.length}`, mx * W, my * H);
});
}
// As Ridge.ts paintCards at heading 0: farthest first, each card at its own scale about the horizon row of the plane.
const s = win.plane.scale;
const x0 = (W - win.plane.w) / 2;
const planeTop = H - (win.plane.h + win.plane.bottom);
const ox = x0 + win.plane.w / 2;
const oy = planeTop + view.horizonRow * s;
for (let k = cards.length - 1; k >= 0; k -= 1) {
ctx.save();
ctx.translate(ox, oy);
ctx.scale(cards[k].scale, cards[k].scale);
ctx.drawImage(
cards[k].canvas,
x0 - ox,
planeTop + cards[k].top * s - oy,
win.plane.w,
cards[k].h * s
);
ctx.restore();
}
tr[r].insertCell().append(cell);
}
}
document.title = 'ridge look sheet: done';
}
main().catch((e) => {
console.error(e);
root.textContent = `ridge look sheet failed: ${e}`;
});

View file

@ -1,12 +1,13 @@
{ {
"name": "Ratatoskr", "name": "Ratatoskr",
"short_name": "Ratatoskr", "short_name": "Ratatoskr",
"id": "/",
"description": "GameCult's Matrix client", "description": "GameCult's Matrix client",
"dir": "auto", "dir": "auto",
"lang": "en-US", "lang": "en-US",
"display": "standalone", "display": "standalone",
"orientation": "portrait",
"start_url": "./", "start_url": "./",
"scope": "./",
"background_color": "#07111a", "background_color": "#07111a",
"theme_color": "#07111a", "theme_color": "#07111a",
"icons": [ "icons": [
@ -54,6 +55,12 @@
"src": "./public/android/android-chrome-512x512.png", "src": "./public/android/android-chrome-512x512.png",
"sizes": "512x512", "sizes": "512x512",
"type": "image/png" "type": "image/png"
},
{
"src": "./public/android/android-chrome-maskable-512x512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
} }
] ]
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

7
public/ridge/index.json Normal file
View file

@ -0,0 +1,7 @@
{
"schema": 1,
"default": "vienna",
"places": {
"vienna": "vienna-6815bb9dca99"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

View file

@ -0,0 +1,100 @@
{
"schema": 2,
"baker_version": 2,
"bake_id": "6815bb9dca99",
"place": {
"id": "vienna",
"name": "Vienna, looking SW to Rax/Schneeberg",
"lat": 48.1929826,
"lon": 16.3534237,
"altitude_km": 0.18330000000000002,
"eye_m": 213.3
},
"view": {
"look_az_deg": 214.0,
"plane_h": 600,
"px_per_deg_h": 17.77777777777778,
"px_per_deg_v": 177.77777777777777,
"exaggeration": 10.0,
"horizon_row": 294.58455032829386,
"sky_row": 24.0,
"near_row": 396.0,
"window_deg": 72,
"plane_w": 1280
},
"curvature": {
"r_earth_m": 6371000.0,
"k_ref": 0.13
},
"encoding": {
"log_d_min": 6.214608098422191,
"log_d_max": 11.462786662662916,
"normal": "rt8"
},
"camera": {
"r_m": 200.0,
"heading_max_deg": 23.0
},
"cards": [
{
"top": 182,
"h": 418,
"near_m": null,
"far_m": 5392.093596252347,
"median_m": 1478.456787109375,
"distance_m": 1478.456787109375,
"scale": 1.1564386078720779,
"colour": {
"file": "card-0-colour.webp",
"bytes": 4598
},
"geometry": {
"file": "card-0-geometry.webp",
"bytes": 95716
}
},
{
"top": 24,
"h": 576,
"near_m": 5392.093596252347,
"far_m": 39877.08347165139,
"median_m": 11107.0283203125,
"distance_m": 11107.0283203125,
"scale": 1.0183368002838622,
"colour": {
"file": "card-1-colour.webp",
"bytes": 8396
},
"geometry": {
"file": "card-1-geometry.webp",
"bytes": 130870
}
},
{
"top": 40,
"h": 560,
"near_m": 39877.08347165139,
"far_m": null,
"median_m": 48378.26953125,
"distance_m": 48378.26953125,
"scale": 1.0041512491408657,
"colour": {
"file": "card-2-colour.webp",
"bytes": 9718
},
"geometry": {
"file": "card-2-geometry.webp",
"bytes": 118378
}
}
],
"w": 1280,
"h": 600,
"bytes": 367676,
"attribution": {
"credit_line": "Contains modified Copernicus data: DEM \u00a9 DLR e.V. 2010-2014 and \u00a9 Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved.",
"licence": "Copernicus DEM licence: free, full and open access, with the credit line shown",
"dem_source": "Copernicus DEM GLO-30 (30 m)",
"url": "https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model"
}
}

View file

@ -1,123 +0,0 @@
#!/usr/bin/env python3
"""Bake the 360 degree horizon seen from the ridge viewpoint (src/app/features/scene/ridge/vienna.ts: VIENNA) into
src/app/features/scene/ridge/viennaHorizon.json: per azimuth, the highest elevation angle the terrain subtends, the distance and
height of the point that sets it, and the surface slope there (the normal). The source is Copernicus DEM GLO-30, a DSM (it
includes buildings and trees, which is what a horizon is made of). Source, licence and attribution go beside the bake, in its
`source` block, so the file cannot travel without them.
python3 scripts/bake-horizon.py <dir with the nine Copernicus_DSM_COG_10_N{47..49}_00_E{015..017}_00_DEM.tif> [out.json]
Needs numpy, tifffile, imagecodecs (pip, in a venv: this is a build-time tool, the bake is committed).
"""
import json
import math
import sys
from pathlib import Path
import numpy as np
import tifffile
LAT, LON = 48.1929826, 16.3534237 # the server location Meta gave, 2026-11-11; keep equal to VIENNA in vienna.ts
STEP_DEG = 0.5
RADIUS_KM = 60.0
EARTH_R = 6_371_000.0
REFRACTION_K = 0.13 # standard terrestrial refraction: effective radius R / (1 - k)
EYE_ABOVE_GROUND = 0.0 # the viewpoint is the DSM surface at the point (a roof, in a city); the page lifts it with VIENNA.altitudeKm
MIN_KM = 1.0 # the DSM at 30 m cannot resolve neighbouring buildings as a horizon; nearer than this is not ridge
class Mosaic:
def __init__(self, folder: Path):
self.tiles = {}
for p in sorted(folder.glob("Copernicus_DSM_COG_10_N*_E*_DEM.tif")):
lat0 = int(p.name.split("_N")[1][:2])
lon0 = int(p.name.split("_E")[1][:3])
with tifffile.TiffFile(p) as t:
self.tiles[(lat0, lon0)] = t.pages[0].asarray()
def height(self, lat: float, lon: float) -> float:
key = (math.floor(lat), math.floor(lon))
a = self.tiles.get(key)
if a is None:
return float("nan")
n = a.shape[0]
# Tile origin is the north-west corner; pixels are 1/n degree, pixel-is-area (centre at +0.5).
y = (key[0] + 1 - lat) * n - 0.5
x = (lon - key[1]) * n - 0.5
y0, x0 = int(math.floor(y)), int(math.floor(x))
y0 = min(max(y0, 0), n - 2)
x0 = min(max(x0, 0), n - 2)
fy, fx = min(max(y - y0, 0), 1), min(max(x - x0, 0), 1)
top = a[y0, x0] * (1 - fx) + a[y0, x0 + 1] * fx
bot = a[y0 + 1, x0] * (1 - fx) + a[y0 + 1, x0 + 1] * fx
return float(top * (1 - fy) + bot * fy)
def offset(lat: float, lon: float, az_deg: float, d_m: float):
az = math.radians(az_deg)
dlat = d_m * math.cos(az) / 111_320.0
dlon = d_m * math.sin(az) / (111_320.0 * math.cos(math.radians(lat)))
return lat + dlat, lon + dlon
def main() -> None:
folder = Path(sys.argv[1])
out = Path(sys.argv[2]) if len(sys.argv) > 2 else Path("src/app/features/scene/ridge/viennaHorizon.json")
m = Mosaic(folder)
h0 = m.height(LAT, LON) + EYE_ABOVE_GROUND
az_count = int(360 / STEP_DEG)
elev, dist, peak, east, north = [], [], [], [], []
for i in range(az_count):
az = i * STEP_DEG
best, best_d, best_h, best_pt = -90.0, 0.0, h0, (LAT, LON)
d = MIN_KM * 1000
while d <= RADIUS_KM * 1000:
lat, lon = offset(LAT, LON, az, d)
h = m.height(lat, lon)
if not math.isnan(h):
drop = d * d / (2 * EARTH_R) * (1 - REFRACTION_K)
ang = math.degrees(math.atan2(h - h0 - drop, d))
if ang > best:
best, best_d, best_h, best_pt = ang, d, h, (lat, lon)
d += 30.0 if d < 5000 else 60.0 if d < 20000 else 120.0
# Surface slope at the peak (rise per metre, east and north), central difference over 60 m.
la, lo = best_pt
dl, dn = 60.0 / 111_320.0, 60.0 / (111_320.0 * math.cos(math.radians(la)))
ge = (m.height(la, lo + dn) - m.height(la, lo - dn)) / 120.0
gn = (m.height(la + dl, lo) - m.height(la - dl, lo)) / 120.0
elev.append(round(best, 3))
dist.append(round(best_d / 1000, 2))
peak.append(round(best_h, 1))
east.append(round(ge, 3))
north.append(round(gn, 3))
doc = {
"viewpoint": {"lat": LAT, "lon": LON, "groundM": round(h0, 1)},
"stepDeg": STEP_DEG,
"radiusKm": RADIUS_KM,
"minKm": MIN_KM,
"curvature": f"drop d^2/2R*(1-{REFRACTION_K}), R={int(EARTH_R)} m",
"source": {
"dataset": "Copernicus DEM GLO-30 (COP-DEM_GLO-30-DGED), a DSM, EGM2008 heights, 1 arc-second grid",
"tiles": sorted(f"N{a:02d}_00_E{b:03d}_00" for a, b in m.tiles),
"tileBytesEach": "about 42-44 MB (Cloud Optimized GeoTIFF); nine tiles, about 380 MB, read once, not committed",
"url": "https://copernicus-dem-30m.s3.amazonaws.com/ (AWS Open Data, eu-central-1, no account)",
"licence": "Copernicus DEM licence: free of charge for any use incl. commercial, attribution required, no warranty "
"(https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model, Licencing)",
"attribution": "Contains modified Copernicus data: DEM © DLR e.V. 2010-2014 and © Airbus Defence and Space GmbH 2014-2018 "
"provided under COPERNICUS by the European Union and ESA; all rights reserved.",
"bakedBy": "scripts/bake-horizon.py",
},
"elevationDeg": elev,
"distanceKm": dist,
"peakHeightM": peak,
"slopeEast": east,
"slopeNorth": north,
}
out.write_text(json.dumps(doc, separators=(",", ":")) + "\n")
top = int(np.argmax(elev))
print(f"ground {h0:.1f} m; {az_count} azimuths; highest {elev[top]:.2f} deg at az {top * STEP_DEG}, {dist[top]} km, {peak[top]} m")
print(f"wrote {out} ({out.stat().st_size} bytes)")
if __name__ == "__main__":
main()

56
scripts/buildSha.js Normal file
View file

@ -0,0 +1,56 @@
// The commit a bundle was built from, stamped into its index.html as <meta name="build-sha">, so a built
// folder says what it is without a build log: `grep -o 'build-sha" content="[^"]*' dist/index.html`.
// Where git governs the tree (REPO_DIR is a repository root) git decides: HEAD, suffixed -dirty when the tree has
// uncommitted changes, or `<BUILD_SHA>-mismatch` when an explicit BUILD_SHA names a different commit, so a stamp
// never vouches for code it does not hold; a git failure there is 'unknown'. Where git does not govern (a source
// archive), a full-sha BUILD_SHA stands, else 'unknown'.
import { execFileSync } from 'child_process';
import { dirname, resolve } from 'path';
import { fileURLToPath } from 'url';
const REPO_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '..');
// Vite writes vite.config.js.timestamp-*.mjs next to the config while it loads it; that file is the
// build's own, not source, so an UNTRACKED one must not mark the tree dirty. A tracked file of that name,
// or any other change, still does. Filtering status lines (not a pathspec) is what keeps it untracked-only.
const VITE_TEMP = /^\?\? (?:.*\/)?vite\.config\.[a-z]+\.timestamp-\d+-[0-9a-f]+\.mjs$/;
export const gitIn =
(cwd) =>
(...args) =>
execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
const FULL_SHA = /^[0-9a-f]{40}$/;
export const readBuildSha = (env = process.env, run = gitIn(REPO_DIR)) => {
const fromEnv = (env.BUILD_SHA ?? '').trim();
const explicit = FULL_SHA.test(fromEnv) ? fromEnv : null;
// Git governs this tree only when REPO_DIR is its root: a source archive unpacked inside some other
// repository has no git of its own, and that repository's HEAD says nothing about it.
let governed;
try {
governed = run('rev-parse', '--show-prefix').trim() === '';
} catch {
governed = false;
}
if (!governed) return explicit ?? 'unknown';
// Git governs and answers: from here a failure is 'unknown', never the bare explicit sha.
try {
const head = run('rev-parse', 'HEAD').trim();
if (!FULL_SHA.test(head)) return 'unknown';
if (explicit && explicit !== head) return `${explicit}-mismatch`;
const dirty = run('status', '--porcelain', '-uall', '--', '.')
.split('\n')
.some((l) => l.trim() !== '' && !VITE_TEMP.test(l));
return dirty ? `${head}-dirty` : head;
} catch {
return 'unknown';
}
};
export const buildShaPlugin = (sha = readBuildSha()) => ({
name: 'ratatoskr-build-sha',
transformIndexHtml: () => [
{ tag: 'meta', attrs: { name: 'build-sha', content: sha }, injectTo: 'head-prepend' },
],
});

170
scripts/buildSha.test.js Normal file
View file

@ -0,0 +1,170 @@
import { execFileSync } from 'child_process';
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { afterEach, describe, expect, it } from 'vitest';
import { buildShaPlugin, gitIn, readBuildSha } from './buildSha';
const SHA = 'b6b1d522f1c0a9d3e2b4c5d6e7f8091a2b3c4d5e';
const gitAt =
(head, status = '') =>
(cmd, ...args) =>
cmd === 'rev-parse' ? (args[0] === '--show-prefix' ? '\n' : `${head}\n`) : status;
describe('readBuildSha', () => {
it('reads the checkout it is built from', () => {
expect(readBuildSha({}, gitAt(SHA))).toBe(SHA);
});
it('marks a tree with uncommitted changes, so a stamp never vouches for code it does not hold', () => {
expect(readBuildSha({}, gitAt(SHA, ' M src/x.ts\n'))).toBe(`${SHA}-dirty`);
});
it('lets BUILD_SHA stand in where there is no git, and ignores a value that is not a full sha', () => {
const noGit = () => {
throw new Error('not a git repository');
};
expect(readBuildSha({ BUILD_SHA: SHA }, noGit)).toBe(SHA);
expect(readBuildSha({ BUILD_SHA: SHA }, gitAt(SHA))).toBe(SHA);
// a different HEAD is a mismatch, not a clean stamp of the explicit sha
expect(readBuildSha({ BUILD_SHA: SHA }, gitAt('c'.repeat(40)))).toBe(`${SHA}-mismatch`);
// a value that is not a lowercase full sha is ignored
['b6b1d52', SHA.toUpperCase(), `${SHA}0`].forEach((v) =>
expect(readBuildSha({ BUILD_SHA: v }, noGit)).toBe('unknown')
);
// git that answers but cannot say what the tree holds fails closed
const brokenStatus = (cmd, ...args) => {
if (cmd === 'status') throw new Error('index file smaller than expected');
return args[0] === '--show-prefix' ? '\n' : `${SHA}\n`;
};
expect(readBuildSha({ BUILD_SHA: SHA }, brokenStatus)).toBe('unknown');
expect(readBuildSha({}, brokenStatus)).toBe('unknown');
expect(readBuildSha({}, gitAt('nope'))).toBe('unknown');
// inside another repository's subfolder git does not govern: the explicit sha stands
const nested = (cmd, ...args) => (args[0] === '--show-prefix' ? 'vendor/ratatoskr/\n' : SHA);
expect(readBuildSha({ BUILD_SHA: SHA }, nested)).toBe(SHA);
expect(readBuildSha({}, nested)).toBe('unknown');
expect(readBuildSha({ BUILD_SHA: 'main' }, noGit)).toBe('unknown');
});
it("says 'unknown' rather than failing the build when git is absent", () => {
expect(
readBuildSha({}, () => {
throw new Error('spawn git ENOENT');
})
).toBe('unknown');
});
});
describe('readBuildSha against a real repository', () => {
const made = [];
afterEach(() => {
made.splice(0).forEach((d) => rmSync(d, { recursive: true, force: true }));
});
const repo = () => {
const dir = mkdtempSync(join(tmpdir(), 'buildsha-'));
made.push(dir);
const g = (...a) => execFileSync('git', a, { cwd: dir, stdio: 'ignore' });
g('init', '-q');
mkdirSync(join(dir, 'src'));
writeFileSync(join(dir, 'src', 'a.ts'), 'export {};\n');
g('add', '.');
g('-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'x');
return dir;
};
it("stays clean with vite's temp config file present, and is dirty with a stray source file", () => {
const dir = repo();
const run = gitIn(dir);
writeFileSync(join(dir, 'vite.config.js.timestamp-1700000000-abc123.mjs'), '');
expect(readBuildSha({}, run)).toMatch(/^[0-9a-f]{40}$/);
writeFileSync(join(dir, 'src', 'zz-stray.ts'), '');
expect(readBuildSha({}, run)).toMatch(/^[0-9a-f]{40}-dirty$/);
});
});
describe('readBuildSha dirty rules against a real repository', () => {
const made2 = [];
afterEach(() => {
made2.splice(0).forEach((d) => rmSync(d, { recursive: true, force: true }));
});
const TEMP = 'vite.config.js.timestamp-1700000000-abc123.mjs';
const repo2 = (tracked = []) => {
const dir = mkdtempSync(join(tmpdir(), 'buildsha-'));
made2.push(dir);
const g = (...a) => execFileSync('git', a, { cwd: dir, stdio: 'ignore' });
g('init', '-q');
mkdirSync(join(dir, 'src'));
writeFileSync(join(dir, 'src', 'a.ts'), 'export {};\n');
tracked.forEach((f) => writeFileSync(join(dir, f), 'x\n'));
g('add', '.');
g('-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'x');
return {
dir,
head: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: dir, encoding: 'utf8' }).trim(),
};
};
it('does not let an explicit BUILD_SHA mask a dirty tree', () => {
const { dir, head } = repo2();
const run = gitIn(dir);
expect(readBuildSha({ BUILD_SHA: head }, run)).toBe(head);
writeFileSync(join(dir, 'src', 'zz-stray.ts'), '');
expect(readBuildSha({ BUILD_SHA: head }, run)).toBe(`${head}-dirty`);
});
it('lets git speak only for a tree whose root it is: an archive unpacked inside another repository keeps its explicit sha', () => {
const { dir } = repo2();
const inner = join(dir, 'vendor', 'ratatoskr');
mkdirSync(inner, { recursive: true });
writeFileSync(join(inner, 'x.ts'), '');
expect(readBuildSha({ BUILD_SHA: SHA }, gitIn(inner))).toBe(SHA);
expect(readBuildSha({}, gitIn(inner))).toBe('unknown');
});
it("notices an untracked .mjs that is not vite's temp file", () => {
const { dir, head } = repo2();
writeFileSync(join(dir, 'foo.mjs'), '');
expect(readBuildSha({}, gitIn(dir))).toBe(`${head}-dirty`);
rmSync(join(dir, 'foo.mjs'));
// only vite's exact shape is its own: vite.config.<ext>.timestamp-<digits>-<hex>.mjs
[
'vite.config.js.timestamp-1-ab.mjs.bak',
'vite.config.js.timestamp-x-ab.mjs',
'vite.config.js.timestamp-1-zz.mjs',
'vite.config.a.b.timestamp-1-ab.mjs',
'vite.config.js.timestamp-1-ab-c.mjs',
].forEach((name) => {
writeFileSync(join(dir, name), '');
expect(readBuildSha({}, gitIn(dir)), name).toBe(`${head}-dirty`);
rmSync(join(dir, name));
});
expect(readBuildSha({}, gitIn(dir))).toBe(head);
});
it('treats a stray source file as dirty even beside the vite temp file, in the root or a subfolder', () => {
const { dir, head } = repo2();
const run = gitIn(dir);
writeFileSync(join(dir, TEMP), '');
writeFileSync(join(dir, 'src', TEMP), '');
expect(readBuildSha({}, run)).toBe(head);
writeFileSync(join(dir, 'src', 'zz-stray.ts'), '');
expect(readBuildSha({}, run)).toBe(`${head}-dirty`);
});
it('marks a tracked file of the temp name dirty once it changes', () => {
const { dir, head } = repo2([TEMP]);
const run = gitIn(dir);
expect(readBuildSha({}, run)).toBe(head);
writeFileSync(join(dir, TEMP), 'changed\n');
expect(readBuildSha({}, run)).toBe(`${head}-dirty`);
});
it('marks an untracked file in a new folder dirty (status lists files, not the folder)', () => {
const { dir, head } = repo2();
mkdirSync(join(dir, 'new'));
writeFileSync(join(dir, 'new', TEMP), '');
expect(readBuildSha({}, gitIn(dir))).toBe(head);
writeFileSync(join(dir, 'new', 'b.ts'), '');
expect(readBuildSha({}, gitIn(dir))).toBe(`${head}-dirty`);
});
});
describe('buildShaPlugin', () => {
it("hands vite a meta tag for the page's head carrying the sha", () => {
const plugin = buildShaPlugin(SHA);
expect(plugin.transformIndexHtml()).toEqual([
{ tag: 'meta', attrs: { name: 'build-sha', content: SHA }, injectTo: 'head-prepend' },
]);
});
});

1
scripts/ridge-bake/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
__pycache__/

View file

@ -0,0 +1,48 @@
# ridge-bake
Offline baker for the ridge backdrop: it turns a Copernicus DEM into K+1 G-buffer cards per place, split by K authored seams, plus a `manifest.json` (schema 2) and an `index.json` that the runtime reads. Each card is a colour WebP (albedo and coverage) and a geometry WebP (normal and log-distance). The baker is not shipped; `public/ridge/` holds its output. The client owns lighting, haze and ink: no sun, haze or shadow is baked.
## Run
```sh
python3 -I scripts/ridge-bake/export.py <place-id> --tiles DIR --out public/ridge/ [--work DIR] [--sheet contact.png]
```
Needs Python 3 with `numpy`, `tifffile` and `imagecodecs`. `--tiles` is a directory of Copernicus GLO-30 tiles (never committed); `--work` caches the mosaic and rays (default `$TMPDIR/ridge-bake-work`); `--sheet` writes the contact sheet (the composite, every card alone and the depth image with every seam, lit by one fixed light). `python3 -I scripts/ridge-bake/export.py --write-schema` rewrites `ridge-bake.schema.json`, which the tests pin.
Tests: `RIDGE_PY=<python> RIDGE_TILES=DIR scripts/ridge-bake/tests/run.sh [test_ridge.py|mutate.py]` (`mutate.py` re-introduces each rule's failure into a copy of the baker and fails if a test does not notice).
## Tiles per preset (`places.json`)
Files are `Copernicus_DSM_COG_10_<N|S>dd_00_<E|W>ddd_00_DEM.tif`; the list below is `<N|S>dd<E|W>ddd`.
| place id | tiles |
|---|---|
| vienna | N47E015 N47E016 N47E017 N48E015 N48E016 N48E017 N49E015 N49E016 |
| matterhorn | N45E007 N45E008 N46E007 N46E008 |
| fuji | N34E138 N34E139 N35E137 N35E138 N35E139 |
| halfdome | N37W121 N37W120 N38W120 |
| amadablam | N27E086 N27E087 N28E086 N28E087 |
| trecime | N46E011 N46E012 |
## Cards
`places.json` gives each preset `card_split_km`, an ordered list of 1 to 5 seam depths in km, and optionally `prefilter_m`. A preset without `card_split_km` is refused, and so is a split that leaves a card empty (the message names the splits); K splits make K+1 cards, at most `MAX_CARDS` = 6 per place. New places get a seam probe look before their first bake.
1. **March.** `stage0` marches 6400 azimuth columns of rays over the DEM with Earth curvature and refraction (`ridge.elev`), cached by a key of its inputs.
2. **Low-pass.** `prefilter` blurs the sampled heights with a Gaussian of `prefilter_m` metres along each ray and across rays at equal distance (sigma = `prefilter_m` / (distance x column width) columns), then recomputes the angles. Roofs go, hills stay.
3. **View.** `set_view` maps angle to row linearly: the highest skyline angle in the window sits at 4% of the frame height, the lowest at 66%, clamped to 1x to 10x vertical exaggeration.
4. **Seams.** `coverage` counts the visible rows of the opaque view per log-distance bin and column. `seams` finds one seam per authored split per column by dynamic programming (seam carving, forward energy): it sits in a gap between depths, moving it costs 2 per bin plus the visible rows it sweeps (so it never hops across a ridge between two columns and splits it side by side), a seam inside visible terrain is cheap to cross-fade, the authored depth only breaks ties. Seam k stays 0.4 nat beyond seam k-1.
5. **Cards.** `cards` makes card i from the first visible hit at or beyond seam i-1 (layered depth: a farther card keeps the terrain a nearer ridge hides), alpha 1 minus a smoothstep over seam i in log-distance (the cross-fade), crest rows with fractional coverage, distance and normal interpolated between samples by angle, albedo from a small height and slope material, cropped to the rows where alpha is not zero. The rows of card i > 0 below the angle of its first sample (hit and first sample of the card) are its **wall**: the extruded face of the ridge the card starts at, which keeps that sample's distance, wears the ground material at its height with the face up, and is flagged `wall` (card 0 has none: its rows there are the ground). The alpha-over composite of the cards equals the opaque view; `check_cover` refuses a bake that differs by more than 0.02.
6. **Camera.** `CAMERA_R_M` (+200 m, signed: + forward, - backward; `camera_r_m` in `places.json` per place) and `HEADING_MAX_DEG` (23) are the camera on a circle round the bake centre (ruling `ridge-camera-on-circle`). `pack` gives each card `distance_m` (the median distance of its solid pixels that are not wall; `median_m` is the same number) and `scale = distance_m / (distance_m - r)`, the card's pan rate per unit of heading and its static size. It refuses `|r|` at or above half the nearest card's distance, a card with no solid terrain apart from its wall, and (in `write_bake`) a camera that lifts the nearest card off the frame bottom (every backward `r`: the bake is not wider and taller yet) or shrinks a card below what a 16:9 viewport needs at rest.
7. **Normals.** `normals` takes the along-ray slope and the across-ray slope at equal distance (neighbouring columns, same sample), both times the vertical exaggeration.
Files per card `i`: `card-<i>-colour.webp` (lossy RGB albedo, lossless straight alpha) and `card-<i>-geometry.webp` (lossless: R, G = (n + 1) / 2 for the normal's along and across components, B = log-distance normalised between `encoding.log_d_min` and `log_d_max`; wall pixels write R = G = 255, a code outside the unit disc that no real normal reaches). The manifest lists the cards nearest first with their row band (`top`, `h`), median seam depths, `distance_m`, `scale` and files, and the `camera` {`r_m`, `heading_max_deg`}; the runtime paints the list last to first. `check_budget` refuses more than `MAX_CARDS` cards, more than 1.5 MB of card files, or more than 20 MB decoded (2 textures x width x band rows x 4 bytes per card); a cap is never raised to fit a bake.
## Licence
Elevation: Copernicus DEM GLO-30. The credit line is written into every manifest (`attribution`) and must be shown with any rendering:
> Contains modified Copernicus data: DEM © DLR e.V. 2010-2014 and © Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved.
Licence: free, full and open access, with the credit line shown (https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model).

View file

@ -0,0 +1,206 @@
"""Ridge backdrop export: bake a place with ridge.py and write its K+1 G-buffer cards (colour + geometry WebP each), a manifest v2 and the index.
python3 -I scripts/ridge-bake/export.py <place-id> --tiles DIR --out public/ridge/ [--work DIR] [--sheet contact.png]
python3 -I scripts/ridge-bake/export.py --write-schema (rewrites ridge-bake.schema.json from SCHEMA below)
The runtime reads manifest.json (SCHEMA is its contract) and nothing else about the bake; the camera (ruling ridge-camera-on-circle) is the baker's, so per-card scale and the heading range ride the manifest; it lights the cards itself (ruling ridge-cards-runtime-lit). The pure parts (budget, bake_id, manifest, index, schema check)
import no baker; bake_place imports ridge, which needs RIDGE_TILES and RIDGE_WORK (main sets them from --tiles / --work)."""
import os, sys, json, math, shutil, hashlib, argparse, tempfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import numpy as np, imagecodecs
BAKER_VERSION = 2
WINDOW_DEG = 72
PLANE_W = 1280 # every card is the whole 72 deg window wide
PLANE_W_MAX = 4096
MAX_CARDS = 6 # per place; a full-frame card decodes to 2 textures x 1280 x 600 x 4 B = 6.1 MB, the decode budget below holds 3 of them and cropping to the row band is what lets a livelier place have more
TOTAL_BYTES_MAX = 1_500_000 # every card file of a place together
DECODE_BYTES_MAX = 20_000_000 # the cards decoded: sum over cards of 2 textures x w x band h x 4 bytes
COVER_TOL = 0.02 # the composite of the cards may differ from the opaque view by this much of a pixel, nowhere more
CAMERA_R_M = 200.0 # ruling ridge-camera-on-circle: the camera sits on a circle of this radius round the bake centre, signed, + forward along its heading and - backward; places.json may set camera_r_m per place. The steward's calibration for feel, tuned in the art pass
HEADING_MAX_DEG = 23.0 # the drift's heading range each side of look_az: today's phone sweep, 409 card px (the runtime caps it by what a viewport can cover)
R_FRAC_MAX = 0.5 # |r| stays under this share of the nearest card's distance: the offset must stay well inside the nearest cylinder
REST_SCALE_MIN = 1 / 1.1 # a 16:9 viewport is width-bound and the runtime's plane is 1.1 viewport widths wide (view.ts windowFor, DRIFT_FRAC 0.05 a side): a card scaled below this leaves the viewport's edge bare at rest
WEBP_QUALITY = 80
SHEET_SKY = (0.80, 0.86, 0.94) # the flat sky of the contact sheet
SHEET_LIGHT = (-0.35, 0.55, 0.76) # the fixed light of the contact sheet in (along ray, across ray, up); the sheet is a look at the cards, the client lights the real thing
ATTRIBUTION = dict(
credit_line='Contains modified Copernicus data: DEM © DLR e.V. 2010-2014 and © Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved.',
licence='Copernicus DEM licence: free, full and open access, with the credit line shown',
dem_source='Copernicus DEM GLO-30 (30 m)',
url='https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model')
# ------------------------------------------------------------------------------------ schema (the one dict the schema file and the validator both come from)
_num, _int, _str = {'type': 'number'}, {'type': 'integer'}, {'type': 'string'}
_numnull = {'type': ['number', 'null']}
def _obj(**props): return {'type': 'object', 'required': list(props), 'additionalProperties': False, 'properties': props}
_file = _obj(file=_str, bytes=_int)
SCHEMA = {'$schema': 'https://json-schema.org/draft/2020-12/schema', 'title': 'ridge-bake manifest v2 and index v1', '$defs': {
'manifest': _obj(schema={'const': 2}, baker_version=_int, bake_id=_str,
place=_obj(id=_str, name=_str, lat=_num, lon=_num, altitude_km=_num, eye_m=_num),
view=_obj(look_az_deg=_num, window_deg={'const': WINDOW_DEG}, plane_w={'type': 'integer', 'maximum': PLANE_W_MAX}, plane_h=_int, px_per_deg_h=_num, px_per_deg_v=_num, exaggeration=_num, horizon_row=_num, sky_row=_num, near_row=_num),
curvature=_obj(r_earth_m=_num, k_ref=_num),
encoding=_obj(log_d_min=_num, log_d_max=_num, normal={'const': 'rt8'}),
camera=_obj(r_m=_num, heading_max_deg=_num),
cards={'type': 'array', 'minItems': 1, 'maxItems': MAX_CARDS, 'items': dict(_obj(top=_int, h=_int, near_m=_numnull, far_m=_numnull, median_m=_num, distance_m=_num, scale=_num, colour=_file, geometry=_file),
description="nearest first; the runtime paints the list last to first. top and h place the card back at its rows of the frame; near_m and far_m are the median seam depths, null at the ends; median_m and distance_m are the median distance of the card's solid pixels that are not wall; scale = distance_m / (distance_m - camera.r_m) is the card's pan rate per unit of heading and its static size.")},
w=_int, h=_int, bytes=_int,
attribution=_obj(credit_line=_str, licence=_str, dem_source=_str, url=_str)),
'index': _obj(schema={'const': 1}, default=_str, places={'type': 'object', 'additionalProperties': _str})}}
def validate(x, s, path='$'):
"""The subset of JSON Schema SCHEMA uses; raises ValueError naming the path."""
if '$ref' in s: return validate(x, SCHEMA['$defs'][s['$ref'].split('/')[-1]], path)
tys = s.get('type'); tys = [tys] if isinstance(tys, str) else tys; py = {'object': dict, 'array': list, 'string': str, 'number': (int, float), 'integer': int, 'null': type(None)}
if tys and not any(isinstance(x, py[t]) and not (isinstance(x, bool) and t != 'null') for t in tys): raise ValueError(f'{path}: not a {"/".join(tys)}')
if 'const' in s and x != s['const']: raise ValueError(f"{path}: must be {s['const']!r}")
if 'enum' in s and x not in s['enum']: raise ValueError(f'{path}: not one of {s["enum"]}')
if 'maximum' in s and x > s['maximum']: raise ValueError(f'{path}: above {s["maximum"]}')
if isinstance(x, list):
if not s.get('minItems', 0) <= len(x) <= s.get('maxItems', 1 << 30): raise ValueError(f'{path}: wrong length')
for i, v in enumerate(x): validate(v, s['items'], f'{path}[{i}]')
if isinstance(x, dict):
props = s.get('properties', {}); extra = s.get('additionalProperties', True)
for k in s.get('required', []):
if k not in x: raise ValueError(f'{path}: missing {k}')
for k, v in x.items():
if k in props: validate(v, props[k], f'{path}.{k}')
elif extra is False: raise ValueError(f'{path}: extra key {k}')
elif isinstance(extra, dict): validate(v, extra, f'{path}.{k}')
# ------------------------------------------------------------------------------------ cards -> bytes
def u8(a): return np.clip(np.rint(np.asarray(a) * 255.0), 0, 255).astype(np.uint8)
def encode_colour(albedo, alpha):
"""Lossy RGB albedo with lossless alpha coverage, straight (not premultiplied); the colour under a zero alpha is zeroed."""
a = u8(alpha); rgb = u8(albedo) * (a[..., None] > 0); return bytes(imagecodecs.webp_encode(np.dstack([rgb, a]), level=WEBP_QUALITY, lossless=False))
def encode_geometry(n_r, n_t, logd, enc, wall=None):
"""Lossless, opaque RGB: R, G = (n_r + 1) / 2, (n_t + 1) / 2 ('rt8'), B = the log-distance normalised between enc log_d_min and log_d_max. Wall pixels (the extruded face under a ridge; wall (h, w) bool) write R = G = 255: a code outside the unit disc
that no real normal reaches (real r2 + t2 peaks at 0.998), which the runtime reads as 'normal up, no crease'."""
b = (np.asarray(logd) - enc['log_d_min']) / (enc['log_d_max'] - enc['log_d_min']); r, t = u8((np.asarray(n_r) + 1) / 2), u8((np.asarray(n_t) + 1) / 2)
if wall is not None: m = np.asarray(wall, bool); r, t = np.where(m, 255, r).astype(np.uint8), np.where(m, 255, t).astype(np.uint8)
return bytes(imagecodecs.webp_encode(np.dstack([r, t, u8(b)]), lossless=True))
def decode(b):
"""A WebP's bytes as RGBA uint8; the codec returns RGB for an image that is opaque everywhere, which is solid."""
a = imagecodecs.webp_decode(b)
return a if a.shape[-1] == 4 else np.concatenate([a, np.full(a.shape[:2] + (1,), 255, np.uint8)], -1)
def composite_alpha(cards, h, w):
"""Coverage of the alpha-over of all cards, each (top, rgba uint8 or float alpha (rows, w)) placed at its rows of an h x w frame."""
clear = np.ones((h, w))
for top, al in cards: clear[top:top + al.shape[0]] *= 1 - np.asarray(al, np.float64)
return 1 - clear
def check_cover(cards, opaque, tol=COVER_TOL):
"""Refuse a bake whose cards, alpha-over, differ from the opaque view's coverage by more than tol anywhere: a hole shows the sky through terrain, an excess is a ghost. cards: [(top, alpha 0..1 (rows, w))], opaque (h, w)."""
err = np.abs(composite_alpha(cards, *opaque.shape) - opaque); bad = err > tol
if bad.any(): y, x = np.unravel_index(int(np.argmax(err)), err.shape); raise ValueError(f'the cards do not composite to the opaque view within {tol}: {int(bad.sum())} pixels differ, worst {err.max():.3f} at x={x} row {y}')
def check_budget(card_bytes, w, bands):
"""Refuse a bake the runtime could not hold: more than MAX_CARDS cards, a card wider than PLANE_W_MAX, every card file together above TOTAL_BYTES_MAX, or the cards decoding (2 textures x w x band rows x 4 bytes each) above DECODE_BYTES_MAX."""
if len(card_bytes) > MAX_CARDS: raise ValueError(f'{len(card_bytes)} cards, above {MAX_CARDS}')
if w > PLANE_W_MAX: raise ValueError(f'card width {w} above {PLANE_W_MAX}')
if sum(card_bytes) > TOTAL_BYTES_MAX: raise ValueError(f'the cards are {sum(card_bytes)} bytes, above {TOTAL_BYTES_MAX}')
decoded = sum(2 * w * h * 4 for h in bands)
if decoded > DECODE_BYTES_MAX: raise ValueError(f'the cards decode to {decoded} bytes, above {DECODE_BYTES_MAX}')
def card_scales(distances, r_m):
"""scale_i = d_i / (d_i - r) for the cards' distances (m), nearest first: the card's pan rate per unit of heading and its static size seen from a camera r metres along its heading (ruling ridge-camera-on-circle; + forward, - backward). Refuses |r| >= R_FRAC_MAX x the nearest distance."""
if abs(r_m) >= R_FRAC_MAX * min(distances): raise ValueError(f"the camera offset {r_m:g} m is not under {R_FRAC_MAX} x the nearest card's distance {min(distances):g} m")
return [d / (d - r_m) for d in distances]
def check_camera(scales, tops, bands, view):
"""Refuse a camera whose scaled cards leave the frame uncovered: the nearest card, scaled about the horizon row, must still reach the frame bottom (a backward camera shrinks it away), and no card may be smaller than REST_SCALE_MIN (a 16:9 viewport's edge)."""
hr = view['horizon_row']; bottom = hr + (tops[0] + bands[0] - hr) * scales[0]
if bottom < view['plane_h'] - 1e-6: raise ValueError(f"the camera lifts the nearest card to row {bottom:.1f}, off the frame bottom (row {view['plane_h']})")
if min(scales) < REST_SCALE_MIN: raise ValueError(f'a card scaled {min(scales):.3f} cannot cover a 16:9 viewport at rest (below {REST_SCALE_MIN:.3f})')
def bake_id(cards):
"""First 12 hex of sha256 over the card files in index order, colour then geometry. cards: [(colour bytes, geometry bytes)]."""
h = hashlib.sha256()
for colour, geometry in cards: h.update(colour); h.update(geometry)
return h.hexdigest()[:12]
def write_bake(out, place, view, meta, cards, opaque, default=None):
"""Write out/<place>-<bake_id>/ (card WebPs + manifest.json), rewrite out/index.json, delete the place's previous dir. cards: [dict(top, colour bytes, geometry bytes, near_m, far_m, median_m, distance_m, scale)], nearest first; opaque (h, w) is
the opaque view's coverage. Refuses before writing a bake whose files decode to different sizes, leave the frame or the view's plane_h, break the budget or composite away from the opaque view. meta: dict(curvature, encoding, camera dict(r_m, heading_max_deg)). Returns the directory."""
dec = [(decode(c['colour']), decode(c['geometry'])) for c in cards]; shapes = {a.shape[:2] for pair in dec for a in pair}; bands = [a.shape[0] for a, _ in dec]
if any(c.shape[:2] != g.shape[:2] for c, g in dec): raise ValueError('a card colour and geometry are not one size')
if len({a.shape[1] for pair in dec for a in pair}) != 1: raise ValueError(f'the cards are not one width: {sorted(shapes)}')
w = dec[0][0].shape[1]; h = view['plane_h']
if any(band < 1 or c['top'] < 0 or c['top'] + band > h for c, band in zip(cards, bands)): raise ValueError(f'a card leaves the {h} rows of the frame')
if opaque.shape != (h, w): raise ValueError(f'the opaque view is {opaque.shape}, the frame {(h, w)}')
sizes = [len(c['colour']) + len(c['geometry']) for c in cards]; check_budget(sizes, w, bands)
check_cover([(c['top'], col[..., 3] / 255.0) for c, (col, _) in zip(cards, dec)], opaque); check_camera([c['scale'] for c in cards], [c['top'] for c in cards], bands, view)
bid = bake_id([(c['colour'], c['geometry']) for c in cards]); name = f"{place['id']}-{bid}"; out = Path(out); dest = out / name
manifest = dict(schema=2, baker_version=BAKER_VERSION, bake_id=bid, place=place, view=dict(view, window_deg=WINDOW_DEG, plane_w=w), curvature=meta['curvature'], encoding=dict(meta['encoding'], normal='rt8'), camera=dict(r_m=meta['camera']['r_m'], heading_max_deg=meta['camera']['heading_max_deg']),
cards=[dict(top=c['top'], h=band, near_m=c['near_m'], far_m=c['far_m'], median_m=c['median_m'], distance_m=c['distance_m'], scale=c['scale'], colour=dict(file=f'card-{i}-colour.webp', bytes=len(c['colour'])), geometry=dict(file=f'card-{i}-geometry.webp', bytes=len(c['geometry'])))
for i, (c, band) in enumerate(zip(cards, bands))], w=w, h=h, bytes=sum(sizes), attribution=ATTRIBUTION)
validate(manifest, SCHEMA['$defs']['manifest']); out.mkdir(parents=True, exist_ok=True); tmp = Path(tempfile.mkdtemp(dir=out, prefix='.bake-'))
for i, c in enumerate(cards): (tmp / f'card-{i}-colour.webp').write_bytes(c['colour']); (tmp / f'card-{i}-geometry.webp').write_bytes(c['geometry'])
(tmp / 'manifest.json').write_text(json.dumps(manifest, indent=1) + '\n')
idx_path = out / 'index.json'; idx = json.loads(idx_path.read_text()) if idx_path.exists() else dict(schema=1, default=place['id'], places={})
old = idx['places'].get(place['id']); idx['places'][place['id']] = name; idx['default'] = default or (idx['default'] if idx['default'] in idx['places'] else place['id'])
validate(idx, SCHEMA['$defs']['index'])
if dest.exists(): shutil.rmtree(dest)
os.rename(tmp, dest); (out / '.index.tmp').write_text(json.dumps(idx, indent=1) + '\n'); os.replace(out / '.index.tmp', idx_path)
if old and old != name: shutil.rmtree(out / old, ignore_errors=True)
return dest
# ------------------------------------------------------------------------------------ the bake
def bake_place(pid):
"""stage 0, prefilter, set_view, coverage, seams, cards: dict(place, view, meta, cards (ridge.cards arrays), seams (K, w) in m, cov (bins, w), opaque (h, w) coverage). Needs RIDGE_TILES / RIDGE_WORK."""
import ridge
assert ridge.WIN == PLANE_W and ridge.H > 0
p = ridge.configure(ridge.load_preset(pid)); ridge.mosaic(p); d, _, Hh, _ = ridge.stage0(False); a, h = ridge.prefilter(d, Hh, p.get('prefilter_m', 0)); v = ridge.set_view(a.max(0))
nrm = tuple(ridge.win(x) for x in ridge.normals(d, h)); aw, hw = ridge.win(a), ridge.win(h); cov = ridge.coverage(d, aw); sm = ridge.seams(cov, [k * 1000.0 for k in p['card_split_km']], d)
place = dict(id=p['id'], name=p['name'], lat=p['lat'], lon=p['lon'], altitude_km=p['ground_m'] / 1000.0, eye_m=p['eye_m'])
view = dict(look_az_deg=p['az_center'], plane_h=ridge.H, px_per_deg_h=ridge.HPX_DEG, px_per_deg_v=v['px_per_deg'], exaggeration=v['exaggeration'], horizon_row=v['horizon_row'], sky_row=v['sky_row'] * ridge.H, near_row=v['near_row'] * ridge.H)
meta = dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(d[0]), log_d_max=math.log(d[-1])), camera=dict(r_m=float(p.get('camera_r_m', CAMERA_R_M)), heading_max_deg=HEADING_MAX_DEG))
return dict(place=place, view=view, meta=meta, cards=ridge.cards(d, aw, hw, sm, nrm), splits_km=list(p['card_split_km']), seams=sm, cov=cov, opaque=ridge.opaque(aw), edges=ridge.log_edges(d))
def pack(bake):
"""The cards of a bake as bytes plus their manifest facts: median seam depths either side, the median distance of the card's solid pixels that are not wall (median_m = distance_m), and scale = distance_m / (distance_m - camera r). Refuses a card
with no solid terrain apart from its wall rows, and a camera offset the cards cannot take (card_scales)."""
enc = bake['meta']['encoding']; sm = bake['seams']; out = []; sp = bake['splits_km']; cs = bake['cards']
for i, c in enumerate(cs):
if c['alpha'].shape[0] == 0: raise ValueError(f"card {i} is empty: it lies between the splits {' and '.join(f'{sp[j]:g} km' for j in (i - 1, i) if 0 <= j < len(sp))} (card_split_km {sp}) and holds no terrain nothing nearer hides; move or remove a split")
dist = []
for i, c in enumerate(cs):
ground = (c['alpha'] >= 0.5) & ~c['wall']
if not ground.any(): raise ValueError(f'card {i} holds no solid terrain apart from its wall rows')
dist.append(float(np.exp(np.median(c['logd'][ground]))))
scales = card_scales(dist, bake['meta']['camera']['r_m'])
for i, c in enumerate(cs):
out.append(dict(top=c['top'], colour=encode_colour(c['albedo'], c['alpha']), geometry=encode_geometry(c['n_r'], c['n_t'], c['logd'], enc, c['wall']),
near_m=float(np.median(sm[i - 1])) if i else None, far_m=float(np.median(sm[i])) if i < len(sm) else None, median_m=dist[i], distance_m=dist[i], scale=scales[i]))
return out
def lit(c):
"""albedo x (0.35 + 0.65 max(n.L, 0)) under the fixed sheet light, with the card's alpha: (rgb, alpha). Wall pixels are lit with the face up, as the runtime reads their code."""
wall = c['wall']; n_r, n_t = np.where(wall, 0.0, c['n_r']), np.where(wall, 0.0, c['n_t'])
up = np.sqrt(np.clip(1 - n_r ** 2 - n_t ** 2, 0, 1)); L = np.array(SHEET_LIGHT) / np.linalg.norm(SHEET_LIGHT); nl = np.clip(n_r * L[0] + n_t * L[1] + up * L[2], 0, 1)
return c['albedo'] * (0.35 + 0.65 * nl)[..., None], c['alpha']
def sheet(bake):
"""Contact sheet (png bytes), stacked: the composite, every card alone, and the depth image (log-distance bins, far at the top, every seam drawn). All lit by SHEET_LIGHT over the flat SHEET_SKY; reads the arrays the encoder writes."""
h, w = bake['opaque'].shape; sky = np.broadcast_to(np.array(SHEET_SKY), (h, w, 3)); comp = sky.copy(); panels = []
for c in bake['cards']:
rgb, al = lit(c); alone = sky.copy(); sl = slice(c['top'], c['top'] + al.shape[0]); alone[sl] = sky[sl] * (1 - al[..., None]) + rgb * al[..., None]; panels.append(alone)
for c in reversed(bake['cards']): rgb, al = lit(c); sl = slice(c['top'], c['top'] + al.shape[0]); comp[sl] = comp[sl] * (1 - al[..., None]) + rgb * al[..., None]
cov = bake['cov']; img = np.repeat(np.log1p(cov[::-1]) / np.log1p(cov.max()), 2, 0); depth = np.dstack([img] * 3) * 0.92 + 0.04; nb = cov.shape[0]; cols = np.arange(w)
for k, s in enumerate(bake['seams']):
j = np.clip(np.searchsorted(bake['edges'], np.log(s), 'right') - 1, 0, nb - 1); col = [(0.24, 0.78, 1.0), (1.0, 0.47, 0.24), (0.6, 1.0, 0.4), (1.0, 0.9, 0.3), (0.9, 0.4, 1.0)][k % 5]
for dy in (0, 1): depth[(nb - 1 - j) * 2 + dy, cols] = col
return bytes(imagecodecs.png_encode(u8(np.concatenate([comp] + panels + [depth], 0))))
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split('\n')[0]); ap.add_argument('place', nargs='?'); ap.add_argument('--tiles'); ap.add_argument('--out'); ap.add_argument('--work'); ap.add_argument('--sheet'); ap.add_argument('--write-schema', action='store_true')
a = ap.parse_args(argv)
if a.write_schema: (HERE / 'ridge-bake.schema.json').write_text(json.dumps(SCHEMA, indent=1, ensure_ascii=False) + '\n'); return 0
if not (a.place and a.tiles and a.out): ap.error('place, --tiles and --out are required')
os.environ['RIDGE_TILES'] = a.tiles; os.environ['RIDGE_WORK'] = a.work or os.path.join(os.environ.get('TMPDIR', tempfile.gettempdir()), 'ridge-bake-work'); os.makedirs(os.environ['RIDGE_WORK'], exist_ok=True)
bake = bake_place(a.place)
if a.sheet: Path(a.sheet).write_bytes(sheet(bake))
dest = write_bake(a.out, bake['place'], bake['view'], bake['meta'], pack(bake), bake['opaque'])
print(dest); return 0
if __name__ == '__main__': sys.exit(main())

View file

@ -0,0 +1,637 @@
{
"_doc": "Place presets for the A+D baker (ridge.py). eye = observer lat/lon; eye_h_m = eye above the local DEM surface (ground_override_m replaces the DEM ground elevation, used for Vienna to keep round 1's 183.3 m); look_at = target lat/lon whose bearing centres the 72 deg window (or az_deg); rmax_km = ring radius (decides the tile list: every 1x1 deg GLO-30 tile whose rectangle intersects the circle); card_split_km = the ordered list of 1 to MAX_CARDS - 1 authored seam depths in km (the seam search refines each per column; K splits make K+1 cards; required, never defaulted); prefilter_m = Gaussian sigma in metres of the height low-pass before the cards are cut (default 0).",
"presets": [
{
"id": "vienna",
"name": "Vienna, looking SW to Rax/Schneeberg",
"kind": "far range over a flat foreground",
"lat": 48.1929826,
"lon": 16.3534237,
"eye_h_m": 30.0,
"ground_override_m": 183.3,
"az_deg": 214.0,
"rmax_km": 95,
"card_split_km": [
6,
40
],
"prefilter_m": 100,
"viewpoint_source": {
"status": "existing observer of the round-1 mockup (the scene camera used by the game), not photo-sourced; eye 30 m above ground as in round 1"
}
},
{
"id": "matterhorn",
"name": "Matterhorn from the Gornergrat (photo cell, 9.7 km)",
"kind": "lone horn, close, 27 deg of relief",
"lat": 45.983139,
"lon": 7.782466,
"eye_h_m": 1.6,
"look_at": [
45.97666,
7.65678
],
"rmax_km": 60,
"initial_guess_not_used": {
"lat": 45.9856,
"lon": 7.7452
},
"viewpoint_source": {
"status": "sourced",
"source": "Wikimedia Commons geosearch (namespace 6), geotagged photos",
"query": "geosearch ns=6 gslimit=500 gsradius=10000 around 25 centres (peak + 3 rings x 8 bearings, radii 3600-12000 m), then EXIF GPSImgDirection of every file in range via prop=imageinfo&iiprop=commonmetadata",
"files_found": 5003,
"in_range": 3241,
"with_exif_heading": 205,
"facing_the_peak": 52,
"pool": "photos whose camera heading is within 30 deg of the bearing to the summit",
"rule": "densest 1 km cell of photos 3000-12000 m from the summit whose EXIF camera heading faces the summit (within 30 deg) with the summit visible on the DEM (straight line, first 250 m ignored, 8 m clutter allowed); viewpoint = median coordinate of the cell",
"median_camera_heading_deg": 245.8,
"photos_in_cell": 7,
"cells_tried": [
{
"n_facing": 7,
"lat": 45.98314,
"lon": 7.78247,
"peak_visible": true
}
],
"distance_to_peak_m": 9749,
"bearing_to_peak_deg": 265.8,
"dem_ground_m": 3090.7,
"eye_height_rule": "DEM ground at the viewpoint + 1.6 m (the source gives no eye height)",
"sample_files": [
{
"title": "File:Gornergrat-04.jpg",
"lat": 45.983061,
"lon": 7.782031,
"heading": 256.0,
"url": "https://commons.wikimedia.org/wiki/File%3AGornergrat-04.jpg"
},
{
"title": "File:Gornergrat-03.jpg",
"lat": 45.983058,
"lon": 7.782038,
"heading": 245.8,
"url": "https://commons.wikimedia.org/wiki/File%3AGornergrat-03.jpg"
},
{
"title": "File:Gornergrat-07.jpg",
"lat": 45.982653,
"lon": 7.782466,
"heading": 250.2,
"url": "https://commons.wikimedia.org/wiki/File%3AGornergrat-07.jpg"
},
{
"title": "File:Gornergratsee 2021 10.jpg",
"lat": 45.986958,
"lon": 7.780303,
"heading": 243.4,
"url": "https://commons.wikimedia.org/wiki/File%3AGornergratsee_2021_10.jpg"
},
{
"title": "File:Early morning Eiger.jpg",
"lat": 45.983242,
"lon": 7.783361,
"heading": 254.7,
"url": "https://commons.wikimedia.org/wiki/File%3AEarly_morning_Eiger.jpg"
},
{
"title": "File:Klein Matterhorn mit Wolken an Theodulhorn und Furgghorn \u00fcber dem Oberen Theodulgletscher- a view from Gornergrat 2021 02 (cropped).jpg",
"lat": 45.983139,
"lon": 7.784172,
"heading": 242.1,
"url": "https://commons.wikimedia.org/wiki/File%3AKlein_Matterhorn_mit_Wolken_an_Theodulhorn_und_Furgghorn_%C3%BCber_dem_Oberen_Theodulgletscher-_a_view_from_Gornergrat_2021_02_%28cropped%29.jpg"
},
{
"title": "File:Breithorn and neighbours from Gornergrat 2021 02.jpg",
"lat": 45.983139,
"lon": 7.784172,
"heading": 242.1,
"url": "https://commons.wikimedia.org/wiki/File%3ABreithorn_and_neighbours_from_Gornergrat_2021_02.jpg"
}
],
"exif_headings": [
{
"title": "File:Gornergrat-04.jpg",
"heading": 256.0
},
{
"title": "File:Gornergrat-03.jpg",
"heading": 245.8
},
{
"title": "File:Gornergrat-07.jpg",
"heading": 250.2
},
{
"title": "File:Gornergratsee 2021 10.jpg",
"heading": 243.4
},
{
"title": "File:Early morning Eiger.jpg",
"heading": 254.7
},
{
"title": "File:Klein Matterhorn mit Wolken an Theodulhorn und Furgghorn \u00fcber dem Oberen Theodulgletscher- a view from Gornergrat 2021 02 (cropped).jpg",
"heading": 242.1
},
{
"title": "File:Breithorn and neighbours from Gornergrat 2021 02.jpg",
"heading": 242.1
}
],
"n_with_exif_heading": 7,
"summit_dem_m": 4324.9,
"summit_nominal": [
45.97639,
7.65833
]
}
},
{
"id": "fuji",
"name": "Fuji from the Shiraito Falls side, 13.8 km WSW (photo cell)",
"kind": "lone cone, smooth",
"lat": 35.312467222222494,
"lon": 138.587223194445,
"eye_h_m": 1.6,
"look_at": [
35.36061,
138.72731
],
"rmax_km": 60,
"initial_guess_not_used": {
"lat": 35.4994,
"lon": 138.7686
},
"viewpoint_source": {
"status": "sourced",
"source": "Wikimedia Commons geosearch (namespace 6), geotagged photos",
"query": "geosearch ns=6 gslimit=500 gsradius=10000 around 25 centres (peak + 3 rings x 8 bearings, radii 9000-30000 m), then EXIF GPSImgDirection of every file in range via prop=imageinfo&iiprop=commonmetadata",
"files_found": 6494,
"in_range": 4280,
"with_exif_heading": 588,
"facing_the_peak": 132,
"pool": "photos whose camera heading is within 30 deg of the bearing to the summit",
"rule": "densest 1 km cell of photos 8000-30000 m from the summit whose EXIF camera heading faces the summit (within 30 deg) with the summit visible on the DEM (straight line, first 250 m ignored, 8 m clutter allowed); viewpoint = median coordinate of the cell",
"median_camera_heading_deg": 64.4,
"photos_in_cell": 8,
"cells_tried": [
{
"n_facing": 15,
"lat": 35.36248,
"lon": 138.86287,
"peak_visible": false
},
{
"n_facing": 8,
"lat": 35.31247,
"lon": 138.58722,
"peak_visible": true
}
],
"distance_to_peak_m": 13808,
"bearing_to_peak_deg": 67.2,
"dem_ground_m": 486.9,
"eye_height_rule": "DEM ground at the viewpoint + 1.6 m (the source gives no eye height)",
"sample_files": [
{
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 03.JPG",
"lat": 35.31114,
"lon": 138.5886,
"heading": 48.0,
"url": "https://commons.wikimedia.org/wiki/File%3A%E5%AF%8C%E5%A3%AB%E5%B1%B1%EF%BC%88%E3%81%B5%E3%81%98%E3%81%95%E3%82%93%E3%80%81%E8%8B%B1%E8%AA%9E%EF%BC%9AMount_Fuji%EF%BC%89_03.JPG"
},
{
"title": "File:Mount Fuji, view from Shiraito no Taki.jpg",
"lat": 35.313589,
"lon": 138.588394,
"heading": 68.8,
"url": "https://commons.wikimedia.org/wiki/File%3AMount_Fuji%2C_view_from_Shiraito_no_Taki.jpg"
},
{
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 02.JPG",
"lat": 35.313248055556,
"lon": 138.58760805556,
"heading": 64.2,
"url": "https://commons.wikimedia.org/wiki/File%3A%E5%AF%8C%E5%A3%AB%E5%B1%B1%EF%BC%88%E3%81%B5%E3%81%98%E3%81%95%E3%82%93%E3%80%81%E8%8B%B1%E8%AA%9E%EF%BC%9AMount_Fuji%EF%BC%89_02.JPG"
},
{
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 07.JPG",
"lat": 35.312428055556,
"lon": 138.58723138889,
"heading": 88.8,
"url": "https://commons.wikimedia.org/wiki/File%3A%E5%AF%8C%E5%A3%AB%E5%B1%B1%EF%BC%88%E3%81%B5%E3%81%98%E3%81%95%E3%82%93%E3%80%81%E8%8B%B1%E8%AA%9E%EF%BC%9AMount_Fuji%EF%BC%89_07.JPG"
},
{
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 08.JPG",
"lat": 35.312418055556,
"lon": 138.587215,
"heading": 64.0,
"url": "https://commons.wikimedia.org/wiki/File%3A%E5%AF%8C%E5%A3%AB%E5%B1%B1%EF%BC%88%E3%81%B5%E3%81%98%E3%81%95%E3%82%93%E3%80%81%E8%8B%B1%E8%AA%9E%EF%BC%9AMount_Fuji%EF%BC%89_08.JPG"
},
{
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 04.JPG",
"lat": 35.312478055556,
"lon": 138.58717805556,
"heading": 62.2,
"url": "https://commons.wikimedia.org/wiki/File%3A%E5%AF%8C%E5%A3%AB%E5%B1%B1%EF%BC%88%E3%81%B5%E3%81%98%E3%81%95%E3%82%93%E3%80%81%E8%8B%B1%E8%AA%9E%EF%BC%9AMount_Fuji%EF%BC%89_04.JPG"
},
{
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 06.JPG",
"lat": 35.312456388889,
"lon": 138.58715805556,
"heading": 65.2,
"url": "https://commons.wikimedia.org/wiki/File%3A%E5%AF%8C%E5%A3%AB%E5%B1%B1%EF%BC%88%E3%81%B5%E3%81%98%E3%81%95%E3%82%93%E3%80%81%E8%8B%B1%E8%AA%9E%EF%BC%9AMount_Fuji%EF%BC%89_06.JPG"
},
{
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 05.JPG",
"lat": 35.312479722222,
"lon": 138.58714138889,
"heading": 64.5,
"url": "https://commons.wikimedia.org/wiki/File%3A%E5%AF%8C%E5%A3%AB%E5%B1%B1%EF%BC%88%E3%81%B5%E3%81%98%E3%81%95%E3%82%93%E3%80%81%E8%8B%B1%E8%AA%9E%EF%BC%9AMount_Fuji%EF%BC%89_05.JPG"
}
],
"exif_headings": [
{
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 03.JPG",
"heading": 48.0
},
{
"title": "File:Mount Fuji, view from Shiraito no Taki.jpg",
"heading": 68.8
},
{
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 02.JPG",
"heading": 64.2
},
{
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 07.JPG",
"heading": 88.8
},
{
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 08.JPG",
"heading": 64.0
},
{
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 04.JPG",
"heading": 62.2
},
{
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 06.JPG",
"heading": 65.2
},
{
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 05.JPG",
"heading": 64.5
}
],
"n_with_exif_heading": 8,
"summit_dem_m": 3765.5,
"summit_nominal": [
35.36061,
138.72731
]
}
},
{
"id": "halfdome",
"name": "Half Dome from the Yosemite Valley floor (Sentinel Bridge photo cell)",
"kind": "granite wall across a valley",
"lat": 37.745833333333,
"lon": -119.592606,
"eye_h_m": 1.6,
"look_at": [
37.74435,
-119.53426
],
"rmax_km": 40,
"initial_guess_not_used": {
"lat": 37.7305,
"lon": -119.5734
},
"viewpoint_source": {
"status": "sourced",
"source": "Wikimedia Commons geosearch (namespace 6), geotagged photos",
"query": "geosearch ns=6 gslimit=500 gsradius=10000 around 25 centres (peak + 3 rings x 8 bearings, radii 2700-9000 m), then EXIF GPSImgDirection of every file in range via prop=imageinfo&iiprop=commonmetadata",
"files_found": 2505,
"in_range": 1788,
"with_exif_heading": 181,
"facing_the_peak": 64,
"pool": "photos whose camera heading is within 30 deg of the bearing to the summit",
"rule": "densest 1 km cell of photos 2000-9000 m from the summit whose EXIF camera heading faces the summit (within 30 deg) with the summit visible on the DEM (straight line, first 250 m ignored, 8 m clutter allowed); viewpoint = median coordinate of the cell",
"median_camera_heading_deg": 91.6,
"photos_in_cell": 9,
"cells_tried": [
{
"n_facing": 9,
"lat": 37.73853,
"lon": -119.57124,
"peak_visible": false
},
{
"n_facing": 9,
"lat": 37.74583,
"lon": -119.59261,
"peak_visible": true
}
],
"distance_to_peak_m": 5138,
"bearing_to_peak_deg": 91.8,
"dem_ground_m": 1209.2,
"eye_height_rule": "DEM ground at the viewpoint + 1.6 m (the source gives no eye height)",
"sample_files": [
{
"title": "File:Yosemite National Park - 51700634719.jpg",
"lat": 37.746606,
"lon": -119.590317,
"heading": 87.0,
"url": "https://commons.wikimedia.org/wiki/File%3AYosemite_National_Park_-_51700634719.jpg"
},
{
"title": "File:Half Dome, Yosemite National Park - 53324601178.jpg",
"lat": 37.748264,
"lon": -119.592606,
"heading": 98.8,
"url": "https://commons.wikimedia.org/wiki/File%3AHalf_Dome%2C_Yosemite_National_Park_-_53324601178.jpg"
},
{
"title": "File:Half Dome, Yosemite National Park - 53324824955.jpg",
"lat": 37.748322,
"lon": -119.592736,
"heading": 90.1,
"url": "https://commons.wikimedia.org/wiki/File%3AHalf_Dome%2C_Yosemite_National_Park_-_53324824955.jpg"
},
{
"title": "File:2013-09-19 18 35 25 Half Dome and the Merced River in Yosemite National Park.JPG",
"lat": 37.7435,
"lon": -119.58966666667,
"heading": 91.6,
"url": "https://commons.wikimedia.org/wiki/File%3A2013-09-19_18_35_25_Half_Dome_and_the_Merced_River_in_Yosemite_National_Park.JPG"
},
{
"title": "File:Half Dome from the Yosemite Valley floor in mid-Spring.jpeg",
"lat": 37.745833333333,
"lon": -119.59233333333,
"heading": 92.0,
"url": "https://commons.wikimedia.org/wiki/File%3AHalf_Dome_from_the_Yosemite_Valley_floor_in_mid-Spring.jpeg"
},
{
"title": "File:Sentinel Bridge & Half Dome.jpg",
"lat": 37.743419,
"lon": -119.590562,
"heading": 86.8,
"url": "https://commons.wikimedia.org/wiki/File%3ASentinel_Bridge_%26_Half_Dome.jpg"
},
{
"title": "File:Half Dome pre Super moon 2.jpg",
"lat": 37.745769,
"lon": -119.592972,
"heading": 106.5,
"url": "https://commons.wikimedia.org/wiki/File%3AHalf_Dome_pre_Super_moon_2.jpg"
},
{
"title": "File:Half Dome pre Super moon.jpg",
"lat": 37.745747,
"lon": -119.593033,
"heading": 97.1,
"url": "https://commons.wikimedia.org/wiki/File%3AHalf_Dome_pre_Super_moon.jpg"
},
{
"title": "File:Yosemite National Park 003.jpg",
"lat": 37.750814,
"lon": -119.598664,
"heading": 80.1,
"url": "https://commons.wikimedia.org/wiki/File%3AYosemite_National_Park_003.jpg"
}
],
"exif_headings": [
{
"title": "File:Yosemite National Park - 51700634719.jpg",
"heading": 87.0
},
{
"title": "File:Half Dome, Yosemite National Park - 53324601178.jpg",
"heading": 98.8
},
{
"title": "File:Half Dome, Yosemite National Park - 53324824955.jpg",
"heading": 90.1
},
{
"title": "File:2013-09-19 18 35 25 Half Dome and the Merced River in Yosemite National Park.JPG",
"heading": 91.6
},
{
"title": "File:Half Dome from the Yosemite Valley floor in mid-Spring.jpeg",
"heading": 92.0
},
{
"title": "File:Sentinel Bridge & Half Dome.jpg",
"heading": 86.8
},
{
"title": "File:Half Dome pre Super moon 2.jpg",
"heading": 106.5
},
{
"title": "File:Half Dome pre Super moon.jpg",
"heading": 97.1
},
{
"title": "File:Yosemite National Park 003.jpg",
"heading": 80.1
}
],
"n_with_exif_heading": 9,
"summit_dem_m": 2669.1,
"summit_nominal": [
37.74597,
-119.5329
]
}
},
{
"id": "amadablam",
"name": "Ama Dablam and the Everest massif, 4 km WSW of Tengboche near Khumjung (photo cell)",
"kind": "far high range behind a near spire",
"lat": 27.822000000000003,
"lon": 86.722666666667,
"eye_h_m": 1.6,
"look_at": [
27.8617,
86.86079
],
"rmax_km": 60,
"initial_guess_not_used": {
"lat": 27.8369,
"lon": 86.7643
},
"viewpoint_source": {
"status": "sourced",
"source": "Wikimedia Commons geosearch (namespace 6), geotagged photos",
"query": "geosearch ns=6 gslimit=500 gsradius=10000 around 25 centres (peak + 3 rings x 8 bearings, radii 4800-16000 m), then EXIF GPSImgDirection of every file in range via prop=imageinfo&iiprop=commonmetadata",
"files_found": 1398,
"in_range": 1143,
"with_exif_heading": 54,
"facing_the_peak": 13,
"pool": "photos whose camera heading is within 30 deg of the bearing to the summit",
"rule": "densest 1 km cell of photos 4000-16000 m from the summit whose EXIF camera heading faces the summit (within 30 deg) with the summit visible on the DEM (straight line, first 250 m ignored, 8 m clutter allowed); viewpoint = median coordinate of the cell",
"median_camera_heading_deg": 79.6,
"photos_in_cell": 2,
"cells_tried": [
{
"n_facing": 2,
"lat": 27.822,
"lon": 86.72267,
"peak_visible": true
}
],
"distance_to_peak_m": 14299,
"bearing_to_peak_deg": 72.0,
"dem_ground_m": 3782.0,
"eye_height_rule": "DEM ground at the viewpoint + 1.6 m (the source gives no eye height)",
"sample_files": [
{
"title": "File:Thamserku (6).JPG",
"lat": 27.822666666667,
"lon": 86.722666666667,
"heading": 73.6,
"url": "https://commons.wikimedia.org/wiki/File%3AThamserku_%286%29.JPG"
},
{
"title": "File:Thamserku (7).JPG",
"lat": 27.821333333333,
"lon": 86.722666666667,
"heading": 85.7,
"url": "https://commons.wikimedia.org/wiki/File%3AThamserku_%287%29.JPG"
}
],
"exif_headings": [
{
"title": "File:Thamserku (6).JPG",
"heading": 73.6
},
{
"title": "File:Thamserku (7).JPG",
"heading": 85.7
}
],
"n_with_exif_heading": 2,
"summit_dem_m": 6659.6,
"summit_nominal": [
27.8617,
86.8614
]
}
},
{
"id": "trecime",
"name": "Tre Cime di Lavaredo from the Dreizinnenhuette area, 2.4 km N (photo cell)",
"kind": "cirque wall, spires",
"lat": 46.636906,
"lon": 12.310064,
"eye_h_m": 1.6,
"look_at": [
46.61806,
12.29583
],
"rmax_km": 40,
"initial_guess_not_used": {
"lat": 46.5833,
"lon": 12.2536
},
"viewpoint_source": {
"status": "sourced",
"source": "Wikimedia Commons geosearch (namespace 6), geotagged photos",
"query": "geosearch ns=6 gslimit=500 gsradius=10000 around 25 centres (peak + 3 rings x 8 bearings, radii 3000-10000 m), then EXIF GPSImgDirection of every file in range via prop=imageinfo&iiprop=commonmetadata",
"files_found": 2028,
"in_range": 763,
"with_exif_heading": 207,
"facing_the_peak": 33,
"pool": "photos whose camera heading is within 30 deg of the bearing to the summit",
"rule": "densest 1 km cell of photos 1500-10000 m from the summit whose EXIF camera heading faces the summit (within 30 deg) with the summit visible on the DEM (straight line, first 250 m ignored, 8 m clutter allowed); viewpoint = median coordinate of the cell",
"median_camera_heading_deg": 194.6,
"photos_in_cell": 5,
"cells_tried": [
{
"n_facing": 5,
"lat": 46.63691,
"lon": 12.31006,
"peak_visible": true
}
],
"distance_to_peak_m": 2363,
"bearing_to_peak_deg": 207.4,
"dem_ground_m": 2403.0,
"eye_height_rule": "DEM ground at the viewpoint + 1.6 m (the source gives no eye height)",
"sample_files": [
{
"title": "File:Cime e Nuvole.jpg",
"lat": 46.63605,
"lon": 12.310064,
"heading": 200.3,
"url": "https://commons.wikimedia.org/wiki/File%3ACime_e_Nuvole.jpg"
},
{
"title": "File:DreiZinnenP.jpg",
"lat": 46.636770555556,
"lon": 12.310305555556,
"heading": 180.1,
"url": "https://commons.wikimedia.org/wiki/File%3ADreiZinnenP.jpg"
},
{
"title": "File:Soffio di sguardo.jpg",
"lat": 46.636906,
"lon": 12.311142,
"heading": 194.6,
"url": "https://commons.wikimedia.org/wiki/File%3ASoffio_di_sguardo.jpg"
},
{
"title": "File:2405-DreizinnenH.jpg",
"lat": 46.637782777778,
"lon": 12.309966388889,
"heading": 178.4,
"url": "https://commons.wikimedia.org/wiki/File%3A2405-DreizinnenH.jpg"
},
{
"title": "File:Dolomiten-Fingerkraut in den Sextener Dolomiten - N\u00e4he Drei-Zinnen-H\u00fctte (9801216636).jpg",
"lat": 46.642352,
"lon": 12.30829,
"heading": 200.0,
"url": "https://commons.wikimedia.org/wiki/File%3ADolomiten-Fingerkraut_in_den_Sextener_Dolomiten_-_N%C3%A4he_Drei-Zinnen-H%C3%BCtte_%289801216636%29.jpg"
}
],
"exif_headings": [
{
"title": "File:Cime e Nuvole.jpg",
"heading": 200.3
},
{
"title": "File:DreiZinnenP.jpg",
"heading": 180.1
},
{
"title": "File:Soffio di sguardo.jpg",
"heading": 194.6
},
{
"title": "File:2405-DreizinnenH.jpg",
"heading": 178.4
},
{
"title": "File:Dolomiten-Fingerkraut in den Sextener Dolomiten - N\u00e4he Drei-Zinnen-H\u00fctte (9801216636).jpg",
"heading": 200.0
}
],
"n_with_exif_heading": 5,
"summit_dem_m": 2746.9,
"summit_nominal": [
46.6186,
12.3025
]
}
}
]
}

View file

@ -0,0 +1,307 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "ridge-bake manifest v2 and index v1",
"$defs": {
"manifest": {
"type": "object",
"required": [
"schema",
"baker_version",
"bake_id",
"place",
"view",
"curvature",
"encoding",
"camera",
"cards",
"w",
"h",
"bytes",
"attribution"
],
"additionalProperties": false,
"properties": {
"schema": {
"const": 2
},
"baker_version": {
"type": "integer"
},
"bake_id": {
"type": "string"
},
"place": {
"type": "object",
"required": [
"id",
"name",
"lat",
"lon",
"altitude_km",
"eye_m"
],
"additionalProperties": false,
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"lat": {
"type": "number"
},
"lon": {
"type": "number"
},
"altitude_km": {
"type": "number"
},
"eye_m": {
"type": "number"
}
}
},
"view": {
"type": "object",
"required": [
"look_az_deg",
"window_deg",
"plane_w",
"plane_h",
"px_per_deg_h",
"px_per_deg_v",
"exaggeration",
"horizon_row",
"sky_row",
"near_row"
],
"additionalProperties": false,
"properties": {
"look_az_deg": {
"type": "number"
},
"window_deg": {
"const": 72
},
"plane_w": {
"type": "integer",
"maximum": 4096
},
"plane_h": {
"type": "integer"
},
"px_per_deg_h": {
"type": "number"
},
"px_per_deg_v": {
"type": "number"
},
"exaggeration": {
"type": "number"
},
"horizon_row": {
"type": "number"
},
"sky_row": {
"type": "number"
},
"near_row": {
"type": "number"
}
}
},
"curvature": {
"type": "object",
"required": [
"r_earth_m",
"k_ref"
],
"additionalProperties": false,
"properties": {
"r_earth_m": {
"type": "number"
},
"k_ref": {
"type": "number"
}
}
},
"encoding": {
"type": "object",
"required": [
"log_d_min",
"log_d_max",
"normal"
],
"additionalProperties": false,
"properties": {
"log_d_min": {
"type": "number"
},
"log_d_max": {
"type": "number"
},
"normal": {
"const": "rt8"
}
}
},
"camera": {
"type": "object",
"required": [
"r_m",
"heading_max_deg"
],
"additionalProperties": false,
"properties": {
"r_m": {
"type": "number"
},
"heading_max_deg": {
"type": "number"
}
}
},
"cards": {
"type": "array",
"minItems": 1,
"maxItems": 6,
"items": {
"type": "object",
"required": [
"top",
"h",
"near_m",
"far_m",
"median_m",
"distance_m",
"scale",
"colour",
"geometry"
],
"additionalProperties": false,
"properties": {
"top": {
"type": "integer"
},
"h": {
"type": "integer"
},
"near_m": {
"type": [
"number",
"null"
]
},
"far_m": {
"type": [
"number",
"null"
]
},
"median_m": {
"type": "number"
},
"distance_m": {
"type": "number"
},
"scale": {
"type": "number"
},
"colour": {
"type": "object",
"required": [
"file",
"bytes"
],
"additionalProperties": false,
"properties": {
"file": {
"type": "string"
},
"bytes": {
"type": "integer"
}
}
},
"geometry": {
"type": "object",
"required": [
"file",
"bytes"
],
"additionalProperties": false,
"properties": {
"file": {
"type": "string"
},
"bytes": {
"type": "integer"
}
}
}
},
"description": "nearest first; the runtime paints the list last to first. top and h place the card back at its rows of the frame; near_m and far_m are the median seam depths, null at the ends; median_m and distance_m are the median distance of the card's solid pixels that are not wall; scale = distance_m / (distance_m - camera.r_m) is the card's pan rate per unit of heading and its static size."
}
},
"w": {
"type": "integer"
},
"h": {
"type": "integer"
},
"bytes": {
"type": "integer"
},
"attribution": {
"type": "object",
"required": [
"credit_line",
"licence",
"dem_source",
"url"
],
"additionalProperties": false,
"properties": {
"credit_line": {
"type": "string"
},
"licence": {
"type": "string"
},
"dem_source": {
"type": "string"
},
"url": {
"type": "string"
}
}
}
}
},
"index": {
"type": "object",
"required": [
"schema",
"default",
"places"
],
"additionalProperties": false,
"properties": {
"schema": {
"const": 1
},
"default": {
"type": "string"
},
"places": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
}
}
}
}

267
scripts/ridge-bake/ridge.py Normal file
View file

@ -0,0 +1,267 @@
"""Ridge baker: the ray march of a place, cut into K+1 layered-depth G-buffer cards by K authored seams (places.json), no painter, no sun.
Offline baker for the ridge backdrop (scripts/ridge-bake); export.py drives it.
load_preset(id) -> configure() : observer, tiles, mosaic origin, ring radius, window azimuth, card splits and prefilter from places.json
stage0(detail) : ray march of all 6400 azimuth columns (curvature+refraction), optional authored sub-DEM foreground detail, cached
prefilter(d, h, sigma_m) : Gaussian low-pass of the sampled heights (along each ray, across rays at equal distance), angles recomputed with elev
set_view(skyline) : authored Y mapping from the march skyline: angle -> row, see set_view
coverage(d, a) / seams(cov, ..) : visible rows per log-distance bin; one forward-energy seam per authored split, per column
normals(d, h) / cards(...) : per-sample normals; the K+1 cards (coverage, distance, normal, albedo), each cropped to its band of rows
Vertical exaggeration is AUTHORED and derived per view by set_view (printed on the page). The client owns lighting, haze and ink (ruling ridge-cards-runtime-lit)."""
import sys, time, math, json
import os, hashlib
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import numpy as np, tifffile
def _env_dir(name, what):
v = os.environ.get(name)
if not v: raise RuntimeError(f"{name} is not set: it must name {what} (no default location is assumed)")
return Path(v)
B = _env_dir('RIDGE_WORK', 'the work directory (the mosaic / ray caches)')
COP = _env_dir('RIDGE_TILES', 'the directory of Copernicus GLO-30 tiles (Copernicus_DSM_COG_10_*_DEM.tif)')
W = 6400 # ring columns: 360 deg at 17.78 px/deg
WIN = 1280 # window = 72 deg of the ring
HPX_DEG = W / 360.0
H = 600 # frame rows
COLW = math.radians(360.0 / W)
R_EARTH, KREF = 6371000.0, 0.13
P = {} # configured preset
rowang = np.zeros(H); PXDEG_V = 100.0; TOP_DEG = 2.6; BOTTOM_DEG = -3.4
def load_preset(pid, path=Path(__file__).resolve().parent / 'places.json'):
"""The preset dict. card_split_km is the ordered list of authored seam depths (km): required, strictly increasing, at most export.MAX_CARDS - 1 (the cap is export's, which owns the budget); refused here, before any march."""
d = json.load(open(path)); p = dict(next(x for x in d['presets'] if x['id'] == pid)); sp = p.get('card_split_km')
from export import MAX_CARDS
if not sp: raise ValueError(f"preset {pid}: card_split_km is required (an ordered list of 1 to {MAX_CARDS - 1} depths in km)")
if len(sp) > MAX_CARDS - 1 or any(b <= a for a, b in zip(sp, sp[1:])): raise ValueError(f"preset {pid}: card_split_km {sp} must be strictly increasing with at most {MAX_CARDS - 1} entries")
return p
# ====================================================================== configuration, DEM
def tiles_for(p):
lat, lon, r = p['lat'], p['lon'], p['rmax_km']; dl = r / 111.32; dn = r / (111.32 * math.cos(math.radians(lat))); out = []
for la in range(math.floor(lat - dl), math.floor(lat + dl) + 1):
for lo in range(math.floor(lon - dn), math.floor(lon + dn) + 1):
cy = min(max(lat, la), la + 1); cx = min(max(lon, lo), lo + 1)
if math.hypot((cy - lat) * 111.32, (cx - lon) * 111.32 * math.cos(math.radians(lat))) <= r: out.append((la, lo))
return out
def tile_path(la, lo): return COP / f"Copernicus_DSM_COG_10_{'N' if la >= 0 else 'S'}{abs(la):02d}_00_{'E' if lo >= 0 else 'W'}{abs(lo):03d}_00_DEM.tif"
def cache_key(*parts):
"""Short digest of everything a cached array was computed from. A cache file is read only under the key of its own inputs, so a changed preset field, tile list or baker constant never meets a stale file."""
h = hashlib.sha256()
for q in parts: h.update(q.tobytes() if isinstance(q, np.ndarray) else repr(q).encode()); h.update(b'|')
return h.hexdigest()[:12]
def mosaic_key(p): return cache_key('mosaic.v1', sorted(tiles_for(p)), 3600)
_mos = {}
def mosaic(p):
"""Tile grid covering the circle (bounding rows/cols), cached as .npy per preset. Missing tiles (open sea has no GLO-30 tile) are zero."""
key = (p['id'], mosaic_key(p))
if key in _mos: return _mos[key]
ts = tiles_for(p); las = [t[0] for t in ts]; los = [t[1] for t in ts]; lat_top = max(las) + 1; lon_left = min(los)
c = B / f"mosaic-{p['id']}-{key[1]}.npy"
if c.exists(): m = np.load(c, mmap_mode='r')
else:
rows = []
for la in range(max(las), min(las) - 1, -1):
rows.append(np.concatenate([tifffile.imread(tile_path(la, lo)) if tile_path(la, lo).exists() else np.zeros((3600, 3600), np.float32) for lo in range(min(los), max(los) + 1)], axis=1))
m = np.concatenate(rows, axis=0).astype(np.float32); np.save(c, m)
_mos[key] = (m, lat_top, lon_left); return _mos[key]
def bil(a, lat_top, lon_left, lat, lon):
y = (lat_top - lat) * 3600 - 0.5; x = (lon - lon_left) * 3600 - 0.5
y0 = np.clip(np.floor(y).astype(int), 0, a.shape[0] - 2); x0 = np.clip(np.floor(x).astype(int), 0, a.shape[1] - 2)
fy = np.clip(y - y0, 0, 1); fx = np.clip(x - x0, 0, 1)
return (a[y0, x0] * (1 - fx) * (1 - fy) + a[y0, x0 + 1] * fx * (1 - fy) + a[y0 + 1, x0] * (1 - fx) * fy + a[y0 + 1, x0 + 1] * fx * fy)
def configure(p):
"""Set the module state for a preset: observer, eye elevation (DEM ground + eye height, or ground_override), window azimuth."""
global P
P = p; m, lt, ll = mosaic(p)
ground = p['ground_override_m'] if 'ground_override_m' in p else float(bil(m, lt, ll, np.array(p['lat']), np.array(p['lon'])))
P['ground_m'] = ground; P['eye_m'] = ground + p['eye_h_m']
if 'look_at' in p:
la, lo = p['look_at']; P['az_center'] = (math.degrees(math.atan2((lo - p['lon']) * math.cos(math.radians(p['lat'])), la - p['lat'])) + 360) % 360
else: P['az_center'] = p['az_deg']
P['win0'] = int(round(P['az_center'] / 360 * W - WIN / 2)) % W
return P
def win(img): return np.take(img, (P['win0'] + np.arange(WIN)) % W, axis=1)
# ====================================================================== authored sub-DEM foreground detail (Aetheria / CultMath ridged multifractal)
def _frac(v): return v - np.floor(v)
def _hash2(x, y): return _frac(np.sin(x * 127.1 + y * 311.7) * 43758.5453) # cultmath_hash(vec2), as Ratatoskr noise.ts
def _vnoise2(x, y): # cultmath_value_noise: 4 hashed corners, smoothstep blend
cx, cy = np.floor(x), np.floor(y); u = x - cx; v = y - cy; u = u * u * (3 - 2 * u); v = v * v * (3 - 2 * v)
a, b, c, d = _hash2(cx, cy), _hash2(cx + 1, cy), _hash2(cx, cy + 1), _hash2(cx + 1, cy + 1)
return (a + (b - a) * u) * (1 - v) + (c + (d - c) * u) * v
LACUN, WEIGHT_GAIN, AMP_GAIN, CRAG = 2.07, 2.0, 0.5, 0.5 # ridgeWorld.ts constants
DETAIL = dict(cell_m=60.0, octaves=4, amp_m=24.0, fade_from_m=500.0, fade_to_m=4000.0, seed=17)
def detail_height(E, N, dist):
"""Ridged multifractal (ridgeWorld.ts `profile`, folded value noise weighted by the previous octave) in WORLD metres (east, north of the observer),
so it is automatically periodic around the ring. First octave wavelength = 60 m = two GLO-30 cells (nothing coarser than the DEM can resolve is
touched), then x2.07. Amplitude fades to zero between fade_from and fade_to metres of distance. Seeded, deterministic, authored."""
cfg = DETAIL; e = 0.03 + (1 - CRAG) * 0.4; top = math.sqrt(1 + e * e); s = 0.0; nrm = 0.0; amp = 1.0; f = 1.0 / cfg['cell_m']; w = 1.0
for k in range(cfg['octaves']):
v = 2 * _vnoise2(E * f + cfg['seed'] * 7.31, N * f + cfg['seed'] * 3.17 + k * 13) - 1
sig = (1 - np.sqrt(v * v + e * e) / top) ** 2 * w; w = np.minimum(1.0, sig * WEIGHT_GAIN); s = s + sig * amp; nrm += amp; amp *= AMP_GAIN; f *= LACUN
t = np.clip((dist - cfg['fade_from_m']) / (cfg['fade_to_m'] - cfg['fade_from_m']), 0, 1); fade = 1 - t * t * (3 - 2 * t)
return cfg['amp_m'] * fade * (s / nrm - 0.3)
# ====================================================================== stage 0: march
def schedule(detail):
d = [500.0]
while d[-1] < P['rmax_km'] * 1000:
d.append(d[-1] + min(250.0, max(10.0 if detail else 40.0, 0.004 * d[-1])))
return np.array(d)
def elev(h, d, curvature=True):
"""Elevation angle (degrees) of height h (m) at distance d (m) from the eye: Earth curvature with refraction. The one formula of march and prefilter."""
drop = d * d / (2 * R_EARTH) * (1 - KREF) if curvature else 0.0
return np.degrees(np.arctan2(h - P['eye_m'] - drop, d))
def march(detail=False, curvature=True):
m, lt, ll = mosaic(P); az = np.radians((np.arange(W) + 0.5) / W * 360.0); d = schedule(detail); cosl = math.cos(math.radians(P['lat']))
A = np.zeros((len(d), W), np.float32); Hh = np.zeros_like(A); sa, ca = np.sin(az), np.cos(az)
for k, dk in enumerate(d):
lat = P['lat'] + dk * ca / 111320.0; lon = P['lon'] + dk * sa / (111320.0 * cosl)
h = bil(m, lt, ll, lat, lon)
if detail and dk < DETAIL['fade_to_m']: h = h + detail_height(dk * sa, dk * ca, dk)
A[k] = elev(h, dk, curvature); Hh[k] = h
return d, A, Hh
def rays_key(detail):
"""Inputs of the ray march: observer, eye elevation, range, the DEM mosaic, the sample schedule (hashed as the array it produces), the Earth / refraction constants, the ring width, and (detail) the foreground detail noise."""
return cache_key('rays.v1', P['lat'], P['lon'], P['rmax_km'], round(float(P['eye_m']), 3), mosaic_key(P), schedule(detail), R_EARTH, KREF, W, bool(detail),
(sorted(DETAIL.items()), LACUN, WEIGHT_GAIN, AMP_GAIN, CRAG) if detail else None)
def stage0(detail=False, force=False):
c = B / f"rays-{P['id']}{'-detail' if detail else ''}-{rays_key(detail)}.npz"
if c.exists() and not force:
z = np.load(c); return z['d'], z['ang'], z['h'], None
t0 = time.time(); mosaic(P); t1 = time.time(); d, A, Hh = march(detail); t2 = time.time(); np.savez(c, d=d, ang=A, h=Hh)
return d, A, Hh, dict(mosaic=t1 - t0, march=t2 - t1, samples=len(d))
# ====================================================================== periodic helpers
def blurw(a, s):
r = int(3 * s) + 1; k = np.exp(-0.5 * (np.arange(-r, r + 1) / s) ** 2); k /= k.sum()
a = np.asarray(a, np.float64); xp = np.concatenate([a[..., -r:], a, a[..., :r]], axis=-1); o = np.zeros_like(a)
for i, kv in enumerate(k): o += kv * xp[..., i:i + a.shape[-1]]
return o
# ====================================================================== prefilter: the march is a heightfield of roofs and hills; the cards want the hills
def prefilter(d, h, sigma_m):
"""Gaussian low-pass of the ray heights h (K, W): along each ray with sigma sigma_m metres (weighted by sample spacing, the schedule is not uniform), then across rays at equal distance with
sigma = sigma_m / (d * COLW) columns (periodic, exact in the Fourier domain). Angles are recomputed from the filtered heights with elev. Returns (angles, heights); sigma_m 0 leaves the heights as they are."""
d = np.asarray(d, np.float64); h = np.asarray(h, np.float64)
if sigma_m > 0:
f = np.fft.rfftfreq(h.shape[1]); sc = sigma_m / (d * COLW)
h = np.fft.irfft(np.fft.rfft(h, axis=1) * np.exp(-2 * (np.pi * f[None, :] * sc[:, None]) ** 2), n=h.shape[1], axis=1)
dd = np.gradient(d); out = np.empty_like(h)
for k in range(len(d)):
r = int(min(3 * sigma_m / dd[k] + 1, 60)); lo, hi = max(0, k - r), min(len(d), k + r + 1)
w = np.exp(-0.5 * ((d[lo:hi] - d[k]) / sigma_m) ** 2) * dd[lo:hi]; out[k] = (w[:, None] * h[lo:hi]).sum(0) / w.sum()
h = out
return elev(h, d[:, None]), h
def normals(d, h):
"""Surface normal at every ray sample (n_r, n_t, n_up), each (K, W): n_r along the ray, n_t across it (towards increasing azimuth), n_up vertical. The slopes are the ray's own dh/dd and the difference of the
neighbouring columns at the SAME sample (equal distance, never equal row) over 2 d COLW, both times the authored vertical exaggeration PXDEG_V / HPX_DEG, so a face reads as steep as the view draws it."""
d = np.asarray(d, np.float64); h = np.asarray(h, np.float64); E = PXDEG_V / HPX_DEG
sr = E * np.gradient(h, d, axis=0); st = E * (np.roll(h, -1, axis=1) - np.roll(h, 1, axis=1)) / (2 * d[:, None] * COLW); nz = 1.0 / np.sqrt(1 + sr * sr + st * st)
return -sr * nz, -st * nz, nz
# ====================================================================== the authored Y mapping
def set_view(skyline, sky_row=0.04, near_row=0.66):
"""AUTHORED vertical mapping, linear in elevation angle: row = (TOP_DEG - angle) * PXDEG_V over the whole 600-row frame (cylindrical, horizontal 17.78 px/deg). skyline is the highest angle any sample reaches in each
ring column (W,), straight from the march. Two anchors: the highest skyline angle in the window sits at `sky_row` (4%) of the frame height, the LOWEST sits at `near_row` (66%); everything below is body and ground.
PXDEG_V = (near_row - sky_row) * 600 / (highest - lowest), clamped to [17.78, 178] px/deg = vertical exaggeration 1x..10x. TOP_DEG = highest + sky_row*600/PXDEG_V; BOTTOM_DEG = TOP_DEG - 600/PXDEG_V."""
global rowang, PXDEG_V, TOP_DEG, BOTTOM_DEG
w = win(np.asarray(skyline)[None, :])[0]; sky = float(w.max()); low = float(w.min())
ppd = float(np.clip((near_row - sky_row) * H / max(sky - low, 0.05), HPX_DEG, 10 * HPX_DEG))
PXDEG_V = ppd; TOP_DEG = sky + sky_row * H / ppd; BOTTOM_DEG = TOP_DEG - H / ppd; rowang = TOP_DEG - (np.arange(H) + 0.5) / PXDEG_V
return dict(top_deg=TOP_DEG, bottom_deg=BOTTOM_DEG, px_per_deg=PXDEG_V, exaggeration=PXDEG_V / HPX_DEG, horizon_row=TOP_DEG * PXDEG_V, sky_deg=sky, low_deg=low, sky_row=sky_row, near_row=near_row)
# ====================================================================== coverage and seams
COV_BINS = 160 # log-distance bins between the first and the last sample
SIG_B = 1.5 # blur of the coverage along depth (bins): seams settle in gaps
SEAM_LAM, SEAM_UNARY = 2.0, 0.25 # forward energy: a seam that moves a bin between neighbouring columns pays SEAM_LAM per bin plus every visible row it sweeps; one that sits in visible terrain pays SEAM_UNARY x those rows (cross-fadable)
SEAM_PRIOR = 0.02 # the authored depth is a faint pull, rows per nat^2 (the test pins the window: six synthetic receding ridges tear at 0.1, and without the swept-rows term at 0.02 they tear again)
SEAM_SEP = 0.4 # seams at least this far apart in log-distance (nat)
XF = 0.07 # half-width of a seam's cross-fade, nat (about two bins)
def log_edges(d, nb=COV_BINS): L = np.log(np.asarray(d, np.float64)); return np.linspace(L[0], L[-1] + 1e-9, nb + 1)
def opaque(a):
"""Coverage 0..1 of every frame row by the opaque view of angles a (K, n): the share of the row's angular span under the column skyline."""
p = 1.0 / PXDEG_V; lo = rowang - 0.5 * p; return np.clip((np.asarray(a, np.float64).max(0)[None, :] - lo[:, None]) / p, 0, 1)
def coverage(d, a, nb=COV_BINS):
"""(nb, n): rows of the opaque view first revealed by the samples of each log-distance bin, per column. The first sample reveals every row from the frame bottom up to its angle, so the rows below it (nearer than it) count in bin 0. Needs set_view."""
a = np.asarray(a, np.float64); edges = log_edges(d, nb); kb = np.clip(np.searchsorted(edges, np.log(d), 'right') - 1, 0, nb - 1)
runmax = np.maximum.accumulate(a, axis=0); prev = np.vstack([np.full((1, a.shape[1]), BOTTOM_DEG), runmax[:-1]])
C = np.zeros((nb, a.shape[1])); np.add.at(C, kb, np.clip(np.minimum(a, TOP_DEG) - np.maximum(prev, BOTTOM_DEG), 0, None) * PXDEG_V)
return C
def _dt(f, u):
"""out[i] = min_k f[k] + |u[i] - u[k]| along axis 0, u increasing: two cumulative-minimum passes (Felzenszwalb & Huttenlocher's L1 distance transform)."""
u = u.reshape((-1,) + (1,) * (f.ndim - 1)); return np.minimum(np.minimum.accumulate(f - u, axis=0) + u, np.flip(np.minimum.accumulate(np.flip(f + u, 0), axis=0), 0) - u)
def seams(cov, targets, d):
"""(K, n) ordered seam distances (m), one per authored target (m), each column. One 1D forward-energy DP per seam, in target order (seam carving, Avidan & Shamir 2007; forward energy, Rubinstein et al. 2008): unary
SEAM_UNARY x the rows at the seam; moving a bin between neighbouring columns costs SEAM_LAM per bin plus the rows swept, an L1 distance in u = cumsum(rows) + SEAM_LAM x bin; a weak prior to the target. Seam k is held at
least SEAM_SEP nat beyond seam k-1 in every column. Sequential, not joint: a joint DP has NB^K states per column and seams in gaps do not interact."""
cov = np.asarray(cov, np.float64); nb, n = cov.shape; edges = log_edges(d, nb); bc = 0.5 * (edges[:-1] + edges[1:]); sep = int(math.ceil(SEAM_SEP / (edges[1] - edges[0]))); INF = 1e12
r = int(3 * SIG_B) + 1; kern = np.exp(-0.5 * (np.arange(-r, r + 1) / SIG_B) ** 2); kern /= kern.sum(); pad = np.pad(cov, ((r, r), (0, 0)), mode='edge'); Cs = sum(kv * pad[i:i + nb] for i, kv in enumerate(kern))
bins = np.arange(nb); lo = np.zeros(n, int); out = np.zeros((len(targets), n))
for t, T in enumerate(targets):
prior = SEAM_PRIOR * (bc - math.log(T)) ** 2; need = np.minimum(lo + (sep if t else 0), nb - 1); feas = bins[:, None] >= need[None, :]
warp = lambda x: np.cumsum(0.5 * (cov[:, x - 1] + cov[:, x])) + SEAM_LAM * bins
cost = np.where(feas[:, 0], SEAM_UNARY * Cs[:, 0] + prior, INF); store = [cost]
for x in range(1, n): cost = np.where(feas[:, x], _dt(cost, warp(x)) + SEAM_UNARY * Cs[:, x] + prior, INF); store.append(cost)
j = np.zeros(n, int); j[-1] = int(np.argmin(store[-1]))
for x in range(n - 1, 0, -1): u = warp(x); j[x - 1] = int(np.argmin(store[x - 1] + np.abs(u - u[j[x]])))
out[t] = np.exp(bc[j]); lo = j
return out
# ====================================================================== cards: layered depth, one per band between seams
GRASS, FOREST, ROCK, SNOW = (0.36, 0.44, 0.26), (0.22, 0.31, 0.20), (0.47, 0.44, 0.41), (0.93, 0.95, 0.97)
def albedo(h, n_up):
"""The authored material, a few numbers: valley green to forest to rock by height, rock where the face is steep, snow above the tree line. Straight colour, no light in it."""
t = lambda a, b: np.clip((h - a) / (b - a), 0, 1)[..., None]; c = np.asarray(GRASS) + (np.asarray(FOREST) - GRASS) * t(150, 900); c = c + (np.asarray(ROCK) - c) * t(1300, 2000)
c = c + (np.asarray(ROCK) - c) * np.clip((0.93 - n_up) / 0.25, 0, 1)[..., None]; return c + (np.asarray(SNOW) - c) * (t(1900, 2300) * np.clip((n_up - 0.55) / 0.3, 0, 1)[..., None])
def cards(d, a, h, seams, nrm=None):
"""K+1 cards, nearest first, from the angles a and heights h (samples, n) of n columns and the (K, n) seams (m). Card i holds per pixel the FIRST VISIBLE hit at or beyond seam i-1 (less XF): layered depth, so a farther
card keeps the terrain a nearer ridge hides. Its alpha is that pixel's coverage (a crest row holds the share of its angular span under the card's running maximum) times 1 - smoothstep over seam i +- XF in
log-distance of the hit; card 0 owns the rows below the first sample, the last card has no far edge. Alphas are then made nested so the alpha-over composite of all cards is exactly the opaque coverage (a row two
cards both hold partly is not counted twice). Distance and normal are interpolated between sample k-1 and k by angle. Each card is cropped to the rows where its 8-bit alpha is not zero.
nrm is normals(d, h) of the same columns (default: computed from h as given, so pass it for a window cut from the ring). Rows of a card i > 0 below the angle of its first sample (hit and idx == 0) are the extruded wall of the ridge the card starts at: they keep that sample's distance, their albedo is the ground material at their height with the face up (n_up = 1),
and `wall` flags them (card 0 has no wall: its rows below the first sample are the ground). Each card: dict(top, alpha (h,n), albedo (h,n,3), n_r, n_t, logd (ln metres) (h,n), wall (h,n) bool)."""
d = np.asarray(d, np.float64); a = np.asarray(a, np.float64); h = np.asarray(h, np.float64); seams = np.asarray(seams, np.float64); nk, n = a.shape; nc = len(seams) + 1
n_r, n_t, n_u = nrm if nrm is not None else normals(d, h); ld = np.broadcast_to(np.log(d)[:, None], (nk, n)); p = 1.0 / PXDEG_V; lo = rowang - 0.5 * p
ks0 = [np.searchsorted(d, seams[i - 1] * math.exp(-XF)) for i in range(1, nc)]; ks1 = [np.searchsorted(d, seams[i] * math.exp(XF)) for i in range(nc - 1)]
F = np.zeros((nc, H, n)); X = np.ones((nc, H, n)); G = np.zeros((nc, 5, H, n)); Wl = np.zeros((nc, H, n), bool) # coverage, far fade, then (logd, h, n_r, n_t, n_u); wall rows
for x in range(n):
for i in range(nc):
k0 = 0 if i == 0 else int(ks0[i - 1][x]); k1 = nk if i == nc - 1 else int(ks1[i][x])
if k1 <= k0: continue
rm = np.maximum.accumulate(a[k0:k1, x]); idx = np.searchsorted(rm, lo, 'right'); hit = idx < len(rm); idx = np.minimum(idx, len(rm) - 1); kk = k0 + idx
if not hit.any(): continue
kp = np.maximum(kk - 1, k0); prev = np.where(idx > 0, rm[np.maximum(idx - 1, 0)], rm[idx] - 1.0)
t = np.where(idx > 0, np.clip((rowang - prev) / np.maximum(rm[idx] - prev, 1e-9), 0, 1), 1.0); mix = lambda arr: arr[kp, x] + t * (arr[kk, x] - arr[kp, x])
F[i, :, x] = np.where(hit, np.clip((rm[-1] - lo) / p, 0, 1), 0); lh = mix(ld)
G[i, :, :, x] = np.where(hit, np.stack([lh, mix(h), mix(n_r), mix(n_t), mix(n_u)]), 0)
if i: Wl[i, :, x] = hit & (idx == 0) # rows below the card's first sample: the extruded wall (card 0's are the ground)
if i < nc - 1: s = np.clip((lh - (math.log(seams[i, x]) - XF)) / (2 * XF), 0, 1); X[i, :, x] = 1 - s * s * (3 - 2 * s)
out = []; A = np.zeros((H, n))
for i in range(nc):
part = np.where(F[i] < 1, np.clip((np.maximum(A, F[i]) - A) / np.maximum(1 - A, 1e-6), 0, 1), F[i]); al = np.where(np.rint(X[i] * part * 255) > 0, X[i] * part, 0.0); A = 1 - (1 - A) * (1 - al)
rows = np.flatnonzero(al.max(1) > 0)
if not len(rows): out.append(dict(top=0, alpha=np.zeros((0, n), np.float32), albedo=np.zeros((0, n, 3), np.float32), n_r=np.zeros((0, n), np.float32), n_t=np.zeros((0, n), np.float32), logd=np.zeros((0, n), np.float32), wall=np.zeros((0, n), bool))); continue
sl = slice(int(rows[0]), int(rows[-1]) + 1); g = G[i, :, sl]; nz = np.sqrt(g[2] ** 2 + g[3] ** 2 + g[4] ** 2) + 1e-12
out.append(dict(top=int(rows[0]), alpha=al[sl].astype(np.float32), albedo=albedo(g[1], np.where(Wl[i, sl], 1.0, g[4] / nz)).astype(np.float32), n_r=(g[2] / nz).astype(np.float32), n_t=(g[3] / nz).astype(np.float32), logd=g[0].astype(np.float32), wall=Wl[i, sl].copy()))
return out

View file

@ -0,0 +1,60 @@
"""Mutation check: re-introduce a cause into a COPY of the baker, run the fixtures against it, and require that at least one fails.
venv/bin/python tests/mutate.py (prints one line per mutant; exit 1 if a mutant survives)"""
import os, shutil, subprocess, sys, tempfile
HERE = os.path.dirname(os.path.abspath(__file__)); SRC = os.path.join(HERE, '..')
MUTANTS = { # name -> (text in ridge.py or export.py, replacement)
'seam cost: the rows a seam sweeps are not paid (it hops across a receding ridge)': ("np.cumsum(0.5 * (cov[:, x - 1] + cov[:, x])) + SEAM_LAM * bins", "SEAM_LAM * bins"),
'seam prior pulls hard to the target (2.0, or 0.1: the seam hops across a ridge)': ("SEAM_PRIOR = 0.02 ", "SEAM_PRIOR = 2.0 "),
'normals: the authored exaggeration is dropped': ("h = np.asarray(h, np.float64); E = PXDEG_V / HPX_DEG", "h = np.asarray(h, np.float64); E = 1.0"),
'normals: the lateral neighbour is one sample nearer (not equal distance)': ("st = E * (np.roll(h, -1, axis=1) - np.roll(h, 1, axis=1))", "st = E * (np.roll(np.roll(h, -1, axis=1), 1, axis=0) - np.roll(h, 1, axis=1))"),
'cards: the near edge is ignored (every card starts at sample 0)': ("k0 = 0 if i == 0 else int(ks0[i - 1][x])", "k0 = 0"),
'cards: the farther card fades in over the window too (both cards translucent)': ("X[i, :, x] = 1 - s * s * (3 - 2 * s)", "X[i, :, x] = 1 - s * s * (3 - 2 * s); X[i + 1, :, x] = s * s * (3 - 2 * s)"),
'cards: a crest row is all or nothing (no fractional coverage)': ("F[i, :, x] = np.where(hit, np.clip((rm[-1] - lo) / p, 0, 1), 0)", "F[i, :, x] = np.where(hit, 1.0, 0)"),
'prefilter ignores sigma': ("if sigma_m > 0:", "if False:"),
'prefilter across rays uses one sigma in columns (not per distance)': ("sc = sigma_m / (d * COLW)", "sc = sigma_m / (d[0] * COLW) * np.ones_like(d)"),
'bake_id hashes geometry before colour': ("h.update(colour); h.update(geometry)", "h.update(geometry); h.update(colour)"),
'check_cover accepts any composite': ("if bad.any(): y, x", "if False: y, x"),
'check_budget ignores the cropped bands (decoded as full frames)': ("decoded = sum(2 * w * h * 4 for h in bands)", "decoded = 0"),
'load_preset accepts splits that do not increase': ("or any(b <= a for a, b in zip(sp, sp[1:]))", ""),
'geometry: n_r and n_t channels swapped': ("r, t = u8((np.asarray(n_r) + 1) / 2), u8((np.asarray(n_t) + 1) / 2)", "r, t = u8((np.asarray(n_t) + 1) / 2), u8((np.asarray(n_r) + 1) / 2)"),
'geometry: log-distance not normalised by the encoding range': ("b = (np.asarray(logd) - enc['log_d_min']) / (enc['log_d_max'] - enc['log_d_min'])", "b = np.asarray(logd) / 12.0"),
'colour: albedo zeroed in the file': ("rgb = u8(albedo) * (a[..., None] > 0)", "rgb = u8(albedo) * 0"),
'colour: premultiplied instead of straight': ("rgb = u8(albedo) * (a[..., None] > 0)", "rgb = u8(np.asarray(albedo) * np.asarray(alpha)[..., None])"),
'seams: the separation between seams is ignored': ("SEAM_SEP = 0.4 ", "SEAM_SEP = 0.0 "),
'elev: curvature and refraction dropped': ("drop = d * d / (2 * R_EARTH) * (1 - KREF) if curvature else 0.0", "drop = 0.0"),
'coverage: the rows below the first sample are not counted': ("prev = np.vstack([np.full((1, a.shape[1]), BOTTOM_DEG), runmax[:-1]])", "prev = np.vstack([np.full((1, a.shape[1]), 100.0), runmax[:-1]])"),
'coverage: the rows below the first sample are counted twice': ("* PXDEG_V)\n return C", "* PXDEG_V); C[0] += np.clip(np.minimum(a[0], TOP_DEG) - BOTTOM_DEG, 0, None) * PXDEG_V\n return C"),
'cards: the hit is not interpolated between samples': ("t = np.where(idx > 0, np.clip((rowang - prev) / np.maximum(rm[idx] - prev, 1e-9), 0, 1), 1.0)", "t = np.ones_like(rowang)"),
'cards: the blended normal is not renormalised': ("nz = np.sqrt(g[2] ** 2 + g[3] ** 2 + g[4] ** 2) + 1e-12", "nz = 1.0"),
'wall: no row is flagged (the flag is dropped)': ("if i: Wl[i, :, x] = hit & (idx == 0)", "if i: Wl[i, :, x] = False"),
'wall: card 0 is flagged too (its ground rows become wall)': ("if i: Wl[i, :, x] = hit & (idx == 0)", "Wl[i, :, x] = hit & (idx == 0)"),
'wall: albedo takes the face normal, not the face up': ("np.where(Wl[i, sl], 1.0, g[4] / nz)", "g[4] / nz"),
'wall: the code is not written to the geometry': ("if wall is not None: m = np.asarray(wall, bool)", "if False: m = np.asarray(wall, bool)"),
'wall: the sheet lights wall rows with their normal': ("wall = c['wall']; n_r, n_t = np.where(wall, 0.0, c['n_r']), np.where(wall, 0.0, c['n_t'])", "n_r, n_t = c['n_r'], c['n_t']"),
'camera: the sign of r is flipped in the scale': ("return [d / (d - r_m) for d in distances]", "return [d / (d + r_m) for d in distances]"),
'camera: the scale is clamped (a function of r that is not the formula)': ("return [d / (d - r_m) for d in distances]", "return [min(d / (d - r_m), 1.2) for d in distances]"),
'camera: the card distance includes wall rows': ("ground = (c['alpha'] >= 0.5) & ~c['wall']", "ground = (c['alpha'] >= 0.5)"),
'camera: the offset bound is ignored': ("if abs(r_m) >= R_FRAC_MAX * min(distances): raise", "if False: raise"),
'camera: the frame-bottom coverage check is removed': ("if bottom < view['plane_h'] - 1e-6: raise", "if False: raise"),
'camera: the 16:9 rest coverage check is removed': ("if min(scales) < REST_SCALE_MIN: raise", "if False: raise"),
'camera: the preset camera_r_m is ignored': ("r_m=float(p.get('camera_r_m', CAMERA_R_M))", "r_m=float(CAMERA_R_M)"),
'camera: the manifest writes the default heading range, not the bake\'s': ("heading_max_deg=meta['camera']['heading_max_deg']),", "heading_max_deg=HEADING_MAX_DEG),"),
'export: an empty card is not refused': ("if c['alpha'].shape[0] == 0: raise", "if False: raise"),
'rays cache key ignores the refraction constant': ("R_EARTH, KREF, W, bool(detail)", "R_EARTH, W, bool(detail)"),
'rays cache key ignores the eye elevation': ("round(float(P['eye_m']), 3), ", ""),
'mosaic cache key ignores the tile list': ("sorted(tiles_for(p)), 3600", "3600"),
}
EQUIVALENT = {} # mutant name -> one line on why it is behaviourally equivalent (reported, not run)
def run(item):
name, (a, b) = item; d = tempfile.mkdtemp(); shutil.copytree(SRC, os.path.join(d, 'src'), ignore=shutil.ignore_patterns('tests', '__pycache__')); p = next(q for q in (os.path.join(d, 'src', f) for f in ('ridge.py', 'export.py')) if a in open(q).read()); s = open(p).read(); assert a in s, name
open(p, 'w').write(s.replace(a, b))
r = subprocess.run([sys.executable, os.path.join(HERE, 'test_ridge.py')], env=dict(os.environ, RIDGE_SRC=os.path.join(d, 'src')), capture_output=True, text=True); shutil.rmtree(d)
fails = [l.split('|')[0].strip() for l in r.stdout.splitlines() if l.startswith('FAIL')]
line = ('KILLED ' if r.returncode else 'SURVIVED ') + name + ' -> ' + (', '.join(fails) or 'no fixture failed'); print(line, file=sys.stderr, flush=True) # progress: a killed run keeps what finished
return line, r.returncode == 0
if __name__ == '__main__':
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(int(os.environ.get('MUTATE_JOBS', '6'))) as ex: res = list(ex.map(run, [(n, v) for n, v in MUTANTS.items() if n not in EQUIVALENT]))
for line, _ in res: print(line, flush=True)
for n, why in EQUIVALENT.items(): print('EQUIVALENT ' + n + ' -> ' + why)
sys.exit(1 if any(sv for _, sv in res) else 0)

View file

@ -0,0 +1,7 @@
#!/bin/sh
# Usage: RIDGE_PY=<venv python> RIDGE_TILES=<tiles dir> tests/run.sh [test_ridge.py|mutate.py]
# RIDGE_WORK (cache dir) defaults to a fresh directory under $TMPDIR.
: "${RIDGE_PY:?RIDGE_PY must name the python of the baker venv}"
export RIDGE_WORK="${RIDGE_WORK:-${TMPDIR:-/tmp}/ridge-bake-work}"; mkdir -p "$RIDGE_WORK"
HERE=$(cd "$(dirname "$0")" && pwd)
exec "$RIDGE_PY" -I "$HERE/${1:-test_ridge.py}"

View file

@ -0,0 +1,385 @@
"""Fixtures for the ridge baker (march, prefilter, coverage, seams, normals, cards, export). Plain asserts, no pytest needed: venv/bin/python tests/test_ridge.py (exit code 1 on failure).
RIDGE_SRC selects the source directory (default ..) (the mutation runner points it at a patched copy).
Synthetic terrain has a known right answer; the Vienna tests bake the real preset (its rays come from stage0: RIDGE_TILES needs the tiles, or a cached rays file must exist)."""
import os, sys, math, json, shutil, tempfile, traceback
SRC = os.environ.get('RIDGE_SRC') or os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'); sys.path.insert(0, SRC) # RIDGE_WORK and RIDGE_TILES must be set (tests/run.sh sets them)
import numpy as np, ridge, export
from ridge import W, WIN, H
EYE = 100.0; GROUND = 50.0 # ground below the eye: every ray climbs, so only the placed blocks make ridges
ridge.P = dict(id='synthetic', rmax_km=95, eye_m=100.0, win0=0)
D = ridge.schedule(False)
def az_of(x): return (x + 0.5) / W * 360.0
def col_of(az): return int(round(az / 360.0 * W - 0.5)) % W
def rays(hfun):
az = (np.arange(W) + 0.5) / W * 360.0; A = np.zeros((len(D), W), np.float32); Hh = np.zeros_like(A)
for k, dk in enumerate(D):
h = hfun(dk, az); Hh[k] = h; A[k] = np.degrees(np.arctan2(h - EYE - dk * dk / (2 * ridge.R_EARTH) * (1 - ridge.KREF), dk))
return A, Hh
def theta(h, d): return math.degrees(math.atan2(h - EYE - d * d / (2 * ridge.R_EARTH) * (1 - ridge.KREF), d))
def in_arc(az, a0, a1): return ((az - a0) % 360.0) <= ((a1 - a0) % 360.0)
def block(a0, a1, d0, d1, h): return lambda dk, az: np.where(in_arc(az, a0, a1) & (dk >= d0) & (dk < d1), h, 0.0)
def terrain(*blocks): return lambda dk, az: np.maximum.reduce([np.full_like(az, GROUND)] + [np.asarray(b(dk, az), float) for b in blocks])
def test_cache_keys_follow_every_input_of_the_cached_array():
"""mosaic-/rays- cache files are keyed by a digest of their inputs. Right answer: identical inputs -> identical key (the preset id does not enter), a changed preset field (eye height, range, position), tile list or baker constant (refraction, detail noise) -> a different key."""
saved = ridge.P
try:
base = dict(id='k1', lat=47.0, lon=11.0, rmax_km=40, eye_m=2000.0); ridge.P = dict(base); k0 = (ridge.rays_key(False), ridge.rays_key(True), ridge.mosaic_key(ridge.P))
ridge.P = dict(base, id='other'); assert (ridge.rays_key(False), ridge.rays_key(True), ridge.mosaic_key(ridge.P)) == k0, 'the preset id changed the key'
for fld, v in (('eye_m', 2010.0), ('rmax_km', 41), ('lon', 11.001), ('lat', 47.001)):
ridge.P = dict(base, **{fld: v}); assert ridge.rays_key(False) != k0[0], ('rays key ignores', fld)
ridge.P = dict(base, lat=47.0, lon=13.5); assert ridge.mosaic_key(ridge.P) != k0[2], 'mosaic key ignores the tile list'
ridge.P = dict(base); old = ridge.KREF; ridge.KREF = 0.2
try: assert ridge.rays_key(False) != k0[0], 'rays key ignores the refraction constant'
finally: ridge.KREF = old
old = ridge.DETAIL; ridge.DETAIL = dict(old, amp_m=30.0)
try: assert ridge.rays_key(True) != k0[1] and ridge.rays_key(False) == k0[0], 'detail key ignores the noise settings (or the plain key follows them)'
finally: ridge.DETAIL = old
finally: ridge.P = saved
def test_paths_come_from_the_environment_with_no_default():
"""Importing the baker without RIDGE_WORK / RIDGE_TILES fails with a message naming the variable (no location is assumed)."""
import subprocess; env = {k: v for k, v in os.environ.items() if not k.startswith('RIDGE_')}
for var in ('RIDGE_WORK', 'RIDGE_TILES'):
e = dict(env); e.update({'RIDGE_WORK': '.', 'RIDGE_TILES': '.'}); del e[var]
r = subprocess.run([sys.executable, '-I', '-c', 'import sys; sys.path.insert(0, %r); import ridge' % SRC], env=e, capture_output=True, text=True); assert r.returncode and var in r.stderr and 'not set' in r.stderr, (var, r.stderr[-200:])
# ---------------------------------------------------------------------------------------- synthetic bakes: the shared steps of export.bake_place on rays the fixtures make
def _bake(hfun, splits_km, sigma=0.0):
"""prefilter, set_view, coverage, seams, cards on synthetic rays (window = columns 0..WIN, i.e. azimuth 0..72): the dict bake_place returns."""
A, Hh = rays(hfun); ridge.P.update(win0=0, eye_m=EYE); a, h = ridge.prefilter(D, Hh, sigma); v = ridge.set_view(a.max(0))
nrm = tuple(ridge.win(x) for x in ridge.normals(D, h)); aw, hw = ridge.win(a), ridge.win(h); cov = ridge.coverage(D, aw); sm = ridge.seams(cov, [k * 1000.0 for k in splits_km], D)
place = dict(id='synthetic', name='Synthetic', lat=48.0, lon=16.0, altitude_km=0.05, eye_m=EYE)
view = dict(look_az_deg=36.0, plane_h=H, px_per_deg_h=ridge.HPX_DEG, px_per_deg_v=v['px_per_deg'], exaggeration=v['exaggeration'], horizon_row=v['horizon_row'], sky_row=v['sky_row'] * H, near_row=v['near_row'] * H)
meta = dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(D[0]), log_d_max=math.log(D[-1])), camera=dict(r_m=export.CAMERA_R_M, heading_max_deg=17.0))
return dict(place=place, view=view, meta=meta, cards=ridge.cards(D, aw, hw, sm, nrm, ), splits_km=list(splits_km), seams=sm, cov=cov, opaque=ridge.opaque(aw), edges=ridge.log_edges(D), a=aw, h=hw, v=v)
def _canvas(card, key='alpha'):
out = np.zeros((H, WIN) + card[key].shape[2:], np.float32); out[card['top']:card['top'] + card[key].shape[0]] = card[key]; return out
def _row(deg): return int(np.argmin(np.abs(ridge.rowang - deg)))
THREE = terrain(block(0, 359.99, 3000, 3600, 350), block(0, 359.99, 20000, 21500, 1800), block(0, 359.99, 70000, 72000, 7000)) # ridges at 3, 20 and 70 km, each taller in angle than the one before
WIDE3 = terrain(block(0, 359.99, 9000, 10000, 300), block(0, 359.99, 38000, 40000, 2000), block(0, 359.99, 70000, 72000, 3000)) # low near hills, then ridges at 39 and 71 km: the frame reaches below the ground at the seams (so cards have wall rows) and the horizon is inside it
WALLED = terrain(block(0, 359.99, 9000, 10000, 300), block(0, 359.99, 38000, 40000, 2000))
NEARHILL = terrain(block(0, 359.99, 0, 4000, 150), block(0, 359.99, 38000, 40000, 2000)) # ground above the eye from the first sample on: every row of card 0 lies below its first sample
def _ramp(dk, az): return np.maximum(GROUND, np.where(dk > 12000, (dk - 12000) * 0.045 + 50.0, 0.0)) # a slope the first sample of card 1 stands on: n_up about 0.9, so the material would be rock if the face counted
def test_seams_fall_in_depth_gaps():
"""Three ridges at 3, 20 and 70 km: targets [6, 40] give a seam in (3, 20) and one in (20, 70) in EVERY column, ordered with at least 0.4 nat between; targets [6] give one seam in (3, 20)."""
b = _bake(THREE, [6, 40]); s = b['seams']; assert s.shape == (2, WIN)
assert (s[0] > 3600).all() and (s[0] < 20000).all() and (s[1] > 21500).all() and (s[1] < 70000).all(), (s.min(1), s.max(1)); assert (np.log(s[1]) - np.log(s[0]) >= 0.4 - 1e-9).all()
s1 = _bake(THREE, [6])['seams']; assert s1.shape == (1, WIN) and (s1[0] > 3600).all() and (s1[0] < 20000).all(), (s1.min(), s1.max())
def _recede(d0, d1, thick=300.0, hgt=1500.0):
"""A ridge `thick` m thick whose distance runs from d0 m at azimuth 0 to d1 m at azimuth 72."""
return terrain(lambda dk, az: np.where((az <= 72) & (np.abs(dk - (d0 + (d1 - d0) * np.clip(az / 72.0, 0, 1))) < thick / 2), hgt, 0.0))
def _receding(dk, az): return _recede(4000.0, 15000.0)(dk, az)
def test_the_swept_rows_term_keeps_the_seam_from_hopping_under_a_stronger_pull():
"""With the authored depth pulling harder (0.1 instead of 0.02) the 4 to 15 km ridge's seam still follows the ridge: only the cost of the visible rows it would sweep holds it back (with that term out of the cost it hops between two columns)."""
old = ridge.SEAM_PRIOR; ridge.SEAM_PRIOR = 0.1
try: j0, j1, cover = _alpha_jumps(4, 15, 6)
finally: ridge.SEAM_PRIOR = old
assert j0 < 0.35 and j1 < 0.35 and cover > 0.999, ('the seam hopped across the ridge', j0, j1)
RECEDING = [(4, 15, 6), (3, 12, 6), (5, 30, 12), (8, 40, 15), (4, 15, 10), (6, 14, 9)] # km at azimuth 0, km at azimuth 72, authored split km
def _alpha_jumps(d0, d1, split):
"""The two cards' alpha on the ridge body (crest + 4 rows), column to column: the largest step of each. """
b = _bake(_recede(d0 * 1000.0, d1 * 1000.0), [split]); c0 = _canvas(b['cards'][0]); c1 = _canvas(b['cards'][1]); crest = np.argmax(b['opaque'] > 0.5, axis=0); r = np.clip(crest + 4, 0, H - 1); ok = crest > 0
a0 = c0[r, np.arange(WIN)]; a1 = c1[r, np.arange(WIN)]; return float(np.abs(np.diff(a0[ok])).max()), float(np.abs(np.diff(a1[ok])).max()), (a0 + (1 - a0) * a1)[ok].min()
def test_seam_never_splits_a_receding_ridge_side_by_side():
"""Six synthetic ridges whose distance recedes across the window (4 to 15, 3 to 12, 5 to 30, 8 to 40, 4 to 15 and 6 to 14 km, targets 6, 6, 12, 15, 10, 9 km): the nearer and the farther card's alpha on the ridge's body never jumps by 0.35 between neighbouring
columns (a tear: one card here, the other next door; fading slowly over the cross-fade is fine) and the two cards together cover the body. With the swept-rows term out of the seam cost the seam hops across the ridge; with the prior at 0.1 it hops on two of the six."""
for d0, d1, sp in RECEDING:
j0, j1, cover = _alpha_jumps(d0, d1, sp); assert j0 < 0.35 and j1 < 0.35, ('a card appears or vanishes between neighbouring columns', (d0, d1, sp), j0, j1); assert cover > 0.999, ('the ridge body is not covered by the two cards together', (d0, d1, sp))
def test_far_card_keeps_terrain_hidden_behind_a_nearer_ridge():
"""Layered depth: a far ridge (20 km) lower in angle than the near ridge (3 km) in azimuth 0..36 and higher in 36..72. Where the near card is opaque in front of the far ridge (columns 100..500) the mid card still holds that ridge, at its distance;
where the far ridge shows above the near one (column 900) the near card is empty and the mid card holds it."""
b = _bake(terrain(block(0, 359.99, 3000, 3600, 350), block(0, 36, 20000, 21500, 1500), block(36, 359.99, 20000, 21500, 2400)), [6]); c0, c1 = _canvas(b['cards'][0]), b['cards'][1]; a1 = _canvas(c1); ld1 = _canvas(c1, 'logd'); r = _row(theta(1500, 20000) - 0.2)
for x in (100, 300, 500):
assert c0[r, x] > 0.99, ('the near ridge does not cover the far one here', x); assert a1[r, x] > 0.99, ('the far card lost the terrain behind the near ridge', x); assert abs(math.exp(ld1[r, x]) - 20000) < 1500, (x, math.exp(ld1[r, x]))
r = _row(0.5 * (theta(350, 3000) + theta(2400, 20000))); assert c0[r, 900] < 0.01 and a1[r, 900] > 0.99 and abs(math.exp(ld1[r, 900]) - 20000) < 1500, (c0[r, 900], a1[r, 900])
def test_crossfade_is_complementary():
"""A ridge across the seam (seam fixed at 6 km, the ridge's front face at 5.9 km inside the cross-fade): the nearer card is partly transparent over the window, the farther card is opaque on the ridge, and the composite stays at coverage 1 below the crest."""
A, Hh = rays(terrain(block(0, 359.99, 5900, 6100, 900))); ridge.P.update(win0=0, eye_m=EYE); ridge.set_view(A.max(0)); aw, hw = ridge.win(A), ridge.win(Hh)
cs = ridge.cards(D, aw, hw, np.full((1, WIN), 6000.0)); c0, c1 = _canvas(cs[0]), _canvas(cs[1]); crest = int(np.argmax(ridge.opaque(aw)[:, 500] > 0.5)); r = crest + 6
assert 0.2 < c0[r, 500] < 0.8, ('the near card does not fade over the window', c0[r, 500]); assert c1[r, 500] > 0.99, 'the far card is not opaque on the ridge'
comp = 1 - (1 - c0) * (1 - c1); assert (comp[crest + 3:, :] > 0.999).all(), 'the composite dips below coverage 1 under the crest'
def test_normals_of_a_tilted_plane():
"""A plane with front slope s (north) and lateral slope l (east), seen towards azimuth 0: n = (-E s, -E l, 1) normalised, E the authored exaggeration (a dropped E fails)."""
s, l, E = 0.12, -0.08, 3.0; saved = ridge.PXDEG_V; ridge.PXDEG_V = E * ridge.HPX_DEG
try:
az = (np.arange(W) + 0.5) / W * 2 * math.pi; h = 300.0 + s * D[:, None] * np.cos(az)[None, :] + l * D[:, None] * np.sin(az)[None, :]; nr, nt, nu = ridge.normals(D, h); k = len(D) // 2; x = [0, 1, 2, W - 2, W - 1]
want = np.array([-E * s, -E * l, 1.0]); want /= np.linalg.norm(want); got = np.array([nr[k, x].mean(), nt[k, x].mean(), nu[k, x].mean()]); assert np.abs(got - want).max() < 2e-3, (got, want)
assert np.abs(nr ** 2 + nt ** 2 + nu ** 2 - 1).max() < 1e-9
finally: ridge.PXDEG_V = saved
def test_lateral_slope_uses_equal_distance_not_equal_row():
"""A plane with lateral slope l at 20 km, a 3 km ridge only for azimuth above 40 deg: at the 20 km samples, in the columns around the ridge's azimuth edge, the across-ray slope is the plane's own l (neighbouring columns at the same distance), not a step between the ridge and the plane."""
l = 0.05; saved = ridge.PXDEG_V; ridge.PXDEG_V = 2.0 * ridge.HPX_DEG
try:
az = (np.arange(W) + 0.5) / W * 360.0; A, Hh = rays(lambda dk, a: np.where(dk > 10000, GROUND + l * dk * np.radians(a), GROUND) + np.where((a > 40) & (dk >= 3000) & (dk < 3600), 400.0, 0.0))
nr, nt, nu = ridge.normals(D, Hh); k = int(np.searchsorted(D, 20000)); x0 = int(40 / 360 * W); want = -2.0 * l / math.sqrt(1 + 4 * l * l + (2.0 * 0.0) ** 2)
assert np.abs(nt[k, x0 - 20:x0 + 20] / nu[k, x0 - 20:x0 + 20] + 2.0 * l).max() < 5e-3, nt[k, x0 - 5:x0 + 5] / nu[k, x0 - 5:x0 + 5]
finally: ridge.PXDEG_V = saved
def test_prefilter_flattens_roofs_and_keeps_hills():
"""A 25 m bump 60 m wide at 2 km drops below 5 m; a 400 m hill (3 km scale) keeps at least 90% of its height."""
ridge.P.update(eye_m=EYE); roof = lambda dk, az: GROUND + np.where((az < 1.72) & (dk >= 2000) & (dk < 2060), 25.0, 0.0)
hill = lambda dk, az: GROUND + 400.0 * np.exp(-((dk - 10000.0) / 3000.0) ** 2 - ((np.radians(((az + 180) % 360) - 180) * dk) / 3000.0) ** 2)
for f, name in ((roof, 'roof'), (hill, 'hill')):
A, Hh = rays(f); a, h = ridge.prefilter(D, Hh, 100.0); k = int(np.argmin(np.abs(D - (2030 if name == 'roof' else 10000)))); x = int(np.argmax(Hh[k]))
if name == 'roof': assert h[k, x] - GROUND < 5.0 and Hh[k, x] - GROUND >= 24.9, ('the roof survives the low-pass', h[k, x] - GROUND)
else: assert h[k, x] - GROUND >= 0.9 * 400.0, ('the hill is flattened', h[k, x] - GROUND)
assert np.allclose(ridge.prefilter(D, Hh, 0.0)[1], Hh), 'sigma 0 changed the heights'
def test_crest_rows_have_fractional_coverage():
"""The top row of a card's run has alpha equal to the share of its angular span under the running maximum, and the rows below it are 1 (a lower ridge in columns 0..640 so its crest is not at the frame's top edge)."""
A, Hh = rays(terrain(block(0, 36, 5000, 5600, 500), block(36, 359.99, 5000, 5600, 560))); ridge.P.update(win0=0, eye_m=EYE); ridge.set_view(A.max(0)); aw, hw = ridge.win(A), ridge.win(Hh); c = ridge.cards(D, aw, hw, np.zeros((0, WIN)))[0]
cv = _canvas(c)[:, 300]; r = int(np.argmax(cv > 0)); top = float(aw.max(0)[300]); p = 1.0 / ridge.PXDEG_V; want = (top - (ridge.rowang[r] - 0.5 * p)) / p
assert 0.0 < want < 1.0 and abs(cv[r] - want) < 0.01, (cv[r], want, r); assert (cv[r + 1:] > 0.999).all()
def test_cards_composite_to_the_opaque_view():
"""Alpha-over of all cards, last to first, equals the opaque march coverage within 0.02 everywhere, and where opaque the nearest solid card's distance is the first-hit distance of the march."""
for hf, sp in ((THREE, [6, 40]), (terrain(_receding), [6]), (terrain(block(0, 359.99, 3000, 3600, 350), block(0, 36, 20000, 21500, 700), block(36, 359.99, 20000, 21500, 1800)), [6])):
b = _bake(hf, sp); comp = 1 - np.prod([1 - _canvas(c) for c in b['cards']], axis=0); assert np.abs(comp - b['opaque']).max() < 0.02, np.abs(comp - b['opaque']).max()
rm = np.maximum.accumulate(b['a'], axis=0); col = 640; r = _row(float(b['a'][:, col].max()) - 0.5); k = int(np.searchsorted(rm[:, col], ridge.rowang[r], 'left')); first = None
for c in b['cards']:
if _canvas(c)[r, col] > 0.99: first = math.exp(_canvas(c, 'logd')[r, col]); break
assert first is not None and abs(first - D[k]) < 0.1 * D[k] + 60, (first, D[k])
# ---------------------------------------------------------------------------------------- the real thing: Vienna
def _vienna(splits):
saved = ridge.P
try:
p = ridge.configure(dict(ridge.load_preset('vienna'), card_split_km=splits)); d, _, Hh, _ = ridge.stage0(False); a, h = ridge.prefilter(d, Hh, p['prefilter_m']); ridge.set_view(a.max(0)); aw = ridge.win(a); hw = ridge.win(h)
nrm = tuple(ridge.win(x) for x in ridge.normals(d, h)); cov = ridge.coverage(d, aw); sm = ridge.seams(cov, [k * 1000.0 for k in splits], d); return d, aw, ridge.cards(d, aw, hw, sm, nrm), sm, ridge.opaque(aw)
finally: ridge.P = saved
def test_vienna_k1_k2_k3():
"""Vienna with card_split_km [6], [6, 40] and [6, 20, 40]: 2, 3 and 4 cards, seams ordered in every column, each composite equals the opaque view within 0.02; the cross-fade column count of each K is printed."""
for sp in ([6], [6, 40], [6, 20, 40]):
d, aw, cs, sm, op = _vienna(sp); assert len(cs) == len(sp) + 1 and sm.shape == (len(sp), WIN)
if len(sp) > 1: assert (np.diff(np.log(sm), axis=0) >= 0.4 - 1e-9).all(), 'seams out of order'
comp = 1 - np.prod([1 - _canvas(c) for c in cs], axis=0); assert np.abs(comp - op).max() < 0.02, (sp, np.abs(comp - op).max())
xf = int(np.any([((0.02 < _canvas(c)) & (_canvas(c) < 0.98)).sum(0) > 3 for c in cs], axis=0).sum())
print(f' K={len(sp)} splits {sp}: {len(cs)} cards, bands {[(c["top"], c["alpha"].shape[0]) for c in cs]}, seam medians km {[round(float(np.median(s)) / 1000, 1) for s in sm]}, cross-fade columns {xf} of {WIN}')
def test_bake_place_manifest_fields_on_vienna():
"""bake_place on the real Vienna preset: three cards, the place carries the ground (km) and the eye, horizon_row is the row where the elevation angle is 0, px_per_deg_h is the ring's; write_bake of its packed cards validates, index default 'vienna', and no temp dir is left."""
saved = ridge.P
load = ridge.load_preset; ridge.load_preset = lambda pid, *a: dict(load(pid, *a), camera_r_m=123.0) # a preset's camera_r_m is the bake's camera
try: b = export.bake_place('vienna'); P = ridge.P; rowang = ridge.rowang; pxv = ridge.PXDEG_V
finally: ridge.P = saved; ridge.load_preset = load
assert b['meta']['camera'] == dict(r_m=123.0, heading_max_deg=export.HEADING_MAX_DEG), b['meta']['camera']
pl, view = b['place'], b['view']; assert abs(pl['altitude_km'] * 1000 - P['ground_m']) < 1e-6 and abs(pl['eye_m'] - P['eye_m']) < 1e-9 and pl['id'] == 'vienna' and len(b['cards']) == 3
assert 0 < view['sky_row'] < view['horizon_row'] < view['near_row'] < H and abs(rowang[int(view['horizon_row'])]) <= 1.0 / pxv, (view, rowang[int(view['horizon_row'])]); assert view['px_per_deg_h'] == ridge.HPX_DEG and abs(view['exaggeration'] - pxv / ridge.HPX_DEG) < 1e-9
d = tempfile.mkdtemp()
try:
dest = export.write_bake(d, pl, view, b['meta'], export.pack(b), b['opaque']); m = json.load(open(dest / 'manifest.json')); export.validate(m, export.SCHEMA['$defs']['manifest'])
assert json.load(open(d + '/index.json'))['default'] == 'vienna' and sorted(os.listdir(d)) == sorted(['index.json', dest.name]), os.listdir(d); print(' vienna manifest bytes', m['bytes'], 'cards', [(c['top'], c['h'], c['colour']['bytes'] + c['geometry']['bytes']) for c in m['cards']])
finally: shutil.rmtree(d)
# ---------------------------------------------------------------------------------------- export: manifest v2, budget, cover
def _packed(b=None):
b = b or _bake(WIDE3, [20, 55]); return b, export.pack(b)
def _refuses(out, b, packed, why, **kw):
args = dict(place=b['place'], view=b['view'], meta=b['meta'], cards=packed, opaque=b['opaque']); args.update(kw)
try: export.write_bake(out, **args)
except ValueError: assert not os.path.exists(out), ('a refused bake left files', why)
else: assert False, why
def test_manifest_v2_writer():
"""Two independent bakes give the same bytes and bake_id; the manifest validates (an extra key does not), cards are nearest first with their bands and seam medians, the files are what the manifest says, the index points at the dir, a rebake replaces
the old dir, the committed schema is current, and the Copernicus attribution is the four pinned strings."""
d = tempfile.mkdtemp()
try:
b, pk = _packed(); b2, pk2 = _packed(_bake(WIDE3, [20, 55])); assert [(c['colour'], c['geometry']) for c in pk] == [(c['colour'], c['geometry']) for c in pk2], 'two independent bakes gave different bytes'
a = export.write_bake(d + '/a', b['place'], b['view'], b['meta'], pk, b['opaque']); assert a.name == 'synthetic-' + export.bake_id([(c['colour'], c['geometry']) for c in pk]); assert sorted(os.listdir(d + '/a')) == sorted(['index.json', a.name])
m = json.load(open(a / 'manifest.json')); export.validate(m, export.SCHEMA['$defs']['manifest']); assert m['schema'] == 2 and m['baker_version'] == export.BAKER_VERSION and len(m['cards']) == 3 and m['w'] == WIN and m['h'] == H
assert m['camera'] == dict(r_m=export.CAMERA_R_M, heading_max_deg=17.0) and all(c['scale'] == c['distance_m'] / (c['distance_m'] - export.CAMERA_R_M) and c['distance_m'] == c['median_m'] for c in m['cards']), m['camera']
assert m['cards'][0]['near_m'] is None and m['cards'][-1]['far_m'] is None and m['cards'][0]['far_m'] == m['cards'][1]['near_m'] and m['cards'][0]['median_m'] < m['cards'][1]['median_m'] < m['cards'][2]['median_m']
for c in m['cards']:
for kind in ('colour', 'geometry'): f = a / c[kind]['file']; assert f.stat().st_size == c[kind]['bytes'] and export.decode(f.read_bytes()).shape[:2] == (c['h'], WIN), c
assert m['bytes'] == sum(c[k]['bytes'] for c in m['cards'] for k in ('colour', 'geometry')) and m['encoding']['normal'] == 'rt8' and m['curvature'] == dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF)
idx = json.load(open(d + '/a/index.json')); export.validate(idx, export.SCHEMA['$defs']['index']); assert idx == dict(schema=1, default='synthetic', places={'synthetic': a.name})
pk3 = [dict(c) for c in pk]; pk3[1]['geometry'] = pk3[1]['geometry'] + b'x'; assert export.bake_id([(c['colour'], c['geometry']) for c in pk3]) != export.bake_id([(c['colour'], c['geometry']) for c in pk]), 'a changed byte kept the bake_id'
import hashlib; want = hashlib.sha256(b''.join(c['colour'] + c['geometry'] for c in pk)).hexdigest()[:12]; assert export.bake_id([(c['colour'], c['geometry']) for c in pk]) == want, 'bake_id is not the sha256 of the card files, colour then geometry, in index order'
assert export.bake_id([(c['geometry'], c['colour']) for c in pk]) != want and export.bake_id([(c['colour'], c['geometry']) for c in pk[::-1]]) != want, 'bake_id ignores the file order'
bad = json.loads(json.dumps(m)); bad['cards'][0]['extra'] = 1
try: export.validate(bad, export.SCHEMA['$defs']['manifest'])
except ValueError: pass
else: assert False, 'an extra key passed the schema'
assert json.load(open(os.path.join(SRC, 'ridge-bake.schema.json'))) == json.loads(json.dumps(export.SCHEMA)), 'ridge-bake.schema.json is stale (export.py --write-schema)'
want = dict(credit_line='Contains modified Copernicus data: DEM © DLR e.V. 2010-2014 and © Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved.',
licence='Copernicus DEM licence: free, full and open access, with the credit line shown', dem_source='Copernicus DEM GLO-30 (30 m)', url='https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model')
assert m['attribution'] == want, m['attribution']
c = export.write_bake(d + '/a', b['place'], b['view'], b['meta'], pk, b['opaque'])
assert c.name == a.name; other = dict(b['place'], id='other'); export.write_bake(d + '/a', other, b['view'], b['meta'], pk, b['opaque']); assert json.load(open(d + '/a/index.json'))['default'] == 'synthetic'
export.write_bake(d + '/a', other, b['view'], b['meta'], pk, b['opaque'], default='other'); assert json.load(open(d + '/a/index.json'))['default'] == 'other'
idx = json.load(open(d + '/a/index.json')); idx['default'] = 'gone'; open(d + '/a/index.json', 'w').write(json.dumps(idx)); export.write_bake(d + '/a', other, b['view'], b['meta'], pk, b['opaque']); assert json.load(open(d + '/a/index.json'))['default'] == 'other'
finally: shutil.rmtree(d)
def test_cover_and_size_refusals_write_nothing():
"""write_bake measures the files it is handed: a card with a hole (alpha zeroed in a band of columns) fails the cover check, a card leaving the frame, cards of two widths and a colour/geometry size mismatch are refused, and nothing is written."""
d = tempfile.mkdtemp()
try:
b, pk = _packed(); c1 = b['cards'][1]; hole = c1['alpha'].copy(); hole[:, 200:260] = 0
holed = [dict(c) for c in pk]; holed[1]['colour'] = export.encode_colour(c1['albedo'], hole); holed[2] = dict(pk[2], colour=export.encode_colour(b['cards'][2]['albedo'], b['cards'][2]['alpha'] * 0)); _refuses(d + '/hole', b, holed, 'a bake whose cards leave a hole was written')
_refuses(d + '/off', b, [dict(c, top=H - 5) if i == 0 else c for i, c in enumerate(pk)], 'a card leaving the frame was written')
narrow = [dict(c) for c in pk]; narrow[0]['colour'] = export.encode_colour(b['cards'][0]['albedo'][:, :1000], b['cards'][0]['alpha'][:, :1000]); _refuses(d + '/wide', b, narrow, 'cards of two widths were written')
_refuses(d + '/rows', b, pk, 'view plane_h disagreeing with the opaque view was written', view=dict(b['view'], plane_h=H + 1))
finally: shutil.rmtree(d)
def _flat_card(top, h, w=WIN, seed=0, noise=False):
rng = np.random.default_rng(seed); alpha = np.ones((h, w), np.float32); rgb = rng.random((h, w, 3)).astype(np.float32) if noise else np.full((h, w, 3), 0.5, np.float32); geo = rng.random((h, w)).astype(np.float32) if noise else np.full((h, w), 0.5, np.float32)
enc = dict(log_d_min=0.0, log_d_max=1.0); return dict(top=top, colour=export.encode_colour(rgb, alpha), geometry=export.encode_geometry(geo, geo, geo, enc), near_m=None, far_m=None, median_m=1.0, distance_m=1.0, scale=1.0)
def test_card_cap_refusals():
"""A preset with 6 splits, or splits not increasing, is refused by load_preset before any march; write_bake refuses 4 full-frame 1280x600 cards (24.6 MB decoded) and writes nothing; 6 cards whose bands fit the budget are written; the card count and bytes are capped."""
d = tempfile.mkdtemp()
try:
for bad in ([5, 10, 20, 30, 40, 50], [6, 6], [6, 5], []):
p = os.path.join(d, 'p.json'); json.dump(dict(presets=[dict(id='x', card_split_km=bad)]), open(p, 'w'))
try: ridge.load_preset('x', p)
except ValueError: pass
else: assert False, ('a preset with splits', bad, 'was accepted')
json.dump(dict(presets=[dict(id='x')]), open(os.path.join(d, 'q.json'), 'w'))
try: ridge.load_preset('x', os.path.join(d, 'q.json'))
except ValueError: pass
else: assert False, 'a preset without card_split_km was defaulted'
json.dump(dict(presets=[dict(id='x', card_split_km=[1, 2, 3, 4, 5])]), open(os.path.join(d, 'r.json'), 'w')); assert ridge.load_preset('x', os.path.join(d, 'r.json'))['card_split_km'] == [1, 2, 3, 4, 5]
place = dict(id='synthetic', name='S', lat=0.0, lon=0.0, altitude_km=0.0, eye_m=1.0); meta = dict(curvature=dict(r_earth_m=1.0, k_ref=0.1), encoding=dict(log_d_min=0.0, log_d_max=1.0), camera=dict(r_m=0.0, heading_max_deg=1.0)); view = dict(look_az_deg=0.0, plane_h=H, px_per_deg_h=1.0, px_per_deg_v=1.0, exaggeration=1.0, horizon_row=1.0, sky_row=1.0, near_row=1.0)
full = np.ones((H, WIN))
_refuses(d + '/four', dict(place=place, view=view, meta=meta, opaque=full), [_flat_card(0, H) for _ in range(4)], 'four full-frame cards (24.6 MB decoded) were written')
ok = [_flat_card(0, H)] + [_flat_card(0, 150, seed=i) for i in range(1, 6)]; dest = export.write_bake(d + '/six', place, view, meta, ok, full); assert len(json.load(open(dest / 'manifest.json'))['cards']) == 6
try: export.check_budget([1000] * 7, WIN, [10] * 7)
except ValueError as e: assert 'above 6' in str(e)
else: assert False, '7 cards were accepted'
try: export.check_budget([750_001, 750_000], WIN, [10, 10])
except ValueError as e: assert 'bytes' in str(e)
else: assert False, 'cards above TOTAL_BYTES_MAX were accepted'
export.check_budget([750_000, 750_000], WIN, [10, 10])
try: export.check_budget([1, 1], export.PLANE_W_MAX + 1, [10, 10])
except ValueError: pass
else: assert False, 'a card wider than the cap was accepted'
finally: shutil.rmtree(d)
def test_cards_are_cropped_to_their_band():
"""Each card is exactly the rows where its 8-bit alpha is non-zero; the manifest top and h place it back at the same rows (colour and geometry decode to that band, alpha in the file equals the canvas row for row)."""
d = tempfile.mkdtemp()
try:
b, pk = _packed(); dest = export.write_bake(d, b['place'], b['view'], b['meta'], pk, b['opaque']); m = json.load(open(dest / 'manifest.json'))
for c, rec in zip(b['cards'], m['cards']):
canvas = _canvas(c); rows = np.flatnonzero(np.rint(canvas * 255).max(1) > 0); assert rec['top'] == rows[0] and rec['h'] == rows[-1] - rows[0] + 1 == c['alpha'].shape[0], (rec, rows[0], rows[-1])
col = export.decode((dest / rec['colour']['file']).read_bytes()); assert col.shape[:2] == (rec['h'], WIN) and np.abs(col[..., 3].astype(int) - np.rint(c['alpha'] * 255)).max() == 0, 'the written alpha is not the card alpha'
assert export.decode((dest / rec['geometry']['file']).read_bytes()).shape[:2] == (rec['h'], WIN)
finally: shutil.rmtree(d)
def test_an_empty_card_is_refused_before_writing_naming_the_split():
"""A card with no rows (its splits leave it no terrain) stops pack with a message that names the splits, instead of dying inside the codec."""
b = _bake(THREE, [6, 40]); b['cards'][1] = dict(top=0, alpha=np.zeros((0, WIN), np.float32), albedo=np.zeros((0, WIN, 3), np.float32), n_r=np.zeros((0, WIN), np.float32), n_t=np.zeros((0, WIN), np.float32), logd=np.zeros((0, WIN), np.float32), wall=np.zeros((0, WIN), bool))
try: export.pack(b)
except ValueError as e: assert 'card 1 is empty' in str(e) and '6 km' in str(e) and '40 km' in str(e), str(e)
else: assert False, 'an empty card was packed'
b['cards'][2] = b['cards'][1]
try: export.pack(dict(b, cards=[b['cards'][0], _bake(THREE, [6, 40])['cards'][1], b['cards'][1]]))
except ValueError as e: assert 'card 2 is empty' in str(e) and '40 km' in str(e), str(e)
else: assert False, 'an empty last card was packed'
# ---------------------------------------------------------------------------------------- the written files are the cards
def test_written_cards_decode_to_the_cards_in_memory():
"""Vienna's three cards, written and decoded again: alpha exactly, albedo within the lossy codec (and straight, not premultiplied, at partial alpha), the normal channels in their order (R along the ray, G across it), and the log-distance over the encoding range, within quantisation."""
saved = ridge.P
try: b = export.bake_place('vienna')
finally: ridge.P = saved
d = tempfile.mkdtemp()
try:
dest = export.write_bake(d, b['place'], b['view'], b['meta'], export.pack(b), b['opaque']); m = json.load(open(dest / 'manifest.json')); enc = m['encoding']; span = enc['log_d_max'] - enc['log_d_min']; partial_seen = 0
for c, rec in zip(b['cards'], m['cards']):
col = export.decode((dest / rec['colour']['file']).read_bytes()); geo = export.decode((dest / rec['geometry']['file']).read_bytes()); al = c['alpha']; wall = c['wall']; solid = (al > 0) & ~wall; part = (al > 0.05) & (al < 0.95) & ~wall; partial_seen += int(part.sum())
assert (col[..., 3] == np.rint(al * 255)).all(), 'alpha is not exact'; e = np.abs(col[..., :3] / 255.0 - c['albedo']).max(-1)
assert e[solid].mean() < 0.02 and np.percentile(e[solid], 99) < 0.08, ('albedo is off', e[solid].mean(), np.percentile(e[solid], 99)); assert part.sum() == 0 or e[part].mean() < 0.1, ('albedo at partial alpha is off: premultiplied?', e[part].mean())
assert (geo[..., 3] == 255).all(); q = 1.0 / 255 + 1e-6; assert (((geo[..., 0] == 255) & (geo[..., 1] == 255)) == wall).all(), 'the wall code is not R = G = 255 on exactly the wall pixels'
assert np.abs(geo[..., 0] / 255.0 * 2 - 1 - c['n_r'])[solid].max() < 2 * q and np.abs(geo[..., 1] / 255.0 * 2 - 1 - c['n_t'])[solid].max() < 2 * q, 'a normal channel is off or swapped'
assert np.abs(enc['log_d_min'] + geo[..., 2] / 255.0 * span - c['logd'])[solid].max() < span * q, 'the log-distance is off or not over the encoding range'
assert np.abs(c['n_r'][solid]).mean() > 0.05 and np.abs(c['n_t'][solid]).mean() > 0.01 and np.abs(c['n_r'][solid].mean() - c['n_t'][solid].mean()) > 0.0, 'the fixture does not tell the channels apart'
assert col[..., :3][solid].mean() > 20, 'albedo is zeroed'
assert partial_seen > 0, 'the fixture has no partial alpha'
finally: shutil.rmtree(d)
# ---------------------------------------------------------------------------------------- wall rows and the camera
def _first_sample_angle(b, i):
"""Per column, the angle of the first sample card i (> 0) reads: the first sample at or beyond its near seam, less the cross-fade half-width."""
k0 = np.array([np.searchsorted(D, b['seams'][i - 1][x] * math.exp(-ridge.XF)) for x in range(WIN)]); return k0, b['a'][k0, np.arange(WIN)]
def test_wall_rows_flagged():
"""Card i > 0 flags as wall exactly the rows below the angle of its first sample (the extruded face of the ridge it starts at), card 0 none; the wall carries R = G = 255 in the geometry file and no other pixel has r2 + t2 above 1.02; wall pixels keep that sample's
distance and their albedo is the ground material of the sample's height with the face up (so a steep face is not rock), constant down the column."""
steep = 0
for make in (lambda: _bake(WALLED, [20]), lambda: _bake(WIDE3, [20, 55]), lambda: _bake(_receding, [6]), lambda: _bake(_ramp, [20])):
b = make(); assert not b['cards'][0]['wall'].any(), 'card 0 has a wall'; lo = ridge.rowang - 0.5 / ridge.PXDEG_V; seen = 0
for i, c in enumerate(b['cards']):
if i == 0: continue
k0, a0 = _first_sample_angle(b, i); want = (lo[:, None] < a0[None, :])[c['top']:c['top'] + c['alpha'].shape[0]]; assert (c['wall'] == want).all(), ('wall rows are not the rows below the first sample', i, int((c['wall'] != want).sum())); seen += int(want.sum())
geo = export.decode(export.encode_geometry(c['n_r'], c['n_t'], c['logd'], b['meta']['encoding'], c['wall'])); r, t = geo[..., 0] / 255.0 * 2 - 1, geo[..., 1] / 255.0 * 2 - 1; code = (geo[..., 0] == 255) & (geo[..., 1] == 255)
assert (code == c['wall']).all() and (r[~code] ** 2 + t[~code] ** 2 <= 1.02).all(), 'the wall code is not on exactly the wall pixels, or a real normal reaches it'
for x in np.flatnonzero(c['wall'].any(0)):
rows = np.flatnonzero(c['wall'][:, x]); ld = c['logd'][rows, x]; assert np.ptp(ld) < 1e-5 and abs(math.exp(ld[0]) - D[k0[x]]) < 1e-3 * D[k0[x]] + 60, ('a wall keeps its sample distance', x)
want_alb = ridge.albedo(np.array([b['h'][k0[x], x]]), np.array([1.0]))[0]; assert np.abs(c['albedo'][rows, x] - want_alb).max() < 1e-5, ('wall albedo is not the ground material with the face up', x)
assert seen > 1000, 'the fixture has no wall'
for i in range(1, len(b['cards'])):
c = b['cards'][i]; steep += int((np.sqrt(np.clip(1 - c['n_r'] ** 2 - c['n_t'] ** 2, 0, 1))[c['wall']] < 0.93).sum())
assert steep > 1000, 'no wall pixel has a steep face under it: a wall lit by its own normal would pass'
b = _bake(NEARHILL, [20]); c0 = b['cards'][0]; lo = ridge.rowang - 0.5 / ridge.PXDEG_V; below = (lo[:, None] < b['a'][0][None, :])[c0['top']:c0['top'] + c0['alpha'].shape[0]]
assert below.sum() > 1000 and not c0['wall'].any(), ('card 0 has no wall, though rows lie below its first sample', int(below.sum()))
def test_the_sheet_lights_a_wall_with_the_face_up():
"""The contact sheet shades a wall pixel as an up-facing one whatever normal the card carries there, and a non-wall pixel by its normal."""
n = 4; c = dict(albedo=np.ones((n, n, 3), np.float32), alpha=np.ones((n, n), np.float32), n_r=np.full((n, n), 0.9, np.float32), n_t=np.zeros((n, n), np.float32), wall=np.zeros((n, n), bool)); c['wall'][:, :2] = True
rgb, _ = export.lit(c); L = np.array(export.SHEET_LIGHT) / np.linalg.norm(export.SHEET_LIGHT); up = 0.35 + 0.65 * L[2]; tilted = 0.35 + 0.65 * np.clip(0.9 * L[0] + np.sqrt(1 - 0.81) * L[2], 0, 1)
assert np.allclose(rgb[:, :2], up) and np.allclose(rgb[:, 2:], tilted) and abs(up - tilted) > 0.05, (rgb[0, 0], rgb[0, 3])
def test_camera_contract():
"""scale_i = d_i / (d_i - r) for r = +200 and r = -100 (a function of r, not a constant or a clamp); a card's distance excludes its wall rows; |r| at half the nearest distance is refused; an r that lifts the nearest card off the frame bottom (backward) is
refused and writes nothing; a card shrunk below what a 16:9 viewport needs is refused; one card works."""
ds = [1000.0, 12000.0, 40000.0]
for r in (200.0, -100.0, 0.0): assert export.card_scales(ds, r) == [d / (d - r) for d in ds], r
assert export.card_scales(ds, 200.0)[0] > 1.2 and export.card_scales(ds, -100.0)[0] < 0.92 and export.card_scales(ds, 0.0) == [1.0, 1.0, 1.0]
for bad in (500.0, -500.0, 800.0):
try: export.card_scales(ds, bad)
except ValueError: pass
else: assert False, ('an offset of', bad, 'was accepted')
export.card_scales(ds, 499.0); export.card_scales(ds, -499.0)
b = _bake(WIDE3, [20, 55]); c1 = b['cards'][1]; solid = c1['alpha'] >= 0.5; c1['wall'] = np.zeros_like(c1['wall']); c1['wall'][:c1['alpha'].shape[0] * 3 // 4] = True; c1['logd'] = np.where(c1['wall'], c1['logd'] + 3.0, c1['logd']) # three quarters of the card is wall, far off the rest
want = float(np.exp(np.median(c1['logd'][solid & ~c1['wall']]))); with_wall = float(np.exp(np.median(c1['logd'][solid]))); assert abs(with_wall - want) > 0.05 * want, ('the fixture cannot tell the median with walls from the one without', with_wall, want)
pk = export.pack(b); assert abs(pk[1]['distance_m'] - want) < 1e-6 * want and pk[1]['median_m'] == pk[1]['distance_m'], ('the distance counted wall rows', pk[1]['distance_m'], want)
assert [p['scale'] for p in pk] == [p['distance_m'] / (p['distance_m'] - export.CAMERA_R_M) for p in pk]
d = tempfile.mkdtemp()
try:
back = dict(b['meta'], camera=dict(r_m=-100.0, heading_max_deg=23.0)); pkb = export.pack(dict(b, meta=back)); assert all(p['scale'] < 1 for p in pkb)
_refuses(d + '/back', b, pkb, 'a backward camera that lifts the nearest card off the frame bottom was written', meta=back)
try: export.pack(dict(b, meta=dict(b['meta'], camera=dict(r_m=0.5 * pk[0]['distance_m'], heading_max_deg=23.0))))
except ValueError: pass
else: assert False, 'an offset of half the nearest distance was packed'
view = b['view']; tops = [c['top'] for c in b['cards']]; bands = [c['alpha'].shape[0] for c in b['cards']]; export.check_camera([1.0, 1.0, 1.0], tops, bands, view)
try: export.check_camera([1.0, 1.0, 0.8], tops, bands, view)
except ValueError as e: assert '16:9' in str(e), str(e)
else: assert False, 'a card too small for a 16:9 viewport at rest was accepted'
one, pk1 = _packed(_bake(WALLED, [])); assert len(pk1) == 1 and pk1[0]['scale'] == pk1[0]['distance_m'] / (pk1[0]['distance_m'] - export.CAMERA_R_M); dest = export.write_bake(d + '/one', one['place'], one['view'], one['meta'], pk1, one['opaque'])
assert len(json.load(open(dest / 'manifest.json'))['cards']) == 1
finally: shutil.rmtree(d)
# ---------------------------------------------------------------------------------------- rules that no other test touched
def test_seams_keep_their_separation():
"""Two authored targets closer than SEAM_SEP (6 and 7 km, 0.15 nat): the seams still sit at least 0.4 nat apart in every column."""
s = _bake(THREE, [6, 7])['seams']; assert (np.log(s[1]) - np.log(s[0]) >= 0.4 - 1e-9).all(), float((np.log(s[1]) - np.log(s[0])).min())
def test_elev_is_the_curved_refracted_angle():
"""elev(h, d) = atan2(h - eye - d^2 / 2R x (1 - k), d): at 80 km a 3000 m summit stands 0.3 deg lower than the flat angle, and curvature False gives the flat one."""
ridge.P.update(eye_m=EYE); d = 80000.0; want = math.degrees(math.atan2(3000.0 - EYE - d * d / (2 * ridge.R_EARTH) * (1 - ridge.KREF), d)); flat = math.degrees(math.atan2(3000.0 - EYE, d))
assert abs(float(ridge.elev(3000.0, d)) - want) < 1e-9 and abs(float(ridge.elev(3000.0, d, curvature=False)) - flat) < 1e-9 and flat - want > 0.25, (want, flat)
assert ridge.elev(np.array([[1000.0, 1200.0]]), np.array([[d], [d / 2]])).shape == (2, 2)
def test_coverage_counts_every_visible_row_including_the_foreground():
"""Per column the coverage sums to the visible rows of the opaque view: (min(skyline, top) - bottom) x px per degree, the rows below the first sample included once, not twice (a ground just under the eye shows below the first sample)."""
for i, hf in enumerate((terrain(block(0, 359.99, 0, 20000, 91), block(0, 359.99, 20000, 21500, 600)), THREE)):
A, Hh = rays(hf); ridge.P.update(win0=0, eye_m=EYE); ridge.set_view(A.max(0)); aw = ridge.win(A); cov = ridge.coverage(D, aw); want = np.clip(np.minimum(aw.max(0), ridge.TOP_DEG) - ridge.BOTTOM_DEG, 0, None) * ridge.PXDEG_V
assert np.abs(cov.sum(0) - want).max() < 1e-6, np.abs(cov.sum(0) - want).max(); assert cov.shape == (ridge.COV_BINS, WIN)
if i == 0: assert (cov[0] > 100).all(), ('no foreground rows in the first bin', float(cov[0].min()))
def test_cards_interpolate_between_samples_and_renormalise():
"""On a ramp face every card pixel sits between two samples: its log-distance lies strictly between theirs (not on the nearer sample), and its normal is the normalised blend of theirs by that same fraction (the samples carry alternating normals, so a blend
that is not renormalised, or a hit that is not interpolated, differs)."""
A, Hh = rays(terrain(lambda dk, az: np.where(dk >= 4000, GROUND + 0.5 * (dk - 4000), 0.0) + 0 * az)); ridge.P.update(win0=0, eye_m=EYE); ridge.set_view(A.max(0)); aw, hw = ridge.win(A), ridge.win(Hh); k = np.arange(len(D))[:, None]
nr = np.broadcast_to(np.where(k % 2 == 0, -0.8, 0.8), aw.shape).astype(float); nt = np.broadcast_to(np.where(k % 3 == 0, 0.3, -0.3), aw.shape).astype(float); nu = np.sqrt(1 - nr ** 2 - nt ** 2) * 0 + 0.5
c = ridge.cards(D, aw, hw, np.zeros((0, WIN)), nrm=(nr, nt, nu))[0]; x = 300; sel = np.flatnonzero(c['alpha'][:, x] > 0.999); ld = c['logd'][sel, x].astype(np.float64); L = np.log(D); kk = np.searchsorted(L, ld, 'left'); kp = kk - 1; ok = kp >= 0
t = (ld - L[np.maximum(kp, 0)]) / (L[kk] - L[np.maximum(kp, 0)]); inner = ok & (t > 0.02) & (t < 0.98); assert inner.sum() > 0.3 * len(sel), ('hits sit on samples, not between them', int(inner.sum()), len(sel))
mix = lambda arr: arr[np.maximum(kp, 0), x] + t * (arr[kk, x] - arr[np.maximum(kp, 0), x]); m = np.sqrt(mix(nr) ** 2 + mix(nt) ** 2 + mix(nu) ** 2); er = np.abs(c['n_r'][sel, x] - mix(nr) / m)[inner]; et = np.abs(c['n_t'][sel, x] - mix(nt) / m)[inner]
assert er.max() < 1e-3 and et.max() < 1e-3, ('the normal is not the normalised blend of the two samples', er.max(), et.max())
TESTS = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
if __name__ == '__main__':
fails = 0
for t in TESTS:
try: t(); print("PASS", t.__name__)
except Exception as e: fails += 1; print("FAIL", t.__name__, "|", repr(e)[:300])
print("failures:", fails); sys.exit(1 if fails else 0)

View file

@ -0,0 +1,121 @@
"""Pack the night sky's data into src/app/features/scene/ridge/nightSkyData.ts.
Usage (parse downloads with isolated mode):
python -I scripts/ridge-sky/build-night-sky.py BSC5.DAT.GZ CONSTELLATIONS.LINES.JSON OUT.ts [MAX_MAG]
Inputs, each in its own directory, never run from inside it:
bsc5.dat.gz Yale Bright Star Catalogue, 5th revised ed. (Hoffleit & Warren 1991), public domain; CDS/VizieR V/50.
CDS was unreachable on 2026-11-20, so the file is the SAO Telescope Data Center's copy of the same
catalogue: http://tdc-www.harvard.edu/catalogs/bsc5.dat.gz (fixed-width, CDS V/50 `catalog` layout).
constellations.lines.json d3-celestial (Olaf Frohn), BSD-3-Clause:
https://github.com/ofrohn/d3-celestial/blob/master/data/constellations.lines.json
GeoJSON MultiLineStrings of [RA, Dec] degrees, J2000.
Stars (stars cut to Vmag <= MAX_MAG, default 5.5), 6 bytes each: RA uint16 (360 deg / 65536), Dec uint16 ((dec + 90) / 180 * 65535),
Vmag uint8 ((V + 2) * 20), B-V uint8 ((B-V + 0.5) * 50; missing B-V stored as 0.65). Little endian, base64.
Lines: per chain a uint8 vertex count then that many (RA uint16, Dec uint16) pairs, same scaling; chains concatenated; base64.
"""
import base64
import gzip
import hashlib
import json
import struct
import sys
def sha256(path):
h = hashlib.sha256()
with open(path, "rb") as f:
h.update(f.read())
return h.hexdigest()
def ra16(deg):
return int(round((deg % 360.0) / 360.0 * 65536.0)) % 65536
def dec16(deg):
return int(round((deg + 90.0) / 180.0 * 65535.0))
def stars(path, max_mag):
out = []
for line in gzip.open(path, "rt", encoding="latin-1"):
if len(line) < 114 or not line[75:77].strip():
continue # entries struck from the catalogue carry no position
try:
ra = (int(line[75:77]) + int(line[77:79]) / 60.0 + float(line[79:83]) / 3600.0) * 15.0
dec = int(line[84:86]) + int(line[86:88]) / 60.0 + int(line[88:90]) / 3600.0
dec = -dec if line[83] == "-" else dec
v = float(line[102:107])
except ValueError:
continue
if v > max_mag:
continue
bv_text = line[109:114].strip()
bv = float(bv_text) if bv_text else 0.65
out.append((ra, dec, v, bv))
out.sort(key=lambda s: s[2]) # brightest first: a prefix is the brighter stars
return out
def pack_stars(rows):
buf = bytearray()
for ra, dec, v, bv in rows:
vq = min(255, max(0, int(round((v + 2.0) * 20.0))))
bq = min(255, max(0, int(round((bv + 0.5) * 50.0))))
buf += struct.pack("<HHBB", ra16(ra), dec16(dec), vq, bq)
return bytes(buf)
def pack_lines(path):
with open(path, encoding="utf-8") as f:
gj = json.load(f)
buf = bytearray()
chains = 0
for feat in gj["features"]:
geom = feat["geometry"]
assert geom["type"] == "MultiLineString"
for chain in geom["coordinates"]:
assert 2 <= len(chain) < 256
buf.append(len(chain))
for lon, lat in chain:
buf += struct.pack("<HH", ra16(lon), dec16(lat))
chains += 1
return bytes(buf), chains
def wrap(b64, width=110):
return "\n".join(b64[i : i + width] for i in range(0, len(b64), width))
def main():
bsc, lines, out = sys.argv[1:4]
max_mag = float(sys.argv[4]) if len(sys.argv) > 4 else 5.5
rows = stars(bsc, max_mag)
star_bytes = pack_stars(rows)
line_bytes, chains = pack_lines(lines)
text = f"""/* eslint-disable */
// GENERATED by scripts/ridge-sky/build-night-sky.py: do not edit. The night sky's data, J2000.
// Stars: Yale Bright Star Catalogue, 5th revised ed. (Hoffleit & Warren 1991; public domain), Vmag <= {max_mag}, {len(rows)} stars.
// source http://tdc-www.harvard.edu/catalogs/bsc5.dat.gz (copy of CDS/VizieR V/50), sha256 {sha256(bsc)}
// Constellation lines: d3-celestial constellations.lines.json (Olaf Frohn, BSD-3-Clause), {chains} chains.
// source https://github.com/ofrohn/d3-celestial/blob/master/data/constellations.lines.json, sha256 {sha256(lines)}
// Layout: see the generator's docstring. Stars are sorted brightest first.
export const STAR_COUNT = {len(rows)};
export const STARS_B64 = `
{wrap(base64.b64encode(star_bytes).decode())}
`;
export const LINE_CHAINS = {chains};
export const LINES_B64 = `
{wrap(base64.b64encode(line_bytes).decode())}
`;
"""
with open(out, "w", encoding="utf-8", newline="\n") as f:
f.write(text)
print(f"{len(rows)} stars, {chains} chains, {len(star_bytes)} + {len(line_bytes)} bytes")
main()

View file

@ -16,6 +16,7 @@ import {
} from 'folds'; } from 'folds';
import { MatrixError } from 'matrix-js-sdk'; import { MatrixError } from 'matrix-js-sdk';
import { Cursor } from '../plugins/text-area'; import { Cursor } from '../plugins/text-area';
import { PhoneHit } from '../styles/PhoneHit.css';
import { syntaxErrorPosition } from '../utils/dom'; import { syntaxErrorPosition } from '../utils/dom';
import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback'; import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback';
import { Page, PageHeader } from './page'; import { Page, PageHeader } from './page';
@ -294,7 +295,7 @@ export function AccountDataEditor({
</Chip> </Chip>
</Box> </Box>
<Box shrink="No"> <Box shrink="No">
<IconButton onClick={requestClose} variant="Surface"> <IconButton onClick={requestClose} variant="Surface" className={PhoneHit}>
<Icon src={Icons.Cross} /> <Icon src={Icons.Cross} />
</IconButton> </IconButton>
</Box> </Box>

View file

@ -30,6 +30,7 @@ import {
} from '../hooks/useKeyBackup'; } from '../hooks/useKeyBackup';
import { stopPropagation } from '../utils/keyboard'; import { stopPropagation } from '../utils/keyboard';
import { useRestoreBackupOnVerification } from '../hooks/useRestoreBackupOnVerification'; import { useRestoreBackupOnVerification } from '../hooks/useRestoreBackupOnVerification';
import { PhoneHit } from '../styles/PhoneHit.css';
type BackupStatusProps = { type BackupStatusProps = {
enabled: boolean; enabled: boolean;
@ -177,6 +178,7 @@ export function BackupRestoreTile({ crypto }: BackupRestoreTileProps) {
<BackupSyncing count={remainingSession} /> <BackupSyncing count={remainingSession} />
)} )}
<IconButton <IconButton
className={PhoneHit}
aria-pressed={!!menuCords} aria-pressed={!!menuCords}
size="300" size="300"
variant="Surface" variant="Surface"

View file

@ -30,6 +30,7 @@ import {
} from '../hooks/useVerificationRequest'; } from '../hooks/useVerificationRequest';
import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback'; import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback';
import { ContainerColor } from '../styles/ContainerColor.css'; import { ContainerColor } from '../styles/ContainerColor.css';
import { PhoneHit } from '../styles/PhoneHit.css';
const DialogHeaderStyles: CSSProperties = { const DialogHeaderStyles: CSSProperties = {
padding: `0 ${config.space.S200} 0 ${config.space.S400}`, padding: `0 ${config.space.S200} 0 ${config.space.S400}`,
@ -261,7 +262,7 @@ export function DeviceVerification({ request, onExit }: DeviceVerificationProps)
<Box grow="Yes"> <Box grow="Yes">
<Text size="H4">Device Verification</Text> <Text size="H4">Device Verification</Text>
</Box> </Box>
<IconButton size="300" radii="300" onClick={handleCancel}> <IconButton className={PhoneHit} size="300" radii="300" onClick={handleCancel}>
<Icon src={Icons.Cross} /> <Icon src={Icons.Cross} />
</IconButton> </IconButton>
</Header> </Header>

View file

@ -25,6 +25,7 @@ import { ActionUIA, ActionUIAFlowsLoader } from './ActionUIA';
import { useMatrixClient } from '../hooks/useMatrixClient'; import { useMatrixClient } from '../hooks/useMatrixClient';
import { useAlive } from '../hooks/useAlive'; import { useAlive } from '../hooks/useAlive';
import { UseStateProvider } from './UseStateProvider'; import { UseStateProvider } from './UseStateProvider';
import { PhoneHit } from '../styles/PhoneHit.css';
type UIACallback<T> = ( type UIACallback<T> = (
authDict: AuthDict | null authDict: AuthDict | null
@ -301,7 +302,7 @@ export const DeviceVerificationSetup = forwardRef<HTMLDivElement, DeviceVerifica
<Box grow="Yes"> <Box grow="Yes">
<Text size="H4">Setup Device Verification</Text> <Text size="H4">Setup Device Verification</Text>
</Box> </Box>
<IconButton size="300" radii="300" onClick={onCancel}> <IconButton className={PhoneHit} size="300" radii="300" onClick={onCancel}>
<Icon src={Icons.Cross} /> <Icon src={Icons.Cross} />
</IconButton> </IconButton>
</Header> </Header>
@ -336,7 +337,7 @@ export const DeviceVerificationReset = forwardRef<HTMLDivElement, DeviceVerifica
<Box grow="Yes"> <Box grow="Yes">
<Text size="H4">Reset Device Verification</Text> <Text size="H4">Reset Device Verification</Text>
</Box> </Box>
<IconButton size="300" radii="300" onClick={onCancel}> <IconButton className={PhoneHit} size="300" radii="300" onClick={onCancel}>
<Icon src={Icons.Cross} /> <Icon src={Icons.Cross} />
</IconButton> </IconButton>
</Header> </Header>

View file

@ -27,6 +27,7 @@ import { AsyncStatus } from '../../hooks/useAsyncCallback';
import { useZoom } from '../../hooks/useZoom'; import { useZoom } from '../../hooks/useZoom';
import { createPage, usePdfDocumentLoader, usePdfJSLoader } from '../../plugins/pdfjs-dist'; import { createPage, usePdfDocumentLoader, usePdfJSLoader } from '../../plugins/pdfjs-dist';
import { stopPropagation } from '../../utils/keyboard'; import { stopPropagation } from '../../utils/keyboard';
import { PhoneHit, PhoneHitSpread24 } from '../../styles/PhoneHit.css';
export type PdfViewerProps = { export type PdfViewerProps = {
name: string; name: string;
@ -108,7 +109,7 @@ export const PdfViewer = as<'div', PdfViewerProps>(
<Box className={classNames(css.PdfViewer, className)} direction="Column" {...props} ref={ref}> <Box className={classNames(css.PdfViewer, className)} direction="Column" {...props} ref={ref}>
<Header className={css.PdfViewerHeader} size="400"> <Header className={css.PdfViewerHeader} size="400">
<Box grow="Yes" alignItems="Center" gap="200"> <Box grow="Yes" alignItems="Center" gap="200">
<IconButton size="300" radii="300" onClick={requestClose}> <IconButton className={PhoneHit} size="300" radii="300" onClick={requestClose}>
<Icon size="50" src={Icons.ArrowLeft} /> <Icon size="50" src={Icons.ArrowLeft} />
</IconButton> </IconButton>
<Text size="T300" truncate> <Text size="T300" truncate>
@ -117,6 +118,7 @@ export const PdfViewer = as<'div', PdfViewerProps>(
</Box> </Box>
<Box shrink="No" alignItems="Center" gap="200"> <Box shrink="No" alignItems="Center" gap="200">
<IconButton <IconButton
className={PhoneHitSpread24}
variant={zoom < 1 ? 'Success' : 'SurfaceVariant'} variant={zoom < 1 ? 'Success' : 'SurfaceVariant'}
outlined={zoom < 1} outlined={zoom < 1}
size="300" size="300"
@ -130,6 +132,7 @@ export const PdfViewer = as<'div', PdfViewerProps>(
<Text size="B300">{Math.round(zoom * 100)}%</Text> <Text size="B300">{Math.round(zoom * 100)}%</Text>
</Chip> </Chip>
<IconButton <IconButton
className={PhoneHitSpread24}
variant={zoom > 1 ? 'Success' : 'SurfaceVariant'} variant={zoom > 1 ? 'Success' : 'SurfaceVariant'}
outlined={zoom > 1} outlined={zoom > 1}
size="300" size="300"

View file

@ -13,6 +13,7 @@ import {
IconButton, IconButton,
} from 'folds'; } from 'folds';
import FocusTrap from 'focus-trap-react'; import FocusTrap from 'focus-trap-react';
import { PhoneHit } from '../styles/PhoneHit.css';
export type UIAFlowOverlayProps = { export type UIAFlowOverlayProps = {
currentStep: number; currentStep: number;
@ -53,6 +54,7 @@ export function UIAFlowOverlay({
> >
{(anchorRef) => ( {(anchorRef) => (
<IconButton <IconButton
className={PhoneHit}
ref={anchorRef} ref={anchorRef}
variant="Critical" variant="Critical"
size="300" size="300"

View file

@ -1,84 +0,0 @@
import React, { useState } from 'react';
import FocusTrap from 'focus-trap-react';
import {
config,
Icon,
IconButton,
Icons,
Line,
Modal,
Overlay,
OverlayBackdrop,
OverlayCenter,
} from 'folds';
import { CustomEditor, useEditor } from './Editor';
import { Toolbar } from './Toolbar';
import { stopPropagation } from '../../utils/keyboard';
export function EditorPreview() {
const [open, setOpen] = useState(false);
const editor = useEditor();
const [toolbar, setToolbar] = useState(false);
return (
<>
<IconButton variant="SurfaceVariant" onClick={() => setOpen(!open)}>
<Icon src={Icons.BlockQuote} />
</IconButton>
<Overlay open={open} backdrop={<OverlayBackdrop />}>
<OverlayCenter>
<FocusTrap
focusTrapOptions={{
initialFocus: false,
onDeactivate: () => setOpen(false),
clickOutsideDeactivates: true,
escapeDeactivates: stopPropagation,
}}
>
<Modal size="500">
<div style={{ padding: config.space.S400 }}>
<CustomEditor
editor={editor}
placeholder="Send a message..."
before={
<IconButton variant="SurfaceVariant" size="300" radii="300">
<Icon src={Icons.PlusCircle} />
</IconButton>
}
after={
<>
<IconButton
variant="SurfaceVariant"
size="300"
radii="300"
onClick={() => setToolbar(!toolbar)}
aria-pressed={toolbar}
>
<Icon src={toolbar ? Icons.AlphabetUnderline : Icons.Alphabet} />
</IconButton>
<IconButton variant="SurfaceVariant" size="300" radii="300">
<Icon src={Icons.Smile} />
</IconButton>
<IconButton variant="SurfaceVariant" size="300" radii="300">
<Icon src={Icons.Send} />
</IconButton>
</>
}
bottom={
toolbar && (
<div>
<Line variant="SurfaceVariant" size="300" />
<Toolbar />
</div>
)
}
/>
</div>
</Modal>
</FocusTrap>
</OverlayCenter>
</Overlay>
</>
);
}

View file

@ -36,6 +36,7 @@ import { KeySymbol } from '../../utils/key-symbol';
import { useSetting } from '../../state/hooks/settings'; import { useSetting } from '../../state/hooks/settings';
import { settingsAtom } from '../../state/settings'; import { settingsAtom } from '../../state/settings';
import { stopPropagation } from '../../utils/keyboard'; import { stopPropagation } from '../../utils/keyboard';
import { PhoneHit, PhoneHitRoom36, PhoneHitSpread36 } from '../../styles/PhoneHit.css';
function BtnTooltip({ text, shortCode }: { text: string; shortCode?: string }) { function BtnTooltip({ text, shortCode }: { text: string; shortCode?: string }) {
return ( return (
@ -72,6 +73,7 @@ export function MarkButton({ format, icon, tooltip }: MarkButtonProps) {
<TooltipProvider tooltip={tooltip} delay={500}> <TooltipProvider tooltip={tooltip} delay={500}>
{(triggerRef) => ( {(triggerRef) => (
<IconButton <IconButton
className={PhoneHitSpread36}
ref={triggerRef} ref={triggerRef}
variant="SurfaceVariant" variant="SurfaceVariant"
onClick={handleClick} onClick={handleClick}
@ -104,6 +106,7 @@ export function BlockButton({ format, icon, tooltip }: BlockButtonProps) {
<TooltipProvider tooltip={tooltip} delay={500}> <TooltipProvider tooltip={tooltip} delay={500}>
{(triggerRef) => ( {(triggerRef) => (
<IconButton <IconButton
className={PhoneHitSpread36}
ref={triggerRef} ref={triggerRef}
variant="SurfaceVariant" variant="SurfaceVariant"
onClick={handleClick} onClick={handleClick}
@ -163,6 +166,7 @@ export function HeadingBlockButton() {
> >
{(triggerRef) => ( {(triggerRef) => (
<IconButton <IconButton
className={PhoneHitRoom36}
ref={triggerRef} ref={triggerRef}
onClick={() => handleMenuSelect(1)} onClick={() => handleMenuSelect(1)}
size="400" size="400"
@ -178,6 +182,7 @@ export function HeadingBlockButton() {
> >
{(triggerRef) => ( {(triggerRef) => (
<IconButton <IconButton
className={PhoneHitRoom36}
ref={triggerRef} ref={triggerRef}
onClick={() => handleMenuSelect(2)} onClick={() => handleMenuSelect(2)}
size="400" size="400"
@ -193,6 +198,7 @@ export function HeadingBlockButton() {
> >
{(triggerRef) => ( {(triggerRef) => (
<IconButton <IconButton
className={PhoneHitRoom36}
ref={triggerRef} ref={triggerRef}
onClick={() => handleMenuSelect(3)} onClick={() => handleMenuSelect(3)}
size="400" size="400"
@ -208,6 +214,7 @@ export function HeadingBlockButton() {
} }
> >
<IconButton <IconButton
className={PhoneHit}
style={{ width: 'unset' }} style={{ width: 'unset' }}
variant="SurfaceVariant" variant="SurfaceVariant"
onClick={handleMenuOpen} onClick={handleMenuOpen}
@ -239,6 +246,7 @@ export function ExitFormatting({ tooltip }: ExitFormattingProps) {
<TooltipProvider tooltip={tooltip} delay={500}> <TooltipProvider tooltip={tooltip} delay={500}>
{(triggerRef) => ( {(triggerRef) => (
<IconButton <IconButton
className={PhoneHit}
ref={triggerRef} ref={triggerRef}
variant="SurfaceVariant" variant="SurfaceVariant"
onClick={handleClick} onClick={handleClick}
@ -344,6 +352,7 @@ export function Toolbar() {
> >
{(triggerRef) => ( {(triggerRef) => (
<IconButton <IconButton
className={PhoneHit}
ref={triggerRef} ref={triggerRef}
variant="SurfaceVariant" variant="SurfaceVariant"
onClick={() => setIsMarkdown(!isMarkdown)} onClick={() => setIsMarkdown(!isMarkdown)}

View file

@ -14,6 +14,7 @@ import {
} from 'folds'; } from 'folds';
import classNames from 'classnames'; import classNames from 'classnames';
import * as css from './styles.css'; import * as css from './styles.css';
import { PhoneHit } from '../../../styles/PhoneHit.css';
export function Sidebar({ children }: { children: ReactNode }) { export function Sidebar({ children }: { children: ReactNode }) {
return ( return (
@ -68,6 +69,7 @@ function SidebarBtn<T extends string>({
> >
{(ref) => ( {(ref) => (
<IconButton <IconButton
className={PhoneHit}
aria-pressed={active} aria-pressed={active}
aria-labelledby={`SidebarStackItem-${id}-label`} aria-labelledby={`SidebarStackItem-${id}-label`}
ref={ref} ref={ref}

View file

@ -24,6 +24,7 @@ import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
import { useOpenUserRoomProfile } from '../../state/hooks/userRoomProfile'; import { useOpenUserRoomProfile } from '../../state/hooks/userRoomProfile';
import { useSpaceOptionally } from '../../hooks/useSpace'; import { useSpaceOptionally } from '../../hooks/useSpace';
import { getMouseEventCords } from '../../utils/dom'; import { getMouseEventCords } from '../../utils/dom';
import { PhoneHit } from '../../styles/PhoneHit.css';
export type EventReadersProps = { export type EventReadersProps = {
room: Room; room: Room;
@ -52,7 +53,7 @@ export const EventReaders = as<'div', EventReadersProps>(
<Box grow="Yes"> <Box grow="Yes">
<Text size="H3">Seen by</Text> <Text size="H3">Seen by</Text>
</Box> </Box>
<IconButton size="300" onClick={requestClose}> <IconButton className={PhoneHit} size="300" onClick={requestClose}>
<Icon src={Icons.Cross} /> <Icon src={Icons.Cross} />
</IconButton> </IconButton>
</Header> </Header>

View file

@ -2,6 +2,7 @@ import React from 'react';
import classNames from 'classnames'; import classNames from 'classnames';
import { Box, Chip, Header, Icon, IconButton, Icons, Text, as } from 'folds'; import { Box, Chip, Header, Icon, IconButton, Icons, Text, as } from 'folds';
import * as css from './ImageEditor.css'; import * as css from './ImageEditor.css';
import { PhoneHit } from '../../styles/PhoneHit.css';
export type ImageEditorProps = { export type ImageEditorProps = {
name: string; name: string;
@ -24,7 +25,7 @@ export const ImageEditor = as<'div', ImageEditorProps>(
> >
<Header className={css.ImageEditorHeader} size="400"> <Header className={css.ImageEditorHeader} size="400">
<Box grow="Yes" alignItems="Center" gap="200"> <Box grow="Yes" alignItems="Center" gap="200">
<IconButton size="300" radii="300" onClick={requestClose}> <IconButton className={PhoneHit} size="300" radii="300" onClick={requestClose}>
<Icon size="50" src={Icons.ArrowLeft} /> <Icon size="50" src={Icons.ArrowLeft} />
</IconButton> </IconButton>
<Text size="T300" truncate> <Text size="T300" truncate>

View file

@ -1,6 +1,7 @@
import React from 'react'; import React from 'react';
import { Box, IconButton, Text, Icon, Icons, Scroll, Chip } from 'folds'; import { Box, IconButton, Text, Icon, Icons, Scroll, Chip } from 'folds';
import { PackAddress } from '../../plugins/custom-emoji'; import { PackAddress } from '../../plugins/custom-emoji';
import { PhoneHit } from '../../styles/PhoneHit.css';
import { Page, PageHeader, PageContent } from '../page'; import { Page, PageHeader, PageContent } from '../page';
import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useMatrixClient } from '../../hooks/useMatrixClient';
import { RoomImagePack } from './RoomImagePack'; import { RoomImagePack } from './RoomImagePack';
@ -29,7 +30,7 @@ export function ImagePackView({ address, requestClose }: ImagePackViewProps) {
</Chip> </Chip>
</Box> </Box>
<Box shrink="No"> <Box shrink="No">
<IconButton onClick={requestClose} variant="Surface"> <IconButton onClick={requestClose} variant="Surface" className={PhoneHit}>
<Icon src={Icons.Cross} /> <Icon src={Icons.Cross} />
</IconButton> </IconButton>
</Box> </Box>

View file

@ -7,6 +7,7 @@ import * as css from './ImageViewer.css';
import { useZoom } from '../../hooks/useZoom'; import { useZoom } from '../../hooks/useZoom';
import { usePan } from '../../hooks/usePan'; import { usePan } from '../../hooks/usePan';
import { downloadMedia } from '../../utils/matrix'; import { downloadMedia } from '../../utils/matrix';
import { PhoneHit, PhoneHitSpread24 } from '../../styles/PhoneHit.css';
export type ImageViewerProps = { export type ImageViewerProps = {
alt: string; alt: string;
@ -33,7 +34,7 @@ export const ImageViewer = as<'div', ImageViewerProps>(
> >
<Header className={css.ImageViewerHeader} size="400"> <Header className={css.ImageViewerHeader} size="400">
<Box grow="Yes" alignItems="Center" gap="200"> <Box grow="Yes" alignItems="Center" gap="200">
<IconButton size="300" radii="300" onClick={requestClose}> <IconButton className={PhoneHit} size="300" radii="300" onClick={requestClose}>
<Icon size="50" src={Icons.ArrowLeft} /> <Icon size="50" src={Icons.ArrowLeft} />
</IconButton> </IconButton>
<Text size="T300" truncate> <Text size="T300" truncate>
@ -42,6 +43,7 @@ export const ImageViewer = as<'div', ImageViewerProps>(
</Box> </Box>
<Box shrink="No" alignItems="Center" gap="200"> <Box shrink="No" alignItems="Center" gap="200">
<IconButton <IconButton
className={PhoneHitSpread24}
variant={zoom < 1 ? 'Success' : 'SurfaceVariant'} variant={zoom < 1 ? 'Success' : 'SurfaceVariant'}
outlined={zoom < 1} outlined={zoom < 1}
size="300" size="300"
@ -55,6 +57,7 @@ export const ImageViewer = as<'div', ImageViewerProps>(
<Text size="B300">{Math.round(zoom * 100)}%</Text> <Text size="B300">{Math.round(zoom * 100)}%</Text>
</Chip> </Chip>
<IconButton <IconButton
className={PhoneHitSpread24}
variant={zoom > 1 ? 'Success' : 'SurfaceVariant'} variant={zoom > 1 ? 'Success' : 'SurfaceVariant'}
outlined={zoom > 1} outlined={zoom > 1}
size="300" size="300"

View file

@ -42,6 +42,7 @@ import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useMatrixClient } from '../../hooks/useMatrixClient';
import { BreakWord } from '../../styles/Text.css'; import { BreakWord } from '../../styles/Text.css';
import { useAlive } from '../../hooks/useAlive'; import { useAlive } from '../../hooks/useAlive';
import { PhoneHit } from '../../styles/PhoneHit.css';
const SEARCH_OPTIONS: UseAsyncSearchOptions = { const SEARCH_OPTIONS: UseAsyncSearchOptions = {
limit: 1000, limit: 1000,
@ -173,7 +174,7 @@ export function InviteUserPrompt({ room, requestClose }: InviteUserProps) {
</Text> </Text>
</Box> </Box>
<Box shrink="No"> <Box shrink="No">
<IconButton size="300" radii="300" onClick={requestClose}> <IconButton className={PhoneHit} size="300" radii="300" onClick={requestClose}>
<Icon src={Icons.Cross} /> <Icon src={Icons.Cross} />
</IconButton> </IconButton>
</Box> </Box>

View file

@ -20,6 +20,7 @@ import { stopPropagation } from '../../utils/keyboard';
import { isRoomAlias, isRoomId } from '../../utils/matrix'; import { isRoomAlias, isRoomId } from '../../utils/matrix';
import { parseMatrixToRoom, parseMatrixToRoomEvent, testMatrixTo } from '../../plugins/matrix-to'; import { parseMatrixToRoom, parseMatrixToRoomEvent, testMatrixTo } from '../../plugins/matrix-to';
import { tryDecodeURIComponent } from '../../utils/dom'; import { tryDecodeURIComponent } from '../../utils/dom';
import { PhoneHit } from '../../styles/PhoneHit.css';
type JoinAddressProps = { type JoinAddressProps = {
onOpen: (roomIdOrAlias: string, via?: string[], eventId?: string) => void; onOpen: (roomIdOrAlias: string, via?: string[], eventId?: string) => void;
@ -82,7 +83,7 @@ export function JoinAddressPrompt({ onOpen, onCancel }: JoinAddressProps) {
<Box grow="Yes"> <Box grow="Yes">
<Text size="H4">Join with Address</Text> <Text size="H4">Join with Address</Text>
</Box> </Box>
<IconButton size="300" onClick={onCancel} radii="300"> <IconButton className={PhoneHit} size="300" onClick={onCancel} radii="300">
<Icon src={Icons.Cross} /> <Icon src={Icons.Cross} />
</IconButton> </IconButton>
</Header> </Header>

View file

@ -20,6 +20,7 @@ import { MatrixError } from 'matrix-js-sdk';
import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useMatrixClient } from '../../hooks/useMatrixClient';
import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback'; import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
import { stopPropagation } from '../../utils/keyboard'; import { stopPropagation } from '../../utils/keyboard';
import { PhoneHit } from '../../styles/PhoneHit.css';
type LeaveRoomPromptProps = { type LeaveRoomPromptProps = {
roomId: string; roomId: string;
@ -68,7 +69,7 @@ export function LeaveRoomPrompt({ roomId, onDone, onCancel }: LeaveRoomPromptPro
<Box grow="Yes"> <Box grow="Yes">
<Text size="H4">Leave Room</Text> <Text size="H4">Leave Room</Text>
</Box> </Box>
<IconButton size="300" onClick={onCancel} radii="300"> <IconButton className={PhoneHit} size="300" onClick={onCancel} radii="300">
<Icon src={Icons.Cross} /> <Icon src={Icons.Cross} />
</IconButton> </IconButton>
</Header> </Header>

View file

@ -20,6 +20,7 @@ import { MatrixError } from 'matrix-js-sdk';
import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useMatrixClient } from '../../hooks/useMatrixClient';
import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback'; import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
import { stopPropagation } from '../../utils/keyboard'; import { stopPropagation } from '../../utils/keyboard';
import { PhoneHit } from '../../styles/PhoneHit.css';
type LeaveSpacePromptProps = { type LeaveSpacePromptProps = {
roomId: string; roomId: string;
@ -68,7 +69,7 @@ export function LeaveSpacePrompt({ roomId, onDone, onCancel }: LeaveSpacePromptP
<Box grow="Yes"> <Box grow="Yes">
<Text size="H4">Leave Space</Text> <Text size="H4">Leave Space</Text>
</Box> </Box>
<IconButton size="300" onClick={onCancel} radii="300"> <IconButton className={PhoneHit} size="300" onClick={onCancel} radii="300">
<Icon src={Icons.Cross} /> <Icon src={Icons.Cross} />
</IconButton> </IconButton>
</Header> </Header>

View file

@ -2,6 +2,7 @@ import { Badge, Box, Icon, IconButton, Icons, Spinner, Text, as, toRem } from 'f
import React, { ReactNode, useCallback } from 'react'; import React, { ReactNode, useCallback } from 'react';
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment'; import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import FileSaver from 'file-saver'; import FileSaver from 'file-saver';
import { PhoneHit } from '../../styles/PhoneHit.css';
import { mimeTypeToExt } from '../../utils/mimeTypes'; import { mimeTypeToExt } from '../../utils/mimeTypes';
import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useMatrixClient } from '../../hooks/useMatrixClient';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication'; import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
@ -48,6 +49,7 @@ export function FileDownloadButton({ filename, url, mimeType, encInfo }: FileDow
variant={hasError ? 'Critical' : 'SurfaceVariant'} variant={hasError ? 'Critical' : 'SurfaceVariant'}
size="300" size="300"
radii="300" radii="300"
className={PhoneHit}
> >
{downloading ? ( {downloading ? (
<Spinner size="100" variant={hasError ? 'Critical' : 'Secondary'} /> <Spinner size="100" variant={hasError ? 'Critical' : 'Secondary'} />

View file

@ -1,6 +1,9 @@
import { createVar, style } from '@vanilla-extract/css'; import { createVar, style } from '@vanilla-extract/css';
import { DefaultReset, FocusOutline, color, config, toRem } from 'folds'; import { DefaultReset, FocusOutline, color, config, toRem } from 'folds';
import { MOBILE_BREAKPOINT } from '../../hooks/useScreenSize';
import { PHONE_TAP } from '../../styles/PhoneHit.css';
const PHONE = `screen and (max-width: ${MOBILE_BREAKPOINT}px)`;
const Container = createVar(); const Container = createVar();
const ContainerHover = createVar(); const ContainerHover = createVar();
const ContainerActive = createVar(); const ContainerActive = createVar();
@ -25,6 +28,14 @@ export const Reaction = style([
selectors: { selectors: {
'button&': { 'button&': {
cursor: 'pointer', cursor: 'pointer',
// Phone tap target: the chip is 26 px tall, so its hit area grows 9 px above and below (an ::after) and the
// same 9 px of margin opens the row, so the chips of one row and of the next never share a tap.
'@media': { [PHONE]: { position: 'relative', marginBlock: (PHONE_TAP - 26) / 2 } },
},
'button&::after': {
'@media': {
[PHONE]: { content: '""', position: 'absolute', inset: `${-(PHONE_TAP - 26) / 2}px 0` },
},
}, },
'&[aria-pressed=true]': { '&[aria-pressed=true]': {
vars: { vars: {

View file

@ -3,6 +3,7 @@ import React, { ReactNode, useCallback, useRef, useState } from 'react';
import { Badge, Chip, Icon, IconButton, Icons, ProgressBar, Spinner, Text, toRem } from 'folds'; import { Badge, Chip, Icon, IconButton, Icons, ProgressBar, Spinner, Text, toRem } from 'folds';
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment'; import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import { Range } from 'react-range'; import { Range } from 'react-range';
import { PhoneHitSpread24 } from '../../../styles/PhoneHit.css';
import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { IAudioInfo } from '../../../../types/matrix/common'; import { IAudioInfo } from '../../../../types/matrix/common';
@ -159,6 +160,7 @@ export function AudioContent({
variant="SurfaceVariant" variant="SurfaceVariant"
size="300" size="300"
radii="Pill" radii="Pill"
className={PhoneHitSpread24}
onClick={() => setMute(!mute)} onClick={() => setMute(!mute)}
aria-pressed={mute} aria-pressed={mute}
> >

View file

@ -299,7 +299,10 @@ export const BubbleLeftArrow = style({
}); });
// Phone tap target: a sender name is 23 px tall, so the button grows 11 px above and below (44+ px to tap) and the // Phone tap target: a sender name is 23 px tall, so the button grows 11 px above and below (44+ px to tap) and the
// negative margin takes the growth back out of the layout. Hit area only: no background, border or outline moves. // negative margin takes the growth back out of the layout. Sideways it cannot borrow from the layout the
// same way (a negative inline margin makes the button shrink inside its shrink-to-fit parent and clip the name), so
// a name under 44 px is 44 px wide, text kept at the start: real growth of at most 16 px, in a row with room for it.
// No background, border or outline moves.
const SCREEN_PHONE = `screen and (max-width: ${MOBILE_BREAKPOINT}px)`; const SCREEN_PHONE = `screen and (max-width: ${MOBILE_BREAKPOINT}px)`;
export const Username = style({ export const Username = style({
overflow: 'hidden', overflow: 'hidden',
@ -309,7 +312,7 @@ export const Username = style({
'button&': { 'button&': {
cursor: 'pointer', cursor: 'pointer',
'@media': { '@media': {
[SCREEN_PHONE]: { paddingBlock: 11, marginBlock: -11 }, [SCREEN_PHONE]: { paddingBlock: 11, marginBlock: -11, minWidth: 44, textAlign: 'start' },
}, },
}, },
'button&:hover, button&:focus-visible': { 'button&:hover, button&:focus-visible': {

View file

@ -53,6 +53,10 @@ export const NavCategoryHeader = style({
'&&': { paddingLeft: 0 }, '&&': { paddingLeft: 0 },
}, },
'@media': { '@media': {
// A phone's section header is as tall as its 44 px button, so it does not overlap the next row.
'screen and (max-width: 750px)': {
selectors: { '&&': { minHeight: toRem(44), height: toRem(44) } },
},
// Category labels sit on the scene like the rows do, and need a wash to be read (wide screens; // Category labels sit on the scene like the rows do, and need a wash to be read (wide screens;
// a phone's list is plain text). // a phone's list is plain text).
'screen and (min-width: 751px)': { 'screen and (min-width: 751px)': {
@ -117,6 +121,8 @@ const NavItemBase = style({
[PHONE]: { [PHONE]: {
backgroundColor: 'transparent', backgroundColor: 'transparent',
borderRadius: 0, borderRadius: 0,
// The row is as tall as the 44 px tap target inside it (EstateNavigator.css.ts), so neighbours do not overlap.
minHeight: toRem(44),
}, },
[WIDE]: { [WIDE]: {
selectors: { selectors: {
@ -127,7 +133,7 @@ const NavItemBase = style({
backgroundColor: ContainerHover, backgroundColor: ContainerHover,
}, },
// While the background scene runs the shell is clear (sceneShell.css.ts); a row is a faint // While the background scene runs the shell is clear (sceneShell.css.ts); a row is a faint
// wash of the theme's own surface: the terrain stays visible, the text stays readable. // wash of the theme's own surface: the scene stays visible, the text stays readable.
// Hover, the selected row and a press each strengthen it a step. // Hover, the selected row and a press each strengthen it a step.
':root[data-scene] &': { ':root[data-scene] &': {
backgroundColor: `color-mix(in srgb, ${surfaceInk} ${SCRIM_ROW}, transparent)`, backgroundColor: `color-mix(in srgb, ${surfaceInk} ${SCRIM_ROW}, transparent)`,

View file

@ -1,6 +1,7 @@
import React, { ComponentProps, forwardRef } from 'react'; import React, { ComponentProps, forwardRef } from 'react';
import { Icon, IconButton, Input, config, Icons } from 'folds'; import { Icon, IconButton, Input, config, Icons } from 'folds';
import { UseStateProvider } from '../UseStateProvider'; import { UseStateProvider } from '../UseStateProvider';
import { PhoneHit } from '../../styles/PhoneHit.css';
type PasswordInputProps = Omit<ComponentProps<typeof Input>, 'type' | 'size'> & { type PasswordInputProps = Omit<ComponentProps<typeof Input>, 'type' | 'size'> & {
size: '400' | '500'; size: '400' | '500';
@ -23,6 +24,7 @@ export const PasswordInput = forwardRef<HTMLInputElement, PasswordInputProps>(
<> <>
{after} {after}
<IconButton <IconButton
className={PhoneHit}
onClick={() => setVisible(!visible)} onClick={() => setVisible(!visible)}
type="button" type="button"
variant={visible ? 'Warning' : variant} variant={visible ? 'Warning' : variant}

View file

@ -4,6 +4,7 @@ import classNames from 'classnames';
import Linkify from 'linkify-react'; import Linkify from 'linkify-react';
import * as css from './style.css'; import * as css from './style.css';
import { LINKIFY_OPTS, scaleSystemEmoji } from '../../plugins/react-custom-html-parser'; import { LINKIFY_OPTS, scaleSystemEmoji } from '../../plugins/react-custom-html-parser';
import { PhoneHit } from '../../styles/PhoneHit.css';
export const RoomTopicViewer = as< export const RoomTopicViewer = as<
'div', 'div',
@ -26,7 +27,7 @@ export const RoomTopicViewer = as<
{name} {name}
</Text> </Text>
</Box> </Box>
<IconButton size="300" onClick={requestClose} radii="300"> <IconButton className={PhoneHit} size="300" onClick={requestClose} radii="300">
<Icon src={Icons.Cross} /> <Icon src={Icons.Cross} />
</IconButton> </IconButton>
</Header> </Header>

View file

@ -5,6 +5,7 @@ import { Box, Chip, Header, Icon, IconButton, Icons, Scroll, Text, as } from 'fo
import { ErrorBoundary } from 'react-error-boundary'; import { ErrorBoundary } from 'react-error-boundary';
import * as css from './TextViewer.css'; import * as css from './TextViewer.css';
import { copyToClipboard } from '../../utils/dom'; import { copyToClipboard } from '../../utils/dom';
import { PhoneHit } from '../../styles/PhoneHit.css';
const ReactPrism = lazy(() => import('../../plugins/react-prism/ReactPrism')); const ReactPrism = lazy(() => import('../../plugins/react-prism/ReactPrism'));
@ -53,7 +54,7 @@ export const TextViewer = as<'div', TextViewerProps>(
> >
<Header className={css.TextViewerHeader} size="400"> <Header className={css.TextViewerHeader} size="400">
<Box grow="Yes" alignItems="Center" gap="200"> <Box grow="Yes" alignItems="Center" gap="200">
<IconButton size="300" radii="300" onClick={requestClose}> <IconButton className={PhoneHit} size="300" radii="300" onClick={requestClose}>
<Icon size="50" src={Icons.ArrowLeft} /> <Icon size="50" src={Icons.ArrowLeft} />
</IconButton> </IconButton>
<Text size="T300" truncate> <Text size="T300" truncate>

View file

@ -4,6 +4,7 @@ import { AuthType } from 'matrix-js-sdk';
import { StageComponentProps } from './types'; import { StageComponentProps } from './types';
import { ErrorCode } from '../../cs-errorcode'; import { ErrorCode } from '../../cs-errorcode';
import { PasswordInput } from '../password-input'; import { PasswordInput } from '../password-input';
import { PhoneHit } from '../../styles/PhoneHit.css';
export function PasswordStage({ export function PasswordStage({
stageData, stageData,
@ -45,7 +46,7 @@ export function PasswordStage({
<Box grow="Yes"> <Box grow="Yes">
<Text size="H4">Account Password</Text> <Text size="H4">Account Password</Text>
</Box> </Box>
<IconButton size="300" onClick={onCancel} radii="300"> <IconButton className={PhoneHit} size="300" onClick={onCancel} radii="300">
<Icon src={Icons.Cross} /> <Icon src={Icons.Cross} />
</IconButton> </IconButton>
</Header> </Header>

View file

@ -1,6 +1,7 @@
import { Box, Button, color, config, Dialog, Header, Icon, IconButton, Icons, Text } from 'folds'; import { Box, Button, color, config, Dialog, Header, Icon, IconButton, Icons, Text } from 'folds';
import React, { useCallback, useEffect, useState } from 'react'; import React, { useCallback, useEffect, useState } from 'react';
import { StageComponentProps } from './types'; import { StageComponentProps } from './types';
import { PhoneHit } from '../../styles/PhoneHit.css';
export function SSOStage({ export function SSOStage({
ssoRedirectURL, ssoRedirectURL,
@ -56,7 +57,7 @@ export function SSOStage({
<Box grow="Yes"> <Box grow="Yes">
<Text size="H4">SSO Login</Text> <Text size="H4">SSO Login</Text>
</Box> </Box>
<IconButton size="300" onClick={onCancel} radii="300"> <IconButton className={PhoneHit} size="300" onClick={onCancel} radii="300">
<Icon src={Icons.Cross} /> <Icon src={Icons.Cross} />
</IconButton> </IconButton>
</Header> </Header>

View file

@ -6,6 +6,8 @@ import { useMatrixClient } from '../../hooks/useMatrixClient';
import { TUploadContent } from '../../utils/matrix'; import { TUploadContent } from '../../utils/matrix';
import { bytesToSize, getFileTypeIcon } from '../../utils/common'; import { bytesToSize, getFileTypeIcon } from '../../utils/common';
import { useMediaConfig } from '../../hooks/useMediaConfig'; import { useMediaConfig } from '../../hooks/useMediaConfig';
import { UploadFailureNote } from './UploadFailureNote';
import { PhoneHitSpread28 } from '../../styles/PhoneHit.css';
type CompactUploadCardRendererProps = { type CompactUploadCardRendererProps = {
isEncrypted?: boolean; isEncrypted?: boolean;
@ -63,6 +65,7 @@ export function CompactUploadCardRenderer({
</Chip> </Chip>
)} )}
<IconButton <IconButton
className={PhoneHitSpread28}
onClick={removeUpload} onClick={removeUpload}
aria-label="Cancel Upload" aria-label="Cancel Upload"
variant="SurfaceVariant" variant="SurfaceVariant"
@ -91,7 +94,7 @@ export function CompactUploadCardRenderer({
)} )}
{upload.status === UploadStatus.Error && ( {upload.status === UploadStatus.Error && (
<UploadCardError> <UploadCardError>
<Text size="T200">{upload.error.message}</Text> <UploadFailureNote error={upload.error} />
</UploadCardError> </UploadCardError>
)} )}
{upload.status === UploadStatus.Idle && fileSizeExceeded && ( {upload.status === UploadStatus.Idle && fileSizeExceeded && (

View file

@ -12,6 +12,8 @@ import {
} from '../../state/room/roomInputDrafts'; } from '../../state/room/roomInputDrafts';
import { useObjectURL } from '../../hooks/useObjectURL'; import { useObjectURL } from '../../hooks/useObjectURL';
import { useMediaConfig } from '../../hooks/useMediaConfig'; import { useMediaConfig } from '../../hooks/useMediaConfig';
import { UploadFailureNote } from './UploadFailureNote';
import { PhoneHitSpread28 } from '../../styles/PhoneHit.css';
type PreviewImageProps = { type PreviewImageProps = {
fileItem: TUploadItem; fileItem: TUploadItem;
@ -160,6 +162,7 @@ export function UploadCardRenderer({
</Chip> </Chip>
)} )}
<IconButton <IconButton
className={PhoneHitSpread28}
onClick={removeUpload} onClick={removeUpload}
aria-label="Cancel Upload" aria-label="Cancel Upload"
variant="SurfaceVariant" variant="SurfaceVariant"
@ -190,7 +193,7 @@ export function UploadCardRenderer({
)} )}
{upload.status === UploadStatus.Error && ( {upload.status === UploadStatus.Error && (
<UploadCardError> <UploadCardError>
<Text size="T200">{upload.error.message}</Text> <UploadFailureNote error={upload.error} />
</UploadCardError> </UploadCardError>
)} )}
{upload.status === UploadStatus.Idle && fileSizeExceeded && ( {upload.status === UploadStatus.Idle && fileSizeExceeded && (

View file

@ -0,0 +1,33 @@
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
import { uploadFailure } from '../../utils/matrix';
import { UploadFailureNote } from './UploadFailureNote';
const text = (html: string) =>
html
.replace(/<[^>]*>/g, ' ')
.replace(/\s+/g, ' ')
.trim();
describe('the failed upload card', () => {
it('leads with the reason and the next step, and keeps the diagnostics behind Details', async () => {
const error = await uploadFailure(new DOMException('', 'AbortError'), new Blob(['abcd']), {
startedAt: Date.now(),
});
const html = renderToStaticMarkup(<UploadFailureNote error={error} />);
const before = html.slice(0, html.indexOf('<details'));
expect(text(before)).toBe(
'Upload failed: the connection dropped before the file started. Send again.'
);
expect(before).not.toContain('bytes');
expect(html).toMatch(/<details[^>]*>.*Details.*<\/details>/s);
expect(text(html.slice(html.indexOf('<details')))).toContain('4 bytes');
});
it('an error nobody classified still shows a sentence, not a blank card', () => {
const html = renderToStaticMarkup(<UploadFailureNote error={new Error('boom')} />);
expect(text(html)).toContain('Upload failed. Send again');
expect(text(html)).toContain('boom');
});
});

View file

@ -0,0 +1,22 @@
import React from 'react';
import { Text } from 'folds';
import { uploadFailureText } from '../../utils/uploadReason';
/** A failed upload as the card shows it: the reason and what to do, the diagnostic text one tap away. */
export function UploadFailureNote({ error }: { error: Error }) {
return (
<>
<Text size="T200">{uploadFailureText(error)}</Text>
<details style={{ flex: 1, minWidth: 0 }}>
<summary style={{ minHeight: 44, display: 'flex', alignItems: 'center' }}>
<Text as="span" size="T200">
Details
</Text>
</summary>
<Text size="T200" style={{ wordBreak: 'break-word' }}>
{error.message}
</Text>
</details>
</>
);
}

View file

@ -1,3 +1,4 @@
import classNames from 'classnames';
import React, { useCallback, useEffect, useRef, useState } from 'react'; import React, { useCallback, useEffect, useRef, useState } from 'react';
import { IPreviewUrlResponse } from 'matrix-js-sdk'; import { IPreviewUrlResponse } from 'matrix-js-sdk';
import { Box, Icon, IconButton, Icons, Scroll, Spinner, Text, as, color, config } from 'folds'; import { Box, Icon, IconButton, Icons, Scroll, Spinner, Text, as, color, config } from 'folds';
@ -10,6 +11,7 @@ import {
useIntersectionObserver, useIntersectionObserver,
} from '../../hooks/useIntersectionObserver'; } from '../../hooks/useIntersectionObserver';
import * as css from './UrlPreviewCard.css'; import * as css from './UrlPreviewCard.css';
import { PhoneHitInPlace } from '../../styles/PhoneHit.css';
import { tryDecodeURIComponent } from '../../utils/dom'; import { tryDecodeURIComponent } from '../../utils/dom';
import { mxcUrlToHttp } from '../../utils/matrix'; import { mxcUrlToHttp } from '../../utils/matrix';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication'; import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
@ -181,7 +183,10 @@ export const UrlPreviewHolder = as<'div'>(({ children, ...props }, ref) => {
<> <>
<div className={css.UrlPreviewHolderGradient({ position: 'Left' })} /> <div className={css.UrlPreviewHolderGradient({ position: 'Left' })} />
<IconButton <IconButton
className={css.UrlPreviewHolderBtn({ position: 'Left' })} className={classNames(
css.UrlPreviewHolderBtn({ position: 'Left' }),
PhoneHitInPlace
)}
variant="Secondary" variant="Secondary"
radii="Pill" radii="Pill"
size="300" size="300"
@ -199,7 +204,10 @@ export const UrlPreviewHolder = as<'div'>(({ children, ...props }, ref) => {
<> <>
<div className={css.UrlPreviewHolderGradient({ position: 'Right' })} /> <div className={css.UrlPreviewHolderGradient({ position: 'Right' })} />
<IconButton <IconButton
className={css.UrlPreviewHolderBtn({ position: 'Right' })} className={classNames(
css.UrlPreviewHolderBtn({ position: 'Right' }),
PhoneHitInPlace
)}
variant="Primary" variant="Primary"
radii="Pill" radii="Pill"
size="300" size="300"

View file

@ -43,6 +43,7 @@ import { getPowerTagIconSrc, useGetMemberPowerTag } from '../../hooks/useMemberP
import { useRoomCreators } from '../../hooks/useRoomCreators'; import { useRoomCreators } from '../../hooks/useRoomCreators';
import { useRoomPermissions } from '../../hooks/useRoomPermissions'; import { useRoomPermissions } from '../../hooks/useRoomPermissions';
import { useMemberPowerCompare } from '../../hooks/useMemberPowerCompare'; import { useMemberPowerCompare } from '../../hooks/useMemberPowerCompare';
import { PhoneHit } from '../../styles/PhoneHit.css';
type SelfDemoteAlertProps = { type SelfDemoteAlertProps = {
power: number; power: number;
@ -70,7 +71,7 @@ function SelfDemoteAlert({ power, onCancel, onChange }: SelfDemoteAlertProps) {
<Box grow="Yes"> <Box grow="Yes">
<Text size="H4">Self Demotion</Text> <Text size="H4">Self Demotion</Text>
</Box> </Box>
<IconButton size="300" onClick={onCancel} radii="300"> <IconButton className={PhoneHit} size="300" onClick={onCancel} radii="300">
<Icon src={Icons.Cross} /> <Icon src={Icons.Cross} />
</IconButton> </IconButton>
</Header> </Header>
@ -120,7 +121,7 @@ function SharedPowerAlert({ power, onCancel, onChange }: SharedPowerAlertProps)
<Box grow="Yes"> <Box grow="Yes">
<Text size="H4">Shared Power</Text> <Text size="H4">Shared Power</Text>
</Box> </Box>
<IconButton size="300" onClick={onCancel} radii="300"> <IconButton className={PhoneHit} size="300" onClick={onCancel} radii="300">
<Icon src={Icons.Cross} /> <Icon src={Icons.Cross} />
</IconButton> </IconButton>
</Header> </Header>

View file

@ -54,6 +54,7 @@ import { StateEvent } from '../../../types/matrix/room';
import { getViaServers } from '../../plugins/via-servers'; import { getViaServers } from '../../plugins/via-servers';
import { rateLimitedActions } from '../../utils/matrix'; import { rateLimitedActions } from '../../utils/matrix';
import { useAlive } from '../../hooks/useAlive'; import { useAlive } from '../../hooks/useAlive';
import { PhoneHit } from '../../styles/PhoneHit.css';
const SEARCH_OPTS: UseAsyncSearchOptions = { const SEARCH_OPTS: UseAsyncSearchOptions = {
limit: 500, limit: 500,
@ -201,7 +202,7 @@ export function AddExistingModal({ parentId, space, requestClose }: AddExistingM
<Text size="H4">Add Existing</Text> <Text size="H4">Add Existing</Text>
</Box> </Box>
<Box shrink="No"> <Box shrink="No">
<IconButton size="300" radii="300" onClick={requestClose}> <IconButton className={PhoneHit} size="300" radii="300" onClick={requestClose}>
<Icon src={Icons.Cross} /> <Icon src={Icons.Cross} />
</IconButton> </IconButton>
</Box> </Box>

View file

@ -49,3 +49,23 @@ export const FilesWide = style({
}); });
export const Dim = style({ opacity: config.opacity.P300 }); export const Dim = style({ opacity: config.opacity.P300 });
/** The share panel: idle it is one row; the title, names and Send mount only once files are picked. */
export const SharePanel = style({
display: 'flex',
flexDirection: 'column',
gap: config.space.S200,
});
export const ShareTitle = style({
all: 'unset',
boxSizing: 'border-box',
minHeight: 44,
width: '100%',
borderBottom: `1px solid ${color.Background.ContainerLine}`,
color: color.Background.OnContainer,
':focus-visible': { borderBottomColor: color.Background.OnContainer },
});
/** Picked names and send notes wrap, even a long unbroken name. */
export const ShareNames = style({ overflowWrap: 'anywhere' });

View file

@ -14,8 +14,17 @@ import { markAsRead } from '../../utils/notifications';
import { getBlobSafeMimeType } from '../../utils/mimeTypes'; import { getBlobSafeMimeType } from '../../utils/mimeTypes';
import { timeDayMonYear } from '../../utils/time'; import { timeDayMonYear } from '../../utils/time';
import { getMemberDisplayName } from '../../utils/room'; import { getMemberDisplayName } from '../../utils/room';
import { Album, AlbumFile } from './buildAlbums'; import {
Album,
AlbumFile,
TimelineEvent,
lastEvent,
looseFiles,
looseNoteFor,
} from './buildAlbums';
import { folderOf, listFolder, pathLabel } from './albumFolders';
import { FileReadBy } from './FileReadBy'; import { FileReadBy } from './FileReadBy';
import { ShareSet, useShareEnabled } from './ShareSet';
import { useAlbums } from './useAlbums'; import { useAlbums } from './useAlbums';
import * as css from './AlbumView.css'; import * as css from './AlbumView.css';
@ -66,6 +75,26 @@ function FileRow({ room, file, author }: FileRowProps) {
); );
} }
/** A file, and under it a row that unfolds the versions it supersedes. */
function VersionedFileRow({ room, file, author }: FileRowProps) {
const [shown, setShown] = useState(false);
const n = file.earlier.length;
return (
<>
<FileRow room={room} file={file} author={author} />
{n > 0 && (
<button type="button" className={css.Row} onClick={() => setShown(!shown)}>
<Text size="T200" className={css.Dim}>
{`${shown ? '▾' : '▸'} ${n} earlier ${n === 1 ? 'version' : 'versions'}`}
</Text>
</button>
)}
{shown &&
file.earlier.map((e) => <FileRow key={e.id} room={room} file={e} author={author} />)}
</>
);
}
const countLabel = (n: number) => `${n} ${n === 1 ? 'file' : 'files'}`; const countLabel = (n: number) => `${n} ${n === 1 ? 'file' : 'files'}`;
/** The zone never mounts RoomTimeline, so it sends the read receipt the timeline would. */ /** The zone never mounts RoomTimeline, so it sends the read receipt the timeline would. */
@ -84,15 +113,51 @@ function useMarkZoneRead(room: Room) {
}, [mx, room, hideActivity]); }, [mx, room, hideActivity]);
} }
/** The file events in the room's live timeline that no album thread holds, kept current as it syncs. */
function useLooseFiles(room: Room): AlbumFile[] {
const [, bump] = useState(0);
useEffect(() => {
const on = () => bump((n) => n + 1);
room.on(RoomEvent.Timeline, on);
room.on(RoomEvent.Redaction, on);
return () => {
room.off(RoomEvent.Timeline, on);
room.off(RoomEvent.Redaction, on);
};
}, [room]);
const events: TimelineEvent[] = room
.getLiveTimeline()
.getEvents()
.map((e) => ({
event_id: e.getId(),
type: e.getType(),
sender: e.getSender(),
origin_server_ts: e.getTs(),
content: e.getContent(),
unsigned: e.getUnsigned() as Record<string, unknown>,
threadRoot: e.threadRootId,
}));
return looseFiles(events);
}
type AlbumViewProps = { room: Room; onTimeline: () => void }; type AlbumViewProps = { room: Room; onTimeline: () => void };
export function AlbumView({ room, onTimeline }: AlbumViewProps) { export function AlbumView({ room, onTimeline }: AlbumViewProps) {
useMarkZoneRead(room); useMarkZoneRead(room);
const { loading, error, albums } = useAlbums(room); const { loading, error, albums, truncated } = useAlbums(room);
const [dateFormat] = useSetting(settingsAtom, 'dateFormatString'); const [dateFormat] = useSetting(settingsAtom, 'dateFormatString');
const [openId, setOpenId] = useState<string>(); const [openId, setOpenId] = useState<string>();
const [path, setPath] = useState<string[]>([]);
const open: Album | undefined = albums.find((a) => a.id === openId); const open: Album | undefined = albums.find((a) => a.id === openId);
const authorOf = (a: Album) => getMemberDisplayName(room, a.author) ?? a.author; const authorOf = (a: Album) => getMemberDisplayName(room, a.author) ?? a.author;
const encrypted = room.hasEncryptionStateEvent(); const encrypted = room.hasEncryptionStateEvent();
const canShare = useShareEnabled(room);
const loose = useLooseFiles(room);
const looseNote = looseNoteFor(loose, {
open: !!open,
encrypted,
loading,
error: !!error,
});
let body: React.ReactNode; let body: React.ReactNode;
if (loading) body = <Text>Loading albums…</Text>; if (loading) body = <Text>Loading albums…</Text>;
@ -101,39 +166,98 @@ export function AlbumView({ room, onTimeline }: AlbumViewProps) {
const images = open.files.length > 0 && open.files.every((f) => f.kind === 'image'); const images = open.files.length > 0 && open.files.every((f) => f.kind === 'image');
body = ( body = (
<> <>
<button type="button" className={css.Back} onClick={() => setOpenId(undefined)}> <button
<Text size="B400">‹ Albums</Text> type="button"
className={css.Back}
onClick={() => {
setPath(folderOf(open));
setOpenId(undefined);
}}
>
<Text size="B400">{`‹ ${
folderOf(open).length ? pathLabel(folderOf(open)) : 'Albums'
}`}</Text>
</button> </button>
<Text size="H4">{open.title}</Text> <Text size="H4">{open.title}</Text>
<Text size="T200" className={css.Dim}> <Text size="T200" className={css.Dim}>
{authorOf(open)} · {countLabel(open.count)} · {timeDayMonYear(open.ts, dateFormat)} {authorOf(open)} · {countLabel(open.count)} · {timeDayMonYear(open.ts, dateFormat)}
</Text> </Text>
{open.count === 0 && <Text>This album has no files.</Text>} {open.count === 0 && <Text>This album has no files.</Text>}
{canShare && (
<ShareSet
key={open.id}
room={room}
into={{ albumId: open.id, lastId: lastEvent(open).id, lastTs: lastEvent(open).ts }}
/>
)}
<div className={images ? `${css.Files} ${css.FilesWide}` : css.Files}> <div className={images ? `${css.Files} ${css.FilesWide}` : css.Files}>
{open.files.map((f) => ( {open.files.map((f) => (
<FileRow key={f.id} room={room} file={f} author={authorOf(open)} /> <VersionedFileRow key={f.id} room={room} file={f} author={authorOf(open)} />
))} ))}
</div> </div>
</> </>
); );
} else if (encrypted) } else if (encrypted)
body = <Text>This zone is encrypted, so its albums cannot be listed here.</Text>; body = <Text>This zone is encrypted, so its albums cannot be listed here.</Text>;
else if (albums.length === 0) body = <Text>No albums yet.</Text>; else if (albums.length === 0 && path.length === 0) body = <Text>No albums yet.</Text>;
else { else {
body = albums.map((a) => ( const here = listFolder(albums, path);
body = (
<>
{path.length > 0 && (
<button type="button" className={css.Back} onClick={() => setPath(path.slice(0, -1))}>
<Text size="B400">{`‹ ${
path.length > 1 ? pathLabel(path.slice(0, -1)) : 'Albums'
}`}</Text>
</button>
)}
{path.length > 0 && <Text size="H4">{pathLabel(path)}</Text>}
{here.folders.map((f) => (
<button
key={`d:${f.name}`}
type="button"
className={css.Row}
onClick={() => setPath(f.path)}
>
<Text size="T400">{`${f.name} /`}</Text>
<Text size="T200" className={css.Dim}>
{f.albums} {f.albums === 1 ? 'album' : 'albums'} · {timeDayMonYear(f.ts, dateFormat)}
</Text>
</button>
))}
{here.albums.map(({ album: a, leaf }) => (
<button key={a.id} type="button" className={css.Row} onClick={() => setOpenId(a.id)}> <button key={a.id} type="button" className={css.Row} onClick={() => setOpenId(a.id)}>
<Text size="T400">{a.title}</Text> <Text size="T400">{leaf}</Text>
<Text size="T200" className={css.Dim}> <Text size="T200" className={css.Dim}>
{authorOf(a)} · {countLabel(a.count)} · {timeDayMonYear(a.ts, dateFormat)} {authorOf(a)} · {countLabel(a.count)} · {timeDayMonYear(a.ts, dateFormat)}
</Text> </Text>
</button> </button>
)); ))}
{here.folders.length === 0 && here.albums.length === 0 && <Text>Nothing here.</Text>}
{truncated && (
<Text size="T200" className={css.Dim}>
The list is cut short: some albums or files are not loaded.
</Text>
)}
</>
);
} }
return ( return (
<Scroll hideTrack visibility="Hover"> <Scroll hideTrack visibility="Hover">
<div className={css.Column}> <div className={css.Column}>
{body} {body}
{looseNote && (
<Text size="T200" className={css.Dim}>
{looseNote}
</Text>
)}
{/* Stays mounted while an album is open, so a running send keeps its progress. */}
{canShare && (
<div hidden={!!open}>
<ShareSet room={room} folder={path} />
</div>
)}
<button type="button" className={css.Row} onClick={onTimeline}> <button type="button" className={css.Row} onClick={onTimeline}>
<Text size="B400">Timeline ›</Text> <Text size="B400">Timeline ›</Text>
</button> </button>

View file

@ -0,0 +1,140 @@
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { MatrixClientProvider } from '../../hooks/useMatrixClient';
import { MediaConfig, MediaConfigProvider } from '../../hooks/useMediaConfig';
// ShareSet hands its folder to the title the send lands under. The controller is held still and its
// `run` captured, and sendShareSet records the title it was given, so the path from the `folder`
// prop to the album root's title is read without a homeserver or a DOM.
const captured = vi.hoisted(() => ({
run: undefined as undefined | ((files: unknown[], title: string, onFile: () => void) => unknown),
maxBytes: undefined as undefined | (() => number | undefined),
titles: [] as string[],
}));
vi.mock('./shareController', () => ({
createShareController: (deps: {
run: NonNullable<typeof captured.run>;
maxBytes: NonNullable<typeof captured.maxBytes>;
}) => {
captured.run = deps.run;
captured.maxBytes = deps.maxBytes;
return {
subscribe: () => () => undefined,
getState: () => ({ files: [], title: '', phase: { kind: 'idle' }, epoch: 0 }),
pick: () => undefined,
setTitle: () => undefined,
send: () => undefined,
cancel: () => undefined,
};
},
}));
vi.mock('./shareSet', async (importOriginal) => ({
...(await importOriginal<typeof import('./shareSet')>()),
sendShareSet: async (_port: unknown, into: string | { albumId: string; lastId: string }) => {
captured.titles.push(typeof into === 'string' ? into : `into:${into.albumId}@${into.lastId}`);
return { albumId: '$a', sent: 0, failed: [], failedAt: [] };
},
}));
vi.mock('react', async (importOriginal) => {
const actual = await importOriginal<typeof import('react')>();
// The server renderer has no snapshot for an external store; read the client one.
const useSyncExternalStore = (_sub: unknown, get: () => unknown) => get();
return { ...actual, default: { ...actual, useSyncExternalStore }, useSyncExternalStore };
});
// eslint-disable-next-line import/first
import { ShareSet } from './ShareSet';
const timeline: unknown[] = [];
const ev = (id: string, ts: number, threadRootId?: string, status: string | null = null) => ({
getId: () => id,
getTs: () => ts,
threadRootId,
status,
});
const mount = (
folder?: string[],
into?: { albumId: string; lastId: string; lastTs: number },
mediaConfig: MediaConfig = {}
) => {
const room = {
roomId: '!r:x',
hasEncryptionStateEvent: () => false,
getLiveTimeline: () => ({ getEvents: () => timeline }),
} as never;
renderToStaticMarkup(
<QueryClientProvider client={new QueryClient()}>
<MatrixClientProvider value={{ sendMessage: async () => ({ event_id: '$e' }) } as never}>
<MediaConfigProvider value={mediaConfig}>
<ShareSet room={room} folder={folder} into={into} />
</MediaConfigProvider>
</MatrixClientProvider>
</QueryClientProvider>
);
};
const send = async (typed: string) => {
await captured.run?.([], typed, () => undefined);
return captured.titles.at(-1);
};
describe('ShareSet: the folder reaches the album title', () => {
beforeEach(() => {
captured.run = undefined;
captured.titles.length = 0;
timeline.length = 0;
});
it('at the top, the typed title goes as typed', async () => {
mount();
expect(await send('Poses')).toBe('Poses');
});
it('inside a folder, the path prefixes the typed title', async () => {
mount(['cast-art', 'poses']);
expect(await send('Set 2')).toBe('cast-art/poses/Set 2');
});
it('an empty typed title falls back to the default, still under the folder', async () => {
mount(['handoff']);
expect(await send(' ')).toBe('handoff/Shared files');
});
it('a typed title containing a slash goes deeper', async () => {
mount(['a']);
expect(await send('b/c')).toBe('a/b/c');
});
it('an existing album takes the files instead of a title, whatever the folder', async () => {
mount(['a'], { albumId: '$alb', lastId: '$last', lastTs: 5 });
expect(await send('ignored')).toBe('into:$alb@$last');
});
it('the freshest sent event of that thread in the room timeline is where the files thread after', async () => {
timeline.push(
ev('$other', 99, '$else'),
ev('$local', 98, '$alb', 'sending'),
ev('$new', 50, '$alb'),
ev('$sentNotEchoed', 60, '$alb', 'sent'),
ev('$failed', 70, '$alb', 'not_sent')
);
mount(['a'], { albumId: '$alb', lastId: '$last', lastTs: 5 });
expect(await send('x')).toBe('into:$alb@$sentNotEchoed');
});
});
describe('ShareSet: the homeserver upload cap reaches the controller', () => {
it('is the server-stated m.upload.size, and none when the server states none', () => {
mount([], undefined, { 'm.upload.size': 52428800 });
expect(captured.maxBytes?.()).toBe(52428800);
mount([], undefined, {});
expect(captured.maxBytes?.()).toBeUndefined();
// A cap that is not a positive number is no cap, never "refuse everything".
[0, -1, Number.NaN, '50' as unknown as number].forEach((bad) => {
mount([], undefined, { 'm.upload.size': bad });
expect(captured.maxBytes?.()).toBeUndefined();
});
});
});

View file

@ -0,0 +1,123 @@
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
import { ClientConfigProvider } from '../../hooks/useClientConfig';
import type { ClientConfig } from '../../hooks/useClientConfig';
import { ShareState } from './shareController';
import { ShareSetView, shareEnabled, useShareEnabled } from './ShareSet';
const text = (html: string) =>
html
.replace(/<[^>]*>/g, ' ')
.replace(/\s+/g, ' ')
.trim();
const noop = () => undefined;
const file = (name: string) => ({ name, type: 'audio/ogg' } as File);
const view = (over: Partial<ShareState<File>> = {}, adding = false) =>
renderToStaticMarkup(
<ShareSetView
state={{ files: [], title: '', phase: { kind: 'idle' }, epoch: 0, ...over }}
onPickClick={noop}
onPicked={noop}
onTitle={noop}
onSend={noop}
onCancel={noop}
onStop={noop}
adding={adding}
/>
);
describe('the share panel, drawn', () => {
it('idle: one "Share files" row and no title, names, Send or Cancel', () => {
const html = view();
expect(text(html)).toBe('Share files ›');
expect(html).not.toContain('aria-label="Album title"');
expect(html).toContain('type="file"');
expect(html).toContain('multiple');
expect(html).toContain('hidden');
});
it('picked: the title field, the names on one line, Send N files and Cancel; no pick row', () => {
const html = view({ files: [file('a.ogg'), file('b.ogg')] });
expect(html).toContain('aria-label="Album title"');
expect(html).toContain('placeholder="Shared files"');
expect(text(html)).toBe('a.ogg · b.ogg Send 2 files Cancel');
expect(text(html)).not.toContain('Share files');
});
it('one picked file reads "Send 1 file"', () => {
expect(text(view({ files: [file('a.ogg')] }))).toContain('Send 1 file Cancel');
});
it('sending: progress replaces Send and Cancel, and the title is locked', () => {
const html = view({
files: [file('a'), file('b'), file('c')],
phase: { kind: 'sending', done: 2 },
});
expect(text(html)).toContain('Sending 2 of 3…');
expect(text(html)).toContain('Stop');
expect(text(html)).not.toContain('Send 3 files');
expect(text(html)).not.toContain('Cancel');
expect(html).toMatch(
/aria-label="Album title"[^>]*disabled|disabled[^>]*aria-label="Album title"/
);
});
it('the encrypted note shows above the kept pick', () => {
const html = view({
files: [file('a.ogg')],
phase: { kind: 'done', text: 'Not shared: this room is encrypted.' },
});
expect(text(html)).toBe('Not shared: this room is encrypted. a.ogg Send 1 file Cancel');
});
it('after a full success the idle row and the note show together', () => {
expect(text(view({ phase: { kind: 'done', text: 'Shared 2 files.' } }))).toBe(
'Share files › Shared 2 files.'
);
});
});
describe('adding to an existing album', () => {
it('the idle row says Add files', () => {
expect(text(view({}, true))).toBe('Add files ›');
});
it('picked: no title field, the names, Send and Cancel', () => {
const html = view({ files: [file('a.ogg')] }, true);
expect(html).not.toContain('aria-label="Album title"');
expect(text(html)).toBe('a.ogg Send 1 file Cancel');
});
});
describe('the flag', () => {
it('off, missing or empty offers no share', () => {
expect(shareEnabled({}, false)).toBe(false);
expect(shareEnabled({ fileZoneShare: {} }, false)).toBe(false);
expect(shareEnabled({ fileZoneShare: { enabled: false } }, false)).toBe(false);
});
it('on offers it, except in an encrypted room', () => {
expect(shareEnabled({ fileZoneShare: { enabled: true } }, false)).toBe(true);
expect(shareEnabled({ fileZoneShare: { enabled: true } }, true)).toBe(false);
});
it('the hook reads the client config and the room, as AlbumView mounts it', () => {
const room = (encrypted: boolean) => ({ hasEncryptionStateEvent: () => encrypted } as never);
function Probe({ encrypted }: { encrypted: boolean }) {
return <span>{String(useShareEnabled(room(encrypted)))}</span>;
}
const probe = (config: ClientConfig, encrypted: boolean) =>
text(
renderToStaticMarkup(
<ClientConfigProvider value={config}>
<Probe encrypted={encrypted} />
</ClientConfigProvider>
)
);
expect(probe({}, false)).toBe('false');
expect(probe({ fileZoneShare: { enabled: true } }, false)).toBe('true');
expect(probe({ fileZoneShare: { enabled: true } }, true)).toBe('false');
});
});

View file

@ -0,0 +1,210 @@
import React, { useRef, useState, useSyncExternalStore } from 'react';
import { Text } from 'folds';
import { useQueryClient } from '@tanstack/react-query';
import { EventStatus, Room } from 'matrix-js-sdk';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { useClientConfig } from '../../hooks/useClientConfig';
import { useMediaConfig } from '../../hooks/useMediaConfig';
import { uploadContent } from '../../utils/matrix';
import { safeFile } from '../../utils/mimeTypes';
import { getMsgContent } from '../room/msgContent';
import { FILE_HASH_KEY, hashForSend } from './fileReceipt';
import { ShareController, ShareState, createShareController } from './shareController';
import { titleIn } from './albumFolders';
import { DEFAULT_TITLE, ExistingAlbum, freshest, sendShareSet, ThreadEvent } from './shareSet';
import * as css from './AlbumView.css';
/** Off unless `fileZoneShare.enabled` is true. An encrypted zone is never offered the share. */
export const shareEnabled = (
config: { fileZoneShare?: { enabled?: boolean } },
encrypted: boolean
) => !!config.fileZoneShare?.enabled && !encrypted;
export const useShareEnabled = (room: Room): boolean =>
shareEnabled(useClientConfig(), room.hasEncryptionStateEvent());
type ShareViewProps = {
state: ShareState<File>;
onPickClick: () => void;
onPicked: (files: File[]) => void;
onTitle: (title: string) => void;
onSend: () => void;
onCancel: () => void;
onStop: () => void;
/** Adding to an existing album: the files join it, so there is no title to ask for. */
adding?: boolean;
inputRef?: React.Ref<HTMLInputElement>;
};
/**
* One row when idle. Picking files (any number, one picker) opens the panel: a title, the picked
* names, Send. Nothing but the row is visible until files are picked.
*/
export function ShareSetView({
state,
onPickClick,
onPicked,
onTitle,
onSend,
onCancel,
onStop,
adding,
inputRef,
}: ShareViewProps) {
const { files, title, phase, epoch } = state;
return (
<div className={css.SharePanel}>
<input
key={epoch}
ref={inputRef}
type="file"
multiple
hidden
onChange={(e) => onPicked(Array.from(e.target.files ?? []))}
/>
{files.length === 0 && phase.kind !== 'sending' && (
<button type="button" className={css.Row} onClick={onPickClick}>
<Text size="B400">{adding ? 'Add files ›' : 'Share files ›'}</Text>
</button>
)}
{phase.kind === 'done' && (
<Text size="T200" className={css.ShareNames}>
{phase.text}
</Text>
)}
{files.length > 0 && (
<>
{!adding && (
<input
className={css.ShareTitle}
value={title}
placeholder={DEFAULT_TITLE}
aria-label="Album title"
disabled={phase.kind === 'sending'}
onChange={(e) => onTitle(e.target.value)}
/>
)}
<Text size="T200" className={`${css.Dim} ${css.ShareNames}`}>
{files.map((f) => f.name).join(' · ')}
</Text>
{phase.kind === 'sending' ? (
<>
<Text size="T300">
Sending {phase.done} of {files.length}…
</Text>
<button type="button" className={css.Row} onClick={onStop}>
<Text size="B400">Stop</Text>
</button>
</>
) : (
<>
<button type="button" className={css.Row} onClick={onSend}>
<Text size="B400">
Send {files.length} {files.length === 1 ? 'file' : 'files'}
</Text>
</button>
<button type="button" className={css.Row} onClick={onCancel}>
<Text size="B400">Cancel</Text>
</button>
</>
)}
</>
)}
</div>
);
}
/** The sent events in the room's live timeline, as the thread view of them `freshest` reads. */
const threadEvents = (room: Room): ThreadEvent[] =>
room
.getLiveTimeline()
.getEvents()
.filter((e) => (!e.status || e.status === EventStatus.SENT) && !!e.getId())
.map((e) => ({ id: e.getId() as string, ts: e.getTs(), threadRoot: e.threadRootId }));
type ShareSetProps = {
room: Room;
/** The path a new album lands in: its title is prefixed by it (docs/commons-files-desk.md). */
folder?: string[];
/** Add the files to this album instead of making one. */
into?: ExistingAlbum;
};
export function ShareSet({ room, folder = [], into }: ShareSetProps) {
const mx = useMatrixClient();
const queryClient = useQueryClient();
const mediaConfig = useMediaConfig();
const input = useRef<HTMLInputElement>(null);
// Built once per mount (AlbumView keys the panel by room): the pick lives in the controller, so a
// rerender with a new client or Room object must not build another. Live values go through `live`.
const live = useRef({ mx, room, queryClient, folder, into, mediaConfig });
live.current = { mx, room, queryClient, folder, into, mediaConfig };
const [controller]: [ShareController<File>, unknown] = useState(() =>
createShareController<File>({
roomId: room.roomId,
isEncrypted: () => live.current.room.hasEncryptionStateEvent(),
maxBytes: () => {
const cap = live.current.mediaConfig['m.upload.size'];
return typeof cap === 'number' && Number.isFinite(cap) && cap > 0 ? cap : undefined;
},
onSent: () =>
live.current.queryClient.invalidateQueries({ queryKey: ['albums', room.roomId] }),
run: (files, title, onFile, signal) =>
sendShareSet(
{
signal,
send: async (content) =>
(await live.current.mx.sendMessage(room.roomId, content as any)).event_id,
contentOf: async (f) => {
const file = safeFile(f.file);
const mxc = await new Promise<string>((resolve, reject) => {
const { mx: client } = live.current;
let upload: Promise<unknown> | undefined;
const abort = () => upload && client.cancelUpload(upload as never);
signal.addEventListener('abort', abort, { once: true });
uploadContent(client, file, {
onPromise: (p) => {
upload = p;
if (signal.aborted) abort();
},
onSuccess: resolve,
onError: reject,
});
});
const content = await getMsgContent(
live.current.mx,
{
file,
originalFile: f.file,
metadata: { markedAsSpoiler: false },
encInfo: undefined,
},
mxc
);
const sha256 = await hashForSend(f.file);
if (sha256) content.info = { ...content.info, [FILE_HASH_KEY]: sha256 };
return content;
},
onFile,
},
live.current.into
? freshest(live.current.into, threadEvents(live.current.room))
: titleIn(live.current.folder, title, DEFAULT_TITLE),
files.map((file) => ({ name: file.name, mimeType: file.type, file }))
),
})
);
const state = useSyncExternalStore(controller.subscribe, controller.getState);
return (
<ShareSetView
state={state}
inputRef={input}
onPickClick={() => input.current?.click()}
onPicked={controller.pick}
onTitle={controller.setTitle}
onSend={controller.send}
onCancel={controller.cancel}
onStop={controller.stop}
adding={!!into}
/>
);
}

View file

@ -0,0 +1,133 @@
import { describe, expect, it } from 'vitest';
import { buildAlbums } from './buildAlbums';
import type { Album, ZoneEvent } from './buildAlbums';
import { folderOf, listFolder, splitPath, titleIn } from './albumFolders';
import { DEFAULT_TITLE, sendShareSet } from './shareSet';
const album = (id: string, title: string, ts = 1): Album => ({
id,
title,
author: '@a:x',
ts,
files: [],
count: 0,
});
const names = (l: ReturnType<typeof listFolder>) => ({
folders: l.folders.map((f) => `${f.name}:${f.albums}`),
albums: l.albums.map((a) => `${a.album.id}=${a.leaf}`),
});
describe('splitPath', () => {
it('drops empty segments and padding; dots are names, not navigation', () => {
expect(splitPath(' a // b /')).toEqual(['a', 'b']);
expect(splitPath('../x')).toEqual(['..', 'x']);
expect(splitPath('///')).toEqual([]);
});
});
describe('listFolder', () => {
const all = [
album('$1', 'handoff/2026-11/notes', 10),
album('$2', 'handoff/2026-11/plan', 30),
album('$3', 'handoff/readme', 20),
album('$4', 'cast-art', 5),
album('$5', 'Plain album', 40),
];
it('root: first segments become folders (counted below, newest first); single-segment titles are albums', () => {
expect(names(listFolder(all, []))).toEqual({
folders: ['handoff:3'],
albums: ['$5=Plain album', '$4=cast-art'],
});
});
it('nested: a folder shows its sub-folders and its own albums under their leaf names', () => {
expect(names(listFolder(all, ['handoff']))).toEqual({
folders: ['2026-11:2'],
albums: ['$3=readme'],
});
expect(names(listFolder(all, ['handoff', '2026-11']))).toEqual({
folders: [],
albums: ['$2=plan', '$1=notes'],
});
});
it('an album titled exactly like a folder is not hidden by it', () => {
const l = listFolder([album('$a', 'x'), album('$b', 'x/y')], []);
expect(names(l)).toEqual({ folders: ['x:1'], albums: ['$a=x'] });
expect(names(listFolder([album('$a', 'x'), album('$b', 'x/y')], ['x']))).toEqual({
folders: [],
albums: ['$b=y'],
});
});
it('a path that exists nowhere lists nothing; the prefix match is by whole segment', () => {
expect(names(listFolder(all, ['hand']))).toEqual({ folders: [], albums: [] });
});
it('an untitled or all-slash album stays at the root, nowhere else', () => {
const odd = [album('$u', '///')];
expect(names(listFolder(odd, []))).toEqual({ folders: [], albums: ['$u=///'] });
expect(names(listFolder(odd, ['x']))).toEqual({ folders: [], albums: [] });
expect(names(listFolder([album('$w', ' ')], []))).toEqual({
folders: [],
albums: ['$w=Untitled album'],
});
});
it('server-supplied names like "constructor" are folders, not prototype hits', () => {
expect(names(listFolder([album('$c', 'constructor/a')], []))).toEqual({
folders: ['constructor:1'],
albums: [],
});
});
});
describe('titleIn and folderOf', () => {
it('prefixes the folder, keeps a typed sub-path, falls back to the default title', () => {
expect(titleIn([], '', DEFAULT_TITLE)).toBe(DEFAULT_TITLE);
expect(titleIn([], ' Mine ', DEFAULT_TITLE)).toBe('Mine');
expect(titleIn(['uploads', 'me'], '', DEFAULT_TITLE)).toBe(`uploads/me/${DEFAULT_TITLE}`);
expect(titleIn(['uploads'], 'a/b', DEFAULT_TITLE)).toBe('uploads/a/b');
});
it('folderOf is the title path without its leaf', () => {
expect(folderOf(album('$', 'a/b/c'))).toEqual(['a', 'b']);
expect(folderOf(album('$', 'c'))).toEqual([]);
});
});
describe('a share into a folder, read back as the viewer reads it', () => {
it('posts a root titled under the folder, and buildAlbums + listFolder put it in that folder', async () => {
const sent: Record<string, unknown>[] = [];
const res = await sendShareSet(
{
send: async (c) => {
sent.push(c);
return `$e${sent.length}`;
},
contentOf: async (f) => ({ msgtype: 'm.file', body: f.name, filename: f.name }),
},
titleIn(['uploads', 'meta'], 'Photos', DEFAULT_TITLE),
[{ name: 'a.png', mimeType: 'image/png' }]
);
expect(res.sent).toBe(1);
expect(sent[0]).toEqual({ msgtype: 'm.text', body: 'uploads/meta/Photos' });
const asEvent = (c: Record<string, unknown>, id: string): ZoneEvent => ({
event_id: id,
type: 'm.room.message',
sender: '@a:x',
origin_server_ts: 1,
content: c,
});
const albums = buildAlbums([
{ root: asEvent(sent[0], '$e1'), replies: [asEvent(sent[1], '$e2')] },
]);
expect(names(listFolder(albums, []))).toEqual({ folders: ['uploads:1'], albums: [] });
expect(names(listFolder(albums, ['uploads', 'meta']))).toEqual({
folders: [],
albums: ['$e1=Photos'],
});
});
});

View file

@ -0,0 +1,73 @@
// Pure: folders are albums whose title is a `/`-separated path (docs/commons-files-desk.md, "Folders").
// No wire change: the album is still one thread root; the folder tree is only how the list is grouped.
import { Album, UNTITLED } from './buildAlbums';
/** A path as segments. Empty segments and surrounding space drop out; `.` and `..` are ordinary names, never navigation. */
export const splitPath = (title: string): string[] =>
title
.split('/')
.map((s) => s.trim())
.filter(Boolean);
export type FolderEntry = {
name: string;
/** Segments from the root to this folder. */
path: string[];
/** Albums at any depth below. */
albums: number;
/** The newest album ts below, for ordering. */
ts: number;
};
export type AlbumEntry = { album: Album; leaf: string };
export type FolderListing = { folders: FolderEntry[]; albums: AlbumEntry[] };
const startsWith = (path: string[], prefix: string[]) => prefix.every((seg, i) => path[i] === seg);
/**
* What one folder shows: its direct sub-folders and the albums titled exactly at its path plus a leaf.
* An album titled `x` and a folder `x/` coexist at the same level; neither hides the other. Newest first, both lists.
*/
export const listFolder = (albums: readonly Album[], at: string[]): FolderListing => {
const folders = new Map<string, FolderEntry>();
const direct: AlbumEntry[] = [];
albums.forEach((album) => {
const segs = splitPath(album.title);
if (segs.length === 0) {
// An untitled or all-slash title lives at the root under the title as written.
if (at.length === 0) direct.push({ album, leaf: album.title.trim() || UNTITLED });
return;
}
if (!startsWith(segs, at)) return;
// An album titled exactly at this path sits in the parent, not inside the folder it shares a name with.
if (segs.length <= at.length) return;
if (segs.length === at.length + 1) {
direct.push({ album, leaf: segs[segs.length - 1] });
return;
}
const name = segs[at.length];
const f = folders.get(name) ?? { name, path: [...at, name], albums: 0, ts: 0 };
f.albums += 1;
f.ts = Math.max(f.ts, album.ts);
folders.set(name, f);
});
return {
folders: [...folders.values()].sort((a, b) => b.ts - a.ts),
albums: direct.sort((a, b) => b.album.ts - a.album.ts),
};
};
/** The folder an album sits in: its title path without the leaf. */
export const folderOf = (album: Album): string[] => splitPath(album.title).slice(0, -1);
/**
* The title a share sends into `folder`: the folder path then what the sender typed. The typed title
* may itself contain `/`, which just goes deeper. An empty typed title falls back to `fallback`.
*/
export const titleIn = (folder: string[], typed: string, fallback: string): string => {
const leaf = splitPath(typed).join('/') || fallback;
return [...folder, leaf].join('/');
};
export const pathLabel = (path: string[]): string => path.join(' / ');

View file

@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { AlbumInput, ZoneEvent, buildAlbums } from './buildAlbums'; import { AlbumInput, ZoneEvent, buildAlbums, lastEvent } from './buildAlbums';
const root = (id: string, ts: number, over: Partial<ZoneEvent> = {}): ZoneEvent => ({ const root = (id: string, ts: number, over: Partial<ZoneEvent> = {}): ZoneEvent => ({
event_id: id, event_id: id,
@ -215,6 +215,42 @@ describe('buildAlbums', () => {
}); });
}); });
describe('versions', () => {
const v = (id: string, ts: number, replaces?: string) =>
reply(id, ts, 'm.file', id, replaces ? { 'org.gamecult.publish': { replaces } } : {});
it('lists the latest of a chain and folds the earlier versions under it', () => {
const a = one(root('$r', 1), [v('$v1', 10), v('$v2', 20, '$v1'), reply('$x', 30, 'm.file')]);
expect(a.files.map((f) => [f.id, f.earlier.map((e) => e.id)])).toEqual([
['$v2', ['$v1']],
['$x', []],
]);
expect(a.count).toBe(2);
});
});
describe('versions: cover and sender', () => {
it('the cover comes from the shown version, not a folded image', () => {
const img = (id: string, ts: number, type: string, replaces?: string) =>
reply(id, ts, type, id, replaces ? { 'org.gamecult.publish': { replaces } } : {});
const a = one(root('$r', 1), [img('$v1', 10, 'm.image'), img('$v2', 20, 'm.file', '$v1')]);
expect(a.files.map((f) => f.id)).toEqual(['$v2']);
expect(a.cover).toBeUndefined();
});
});
describe('lastEvent', () => {
it('is the newest event of the thread, a folded version included; the root when empty', () => {
const v = (id: string, ts: number, replaces?: string) =>
reply(id, ts, 'm.file', id, replaces ? { 'org.gamecult.publish': { replaces } } : {});
expect(lastEvent(one(root('$r', 1), [v('$a', 10), v('$b', 20, '$a'), v('$c', 15)]))).toEqual({
id: '$b',
ts: 20,
});
expect(lastEvent(one(root('$r', 1), []))).toEqual({ id: '$r', ts: 1 });
});
});
describe('Mind receipts', () => { describe('Mind receipts', () => {
const HASH = 'a'.repeat(64); const HASH = 'a'.repeat(64);
const file = (id: string, sha?: string) => const file = (id: string, sha?: string) =>

View file

@ -3,6 +3,7 @@
// into albums. See docs/file-zone.md for the rulings this encodes. // into albums. See docs/file-zone.md for the rulings this encodes.
import { readersOf } from './fileReceipt'; import { readersOf } from './fileReceipt';
import type { FileReader } from './fileReceipt'; import type { FileReader } from './fileReceipt';
import { foldVersions } from './versions';
/** The slice of a Matrix event this module reads. Every field may be missing. */ /** The slice of a Matrix event this module reads. Every field may be missing. */
export type ZoneEvent = { export type ZoneEvent = {
@ -22,11 +23,14 @@ export type AlbumFile = {
id: string; id: string;
kind: FileKind; kind: FileKind;
name: string; name: string;
sender: string;
ts: number; ts: number;
/** The event content, as RenderMessageContent reads it. */ /** The event content, as RenderMessageContent reads it. */
content: Record<string, unknown>; content: Record<string, unknown>;
/** Receipts in this album that name this file, one per sender (the latest), oldest first. */ /** Receipts in this album that name this file, one per sender (the latest), oldest first. */
readBy: FileReader[]; readBy: FileReader[];
/** The versions this file supersedes, nearest first (`org.gamecult.publish.replaces`). */
earlier: AlbumFile[];
}; };
export type Album = { export type Album = {
@ -64,7 +68,7 @@ const tsOf = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v
const asString = (v: unknown): string => (typeof v === 'string' ? v : ''); const asString = (v: unknown): string => (typeof v === 'string' ? v : '');
const toFile = (e: ZoneEvent): AlbumFile | undefined => { export const toFile = (e: ZoneEvent): AlbumFile | undefined => {
if (!live(e)) return undefined; if (!live(e)) return undefined;
const kind = KIND_OF_MSGTYPE.get(e.content.msgtype as string); const kind = KIND_OF_MSGTYPE.get(e.content.msgtype as string);
if (!kind) return undefined; if (!kind) return undefined;
@ -72,9 +76,11 @@ const toFile = (e: ZoneEvent): AlbumFile | undefined => {
id: e.event_id, id: e.event_id,
kind, kind,
name: asString(e.content.filename) || asString(e.content.body), name: asString(e.content.filename) || asString(e.content.body),
sender: e.sender ?? '',
ts: tsOf(e.origin_server_ts), ts: tsOf(e.origin_server_ts),
content: e.content, content: e.content,
readBy: [], readBy: [],
earlier: [],
}; };
}; };
@ -103,14 +109,15 @@ const toAlbum = (input: AlbumInput, server: string): Album | undefined => {
}) })
.sort((a, b) => a.ts - b.ts) .sort((a, b) => a.ts - b.ts)
.map((f) => ({ ...f, readBy: readersOf(list, f.id, f.content, server) })); .map((f) => ({ ...f, readBy: readersOf(list, f.id, f.content, server) }));
const heads = foldVersions(files);
return { return {
id: root.event_id, id: root.event_id,
title: titleOf(root), title: titleOf(root),
author: root.sender ?? '', author: root.sender ?? '',
ts: tsOf(root.origin_server_ts), ts: tsOf(root.origin_server_ts),
cover: files.find((f) => f.kind === 'image'), cover: heads.find((f) => f.kind === 'image'),
files, files: heads,
count: files.length, count: heads.length,
}; };
}; };
@ -127,3 +134,51 @@ export const buildAlbums = (inputs: AlbumInput[], server = ''): Album[] => {
}) })
.sort((a, b) => b.ts - a.ts); .sort((a, b) => b.ts - a.ts);
}; };
/** The newest event in an album's thread (shown or folded), else its root: where a new file threads after. */
export const lastEvent = (album: Album): { id: string; ts: number } =>
album.files
.flatMap((f) => [f, ...f.earlier])
.reduce<{ id: string; ts: number }>((a, f) => (f.ts >= a.ts ? { id: f.id, ts: f.ts } : a), {
id: album.id,
ts: album.ts,
});
/** A room event with the thread root the SDK resolved for it, when it has one. */
export type TimelineEvent = ZoneEvent & { threadRoot?: string };
/**
* File events that sit in the room outside any album thread: what a poster that does not thread
* its files leaves behind. The album list never reads them (it lists threads), so they are named
* to the sender instead of left out silently.
*/
export const looseFiles = (events: TimelineEvent[]): AlbumFile[] =>
events
.filter((e) => {
const rel = e?.content?.['m.relates_to'] as { rel_type?: unknown } | undefined;
return !e?.threadRoot && rel?.rel_type !== 'm.thread';
})
.map(toFile)
.filter((f): f is AlbumFile => !!f);
const NAMED = 3;
/** The line that says loose files exist and are not listed; empty when there are none. */
export const looseNote = (files: AlbumFile[]): string => {
if (files.length === 0) return '';
const names = files.slice(0, NAMED).map((f) => f.name || 'unnamed');
const more = files.length > NAMED ? ` and ${files.length - NAMED} more` : '';
const what = files.length === 1 ? '1 file was' : `${files.length} files were`;
return `${what} posted outside an album and ${
files.length === 1 ? 'is' : 'are'
} not listed here: ${names.join(', ')}${more}. ${
files.length === 1 ? 'It is' : 'They are'
} in the Timeline.`;
};
/** Where the album view stands when it decides whether to show the loose-files note. */
export type ViewState = { open: boolean; encrypted: boolean; loading: boolean; error: boolean };
/** The note for the list view only: never inside an open album, an encrypted zone, or a load that is not finished. */
export const looseNoteFor = (files: AlbumFile[], view: ViewState): string =>
view.open || view.encrypted || view.loading || view.error ? '' : looseNote(files);

View file

@ -0,0 +1,126 @@
import { describe, expect, it } from 'vitest';
import { buildAlbums, looseFiles, looseNote, looseNoteFor, TimelineEvent } from './buildAlbums';
// The Commons publisher as it posted before gamecult-ops #121: loose files (no album thread), a
// flat `org.gamecult.publish.replaces` key, no info.sha256. The sender must see that, not a
// silently empty or silently unfolded zone.
const MIND = '@eureka:gamecult.org';
const file = (
id: string,
name: string,
extra: Record<string, unknown> = {},
ts = 1
): TimelineEvent => ({
event_id: id,
type: 'm.room.message',
sender: MIND,
origin_server_ts: ts,
content: { msgtype: 'm.file', body: name, filename: name, url: `mxc://x/${id}`, ...extra },
});
const text = (id: string, body: string): TimelineEvent => ({
event_id: id,
type: 'm.room.message',
sender: MIND,
origin_server_ts: 1,
content: { msgtype: 'm.text', body },
});
describe('loose files from a poster that does not thread', () => {
it('are found, with the names the sender sees', () => {
const loose = looseFiles([file('$a', 'notes.md'), file('$b', 'plan.pdf')]);
expect(loose.map((f) => f.name)).toEqual(['notes.md', 'plan.pdf']);
});
it('are not the album roots, thread replies (by SDK root or by relation), edits or redactions', () => {
const events: TimelineEvent[] = [
text('$root', 'handoff/eureka'),
{ ...file('$r1', 'a.md'), threadRoot: '$root' },
file('$r2', 'b.md', {
'm.relates_to': { rel_type: 'm.thread', event_id: '$root' },
}),
file('$edit', 'c.md', { 'm.relates_to': { rel_type: 'm.replace', event_id: '$r1' } }),
{ ...file('$gone', 'd.md'), unsigned: { redacted_because: {} } },
file('$loose', 'e.md'),
];
expect(looseFiles(events).map((f) => f.id)).toEqual(['$loose']);
});
it('a zone holding only loose files still has no albums, and the note says why', () => {
const events = [file('$a', 'notes.md')];
expect(buildAlbums([])).toEqual([]);
expect(looseNote(looseFiles(events))).toBe(
'1 file was posted outside an album and is not listed here: notes.md. It is in the Timeline.'
);
});
it('the note names three and counts the rest', () => {
const many = looseFiles(['a', 'b', 'c', 'd', 'e'].map((n) => file(`$${n}`, `${n}.md`)));
expect(looseNote(many)).toBe(
'5 files were posted outside an album and are not listed here: a.md, b.md, c.md and 2 more. They are in the Timeline.'
);
expect(looseNote([])).toBe('');
});
});
describe('where the loose-files note shows', () => {
const loose = looseFiles([file('$a', 'notes.md')]);
const list = { open: false, encrypted: false, loading: false, error: false };
it('on the album list, and only there', () => {
expect(looseNoteFor(loose, list)).toContain('notes.md');
expect(looseNoteFor(loose, { ...list, open: true })).toBe('');
expect(looseNoteFor(loose, { ...list, encrypted: true })).toBe('');
expect(looseNoteFor(loose, { ...list, loading: true })).toBe('');
expect(looseNoteFor(loose, { ...list, error: true })).toBe('');
});
it('says nothing when there are no loose files', () => {
expect(looseNoteFor([], list)).toBe('');
});
it('names m.notice and m.sticker posts as not files', () => {
const notice = { ...text('$n', 'hi'), content: { msgtype: 'm.notice', body: 'hi' } };
expect(looseFiles([notice])).toEqual([]);
});
it('a file with no name reads as unnamed', () => {
const bare: TimelineEvent = { ...file('$b', ''), content: { msgtype: 'm.file', body: '' } };
expect(looseNote(looseFiles([bare]))).toContain('unnamed');
});
});
describe('the old wire shape inside an album', () => {
const root = text('$root', 'handoff/eureka');
const albumOf = (replies: TimelineEvent[]) => buildAlbums([{ root, replies }], 'gamecult.org')[0];
it('a flat replaces key folds nothing: both versions show, none is hidden', () => {
const album = albumOf([
file('$v1', 'plan.md', { 'org.gamecult.publish.sha256': 'aa' }, 1),
file('$v2', 'plan.md', { 'org.gamecult.publish.replaces': '$v1' }, 2),
]);
expect(album.files.map((f) => f.id)).toEqual(['$v1', '$v2']);
expect(album.files.every((f) => f.earlier.length === 0)).toBe(true);
});
it('the nested shape from the fixed publisher folds as before', () => {
const album = albumOf([
file('$v1', 'plan.md', {}, 1),
file('$v2', 'plan.md', { 'org.gamecult.publish': { replaces: '$v1' } }, 2),
]);
expect(album.files.map((f) => f.id)).toEqual(['$v2']);
expect(album.files[0].earlier.map((f) => f.id)).toEqual(['$v1']);
});
it('a file with no info.sha256 lists fine, with no readers even when a receipt names it', () => {
const receipt: TimelineEvent = {
event_id: '$rc',
type: 'org.gamecult.file_received',
sender: '@void:gamecult.org',
origin_server_ts: 5,
content: { 'org.gamecult.file_received': { event_id: '$v1', sha256: 'aa', size: 1 } },
};
const album = albumOf([file('$v1', 'plan.md'), receipt]);
expect(album.count).toBe(1);
expect(album.files[0].readBy).toEqual([]);
});
});

View file

@ -0,0 +1,55 @@
import { describe, expect, it } from 'vitest';
import { Page, readPages } from './readPages';
const pager = (pages: Page<number>[]) => {
const froms: (string | undefined)[] = [];
return {
froms,
fetchPage: async (from: string | undefined) => {
froms.push(from);
return pages[froms.length - 1] ?? {};
},
};
};
describe('readPages', () => {
it('one page without a token is the whole read', async () => {
const p = pager([{ chunk: [1, 2] }]);
expect(await readPages(p.fetchPage)).toEqual({ items: [1, 2], truncated: false });
expect(p.froms).toEqual([undefined]);
});
it('follows next_batch in order, passing each token back', async () => {
const p = pager([
{ chunk: [1], next_batch: 'a' },
{ chunk: [2], next_batch: 'b' },
{ chunk: [3] },
]);
expect(await readPages(p.fetchPage)).toEqual({ items: [1, 2, 3], truncated: false });
expect(p.froms).toEqual([undefined, 'a', 'b']);
});
it('a missing chunk reads as empty', async () => {
expect(await readPages(async () => ({}))).toEqual({ items: [], truncated: false });
});
it('an empty page ends the read even when it carries a token', async () => {
const p = pager([
{ chunk: [1], next_batch: 'a' },
{ chunk: [], next_batch: 'b' },
]);
expect(await readPages(p.fetchPage)).toEqual({ items: [1], truncated: false });
expect(p.froms).toHaveLength(2);
});
it('the cap stops the read and says it was cut short', async () => {
const p = pager(Array.from({ length: 10 }, (_, i) => ({ chunk: [i], next_batch: `t${i}` })));
expect(await readPages(p.fetchPage, 3)).toEqual({ items: [0, 1, 2], truncated: true });
expect(p.froms).toHaveLength(3);
});
it('a last page exactly at the cap is not truncated', async () => {
const p = pager([{ chunk: [1], next_batch: 'a' }, { chunk: [2] }]);
expect((await readPages(p.fetchPage, 2)).truncated).toBe(false);
});
});

View file

@ -0,0 +1,27 @@
/** One page of a Matrix paginated endpoint: its events and the token for the next page, if any. */
export type Page<T> = { chunk?: T[]; next_batch?: string };
/** Pages read per endpoint at most, so a runaway zone cannot hold the phone in a loop. */
export const MAX_PAGES = 20;
/**
* Reads every page of an endpoint by following `next_batch`, up to `maxPages`. `truncated` is true
* when the cap stopped the read with more still to come, so a caller can say the list is partial.
*/
export const readPages = async <T>(
fetchPage: (from: string | undefined) => Promise<Page<T>>,
maxPages = MAX_PAGES
): Promise<{ items: T[]; truncated: boolean }> => {
const items: T[] = [];
let from: string | undefined;
for (let n = 0; n < maxPages; n += 1) {
// eslint-disable-next-line no-await-in-loop
const page = await fetchPage(from);
items.push(...(page.chunk ?? []));
// An empty page ends the read even if a token is returned: a server that keeps handing out
// tokens with nothing behind them would otherwise spend every page of the cap.
if (!page.next_batch || !page.chunk?.length) return { items, truncated: false };
from = page.next_batch;
}
return { items, truncated: true };
};

View file

@ -0,0 +1,380 @@
import { describe, expect, it } from 'vitest';
import { Picked, ShareDeps, createShareController } from './shareController';
import { ShareResult } from './shareSet';
const file = (name: string, size?: number): Picked => ({ name, type: 'audio/ogg', size });
const MB = 1024 * 1024;
const ok = (n: number): ShareResult => ({ albumId: '$r', sent: n, failed: [], failedAt: [] });
/** A run the test settles by hand, so "in flight" is a state the test can stand in. */
const hand = () => {
const calls: { files: Picked[]; title: string; onFile: () => void; signal: AbortSignal }[] = [];
let release: (r: ShareResult) => void = () => undefined;
let fail: (e: Error) => void = () => undefined;
const run: ShareDeps<Picked>['run'] = (files, title, onFile, signal) => {
calls.push({ files, title, onFile, signal });
return new Promise<ShareResult>((resolve, reject) => {
release = resolve;
fail = reject;
});
};
return { calls, run, release: (r: ShareResult) => release(r), fail: (e: Error) => fail(e) };
};
const make = (over: Partial<ShareDeps<Picked>> = {}, roomId = '!zone:x') => {
const h = hand();
const sentTo: string[] = [];
const c = createShareController<Picked>({
roomId,
isEncrypted: () => false,
run: h.run,
onSent: () => sentTo.push(roomId),
...over,
});
return { c, h, sentTo };
};
describe('picking', () => {
it('starts idle with nothing picked, and a pick holds the files in order', () => {
const { c } = make();
expect(c.getState().files).toEqual([]);
expect(c.getState().phase).toEqual({ kind: 'idle' });
c.pick([file('a'), file('b')]);
expect(c.getState().files.map((f) => f.name)).toEqual(['a', 'b']);
});
it('Cancel empties the pick and the title and bumps the input epoch', () => {
const { c } = make();
c.pick([file('a')]);
c.setTitle('Take 4');
const before = c.getState().epoch;
c.cancel();
expect(c.getState()).toMatchObject({ files: [], title: '', epoch: before + 1 });
});
it('subscribers hear every change and stop hearing after unsubscribe', () => {
const { c } = make();
let heard = 0;
const off = c.subscribe(() => {
heard += 1;
});
c.pick([file('a')]);
off();
c.pick([]);
expect(heard).toBe(1);
});
});
describe('the Send guard', () => {
it('a double tap starts one send', async () => {
const { c, h } = make();
c.pick([file('a'), file('b')]);
const first = c.send();
const second = c.send();
expect(h.calls).toHaveLength(1);
h.release(ok(2));
await Promise.all([first, second]);
expect(h.calls).toHaveLength(1);
});
it('a re-mounted panel for the same room cannot start a second send while one is in flight', async () => {
const { c, h } = make();
c.pick([file('a')]);
const first = c.send();
// The page was left and returned to: a new controller, nothing picked in it but a new pick.
const again = make({}, '!zone:x');
again.c.pick([file('b')]);
await again.c.send();
expect(again.h.calls).toHaveLength(0);
h.release(ok(1));
await first;
// Once the first has settled the room is free again.
const next = again.c.send();
expect(again.h.calls).toHaveLength(1);
again.h.release(ok(1));
await next;
});
it('another room is not blocked by a send in flight', async () => {
const a = make({}, '!a:x');
const b = make({}, '!b:x');
a.c.pick([file('a')]);
b.c.pick([file('b')]);
const sendA = a.c.send();
const sendB = b.c.send();
expect(b.h.calls).toHaveLength(1);
a.h.release(ok(1));
b.h.release(ok(1));
await Promise.all([sendA, sendB]);
});
it('sends nothing when nothing is picked', async () => {
const { c, h } = make();
await c.send();
expect(h.calls).toHaveLength(0);
});
it('a send that throws frees the room and says so', async () => {
const { c, h } = make();
c.pick([file('a')]);
const p = c.send();
h.fail(new Error('M_FORBIDDEN'));
await p;
expect(c.getState().phase).toEqual({ kind: 'done', text: 'Could not share: M_FORBIDDEN' });
expect(c.getState().files).toHaveLength(1);
const retry = c.send();
expect(h.calls).toHaveLength(2);
h.release(ok(1));
await retry;
});
});
describe('progress and results', () => {
it('counts files as they settle, passing the title through', async () => {
const { c, h } = make();
c.pick([file('a'), file('b')]);
c.setTitle('Take 4');
const p = c.send();
expect(c.getState().phase).toEqual({ kind: 'sending', done: 0 });
expect(h.calls[0].title).toBe('Take 4');
h.calls[0].onFile();
expect(c.getState().phase).toEqual({ kind: 'sending', done: 1 });
h.release(ok(2));
await p;
expect(c.getState().phase).toEqual({ kind: 'done', text: 'Shared 2 files.' });
});
it('full success clears the pick, tells the room list, and remounts the input', async () => {
const { c, h, sentTo } = make();
c.pick([file('a')]);
const { epoch } = c.getState();
const p = c.send();
h.release(ok(1));
await p;
expect(c.getState()).toMatchObject({ files: [], title: '', epoch: epoch + 1 });
expect(sentTo).toEqual(['!zone:x']);
});
it('failed files stay picked by position, so a same-named twin that went is not re-sent', async () => {
const { c, h } = make();
const twins = [file('a.ogg'), file('a.ogg'), file('b.ogg')];
c.pick(twins);
const p = c.send();
h.release({ albumId: '$r', sent: 2, failed: ['a.ogg'], failedAt: [1] });
await p;
expect(c.getState().files).toEqual([twins[1]]);
expect(c.getState().phase).toEqual({ kind: 'done', text: 'Shared 2. Not sent: a.ogg' });
});
it('when every upload failed everything stays picked and the note says nothing was shared', async () => {
const { c, h } = make();
const picked = [file('a'), file('b')];
c.pick(picked);
const p = c.send();
h.release({ albumId: '$r', sent: 0, failed: ['a', 'b'], failedAt: [0, 1] });
await p;
expect(c.getState().files).toEqual(picked);
expect(c.getState().phase).toEqual({
kind: 'done',
text: 'Nothing was shared. Not sent: a, b',
});
});
it('a new pick after a result drops the result note', async () => {
const { c, h } = make();
c.pick([file('a')]);
const p = c.send();
h.release(ok(1));
await p;
c.pick([file('b')]);
expect(c.getState().phase).toEqual({ kind: 'idle' });
});
});
describe('what a send leaves behind', () => {
it('keeps the title when some files failed, so the retry has the same name', async () => {
const { c, h } = make();
c.pick([file('a'), file('b')]);
c.setTitle('Take 4');
const p = c.send();
h.release({ albumId: '$r', sent: 1, failed: ['b'], failedAt: [1] });
await p;
expect(c.getState().title).toBe('Take 4');
});
it('tells the room list only after the send settled, and not when it threw', async () => {
const { c, h, sentTo } = make();
c.pick([file('a')]);
const p = c.send();
expect(sentTo).toEqual([]);
h.release(ok(1));
await p;
expect(sentTo).toEqual(['!zone:x']);
const bad = make();
bad.c.pick([file('a')]);
const q = bad.c.send();
bad.h.fail(new Error('boom'));
await q;
expect(bad.sentTo).toEqual([]);
});
it('a success lands in one notification: the pick is never empty while still sending', async () => {
const { c, h } = make();
c.pick([file('a')]);
const p = c.send();
const seen: string[] = [];
c.subscribe(() => {
const st = c.getState();
seen.push(`${st.files.length}:${st.phase.kind}`);
});
h.release(ok(1));
await p;
expect(seen).toEqual(['0:done']);
});
});
describe('an encrypted room', () => {
it('says so, sends nothing and keeps the pick', async () => {
const { c, h } = make({ isEncrypted: () => true });
c.pick([file('a')]);
await c.send();
expect(c.getState().phase).toEqual({
kind: 'done',
text: 'Not shared: this room is encrypted.',
});
expect(c.getState().files).toHaveLength(1);
expect(h.calls).toHaveLength(0);
});
it('is checked at Send, not at mount: a room that turns encrypted after the pick is refused', async () => {
let encrypted = false;
const { c, h } = make({ isEncrypted: () => encrypted });
c.pick([file('a')]);
encrypted = true;
await c.send();
expect(h.calls).toHaveLength(0);
expect(c.getState().phase).toMatchObject({
kind: 'done',
text: 'Not shared: this room is encrypted.',
});
});
});
describe('Stop', () => {
it('aborts the signal of the send in flight, and only that send', async () => {
const { c, h } = make();
c.pick([file('a'), file('b')]);
c.stop(); // nothing running: nothing to abort
const sending = c.send();
expect(h.calls[0].signal.aborted).toBe(false);
c.stop();
expect(h.calls[0].signal.aborted).toBe(true);
h.release({ albumId: '$r', sent: 0, failed: ['a', 'b'], failedAt: [0, 1] });
await sending;
expect(c.getState().files.map((f) => f.name)).toEqual(['a', 'b']);
// the next send gets a fresh signal
const again = c.send();
expect(h.calls[1].signal.aborted).toBe(false);
h.release(ok(2));
await again;
});
});
describe('files over the homeserver cap', () => {
const cap = 50 * MB;
const capped = () => make({ maxBytes: () => cap });
it('are named in the note and never sent; the rest go', async () => {
const { c, h } = capped();
c.pick([file('small.ogg', 3 * MB), file('film.mp4', 80 * MB), file('also.ogg', 1)]);
const sent = c.send();
expect(h.calls[0].files.map((f) => f.name)).toEqual(['small.ogg', 'also.ogg']);
expect(c.getState().files.map((f) => f.name)).toEqual(['small.ogg', 'also.ogg']);
h.release(ok(2));
await sent;
expect(c.getState().phase).toEqual({
kind: 'done',
text: 'Shared 2 files. Too large for this server (limit 50 MB): film.mp4',
});
expect(c.getState().files).toEqual([]);
});
it('are not kept for a retry that cannot help them, while a failed small file is', async () => {
const { c, h } = capped();
c.pick([file('a.ogg', 1), file('big.wav', 60 * MB)]);
const sent = c.send();
h.release({ albumId: '$r', sent: 0, failed: ['a.ogg'], failedAt: [0] });
await sent;
expect(c.getState().files.map((f) => f.name)).toEqual(['a.ogg']);
});
it('a pick that is all over the cap sends nothing: no run, so no album root, and the pick clears', async () => {
const { c, h, sentTo } = capped();
c.pick([file('a.mp4', 51 * MB), file('b.mp4', 99 * MB)]);
const { epoch } = c.getState();
await c.send();
expect(h.calls).toHaveLength(0);
expect(sentTo).toEqual([]);
expect(c.getState()).toMatchObject({ files: [], epoch: epoch + 1 });
expect(c.getState().phase).toEqual({
kind: 'done',
text: 'Nothing was shared. Too large for this server (limit 50 MB): a.mp4, b.mp4',
});
});
it('a file of exactly the cap goes: the server refuses only what is larger', async () => {
const { c, h } = capped();
c.pick([file('edge.bin', cap)]);
const sent = c.send();
expect(h.calls[0].files).toHaveLength(1);
h.release(ok(1));
await sent;
});
it('the room is not held busy by an all-refused pick, so the next pick sends', async () => {
const { c, h } = capped();
c.pick([file('a.mp4', 99 * MB)]);
await c.send();
c.pick([file('b.ogg', 1)]);
const sent = c.send();
expect(h.calls).toHaveLength(1);
h.release(ok(1));
await sent;
});
it('a server that states no cap, or a file with no size, refuses nothing', async () => {
const none = make();
none.c.pick([file('a', 10 ** 12)]);
const s1 = none.c.send();
expect(none.h.calls[0].files).toHaveLength(1);
none.h.release(ok(1));
await s1;
const unsized = make({ maxBytes: () => cap }, '!other:x');
unsized.c.pick([file('b')]);
const s2 = unsized.c.send();
expect(unsized.h.calls[0].files).toHaveLength(1);
unsized.h.release(ok(1));
await s2;
});
it('a fractional cap reads with one decimal', async () => {
const { c } = make({ maxBytes: () => 1.5 * MB });
c.pick([file('a', 2 * MB)]);
await c.send();
expect(c.getState().phase).toMatchObject({ text: expect.stringContaining('limit 1.5 MB') });
});
it('a run that throws still names the refused files, which are not kept', async () => {
const { c, h } = capped();
c.pick([file('a.ogg', 1), file('big.wav', 60 * MB)]);
const sent = c.send();
h.fail(new Error('network down'));
await sent;
expect(c.getState().phase).toEqual({
kind: 'done',
text: 'Could not share: network down. Too large for this server (limit 50 MB): big.wav',
});
expect(c.getState().files.map((f) => f.name)).toEqual(['a.ogg']);
});
});

View file

@ -0,0 +1,135 @@
// The share panel's state machine, apart from React and Matrix: what is picked, what phase the
// send is in, and the rules that keep a room to one send at a time. ShareSet.tsx draws it.
import { ShareResult, remainingAfter, resultNote } from './shareSet';
export type Picked = { name: string; type: string; size?: number };
export type SharePhase =
| { kind: 'idle' }
| { kind: 'sending'; done: number }
| { kind: 'done'; text: string };
export type ShareState<F extends Picked> = {
files: F[];
title: string;
phase: SharePhase;
/** Bumps whenever the pick is emptied, so the file input can be remounted and re-pick the same files. */
epoch: number;
};
export const ENCRYPTED_NOTE = 'Not shared: this room is encrypted.';
const MIB = 1024 * 1024;
/**
* Files the homeserver would refuse for size (its `m.upload.size`, which Synapse enforces as a
* limit, so a file of exactly that size goes), split from the rest before anything is sent. A
* missing cap or size refuses nothing.
*/
export const splitBySize = <F extends Picked>(files: F[], cap: number | undefined) => {
const over = (f: F) => cap !== undefined && f.size !== undefined && f.size > cap;
return { sendable: files.filter((f) => !over(f)), tooLarge: files.filter(over) };
};
const tooLargeNote = (names: string[], cap: number): string =>
`Too large for this server (limit ${Math.round((cap / MIB) * 10) / 10} MB): ${names.join(', ')}`;
export type ShareDeps<F extends Picked> = {
roomId: string;
isEncrypted: () => boolean;
/** Sends the files as one album; reports each settled file through onFile. */
run: (files: F[], title: string, onFile: () => void, signal: AbortSignal) => Promise<ShareResult>;
/** The homeserver's upload cap in bytes (`m.upload.size`), when it states one. */
maxBytes?: () => number | undefined;
/** Called after a send that reached the room, whatever it left unsent. */
onSent?: () => void;
};
/** Rooms with a share in flight. Module-level: leaving the page unmounts the panel, not the send. */
const sending = new Set<string>();
export const createShareController = <F extends Picked>(deps: ShareDeps<F>) => {
let state: ShareState<F> = { files: [], title: '', phase: { kind: 'idle' }, epoch: 0 };
const listeners = new Set<() => void>();
let running: AbortController | undefined;
const set = (patch: Partial<ShareState<F>>) => {
state = { ...state, ...patch };
listeners.forEach((l) => l());
};
const clear = () => set({ files: [], title: '', epoch: state.epoch + 1 });
const send = async () => {
if (sending.has(deps.roomId) || state.files.length === 0) return;
if (deps.isEncrypted()) {
set({ phase: { kind: 'done', text: ENCRYPTED_NOTE } });
return;
}
// Files over the cap are named and dropped from the pick before any upload or album root: a
// retry cannot help them, and a root with nothing under it is a lone message nobody lists.
const cap = deps.maxBytes?.();
const { sendable, tooLarge } = splitBySize(state.files, cap);
const sizeNote = tooLarge.length
? tooLargeNote(
tooLarge.map((f) => f.name),
cap as number
)
: '';
if (sendable.length === 0) {
const phase: SharePhase = { kind: 'done', text: `Nothing was shared. ${sizeNote}` };
set({ files: [], title: '', epoch: state.epoch + 1, phase });
return;
}
sending.add(deps.roomId);
const abort = new AbortController();
running = abort;
const { title } = state;
const files = sendable;
set({ files, phase: { kind: 'sending', done: 0 } });
let settled = 0;
try {
const res = await deps.run(
files,
title,
() => {
settled += 1;
set({ phase: { kind: 'sending', done: settled } });
},
abort.signal
);
deps.onSent?.();
const left = remainingAfter(files, res);
const phase: SharePhase = {
kind: 'done',
text: sizeNote ? `${resultNote(res)} ${sizeNote}` : resultNote(res),
};
// One notification: no state is ever drawn with the pick emptied and the send still running.
if (left.length === 0) set({ files: [], title: '', epoch: state.epoch + 1, phase });
else set({ files: left, phase });
} catch (e: any) {
const failure = `Could not share: ${e?.message ?? 'send failed'}`;
set({ phase: { kind: 'done', text: sizeNote ? `${failure}. ${sizeNote}` : failure } });
} finally {
running = undefined;
sending.delete(deps.roomId);
}
};
return {
getState: () => state,
subscribe: (l: () => void) => {
listeners.add(l);
return () => {
listeners.delete(l);
};
},
pick: (files: F[]) => set({ files, phase: { kind: 'idle' } }),
setTitle: (title: string) => set({ title }),
cancel: clear,
/** Stops a send in flight: the running upload is aborted and the rest are left picked. */
stop: () => running?.abort(),
send,
};
};
export type ShareController<F extends Picked> = ReturnType<typeof createShareController<F>>;

View file

@ -0,0 +1,328 @@
import { describe, expect, it } from 'vitest';
import config from '../../../../config.json';
import { ZoneEvent, buildAlbums } from './buildAlbums';
import {
DEFAULT_TITLE,
ShareFile,
SharePort,
CANCELLED,
freshest,
refusalOf,
remainingAfter,
resultNote,
sendShareSet,
threadRelation,
} from './shareSet';
const kindOf = (f: ShareFile) => (f.mimeType.startsWith('audio') ? 'm.audio' : 'm.file');
/** A fake room: records what is sent, as the events Synapse would return from /relations. */
const room = (failOn: string[] = []) => {
const events: ZoneEvent[] = [];
const port: SharePort<ShareFile> = {
send: async (content) => {
const id = `$e${events.length + 1}`;
events.push({
event_id: id,
type: 'm.room.message',
sender: '@aqua:chat.gamecult.org',
origin_server_ts: 1000 + events.length,
content,
});
return id;
},
contentOf: async (f) => {
if (failOn.includes(f.name)) throw new Error('upload failed');
return {
msgtype: kindOf(f),
body: f.name,
filename: f.name,
url: `mxc://x/${f.name}`,
info: { mimetype: f.mimeType },
};
},
};
const album = () => {
const [root, ...replies] = events;
return buildAlbums([{ root, replies }], 'chat.gamecult.org')[0];
};
return { events, port, album };
};
const clips: ShareFile[] = [
{ name: 'a.ogg', mimeType: 'audio/ogg' },
{ name: 'b.ogg', mimeType: 'audio/ogg' },
{ name: 'c.txt', mimeType: 'text/plain' },
];
describe('sendShareSet', () => {
it('reads back as one album of the files in pick order', async () => {
const r = room();
const res = await sendShareSet(r.port, 'Take 4', clips);
expect(res).toEqual({ albumId: '$e1', sent: 3, failed: [], failedAt: [], reasons: [] });
const album = r.album();
expect(album.title).toBe('Take 4');
expect(album.files.map((f) => [f.name, f.kind])).toEqual([
['a.ogg', 'audio'],
['b.ogg', 'audio'],
['c.txt', 'file'],
]);
});
it('threads every file under the root, each falling back to the previous event', async () => {
const r = room();
await sendShareSet(r.port, 't', clips);
const rels = r.events.slice(1).map((e) => e.content?.['m.relates_to']);
expect(rels).toEqual([
threadRelation('$e1', '$e1'),
threadRelation('$e1', '$e2'),
threadRelation('$e1', '$e3'),
]);
expect(r.events[0].content?.['m.relates_to']).toBeUndefined();
});
it('titles an untitled share', async () => {
const r = room();
await sendShareSet(r.port, ' ', clips.slice(0, 1));
expect(r.album().title).toBe(DEFAULT_TITLE);
});
it('names a failed file and still sends the rest', async () => {
const r = room(['b.ogg']);
const res = await sendShareSet(r.port, 't', clips);
expect(res.failed).toEqual(['b.ogg']);
expect(res.sent).toBe(2);
expect(r.album().files.map((f) => f.name)).toEqual(['a.ogg', 'c.txt']);
// the next file falls back to the last event that exists, not to the failed one
expect(r.events[2].content?.['m.relates_to']).toEqual(threadRelation('$e1', '$e2'));
});
it('throws when the root cannot be sent, uploading nothing', async () => {
let uploads = 0;
const port: SharePort<ShareFile> = {
send: async () => {
throw new Error('M_FORBIDDEN');
},
contentOf: async () => {
uploads += 1;
return {};
},
};
await expect(sendShareSet(port, 't', clips)).rejects.toThrow('M_FORBIDDEN');
expect(uploads).toBe(0);
});
});
describe('the share flag', () => {
it('ships off', () => {
expect(config.fileZoneShare).toEqual({ enabled: false });
});
});
describe('after a send', () => {
it('keeps the failed one of two same-named files, not both', async () => {
const twins: ShareFile[] = [
{ name: 'a.ogg', mimeType: 'audio/ogg' },
{ name: 'a.ogg', mimeType: 'audio/ogg' },
];
let n = 0;
const r = room();
const port: SharePort<ShareFile> = {
...r.port,
contentOf: async (f) => {
n += 1;
if (n === 2) throw new Error('second upload failed');
return r.port.contentOf(f);
},
};
const res = await sendShareSet(port, 't', twins);
expect(res.failedAt).toEqual([1]);
expect(remainingAfter(twins, res)).toEqual([twins[1]]);
});
it('keeps only the failed files picked, so a retry is one tap', async () => {
const r = room(['b.ogg']);
const res = await sendShareSet(r.port, 't', clips);
expect(remainingAfter(clips, res).map((f) => f.name)).toEqual(['b.ogg']);
expect(resultNote(res)).toBe('Shared 2. Not sent: b.ogg');
});
it('keeps everything and says nothing was shared when every upload failed', async () => {
const r = room(clips.map((c) => c.name));
const res = await sendShareSet(r.port, 't', clips);
expect(remainingAfter(clips, res)).toEqual(clips);
expect(resultNote(res)).toBe('Nothing was shared. Not sent: a.ogg, b.ogg, c.txt');
});
it('clears the pick on full success', async () => {
const r = room();
const res = await sendShareSet(r.port, 't', clips);
expect(remainingAfter(clips, res)).toEqual([]);
expect(resultNote(res)).toBe('Shared 3 files.');
});
});
describe('adding to an existing album', () => {
it('sends no root; each file threads under the album, the first after `lastId`', async () => {
const r = room();
const sent: Record<string, unknown>[] = [];
const port = {
...r.port,
send: async (c: Record<string, unknown>) => {
sent.push(c);
return `$n${sent.length}`;
},
};
const res = await sendShareSet(
port,
{ albumId: '$root', lastId: '$last', lastTs: 1 },
clips.slice(0, 2)
);
expect(res.albumId).toBe('$root');
expect(res.sent).toBe(2);
expect(sent.map((c) => c.msgtype)).toEqual(['m.audio', 'm.audio']);
expect(sent.map((c) => c['m.relates_to'])).toEqual([
threadRelation('$root', '$last'),
threadRelation('$root', '$n1'),
]);
});
});
describe('refusals', () => {
const refuse = (errcode: string): SharePort<ShareFile> => ({
send: async () => '$e',
contentOf: async () => {
throw Object.assign(new Error('raw server text'), { errcode });
},
});
it('names the three upload refusals and nothing else', () => {
expect(refusalOf({ errcode: 'M_TOO_LARGE' })).toBe('too large for this server');
expect(refusalOf({ errcode: 'M_FORBIDDEN' })).toBe('not allowed to upload here');
expect(refusalOf({ errcode: 'M_LIMIT_EXCEEDED' })).toBe(
'uploading too fast, try again shortly'
);
expect(refusalOf({ errcode: 'M_UNKNOWN' })).toBeUndefined();
expect(refusalOf({ errcode: 'constructor' })).toBeUndefined();
expect(refusalOf(new Error('x'))).toBeUndefined();
expect(refusalOf(null)).toBeUndefined();
});
it('the note carries the reason beside each refused file', async () => {
const res = await sendShareSet(refuse('M_TOO_LARGE'), 't', clips.slice(0, 2));
expect(resultNote(res)).toBe(
'Nothing was shared. Not sent: a.ogg (too large for this server), b.ogg (too large for this server)'
);
});
it('a failure the client saw, not the server, is named too', async () => {
const dropped: SharePort<ShareFile> = {
send: async () => '$e',
contentOf: async () => {
throw Object.assign(new Error('x'), {
errcode: 'AbortError',
info: { aborted: true, progressed: true },
});
},
};
const res = await sendShareSet(dropped, 't', clips.slice(0, 1));
expect(resultNote(res)).toBe(
'Nothing was shared. Not sent: a.ogg (the connection dropped partway through)'
);
});
it('an unnamed failure lists the bare name', async () => {
const res = await sendShareSet(refuse('M_UNKNOWN'), 't', clips.slice(0, 1));
expect(resultNote(res)).toBe('Nothing was shared. Not sent: a.ogg');
});
});
describe('stopping a send', () => {
/** A port whose upload of `stopAt` aborts the signal as it runs, as the Stop button does mid-upload. */
const stopping = (stopAt: string, abortAfterUpload = false) => {
const ac = new AbortController();
const r = room();
const port: SharePort<ShareFile> = {
...r.port,
signal: ac.signal,
contentOf: async (f) => {
if (f.name !== stopAt) return r.port.contentOf(f);
ac.abort();
if (abortAfterUpload) return r.port.contentOf(f);
throw Object.assign(new Error('aborted'), { name: 'AbortError' });
},
};
return { port, r };
};
it('an upload aborted mid-file leaves that file and the rest unsent, named as stopped', async () => {
const { port, r } = stopping('b.ogg');
const res = await sendShareSet(port, 't', clips);
expect(res.sent).toBe(1);
expect(res.failed).toEqual(['b.ogg', 'c.txt']);
expect(res.failedAt).toEqual([1, 2]);
expect(res.reasons).toEqual([CANCELLED, CANCELLED]);
expect(r.album().files.map((f) => f.name)).toEqual(['a.ogg']);
expect(remainingAfter(clips, res).map((f) => f.name)).toEqual(['b.ogg', 'c.txt']);
expect(resultNote(res)).toBe('Shared 1. Not sent: b.ogg (stopped), c.txt (stopped)');
});
it('a file whose upload finished after the stop is not sent', async () => {
const { port, r } = stopping('b.ogg', true);
const res = await sendShareSet(port, 't', clips);
expect(res.sent).toBe(1);
expect(res.failedAt).toEqual([1, 2]);
expect(r.album().files.map((f) => f.name)).toEqual(['a.ogg']);
});
it('a signal already aborted starts nothing and sends everything back as unsent', async () => {
const r = room();
const ac = new AbortController();
ac.abort();
let uploads = 0;
const res = await sendShareSet(
{
...r.port,
signal: ac.signal,
contentOf: async (f) => {
uploads += 1;
return r.port.contentOf(f);
},
},
{ albumId: '$a', lastId: '$l', lastTs: 1 },
clips
);
expect(uploads).toBe(0);
expect(res.sent).toBe(0);
expect(res.failedAt).toEqual([0, 1, 2]);
expect(r.events).toEqual([]);
});
it('an abort that is not a stop is an ordinary failure', async () => {
const r = room(['b.ogg']);
const res = await sendShareSet({ ...r.port, signal: new AbortController().signal }, 't', clips);
expect(res.failedAt).toEqual([1]);
expect(res.reasons).toEqual([undefined]);
});
});
describe('freshest', () => {
const album = { albumId: '$alb', lastId: '$old', lastTs: 100 };
it('moves lastId to a newer event of the same thread', () => {
expect(
freshest(album, [
{ id: '$mid', ts: 150, threadRoot: '$alb' },
{ id: '$new', ts: 200, threadRoot: '$alb' },
])
).toEqual({ albumId: '$alb', lastId: '$new', lastTs: 200 });
});
it('ignores older events and events of other threads or none', () => {
expect(
freshest(album, [
{ id: '$older', ts: 50, threadRoot: '$alb' },
{ id: '$other', ts: 900, threadRoot: '$else' },
{ id: '$loose', ts: 900 },
])
).toEqual(album);
});
});

View file

@ -0,0 +1,138 @@
// Share a set of files at once: one album root (a text message) and one thread reply per file.
// That is exactly the shape buildAlbums reads, so a set shared here and a set a Mind's mouth posts
// are the same thing to every viewer. Ports are injected so the order and the failure rules are
// testable without a homeserver. See docs/file-zone.md, "Share a set".
import { uploadReason } from '../../utils/uploadReason';
export type ShareFile = { name: string; mimeType: string };
/** What sendShareSet needs from the outside world. */
export type SharePort<F extends ShareFile> = {
/** Send an event and return its id. */
send: (content: Record<string, unknown>) => Promise<string>;
/** Upload one file and build its message content (msgtype, url, info incl. sha256). */
contentOf: (file: F) => Promise<Record<string, unknown>>;
/** Called after each file settles, for progress. */
onFile?: (index: number, result: 'sent' | 'failed') => void;
/** Aborted to stop the send: the running upload is the port's to cancel, the rest are not started. */
signal?: AbortSignal;
};
export type ShareResult = {
/** The album root's event id; present as soon as the root is sent. */
albumId: string;
sent: number;
failed: string[];
/** Positions in the files array of those that failed; names can repeat, positions cannot. */
failedAt: number[];
/** Why each failed file failed, parallel to `failed`, when the homeserver's refusal is one we name. */
reasons?: (string | undefined)[];
};
/** An album that already exists: new files join its thread after `lastId` (sent at `lastTs`), with no new root. */
export type ExistingAlbum = { albumId: string; lastId: string; lastTs: number };
/** An event as the room's live timeline holds it: its id, time, and the thread root it belongs to. */
export type ThreadEvent = { id: string; ts: number; threadRoot?: string };
/**
* `album` with `lastId` moved to the newest event the room's timeline holds in that thread, when it
* is newer than the one the album list knew. The list refreshes every 30 s; the timeline does not.
*/
export const freshest = (album: ExistingAlbum, events: ThreadEvent[]): ExistingAlbum =>
events
.filter((e) => e.threadRoot === album.albumId)
.reduce((a, e) => (e.ts > a.lastTs ? { ...a, lastId: e.id, lastTs: e.ts } : a), album);
export const CANCELLED = 'stopped';
/** The short reason for a failure we can name (the homeserver's refusal or what the client saw), else undefined. */
export const refusalOf = (e: unknown): string | undefined => uploadReason(e)?.cause;
/** The reply relation Matrix clients expect for a thread message: root, with the last event as fallback reply. */
export const threadRelation = (rootId: string, lastId: string) => ({
rel_type: 'm.thread',
event_id: rootId,
is_falling_back: true,
'm.in_reply_to': { event_id: lastId },
});
export const DEFAULT_TITLE = 'Shared files';
export const titleOrDefault = (title: string): string => title.trim() || DEFAULT_TITLE;
/**
* Files go one at a time, in the order given, so thread order is pick order. A file that fails
* to upload is reported by name and the rest still go; the root is already out, so stopping would
* leave an empty album and the sender nothing to retry from. A root that fails to send throws:
* nothing exists yet.
*/
export const sendShareSet = async <F extends ShareFile>(
port: SharePort<F>,
into: string | ExistingAlbum,
files: F[]
): Promise<ShareResult> => {
const albumId =
typeof into === 'string'
? await port.send({ msgtype: 'm.text', body: titleOrDefault(into) })
: into.albumId;
const result: ShareResult = { albumId, sent: 0, failed: [], failedAt: [], reasons: [] };
let lastId = typeof into === 'string' ? albumId : into.lastId;
// A stopped send leaves its file, and every file after it, unsent and picked, so one tap resumes.
const stopFrom = (from: number) => {
for (let j = from; j < files.length; j += 1) {
result.failed.push(files[j].name);
result.reasons?.push(CANCELLED);
result.failedAt.push(j);
}
};
for (let i = 0; i < files.length; i += 1) {
if (port.signal?.aborted) {
stopFrom(i);
break;
}
try {
// eslint-disable-next-line no-await-in-loop
const content = await port.contentOf(files[i]);
if (port.signal?.aborted) {
stopFrom(i);
break;
}
// eslint-disable-next-line no-await-in-loop
lastId = await port.send({ ...content, 'm.relates_to': threadRelation(albumId, lastId) });
result.sent += 1;
port.onFile?.(i, 'sent');
} catch (e) {
if (port.signal?.aborted) {
stopFrom(i);
break;
}
result.failed.push(files[i].name);
result.reasons?.push(refusalOf(e));
result.failedAt.push(i);
port.onFile?.(i, 'failed');
}
}
return result;
};
/**
* What stays picked after a send: only the files that did not go, so a retry is one tap. A retry
* of a new album makes a second album, and a share where nothing went
* leaves its root as a lone message the album list does not show (it lists threads with replies).
*/
export const remainingAfter = <T>(files: T[], result: ShareResult): T[] =>
files.filter((_, i) => result.failedAt.includes(i));
const failedList = (result: ShareResult): string =>
result.failed
.map((name, i) => (result.reasons?.[i] ? `${name} (${result.reasons[i]})` : name))
.join(', ');
export const resultNote = (result: ShareResult): string => {
if (result.failed.length === 0)
return `Shared ${result.sent} ${result.sent === 1 ? 'file' : 'files'}.`;
if (result.sent === 0) return `Nothing was shared. Not sent: ${failedList(result)}`;
return `Shared ${result.sent}. Not sent: ${failedList(result)}`;
};

View file

@ -7,12 +7,11 @@ import { useClientConfig } from '../../hooks/useClientConfig';
import { Album, ZoneEvent, buildAlbums } from './buildAlbums'; import { Album, ZoneEvent, buildAlbums } from './buildAlbums';
import { isFileZone } from './isFileZone'; import { isFileZone } from './isFileZone';
import { mapLimit } from './mapLimit'; import { mapLimit } from './mapLimit';
import { Page, readPages } from './readPages';
const REPLY_FETCHES_IN_FLIGHT = 6; const REPLY_FETCHES_IN_FLIGHT = 6;
const REFRESH_MS = 30_000; const REFRESH_MS = 30_000;
type Chunk = { chunk?: ZoneEvent[] };
/** True when the room is the file zone: by its create type, or listed in the client config. */ /** True when the room is the file zone: by its create type, or listed in the client config. */
export const useIsFileZone = (room: Room): boolean => { export const useIsFileZone = (room: Room): boolean => {
const config = useClientConfig(); const config = useClientConfig();
@ -29,37 +28,49 @@ export const useIsFileZone = (room: Room): boolean => {
); );
}; };
export type AlbumsState = { loading: boolean; error: Error | null; albums: Album[] }; export type AlbumsState = {
loading: boolean;
error: Error | null;
albums: Album[];
/** A read hit the page cap (readPages), so older albums or files are not in the list. */
truncated: boolean;
};
const PAGE_LIMIT = '100';
/** /**
* Slice 1 reads ONE page of each endpoint (threads: 100 roots; replies per root: 100). A zone with * Reads every page of the zone's threads, then every page of each thread's replies, each capped at
* more albums or files than that is truncated; pagination is a later slice. Reads are made with * MAX_PAGES (readPages). Reads are made with the logged-in client, so the room must be
* the logged-in client, so the room must be unencrypted: encrypted events carry no msgtype and * unencrypted: encrypted events carry no msgtype and are skipped.
* are skipped.
*/ */
export const useAlbums = (room: Room): AlbumsState => { export const useAlbums = (room: Room): AlbumsState => {
const mx = useMatrixClient(); const mx = useMatrixClient();
const { roomId } = room; const { roomId } = room;
const query = useQuery({ const query = useQuery({
queryKey: ['albums', roomId], queryKey: ['albums', roomId],
queryFn: async (): Promise<Album[]> => { queryFn: async (): Promise<{ albums: Album[]; truncated: boolean }> => {
const get = (path: string, params: Record<string, string>) => const get = (path: string, params: Record<string, string>) =>
mx.http.authedRequest<Chunk>(Method.Get, path, params, undefined, { mx.http.authedRequest<Page<ZoneEvent>>(Method.Get, path, params, undefined, {
prefix: ClientPrefix.V1, prefix: ClientPrefix.V1,
}); });
const paged = (path: string, params: Record<string, string>) =>
readPages<ZoneEvent>((from) => get(path, from ? { ...params, from } : params));
const room_ = encodeURIComponent(roomId); const room_ = encodeURIComponent(roomId);
const roots = (await get(`/rooms/${room_}/threads`, { limit: '100' })).chunk ?? []; const roots = await paged(`/rooms/${room_}/threads`, { limit: PAGE_LIMIT });
const inputs = await mapLimit(roots, REPLY_FETCHES_IN_FLIGHT, async (root: ZoneEvent) => ({ let { truncated } = roots;
root, const inputs = await mapLimit(
replies: roots.items,
( REPLY_FETCHES_IN_FLIGHT,
await get( async (root: ZoneEvent) => {
const replies = await paged(
`/rooms/${room_}/relations/${encodeURIComponent(root.event_id ?? '')}/m.thread`, `/rooms/${room_}/relations/${encodeURIComponent(root.event_id ?? '')}/m.thread`,
{ limit: '100', dir: 'f' } { limit: PAGE_LIMIT, dir: 'f' }
) );
).chunk ?? [], truncated = truncated || replies.truncated;
})); return { root, replies: replies.items };
return buildAlbums(inputs, mx.getDomain() ?? ''); }
);
return { albums: buildAlbums(inputs, mx.getDomain() ?? ''), truncated };
}, },
retry: 1, retry: 1,
refetchInterval: REFRESH_MS, refetchInterval: REFRESH_MS,
@ -68,6 +79,7 @@ export const useAlbums = (room: Room): AlbumsState => {
loading: query.isLoading, loading: query.isLoading,
// A failed refetch keeps the albums already loaded; the error shows only when there are none. // A failed refetch keeps the albums already loaded; the error shows only when there are none.
error: query.data ? null : (query.error as Error | null), error: query.data ? null : (query.error as Error | null),
albums: query.data ?? [], albums: query.data?.albums ?? [],
truncated: query.data?.truncated ?? false,
}; };
}; };

View file

@ -0,0 +1,83 @@
import { describe, expect, it } from 'vitest';
import { PUBLISH_KEY, foldVersions, replacesOf } from './versions';
type F = { id: string; sender: string; content: Record<string, unknown>; earlier: F[] };
const f = (id: string, replaces?: string, sender = '@m:x'): F => ({
id,
sender,
content: replaces ? { [PUBLISH_KEY]: { replaces } } : {},
earlier: [],
});
const shape = (files: F[]): unknown => files.map((x) => [x.id, x.earlier.map((e) => e.id)]);
describe('replacesOf', () => {
it('reads the id the publisher key names', () => {
expect(replacesOf({ [PUBLISH_KEY]: { replaces: '$a' } })).toBe('$a');
});
it('anything else says nothing', () => {
expect(replacesOf({})).toBeUndefined();
expect(replacesOf({ [PUBLISH_KEY]: {} })).toBeUndefined();
expect(replacesOf({ [PUBLISH_KEY]: { replaces: 3 } })).toBeUndefined();
expect(replacesOf({ [PUBLISH_KEY]: { replaces: '' } })).toBeUndefined();
expect(replacesOf({ [PUBLISH_KEY]: 'x' })).toBeUndefined();
});
});
describe('foldVersions', () => {
it('files that replace nothing pass through in order, with nothing folded', () => {
expect(shape(foldVersions([f('$a'), f('$b')]))).toEqual([
['$a', []],
['$b', []],
]);
});
it('shows the latest of a chain with earlier versions nearest first', () => {
expect(shape(foldVersions([f('$a'), f('$b', '$a'), f('$c', '$b')]))).toEqual([
['$c', ['$b', '$a']],
]);
});
it('keeps unrelated files beside a chain, in order', () => {
expect(shape(foldVersions([f('$a'), f('$x'), f('$b', '$a')]))).toEqual([
['$x', []],
['$b', ['$a']],
]);
});
it('a replacement whose target is not in the list stands alone', () => {
expect(shape(foldVersions([f('$b', '$gone')]))).toEqual([['$b', []]]);
});
it('a file two others replace sits under both', () => {
expect(shape(foldVersions([f('$a'), f('$b', '$a'), f('$c', '$a')]))).toEqual([
['$b', ['$a']],
['$c', ['$a']],
]);
});
it('files in a loop with no head outside it are all shown, none hidden', () => {
const out = foldVersions([f('$a', '$b'), f('$b', '$a'), f('$s', '$s')]);
expect(shape(out)).toEqual([
['$a', []],
['$b', []],
['$s', []],
]);
});
it('a loop reached from a head is walked once and ends', () => {
const out = foldVersions([f('$a', '$b'), f('$b', '$a'), f('$h', '$a')]);
expect(shape(out)).toEqual([['$h', ['$a', '$b']]]);
});
it('a replacement by another sender folds nothing', () => {
const out = foldVersions([f('$victim', undefined, '@m:x'), f('$evil', '$victim', '@e:x')]);
expect(shape(out)).toEqual([
['$victim', []],
['$evil', []],
]);
});
it('an empty list is empty', () => {
expect(foldVersions([])).toEqual([]);
});
});

View file

@ -0,0 +1,56 @@
// Pure: a file event may name the event it supersedes in `org.gamecult.publish.replaces` (the
// publisher writes it on a later final version; docs/commons-files-desk.md, "replaces, not
// m.replace"). Both events stay ordinary files for every other client; this view shows the latest
// of a chain with the earlier ones folded under it. A chain is read from the events alone.
/** Key the publisher writes its provenance under. */
export const PUBLISH_KEY = 'org.gamecult.publish';
/** The event id a file says it replaces, if it says one. */
export const replacesOf = (content: Record<string, unknown>): string | undefined => {
const id = (content[PUBLISH_KEY] as { replaces?: unknown } | undefined)?.replaces;
return typeof id === 'string' && id ? id : undefined;
};
type Versioned<F> = F & { earlier: F[] };
/**
* Files not replaced by another file in the list, oldest first as given, each carrying the files it
* supersedes (nearest first) in `earlier`. A replacement whose target is missing from the list (a
* redacted event, another thread) replaces nothing and stands as a head. A replacement by another sender is ignored. A file two others claim to
* replace sits under both. The walk refuses to revisit a file, so a malformed chain cannot loop (a real event id hashes its content and cannot cycle); files caught in a loop with no head outside it are all shown, none folded.
*/
export const foldVersions = <
F extends { id: string; sender: string; content: Record<string, unknown> }
>(
files: Versioned<F>[]
): Versioned<F>[] => {
const byId = new Map(files.map((f) => [f.id, f]));
const target = (f: F): F | undefined => {
const id = replacesOf(f.content);
const t = id && id !== f.id ? byId.get(id) : undefined;
// Only the sender of a file can supersede it, so no one else in the thread can fold it away.
return t && t.sender === f.sender ? t : undefined;
};
const replaced = new Set<string>();
files.forEach((f) => {
const t = target(f);
if (t) replaced.add(t.id);
});
const chainOf = (head: Versioned<F>): Versioned<F>[] => {
const out: Versioned<F>[] = [];
const seen = new Set([head.id]);
for (let t = target(head); t && !seen.has(t.id); t = target(t)) {
seen.add(t.id);
out.push({ ...t, earlier: [] });
}
return out;
};
const heads = files.filter((f) => !replaced.has(f.id));
const covered = new Set(heads.flatMap((h) => [h.id, ...chainOf(h).map((e) => e.id)]));
// Files that replace one another with no head outside the loop are never reached from a head; show
// each of them as it is rather than let the loop hide itself.
return files
.filter((f) => !replaced.has(f.id) || !covered.has(f.id))
.map((f) => ({ ...f, earlier: replaced.has(f.id) ? [] : chainOf(f) }));
};

View file

@ -5,6 +5,7 @@ import { StatusDivider } from './components';
import { CallEmbed, useCallControlState } from '../../plugins/call'; import { CallEmbed, useCallControlState } from '../../plugins/call';
import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback'; import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
import { callEmbedAtom } from '../../state/callEmbed'; import { callEmbedAtom } from '../../state/callEmbed';
import { PhoneHitSpread26 } from '../../styles/PhoneHit.css';
type MicrophoneButtonProps = { type MicrophoneButtonProps = {
enabled: boolean; enabled: boolean;
@ -26,6 +27,7 @@ function MicrophoneButton({ enabled, onToggle, disabled }: MicrophoneButtonProps
> >
{(anchorRef) => ( {(anchorRef) => (
<IconButton <IconButton
className={PhoneHitSpread26}
ref={anchorRef} ref={anchorRef}
variant={enabled ? 'Surface' : 'Warning'} variant={enabled ? 'Surface' : 'Warning'}
fill="Soft" fill="Soft"
@ -59,6 +61,7 @@ function SoundButton({ enabled, onToggle, disabled }: SoundButtonProps) {
> >
{(anchorRef) => ( {(anchorRef) => (
<IconButton <IconButton
className={PhoneHitSpread26}
ref={anchorRef} ref={anchorRef}
variant={enabled ? 'Surface' : 'Warning'} variant={enabled ? 'Surface' : 'Warning'}
fill="Soft" fill="Soft"
@ -99,6 +102,7 @@ function VideoButton({ enabled, onToggle, disabled }: VideoButtonProps) {
> >
{(anchorRef) => ( {(anchorRef) => (
<IconButton <IconButton
className={PhoneHitSpread26}
ref={anchorRef} ref={anchorRef}
variant={enabled ? 'Success' : 'Surface'} variant={enabled ? 'Success' : 'Surface'}
fill="Soft" fill="Soft"
@ -136,6 +140,7 @@ function ScreenShareButton({ enabled, onToggle, disabled }: ScreenShareButtonPro
> >
{(anchorRef) => ( {(anchorRef) => (
<IconButton <IconButton
className={PhoneHitSpread26}
ref={anchorRef} ref={anchorRef}
variant={enabled ? 'Success' : 'Surface'} variant={enabled ? 'Success' : 'Surface'}
fill="Soft" fill="Soft"
@ -164,7 +169,10 @@ export function CallControl({
const { microphone, video, sound, screenshare } = useCallControlState(callEmbed.control); const { microphone, video, sound, screenshare } = useCallControlState(callEmbed.control);
const setCallEmbed = useSetAtom(callEmbedAtom); const setCallEmbed = useSetAtom(callEmbedAtom);
const handleMicrophoneToggle = useCallback(() => callEmbed.control.toggleMicrophone(), [callEmbed]); const handleMicrophoneToggle = useCallback(
() => callEmbed.control.toggleMicrophone(),
[callEmbed]
);
const handleVideoToggle = useCallback(() => callEmbed.control.toggleVideo(), [callEmbed]); const handleVideoToggle = useCallback(() => callEmbed.control.toggleVideo(), [callEmbed]);
const [hangupState, hangup] = useAsyncCallback( const [hangupState, hangup] = useAsyncCallback(
@ -195,11 +203,7 @@ export function CallControl({
disabled={!callJoined} disabled={!callJoined}
/> />
{!compact && <StatusDivider />} {!compact && <StatusDivider />}
<VideoButton <VideoButton enabled={video} onToggle={handleVideoToggle} disabled={!callJoined} />
enabled={video}
onToggle={handleVideoToggle}
disabled={!callJoined}
/>
{!compact && ( {!compact && (
<ScreenShareButton <ScreenShareButton
enabled={screenshare} enabled={screenshare}

View file

@ -25,6 +25,7 @@ import {
SoundButton, SoundButton,
VideoButton, VideoButton,
} from './Controls'; } from './Controls';
import { PhoneHitSpread40 } from '../../styles/PhoneHit.css';
import { CallEmbed, useCallControlState } from '../../plugins/call'; import { CallEmbed, useCallControlState } from '../../plugins/call';
import { useResizeObserver } from '../../hooks/useResizeObserver'; import { useResizeObserver } from '../../hooks/useResizeObserver';
import { stopPropagation } from '../../utils/keyboard'; import { stopPropagation } from '../../utils/keyboard';
@ -71,7 +72,10 @@ export function CallControls({ callEmbed }: CallControlsProps) {
setCords(undefined); setCords(undefined);
}; };
const handleMicrophoneToggle = useCallback(() => callEmbed.control.toggleMicrophone(), [callEmbed]); const handleMicrophoneToggle = useCallback(
() => callEmbed.control.toggleMicrophone(),
[callEmbed]
);
const handleVideoToggle = useCallback(() => callEmbed.control.toggleVideo(), [callEmbed]); const handleVideoToggle = useCallback(() => callEmbed.control.toggleVideo(), [callEmbed]);
const [hangupState, hangup] = useAsyncCallback( const [hangupState, hangup] = useAsyncCallback(
@ -97,10 +101,7 @@ export function CallControls({ callEmbed }: CallControlsProps) {
> >
<Box alignItems="Center" gap="Inherit" grow="Yes" direction={compact ? 'Column' : 'Row'}> <Box alignItems="Center" gap="Inherit" grow="Yes" direction={compact ? 'Column' : 'Row'}>
<Box shrink="No" alignItems="Inherit" justifyContent="Inherit" gap="200"> <Box shrink="No" alignItems="Inherit" justifyContent="Inherit" gap="200">
<MicrophoneButton <MicrophoneButton enabled={microphone} onToggle={handleMicrophoneToggle} />
enabled={microphone}
onToggle={handleMicrophoneToggle}
/>
<SoundButton enabled={sound} onToggle={() => callEmbed.control.toggleSound()} /> <SoundButton enabled={sound} onToggle={() => callEmbed.control.toggleSound()} />
</Box> </Box>
{!compact && <ControlDivider />} {!compact && <ControlDivider />}
@ -169,6 +170,7 @@ export function CallControls({ callEmbed }: CallControlsProps) {
} }
> >
<IconButton <IconButton
className={PhoneHitSpread40}
variant="Surface" variant="Surface"
fill="Soft" fill="Soft"
radii="400" radii="400"

View file

@ -4,6 +4,7 @@ import { useAtom } from 'jotai';
import * as css from './styles.css'; import * as css from './styles.css';
import { callChatAtom } from '../../state/callEmbed'; import { callChatAtom } from '../../state/callEmbed';
import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback'; import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
import { PhoneHitSpread40 } from '../../styles/PhoneHit.css';
export function ControlDivider() { export function ControlDivider() {
return ( return (
@ -31,6 +32,7 @@ export function MicrophoneButton({ enabled, onToggle }: MicrophoneButtonProps) {
> >
{(anchorRef) => ( {(anchorRef) => (
<IconButton <IconButton
className={PhoneHitSpread40}
ref={anchorRef} ref={anchorRef}
variant={enabled ? 'Surface' : 'Warning'} variant={enabled ? 'Surface' : 'Warning'}
fill="Soft" fill="Soft"
@ -64,6 +66,7 @@ export function SoundButton({ enabled, onToggle }: SoundButtonProps) {
> >
{(anchorRef) => ( {(anchorRef) => (
<IconButton <IconButton
className={PhoneHitSpread40}
ref={anchorRef} ref={anchorRef}
variant={enabled ? 'Surface' : 'Warning'} variant={enabled ? 'Surface' : 'Warning'}
fill="Soft" fill="Soft"
@ -103,6 +106,7 @@ export function VideoButton({ enabled, onToggle }: VideoButtonProps) {
> >
{(anchorRef) => ( {(anchorRef) => (
<IconButton <IconButton
className={PhoneHitSpread40}
ref={anchorRef} ref={anchorRef}
variant={enabled ? 'Success' : 'Surface'} variant={enabled ? 'Success' : 'Surface'}
fill="Soft" fill="Soft"
@ -140,6 +144,7 @@ export function ScreenShareButton({ enabled, onToggle }: ScreenShareButtonProps)
> >
{(anchorRef) => ( {(anchorRef) => (
<IconButton <IconButton
className={PhoneHitSpread40}
ref={anchorRef} ref={anchorRef}
variant={enabled ? 'Success' : 'Surface'} variant={enabled ? 'Success' : 'Surface'}
fill="Soft" fill="Soft"
@ -170,6 +175,7 @@ export function ChatButton() {
> >
{(anchorRef) => ( {(anchorRef) => (
<IconButton <IconButton
className={PhoneHitSpread40}
ref={anchorRef} ref={anchorRef}
variant={chat ? 'Success' : 'Surface'} variant={chat ? 'Success' : 'Surface'}
fill="Soft" fill="Soft"

View file

@ -26,7 +26,6 @@ export function PrescreenControls({ canJoin }: PrescreenControlsProps) {
const { microphone, video, sound, toggleMicrophone, toggleVideo, toggleSound } = const { microphone, video, sound, toggleMicrophone, toggleVideo, toggleSound } =
useCallPreferences(); useCallPreferences();
const handleMicrophoneToggle = useCallback(async () => toggleMicrophone(), [toggleMicrophone]); const handleMicrophoneToggle = useCallback(async () => toggleMicrophone(), [toggleMicrophone]);
const handleVideoToggle = useCallback(async () => toggleVideo(), [toggleVideo]); const handleVideoToggle = useCallback(async () => toggleVideo(), [toggleVideo]);

View file

@ -30,6 +30,7 @@ import {
AccountDataSubmitCallback, AccountDataSubmitCallback,
} from '../../../components/AccountDataEditor'; } from '../../../components/AccountDataEditor';
import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { PhoneHit } from '../../../styles/PhoneHit.css';
type DeveloperToolsProps = { type DeveloperToolsProps = {
requestClose: () => void; requestClose: () => void;
@ -92,7 +93,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
</Text> </Text>
</Box> </Box>
<Box shrink="No"> <Box shrink="No">
<IconButton onClick={requestClose} variant="Surface"> <IconButton className={PhoneHit} onClick={requestClose} variant="Surface">
<Icon src={Icons.Cross} /> <Icon src={Icons.Cross} />
</IconButton> </IconButton>
</Box> </Box>

View file

@ -22,6 +22,7 @@ import { useTextAreaCodeEditor } from '../../../hooks/useTextAreaCodeEditor';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { syntaxErrorPosition } from '../../../utils/dom'; import { syntaxErrorPosition } from '../../../utils/dom';
import { Cursor } from '../../../plugins/text-area'; import { Cursor } from '../../../plugins/text-area';
import { PhoneHit } from '../../../styles/PhoneHit.css';
const EDITOR_INTENT_SPACE_COUNT = 2; const EDITOR_INTENT_SPACE_COUNT = 2;
@ -118,7 +119,7 @@ export function SendRoomEvent({ type, stateKey, requestClose }: SendRoomEventPro
</Chip> </Chip>
</Box> </Box>
<Box shrink="No"> <Box shrink="No">
<IconButton onClick={requestClose} variant="Surface"> <IconButton className={PhoneHit} onClick={requestClose} variant="Surface">
<Icon src={Icons.Cross} /> <Icon src={Icons.Cross} />
</IconButton> </IconButton>
</Box> </Box>

View file

@ -31,6 +31,7 @@ import { usePowerLevels } from '../../../hooks/usePowerLevels';
import { useTextAreaCodeEditor } from '../../../hooks/useTextAreaCodeEditor'; import { useTextAreaCodeEditor } from '../../../hooks/useTextAreaCodeEditor';
import { useRoomCreators } from '../../../hooks/useRoomCreators'; import { useRoomCreators } from '../../../hooks/useRoomCreators';
import { useRoomPermissions } from '../../../hooks/useRoomPermissions'; import { useRoomPermissions } from '../../../hooks/useRoomPermissions';
import { PhoneHit } from '../../../styles/PhoneHit.css';
const EDITOR_INTENT_SPACE_COUNT = 2; const EDITOR_INTENT_SPACE_COUNT = 2;
@ -275,7 +276,7 @@ export function StateEventEditor({ type, stateKey, requestClose }: StateEventEdi
</Chip> </Chip>
</Box> </Box>
<Box shrink="No"> <Box shrink="No">
<IconButton onClick={requestClose} variant="Surface"> <IconButton className={PhoneHit} onClick={requestClose} variant="Surface">
<Icon src={Icons.Cross} /> <Icon src={Icons.Cross} />
</IconButton> </IconButton>
</Box> </Box>

View file

@ -4,6 +4,7 @@ import { Page, PageContent, PageHeader } from '../../../components/page';
import { ImagePack } from '../../../plugins/custom-emoji'; import { ImagePack } from '../../../plugins/custom-emoji';
import { ImagePackView } from '../../../components/image-pack-view'; import { ImagePackView } from '../../../components/image-pack-view';
import { RoomPacks } from './RoomPacks'; import { RoomPacks } from './RoomPacks';
import { PhoneHit } from '../../../styles/PhoneHit.css';
type EmojisStickersProps = { type EmojisStickersProps = {
requestClose: () => void; requestClose: () => void;
@ -29,7 +30,7 @@ export function EmojisStickers({ requestClose }: EmojisStickersProps) {
</Text> </Text>
</Box> </Box>
<Box shrink="No"> <Box shrink="No">
<IconButton onClick={requestClose} variant="Surface"> <IconButton className={PhoneHit} onClick={requestClose} variant="Surface">
<Icon src={Icons.Cross} /> <Icon src={Icons.Cross} />
</IconButton> </IconButton>
</Box> </Box>

View file

@ -40,6 +40,7 @@ import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { useAlive } from '../../../hooks/useAlive'; import { useAlive } from '../../../hooks/useAlive';
import { useRoomCreators } from '../../../hooks/useRoomCreators'; import { useRoomCreators } from '../../../hooks/useRoomCreators';
import { useRoomPermissions } from '../../../hooks/useRoomPermissions'; import { useRoomPermissions } from '../../../hooks/useRoomPermissions';
import { PhoneHit } from '../../../styles/PhoneHit.css';
type CreatePackTileProps = { type CreatePackTileProps = {
packs: ImagePack[]; packs: ImagePack[];
@ -215,6 +216,7 @@ export function RoomPacks({ onViewPack }: RoomPacksProps) {
{canEdit && {canEdit &&
(removed ? ( (removed ? (
<IconButton <IconButton
className={PhoneHit}
size="300" size="300"
radii="Pill" radii="Pill"
variant="Critical" variant="Critical"
@ -225,6 +227,7 @@ export function RoomPacks({ onViewPack }: RoomPacksProps) {
</IconButton> </IconButton>
) : ( ) : (
<IconButton <IconButton
className={PhoneHit}
size="300" size="300"
radii="Pill" radii="Pill"
variant="Secondary" variant="Secondary"

Some files were not shown because too many files have changed in this diff Show more